• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
iio_backend_debugfs_read_reg(struct file * file,char __user * userbuf,size_t count,loff_t * ppos)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 
iio_backend_debugfs_write_reg(struct file * file,const char __user * userbuf,size_t count,loff_t * ppos)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 
iio_backend_debugfs_read_name(struct file * file,char __user * userbuf,size_t count,loff_t * ppos)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  */
iio_backend_debugfs_add(struct iio_backend * back,struct iio_dev * indio_dev)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  */
iio_backend_debugfs_print_chan_status(struct iio_backend * back,unsigned int chan,char * buf,size_t len)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  */
iio_backend_chan_enable(struct iio_backend * back,unsigned int chan)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  */
iio_backend_chan_disable(struct iio_backend * back,unsigned int chan)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 
__iio_backend_disable(void * back)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  */
iio_backend_disable(struct iio_backend * back)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  */
iio_backend_enable(struct iio_backend * back)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  */
devm_iio_backend_enable(struct device * dev,struct iio_backend * back)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  */
iio_backend_data_format_set(struct iio_backend * back,unsigned int chan,const struct iio_backend_data_fmt * data)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  */
iio_backend_data_source_set(struct iio_backend * back,unsigned int chan,enum iio_backend_data_source data)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_set_sampling_freq - Set channel sampling rate
388  * @back: Backend device
389  * @chan: Channel number
390  * @sample_rate_hz: Sample rate
391  *
392  * RETURNS:
393  * 0 on success, negative error number on failure.
394  */
iio_backend_set_sampling_freq(struct iio_backend * back,unsigned int chan,u64 sample_rate_hz)395 int iio_backend_set_sampling_freq(struct iio_backend *back, unsigned int chan,
396 				  u64 sample_rate_hz)
397 {
398 	return iio_backend_op_call(back, set_sample_rate, chan, sample_rate_hz);
399 }
400 EXPORT_SYMBOL_NS_GPL(iio_backend_set_sampling_freq, IIO_BACKEND);
401 
402 /**
403  * iio_backend_test_pattern_set - Configure a test pattern
404  * @back: Backend device
405  * @chan: Channel number
406  * @pattern: Test pattern
407  *
408  * Configure a test pattern on the backend. This is typically used for
409  * calibrating the timings on the data digital interface.
410  *
411  * RETURNS:
412  * 0 on success, negative error number on failure.
413  */
iio_backend_test_pattern_set(struct iio_backend * back,unsigned int chan,enum iio_backend_test_pattern pattern)414 int iio_backend_test_pattern_set(struct iio_backend *back,
415 				 unsigned int chan,
416 				 enum iio_backend_test_pattern pattern)
417 {
418 	if (pattern >= IIO_BACKEND_TEST_PATTERN_MAX)
419 		return -EINVAL;
420 
421 	return iio_backend_op_call(back, test_pattern_set, chan, pattern);
422 }
423 EXPORT_SYMBOL_NS_GPL(iio_backend_test_pattern_set, IIO_BACKEND);
424 
425 /**
426  * iio_backend_chan_status - Get the channel status
427  * @back: Backend device
428  * @chan: Channel number
429  * @error: Error indication
430  *
431  * Get the current state of the backend channel. Typically used to check if
432  * there were any errors sending/receiving data.
433  *
434  * RETURNS:
435  * 0 on success, negative error number on failure.
436  */
iio_backend_chan_status(struct iio_backend * back,unsigned int chan,bool * error)437 int iio_backend_chan_status(struct iio_backend *back, unsigned int chan,
438 			    bool *error)
439 {
440 	return iio_backend_op_call(back, chan_status, chan, error);
441 }
442 EXPORT_SYMBOL_NS_GPL(iio_backend_chan_status, IIO_BACKEND);
443 
444 /**
445  * iio_backend_iodelay_set - Set digital I/O delay
446  * @back: Backend device
447  * @lane: Lane number
448  * @taps: Number of taps
449  *
450  * Controls delays on sending/receiving data. One usecase for this is to
451  * calibrate the data digital interface so we get the best results when
452  * transferring data. Note that @taps has no unit since the actual delay per tap
453  * is very backend specific. Hence, frontend devices typically should go through
454  * an array of @taps (the size of that array should typically match the size of
455  * calibration points on the frontend device) and call this API.
456  *
457  * RETURNS:
458  * 0 on success, negative error number on failure.
459  */
iio_backend_iodelay_set(struct iio_backend * back,unsigned int lane,unsigned int taps)460 int iio_backend_iodelay_set(struct iio_backend *back, unsigned int lane,
461 			    unsigned int taps)
462 {
463 	return iio_backend_op_call(back, iodelay_set, lane, taps);
464 }
465 EXPORT_SYMBOL_NS_GPL(iio_backend_iodelay_set, IIO_BACKEND);
466 
467 /**
468  * iio_backend_data_sample_trigger - Control when to sample data
469  * @back: Backend device
470  * @trigger: Data trigger
471  *
472  * Mostly useful for input backends. Configures the backend for when to sample
473  * data (eg: rising vs falling edge).
474  *
475  * RETURNS:
476  * 0 on success, negative error number on failure.
477  */
iio_backend_data_sample_trigger(struct iio_backend * back,enum iio_backend_sample_trigger trigger)478 int iio_backend_data_sample_trigger(struct iio_backend *back,
479 				    enum iio_backend_sample_trigger trigger)
480 {
481 	if (trigger >= IIO_BACKEND_SAMPLE_TRIGGER_MAX)
482 		return -EINVAL;
483 
484 	return iio_backend_op_call(back, data_sample_trigger, trigger);
485 }
486 EXPORT_SYMBOL_NS_GPL(iio_backend_data_sample_trigger, IIO_BACKEND);
487 
iio_backend_free_buffer(void * arg)488 static void iio_backend_free_buffer(void *arg)
489 {
490 	struct iio_backend_buffer_pair *pair = arg;
491 
492 	iio_backend_void_op_call(pair->back, free_buffer, pair->buffer);
493 }
494 
495 /**
496  * devm_iio_backend_request_buffer - Device managed buffer request
497  * @dev: Consumer device for the backend
498  * @back: Backend device
499  * @indio_dev: IIO device
500  *
501  * Request an IIO buffer from the backend. The type of the buffer (typically
502  * INDIO_BUFFER_HARDWARE) is up to the backend to decide. This is because,
503  * normally, the backend dictates what kind of buffering we can get.
504  *
505  * The backend .free_buffer() hooks is automatically called on @dev detach.
506  *
507  * RETURNS:
508  * 0 on success, negative error number on failure.
509  */
devm_iio_backend_request_buffer(struct device * dev,struct iio_backend * back,struct iio_dev * indio_dev)510 int devm_iio_backend_request_buffer(struct device *dev,
511 				    struct iio_backend *back,
512 				    struct iio_dev *indio_dev)
513 {
514 	struct iio_backend_buffer_pair *pair;
515 	struct iio_buffer *buffer;
516 
517 	pair = devm_kzalloc(dev, sizeof(*pair), GFP_KERNEL);
518 	if (!pair)
519 		return -ENOMEM;
520 
521 	buffer = iio_backend_ptr_op_call(back, request_buffer, indio_dev);
522 	if (IS_ERR(buffer))
523 		return PTR_ERR(buffer);
524 
525 	/* weak reference should be all what we need */
526 	pair->back = back;
527 	pair->buffer = buffer;
528 
529 	return devm_add_action_or_reset(dev, iio_backend_free_buffer, pair);
530 }
531 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_request_buffer, IIO_BACKEND);
532 
533 /**
534  * iio_backend_read_raw - Read a channel attribute from a backend device.
535  * @back:	Backend device
536  * @chan:	IIO channel reference
537  * @val:	First returned value
538  * @val2:	Second returned value
539  * @mask:	Specify the attribute to return
540  *
541  * RETURNS:
542  * 0 on success, negative error number on failure.
543  */
iio_backend_read_raw(struct iio_backend * back,struct iio_chan_spec const * chan,int * val,int * val2,long mask)544 int iio_backend_read_raw(struct iio_backend *back,
545 			 struct iio_chan_spec const *chan, int *val, int *val2,
546 			 long mask)
547 {
548 	return iio_backend_op_call(back, read_raw, chan, val, val2, mask);
549 }
550 EXPORT_SYMBOL_NS_GPL(iio_backend_read_raw, IIO_BACKEND);
551 
iio_backend_from_indio_dev_parent(const struct device * dev)552 static struct iio_backend *iio_backend_from_indio_dev_parent(const struct device *dev)
553 {
554 	struct iio_backend *back = ERR_PTR(-ENODEV), *iter;
555 
556 	/*
557 	 * We deliberately go through all backends even after finding a match.
558 	 * The reason is that we want to catch frontend devices which have more
559 	 * than one backend in which case returning the first we find is bogus.
560 	 * For those cases, frontends need to explicitly define
561 	 * get_iio_backend() in struct iio_info.
562 	 */
563 	guard(mutex)(&iio_back_lock);
564 	list_for_each_entry(iter, &iio_back_list, entry) {
565 		if (dev == iter->frontend_dev) {
566 			if (!IS_ERR(back)) {
567 				dev_warn(dev,
568 					 "Multiple backends! get_iio_backend() needs to be implemented");
569 				return ERR_PTR(-ENODEV);
570 			}
571 
572 			back = iter;
573 		}
574 	}
575 
576 	return back;
577 }
578 
579 /**
580  * iio_backend_ext_info_get - IIO ext_info read callback
581  * @indio_dev: IIO device
582  * @private: Data private to the driver
583  * @chan: IIO channel
584  * @buf: Buffer where to place the attribute data
585  *
586  * This helper is intended to be used by backends that extend an IIO channel
587  * (through iio_backend_extend_chan_spec()) with extended info. In that case,
588  * backends are not supposed to give their own callbacks (as they would not have
589  * a way to get the backend from indio_dev). This is the getter.
590  *
591  * RETURNS:
592  * Number of bytes written to buf, negative error number on failure.
593  */
iio_backend_ext_info_get(struct iio_dev * indio_dev,uintptr_t private,const struct iio_chan_spec * chan,char * buf)594 ssize_t iio_backend_ext_info_get(struct iio_dev *indio_dev, uintptr_t private,
595 				 const struct iio_chan_spec *chan, char *buf)
596 {
597 	struct iio_backend *back;
598 
599 	/*
600 	 * The below should work for the majority of the cases. It will not work
601 	 * when one frontend has multiple backends in which case we'll need a
602 	 * new callback in struct iio_info so we can directly request the proper
603 	 * backend from the frontend. Anyways, let's only introduce new options
604 	 * when really needed...
605 	 */
606 	back = iio_backend_from_indio_dev_parent(indio_dev->dev.parent);
607 	if (IS_ERR(back))
608 		return PTR_ERR(back);
609 
610 	return iio_backend_op_call(back, ext_info_get, private, chan, buf);
611 }
612 EXPORT_SYMBOL_NS_GPL(iio_backend_ext_info_get, IIO_BACKEND);
613 
614 /**
615  * iio_backend_ext_info_set - IIO ext_info write callback
616  * @indio_dev: IIO device
617  * @private: Data private to the driver
618  * @chan: IIO channel
619  * @buf: Buffer holding the sysfs attribute
620  * @len: Buffer length
621  *
622  * This helper is intended to be used by backends that extend an IIO channel
623  * (trough iio_backend_extend_chan_spec()) with extended info. In that case,
624  * backends are not supposed to give their own callbacks (as they would not have
625  * a way to get the backend from indio_dev). This is the setter.
626  *
627  * RETURNS:
628  * Buffer length on success, negative error number on failure.
629  */
iio_backend_ext_info_set(struct iio_dev * indio_dev,uintptr_t private,const struct iio_chan_spec * chan,const char * buf,size_t len)630 ssize_t iio_backend_ext_info_set(struct iio_dev *indio_dev, uintptr_t private,
631 				 const struct iio_chan_spec *chan,
632 				 const char *buf, size_t len)
633 {
634 	struct iio_backend *back;
635 
636 	back = iio_backend_from_indio_dev_parent(indio_dev->dev.parent);
637 	if (IS_ERR(back))
638 		return PTR_ERR(back);
639 
640 	return iio_backend_op_call(back, ext_info_set, private, chan, buf, len);
641 }
642 EXPORT_SYMBOL_NS_GPL(iio_backend_ext_info_set, IIO_BACKEND);
643 
644 /**
645  * iio_backend_extend_chan_spec - Extend an IIO channel
646  * @back: Backend device
647  * @chan: IIO channel
648  *
649  * Some backends may have their own functionalities and hence capable of
650  * extending a frontend's channel.
651  *
652  * RETURNS:
653  * 0 on success, negative error number on failure.
654  */
iio_backend_extend_chan_spec(struct iio_backend * back,struct iio_chan_spec * chan)655 int iio_backend_extend_chan_spec(struct iio_backend *back,
656 				 struct iio_chan_spec *chan)
657 {
658 	const struct iio_chan_spec_ext_info *frontend_ext_info = chan->ext_info;
659 	const struct iio_chan_spec_ext_info *back_ext_info;
660 	int ret;
661 
662 	ret = iio_backend_op_call(back, extend_chan_spec, chan);
663 	if (ret)
664 		return ret;
665 	/*
666 	 * Let's keep things simple for now. Don't allow to overwrite the
667 	 * frontend's extended info. If ever needed, we can support appending
668 	 * it.
669 	 */
670 	if (frontend_ext_info && chan->ext_info != frontend_ext_info)
671 		return -EOPNOTSUPP;
672 	if (!chan->ext_info)
673 		return 0;
674 
675 	/* Don't allow backends to get creative and force their own handlers */
676 	for (back_ext_info = chan->ext_info; back_ext_info->name; back_ext_info++) {
677 		if (back_ext_info->read != iio_backend_ext_info_get)
678 			return -EINVAL;
679 		if (back_ext_info->write != iio_backend_ext_info_set)
680 			return -EINVAL;
681 	}
682 
683 	return 0;
684 }
685 EXPORT_SYMBOL_NS_GPL(iio_backend_extend_chan_spec, IIO_BACKEND);
686 
iio_backend_release(void * arg)687 static void iio_backend_release(void *arg)
688 {
689 	struct iio_backend *back = arg;
690 
691 	module_put(back->owner);
692 }
693 
__devm_iio_backend_get(struct device * dev,struct iio_backend * back)694 static int __devm_iio_backend_get(struct device *dev, struct iio_backend *back)
695 {
696 	struct device_link *link;
697 	int ret;
698 
699 	/*
700 	 * Make sure the provider cannot be unloaded before the consumer module.
701 	 * Note that device_links would still guarantee that nothing is
702 	 * accessible (and breaks) but this makes it explicit that the consumer
703 	 * module must be also unloaded.
704 	 */
705 	if (!try_module_get(back->owner))
706 		return dev_err_probe(dev, -ENODEV,
707 				     "Cannot get module reference\n");
708 
709 	ret = devm_add_action_or_reset(dev, iio_backend_release, back);
710 	if (ret)
711 		return ret;
712 
713 	link = device_link_add(dev, back->dev, DL_FLAG_AUTOREMOVE_CONSUMER);
714 	if (!link)
715 		return dev_err_probe(dev, -EINVAL,
716 				     "Could not link to supplier(%s)\n",
717 				     dev_name(back->dev));
718 
719 	back->frontend_dev = dev;
720 
721 	dev_dbg(dev, "Found backend(%s) device\n", dev_name(back->dev));
722 
723 	return 0;
724 }
725 
__devm_iio_backend_fwnode_get(struct device * dev,const char * name,struct fwnode_handle * fwnode)726 static struct iio_backend *__devm_iio_backend_fwnode_get(struct device *dev, const char *name,
727 							 struct fwnode_handle *fwnode)
728 {
729 	struct fwnode_handle *fwnode_back;
730 	struct iio_backend *back;
731 	unsigned int index;
732 	int ret;
733 
734 	if (name) {
735 		ret = device_property_match_string(dev, "io-backend-names",
736 						   name);
737 		if (ret < 0)
738 			return ERR_PTR(ret);
739 		index = ret;
740 	} else {
741 		index = 0;
742 	}
743 
744 	fwnode_back = fwnode_find_reference(fwnode, "io-backends", index);
745 	if (IS_ERR(fwnode_back))
746 		return dev_err_cast_probe(dev, fwnode_back,
747 					  "Cannot get Firmware reference\n");
748 
749 	guard(mutex)(&iio_back_lock);
750 	list_for_each_entry(back, &iio_back_list, entry) {
751 		if (!device_match_fwnode(back->dev, fwnode_back))
752 			continue;
753 
754 		fwnode_handle_put(fwnode_back);
755 		ret = __devm_iio_backend_get(dev, back);
756 		if (ret)
757 			return ERR_PTR(ret);
758 
759 		if (name)
760 			back->idx = index;
761 
762 		return back;
763 	}
764 
765 	fwnode_handle_put(fwnode_back);
766 	return ERR_PTR(-EPROBE_DEFER);
767 }
768 
769 /**
770  * devm_iio_backend_get - Device managed backend device get
771  * @dev: Consumer device for the backend
772  * @name: Backend name
773  *
774  * Get's the backend associated with @dev.
775  *
776  * RETURNS:
777  * A backend pointer, negative error pointer otherwise.
778  */
devm_iio_backend_get(struct device * dev,const char * name)779 struct iio_backend *devm_iio_backend_get(struct device *dev, const char *name)
780 {
781 	return __devm_iio_backend_fwnode_get(dev, name, dev_fwnode(dev));
782 }
783 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_get, IIO_BACKEND);
784 
785 /**
786  * devm_iio_backend_fwnode_get - Device managed backend firmware node get
787  * @dev: Consumer device for the backend
788  * @name: Backend name
789  * @fwnode: Firmware node of the backend consumer
790  *
791  * Get's the backend associated with a firmware node.
792  *
793  * RETURNS:
794  * A backend pointer, negative error pointer otherwise.
795  */
devm_iio_backend_fwnode_get(struct device * dev,const char * name,struct fwnode_handle * fwnode)796 struct iio_backend *devm_iio_backend_fwnode_get(struct device *dev,
797 						const char *name,
798 						struct fwnode_handle *fwnode)
799 {
800 	return __devm_iio_backend_fwnode_get(dev, name, fwnode);
801 }
802 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_fwnode_get, IIO_BACKEND);
803 
804 /**
805  * __devm_iio_backend_get_from_fwnode_lookup - Device managed fwnode backend device get
806  * @dev: Consumer device for the backend
807  * @fwnode: Firmware node of the backend device
808  *
809  * Search the backend list for a device matching @fwnode.
810  * This API should not be used and it's only present for preventing the first
811  * user of this framework to break it's DT ABI.
812  *
813  * RETURNS:
814  * A backend pointer, negative error pointer otherwise.
815  */
816 struct iio_backend *
__devm_iio_backend_get_from_fwnode_lookup(struct device * dev,struct fwnode_handle * fwnode)817 __devm_iio_backend_get_from_fwnode_lookup(struct device *dev,
818 					  struct fwnode_handle *fwnode)
819 {
820 	struct iio_backend *back;
821 	int ret;
822 
823 	guard(mutex)(&iio_back_lock);
824 	list_for_each_entry(back, &iio_back_list, entry) {
825 		if (!device_match_fwnode(back->dev, fwnode))
826 			continue;
827 
828 		ret = __devm_iio_backend_get(dev, back);
829 		if (ret)
830 			return ERR_PTR(ret);
831 
832 		return back;
833 	}
834 
835 	return ERR_PTR(-EPROBE_DEFER);
836 }
837 EXPORT_SYMBOL_NS_GPL(__devm_iio_backend_get_from_fwnode_lookup, IIO_BACKEND);
838 
839 /**
840  * iio_backend_get_priv - Get driver private data
841  * @back: Backend device
842  */
iio_backend_get_priv(const struct iio_backend * back)843 void *iio_backend_get_priv(const struct iio_backend *back)
844 {
845 	return back->priv;
846 }
847 EXPORT_SYMBOL_NS_GPL(iio_backend_get_priv, IIO_BACKEND);
848 
iio_backend_unregister(void * arg)849 static void iio_backend_unregister(void *arg)
850 {
851 	struct iio_backend *back = arg;
852 
853 	guard(mutex)(&iio_back_lock);
854 	list_del(&back->entry);
855 }
856 
857 /**
858  * devm_iio_backend_register - Device managed backend device register
859  * @dev: Backend device being registered
860  * @info: Backend info
861  * @priv: Device private data
862  *
863  * @info is mandatory. Not providing it results in -EINVAL.
864  *
865  * RETURNS:
866  * 0 on success, negative error number on failure.
867  */
devm_iio_backend_register(struct device * dev,const struct iio_backend_info * info,void * priv)868 int devm_iio_backend_register(struct device *dev,
869 			      const struct iio_backend_info *info, void *priv)
870 {
871 	struct iio_backend *back;
872 
873 	if (!info || !info->ops)
874 		return dev_err_probe(dev, -EINVAL, "No backend ops given\n");
875 
876 	/*
877 	 * Through device_links, we guarantee that a frontend device cannot be
878 	 * bound/exist if the backend driver is not around. Hence, we can bind
879 	 * the backend object lifetime with the device being passed since
880 	 * removing it will tear the frontend/consumer down.
881 	 */
882 	back = devm_kzalloc(dev, sizeof(*back), GFP_KERNEL);
883 	if (!back)
884 		return -ENOMEM;
885 
886 	back->ops = info->ops;
887 	back->name = info->name;
888 	back->owner = dev->driver->owner;
889 	back->dev = dev;
890 	back->priv = priv;
891 	scoped_guard(mutex, &iio_back_lock)
892 		list_add(&back->entry, &iio_back_list);
893 
894 	return devm_add_action_or_reset(dev, iio_backend_unregister, back);
895 }
896 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_register, IIO_BACKEND);
897 
898 MODULE_AUTHOR("Nuno Sa <nuno.sa@analog.com>");
899 MODULE_DESCRIPTION("Framework to handle complex IIO aggregate devices");
900 MODULE_LICENSE("GPL");
901