xref: /linux/drivers/gpio/gpiolib-shared.c (revision 509d3f45847627f4c5cdce004c3ec79262b5239c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2025 Linaro Ltd.
4  */
5 
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7 
8 #include <linux/auxiliary_bus.h>
9 #include <linux/cleanup.h>
10 #include <linux/device.h>
11 #include <linux/fwnode.h>
12 #include <linux/gpio/consumer.h>
13 #include <linux/gpio/machine.h>
14 #include <linux/idr.h>
15 #include <linux/kref.h>
16 #include <linux/list.h>
17 #include <linux/lockdep.h>
18 #include <linux/module.h>
19 #include <linux/mutex.h>
20 #include <linux/of.h>
21 #include <linux/overflow.h>
22 #include <linux/printk.h>
23 #include <linux/property.h>
24 #include <linux/slab.h>
25 #include <linux/string.h>
26 
27 #include "gpiolib.h"
28 #include "gpiolib-shared.h"
29 
30 /* Represents a single reference to a GPIO pin. */
31 struct gpio_shared_ref {
32 	struct list_head list;
33 	/* Firmware node associated with this GPIO's consumer. */
34 	struct fwnode_handle *fwnode;
35 	/* GPIO flags this consumer uses for the request. */
36 	enum gpiod_flags flags;
37 	char *con_id;
38 	int dev_id;
39 	struct auxiliary_device adev;
40 	struct gpiod_lookup_table *lookup;
41 };
42 
43 /* Represents a single GPIO pin. */
44 struct gpio_shared_entry {
45 	struct list_head list;
46 	/* Firmware node associated with the GPIO controller. */
47 	struct fwnode_handle *fwnode;
48 	/* Hardware offset of the GPIO within its chip. */
49 	unsigned int offset;
50 	/* Index in the property value array. */
51 	size_t index;
52 	struct mutex lock;
53 	struct gpio_shared_desc *shared_desc;
54 	struct kref ref;
55 	struct list_head refs;
56 };
57 
58 static LIST_HEAD(gpio_shared_list);
59 static DEFINE_MUTEX(gpio_shared_lock);
60 static DEFINE_IDA(gpio_shared_ida);
61 
62 #if IS_ENABLED(CONFIG_OF)
63 static struct gpio_shared_entry *
64 gpio_shared_find_entry(struct fwnode_handle *controller_node,
65 		       unsigned int offset)
66 {
67 	struct gpio_shared_entry *entry;
68 
69 	list_for_each_entry(entry, &gpio_shared_list, list) {
70 		if (entry->fwnode == controller_node && entry->offset == offset)
71 			return entry;
72 	}
73 
74 	return NULL;
75 }
76 
77 /* Handle all special nodes that we should ignore. */
78 static bool gpio_shared_of_node_ignore(struct device_node *node)
79 {
80 	/*
81 	 * __symbols__ is a special, internal node and should not be considered
82 	 * when scanning for shared GPIOs.
83 	 */
84 	if (of_node_name_eq(node, "__symbols__"))
85 		return true;
86 
87 	/*
88 	 * GPIO hogs have a "gpios" property which is not a phandle and can't
89 	 * possibly refer to a shared GPIO.
90 	 */
91 	if (of_property_present(node, "gpio-hog"))
92 		return true;
93 
94 	return false;
95 }
96 
97 static int gpio_shared_of_traverse(struct device_node *curr)
98 {
99 	struct gpio_shared_entry *entry;
100 	size_t con_id_len, suffix_len;
101 	struct fwnode_handle *fwnode;
102 	struct of_phandle_args args;
103 	struct property *prop;
104 	unsigned int offset;
105 	const char *suffix;
106 	int ret, count, i;
107 
108 	if (gpio_shared_of_node_ignore(curr))
109 		return 0;
110 
111 	for_each_property_of_node(curr, prop) {
112 		/*
113 		 * The standard name for a GPIO property is "foo-gpios"
114 		 * or "foo-gpio". Some bindings also use "gpios" or "gpio".
115 		 * There are some legacy device-trees which have a different
116 		 * naming convention and for which we have rename quirks in
117 		 * place in gpiolib-of.c. I don't think any of them require
118 		 * support for shared GPIOs so for now let's just ignore
119 		 * them. We can always just export the quirk list and
120 		 * iterate over it here.
121 		 */
122 		if (!strends(prop->name, "-gpios") &&
123 		    !strends(prop->name, "-gpio") &&
124 		    strcmp(prop->name, "gpios") != 0 &&
125 		    strcmp(prop->name, "gpio") != 0)
126 			continue;
127 
128 		count = of_count_phandle_with_args(curr, prop->name,
129 						   "#gpio-cells");
130 		if (count <= 0)
131 			continue;
132 
133 		for (i = 0; i < count; i++) {
134 			struct device_node *np __free(device_node) = NULL;
135 
136 			ret = of_parse_phandle_with_args(curr, prop->name,
137 							 "#gpio-cells", i,
138 							 &args);
139 			if (ret)
140 				continue;
141 
142 			np = args.np;
143 
144 			if (!of_property_present(np, "gpio-controller"))
145 				continue;
146 
147 			/*
148 			 * We support 1, 2 and 3 cell GPIO bindings in the
149 			 * kernel currently. There's only one old MIPS dts that
150 			 * has a one-cell binding but there's no associated
151 			 * consumer so it may as well be an error. There don't
152 			 * seem to be any 3-cell users of non-exclusive GPIOs,
153 			 * so we can skip this as well. Let's occupy ourselves
154 			 * with the predominant 2-cell binding with the first
155 			 * cell indicating the hardware offset of the GPIO and
156 			 * the second defining the GPIO flags of the request.
157 			 */
158 			if (args.args_count != 2)
159 				continue;
160 
161 			fwnode = of_fwnode_handle(args.np);
162 			offset = args.args[0];
163 
164 			entry = gpio_shared_find_entry(fwnode, offset);
165 			if (!entry) {
166 				entry = kzalloc(sizeof(*entry), GFP_KERNEL);
167 				if (!entry)
168 					return -ENOMEM;
169 
170 				entry->fwnode = fwnode_handle_get(fwnode);
171 				entry->offset = offset;
172 				entry->index = count;
173 				INIT_LIST_HEAD(&entry->refs);
174 				mutex_init(&entry->lock);
175 
176 				list_add_tail(&entry->list, &gpio_shared_list);
177 			}
178 
179 			struct gpio_shared_ref *ref __free(kfree) =
180 					kzalloc(sizeof(*ref), GFP_KERNEL);
181 			if (!ref)
182 				return -ENOMEM;
183 
184 			ref->fwnode = fwnode_handle_get(of_fwnode_handle(curr));
185 			ref->flags = args.args[1];
186 
187 			if (strends(prop->name, "gpios"))
188 				suffix = "-gpios";
189 			else if (strends(prop->name, "gpio"))
190 				suffix = "-gpio";
191 			else
192 				suffix = NULL;
193 			if (!suffix)
194 				continue;
195 
196 			/* We only set con_id if there's actually one. */
197 			if (strcmp(prop->name, "gpios") && strcmp(prop->name, "gpio")) {
198 				ref->con_id = kstrdup(prop->name, GFP_KERNEL);
199 				if (!ref->con_id)
200 					return -ENOMEM;
201 
202 				con_id_len = strlen(ref->con_id);
203 				suffix_len = strlen(suffix);
204 
205 				ref->con_id[con_id_len - suffix_len] = '\0';
206 			}
207 
208 			ref->dev_id = ida_alloc(&gpio_shared_ida, GFP_KERNEL);
209 			if (ref->dev_id < 0) {
210 				kfree(ref->con_id);
211 				return -ENOMEM;
212 			}
213 
214 			if (!list_empty(&entry->refs))
215 				pr_debug("GPIO %u at %s is shared by multiple firmware nodes\n",
216 					 entry->offset, fwnode_get_name(entry->fwnode));
217 
218 			list_add_tail(&no_free_ptr(ref)->list, &entry->refs);
219 		}
220 	}
221 
222 	for_each_child_of_node_scoped(curr, child) {
223 		ret = gpio_shared_of_traverse(child);
224 		if (ret)
225 			return ret;
226 	}
227 
228 	return 0;
229 }
230 
231 static int gpio_shared_of_scan(void)
232 {
233 	if (of_root)
234 		return gpio_shared_of_traverse(of_root);
235 
236 	return 0;
237 }
238 #else
239 static int gpio_shared_of_scan(void)
240 {
241 	return 0;
242 }
243 #endif /* CONFIG_OF */
244 
245 static void gpio_shared_adev_release(struct device *dev)
246 {
247 
248 }
249 
250 static int gpio_shared_make_adev(struct gpio_device *gdev,
251 				 struct gpio_shared_entry *entry,
252 				 struct gpio_shared_ref *ref)
253 {
254 	struct auxiliary_device *adev = &ref->adev;
255 	int ret;
256 
257 	lockdep_assert_held(&gpio_shared_lock);
258 
259 	memset(adev, 0, sizeof(*adev));
260 
261 	adev->id = ref->dev_id;
262 	adev->name = "proxy";
263 	adev->dev.parent = gdev->dev.parent;
264 	adev->dev.platform_data = entry;
265 	adev->dev.release = gpio_shared_adev_release;
266 
267 	ret = auxiliary_device_init(adev);
268 	if (ret)
269 		return ret;
270 
271 	ret = auxiliary_device_add(adev);
272 	if (ret) {
273 		auxiliary_device_uninit(adev);
274 		return ret;
275 	}
276 
277 	pr_debug("Created an auxiliary GPIO proxy %s for GPIO device %s\n",
278 		 dev_name(&adev->dev), gpio_device_get_label(gdev));
279 
280 	return 0;
281 }
282 
283 #if IS_ENABLED(CONFIG_RESET_GPIO)
284 /*
285  * Special case: reset-gpio is an auxiliary device that's created dynamically
286  * and put in between the GPIO controller and consumers of shared GPIOs
287  * referred to by the "reset-gpios" property.
288  *
289  * If the supposed consumer of a shared GPIO didn't match any of the mappings
290  * we created when scanning the firmware nodes, it's still possible that it's
291  * the reset-gpio device which didn't exist at the time of the scan.
292  *
293  * This function verifies it an return true if it's the case.
294  */
295 static bool gpio_shared_dev_is_reset_gpio(struct device *consumer,
296 					  struct gpio_shared_entry *entry,
297 					  struct gpio_shared_ref *ref)
298 {
299 	struct fwnode_handle *reset_fwnode = dev_fwnode(consumer);
300 	struct fwnode_reference_args ref_args, aux_args;
301 	struct device *parent = consumer->parent;
302 	bool match;
303 	int ret;
304 
305 	/* The reset-gpio device must have a parent AND a firmware node. */
306 	if (!parent || !reset_fwnode)
307 		return false;
308 
309 	/*
310 	 * FIXME: use device_is_compatible() once the reset-gpio drivers gains
311 	 * a compatible string which it currently does not have.
312 	 */
313 	if (!strstarts(dev_name(consumer), "reset.gpio."))
314 		return false;
315 
316 	/*
317 	 * Parent of the reset-gpio auxiliary device is the GPIO chip whose
318 	 * fwnode we stored in the entry structure.
319 	 */
320 	if (!device_match_fwnode(parent, entry->fwnode))
321 		return false;
322 
323 	/*
324 	 * The device associated with the shared reference's firmware node is
325 	 * the consumer of the reset control exposed by the reset-gpio device.
326 	 * It must have a "reset-gpios" property that's referencing the entry's
327 	 * firmware node.
328 	 *
329 	 * The reference args must agree between the real consumer and the
330 	 * auxiliary reset-gpio device.
331 	 */
332 	ret = fwnode_property_get_reference_args(ref->fwnode, "reset-gpios",
333 						 NULL, 2, 0, &ref_args);
334 	if (ret)
335 		return false;
336 
337 	ret = fwnode_property_get_reference_args(reset_fwnode, "reset-gpios",
338 						 NULL, 2, 0, &aux_args);
339 	if (ret) {
340 		fwnode_handle_put(ref_args.fwnode);
341 		return false;
342 	}
343 
344 	match = ((ref_args.fwnode == entry->fwnode) &&
345 		 (aux_args.fwnode == entry->fwnode) &&
346 		 (ref_args.args[0] == aux_args.args[0]));
347 
348 	fwnode_handle_put(ref_args.fwnode);
349 	fwnode_handle_put(aux_args.fwnode);
350 	return match;
351 }
352 #else
353 static bool gpio_shared_dev_is_reset_gpio(struct device *consumer,
354 					  struct gpio_shared_entry *entry,
355 					  struct gpio_shared_ref *ref)
356 {
357 	return false;
358 }
359 #endif /* CONFIG_RESET_GPIO */
360 
361 int gpio_shared_add_proxy_lookup(struct device *consumer, unsigned long lflags)
362 {
363 	const char *dev_id = dev_name(consumer);
364 	struct gpio_shared_entry *entry;
365 	struct gpio_shared_ref *ref;
366 
367 	struct gpiod_lookup_table *lookup __free(kfree) =
368 			kzalloc(struct_size(lookup, table, 2), GFP_KERNEL);
369 	if (!lookup)
370 		return -ENOMEM;
371 
372 	guard(mutex)(&gpio_shared_lock);
373 
374 	list_for_each_entry(entry, &gpio_shared_list, list) {
375 		list_for_each_entry(ref, &entry->refs, list) {
376 			if (!device_match_fwnode(consumer, ref->fwnode) &&
377 			    !gpio_shared_dev_is_reset_gpio(consumer, entry, ref))
378 				continue;
379 
380 			/* We've already done that on a previous request. */
381 			if (ref->lookup)
382 				return 0;
383 
384 			char *key __free(kfree) =
385 				kasprintf(GFP_KERNEL,
386 					  KBUILD_MODNAME ".proxy.%u",
387 					  ref->adev.id);
388 			if (!key)
389 				return -ENOMEM;
390 
391 			pr_debug("Adding machine lookup entry for a shared GPIO for consumer %s, with key '%s' and con_id '%s'\n",
392 				 dev_id, key, ref->con_id ?: "none");
393 
394 			lookup->dev_id = dev_id;
395 			lookup->table[0] = GPIO_LOOKUP(no_free_ptr(key), 0,
396 						       ref->con_id, lflags);
397 
398 			gpiod_add_lookup_table(no_free_ptr(lookup));
399 
400 			return 0;
401 		}
402 	}
403 
404 	/* We warn here because this can only happen if the programmer borked. */
405 	WARN_ON(1);
406 	return -ENOENT;
407 }
408 
409 static void gpio_shared_remove_adev(struct auxiliary_device *adev)
410 {
411 	lockdep_assert_held(&gpio_shared_lock);
412 
413 	auxiliary_device_uninit(adev);
414 	auxiliary_device_delete(adev);
415 }
416 
417 int gpio_device_setup_shared(struct gpio_device *gdev)
418 {
419 	struct gpio_shared_entry *entry;
420 	struct gpio_shared_ref *ref;
421 	unsigned long *flags;
422 	int ret;
423 
424 	guard(mutex)(&gpio_shared_lock);
425 
426 	list_for_each_entry(entry, &gpio_shared_list, list) {
427 		list_for_each_entry(ref, &entry->refs, list) {
428 			if (gdev->dev.parent == &ref->adev.dev) {
429 				/*
430 				 * This is a shared GPIO proxy. Mark its
431 				 * descriptor as such and return here.
432 				 */
433 				__set_bit(GPIOD_FLAG_SHARED_PROXY,
434 					  &gdev->descs[0].flags);
435 				return 0;
436 			}
437 		}
438 	}
439 
440 	/*
441 	 * This is not a shared GPIO proxy but it still may be the device
442 	 * exposing shared pins. Find them and create the proxy devices.
443 	 */
444 	list_for_each_entry(entry, &gpio_shared_list, list) {
445 		if (!device_match_fwnode(&gdev->dev, entry->fwnode))
446 			continue;
447 
448 		if (list_count_nodes(&entry->refs) <= 1)
449 			continue;
450 
451 		flags = &gdev->descs[entry->offset].flags;
452 
453 		__set_bit(GPIOD_FLAG_SHARED, flags);
454 		/*
455 		 * Shared GPIOs are not requested via the normal path. Make
456 		 * them inaccessible to anyone even before we register the
457 		 * chip.
458 		 */
459 		__set_bit(GPIOD_FLAG_REQUESTED, flags);
460 
461 		pr_debug("GPIO %u owned by %s is shared by multiple consumers\n",
462 			 entry->offset, gpio_device_get_label(gdev));
463 
464 		list_for_each_entry(ref, &entry->refs, list) {
465 			pr_debug("Setting up a shared GPIO entry for %s\n",
466 				 fwnode_get_name(ref->fwnode));
467 
468 			ret = gpio_shared_make_adev(gdev, entry, ref);
469 			if (ret)
470 				return ret;
471 		}
472 	}
473 
474 	return 0;
475 }
476 
477 void gpio_device_teardown_shared(struct gpio_device *gdev)
478 {
479 	struct gpio_shared_entry *entry;
480 	struct gpio_shared_ref *ref;
481 
482 	guard(mutex)(&gpio_shared_lock);
483 
484 	list_for_each_entry(entry, &gpio_shared_list, list) {
485 		if (!device_match_fwnode(&gdev->dev, entry->fwnode))
486 			continue;
487 
488 		list_for_each_entry(ref, &entry->refs, list) {
489 			gpiod_remove_lookup_table(ref->lookup);
490 			kfree(ref->lookup->table[0].key);
491 			kfree(ref->lookup);
492 			ref->lookup = NULL;
493 			gpio_shared_remove_adev(&ref->adev);
494 		}
495 	}
496 }
497 
498 static void gpio_shared_release(struct kref *kref)
499 {
500 	struct gpio_shared_entry *entry =
501 		container_of(kref, struct gpio_shared_entry, ref);
502 	struct gpio_shared_desc *shared_desc;
503 
504 	guard(mutex)(&entry->lock);
505 
506 	shared_desc = entry->shared_desc;
507 	gpio_device_put(shared_desc->desc->gdev);
508 	if (shared_desc->can_sleep)
509 		mutex_destroy(&shared_desc->mutex);
510 	kfree(shared_desc);
511 	entry->shared_desc = NULL;
512 }
513 
514 static void gpiod_shared_put(void *data)
515 {
516 	struct gpio_shared_entry *entry = data;
517 
518 	lockdep_assert_not_held(&gpio_shared_lock);
519 
520 	kref_put(&entry->ref, gpio_shared_release);
521 }
522 
523 static struct gpio_shared_desc *
524 gpiod_shared_desc_create(struct gpio_shared_entry *entry)
525 {
526 	struct gpio_shared_desc *shared_desc;
527 	struct gpio_device *gdev;
528 
529 	lockdep_assert_held(&entry->lock);
530 
531 	shared_desc = kzalloc(sizeof(*shared_desc), GFP_KERNEL);
532 	if (!shared_desc)
533 		return ERR_PTR(-ENOMEM);
534 
535 	gdev = gpio_device_find_by_fwnode(entry->fwnode);
536 	if (!gdev) {
537 		kfree(shared_desc);
538 		return ERR_PTR(-EPROBE_DEFER);
539 	}
540 
541 	shared_desc->desc = &gdev->descs[entry->offset];
542 	shared_desc->can_sleep = gpiod_cansleep(shared_desc->desc);
543 	if (shared_desc->can_sleep)
544 		mutex_init(&shared_desc->mutex);
545 	else
546 		spin_lock_init(&shared_desc->spinlock);
547 
548 	return shared_desc;
549 }
550 
551 struct gpio_shared_desc *devm_gpiod_shared_get(struct device *dev)
552 {
553 	struct gpio_shared_desc *shared_desc;
554 	struct gpio_shared_entry *entry;
555 	int ret;
556 
557 	lockdep_assert_not_held(&gpio_shared_lock);
558 
559 	entry = dev_get_platdata(dev);
560 	if (WARN_ON(!entry))
561 		/* Programmer bug */
562 		return ERR_PTR(-ENOENT);
563 
564 	scoped_guard(mutex, &entry->lock) {
565 		if (entry->shared_desc) {
566 			kref_get(&entry->ref);
567 			shared_desc = entry->shared_desc;
568 		} else {
569 			shared_desc = gpiod_shared_desc_create(entry);
570 			if (IS_ERR(shared_desc))
571 				return ERR_CAST(shared_desc);
572 
573 			kref_init(&entry->ref);
574 			entry->shared_desc = shared_desc;
575 		}
576 
577 		pr_debug("Device %s acquired a reference to the shared GPIO %u owned by %s\n",
578 			 dev_name(dev), gpiod_hwgpio(shared_desc->desc),
579 			 gpio_device_get_label(shared_desc->desc->gdev));
580 	}
581 
582 	ret = devm_add_action_or_reset(dev, gpiod_shared_put, entry);
583 	if (ret)
584 		return ERR_PTR(ret);
585 
586 	return shared_desc;
587 }
588 EXPORT_SYMBOL_GPL(devm_gpiod_shared_get);
589 
590 static void gpio_shared_drop_ref(struct gpio_shared_ref *ref)
591 {
592 	list_del(&ref->list);
593 	kfree(ref->con_id);
594 	ida_free(&gpio_shared_ida, ref->dev_id);
595 	fwnode_handle_put(ref->fwnode);
596 	kfree(ref);
597 }
598 
599 static void gpio_shared_drop_entry(struct gpio_shared_entry *entry)
600 {
601 	list_del(&entry->list);
602 	mutex_destroy(&entry->lock);
603 	fwnode_handle_put(entry->fwnode);
604 	kfree(entry);
605 }
606 
607 /*
608  * This is only called if gpio_shared_init() fails so it's in fact __init and
609  * not __exit.
610  */
611 static void __init gpio_shared_teardown(void)
612 {
613 	struct gpio_shared_entry *entry, *epos;
614 	struct gpio_shared_ref *ref, *rpos;
615 
616 	list_for_each_entry_safe(entry, epos, &gpio_shared_list, list) {
617 		list_for_each_entry_safe(ref, rpos, &entry->refs, list)
618 			gpio_shared_drop_ref(ref);
619 
620 		gpio_shared_drop_entry(entry);
621 	}
622 }
623 
624 static void gpio_shared_free_exclusive(void)
625 {
626 	struct gpio_shared_entry *entry, *epos;
627 
628 	list_for_each_entry_safe(entry, epos, &gpio_shared_list, list) {
629 		if (list_count_nodes(&entry->refs) > 1)
630 			continue;
631 
632 		gpio_shared_drop_ref(list_first_entry(&entry->refs,
633 						      struct gpio_shared_ref,
634 						      list));
635 		gpio_shared_drop_entry(entry);
636 	}
637 }
638 
639 static int __init gpio_shared_init(void)
640 {
641 	int ret;
642 
643 	/* Right now, we only support OF-based systems. */
644 	ret = gpio_shared_of_scan();
645 	if (ret) {
646 		gpio_shared_teardown();
647 		pr_err("Failed to scan OF nodes for shared GPIOs: %d\n", ret);
648 		return ret;
649 	}
650 
651 	gpio_shared_free_exclusive();
652 
653 	pr_debug("Finished scanning firmware nodes for shared GPIOs\n");
654 	return 0;
655 }
656 postcore_initcall(gpio_shared_init);
657