1// SPDX-License-Identifier: GPL-2.0-only
2//
3// GPIO Aggregator
4//
5// Copyright (C) 2019-2020 Glider bv
6
7#define DRV_NAME       "gpio-aggregator"
8#define pr_fmt(fmt)	DRV_NAME ": " fmt
9
10#include <linux/bitmap.h>
11#include <linux/bitops.h>
12#include <linux/ctype.h>
13#include <linux/gpio.h>
14#include <linux/gpio/consumer.h>
15#include <linux/gpio/driver.h>
16#include <linux/gpio/machine.h>
17#include <linux/idr.h>
18#include <linux/kernel.h>
19#include <linux/module.h>
20#include <linux/mutex.h>
21#include <linux/overflow.h>
22#include <linux/platform_device.h>
23#include <linux/spinlock.h>
24#include <linux/string.h>
25
26
27/*
28 * GPIO Aggregator sysfs interface
29 */
30
31struct gpio_aggregator {
32	struct gpiod_lookup_table *lookups;
33	struct platform_device *pdev;
34	char args[];
35};
36
37static DEFINE_MUTEX(gpio_aggregator_lock);	/* protects idr */
38static DEFINE_IDR(gpio_aggregator_idr);
39
40static char *get_arg(char **args)
41{
42	char *start, *end;
43
44	start = skip_spaces(*args);
45	if (!*start)
46		return NULL;
47
48	if (*start == '"') {
49		/* Quoted arg */
50		end = strchr(++start, '"');
51		if (!end)
52			return ERR_PTR(-EINVAL);
53	} else {
54		/* Unquoted arg */
55		for (end = start; *end && !isspace(*end); end++) ;
56	}
57
58	if (*end)
59		*end++ = '\0';
60
61	*args = end;
62	return start;
63}
64
65static bool isrange(const char *s)
66{
67	size_t n;
68
69	if (IS_ERR_OR_NULL(s))
70		return false;
71
72	while (1) {
73		n = strspn(s, "0123456789");
74		if (!n)
75			return false;
76
77		s += n;
78
79		switch (*s++) {
80		case '\0':
81			return true;
82
83		case '-':
84		case ',':
85			break;
86
87		default:
88			return false;
89		}
90	}
91}
92
93static int aggr_add_gpio(struct gpio_aggregator *aggr, const char *key,
94			 int hwnum, unsigned int *n)
95{
96	struct gpiod_lookup_table *lookups;
97
98	lookups = krealloc(aggr->lookups, struct_size(lookups, table, *n + 2),
99			   GFP_KERNEL);
100	if (!lookups)
101		return -ENOMEM;
102
103	lookups->table[*n] =
104		(struct gpiod_lookup)GPIO_LOOKUP_IDX(key, hwnum, NULL, *n, 0);
105
106	(*n)++;
107	memset(&lookups->table[*n], 0, sizeof(lookups->table[*n]));
108
109	aggr->lookups = lookups;
110	return 0;
111}
112
113static int aggr_parse(struct gpio_aggregator *aggr)
114{
115	char *args = aggr->args;
116	unsigned long *bitmap;
117	unsigned int i, n = 0;
118	char *name, *offsets;
119	int error = 0;
120
121	bitmap = bitmap_alloc(ARCH_NR_GPIOS, GFP_KERNEL);
122	if (!bitmap)
123		return -ENOMEM;
124
125	for (name = get_arg(&args), offsets = get_arg(&args); name;
126	     offsets = get_arg(&args)) {
127		if (IS_ERR(name)) {
128			pr_err("Cannot get GPIO specifier: %pe\n", name);
129			error = PTR_ERR(name);
130			goto free_bitmap;
131		}
132
133		if (!isrange(offsets)) {
134			/* Named GPIO line */
135			error = aggr_add_gpio(aggr, name, U16_MAX, &n);
136			if (error)
137				goto free_bitmap;
138
139			name = offsets;
140			continue;
141		}
142
143		/* GPIO chip + offset(s) */
144		error = bitmap_parselist(offsets, bitmap, ARCH_NR_GPIOS);
145		if (error) {
146			pr_err("Cannot parse %s: %d\n", offsets, error);
147			goto free_bitmap;
148		}
149
150		for_each_set_bit(i, bitmap, ARCH_NR_GPIOS) {
151			error = aggr_add_gpio(aggr, name, i, &n);
152			if (error)
153				goto free_bitmap;
154		}
155
156		name = get_arg(&args);
157	}
158
159	if (!n) {
160		pr_err("No GPIOs specified\n");
161		error = -EINVAL;
162	}
163
164free_bitmap:
165	bitmap_free(bitmap);
166	return error;
167}
168
169static ssize_t new_device_store(struct device_driver *driver, const char *buf,
170				size_t count)
171{
172	struct gpio_aggregator *aggr;
173	struct platform_device *pdev;
174	int res, id;
175
176	/* kernfs guarantees string termination, so count + 1 is safe */
177	aggr = kzalloc(sizeof(*aggr) + count + 1, GFP_KERNEL);
178	if (!aggr)
179		return -ENOMEM;
180
181	memcpy(aggr->args, buf, count + 1);
182
183	aggr->lookups = kzalloc(struct_size(aggr->lookups, table, 1),
184				GFP_KERNEL);
185	if (!aggr->lookups) {
186		res = -ENOMEM;
187		goto free_ga;
188	}
189
190	mutex_lock(&gpio_aggregator_lock);
191	id = idr_alloc(&gpio_aggregator_idr, aggr, 0, 0, GFP_KERNEL);
192	mutex_unlock(&gpio_aggregator_lock);
193
194	if (id < 0) {
195		res = id;
196		goto free_table;
197	}
198
199	aggr->lookups->dev_id = kasprintf(GFP_KERNEL, "%s.%d", DRV_NAME, id);
200	if (!aggr->lookups->dev_id) {
201		res = -ENOMEM;
202		goto remove_idr;
203	}
204
205	res = aggr_parse(aggr);
206	if (res)
207		goto free_dev_id;
208
209	gpiod_add_lookup_table(aggr->lookups);
210
211	pdev = platform_device_register_simple(DRV_NAME, id, NULL, 0);
212	if (IS_ERR(pdev)) {
213		res = PTR_ERR(pdev);
214		goto remove_table;
215	}
216
217	aggr->pdev = pdev;
218	return count;
219
220remove_table:
221	gpiod_remove_lookup_table(aggr->lookups);
222free_dev_id:
223	kfree(aggr->lookups->dev_id);
224remove_idr:
225	mutex_lock(&gpio_aggregator_lock);
226	idr_remove(&gpio_aggregator_idr, id);
227	mutex_unlock(&gpio_aggregator_lock);
228free_table:
229	kfree(aggr->lookups);
230free_ga:
231	kfree(aggr);
232	return res;
233}
234
235static DRIVER_ATTR_WO(new_device);
236
237static void gpio_aggregator_free(struct gpio_aggregator *aggr)
238{
239	platform_device_unregister(aggr->pdev);
240	gpiod_remove_lookup_table(aggr->lookups);
241	kfree(aggr->lookups->dev_id);
242	kfree(aggr->lookups);
243	kfree(aggr);
244}
245
246static ssize_t delete_device_store(struct device_driver *driver,
247				   const char *buf, size_t count)
248{
249	struct gpio_aggregator *aggr;
250	unsigned int id;
251	int error;
252
253	if (!str_has_prefix(buf, DRV_NAME "."))
254		return -EINVAL;
255
256	error = kstrtouint(buf + strlen(DRV_NAME "."), 10, &id);
257	if (error)
258		return error;
259
260	mutex_lock(&gpio_aggregator_lock);
261	aggr = idr_remove(&gpio_aggregator_idr, id);
262	mutex_unlock(&gpio_aggregator_lock);
263	if (!aggr)
264		return -ENOENT;
265
266	gpio_aggregator_free(aggr);
267	return count;
268}
269static DRIVER_ATTR_WO(delete_device);
270
271static struct attribute *gpio_aggregator_attrs[] = {
272	&driver_attr_new_device.attr,
273	&driver_attr_delete_device.attr,
274	NULL,
275};
276ATTRIBUTE_GROUPS(gpio_aggregator);
277
278static int __exit gpio_aggregator_idr_remove(int id, void *p, void *data)
279{
280	gpio_aggregator_free(p);
281	return 0;
282}
283
284static void __exit gpio_aggregator_remove_all(void)
285{
286	mutex_lock(&gpio_aggregator_lock);
287	idr_for_each(&gpio_aggregator_idr, gpio_aggregator_idr_remove, NULL);
288	idr_destroy(&gpio_aggregator_idr);
289	mutex_unlock(&gpio_aggregator_lock);
290}
291
292
293/*
294 *  GPIO Forwarder
295 */
296
297struct gpiochip_fwd {
298	struct gpio_chip chip;
299	struct gpio_desc **descs;
300	union {
301		struct mutex mlock;	/* protects tmp[] if can_sleep */
302		spinlock_t slock;	/* protects tmp[] if !can_sleep */
303	};
304	unsigned long tmp[];		/* values and descs for multiple ops */
305};
306
307static int gpio_fwd_get_direction(struct gpio_chip *chip, unsigned int offset)
308{
309	struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
310
311	return gpiod_get_direction(fwd->descs[offset]);
312}
313
314static int gpio_fwd_direction_input(struct gpio_chip *chip, unsigned int offset)
315{
316	struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
317
318	return gpiod_direction_input(fwd->descs[offset]);
319}
320
321static int gpio_fwd_direction_output(struct gpio_chip *chip,
322				     unsigned int offset, int value)
323{
324	struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
325
326	return gpiod_direction_output(fwd->descs[offset], value);
327}
328
329static int gpio_fwd_get(struct gpio_chip *chip, unsigned int offset)
330{
331	struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
332
333	return chip->can_sleep ? gpiod_get_value_cansleep(fwd->descs[offset])
334			       : gpiod_get_value(fwd->descs[offset]);
335}
336
337static int gpio_fwd_get_multiple(struct gpiochip_fwd *fwd, unsigned long *mask,
338				 unsigned long *bits)
339{
340	struct gpio_desc **descs;
341	unsigned long *values;
342	unsigned int i, j = 0;
343	int error;
344
345	/* Both values bitmap and desc pointers are stored in tmp[] */
346	values = &fwd->tmp[0];
347	descs = (void *)&fwd->tmp[BITS_TO_LONGS(fwd->chip.ngpio)];
348
349	bitmap_clear(values, 0, fwd->chip.ngpio);
350	for_each_set_bit(i, mask, fwd->chip.ngpio)
351		descs[j++] = fwd->descs[i];
352
353	if (fwd->chip.can_sleep)
354		error = gpiod_get_array_value_cansleep(j, descs, NULL, values);
355	else
356		error = gpiod_get_array_value(j, descs, NULL, values);
357	if (error)
358		return error;
359
360	j = 0;
361	for_each_set_bit(i, mask, fwd->chip.ngpio)
362		__assign_bit(i, bits, test_bit(j++, values));
363
364	return 0;
365}
366
367static int gpio_fwd_get_multiple_locked(struct gpio_chip *chip,
368					unsigned long *mask, unsigned long *bits)
369{
370	struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
371	unsigned long flags;
372	int error;
373
374	if (chip->can_sleep) {
375		mutex_lock(&fwd->mlock);
376		error = gpio_fwd_get_multiple(fwd, mask, bits);
377		mutex_unlock(&fwd->mlock);
378	} else {
379		spin_lock_irqsave(&fwd->slock, flags);
380		error = gpio_fwd_get_multiple(fwd, mask, bits);
381		spin_unlock_irqrestore(&fwd->slock, flags);
382	}
383
384	return error;
385}
386
387static void gpio_fwd_set(struct gpio_chip *chip, unsigned int offset, int value)
388{
389	struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
390
391	if (chip->can_sleep)
392		gpiod_set_value_cansleep(fwd->descs[offset], value);
393	else
394		gpiod_set_value(fwd->descs[offset], value);
395}
396
397static void gpio_fwd_set_multiple(struct gpiochip_fwd *fwd, unsigned long *mask,
398				  unsigned long *bits)
399{
400	struct gpio_desc **descs;
401	unsigned long *values;
402	unsigned int i, j = 0;
403
404	/* Both values bitmap and desc pointers are stored in tmp[] */
405	values = &fwd->tmp[0];
406	descs = (void *)&fwd->tmp[BITS_TO_LONGS(fwd->chip.ngpio)];
407
408	for_each_set_bit(i, mask, fwd->chip.ngpio) {
409		__assign_bit(j, values, test_bit(i, bits));
410		descs[j++] = fwd->descs[i];
411	}
412
413	if (fwd->chip.can_sleep)
414		gpiod_set_array_value_cansleep(j, descs, NULL, values);
415	else
416		gpiod_set_array_value(j, descs, NULL, values);
417}
418
419static void gpio_fwd_set_multiple_locked(struct gpio_chip *chip,
420					 unsigned long *mask, unsigned long *bits)
421{
422	struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
423	unsigned long flags;
424
425	if (chip->can_sleep) {
426		mutex_lock(&fwd->mlock);
427		gpio_fwd_set_multiple(fwd, mask, bits);
428		mutex_unlock(&fwd->mlock);
429	} else {
430		spin_lock_irqsave(&fwd->slock, flags);
431		gpio_fwd_set_multiple(fwd, mask, bits);
432		spin_unlock_irqrestore(&fwd->slock, flags);
433	}
434}
435
436static int gpio_fwd_set_config(struct gpio_chip *chip, unsigned int offset,
437			       unsigned long config)
438{
439	struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
440
441	return gpiod_set_config(fwd->descs[offset], config);
442}
443
444/**
445 * gpiochip_fwd_create() - Create a new GPIO forwarder
446 * @dev: Parent device pointer
447 * @ngpios: Number of GPIOs in the forwarder.
448 * @descs: Array containing the GPIO descriptors to forward to.
449 *         This array must contain @ngpios entries, and must not be deallocated
450 *         before the forwarder has been destroyed again.
451 *
452 * This function creates a new gpiochip, which forwards all GPIO operations to
453 * the passed GPIO descriptors.
454 *
455 * Return: An opaque object pointer, or an ERR_PTR()-encoded negative error
456 *         code on failure.
457 */
458static struct gpiochip_fwd *gpiochip_fwd_create(struct device *dev,
459						unsigned int ngpios,
460						struct gpio_desc *descs[])
461{
462	const char *label = dev_name(dev);
463	struct gpiochip_fwd *fwd;
464	struct gpio_chip *chip;
465	unsigned int i;
466	int error;
467
468	fwd = devm_kzalloc(dev, struct_size(fwd, tmp,
469			   BITS_TO_LONGS(ngpios) + ngpios), GFP_KERNEL);
470	if (!fwd)
471		return ERR_PTR(-ENOMEM);
472
473	chip = &fwd->chip;
474
475	/*
476	 * If any of the GPIO lines are sleeping, then the entire forwarder
477	 * will be sleeping.
478	 * If any of the chips support .set_config(), then the forwarder will
479	 * support setting configs.
480	 */
481	for (i = 0; i < ngpios; i++) {
482		struct gpio_chip *parent = gpiod_to_chip(descs[i]);
483
484		dev_dbg(dev, "%u => gpio-%d\n", i, desc_to_gpio(descs[i]));
485
486		if (gpiod_cansleep(descs[i]))
487			chip->can_sleep = true;
488		if (parent && parent->set_config)
489			chip->set_config = gpio_fwd_set_config;
490	}
491
492	chip->label = label;
493	chip->parent = dev;
494	chip->owner = THIS_MODULE;
495	chip->get_direction = gpio_fwd_get_direction;
496	chip->direction_input = gpio_fwd_direction_input;
497	chip->direction_output = gpio_fwd_direction_output;
498	chip->get = gpio_fwd_get;
499	chip->get_multiple = gpio_fwd_get_multiple_locked;
500	chip->set = gpio_fwd_set;
501	chip->set_multiple = gpio_fwd_set_multiple_locked;
502	chip->base = -1;
503	chip->ngpio = ngpios;
504	fwd->descs = descs;
505
506	if (chip->can_sleep)
507		mutex_init(&fwd->mlock);
508	else
509		spin_lock_init(&fwd->slock);
510
511	error = devm_gpiochip_add_data(dev, chip, fwd);
512	if (error)
513		return ERR_PTR(error);
514
515	return fwd;
516}
517
518
519/*
520 *  GPIO Aggregator platform device
521 */
522
523static int gpio_aggregator_probe(struct platform_device *pdev)
524{
525	struct device *dev = &pdev->dev;
526	struct gpio_desc **descs;
527	struct gpiochip_fwd *fwd;
528	int i, n;
529
530	n = gpiod_count(dev, NULL);
531	if (n < 0)
532		return n;
533
534	descs = devm_kmalloc_array(dev, n, sizeof(*descs), GFP_KERNEL);
535	if (!descs)
536		return -ENOMEM;
537
538	for (i = 0; i < n; i++) {
539		descs[i] = devm_gpiod_get_index(dev, NULL, i, GPIOD_ASIS);
540		if (IS_ERR(descs[i]))
541			return PTR_ERR(descs[i]);
542	}
543
544	fwd = gpiochip_fwd_create(dev, n, descs);
545	if (IS_ERR(fwd))
546		return PTR_ERR(fwd);
547
548	platform_set_drvdata(pdev, fwd);
549	return 0;
550}
551
552#ifdef CONFIG_OF
553static const struct of_device_id gpio_aggregator_dt_ids[] = {
554	/*
555	 * Add GPIO-operated devices controlled from userspace below,
556	 * or use "driver_override" in sysfs
557	 */
558	{},
559};
560MODULE_DEVICE_TABLE(of, gpio_aggregator_dt_ids);
561#endif
562
563static struct platform_driver gpio_aggregator_driver = {
564	.probe = gpio_aggregator_probe,
565	.driver = {
566		.name = DRV_NAME,
567		.groups = gpio_aggregator_groups,
568		.of_match_table = of_match_ptr(gpio_aggregator_dt_ids),
569	},
570};
571
572static int __init gpio_aggregator_init(void)
573{
574	return platform_driver_register(&gpio_aggregator_driver);
575}
576module_init(gpio_aggregator_init);
577
578static void __exit gpio_aggregator_exit(void)
579{
580	gpio_aggregator_remove_all();
581	platform_driver_unregister(&gpio_aggregator_driver);
582}
583module_exit(gpio_aggregator_exit);
584
585MODULE_AUTHOR("Geert Uytterhoeven <geert+renesas@glider.be>");
586MODULE_DESCRIPTION("GPIO Aggregator");
587MODULE_LICENSE("GPL v2");
588