1 /* The industrial I/O core
2  *
3  * Copyright (c) 2008 Jonathan Cameron
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 as published by
7  * the Free Software Foundation.
8  *
9  * Based on elements of hwmon and input subsystems.
10  */
11 
12 #define pr_fmt(fmt) "iio-core: " fmt
13 
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/idr.h>
17 #include <linux/kdev_t.h>
18 #include <linux/err.h>
19 #include <linux/device.h>
20 #include <linux/fs.h>
21 #include <linux/poll.h>
22 #include <linux/sched.h>
23 #include <linux/wait.h>
24 #include <linux/cdev.h>
25 #include <linux/slab.h>
26 #include <linux/anon_inodes.h>
27 #include <linux/debugfs.h>
28 #include <linux/iio/iio.h>
29 #include "iio_core.h"
30 #include "iio_core_trigger.h"
31 #include <linux/iio/sysfs.h>
32 #include <linux/iio/events.h>
33 #include <linux/iio/buffer.h>
34 
35 /* IDA to assign each registered device a unique id */
36 static DEFINE_IDA(iio_ida);
37 
38 static dev_t iio_devt;
39 
40 #define IIO_DEV_MAX 256
41 struct bus_type iio_bus_type = {
42 	.name = "iio",
43 };
44 EXPORT_SYMBOL(iio_bus_type);
45 
46 static struct dentry *iio_debugfs_dentry;
47 
48 static const char * const iio_direction[] = {
49 	[0] = "in",
50 	[1] = "out",
51 };
52 
53 static const char * const iio_chan_type_name_spec[] = {
54 	[IIO_VOLTAGE] = "voltage",
55 	[IIO_CURRENT] = "current",
56 	[IIO_POWER] = "power",
57 	[IIO_ACCEL] = "accel",
58 	[IIO_ANGL_VEL] = "anglvel",
59 	[IIO_MAGN] = "magn",
60 	[IIO_LIGHT] = "illuminance",
61 	[IIO_INTENSITY] = "intensity",
62 	[IIO_PROXIMITY] = "proximity",
63 	[IIO_TEMP] = "temp",
64 	[IIO_INCLI] = "incli",
65 	[IIO_ROT] = "rot",
66 	[IIO_ANGL] = "angl",
67 	[IIO_TIMESTAMP] = "timestamp",
68 	[IIO_CAPACITANCE] = "capacitance",
69 	[IIO_ALTVOLTAGE] = "altvoltage",
70 	[IIO_CCT] = "cct",
71 	[IIO_PRESSURE] = "pressure",
72 	[IIO_HUMIDITYRELATIVE] = "humidityrelative",
73 };
74 
75 static const char * const iio_modifier_names[] = {
76 	[IIO_MOD_X] = "x",
77 	[IIO_MOD_Y] = "y",
78 	[IIO_MOD_Z] = "z",
79 	[IIO_MOD_ROOT_SUM_SQUARED_X_Y] = "sqrt(x^2+y^2)",
80 	[IIO_MOD_SUM_SQUARED_X_Y_Z] = "x^2+y^2+z^2",
81 	[IIO_MOD_LIGHT_BOTH] = "both",
82 	[IIO_MOD_LIGHT_IR] = "ir",
83 	[IIO_MOD_LIGHT_CLEAR] = "clear",
84 	[IIO_MOD_LIGHT_RED] = "red",
85 	[IIO_MOD_LIGHT_GREEN] = "green",
86 	[IIO_MOD_LIGHT_BLUE] = "blue",
87 	[IIO_MOD_QUATERNION] = "quaternion",
88 	[IIO_MOD_TEMP_AMBIENT] = "ambient",
89 	[IIO_MOD_TEMP_OBJECT] = "object",
90 };
91 
92 /* relies on pairs of these shared then separate */
93 static const char * const iio_chan_info_postfix[] = {
94 	[IIO_CHAN_INFO_RAW] = "raw",
95 	[IIO_CHAN_INFO_PROCESSED] = "input",
96 	[IIO_CHAN_INFO_SCALE] = "scale",
97 	[IIO_CHAN_INFO_OFFSET] = "offset",
98 	[IIO_CHAN_INFO_CALIBSCALE] = "calibscale",
99 	[IIO_CHAN_INFO_CALIBBIAS] = "calibbias",
100 	[IIO_CHAN_INFO_PEAK] = "peak_raw",
101 	[IIO_CHAN_INFO_PEAK_SCALE] = "peak_scale",
102 	[IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW] = "quadrature_correction_raw",
103 	[IIO_CHAN_INFO_AVERAGE_RAW] = "mean_raw",
104 	[IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY]
105 	= "filter_low_pass_3db_frequency",
106 	[IIO_CHAN_INFO_SAMP_FREQ] = "sampling_frequency",
107 	[IIO_CHAN_INFO_FREQUENCY] = "frequency",
108 	[IIO_CHAN_INFO_PHASE] = "phase",
109 	[IIO_CHAN_INFO_HARDWAREGAIN] = "hardwaregain",
110 	[IIO_CHAN_INFO_HYSTERESIS] = "hysteresis",
111 	[IIO_CHAN_INFO_INT_TIME] = "integration_time",
112 };
113 
114 /**
115  * iio_find_channel_from_si() - get channel from its scan index
116  * @indio_dev:		device
117  * @si:			scan index to match
118  */
119 const struct iio_chan_spec
120 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
121 {
122 	int i;
123 
124 	for (i = 0; i < indio_dev->num_channels; i++)
125 		if (indio_dev->channels[i].scan_index == si)
126 			return &indio_dev->channels[i];
127 	return NULL;
128 }
129 
130 /* This turns up an awful lot */
131 ssize_t iio_read_const_attr(struct device *dev,
132 			    struct device_attribute *attr,
133 			    char *buf)
134 {
135 	return sprintf(buf, "%s\n", to_iio_const_attr(attr)->string);
136 }
137 EXPORT_SYMBOL(iio_read_const_attr);
138 
139 static int __init iio_init(void)
140 {
141 	int ret;
142 
143 	/* Register sysfs bus */
144 	ret  = bus_register(&iio_bus_type);
145 	if (ret < 0) {
146 		pr_err("could not register bus type\n");
147 		goto error_nothing;
148 	}
149 
150 	ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
151 	if (ret < 0) {
152 		pr_err("failed to allocate char dev region\n");
153 		goto error_unregister_bus_type;
154 	}
155 
156 	iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
157 
158 	return 0;
159 
160 error_unregister_bus_type:
161 	bus_unregister(&iio_bus_type);
162 error_nothing:
163 	return ret;
164 }
165 
166 static void __exit iio_exit(void)
167 {
168 	if (iio_devt)
169 		unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
170 	bus_unregister(&iio_bus_type);
171 	debugfs_remove(iio_debugfs_dentry);
172 }
173 
174 #if defined(CONFIG_DEBUG_FS)
175 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
176 			      size_t count, loff_t *ppos)
177 {
178 	struct iio_dev *indio_dev = file->private_data;
179 	char buf[20];
180 	unsigned val = 0;
181 	ssize_t len;
182 	int ret;
183 
184 	ret = indio_dev->info->debugfs_reg_access(indio_dev,
185 						  indio_dev->cached_reg_addr,
186 						  0, &val);
187 	if (ret)
188 		dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
189 
190 	len = snprintf(buf, sizeof(buf), "0x%X\n", val);
191 
192 	return simple_read_from_buffer(userbuf, count, ppos, buf, len);
193 }
194 
195 static ssize_t iio_debugfs_write_reg(struct file *file,
196 		     const char __user *userbuf, size_t count, loff_t *ppos)
197 {
198 	struct iio_dev *indio_dev = file->private_data;
199 	unsigned reg, val;
200 	char buf[80];
201 	int ret;
202 
203 	count = min_t(size_t, count, (sizeof(buf)-1));
204 	if (copy_from_user(buf, userbuf, count))
205 		return -EFAULT;
206 
207 	buf[count] = 0;
208 
209 	ret = sscanf(buf, "%i %i", &reg, &val);
210 
211 	switch (ret) {
212 	case 1:
213 		indio_dev->cached_reg_addr = reg;
214 		break;
215 	case 2:
216 		indio_dev->cached_reg_addr = reg;
217 		ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
218 							  val, NULL);
219 		if (ret) {
220 			dev_err(indio_dev->dev.parent, "%s: write failed\n",
221 				__func__);
222 			return ret;
223 		}
224 		break;
225 	default:
226 		return -EINVAL;
227 	}
228 
229 	return count;
230 }
231 
232 static const struct file_operations iio_debugfs_reg_fops = {
233 	.open = simple_open,
234 	.read = iio_debugfs_read_reg,
235 	.write = iio_debugfs_write_reg,
236 };
237 
238 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
239 {
240 	debugfs_remove_recursive(indio_dev->debugfs_dentry);
241 }
242 
243 static int iio_device_register_debugfs(struct iio_dev *indio_dev)
244 {
245 	struct dentry *d;
246 
247 	if (indio_dev->info->debugfs_reg_access == NULL)
248 		return 0;
249 
250 	if (!iio_debugfs_dentry)
251 		return 0;
252 
253 	indio_dev->debugfs_dentry =
254 		debugfs_create_dir(dev_name(&indio_dev->dev),
255 				   iio_debugfs_dentry);
256 	if (indio_dev->debugfs_dentry == NULL) {
257 		dev_warn(indio_dev->dev.parent,
258 			 "Failed to create debugfs directory\n");
259 		return -EFAULT;
260 	}
261 
262 	d = debugfs_create_file("direct_reg_access", 0644,
263 				indio_dev->debugfs_dentry,
264 				indio_dev, &iio_debugfs_reg_fops);
265 	if (!d) {
266 		iio_device_unregister_debugfs(indio_dev);
267 		return -ENOMEM;
268 	}
269 
270 	return 0;
271 }
272 #else
273 static int iio_device_register_debugfs(struct iio_dev *indio_dev)
274 {
275 	return 0;
276 }
277 
278 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
279 {
280 }
281 #endif /* CONFIG_DEBUG_FS */
282 
283 static ssize_t iio_read_channel_ext_info(struct device *dev,
284 				     struct device_attribute *attr,
285 				     char *buf)
286 {
287 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
288 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
289 	const struct iio_chan_spec_ext_info *ext_info;
290 
291 	ext_info = &this_attr->c->ext_info[this_attr->address];
292 
293 	return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
294 }
295 
296 static ssize_t iio_write_channel_ext_info(struct device *dev,
297 				     struct device_attribute *attr,
298 				     const char *buf,
299 					 size_t len)
300 {
301 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
302 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
303 	const struct iio_chan_spec_ext_info *ext_info;
304 
305 	ext_info = &this_attr->c->ext_info[this_attr->address];
306 
307 	return ext_info->write(indio_dev, ext_info->private,
308 			       this_attr->c, buf, len);
309 }
310 
311 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
312 	uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
313 {
314 	const struct iio_enum *e = (const struct iio_enum *)priv;
315 	unsigned int i;
316 	size_t len = 0;
317 
318 	if (!e->num_items)
319 		return 0;
320 
321 	for (i = 0; i < e->num_items; ++i)
322 		len += scnprintf(buf + len, PAGE_SIZE - len, "%s ", e->items[i]);
323 
324 	/* replace last space with a newline */
325 	buf[len - 1] = '\n';
326 
327 	return len;
328 }
329 EXPORT_SYMBOL_GPL(iio_enum_available_read);
330 
331 ssize_t iio_enum_read(struct iio_dev *indio_dev,
332 	uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
333 {
334 	const struct iio_enum *e = (const struct iio_enum *)priv;
335 	int i;
336 
337 	if (!e->get)
338 		return -EINVAL;
339 
340 	i = e->get(indio_dev, chan);
341 	if (i < 0)
342 		return i;
343 	else if (i >= e->num_items)
344 		return -EINVAL;
345 
346 	return snprintf(buf, PAGE_SIZE, "%s\n", e->items[i]);
347 }
348 EXPORT_SYMBOL_GPL(iio_enum_read);
349 
350 ssize_t iio_enum_write(struct iio_dev *indio_dev,
351 	uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
352 	size_t len)
353 {
354 	const struct iio_enum *e = (const struct iio_enum *)priv;
355 	unsigned int i;
356 	int ret;
357 
358 	if (!e->set)
359 		return -EINVAL;
360 
361 	for (i = 0; i < e->num_items; i++) {
362 		if (sysfs_streq(buf, e->items[i]))
363 			break;
364 	}
365 
366 	if (i == e->num_items)
367 		return -EINVAL;
368 
369 	ret = e->set(indio_dev, chan, i);
370 	return ret ? ret : len;
371 }
372 EXPORT_SYMBOL_GPL(iio_enum_write);
373 
374 /**
375  * iio_format_value() - Formats a IIO value into its string representation
376  * @buf: The buffer to which the formated value gets written
377  * @type: One of the IIO_VAL_... constants. This decides how the val and val2
378  *        parameters are formatted.
379  * @vals: pointer to the values, exact meaning depends on the type parameter.
380  */
381 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
382 {
383 	unsigned long long tmp;
384 	bool scale_db = false;
385 
386 	switch (type) {
387 	case IIO_VAL_INT:
388 		return sprintf(buf, "%d\n", vals[0]);
389 	case IIO_VAL_INT_PLUS_MICRO_DB:
390 		scale_db = true;
391 	case IIO_VAL_INT_PLUS_MICRO:
392 		if (vals[1] < 0)
393 			return sprintf(buf, "-%ld.%06u%s\n", abs(vals[0]),
394 					-vals[1],
395 				scale_db ? " dB" : "");
396 		else
397 			return sprintf(buf, "%d.%06u%s\n", vals[0], vals[1],
398 				scale_db ? " dB" : "");
399 	case IIO_VAL_INT_PLUS_NANO:
400 		if (vals[1] < 0)
401 			return sprintf(buf, "-%ld.%09u\n", abs(vals[0]),
402 					-vals[1]);
403 		else
404 			return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
405 	case IIO_VAL_FRACTIONAL:
406 		tmp = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
407 		vals[1] = do_div(tmp, 1000000000LL);
408 		vals[0] = tmp;
409 		return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
410 	case IIO_VAL_FRACTIONAL_LOG2:
411 		tmp = (s64)vals[0] * 1000000000LL >> vals[1];
412 		vals[1] = do_div(tmp, 1000000000LL);
413 		vals[0] = tmp;
414 		return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
415 	case IIO_VAL_INT_MULTIPLE:
416 	{
417 		int i;
418 		int len = 0;
419 
420 		for (i = 0; i < size; ++i)
421 			len += snprintf(&buf[len], PAGE_SIZE - len, "%d ",
422 								vals[i]);
423 		len += snprintf(&buf[len], PAGE_SIZE - len, "\n");
424 		return len;
425 	}
426 	default:
427 		return 0;
428 	}
429 }
430 
431 static ssize_t iio_read_channel_info(struct device *dev,
432 				     struct device_attribute *attr,
433 				     char *buf)
434 {
435 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
436 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
437 	int vals[INDIO_MAX_RAW_ELEMENTS];
438 	int ret;
439 	int val_len = 2;
440 
441 	if (indio_dev->info->read_raw_multi)
442 		ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
443 							INDIO_MAX_RAW_ELEMENTS,
444 							vals, &val_len,
445 							this_attr->address);
446 	else
447 		ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
448 				    &vals[0], &vals[1], this_attr->address);
449 
450 	if (ret < 0)
451 		return ret;
452 
453 	return iio_format_value(buf, ret, val_len, vals);
454 }
455 
456 /**
457  * iio_str_to_fixpoint() - Parse a fixed-point number from a string
458  * @str: The string to parse
459  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
460  * @integer: The integer part of the number
461  * @fract: The fractional part of the number
462  *
463  * Returns 0 on success, or a negative error code if the string could not be
464  * parsed.
465  */
466 int iio_str_to_fixpoint(const char *str, int fract_mult,
467 	int *integer, int *fract)
468 {
469 	int i = 0, f = 0;
470 	bool integer_part = true, negative = false;
471 
472 	if (str[0] == '-') {
473 		negative = true;
474 		str++;
475 	} else if (str[0] == '+') {
476 		str++;
477 	}
478 
479 	while (*str) {
480 		if ('0' <= *str && *str <= '9') {
481 			if (integer_part) {
482 				i = i * 10 + *str - '0';
483 			} else {
484 				f += fract_mult * (*str - '0');
485 				fract_mult /= 10;
486 			}
487 		} else if (*str == '\n') {
488 			if (*(str + 1) == '\0')
489 				break;
490 			else
491 				return -EINVAL;
492 		} else if (*str == '.' && integer_part) {
493 			integer_part = false;
494 		} else {
495 			return -EINVAL;
496 		}
497 		str++;
498 	}
499 
500 	if (negative) {
501 		if (i)
502 			i = -i;
503 		else
504 			f = -f;
505 	}
506 
507 	*integer = i;
508 	*fract = f;
509 
510 	return 0;
511 }
512 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
513 
514 static ssize_t iio_write_channel_info(struct device *dev,
515 				      struct device_attribute *attr,
516 				      const char *buf,
517 				      size_t len)
518 {
519 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
520 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
521 	int ret, fract_mult = 100000;
522 	int integer, fract;
523 
524 	/* Assumes decimal - precision based on number of digits */
525 	if (!indio_dev->info->write_raw)
526 		return -EINVAL;
527 
528 	if (indio_dev->info->write_raw_get_fmt)
529 		switch (indio_dev->info->write_raw_get_fmt(indio_dev,
530 			this_attr->c, this_attr->address)) {
531 		case IIO_VAL_INT_PLUS_MICRO:
532 			fract_mult = 100000;
533 			break;
534 		case IIO_VAL_INT_PLUS_NANO:
535 			fract_mult = 100000000;
536 			break;
537 		default:
538 			return -EINVAL;
539 		}
540 
541 	ret = iio_str_to_fixpoint(buf, fract_mult, &integer, &fract);
542 	if (ret)
543 		return ret;
544 
545 	ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
546 					 integer, fract, this_attr->address);
547 	if (ret)
548 		return ret;
549 
550 	return len;
551 }
552 
553 static
554 int __iio_device_attr_init(struct device_attribute *dev_attr,
555 			   const char *postfix,
556 			   struct iio_chan_spec const *chan,
557 			   ssize_t (*readfunc)(struct device *dev,
558 					       struct device_attribute *attr,
559 					       char *buf),
560 			   ssize_t (*writefunc)(struct device *dev,
561 						struct device_attribute *attr,
562 						const char *buf,
563 						size_t len),
564 			   enum iio_shared_by shared_by)
565 {
566 	int ret = 0;
567 	char *name = NULL;
568 	char *full_postfix;
569 	sysfs_attr_init(&dev_attr->attr);
570 
571 	/* Build up postfix of <extend_name>_<modifier>_postfix */
572 	if (chan->modified && (shared_by == IIO_SEPARATE)) {
573 		if (chan->extend_name)
574 			full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
575 						 iio_modifier_names[chan
576 								    ->channel2],
577 						 chan->extend_name,
578 						 postfix);
579 		else
580 			full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
581 						 iio_modifier_names[chan
582 								    ->channel2],
583 						 postfix);
584 	} else {
585 		if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
586 			full_postfix = kstrdup(postfix, GFP_KERNEL);
587 		else
588 			full_postfix = kasprintf(GFP_KERNEL,
589 						 "%s_%s",
590 						 chan->extend_name,
591 						 postfix);
592 	}
593 	if (full_postfix == NULL)
594 		return -ENOMEM;
595 
596 	if (chan->differential) { /* Differential can not have modifier */
597 		switch (shared_by) {
598 		case IIO_SHARED_BY_ALL:
599 			name = kasprintf(GFP_KERNEL, "%s", full_postfix);
600 			break;
601 		case IIO_SHARED_BY_DIR:
602 			name = kasprintf(GFP_KERNEL, "%s_%s",
603 						iio_direction[chan->output],
604 						full_postfix);
605 			break;
606 		case IIO_SHARED_BY_TYPE:
607 			name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
608 					    iio_direction[chan->output],
609 					    iio_chan_type_name_spec[chan->type],
610 					    iio_chan_type_name_spec[chan->type],
611 					    full_postfix);
612 			break;
613 		case IIO_SEPARATE:
614 			if (!chan->indexed) {
615 				WARN_ON("Differential channels must be indexed\n");
616 				ret = -EINVAL;
617 				goto error_free_full_postfix;
618 			}
619 			name = kasprintf(GFP_KERNEL,
620 					    "%s_%s%d-%s%d_%s",
621 					    iio_direction[chan->output],
622 					    iio_chan_type_name_spec[chan->type],
623 					    chan->channel,
624 					    iio_chan_type_name_spec[chan->type],
625 					    chan->channel2,
626 					    full_postfix);
627 			break;
628 		}
629 	} else { /* Single ended */
630 		switch (shared_by) {
631 		case IIO_SHARED_BY_ALL:
632 			name = kasprintf(GFP_KERNEL, "%s", full_postfix);
633 			break;
634 		case IIO_SHARED_BY_DIR:
635 			name = kasprintf(GFP_KERNEL, "%s_%s",
636 						iio_direction[chan->output],
637 						full_postfix);
638 			break;
639 		case IIO_SHARED_BY_TYPE:
640 			name = kasprintf(GFP_KERNEL, "%s_%s_%s",
641 					    iio_direction[chan->output],
642 					    iio_chan_type_name_spec[chan->type],
643 					    full_postfix);
644 			break;
645 
646 		case IIO_SEPARATE:
647 			if (chan->indexed)
648 				name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
649 						    iio_direction[chan->output],
650 						    iio_chan_type_name_spec[chan->type],
651 						    chan->channel,
652 						    full_postfix);
653 			else
654 				name = kasprintf(GFP_KERNEL, "%s_%s_%s",
655 						    iio_direction[chan->output],
656 						    iio_chan_type_name_spec[chan->type],
657 						    full_postfix);
658 			break;
659 		}
660 	}
661 	if (name == NULL) {
662 		ret = -ENOMEM;
663 		goto error_free_full_postfix;
664 	}
665 	dev_attr->attr.name = name;
666 
667 	if (readfunc) {
668 		dev_attr->attr.mode |= S_IRUGO;
669 		dev_attr->show = readfunc;
670 	}
671 
672 	if (writefunc) {
673 		dev_attr->attr.mode |= S_IWUSR;
674 		dev_attr->store = writefunc;
675 	}
676 
677 error_free_full_postfix:
678 	kfree(full_postfix);
679 
680 	return ret;
681 }
682 
683 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
684 {
685 	kfree(dev_attr->attr.name);
686 }
687 
688 int __iio_add_chan_devattr(const char *postfix,
689 			   struct iio_chan_spec const *chan,
690 			   ssize_t (*readfunc)(struct device *dev,
691 					       struct device_attribute *attr,
692 					       char *buf),
693 			   ssize_t (*writefunc)(struct device *dev,
694 						struct device_attribute *attr,
695 						const char *buf,
696 						size_t len),
697 			   u64 mask,
698 			   enum iio_shared_by shared_by,
699 			   struct device *dev,
700 			   struct list_head *attr_list)
701 {
702 	int ret;
703 	struct iio_dev_attr *iio_attr, *t;
704 
705 	iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
706 	if (iio_attr == NULL)
707 		return -ENOMEM;
708 	ret = __iio_device_attr_init(&iio_attr->dev_attr,
709 				     postfix, chan,
710 				     readfunc, writefunc, shared_by);
711 	if (ret)
712 		goto error_iio_dev_attr_free;
713 	iio_attr->c = chan;
714 	iio_attr->address = mask;
715 	list_for_each_entry(t, attr_list, l)
716 		if (strcmp(t->dev_attr.attr.name,
717 			   iio_attr->dev_attr.attr.name) == 0) {
718 			if (shared_by == IIO_SEPARATE)
719 				dev_err(dev, "tried to double register : %s\n",
720 					t->dev_attr.attr.name);
721 			ret = -EBUSY;
722 			goto error_device_attr_deinit;
723 		}
724 	list_add(&iio_attr->l, attr_list);
725 
726 	return 0;
727 
728 error_device_attr_deinit:
729 	__iio_device_attr_deinit(&iio_attr->dev_attr);
730 error_iio_dev_attr_free:
731 	kfree(iio_attr);
732 	return ret;
733 }
734 
735 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
736 					 struct iio_chan_spec const *chan,
737 					 enum iio_shared_by shared_by,
738 					 const long *infomask)
739 {
740 	int i, ret, attrcount = 0;
741 
742 	for_each_set_bit(i, infomask, sizeof(infomask)*8) {
743 		if (i >= ARRAY_SIZE(iio_chan_info_postfix))
744 			return -EINVAL;
745 		ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
746 					     chan,
747 					     &iio_read_channel_info,
748 					     &iio_write_channel_info,
749 					     i,
750 					     shared_by,
751 					     &indio_dev->dev,
752 					     &indio_dev->channel_attr_list);
753 		if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
754 			continue;
755 		else if (ret < 0)
756 			return ret;
757 		attrcount++;
758 	}
759 
760 	return attrcount;
761 }
762 
763 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
764 					struct iio_chan_spec const *chan)
765 {
766 	int ret, attrcount = 0;
767 	const struct iio_chan_spec_ext_info *ext_info;
768 
769 	if (chan->channel < 0)
770 		return 0;
771 	ret = iio_device_add_info_mask_type(indio_dev, chan,
772 					    IIO_SEPARATE,
773 					    &chan->info_mask_separate);
774 	if (ret < 0)
775 		return ret;
776 	attrcount += ret;
777 
778 	ret = iio_device_add_info_mask_type(indio_dev, chan,
779 					    IIO_SHARED_BY_TYPE,
780 					    &chan->info_mask_shared_by_type);
781 	if (ret < 0)
782 		return ret;
783 	attrcount += ret;
784 
785 	ret = iio_device_add_info_mask_type(indio_dev, chan,
786 					    IIO_SHARED_BY_DIR,
787 					    &chan->info_mask_shared_by_dir);
788 	if (ret < 0)
789 		return ret;
790 	attrcount += ret;
791 
792 	ret = iio_device_add_info_mask_type(indio_dev, chan,
793 					    IIO_SHARED_BY_ALL,
794 					    &chan->info_mask_shared_by_all);
795 	if (ret < 0)
796 		return ret;
797 	attrcount += ret;
798 
799 	if (chan->ext_info) {
800 		unsigned int i = 0;
801 		for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
802 			ret = __iio_add_chan_devattr(ext_info->name,
803 					chan,
804 					ext_info->read ?
805 					    &iio_read_channel_ext_info : NULL,
806 					ext_info->write ?
807 					    &iio_write_channel_ext_info : NULL,
808 					i,
809 					ext_info->shared,
810 					&indio_dev->dev,
811 					&indio_dev->channel_attr_list);
812 			i++;
813 			if (ret == -EBUSY && ext_info->shared)
814 				continue;
815 
816 			if (ret)
817 				return ret;
818 
819 			attrcount++;
820 		}
821 	}
822 
823 	return attrcount;
824 }
825 
826 /**
827  * iio_free_chan_devattr_list() - Free a list of IIO device attributes
828  * @attr_list: List of IIO device attributes
829  *
830  * This function frees the memory allocated for each of the IIO device
831  * attributes in the list. Note: if you want to reuse the list after calling
832  * this function you have to reinitialize it using INIT_LIST_HEAD().
833  */
834 void iio_free_chan_devattr_list(struct list_head *attr_list)
835 {
836 	struct iio_dev_attr *p, *n;
837 
838 	list_for_each_entry_safe(p, n, attr_list, l) {
839 		kfree(p->dev_attr.attr.name);
840 		kfree(p);
841 	}
842 }
843 
844 static ssize_t iio_show_dev_name(struct device *dev,
845 				 struct device_attribute *attr,
846 				 char *buf)
847 {
848 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
849 	return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->name);
850 }
851 
852 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
853 
854 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
855 {
856 	int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
857 	struct iio_dev_attr *p;
858 	struct attribute **attr;
859 
860 	/* First count elements in any existing group */
861 	if (indio_dev->info->attrs) {
862 		attr = indio_dev->info->attrs->attrs;
863 		while (*attr++ != NULL)
864 			attrcount_orig++;
865 	}
866 	attrcount = attrcount_orig;
867 	/*
868 	 * New channel registration method - relies on the fact a group does
869 	 * not need to be initialized if its name is NULL.
870 	 */
871 	if (indio_dev->channels)
872 		for (i = 0; i < indio_dev->num_channels; i++) {
873 			ret = iio_device_add_channel_sysfs(indio_dev,
874 							   &indio_dev
875 							   ->channels[i]);
876 			if (ret < 0)
877 				goto error_clear_attrs;
878 			attrcount += ret;
879 		}
880 
881 	if (indio_dev->name)
882 		attrcount++;
883 
884 	indio_dev->chan_attr_group.attrs = kcalloc(attrcount + 1,
885 						   sizeof(indio_dev->chan_attr_group.attrs[0]),
886 						   GFP_KERNEL);
887 	if (indio_dev->chan_attr_group.attrs == NULL) {
888 		ret = -ENOMEM;
889 		goto error_clear_attrs;
890 	}
891 	/* Copy across original attributes */
892 	if (indio_dev->info->attrs)
893 		memcpy(indio_dev->chan_attr_group.attrs,
894 		       indio_dev->info->attrs->attrs,
895 		       sizeof(indio_dev->chan_attr_group.attrs[0])
896 		       *attrcount_orig);
897 	attrn = attrcount_orig;
898 	/* Add all elements from the list. */
899 	list_for_each_entry(p, &indio_dev->channel_attr_list, l)
900 		indio_dev->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
901 	if (indio_dev->name)
902 		indio_dev->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
903 
904 	indio_dev->groups[indio_dev->groupcounter++] =
905 		&indio_dev->chan_attr_group;
906 
907 	return 0;
908 
909 error_clear_attrs:
910 	iio_free_chan_devattr_list(&indio_dev->channel_attr_list);
911 
912 	return ret;
913 }
914 
915 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
916 {
917 
918 	iio_free_chan_devattr_list(&indio_dev->channel_attr_list);
919 	kfree(indio_dev->chan_attr_group.attrs);
920 }
921 
922 static void iio_dev_release(struct device *device)
923 {
924 	struct iio_dev *indio_dev = dev_to_iio_dev(device);
925 	if (indio_dev->modes & INDIO_BUFFER_TRIGGERED)
926 		iio_device_unregister_trigger_consumer(indio_dev);
927 	iio_device_unregister_eventset(indio_dev);
928 	iio_device_unregister_sysfs(indio_dev);
929 
930 	iio_buffer_put(indio_dev->buffer);
931 
932 	ida_simple_remove(&iio_ida, indio_dev->id);
933 	kfree(indio_dev);
934 }
935 
936 struct device_type iio_device_type = {
937 	.name = "iio_device",
938 	.release = iio_dev_release,
939 };
940 
941 /**
942  * iio_device_alloc() - allocate an iio_dev from a driver
943  * @sizeof_priv:	Space to allocate for private structure.
944  **/
945 struct iio_dev *iio_device_alloc(int sizeof_priv)
946 {
947 	struct iio_dev *dev;
948 	size_t alloc_size;
949 
950 	alloc_size = sizeof(struct iio_dev);
951 	if (sizeof_priv) {
952 		alloc_size = ALIGN(alloc_size, IIO_ALIGN);
953 		alloc_size += sizeof_priv;
954 	}
955 	/* ensure 32-byte alignment of whole construct ? */
956 	alloc_size += IIO_ALIGN - 1;
957 
958 	dev = kzalloc(alloc_size, GFP_KERNEL);
959 
960 	if (dev) {
961 		dev->dev.groups = dev->groups;
962 		dev->dev.type = &iio_device_type;
963 		dev->dev.bus = &iio_bus_type;
964 		device_initialize(&dev->dev);
965 		dev_set_drvdata(&dev->dev, (void *)dev);
966 		mutex_init(&dev->mlock);
967 		mutex_init(&dev->info_exist_lock);
968 		INIT_LIST_HEAD(&dev->channel_attr_list);
969 
970 		dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
971 		if (dev->id < 0) {
972 			/* cannot use a dev_err as the name isn't available */
973 			pr_err("failed to get device id\n");
974 			kfree(dev);
975 			return NULL;
976 		}
977 		dev_set_name(&dev->dev, "iio:device%d", dev->id);
978 		INIT_LIST_HEAD(&dev->buffer_list);
979 	}
980 
981 	return dev;
982 }
983 EXPORT_SYMBOL(iio_device_alloc);
984 
985 /**
986  * iio_device_free() - free an iio_dev from a driver
987  * @dev:		the iio_dev associated with the device
988  **/
989 void iio_device_free(struct iio_dev *dev)
990 {
991 	if (dev)
992 		put_device(&dev->dev);
993 }
994 EXPORT_SYMBOL(iio_device_free);
995 
996 static void devm_iio_device_release(struct device *dev, void *res)
997 {
998 	iio_device_free(*(struct iio_dev **)res);
999 }
1000 
1001 static int devm_iio_device_match(struct device *dev, void *res, void *data)
1002 {
1003 	struct iio_dev **r = res;
1004 	if (!r || !*r) {
1005 		WARN_ON(!r || !*r);
1006 		return 0;
1007 	}
1008 	return *r == data;
1009 }
1010 
1011 /**
1012  * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1013  * @dev:		Device to allocate iio_dev for
1014  * @sizeof_priv:	Space to allocate for private structure.
1015  *
1016  * Managed iio_device_alloc. iio_dev allocated with this function is
1017  * automatically freed on driver detach.
1018  *
1019  * If an iio_dev allocated with this function needs to be freed separately,
1020  * devm_iio_device_free() must be used.
1021  *
1022  * RETURNS:
1023  * Pointer to allocated iio_dev on success, NULL on failure.
1024  */
1025 struct iio_dev *devm_iio_device_alloc(struct device *dev, int sizeof_priv)
1026 {
1027 	struct iio_dev **ptr, *iio_dev;
1028 
1029 	ptr = devres_alloc(devm_iio_device_release, sizeof(*ptr),
1030 			   GFP_KERNEL);
1031 	if (!ptr)
1032 		return NULL;
1033 
1034 	/* use raw alloc_dr for kmalloc caller tracing */
1035 	iio_dev = iio_device_alloc(sizeof_priv);
1036 	if (iio_dev) {
1037 		*ptr = iio_dev;
1038 		devres_add(dev, ptr);
1039 	} else {
1040 		devres_free(ptr);
1041 	}
1042 
1043 	return iio_dev;
1044 }
1045 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1046 
1047 /**
1048  * devm_iio_device_free - Resource-managed iio_device_free()
1049  * @dev:		Device this iio_dev belongs to
1050  * @iio_dev:		the iio_dev associated with the device
1051  *
1052  * Free iio_dev allocated with devm_iio_device_alloc().
1053  */
1054 void devm_iio_device_free(struct device *dev, struct iio_dev *iio_dev)
1055 {
1056 	int rc;
1057 
1058 	rc = devres_release(dev, devm_iio_device_release,
1059 			    devm_iio_device_match, iio_dev);
1060 	WARN_ON(rc);
1061 }
1062 EXPORT_SYMBOL_GPL(devm_iio_device_free);
1063 
1064 /**
1065  * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1066  **/
1067 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1068 {
1069 	struct iio_dev *indio_dev = container_of(inode->i_cdev,
1070 						struct iio_dev, chrdev);
1071 
1072 	if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
1073 		return -EBUSY;
1074 
1075 	iio_device_get(indio_dev);
1076 
1077 	filp->private_data = indio_dev;
1078 
1079 	return 0;
1080 }
1081 
1082 /**
1083  * iio_chrdev_release() - chrdev file close buffer access and ioctls
1084  **/
1085 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1086 {
1087 	struct iio_dev *indio_dev = container_of(inode->i_cdev,
1088 						struct iio_dev, chrdev);
1089 	clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
1090 	iio_device_put(indio_dev);
1091 
1092 	return 0;
1093 }
1094 
1095 /* Somewhat of a cross file organization violation - ioctls here are actually
1096  * event related */
1097 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1098 {
1099 	struct iio_dev *indio_dev = filp->private_data;
1100 	int __user *ip = (int __user *)arg;
1101 	int fd;
1102 
1103 	if (!indio_dev->info)
1104 		return -ENODEV;
1105 
1106 	if (cmd == IIO_GET_EVENT_FD_IOCTL) {
1107 		fd = iio_event_getfd(indio_dev);
1108 		if (copy_to_user(ip, &fd, sizeof(fd)))
1109 			return -EFAULT;
1110 		return 0;
1111 	}
1112 	return -EINVAL;
1113 }
1114 
1115 static const struct file_operations iio_buffer_fileops = {
1116 	.read = iio_buffer_read_first_n_outer_addr,
1117 	.release = iio_chrdev_release,
1118 	.open = iio_chrdev_open,
1119 	.poll = iio_buffer_poll_addr,
1120 	.owner = THIS_MODULE,
1121 	.llseek = noop_llseek,
1122 	.unlocked_ioctl = iio_ioctl,
1123 	.compat_ioctl = iio_ioctl,
1124 };
1125 
1126 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1127 
1128 /**
1129  * iio_device_register() - register a device with the IIO subsystem
1130  * @indio_dev:		Device structure filled by the device driver
1131  **/
1132 int iio_device_register(struct iio_dev *indio_dev)
1133 {
1134 	int ret;
1135 
1136 	/* If the calling driver did not initialize of_node, do it here */
1137 	if (!indio_dev->dev.of_node && indio_dev->dev.parent)
1138 		indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
1139 
1140 	/* configure elements for the chrdev */
1141 	indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
1142 
1143 	ret = iio_device_register_debugfs(indio_dev);
1144 	if (ret) {
1145 		dev_err(indio_dev->dev.parent,
1146 			"Failed to register debugfs interfaces\n");
1147 		return ret;
1148 	}
1149 	ret = iio_device_register_sysfs(indio_dev);
1150 	if (ret) {
1151 		dev_err(indio_dev->dev.parent,
1152 			"Failed to register sysfs interfaces\n");
1153 		goto error_unreg_debugfs;
1154 	}
1155 	ret = iio_device_register_eventset(indio_dev);
1156 	if (ret) {
1157 		dev_err(indio_dev->dev.parent,
1158 			"Failed to register event set\n");
1159 		goto error_free_sysfs;
1160 	}
1161 	if (indio_dev->modes & INDIO_BUFFER_TRIGGERED)
1162 		iio_device_register_trigger_consumer(indio_dev);
1163 
1164 	if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1165 		indio_dev->setup_ops == NULL)
1166 		indio_dev->setup_ops = &noop_ring_setup_ops;
1167 
1168 	cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
1169 	indio_dev->chrdev.owner = indio_dev->info->driver_module;
1170 	indio_dev->chrdev.kobj.parent = &indio_dev->dev.kobj;
1171 	ret = cdev_add(&indio_dev->chrdev, indio_dev->dev.devt, 1);
1172 	if (ret < 0)
1173 		goto error_unreg_eventset;
1174 
1175 	ret = device_add(&indio_dev->dev);
1176 	if (ret < 0)
1177 		goto error_cdev_del;
1178 
1179 	return 0;
1180 error_cdev_del:
1181 	cdev_del(&indio_dev->chrdev);
1182 error_unreg_eventset:
1183 	iio_device_unregister_eventset(indio_dev);
1184 error_free_sysfs:
1185 	iio_device_unregister_sysfs(indio_dev);
1186 error_unreg_debugfs:
1187 	iio_device_unregister_debugfs(indio_dev);
1188 	return ret;
1189 }
1190 EXPORT_SYMBOL(iio_device_register);
1191 
1192 /**
1193  * iio_device_unregister() - unregister a device from the IIO subsystem
1194  * @indio_dev:		Device structure representing the device.
1195  **/
1196 void iio_device_unregister(struct iio_dev *indio_dev)
1197 {
1198 	mutex_lock(&indio_dev->info_exist_lock);
1199 
1200 	device_del(&indio_dev->dev);
1201 
1202 	if (indio_dev->chrdev.dev)
1203 		cdev_del(&indio_dev->chrdev);
1204 	iio_device_unregister_debugfs(indio_dev);
1205 
1206 	iio_disable_all_buffers(indio_dev);
1207 
1208 	indio_dev->info = NULL;
1209 
1210 	iio_device_wakeup_eventset(indio_dev);
1211 	iio_buffer_wakeup_poll(indio_dev);
1212 
1213 	mutex_unlock(&indio_dev->info_exist_lock);
1214 }
1215 EXPORT_SYMBOL(iio_device_unregister);
1216 
1217 static void devm_iio_device_unreg(struct device *dev, void *res)
1218 {
1219 	iio_device_unregister(*(struct iio_dev **)res);
1220 }
1221 
1222 /**
1223  * devm_iio_device_register - Resource-managed iio_device_register()
1224  * @dev:	Device to allocate iio_dev for
1225  * @indio_dev:	Device structure filled by the device driver
1226  *
1227  * Managed iio_device_register.  The IIO device registered with this
1228  * function is automatically unregistered on driver detach. This function
1229  * calls iio_device_register() internally. Refer to that function for more
1230  * information.
1231  *
1232  * If an iio_dev registered with this function needs to be unregistered
1233  * separately, devm_iio_device_unregister() must be used.
1234  *
1235  * RETURNS:
1236  * 0 on success, negative error number on failure.
1237  */
1238 int devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev)
1239 {
1240 	struct iio_dev **ptr;
1241 	int ret;
1242 
1243 	ptr = devres_alloc(devm_iio_device_unreg, sizeof(*ptr), GFP_KERNEL);
1244 	if (!ptr)
1245 		return -ENOMEM;
1246 
1247 	*ptr = indio_dev;
1248 	ret = iio_device_register(indio_dev);
1249 	if (!ret)
1250 		devres_add(dev, ptr);
1251 	else
1252 		devres_free(ptr);
1253 
1254 	return ret;
1255 }
1256 EXPORT_SYMBOL_GPL(devm_iio_device_register);
1257 
1258 /**
1259  * devm_iio_device_unregister - Resource-managed iio_device_unregister()
1260  * @dev:	Device this iio_dev belongs to
1261  * @indio_dev:	the iio_dev associated with the device
1262  *
1263  * Unregister iio_dev registered with devm_iio_device_register().
1264  */
1265 void devm_iio_device_unregister(struct device *dev, struct iio_dev *indio_dev)
1266 {
1267 	int rc;
1268 
1269 	rc = devres_release(dev, devm_iio_device_unreg,
1270 			    devm_iio_device_match, indio_dev);
1271 	WARN_ON(rc);
1272 }
1273 EXPORT_SYMBOL_GPL(devm_iio_device_unregister);
1274 
1275 subsys_initcall(iio_init);
1276 module_exit(iio_exit);
1277 
1278 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1279 MODULE_DESCRIPTION("Industrial I/O core");
1280 MODULE_LICENSE("GPL");
1281