xref: /linux/drivers/iio/industrialio-backend.c (revision add07519ea6b6c2ba2b7842225eb87e0f08f2b0f)
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/debugfs.h>
36 #include <linux/device.h>
37 #include <linux/err.h>
38 #include <linux/errno.h>
39 #include <linux/list.h>
40 #include <linux/module.h>
41 #include <linux/mutex.h>
42 #include <linux/property.h>
43 #include <linux/slab.h>
44 #include <linux/stringify.h>
45 #include <linux/types.h>
46 
47 #include <linux/iio/backend.h>
48 #include <linux/iio/iio.h>
49 
50 struct iio_backend {
51 	struct list_head entry;
52 	const struct iio_backend_ops *ops;
53 	struct device *frontend_dev;
54 	struct device *dev;
55 	struct module *owner;
56 	void *priv;
57 	const char *name;
58 	unsigned int cached_reg_addr;
59 	/*
60 	 * This index is relative to the frontend. Meaning that for
61 	 * frontends with multiple backends, this will be the index of this
62 	 * backend. Used for the debugfs directory name.
63 	 */
64 	u8 idx;
65 };
66 
67 /*
68  * Helper struct for requesting buffers. This ensures that we have all data
69  * that we need to free the buffer in a device managed action.
70  */
71 struct iio_backend_buffer_pair {
72 	struct iio_backend *back;
73 	struct iio_buffer *buffer;
74 };
75 
76 static LIST_HEAD(iio_back_list);
77 static DEFINE_MUTEX(iio_back_lock);
78 
79 /*
80  * Helper macros to call backend ops. Makes sure the option is supported.
81  */
82 #define iio_backend_check_op(back, op) ({ \
83 	struct iio_backend *____back = back;				\
84 	int ____ret = 0;						\
85 									\
86 	if (!____back->ops->op)						\
87 		____ret = -EOPNOTSUPP;					\
88 									\
89 	____ret;							\
90 })
91 
92 #define iio_backend_op_call(back, op, args...) ({		\
93 	struct iio_backend *__back = back;			\
94 	int __ret;						\
95 								\
96 	__ret = iio_backend_check_op(__back, op);		\
97 	if (!__ret)						\
98 		__ret = __back->ops->op(__back, ##args);	\
99 								\
100 	__ret;							\
101 })
102 
103 #define iio_backend_ptr_op_call(back, op, args...) ({		\
104 	struct iio_backend *__back = back;			\
105 	void *ptr_err;						\
106 	int __ret;						\
107 								\
108 	__ret = iio_backend_check_op(__back, op);		\
109 	if (__ret)						\
110 		ptr_err = ERR_PTR(__ret);			\
111 	else							\
112 		ptr_err = __back->ops->op(__back, ##args);	\
113 								\
114 	ptr_err;						\
115 })
116 
117 #define iio_backend_void_op_call(back, op, args...) {		\
118 	struct iio_backend *__back = back;			\
119 	int __ret;						\
120 								\
121 	__ret = iio_backend_check_op(__back, op);		\
122 	if (!__ret)						\
123 		__back->ops->op(__back, ##args);		\
124 	else							\
125 		dev_dbg(__back->dev, "Op(%s) not implemented\n",\
126 			__stringify(op));			\
127 }
128 
129 static ssize_t iio_backend_debugfs_read_reg(struct file *file,
130 					    char __user *userbuf,
131 					    size_t count, loff_t *ppos)
132 {
133 	struct iio_backend *back = file->private_data;
134 	char read_buf[20];
135 	unsigned int val;
136 	int ret, len;
137 
138 	ret = iio_backend_op_call(back, debugfs_reg_access,
139 				  back->cached_reg_addr, 0, &val);
140 	if (ret)
141 		return ret;
142 
143 	len = scnprintf(read_buf, sizeof(read_buf), "0x%X\n", val);
144 
145 	return simple_read_from_buffer(userbuf, count, ppos, read_buf, len);
146 }
147 
148 static ssize_t iio_backend_debugfs_write_reg(struct file *file,
149 					     const char __user *userbuf,
150 					     size_t count, loff_t *ppos)
151 {
152 	struct iio_backend *back = file->private_data;
153 	unsigned int val;
154 	char buf[80];
155 	ssize_t rc;
156 	int ret;
157 
158 	if (count >= sizeof(buf))
159 		return -ENOSPC;
160 
161 	rc = simple_write_to_buffer(buf, sizeof(buf) - 1, ppos, userbuf, count);
162 	if (rc < 0)
163 		return rc;
164 
165 	buf[rc] = '\0';
166 
167 	ret = sscanf(buf, "%i %i", &back->cached_reg_addr, &val);
168 
169 	switch (ret) {
170 	case 1:
171 		return count;
172 	case 2:
173 		ret = iio_backend_op_call(back, debugfs_reg_access,
174 					  back->cached_reg_addr, val, NULL);
175 		if (ret)
176 			return ret;
177 		return count;
178 	default:
179 		return -EINVAL;
180 	}
181 }
182 
183 static const struct file_operations iio_backend_debugfs_reg_fops = {
184 	.open = simple_open,
185 	.read = iio_backend_debugfs_read_reg,
186 	.write = iio_backend_debugfs_write_reg,
187 };
188 
189 static ssize_t iio_backend_debugfs_read_name(struct file *file,
190 					     char __user *userbuf,
191 					     size_t count, loff_t *ppos)
192 {
193 	struct iio_backend *back = file->private_data;
194 	char name[128];
195 	int len;
196 
197 	len = scnprintf(name, sizeof(name), "%s\n", back->name);
198 
199 	return simple_read_from_buffer(userbuf, count, ppos, name, len);
200 }
201 
202 static const struct file_operations iio_backend_debugfs_name_fops = {
203 	.open = simple_open,
204 	.read = iio_backend_debugfs_read_name,
205 };
206 
207 /**
208  * iio_backend_debugfs_add - Add debugfs interfaces for Backends
209  * @back: Backend device
210  * @indio_dev: IIO device
211  */
212 void iio_backend_debugfs_add(struct iio_backend *back,
213 			     struct iio_dev *indio_dev)
214 {
215 	struct dentry *d = iio_get_debugfs_dentry(indio_dev);
216 	struct dentry *back_d;
217 	char name[128];
218 
219 	if (!IS_ENABLED(CONFIG_DEBUG_FS) || !d)
220 		return;
221 	if (!back->ops->debugfs_reg_access && !back->name)
222 		return;
223 
224 	snprintf(name, sizeof(name), "backend%d", back->idx);
225 
226 	back_d = debugfs_create_dir(name, d);
227 	if (IS_ERR(back_d))
228 		return;
229 
230 	if (back->ops->debugfs_reg_access)
231 		debugfs_create_file("direct_reg_access", 0600, back_d, back,
232 				    &iio_backend_debugfs_reg_fops);
233 
234 	if (back->name)
235 		debugfs_create_file("name", 0400, back_d, back,
236 				    &iio_backend_debugfs_name_fops);
237 }
238 EXPORT_SYMBOL_NS_GPL(iio_backend_debugfs_add, "IIO_BACKEND");
239 
240 /**
241  * iio_backend_debugfs_print_chan_status - Print channel status
242  * @back: Backend device
243  * @chan: Channel number
244  * @buf: Buffer where to print the status
245  * @len: Available space
246  *
247  * One usecase where this is useful is for testing test tones in a digital
248  * interface and "ask" the backend to dump more details on why a test tone might
249  * have errors.
250  *
251  * RETURNS:
252  * Number of copied bytes on success, negative error code on failure.
253  */
254 ssize_t iio_backend_debugfs_print_chan_status(struct iio_backend *back,
255 					      unsigned int chan, char *buf,
256 					      size_t len)
257 {
258 	if (!IS_ENABLED(CONFIG_DEBUG_FS))
259 		return -ENODEV;
260 
261 	return iio_backend_op_call(back, debugfs_print_chan_status, chan, buf,
262 				   len);
263 }
264 EXPORT_SYMBOL_NS_GPL(iio_backend_debugfs_print_chan_status, "IIO_BACKEND");
265 
266 /**
267  * iio_backend_chan_enable - Enable a backend channel
268  * @back: Backend device
269  * @chan: Channel number
270  *
271  * RETURNS:
272  * 0 on success, negative error number on failure.
273  */
274 int iio_backend_chan_enable(struct iio_backend *back, unsigned int chan)
275 {
276 	return iio_backend_op_call(back, chan_enable, chan);
277 }
278 EXPORT_SYMBOL_NS_GPL(iio_backend_chan_enable, "IIO_BACKEND");
279 
280 /**
281  * iio_backend_chan_disable - Disable a backend channel
282  * @back: Backend device
283  * @chan: Channel number
284  *
285  * RETURNS:
286  * 0 on success, negative error number on failure.
287  */
288 int iio_backend_chan_disable(struct iio_backend *back, unsigned int chan)
289 {
290 	return iio_backend_op_call(back, chan_disable, chan);
291 }
292 EXPORT_SYMBOL_NS_GPL(iio_backend_chan_disable, "IIO_BACKEND");
293 
294 static void __iio_backend_disable(void *back)
295 {
296 	iio_backend_void_op_call(back, disable);
297 }
298 
299 /**
300  * iio_backend_disable - Backend disable
301  * @back: Backend device
302  */
303 void iio_backend_disable(struct iio_backend *back)
304 {
305 	__iio_backend_disable(back);
306 }
307 EXPORT_SYMBOL_NS_GPL(iio_backend_disable, "IIO_BACKEND");
308 
309 /**
310  * iio_backend_enable - Backend enable
311  * @back: Backend device
312  *
313  * RETURNS:
314  * 0 on success, negative error number on failure.
315  */
316 int iio_backend_enable(struct iio_backend *back)
317 {
318 	return iio_backend_op_call(back, enable);
319 }
320 EXPORT_SYMBOL_NS_GPL(iio_backend_enable, "IIO_BACKEND");
321 
322 /**
323  * devm_iio_backend_enable - Device managed backend enable
324  * @dev: Consumer device for the backend
325  * @back: Backend device
326  *
327  * RETURNS:
328  * 0 on success, negative error number on failure.
329  */
330 int devm_iio_backend_enable(struct device *dev, struct iio_backend *back)
331 {
332 	int ret;
333 
334 	ret = iio_backend_enable(back);
335 	if (ret)
336 		return ret;
337 
338 	return devm_add_action_or_reset(dev, __iio_backend_disable, back);
339 }
340 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_enable, "IIO_BACKEND");
341 
342 /**
343  * iio_backend_data_format_set - Configure the channel data format
344  * @back: Backend device
345  * @chan: Channel number
346  * @data: Data format
347  *
348  * Properly configure a channel with respect to the expected data format. A
349  * @struct iio_backend_data_fmt must be passed with the settings.
350  *
351  * RETURNS:
352  * 0 on success, negative error number on failure.
353  */
354 int iio_backend_data_format_set(struct iio_backend *back, unsigned int chan,
355 				const struct iio_backend_data_fmt *data)
356 {
357 	if (!data || data->type >= IIO_BACKEND_DATA_TYPE_MAX)
358 		return -EINVAL;
359 
360 	return iio_backend_op_call(back, data_format_set, chan, data);
361 }
362 EXPORT_SYMBOL_NS_GPL(iio_backend_data_format_set, "IIO_BACKEND");
363 
364 /**
365  * iio_backend_data_source_set - Select data source
366  * @back: Backend device
367  * @chan: Channel number
368  * @data: Data source
369  *
370  * A given backend may have different sources to stream/sync data. This allows
371  * to choose that source.
372  *
373  * RETURNS:
374  * 0 on success, negative error number on failure.
375  */
376 int iio_backend_data_source_set(struct iio_backend *back, unsigned int chan,
377 				enum iio_backend_data_source data)
378 {
379 	if (data >= IIO_BACKEND_DATA_SOURCE_MAX)
380 		return -EINVAL;
381 
382 	return iio_backend_op_call(back, data_source_set, chan, data);
383 }
384 EXPORT_SYMBOL_NS_GPL(iio_backend_data_source_set, "IIO_BACKEND");
385 
386 /**
387  * iio_backend_data_source_get - Get current data source
388  * @back: Backend device
389  * @chan: Channel number
390  * @data: Pointer to receive the current source value
391  *
392  * A given backend may have different sources to stream/sync data. This allows
393  * to know what source is in use.
394  *
395  * RETURNS:
396  * 0 on success, negative error number on failure.
397  */
398 int iio_backend_data_source_get(struct iio_backend *back, unsigned int chan,
399 				enum iio_backend_data_source *data)
400 {
401 	int ret;
402 
403 	ret = iio_backend_op_call(back, data_source_get, chan, data);
404 	if (ret)
405 		return ret;
406 
407 	if (*data >= IIO_BACKEND_DATA_SOURCE_MAX)
408 		return -EINVAL;
409 
410 	return 0;
411 }
412 EXPORT_SYMBOL_NS_GPL(iio_backend_data_source_get, "IIO_BACKEND");
413 
414 /**
415  * iio_backend_set_sampling_freq - Set channel sampling rate
416  * @back: Backend device
417  * @chan: Channel number
418  * @sample_rate_hz: Sample rate
419  *
420  * RETURNS:
421  * 0 on success, negative error number on failure.
422  */
423 int iio_backend_set_sampling_freq(struct iio_backend *back, unsigned int chan,
424 				  u64 sample_rate_hz)
425 {
426 	return iio_backend_op_call(back, set_sample_rate, chan, sample_rate_hz);
427 }
428 EXPORT_SYMBOL_NS_GPL(iio_backend_set_sampling_freq, "IIO_BACKEND");
429 
430 /**
431  * iio_backend_test_pattern_set - Configure a test pattern
432  * @back: Backend device
433  * @chan: Channel number
434  * @pattern: Test pattern
435  *
436  * Configure a test pattern on the backend. This is typically used for
437  * calibrating the timings on the data digital interface.
438  *
439  * RETURNS:
440  * 0 on success, negative error number on failure.
441  */
442 int iio_backend_test_pattern_set(struct iio_backend *back,
443 				 unsigned int chan,
444 				 enum iio_backend_test_pattern pattern)
445 {
446 	if (pattern >= IIO_BACKEND_TEST_PATTERN_MAX)
447 		return -EINVAL;
448 
449 	return iio_backend_op_call(back, test_pattern_set, chan, pattern);
450 }
451 EXPORT_SYMBOL_NS_GPL(iio_backend_test_pattern_set, "IIO_BACKEND");
452 
453 /**
454  * iio_backend_chan_status - Get the channel status
455  * @back: Backend device
456  * @chan: Channel number
457  * @error: Error indication
458  *
459  * Get the current state of the backend channel. Typically used to check if
460  * there were any errors sending/receiving data.
461  *
462  * RETURNS:
463  * 0 on success, negative error number on failure.
464  */
465 int iio_backend_chan_status(struct iio_backend *back, unsigned int chan,
466 			    bool *error)
467 {
468 	return iio_backend_op_call(back, chan_status, chan, error);
469 }
470 EXPORT_SYMBOL_NS_GPL(iio_backend_chan_status, "IIO_BACKEND");
471 
472 /**
473  * iio_backend_iodelay_set - Set digital I/O delay
474  * @back: Backend device
475  * @lane: Lane number
476  * @taps: Number of taps
477  *
478  * Controls delays on sending/receiving data. One usecase for this is to
479  * calibrate the data digital interface so we get the best results when
480  * transferring data. Note that @taps has no unit since the actual delay per tap
481  * is very backend specific. Hence, frontend devices typically should go through
482  * an array of @taps (the size of that array should typically match the size of
483  * calibration points on the frontend device) and call this API.
484  *
485  * RETURNS:
486  * 0 on success, negative error number on failure.
487  */
488 int iio_backend_iodelay_set(struct iio_backend *back, unsigned int lane,
489 			    unsigned int taps)
490 {
491 	return iio_backend_op_call(back, iodelay_set, lane, taps);
492 }
493 EXPORT_SYMBOL_NS_GPL(iio_backend_iodelay_set, "IIO_BACKEND");
494 
495 /**
496  * iio_backend_data_sample_trigger - Control when to sample data
497  * @back: Backend device
498  * @trigger: Data trigger
499  *
500  * Mostly useful for input backends. Configures the backend for when to sample
501  * data (eg: rising vs falling edge).
502  *
503  * RETURNS:
504  * 0 on success, negative error number on failure.
505  */
506 int iio_backend_data_sample_trigger(struct iio_backend *back,
507 				    enum iio_backend_sample_trigger trigger)
508 {
509 	if (trigger >= IIO_BACKEND_SAMPLE_TRIGGER_MAX)
510 		return -EINVAL;
511 
512 	return iio_backend_op_call(back, data_sample_trigger, trigger);
513 }
514 EXPORT_SYMBOL_NS_GPL(iio_backend_data_sample_trigger, "IIO_BACKEND");
515 
516 static void iio_backend_free_buffer(void *arg)
517 {
518 	struct iio_backend_buffer_pair *pair = arg;
519 
520 	iio_backend_void_op_call(pair->back, free_buffer, pair->buffer);
521 }
522 
523 /**
524  * devm_iio_backend_request_buffer - Device managed buffer request
525  * @dev: Consumer device for the backend
526  * @back: Backend device
527  * @indio_dev: IIO device
528  *
529  * Request an IIO buffer from the backend. The type of the buffer (typically
530  * INDIO_BUFFER_HARDWARE) is up to the backend to decide. This is because,
531  * normally, the backend dictates what kind of buffering we can get.
532  *
533  * The backend .free_buffer() hooks is automatically called on @dev detach.
534  *
535  * RETURNS:
536  * 0 on success, negative error number on failure.
537  */
538 int devm_iio_backend_request_buffer(struct device *dev,
539 				    struct iio_backend *back,
540 				    struct iio_dev *indio_dev)
541 {
542 	struct iio_backend_buffer_pair *pair;
543 	struct iio_buffer *buffer;
544 
545 	pair = devm_kzalloc(dev, sizeof(*pair), GFP_KERNEL);
546 	if (!pair)
547 		return -ENOMEM;
548 
549 	buffer = iio_backend_ptr_op_call(back, request_buffer, indio_dev);
550 	if (IS_ERR(buffer))
551 		return PTR_ERR(buffer);
552 
553 	/* weak reference should be all what we need */
554 	pair->back = back;
555 	pair->buffer = buffer;
556 
557 	return devm_add_action_or_reset(dev, iio_backend_free_buffer, pair);
558 }
559 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_request_buffer, "IIO_BACKEND");
560 
561 /**
562  * iio_backend_read_raw - Read a channel attribute from a backend device.
563  * @back:	Backend device
564  * @chan:	IIO channel reference
565  * @val:	First returned value
566  * @val2:	Second returned value
567  * @mask:	Specify the attribute to return
568  *
569  * RETURNS:
570  * 0 on success, negative error number on failure.
571  */
572 int iio_backend_read_raw(struct iio_backend *back,
573 			 struct iio_chan_spec const *chan, int *val, int *val2,
574 			 long mask)
575 {
576 	return iio_backend_op_call(back, read_raw, chan, val, val2, mask);
577 }
578 EXPORT_SYMBOL_NS_GPL(iio_backend_read_raw, "IIO_BACKEND");
579 
580 static struct iio_backend *iio_backend_from_indio_dev_parent(const struct device *dev)
581 {
582 	struct iio_backend *back = ERR_PTR(-ENODEV), *iter;
583 
584 	/*
585 	 * We deliberately go through all backends even after finding a match.
586 	 * The reason is that we want to catch frontend devices which have more
587 	 * than one backend in which case returning the first we find is bogus.
588 	 * For those cases, frontends need to explicitly define
589 	 * get_iio_backend() in struct iio_info.
590 	 */
591 	guard(mutex)(&iio_back_lock);
592 	list_for_each_entry(iter, &iio_back_list, entry) {
593 		if (dev == iter->frontend_dev) {
594 			if (!IS_ERR(back)) {
595 				dev_warn(dev,
596 					 "Multiple backends! get_iio_backend() needs to be implemented");
597 				return ERR_PTR(-ENODEV);
598 			}
599 
600 			back = iter;
601 		}
602 	}
603 
604 	return back;
605 }
606 
607 /**
608  * iio_backend_ext_info_get - IIO ext_info read callback
609  * @indio_dev: IIO device
610  * @private: Data private to the driver
611  * @chan: IIO channel
612  * @buf: Buffer where to place the attribute data
613  *
614  * This helper is intended to be used by backends that extend an IIO channel
615  * (through iio_backend_extend_chan_spec()) with extended info. In that case,
616  * backends are not supposed to give their own callbacks (as they would not have
617  * a way to get the backend from indio_dev). This is the getter.
618  *
619  * RETURNS:
620  * Number of bytes written to buf, negative error number on failure.
621  */
622 ssize_t iio_backend_ext_info_get(struct iio_dev *indio_dev, uintptr_t private,
623 				 const struct iio_chan_spec *chan, char *buf)
624 {
625 	struct iio_backend *back;
626 
627 	/*
628 	 * The below should work for the majority of the cases. It will not work
629 	 * when one frontend has multiple backends in which case we'll need a
630 	 * new callback in struct iio_info so we can directly request the proper
631 	 * backend from the frontend. Anyways, let's only introduce new options
632 	 * when really needed...
633 	 */
634 	back = iio_backend_from_indio_dev_parent(indio_dev->dev.parent);
635 	if (IS_ERR(back))
636 		return PTR_ERR(back);
637 
638 	return iio_backend_op_call(back, ext_info_get, private, chan, buf);
639 }
640 EXPORT_SYMBOL_NS_GPL(iio_backend_ext_info_get, "IIO_BACKEND");
641 
642 /**
643  * iio_backend_ext_info_set - IIO ext_info write callback
644  * @indio_dev: IIO device
645  * @private: Data private to the driver
646  * @chan: IIO channel
647  * @buf: Buffer holding the sysfs attribute
648  * @len: Buffer length
649  *
650  * This helper is intended to be used by backends that extend an IIO channel
651  * (trough iio_backend_extend_chan_spec()) with extended info. In that case,
652  * backends are not supposed to give their own callbacks (as they would not have
653  * a way to get the backend from indio_dev). This is the setter.
654  *
655  * RETURNS:
656  * Buffer length on success, negative error number on failure.
657  */
658 ssize_t iio_backend_ext_info_set(struct iio_dev *indio_dev, uintptr_t private,
659 				 const struct iio_chan_spec *chan,
660 				 const char *buf, size_t len)
661 {
662 	struct iio_backend *back;
663 
664 	back = iio_backend_from_indio_dev_parent(indio_dev->dev.parent);
665 	if (IS_ERR(back))
666 		return PTR_ERR(back);
667 
668 	return iio_backend_op_call(back, ext_info_set, private, chan, buf, len);
669 }
670 EXPORT_SYMBOL_NS_GPL(iio_backend_ext_info_set, "IIO_BACKEND");
671 
672 /**
673  * iio_backend_interface_type_get - get the interface type used.
674  * @back: Backend device
675  * @type: Interface type
676  *
677  * RETURNS:
678  * 0 on success, negative error number on failure.
679  */
680 int iio_backend_interface_type_get(struct iio_backend *back,
681 				   enum iio_backend_interface_type *type)
682 {
683 	int ret;
684 
685 	ret = iio_backend_op_call(back, interface_type_get, type);
686 	if (ret)
687 		return ret;
688 
689 	if (*type >= IIO_BACKEND_INTERFACE_MAX)
690 		return -EINVAL;
691 
692 	return 0;
693 }
694 EXPORT_SYMBOL_NS_GPL(iio_backend_interface_type_get, "IIO_BACKEND");
695 
696 /**
697  * iio_backend_data_size_set - set the data width/size in the data bus.
698  * @back: Backend device
699  * @size: Size in bits
700  *
701  * Some frontend devices can dynamically control the word/data size on the
702  * interface/data bus. Hence, the backend device needs to be aware of it so
703  * data can be correctly transferred.
704  *
705  * Return:
706  * 0 on success, negative error number on failure.
707  */
708 int iio_backend_data_size_set(struct iio_backend *back, unsigned int size)
709 {
710 	if (!size)
711 		return -EINVAL;
712 
713 	return iio_backend_op_call(back, data_size_set, size);
714 }
715 EXPORT_SYMBOL_NS_GPL(iio_backend_data_size_set, "IIO_BACKEND");
716 
717 /**
718  * iio_backend_oversampling_ratio_set - set the oversampling ratio
719  * @back: Backend device
720  * @ratio: The oversampling ratio - value 1 corresponds to no oversampling.
721  *
722  * Return:
723  * 0 on success, negative error number on failure.
724  */
725 int iio_backend_oversampling_ratio_set(struct iio_backend *back,
726 				       unsigned int ratio)
727 {
728 	return iio_backend_op_call(back, oversampling_ratio_set, ratio);
729 }
730 EXPORT_SYMBOL_NS_GPL(iio_backend_oversampling_ratio_set, "IIO_BACKEND");
731 
732 /**
733  * iio_backend_extend_chan_spec - Extend an IIO channel
734  * @back: Backend device
735  * @chan: IIO channel
736  *
737  * Some backends may have their own functionalities and hence capable of
738  * extending a frontend's channel.
739  *
740  * RETURNS:
741  * 0 on success, negative error number on failure.
742  */
743 int iio_backend_extend_chan_spec(struct iio_backend *back,
744 				 struct iio_chan_spec *chan)
745 {
746 	const struct iio_chan_spec_ext_info *frontend_ext_info = chan->ext_info;
747 	const struct iio_chan_spec_ext_info *back_ext_info;
748 	int ret;
749 
750 	ret = iio_backend_op_call(back, extend_chan_spec, chan);
751 	if (ret)
752 		return ret;
753 	/*
754 	 * Let's keep things simple for now. Don't allow to overwrite the
755 	 * frontend's extended info. If ever needed, we can support appending
756 	 * it.
757 	 */
758 	if (frontend_ext_info && chan->ext_info != frontend_ext_info)
759 		return -EOPNOTSUPP;
760 	if (!chan->ext_info)
761 		return 0;
762 
763 	/* Don't allow backends to get creative and force their own handlers */
764 	for (back_ext_info = chan->ext_info; back_ext_info->name; back_ext_info++) {
765 		if (back_ext_info->read != iio_backend_ext_info_get)
766 			return -EINVAL;
767 		if (back_ext_info->write != iio_backend_ext_info_set)
768 			return -EINVAL;
769 	}
770 
771 	return 0;
772 }
773 EXPORT_SYMBOL_NS_GPL(iio_backend_extend_chan_spec, "IIO_BACKEND");
774 
775 static void iio_backend_release(void *arg)
776 {
777 	struct iio_backend *back = arg;
778 
779 	module_put(back->owner);
780 }
781 
782 static int __devm_iio_backend_get(struct device *dev, struct iio_backend *back)
783 {
784 	struct device_link *link;
785 	int ret;
786 
787 	/*
788 	 * Make sure the provider cannot be unloaded before the consumer module.
789 	 * Note that device_links would still guarantee that nothing is
790 	 * accessible (and breaks) but this makes it explicit that the consumer
791 	 * module must be also unloaded.
792 	 */
793 	if (!try_module_get(back->owner))
794 		return dev_err_probe(dev, -ENODEV,
795 				     "Cannot get module reference\n");
796 
797 	ret = devm_add_action_or_reset(dev, iio_backend_release, back);
798 	if (ret)
799 		return ret;
800 
801 	link = device_link_add(dev, back->dev, DL_FLAG_AUTOREMOVE_CONSUMER);
802 	if (!link)
803 		return dev_err_probe(dev, -EINVAL,
804 				     "Could not link to supplier(%s)\n",
805 				     dev_name(back->dev));
806 
807 	back->frontend_dev = dev;
808 
809 	dev_dbg(dev, "Found backend(%s) device\n", dev_name(back->dev));
810 
811 	return 0;
812 }
813 
814 /**
815  * iio_backend_ddr_enable - Enable interface DDR (Double Data Rate) mode
816  * @back: Backend device
817  *
818  * Enable DDR, data is generated by the IP at each front (raising and falling)
819  * of the bus clock signal.
820  *
821  * RETURNS:
822  * 0 on success, negative error number on failure.
823  */
824 int iio_backend_ddr_enable(struct iio_backend *back)
825 {
826 	return iio_backend_op_call(back, ddr_enable);
827 }
828 EXPORT_SYMBOL_NS_GPL(iio_backend_ddr_enable, "IIO_BACKEND");
829 
830 /**
831  * iio_backend_ddr_disable - Disable interface DDR (Double Data Rate) mode
832  * @back: Backend device
833  *
834  * Disable DDR, setting into SDR mode (Single Data Rate).
835  *
836  * RETURNS:
837  * 0 on success, negative error number on failure.
838  */
839 int iio_backend_ddr_disable(struct iio_backend *back)
840 {
841 	return iio_backend_op_call(back, ddr_disable);
842 }
843 EXPORT_SYMBOL_NS_GPL(iio_backend_ddr_disable, "IIO_BACKEND");
844 
845 /**
846  * iio_backend_data_stream_enable - Enable data stream
847  * @back: Backend device
848  *
849  * Enable data stream over the bus interface.
850  *
851  * RETURNS:
852  * 0 on success, negative error number on failure.
853  */
854 int iio_backend_data_stream_enable(struct iio_backend *back)
855 {
856 	return iio_backend_op_call(back, data_stream_enable);
857 }
858 EXPORT_SYMBOL_NS_GPL(iio_backend_data_stream_enable, "IIO_BACKEND");
859 
860 /**
861  * iio_backend_data_stream_disable - Disable data stream
862  * @back: Backend device
863  *
864  * Disable data stream over the bus interface.
865  *
866  * RETURNS:
867  * 0 on success, negative error number on failure.
868  */
869 int iio_backend_data_stream_disable(struct iio_backend *back)
870 {
871 	return iio_backend_op_call(back, data_stream_disable);
872 }
873 EXPORT_SYMBOL_NS_GPL(iio_backend_data_stream_disable, "IIO_BACKEND");
874 
875 /**
876  * iio_backend_data_transfer_addr - Set data address.
877  * @back: Backend device
878  * @address: Data register address
879  *
880  * Some devices may need to inform the backend about an address
881  * where to read or write the data.
882  *
883  * RETURNS:
884  * 0 on success, negative error number on failure.
885  */
886 int iio_backend_data_transfer_addr(struct iio_backend *back, u32 address)
887 {
888 	return iio_backend_op_call(back, data_transfer_addr, address);
889 }
890 EXPORT_SYMBOL_NS_GPL(iio_backend_data_transfer_addr, "IIO_BACKEND");
891 
892 static struct iio_backend *__devm_iio_backend_fwnode_get(struct device *dev, const char *name,
893 							 struct fwnode_handle *fwnode)
894 {
895 	struct fwnode_handle *fwnode_back;
896 	struct iio_backend *back;
897 	unsigned int index;
898 	int ret;
899 
900 	if (name) {
901 		ret = device_property_match_string(dev, "io-backend-names",
902 						   name);
903 		if (ret < 0)
904 			return ERR_PTR(ret);
905 		index = ret;
906 	} else {
907 		index = 0;
908 	}
909 
910 	fwnode_back = fwnode_find_reference(fwnode, "io-backends", index);
911 	if (IS_ERR(fwnode_back))
912 		return dev_err_cast_probe(dev, fwnode_back,
913 					  "Cannot get Firmware reference\n");
914 
915 	guard(mutex)(&iio_back_lock);
916 	list_for_each_entry(back, &iio_back_list, entry) {
917 		if (!device_match_fwnode(back->dev, fwnode_back))
918 			continue;
919 
920 		fwnode_handle_put(fwnode_back);
921 		ret = __devm_iio_backend_get(dev, back);
922 		if (ret)
923 			return ERR_PTR(ret);
924 
925 		if (name)
926 			back->idx = index;
927 
928 		return back;
929 	}
930 
931 	fwnode_handle_put(fwnode_back);
932 	return ERR_PTR(-EPROBE_DEFER);
933 }
934 
935 /**
936  * devm_iio_backend_get - Device managed backend device get
937  * @dev: Consumer device for the backend
938  * @name: Backend name
939  *
940  * Get's the backend associated with @dev.
941  *
942  * RETURNS:
943  * A backend pointer, negative error pointer otherwise.
944  */
945 struct iio_backend *devm_iio_backend_get(struct device *dev, const char *name)
946 {
947 	return __devm_iio_backend_fwnode_get(dev, name, dev_fwnode(dev));
948 }
949 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_get, "IIO_BACKEND");
950 
951 /**
952  * devm_iio_backend_fwnode_get - Device managed backend firmware node get
953  * @dev: Consumer device for the backend
954  * @name: Backend name
955  * @fwnode: Firmware node of the backend consumer
956  *
957  * Get's the backend associated with a firmware node.
958  *
959  * RETURNS:
960  * A backend pointer, negative error pointer otherwise.
961  */
962 struct iio_backend *devm_iio_backend_fwnode_get(struct device *dev,
963 						const char *name,
964 						struct fwnode_handle *fwnode)
965 {
966 	return __devm_iio_backend_fwnode_get(dev, name, fwnode);
967 }
968 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_fwnode_get, "IIO_BACKEND");
969 
970 /**
971  * __devm_iio_backend_get_from_fwnode_lookup - Device managed fwnode backend device get
972  * @dev: Consumer device for the backend
973  * @fwnode: Firmware node of the backend device
974  *
975  * Search the backend list for a device matching @fwnode.
976  * This API should not be used and it's only present for preventing the first
977  * user of this framework to break it's DT ABI.
978  *
979  * RETURNS:
980  * A backend pointer, negative error pointer otherwise.
981  */
982 struct iio_backend *
983 __devm_iio_backend_get_from_fwnode_lookup(struct device *dev,
984 					  struct fwnode_handle *fwnode)
985 {
986 	struct iio_backend *back;
987 	int ret;
988 
989 	guard(mutex)(&iio_back_lock);
990 	list_for_each_entry(back, &iio_back_list, entry) {
991 		if (!device_match_fwnode(back->dev, fwnode))
992 			continue;
993 
994 		ret = __devm_iio_backend_get(dev, back);
995 		if (ret)
996 			return ERR_PTR(ret);
997 
998 		return back;
999 	}
1000 
1001 	return ERR_PTR(-EPROBE_DEFER);
1002 }
1003 EXPORT_SYMBOL_NS_GPL(__devm_iio_backend_get_from_fwnode_lookup, "IIO_BACKEND");
1004 
1005 /**
1006  * iio_backend_get_priv - Get driver private data
1007  * @back: Backend device
1008  */
1009 void *iio_backend_get_priv(const struct iio_backend *back)
1010 {
1011 	return back->priv;
1012 }
1013 EXPORT_SYMBOL_NS_GPL(iio_backend_get_priv, "IIO_BACKEND");
1014 
1015 static void iio_backend_unregister(void *arg)
1016 {
1017 	struct iio_backend *back = arg;
1018 
1019 	guard(mutex)(&iio_back_lock);
1020 	list_del(&back->entry);
1021 }
1022 
1023 /**
1024  * devm_iio_backend_register - Device managed backend device register
1025  * @dev: Backend device being registered
1026  * @info: Backend info
1027  * @priv: Device private data
1028  *
1029  * @info is mandatory. Not providing it results in -EINVAL.
1030  *
1031  * RETURNS:
1032  * 0 on success, negative error number on failure.
1033  */
1034 int devm_iio_backend_register(struct device *dev,
1035 			      const struct iio_backend_info *info, void *priv)
1036 {
1037 	struct iio_backend *back;
1038 
1039 	if (!info || !info->ops)
1040 		return dev_err_probe(dev, -EINVAL, "No backend ops given\n");
1041 
1042 	/*
1043 	 * Through device_links, we guarantee that a frontend device cannot be
1044 	 * bound/exist if the backend driver is not around. Hence, we can bind
1045 	 * the backend object lifetime with the device being passed since
1046 	 * removing it will tear the frontend/consumer down.
1047 	 */
1048 	back = devm_kzalloc(dev, sizeof(*back), GFP_KERNEL);
1049 	if (!back)
1050 		return -ENOMEM;
1051 
1052 	back->ops = info->ops;
1053 	back->name = info->name;
1054 	back->owner = dev->driver->owner;
1055 	back->dev = dev;
1056 	back->priv = priv;
1057 	scoped_guard(mutex, &iio_back_lock)
1058 		list_add(&back->entry, &iio_back_list);
1059 
1060 	return devm_add_action_or_reset(dev, iio_backend_unregister, back);
1061 }
1062 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_register, "IIO_BACKEND");
1063 
1064 MODULE_AUTHOR("Nuno Sa <nuno.sa@analog.com>");
1065 MODULE_DESCRIPTION("Framework to handle complex IIO aggregate devices");
1066 MODULE_LICENSE("GPL");
1067