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