1 // SPDX-License-Identifier: GPL-2.0
2
3 #include <linux/acpi.h>
4 #include <linux/array_size.h>
5 #include <linux/bitmap.h>
6 #include <linux/cleanup.h>
7 #include <linux/compat.h>
8 #include <linux/debugfs.h>
9 #include <linux/device.h>
10 #include <linux/err.h>
11 #include <linux/errno.h>
12 #include <linux/file.h>
13 #include <linux/fs.h>
14 #include <linux/idr.h>
15 #include <linux/interrupt.h>
16 #include <linux/irq.h>
17 #include <linux/irqdesc.h>
18 #include <linux/kernel.h>
19 #include <linux/list.h>
20 #include <linux/lockdep.h>
21 #include <linux/module.h>
22 #include <linux/nospec.h>
23 #include <linux/of.h>
24 #include <linux/pinctrl/consumer.h>
25 #include <linux/seq_file.h>
26 #include <linux/slab.h>
27 #include <linux/srcu.h>
28 #include <linux/string.h>
29 #include <linux/string_choices.h>
30
31 #include <linux/gpio.h>
32 #include <linux/gpio/driver.h>
33 #include <linux/gpio/machine.h>
34
35 #include <uapi/linux/gpio.h>
36
37 #include "gpiolib-acpi.h"
38 #include "gpiolib-cdev.h"
39 #include "gpiolib-of.h"
40 #include "gpiolib-swnode.h"
41 #include "gpiolib-sysfs.h"
42 #include "gpiolib.h"
43
44 #define CREATE_TRACE_POINTS
45 #include <trace/events/gpio.h>
46
47 /* Implementation infrastructure for GPIO interfaces.
48 *
49 * The GPIO programming interface allows for inlining speed-critical
50 * get/set operations for common cases, so that access to SOC-integrated
51 * GPIOs can sometimes cost only an instruction or two per bit.
52 */
53
54 /* Device and char device-related information */
55 static DEFINE_IDA(gpio_ida);
56 static dev_t gpio_devt;
57 #define GPIO_DEV_MAX 256 /* 256 GPIO chip devices supported */
58
gpio_bus_match(struct device * dev,const struct device_driver * drv)59 static int gpio_bus_match(struct device *dev, const struct device_driver *drv)
60 {
61 struct fwnode_handle *fwnode = dev_fwnode(dev);
62
63 /*
64 * Only match if the fwnode doesn't already have a proper struct device
65 * created for it.
66 */
67 if (fwnode && fwnode->dev != dev)
68 return 0;
69 return 1;
70 }
71
72 static const struct bus_type gpio_bus_type = {
73 .name = "gpio",
74 .match = gpio_bus_match,
75 };
76
77 /*
78 * At the end we want all GPIOs to be dynamically allocated from 0.
79 * However, some legacy drivers still perform fixed allocation.
80 * Until they are all fixed, leave 0-512 space for them.
81 */
82 #define GPIO_DYNAMIC_BASE 512
83 /*
84 * Define the maximum of the possible GPIO in the global numberspace.
85 * While the GPIO base and numbers are positive, we limit it with signed
86 * maximum as a lot of code is using negative values for special cases.
87 */
88 #define GPIO_DYNAMIC_MAX INT_MAX
89
90 /*
91 * Number of GPIOs to use for the fast path in set array
92 */
93 #define FASTPATH_NGPIO CONFIG_GPIOLIB_FASTPATH_LIMIT
94
95 static DEFINE_MUTEX(gpio_lookup_lock);
96 static LIST_HEAD(gpio_lookup_list);
97
98 static LIST_HEAD(gpio_devices);
99 /* Protects the GPIO device list against concurrent modifications. */
100 static DEFINE_MUTEX(gpio_devices_lock);
101 /* Ensures coherence during read-only accesses to the list of GPIO devices. */
102 DEFINE_STATIC_SRCU(gpio_devices_srcu);
103
104 static DEFINE_MUTEX(gpio_machine_hogs_mutex);
105 static LIST_HEAD(gpio_machine_hogs);
106
107 const char *const gpio_suffixes[] = { "gpios", "gpio", NULL };
108
109 static void gpiochip_free_hogs(struct gpio_chip *gc);
110 static int gpiochip_add_irqchip(struct gpio_chip *gc,
111 struct lock_class_key *lock_key,
112 struct lock_class_key *request_key);
113 static void gpiochip_irqchip_remove(struct gpio_chip *gc);
114 static int gpiochip_irqchip_init_hw(struct gpio_chip *gc);
115 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc);
116 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc);
117
118 static bool gpiolib_initialized;
119
gpiod_get_label(struct gpio_desc * desc)120 const char *gpiod_get_label(struct gpio_desc *desc)
121 {
122 struct gpio_desc_label *label;
123 unsigned long flags;
124
125 flags = READ_ONCE(desc->flags);
126
127 label = srcu_dereference_check(desc->label, &desc->gdev->desc_srcu,
128 srcu_read_lock_held(&desc->gdev->desc_srcu));
129
130 if (test_bit(FLAG_USED_AS_IRQ, &flags))
131 return label ? label->str : "interrupt";
132
133 if (!test_bit(FLAG_REQUESTED, &flags))
134 return NULL;
135
136 return label ? label->str : NULL;
137 }
138
desc_free_label(struct rcu_head * rh)139 static void desc_free_label(struct rcu_head *rh)
140 {
141 kfree(container_of(rh, struct gpio_desc_label, rh));
142 }
143
desc_set_label(struct gpio_desc * desc,const char * label)144 static int desc_set_label(struct gpio_desc *desc, const char *label)
145 {
146 struct gpio_desc_label *new = NULL, *old;
147
148 if (label) {
149 new = kzalloc(struct_size(new, str, strlen(label) + 1),
150 GFP_KERNEL);
151 if (!new)
152 return -ENOMEM;
153
154 strcpy(new->str, label);
155 }
156
157 old = rcu_replace_pointer(desc->label, new, 1);
158 if (old)
159 call_srcu(&desc->gdev->desc_srcu, &old->rh, desc_free_label);
160
161 return 0;
162 }
163
164 /**
165 * gpio_to_desc - Convert a GPIO number to its descriptor
166 * @gpio: global GPIO number
167 *
168 * Returns:
169 * The GPIO descriptor associated with the given GPIO, or %NULL if no GPIO
170 * with the given number exists in the system.
171 */
gpio_to_desc(unsigned gpio)172 struct gpio_desc *gpio_to_desc(unsigned gpio)
173 {
174 struct gpio_device *gdev;
175
176 scoped_guard(srcu, &gpio_devices_srcu) {
177 list_for_each_entry_srcu(gdev, &gpio_devices, list,
178 srcu_read_lock_held(&gpio_devices_srcu)) {
179 if (gdev->base <= gpio &&
180 gdev->base + gdev->ngpio > gpio)
181 return &gdev->descs[gpio - gdev->base];
182 }
183 }
184
185 return NULL;
186 }
187 EXPORT_SYMBOL_GPL(gpio_to_desc);
188
189 /* This function is deprecated and will be removed soon, don't use. */
gpiochip_get_desc(struct gpio_chip * gc,unsigned int hwnum)190 struct gpio_desc *gpiochip_get_desc(struct gpio_chip *gc,
191 unsigned int hwnum)
192 {
193 return gpio_device_get_desc(gc->gpiodev, hwnum);
194 }
195
196 /**
197 * gpio_device_get_desc() - get the GPIO descriptor corresponding to the given
198 * hardware number for this GPIO device
199 * @gdev: GPIO device to get the descriptor from
200 * @hwnum: hardware number of the GPIO for this chip
201 *
202 * Returns:
203 * A pointer to the GPIO descriptor or %EINVAL if no GPIO exists in the given
204 * chip for the specified hardware number or %ENODEV if the underlying chip
205 * already vanished.
206 *
207 * The reference count of struct gpio_device is *NOT* increased like when the
208 * GPIO is being requested for exclusive usage. It's up to the caller to make
209 * sure the GPIO device will stay alive together with the descriptor returned
210 * by this function.
211 */
212 struct gpio_desc *
gpio_device_get_desc(struct gpio_device * gdev,unsigned int hwnum)213 gpio_device_get_desc(struct gpio_device *gdev, unsigned int hwnum)
214 {
215 if (hwnum >= gdev->ngpio)
216 return ERR_PTR(-EINVAL);
217
218 return &gdev->descs[array_index_nospec(hwnum, gdev->ngpio)];
219 }
220 EXPORT_SYMBOL_GPL(gpio_device_get_desc);
221
222 /**
223 * desc_to_gpio - convert a GPIO descriptor to the integer namespace
224 * @desc: GPIO descriptor
225 *
226 * This should disappear in the future but is needed since we still
227 * use GPIO numbers for error messages and sysfs nodes.
228 *
229 * Returns:
230 * The global GPIO number for the GPIO specified by its descriptor.
231 */
desc_to_gpio(const struct gpio_desc * desc)232 int desc_to_gpio(const struct gpio_desc *desc)
233 {
234 return desc->gdev->base + (desc - &desc->gdev->descs[0]);
235 }
236 EXPORT_SYMBOL_GPL(desc_to_gpio);
237
238
239 /**
240 * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
241 * @desc: descriptor to return the chip of
242 *
243 * *DEPRECATED*
244 * This function is unsafe and should not be used. Using the chip address
245 * without taking the SRCU read lock may result in dereferencing a dangling
246 * pointer.
247 *
248 * Returns:
249 * Address of the GPIO chip backing this device.
250 */
gpiod_to_chip(const struct gpio_desc * desc)251 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
252 {
253 if (!desc)
254 return NULL;
255
256 return gpio_device_get_chip(desc->gdev);
257 }
258 EXPORT_SYMBOL_GPL(gpiod_to_chip);
259
260 /**
261 * gpiod_to_gpio_device() - Return the GPIO device to which this descriptor
262 * belongs.
263 * @desc: Descriptor for which to return the GPIO device.
264 *
265 * This *DOES NOT* increase the reference count of the GPIO device as it's
266 * expected that the descriptor is requested and the users already holds a
267 * reference to the device.
268 *
269 * Returns:
270 * Address of the GPIO device owning this descriptor.
271 */
gpiod_to_gpio_device(struct gpio_desc * desc)272 struct gpio_device *gpiod_to_gpio_device(struct gpio_desc *desc)
273 {
274 if (!desc)
275 return NULL;
276
277 return desc->gdev;
278 }
279 EXPORT_SYMBOL_GPL(gpiod_to_gpio_device);
280
281 /**
282 * gpio_device_get_base() - Get the base GPIO number allocated by this device
283 * @gdev: GPIO device
284 *
285 * Returns:
286 * First GPIO number in the global GPIO numberspace for this device.
287 */
gpio_device_get_base(struct gpio_device * gdev)288 int gpio_device_get_base(struct gpio_device *gdev)
289 {
290 return gdev->base;
291 }
292 EXPORT_SYMBOL_GPL(gpio_device_get_base);
293
294 /**
295 * gpio_device_get_label() - Get the label of this GPIO device
296 * @gdev: GPIO device
297 *
298 * Returns:
299 * Pointer to the string containing the GPIO device label. The string's
300 * lifetime is tied to that of the underlying GPIO device.
301 */
gpio_device_get_label(struct gpio_device * gdev)302 const char *gpio_device_get_label(struct gpio_device *gdev)
303 {
304 return gdev->label;
305 }
306 EXPORT_SYMBOL(gpio_device_get_label);
307
308 /**
309 * gpio_device_get_chip() - Get the gpio_chip implementation of this GPIO device
310 * @gdev: GPIO device
311 *
312 * Returns:
313 * Address of the GPIO chip backing this device.
314 *
315 * *DEPRECATED*
316 * Until we can get rid of all non-driver users of struct gpio_chip, we must
317 * provide a way of retrieving the pointer to it from struct gpio_device. This
318 * is *NOT* safe as the GPIO API is considered to be hot-unpluggable and the
319 * chip can dissapear at any moment (unlike reference-counted struct
320 * gpio_device).
321 *
322 * Use at your own risk.
323 */
gpio_device_get_chip(struct gpio_device * gdev)324 struct gpio_chip *gpio_device_get_chip(struct gpio_device *gdev)
325 {
326 return rcu_dereference_check(gdev->chip, 1);
327 }
328 EXPORT_SYMBOL_GPL(gpio_device_get_chip);
329
330 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
gpiochip_find_base_unlocked(u16 ngpio)331 static int gpiochip_find_base_unlocked(u16 ngpio)
332 {
333 unsigned int base = GPIO_DYNAMIC_BASE;
334 struct gpio_device *gdev;
335
336 list_for_each_entry_srcu(gdev, &gpio_devices, list,
337 lockdep_is_held(&gpio_devices_lock)) {
338 /* found a free space? */
339 if (gdev->base >= base + ngpio)
340 break;
341 /* nope, check the space right after the chip */
342 base = gdev->base + gdev->ngpio;
343 if (base < GPIO_DYNAMIC_BASE)
344 base = GPIO_DYNAMIC_BASE;
345 if (base > GPIO_DYNAMIC_MAX - ngpio)
346 break;
347 }
348
349 if (base <= GPIO_DYNAMIC_MAX - ngpio) {
350 pr_debug("%s: found new base at %d\n", __func__, base);
351 return base;
352 } else {
353 pr_err("%s: cannot find free range\n", __func__);
354 return -ENOSPC;
355 }
356 }
357
358 /*
359 * This descriptor validation needs to be inserted verbatim into each
360 * function taking a descriptor, so we need to use a preprocessor
361 * macro to avoid endless duplication. If the desc is NULL it is an
362 * optional GPIO and calls should just bail out.
363 */
validate_desc(const struct gpio_desc * desc,const char * func)364 static int validate_desc(const struct gpio_desc *desc, const char *func)
365 {
366 if (!desc)
367 return 0;
368
369 if (IS_ERR(desc)) {
370 pr_warn("%s: invalid GPIO (errorpointer: %pe)\n", func, desc);
371 return PTR_ERR(desc);
372 }
373
374 return 1;
375 }
376
377 #define VALIDATE_DESC(desc) do { \
378 int __valid = validate_desc(desc, __func__); \
379 if (__valid <= 0) \
380 return __valid; \
381 } while (0)
382
383 #define VALIDATE_DESC_VOID(desc) do { \
384 int __valid = validate_desc(desc, __func__); \
385 if (__valid <= 0) \
386 return; \
387 } while (0)
388
389 /**
390 * gpiod_is_equal() - Check if two GPIO descriptors refer to the same pin.
391 * @desc: Descriptor to compare.
392 * @other: The second descriptor to compare against.
393 *
394 * Returns:
395 * True if the descriptors refer to the same physical pin. False otherwise.
396 */
gpiod_is_equal(const struct gpio_desc * desc,const struct gpio_desc * other)397 bool gpiod_is_equal(const struct gpio_desc *desc, const struct gpio_desc *other)
398 {
399 return validate_desc(desc, __func__) > 0 &&
400 !IS_ERR_OR_NULL(other) && desc == other;
401 }
402 EXPORT_SYMBOL_GPL(gpiod_is_equal);
403
gpiochip_get_direction(struct gpio_chip * gc,unsigned int offset)404 static int gpiochip_get_direction(struct gpio_chip *gc, unsigned int offset)
405 {
406 int ret;
407
408 lockdep_assert_held(&gc->gpiodev->srcu);
409
410 if (WARN_ON(!gc->get_direction))
411 return -EOPNOTSUPP;
412
413 ret = gc->get_direction(gc, offset);
414 if (ret < 0)
415 return ret;
416
417 if (ret != GPIO_LINE_DIRECTION_OUT && ret != GPIO_LINE_DIRECTION_IN)
418 ret = -EBADE;
419
420 return ret;
421 }
422
423 /**
424 * gpiod_get_direction - return the current direction of a GPIO
425 * @desc: GPIO to get the direction of
426 *
427 * Returns:
428 * 0 for output, 1 for input, or an error code in case of error.
429 *
430 * This function may sleep if gpiod_cansleep() is true.
431 */
gpiod_get_direction(struct gpio_desc * desc)432 int gpiod_get_direction(struct gpio_desc *desc)
433 {
434 unsigned long flags;
435 unsigned int offset;
436 int ret;
437
438 ret = validate_desc(desc, __func__);
439 if (ret <= 0)
440 return -EINVAL;
441
442 CLASS(gpio_chip_guard, guard)(desc);
443 if (!guard.gc)
444 return -ENODEV;
445
446 offset = gpio_chip_hwgpio(desc);
447 flags = READ_ONCE(desc->flags);
448
449 /*
450 * Open drain emulation using input mode may incorrectly report
451 * input here, fix that up.
452 */
453 if (test_bit(FLAG_OPEN_DRAIN, &flags) &&
454 test_bit(FLAG_IS_OUT, &flags))
455 return 0;
456
457 if (!guard.gc->get_direction)
458 return -ENOTSUPP;
459
460 ret = gpiochip_get_direction(guard.gc, offset);
461 if (ret < 0)
462 return ret;
463
464 /*
465 * GPIO_LINE_DIRECTION_IN or other positive,
466 * otherwise GPIO_LINE_DIRECTION_OUT.
467 */
468 if (ret > 0)
469 ret = 1;
470
471 assign_bit(FLAG_IS_OUT, &flags, !ret);
472 WRITE_ONCE(desc->flags, flags);
473
474 return ret;
475 }
476 EXPORT_SYMBOL_GPL(gpiod_get_direction);
477
478 /*
479 * Add a new chip to the global chips list, keeping the list of chips sorted
480 * by range(means [base, base + ngpio - 1]) order.
481 *
482 * Returns:
483 * -EBUSY if the new chip overlaps with some other chip's integer space.
484 */
gpiodev_add_to_list_unlocked(struct gpio_device * gdev)485 static int gpiodev_add_to_list_unlocked(struct gpio_device *gdev)
486 {
487 struct gpio_device *prev, *next;
488
489 lockdep_assert_held(&gpio_devices_lock);
490
491 if (list_empty(&gpio_devices)) {
492 /* initial entry in list */
493 list_add_tail_rcu(&gdev->list, &gpio_devices);
494 return 0;
495 }
496
497 next = list_first_entry(&gpio_devices, struct gpio_device, list);
498 if (gdev->base + gdev->ngpio <= next->base) {
499 /* add before first entry */
500 list_add_rcu(&gdev->list, &gpio_devices);
501 return 0;
502 }
503
504 prev = list_last_entry(&gpio_devices, struct gpio_device, list);
505 if (prev->base + prev->ngpio <= gdev->base) {
506 /* add behind last entry */
507 list_add_tail_rcu(&gdev->list, &gpio_devices);
508 return 0;
509 }
510
511 list_for_each_entry_safe(prev, next, &gpio_devices, list) {
512 /* at the end of the list */
513 if (&next->list == &gpio_devices)
514 break;
515
516 /* add between prev and next */
517 if (prev->base + prev->ngpio <= gdev->base
518 && gdev->base + gdev->ngpio <= next->base) {
519 list_add_rcu(&gdev->list, &prev->list);
520 return 0;
521 }
522 }
523
524 synchronize_srcu(&gpio_devices_srcu);
525
526 return -EBUSY;
527 }
528
529 /*
530 * Convert a GPIO name to its descriptor
531 * Note that there is no guarantee that GPIO names are globally unique!
532 * Hence this function will return, if it exists, a reference to the first GPIO
533 * line found that matches the given name.
534 */
gpio_name_to_desc(const char * const name)535 static struct gpio_desc *gpio_name_to_desc(const char * const name)
536 {
537 struct gpio_device *gdev;
538 struct gpio_desc *desc;
539 struct gpio_chip *gc;
540
541 if (!name)
542 return NULL;
543
544 guard(srcu)(&gpio_devices_srcu);
545
546 list_for_each_entry_srcu(gdev, &gpio_devices, list,
547 srcu_read_lock_held(&gpio_devices_srcu)) {
548 guard(srcu)(&gdev->srcu);
549
550 gc = srcu_dereference(gdev->chip, &gdev->srcu);
551 if (!gc)
552 continue;
553
554 for_each_gpio_desc(gc, desc) {
555 if (desc->name && !strcmp(desc->name, name))
556 return desc;
557 }
558 }
559
560 return NULL;
561 }
562
563 /*
564 * Take the names from gc->names and assign them to their GPIO descriptors.
565 * Warn if a name is already used for a GPIO line on a different GPIO chip.
566 *
567 * Note that:
568 * 1. Non-unique names are still accepted,
569 * 2. Name collisions within the same GPIO chip are not reported.
570 */
gpiochip_set_desc_names(struct gpio_chip * gc)571 static void gpiochip_set_desc_names(struct gpio_chip *gc)
572 {
573 struct gpio_device *gdev = gc->gpiodev;
574 int i;
575
576 /* First check all names if they are unique */
577 for (i = 0; i != gc->ngpio; ++i) {
578 struct gpio_desc *gpio;
579
580 gpio = gpio_name_to_desc(gc->names[i]);
581 if (gpio)
582 dev_warn(&gdev->dev,
583 "Detected name collision for GPIO name '%s'\n",
584 gc->names[i]);
585 }
586
587 /* Then add all names to the GPIO descriptors */
588 for (i = 0; i != gc->ngpio; ++i)
589 gdev->descs[i].name = gc->names[i];
590 }
591
592 /*
593 * gpiochip_set_names - Set GPIO line names using device properties
594 * @chip: GPIO chip whose lines should be named, if possible
595 *
596 * Looks for device property "gpio-line-names" and if it exists assigns
597 * GPIO line names for the chip. The memory allocated for the assigned
598 * names belong to the underlying firmware node and should not be released
599 * by the caller.
600 */
gpiochip_set_names(struct gpio_chip * chip)601 static int gpiochip_set_names(struct gpio_chip *chip)
602 {
603 struct gpio_device *gdev = chip->gpiodev;
604 struct device *dev = &gdev->dev;
605 const char **names;
606 int ret, i;
607 int count;
608
609 count = device_property_string_array_count(dev, "gpio-line-names");
610 if (count < 0)
611 return 0;
612
613 /*
614 * When offset is set in the driver side we assume the driver internally
615 * is using more than one gpiochip per the same device. We have to stop
616 * setting friendly names if the specified ones with 'gpio-line-names'
617 * are less than the offset in the device itself. This means all the
618 * lines are not present for every single pin within all the internal
619 * gpiochips.
620 */
621 if (count <= chip->offset) {
622 dev_warn(dev, "gpio-line-names too short (length %d), cannot map names for the gpiochip at offset %u\n",
623 count, chip->offset);
624 return 0;
625 }
626
627 names = kcalloc(count, sizeof(*names), GFP_KERNEL);
628 if (!names)
629 return -ENOMEM;
630
631 ret = device_property_read_string_array(dev, "gpio-line-names",
632 names, count);
633 if (ret < 0) {
634 dev_warn(dev, "failed to read GPIO line names\n");
635 kfree(names);
636 return ret;
637 }
638
639 /*
640 * When more that one gpiochip per device is used, 'count' can
641 * contain at most number gpiochips x chip->ngpio. We have to
642 * correctly distribute all defined lines taking into account
643 * chip->offset as starting point from where we will assign
644 * the names to pins from the 'names' array. Since property
645 * 'gpio-line-names' cannot contains gaps, we have to be sure
646 * we only assign those pins that really exists since chip->ngpio
647 * can be different of the chip->offset.
648 */
649 count = (count > chip->offset) ? count - chip->offset : count;
650 if (count > chip->ngpio)
651 count = chip->ngpio;
652
653 for (i = 0; i < count; i++) {
654 /*
655 * Allow overriding "fixed" names provided by the GPIO
656 * provider. The "fixed" names are more often than not
657 * generic and less informative than the names given in
658 * device properties.
659 */
660 if (names[chip->offset + i] && names[chip->offset + i][0])
661 gdev->descs[i].name = names[chip->offset + i];
662 }
663
664 kfree(names);
665
666 return 0;
667 }
668
gpiochip_allocate_mask(struct gpio_chip * gc)669 static unsigned long *gpiochip_allocate_mask(struct gpio_chip *gc)
670 {
671 unsigned long *p;
672
673 p = bitmap_alloc(gc->ngpio, GFP_KERNEL);
674 if (!p)
675 return NULL;
676
677 /* Assume by default all GPIOs are valid */
678 bitmap_fill(p, gc->ngpio);
679
680 return p;
681 }
682
gpiochip_free_mask(unsigned long ** p)683 static void gpiochip_free_mask(unsigned long **p)
684 {
685 bitmap_free(*p);
686 *p = NULL;
687 }
688
gpiochip_count_reserved_ranges(struct gpio_chip * gc)689 static unsigned int gpiochip_count_reserved_ranges(struct gpio_chip *gc)
690 {
691 struct device *dev = &gc->gpiodev->dev;
692 int size;
693
694 /* Format is "start, count, ..." */
695 size = device_property_count_u32(dev, "gpio-reserved-ranges");
696 if (size > 0 && size % 2 == 0)
697 return size;
698
699 return 0;
700 }
701
gpiochip_apply_reserved_ranges(struct gpio_chip * gc)702 static int gpiochip_apply_reserved_ranges(struct gpio_chip *gc)
703 {
704 struct device *dev = &gc->gpiodev->dev;
705 unsigned int size;
706 u32 *ranges;
707 int ret;
708
709 size = gpiochip_count_reserved_ranges(gc);
710 if (size == 0)
711 return 0;
712
713 ranges = kmalloc_array(size, sizeof(*ranges), GFP_KERNEL);
714 if (!ranges)
715 return -ENOMEM;
716
717 ret = device_property_read_u32_array(dev, "gpio-reserved-ranges",
718 ranges, size);
719 if (ret) {
720 kfree(ranges);
721 return ret;
722 }
723
724 while (size) {
725 u32 count = ranges[--size];
726 u32 start = ranges[--size];
727
728 if (start >= gc->ngpio || start + count > gc->ngpio)
729 continue;
730
731 bitmap_clear(gc->gpiodev->valid_mask, start, count);
732 }
733
734 kfree(ranges);
735 return 0;
736 }
737
gpiochip_init_valid_mask(struct gpio_chip * gc)738 static int gpiochip_init_valid_mask(struct gpio_chip *gc)
739 {
740 int ret;
741
742 if (!(gpiochip_count_reserved_ranges(gc) || gc->init_valid_mask))
743 return 0;
744
745 gc->gpiodev->valid_mask = gpiochip_allocate_mask(gc);
746 if (!gc->gpiodev->valid_mask)
747 return -ENOMEM;
748
749 ret = gpiochip_apply_reserved_ranges(gc);
750 if (ret)
751 return ret;
752
753 if (gc->init_valid_mask)
754 return gc->init_valid_mask(gc,
755 gc->gpiodev->valid_mask,
756 gc->ngpio);
757
758 return 0;
759 }
760
gpiochip_free_valid_mask(struct gpio_chip * gc)761 static void gpiochip_free_valid_mask(struct gpio_chip *gc)
762 {
763 gpiochip_free_mask(&gc->gpiodev->valid_mask);
764 }
765
gpiochip_add_pin_ranges(struct gpio_chip * gc)766 static int gpiochip_add_pin_ranges(struct gpio_chip *gc)
767 {
768 /*
769 * Device Tree platforms are supposed to use "gpio-ranges"
770 * property. This check ensures that the ->add_pin_ranges()
771 * won't be called for them.
772 */
773 if (device_property_present(&gc->gpiodev->dev, "gpio-ranges"))
774 return 0;
775
776 if (gc->add_pin_ranges)
777 return gc->add_pin_ranges(gc);
778
779 return 0;
780 }
781
782 /**
783 * gpiochip_query_valid_mask - return the GPIO validity information
784 * @gc: gpio chip which validity information is queried
785 *
786 * Returns: bitmap representing valid GPIOs or NULL if all GPIOs are valid
787 *
788 * Some GPIO chips may support configurations where some of the pins aren't
789 * available. These chips can have valid_mask set to represent the valid
790 * GPIOs. This function can be used to retrieve this information.
791 */
gpiochip_query_valid_mask(const struct gpio_chip * gc)792 const unsigned long *gpiochip_query_valid_mask(const struct gpio_chip *gc)
793 {
794 return gc->gpiodev->valid_mask;
795 }
796 EXPORT_SYMBOL_GPL(gpiochip_query_valid_mask);
797
gpiochip_line_is_valid(const struct gpio_chip * gc,unsigned int offset)798 bool gpiochip_line_is_valid(const struct gpio_chip *gc,
799 unsigned int offset)
800 {
801 /*
802 * hog pins are requested before registering GPIO chip
803 */
804 if (!gc->gpiodev)
805 return true;
806
807 /* No mask means all valid */
808 if (likely(!gc->gpiodev->valid_mask))
809 return true;
810 return test_bit(offset, gc->gpiodev->valid_mask);
811 }
812 EXPORT_SYMBOL_GPL(gpiochip_line_is_valid);
813
gpiod_free_irqs(struct gpio_desc * desc)814 static void gpiod_free_irqs(struct gpio_desc *desc)
815 {
816 int irq = gpiod_to_irq(desc);
817 struct irq_desc *irqd = irq_to_desc(irq);
818 void *cookie;
819
820 for (;;) {
821 /*
822 * Make sure the action doesn't go away while we're
823 * dereferencing it. Retrieve and store the cookie value.
824 * If the irq is freed after we release the lock, that's
825 * alright - the underlying maple tree lookup will return NULL
826 * and nothing will happen in free_irq().
827 */
828 scoped_guard(mutex, &irqd->request_mutex) {
829 if (!irq_desc_has_action(irqd))
830 return;
831
832 cookie = irqd->action->dev_id;
833 }
834
835 free_irq(irq, cookie);
836 }
837 }
838
839 /*
840 * The chip is going away but there may be users who had requested interrupts
841 * on its GPIO lines who have no idea about its removal and have no way of
842 * being notified about it. We need to free any interrupts still in use here or
843 * we'll leak memory and resources (like procfs files).
844 */
gpiochip_free_remaining_irqs(struct gpio_chip * gc)845 static void gpiochip_free_remaining_irqs(struct gpio_chip *gc)
846 {
847 struct gpio_desc *desc;
848
849 for_each_gpio_desc_with_flag(gc, desc, FLAG_USED_AS_IRQ)
850 gpiod_free_irqs(desc);
851 }
852
gpiodev_release(struct device * dev)853 static void gpiodev_release(struct device *dev)
854 {
855 struct gpio_device *gdev = to_gpio_device(dev);
856
857 /* Call pending kfree()s for descriptor labels. */
858 synchronize_srcu(&gdev->desc_srcu);
859 cleanup_srcu_struct(&gdev->desc_srcu);
860
861 ida_free(&gpio_ida, gdev->id);
862 kfree_const(gdev->label);
863 kfree(gdev->descs);
864 cleanup_srcu_struct(&gdev->srcu);
865 kfree(gdev);
866 }
867
868 static const struct device_type gpio_dev_type = {
869 .name = "gpio_chip",
870 .release = gpiodev_release,
871 };
872
873 #ifdef CONFIG_GPIO_CDEV
874 #define gcdev_register(gdev, devt) gpiolib_cdev_register((gdev), (devt))
875 #define gcdev_unregister(gdev) gpiolib_cdev_unregister((gdev))
876 #else
877 /*
878 * gpiolib_cdev_register() indirectly calls device_add(), which is still
879 * required even when cdev is not selected.
880 */
881 #define gcdev_register(gdev, devt) device_add(&(gdev)->dev)
882 #define gcdev_unregister(gdev) device_del(&(gdev)->dev)
883 #endif
884
gpiochip_setup_dev(struct gpio_device * gdev)885 static int gpiochip_setup_dev(struct gpio_device *gdev)
886 {
887 struct fwnode_handle *fwnode = dev_fwnode(&gdev->dev);
888 int ret;
889
890 device_initialize(&gdev->dev);
891
892 /*
893 * If fwnode doesn't belong to another device, it's safe to clear its
894 * initialized flag.
895 */
896 if (fwnode && !fwnode->dev)
897 fwnode_dev_initialized(fwnode, false);
898
899 ret = gcdev_register(gdev, gpio_devt);
900 if (ret)
901 return ret;
902
903 ret = gpiochip_sysfs_register(gdev);
904 if (ret)
905 goto err_remove_device;
906
907 dev_dbg(&gdev->dev, "registered GPIOs %u to %u on %s\n", gdev->base,
908 gdev->base + gdev->ngpio - 1, gdev->label);
909
910 return 0;
911
912 err_remove_device:
913 gcdev_unregister(gdev);
914 return ret;
915 }
916
gpiochip_machine_hog(struct gpio_chip * gc,struct gpiod_hog * hog)917 static void gpiochip_machine_hog(struct gpio_chip *gc, struct gpiod_hog *hog)
918 {
919 struct gpio_desc *desc;
920 int rv;
921
922 desc = gpiochip_get_desc(gc, hog->chip_hwnum);
923 if (IS_ERR(desc)) {
924 chip_err(gc, "%s: unable to get GPIO desc: %ld\n", __func__,
925 PTR_ERR(desc));
926 return;
927 }
928
929 rv = gpiod_hog(desc, hog->line_name, hog->lflags, hog->dflags);
930 if (rv)
931 gpiod_err(desc, "%s: unable to hog GPIO line (%s:%u): %d\n",
932 __func__, gc->label, hog->chip_hwnum, rv);
933 }
934
machine_gpiochip_add(struct gpio_chip * gc)935 static void machine_gpiochip_add(struct gpio_chip *gc)
936 {
937 struct gpiod_hog *hog;
938
939 guard(mutex)(&gpio_machine_hogs_mutex);
940
941 list_for_each_entry(hog, &gpio_machine_hogs, list) {
942 if (!strcmp(gc->label, hog->chip_label))
943 gpiochip_machine_hog(gc, hog);
944 }
945 }
946
gpiochip_setup_devs(void)947 static void gpiochip_setup_devs(void)
948 {
949 struct gpio_device *gdev;
950 int ret;
951
952 guard(srcu)(&gpio_devices_srcu);
953
954 list_for_each_entry_srcu(gdev, &gpio_devices, list,
955 srcu_read_lock_held(&gpio_devices_srcu)) {
956 ret = gpiochip_setup_dev(gdev);
957 if (ret)
958 dev_err(&gdev->dev,
959 "Failed to initialize gpio device (%d)\n", ret);
960 }
961 }
962
gpiochip_set_data(struct gpio_chip * gc,void * data)963 static void gpiochip_set_data(struct gpio_chip *gc, void *data)
964 {
965 gc->gpiodev->data = data;
966 }
967
968 /**
969 * gpiochip_get_data() - get per-subdriver data for the chip
970 * @gc: GPIO chip
971 *
972 * Returns:
973 * The per-subdriver data for the chip.
974 */
gpiochip_get_data(struct gpio_chip * gc)975 void *gpiochip_get_data(struct gpio_chip *gc)
976 {
977 return gc->gpiodev->data;
978 }
979 EXPORT_SYMBOL_GPL(gpiochip_get_data);
980
981 /*
982 * If the calling driver provides the specific firmware node,
983 * use it. Otherwise use the one from the parent device, if any.
984 */
gpiochip_choose_fwnode(struct gpio_chip * gc)985 static struct fwnode_handle *gpiochip_choose_fwnode(struct gpio_chip *gc)
986 {
987 if (gc->fwnode)
988 return gc->fwnode;
989
990 if (gc->parent)
991 return dev_fwnode(gc->parent);
992
993 return NULL;
994 }
995
gpiochip_get_ngpios(struct gpio_chip * gc,struct device * dev)996 int gpiochip_get_ngpios(struct gpio_chip *gc, struct device *dev)
997 {
998 struct fwnode_handle *fwnode = gpiochip_choose_fwnode(gc);
999 u32 ngpios = gc->ngpio;
1000 int ret;
1001
1002 if (ngpios == 0) {
1003 ret = fwnode_property_read_u32(fwnode, "ngpios", &ngpios);
1004 if (ret == -ENODATA)
1005 /*
1006 * -ENODATA means that there is no property found and
1007 * we want to issue the error message to the user.
1008 * Besides that, we want to return different error code
1009 * to state that supplied value is not valid.
1010 */
1011 ngpios = 0;
1012 else if (ret)
1013 return ret;
1014
1015 gc->ngpio = ngpios;
1016 }
1017
1018 if (gc->ngpio == 0) {
1019 dev_err(dev, "tried to insert a GPIO chip with zero lines\n");
1020 return -EINVAL;
1021 }
1022
1023 if (gc->ngpio > FASTPATH_NGPIO)
1024 dev_warn(dev, "line cnt %u is greater than fast path cnt %u\n",
1025 gc->ngpio, FASTPATH_NGPIO);
1026
1027 return 0;
1028 }
1029 EXPORT_SYMBOL_GPL(gpiochip_get_ngpios);
1030
gpiochip_add_data_with_key(struct gpio_chip * gc,void * data,struct lock_class_key * lock_key,struct lock_class_key * request_key)1031 int gpiochip_add_data_with_key(struct gpio_chip *gc, void *data,
1032 struct lock_class_key *lock_key,
1033 struct lock_class_key *request_key)
1034 {
1035 struct gpio_device *gdev;
1036 unsigned int desc_index;
1037 int base = 0;
1038 int ret;
1039
1040 /*
1041 * First: allocate and populate the internal stat container, and
1042 * set up the struct device.
1043 */
1044 gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1045 if (!gdev)
1046 return -ENOMEM;
1047
1048 gdev->dev.type = &gpio_dev_type;
1049 gdev->dev.bus = &gpio_bus_type;
1050 gdev->dev.parent = gc->parent;
1051 rcu_assign_pointer(gdev->chip, gc);
1052
1053 gc->gpiodev = gdev;
1054 gpiochip_set_data(gc, data);
1055
1056 device_set_node(&gdev->dev, gpiochip_choose_fwnode(gc));
1057
1058 ret = ida_alloc(&gpio_ida, GFP_KERNEL);
1059 if (ret < 0)
1060 goto err_free_gdev;
1061 gdev->id = ret;
1062
1063 ret = dev_set_name(&gdev->dev, GPIOCHIP_NAME "%d", gdev->id);
1064 if (ret)
1065 goto err_free_ida;
1066
1067 if (gc->parent && gc->parent->driver)
1068 gdev->owner = gc->parent->driver->owner;
1069 else if (gc->owner)
1070 /* TODO: remove chip->owner */
1071 gdev->owner = gc->owner;
1072 else
1073 gdev->owner = THIS_MODULE;
1074
1075 ret = gpiochip_get_ngpios(gc, &gdev->dev);
1076 if (ret)
1077 goto err_free_dev_name;
1078
1079 gdev->descs = kcalloc(gc->ngpio, sizeof(*gdev->descs), GFP_KERNEL);
1080 if (!gdev->descs) {
1081 ret = -ENOMEM;
1082 goto err_free_dev_name;
1083 }
1084
1085 gdev->label = kstrdup_const(gc->label ?: "unknown", GFP_KERNEL);
1086 if (!gdev->label) {
1087 ret = -ENOMEM;
1088 goto err_free_descs;
1089 }
1090
1091 gdev->ngpio = gc->ngpio;
1092 gdev->can_sleep = gc->can_sleep;
1093
1094 scoped_guard(mutex, &gpio_devices_lock) {
1095 /*
1096 * TODO: this allocates a Linux GPIO number base in the global
1097 * GPIO numberspace for this chip. In the long run we want to
1098 * get *rid* of this numberspace and use only descriptors, but
1099 * it may be a pipe dream. It will not happen before we get rid
1100 * of the sysfs interface anyways.
1101 */
1102 base = gc->base;
1103 if (base < 0) {
1104 base = gpiochip_find_base_unlocked(gc->ngpio);
1105 if (base < 0) {
1106 ret = base;
1107 base = 0;
1108 goto err_free_label;
1109 }
1110
1111 /*
1112 * TODO: it should not be necessary to reflect the
1113 * assigned base outside of the GPIO subsystem. Go over
1114 * drivers and see if anyone makes use of this, else
1115 * drop this and assign a poison instead.
1116 */
1117 gc->base = base;
1118 } else {
1119 dev_warn(&gdev->dev,
1120 "Static allocation of GPIO base is deprecated, use dynamic allocation.\n");
1121 }
1122
1123 gdev->base = base;
1124
1125 ret = gpiodev_add_to_list_unlocked(gdev);
1126 if (ret) {
1127 chip_err(gc, "GPIO integer space overlap, cannot add chip\n");
1128 goto err_free_label;
1129 }
1130 }
1131
1132 rwlock_init(&gdev->line_state_lock);
1133 RAW_INIT_NOTIFIER_HEAD(&gdev->line_state_notifier);
1134 BLOCKING_INIT_NOTIFIER_HEAD(&gdev->device_notifier);
1135
1136 ret = init_srcu_struct(&gdev->srcu);
1137 if (ret)
1138 goto err_remove_from_list;
1139
1140 ret = init_srcu_struct(&gdev->desc_srcu);
1141 if (ret)
1142 goto err_cleanup_gdev_srcu;
1143
1144 #ifdef CONFIG_PINCTRL
1145 INIT_LIST_HEAD(&gdev->pin_ranges);
1146 #endif
1147
1148 if (gc->names)
1149 gpiochip_set_desc_names(gc);
1150
1151 ret = gpiochip_set_names(gc);
1152 if (ret)
1153 goto err_cleanup_desc_srcu;
1154
1155 ret = gpiochip_init_valid_mask(gc);
1156 if (ret)
1157 goto err_cleanup_desc_srcu;
1158
1159 for (desc_index = 0; desc_index < gc->ngpio; desc_index++) {
1160 struct gpio_desc *desc = &gdev->descs[desc_index];
1161
1162 desc->gdev = gdev;
1163
1164 /*
1165 * We would typically want to use gpiochip_get_direction() here
1166 * but we must not check the return value and bail-out as pin
1167 * controllers can have pins configured to alternate functions
1168 * and return -EINVAL. Also: there's no need to take the SRCU
1169 * lock here.
1170 */
1171 if (gc->get_direction && gpiochip_line_is_valid(gc, desc_index))
1172 assign_bit(FLAG_IS_OUT, &desc->flags,
1173 !gc->get_direction(gc, desc_index));
1174 else
1175 assign_bit(FLAG_IS_OUT,
1176 &desc->flags, !gc->direction_input);
1177 }
1178
1179 ret = of_gpiochip_add(gc);
1180 if (ret)
1181 goto err_free_valid_mask;
1182
1183 ret = gpiochip_add_pin_ranges(gc);
1184 if (ret)
1185 goto err_remove_of_chip;
1186
1187 acpi_gpiochip_add(gc);
1188
1189 machine_gpiochip_add(gc);
1190
1191 ret = gpiochip_irqchip_init_valid_mask(gc);
1192 if (ret)
1193 goto err_free_hogs;
1194
1195 ret = gpiochip_irqchip_init_hw(gc);
1196 if (ret)
1197 goto err_remove_irqchip_mask;
1198
1199 ret = gpiochip_add_irqchip(gc, lock_key, request_key);
1200 if (ret)
1201 goto err_remove_irqchip_mask;
1202
1203 /*
1204 * By first adding the chardev, and then adding the device,
1205 * we get a device node entry in sysfs under
1206 * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1207 * coldplug of device nodes and other udev business.
1208 * We can do this only if gpiolib has been initialized.
1209 * Otherwise, defer until later.
1210 */
1211 if (gpiolib_initialized) {
1212 ret = gpiochip_setup_dev(gdev);
1213 if (ret)
1214 goto err_remove_irqchip;
1215 }
1216 return 0;
1217
1218 err_remove_irqchip:
1219 gpiochip_irqchip_remove(gc);
1220 err_remove_irqchip_mask:
1221 gpiochip_irqchip_free_valid_mask(gc);
1222 err_free_hogs:
1223 gpiochip_free_hogs(gc);
1224 acpi_gpiochip_remove(gc);
1225 gpiochip_remove_pin_ranges(gc);
1226 err_remove_of_chip:
1227 of_gpiochip_remove(gc);
1228 err_free_valid_mask:
1229 gpiochip_free_valid_mask(gc);
1230 err_cleanup_desc_srcu:
1231 cleanup_srcu_struct(&gdev->desc_srcu);
1232 err_cleanup_gdev_srcu:
1233 cleanup_srcu_struct(&gdev->srcu);
1234 err_remove_from_list:
1235 scoped_guard(mutex, &gpio_devices_lock)
1236 list_del_rcu(&gdev->list);
1237 synchronize_srcu(&gpio_devices_srcu);
1238 if (gdev->dev.release) {
1239 /* release() has been registered by gpiochip_setup_dev() */
1240 gpio_device_put(gdev);
1241 goto err_print_message;
1242 }
1243 err_free_label:
1244 kfree_const(gdev->label);
1245 err_free_descs:
1246 kfree(gdev->descs);
1247 err_free_dev_name:
1248 kfree(dev_name(&gdev->dev));
1249 err_free_ida:
1250 ida_free(&gpio_ida, gdev->id);
1251 err_free_gdev:
1252 kfree(gdev);
1253 err_print_message:
1254 /* failures here can mean systems won't boot... */
1255 if (ret != -EPROBE_DEFER) {
1256 pr_err("%s: GPIOs %d..%d (%s) failed to register, %d\n", __func__,
1257 base, base + (int)gc->ngpio - 1,
1258 gc->label ? : "generic", ret);
1259 }
1260 return ret;
1261 }
1262 EXPORT_SYMBOL_GPL(gpiochip_add_data_with_key);
1263
1264 /**
1265 * gpiochip_remove() - unregister a gpio_chip
1266 * @gc: the chip to unregister
1267 *
1268 * A gpio_chip with any GPIOs still requested may not be removed.
1269 */
gpiochip_remove(struct gpio_chip * gc)1270 void gpiochip_remove(struct gpio_chip *gc)
1271 {
1272 struct gpio_device *gdev = gc->gpiodev;
1273
1274 /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1275 gpiochip_sysfs_unregister(gdev);
1276 gpiochip_free_hogs(gc);
1277 gpiochip_free_remaining_irqs(gc);
1278
1279 scoped_guard(mutex, &gpio_devices_lock)
1280 list_del_rcu(&gdev->list);
1281 synchronize_srcu(&gpio_devices_srcu);
1282
1283 /* Numb the device, cancelling all outstanding operations */
1284 rcu_assign_pointer(gdev->chip, NULL);
1285 synchronize_srcu(&gdev->srcu);
1286 gpiochip_irqchip_remove(gc);
1287 acpi_gpiochip_remove(gc);
1288 of_gpiochip_remove(gc);
1289 gpiochip_remove_pin_ranges(gc);
1290 gpiochip_free_valid_mask(gc);
1291 /*
1292 * We accept no more calls into the driver from this point, so
1293 * NULL the driver data pointer.
1294 */
1295 gpiochip_set_data(gc, NULL);
1296
1297 /*
1298 * The gpiochip side puts its use of the device to rest here:
1299 * if there are no userspace clients, the chardev and device will
1300 * be removed, else it will be dangling until the last user is
1301 * gone.
1302 */
1303 gcdev_unregister(gdev);
1304 gpio_device_put(gdev);
1305 }
1306 EXPORT_SYMBOL_GPL(gpiochip_remove);
1307
1308 /**
1309 * gpio_device_find() - find a specific GPIO device
1310 * @data: data to pass to match function
1311 * @match: Callback function to check gpio_chip
1312 *
1313 * Returns:
1314 * New reference to struct gpio_device.
1315 *
1316 * Similar to bus_find_device(). It returns a reference to a gpio_device as
1317 * determined by a user supplied @match callback. The callback should return
1318 * 0 if the device doesn't match and non-zero if it does. If the callback
1319 * returns non-zero, this function will return to the caller and not iterate
1320 * over any more gpio_devices.
1321 *
1322 * The callback takes the GPIO chip structure as argument. During the execution
1323 * of the callback function the chip is protected from being freed. TODO: This
1324 * actually has yet to be implemented.
1325 *
1326 * If the function returns non-NULL, the returned reference must be freed by
1327 * the caller using gpio_device_put().
1328 */
gpio_device_find(const void * data,int (* match)(struct gpio_chip * gc,const void * data))1329 struct gpio_device *gpio_device_find(const void *data,
1330 int (*match)(struct gpio_chip *gc,
1331 const void *data))
1332 {
1333 struct gpio_device *gdev;
1334 struct gpio_chip *gc;
1335
1336 might_sleep();
1337
1338 guard(srcu)(&gpio_devices_srcu);
1339
1340 list_for_each_entry_srcu(gdev, &gpio_devices, list,
1341 srcu_read_lock_held(&gpio_devices_srcu)) {
1342 if (!device_is_registered(&gdev->dev))
1343 continue;
1344
1345 guard(srcu)(&gdev->srcu);
1346
1347 gc = srcu_dereference(gdev->chip, &gdev->srcu);
1348
1349 if (gc && match(gc, data))
1350 return gpio_device_get(gdev);
1351 }
1352
1353 return NULL;
1354 }
1355 EXPORT_SYMBOL_GPL(gpio_device_find);
1356
gpio_chip_match_by_label(struct gpio_chip * gc,const void * label)1357 static int gpio_chip_match_by_label(struct gpio_chip *gc, const void *label)
1358 {
1359 return gc->label && !strcmp(gc->label, label);
1360 }
1361
1362 /**
1363 * gpio_device_find_by_label() - wrapper around gpio_device_find() finding the
1364 * GPIO device by its backing chip's label
1365 * @label: Label to lookup
1366 *
1367 * Returns:
1368 * Reference to the GPIO device or NULL. Reference must be released with
1369 * gpio_device_put().
1370 */
gpio_device_find_by_label(const char * label)1371 struct gpio_device *gpio_device_find_by_label(const char *label)
1372 {
1373 return gpio_device_find((void *)label, gpio_chip_match_by_label);
1374 }
1375 EXPORT_SYMBOL_GPL(gpio_device_find_by_label);
1376
gpio_chip_match_by_fwnode(struct gpio_chip * gc,const void * fwnode)1377 static int gpio_chip_match_by_fwnode(struct gpio_chip *gc, const void *fwnode)
1378 {
1379 return device_match_fwnode(&gc->gpiodev->dev, fwnode);
1380 }
1381
1382 /**
1383 * gpio_device_find_by_fwnode() - wrapper around gpio_device_find() finding
1384 * the GPIO device by its fwnode
1385 * @fwnode: Firmware node to lookup
1386 *
1387 * Returns:
1388 * Reference to the GPIO device or NULL. Reference must be released with
1389 * gpio_device_put().
1390 */
gpio_device_find_by_fwnode(const struct fwnode_handle * fwnode)1391 struct gpio_device *gpio_device_find_by_fwnode(const struct fwnode_handle *fwnode)
1392 {
1393 return gpio_device_find((void *)fwnode, gpio_chip_match_by_fwnode);
1394 }
1395 EXPORT_SYMBOL_GPL(gpio_device_find_by_fwnode);
1396
1397 /**
1398 * gpio_device_get() - Increase the reference count of this GPIO device
1399 * @gdev: GPIO device to increase the refcount for
1400 *
1401 * Returns:
1402 * Pointer to @gdev.
1403 */
gpio_device_get(struct gpio_device * gdev)1404 struct gpio_device *gpio_device_get(struct gpio_device *gdev)
1405 {
1406 return to_gpio_device(get_device(&gdev->dev));
1407 }
1408 EXPORT_SYMBOL_GPL(gpio_device_get);
1409
1410 /**
1411 * gpio_device_put() - Decrease the reference count of this GPIO device and
1412 * possibly free all resources associated with it.
1413 * @gdev: GPIO device to decrease the reference count for
1414 */
gpio_device_put(struct gpio_device * gdev)1415 void gpio_device_put(struct gpio_device *gdev)
1416 {
1417 put_device(&gdev->dev);
1418 }
1419 EXPORT_SYMBOL_GPL(gpio_device_put);
1420
1421 /**
1422 * gpio_device_to_device() - Retrieve the address of the underlying struct
1423 * device.
1424 * @gdev: GPIO device for which to return the address.
1425 *
1426 * This does not increase the reference count of the GPIO device nor the
1427 * underlying struct device.
1428 *
1429 * Returns:
1430 * Address of struct device backing this GPIO device.
1431 */
gpio_device_to_device(struct gpio_device * gdev)1432 struct device *gpio_device_to_device(struct gpio_device *gdev)
1433 {
1434 return &gdev->dev;
1435 }
1436 EXPORT_SYMBOL_GPL(gpio_device_to_device);
1437
1438 #ifdef CONFIG_GPIOLIB_IRQCHIP
1439
1440 /*
1441 * The following is irqchip helper code for gpiochips.
1442 */
1443
gpiochip_irqchip_init_hw(struct gpio_chip * gc)1444 static int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
1445 {
1446 struct gpio_irq_chip *girq = &gc->irq;
1447
1448 if (!girq->init_hw)
1449 return 0;
1450
1451 return girq->init_hw(gc);
1452 }
1453
gpiochip_irqchip_init_valid_mask(struct gpio_chip * gc)1454 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
1455 {
1456 struct gpio_irq_chip *girq = &gc->irq;
1457
1458 if (!girq->init_valid_mask)
1459 return 0;
1460
1461 girq->valid_mask = gpiochip_allocate_mask(gc);
1462 if (!girq->valid_mask)
1463 return -ENOMEM;
1464
1465 girq->init_valid_mask(gc, girq->valid_mask, gc->ngpio);
1466
1467 return 0;
1468 }
1469
gpiochip_irqchip_free_valid_mask(struct gpio_chip * gc)1470 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc)
1471 {
1472 gpiochip_free_mask(&gc->irq.valid_mask);
1473 }
1474
gpiochip_irqchip_irq_valid(const struct gpio_chip * gc,unsigned int offset)1475 static bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gc,
1476 unsigned int offset)
1477 {
1478 if (!gpiochip_line_is_valid(gc, offset))
1479 return false;
1480 /* No mask means all valid */
1481 if (likely(!gc->irq.valid_mask))
1482 return true;
1483 return test_bit(offset, gc->irq.valid_mask);
1484 }
1485
1486 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
1487
1488 /**
1489 * gpiochip_set_hierarchical_irqchip() - connects a hierarchical irqchip
1490 * to a gpiochip
1491 * @gc: the gpiochip to set the irqchip hierarchical handler to
1492 * @irqchip: the irqchip to handle this level of the hierarchy, the interrupt
1493 * will then percolate up to the parent
1494 */
gpiochip_set_hierarchical_irqchip(struct gpio_chip * gc,struct irq_chip * irqchip)1495 static void gpiochip_set_hierarchical_irqchip(struct gpio_chip *gc,
1496 struct irq_chip *irqchip)
1497 {
1498 /* DT will deal with mapping each IRQ as we go along */
1499 if (is_of_node(gc->irq.fwnode))
1500 return;
1501
1502 /*
1503 * This is for legacy and boardfile "irqchip" fwnodes: allocate
1504 * irqs upfront instead of dynamically since we don't have the
1505 * dynamic type of allocation that hardware description languages
1506 * provide. Once all GPIO drivers using board files are gone from
1507 * the kernel we can delete this code, but for a transitional period
1508 * it is necessary to keep this around.
1509 */
1510 if (is_fwnode_irqchip(gc->irq.fwnode)) {
1511 int i;
1512 int ret;
1513
1514 for (i = 0; i < gc->ngpio; i++) {
1515 struct irq_fwspec fwspec;
1516 unsigned int parent_hwirq;
1517 unsigned int parent_type;
1518 struct gpio_irq_chip *girq = &gc->irq;
1519
1520 /*
1521 * We call the child to parent translation function
1522 * only to check if the child IRQ is valid or not.
1523 * Just pick the rising edge type here as that is what
1524 * we likely need to support.
1525 */
1526 ret = girq->child_to_parent_hwirq(gc, i,
1527 IRQ_TYPE_EDGE_RISING,
1528 &parent_hwirq,
1529 &parent_type);
1530 if (ret) {
1531 chip_err(gc, "skip set-up on hwirq %d\n",
1532 i);
1533 continue;
1534 }
1535
1536 fwspec.fwnode = gc->irq.fwnode;
1537 /* This is the hwirq for the GPIO line side of things */
1538 fwspec.param[0] = girq->child_offset_to_irq(gc, i);
1539 /* Just pick something */
1540 fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
1541 fwspec.param_count = 2;
1542 ret = irq_domain_alloc_irqs(gc->irq.domain, 1,
1543 NUMA_NO_NODE, &fwspec);
1544 if (ret < 0) {
1545 chip_err(gc,
1546 "can not allocate irq for GPIO line %d parent hwirq %d in hierarchy domain: %d\n",
1547 i, parent_hwirq,
1548 ret);
1549 }
1550 }
1551 }
1552
1553 chip_err(gc, "%s unknown fwnode type proceed anyway\n", __func__);
1554
1555 return;
1556 }
1557
gpiochip_hierarchy_irq_domain_translate(struct irq_domain * d,struct irq_fwspec * fwspec,unsigned long * hwirq,unsigned int * type)1558 static int gpiochip_hierarchy_irq_domain_translate(struct irq_domain *d,
1559 struct irq_fwspec *fwspec,
1560 unsigned long *hwirq,
1561 unsigned int *type)
1562 {
1563 /* We support standard DT translation */
1564 if (is_of_node(fwspec->fwnode))
1565 return irq_domain_translate_twothreecell(d, fwspec, hwirq, type);
1566
1567 /* This is for board files and others not using DT */
1568 if (is_fwnode_irqchip(fwspec->fwnode)) {
1569 int ret;
1570
1571 ret = irq_domain_translate_twocell(d, fwspec, hwirq, type);
1572 if (ret)
1573 return ret;
1574 WARN_ON(*type == IRQ_TYPE_NONE);
1575 return 0;
1576 }
1577 return -EINVAL;
1578 }
1579
gpiochip_hierarchy_irq_domain_alloc(struct irq_domain * d,unsigned int irq,unsigned int nr_irqs,void * data)1580 static int gpiochip_hierarchy_irq_domain_alloc(struct irq_domain *d,
1581 unsigned int irq,
1582 unsigned int nr_irqs,
1583 void *data)
1584 {
1585 struct gpio_chip *gc = d->host_data;
1586 irq_hw_number_t hwirq;
1587 unsigned int type = IRQ_TYPE_NONE;
1588 struct irq_fwspec *fwspec = data;
1589 union gpio_irq_fwspec gpio_parent_fwspec = {};
1590 unsigned int parent_hwirq;
1591 unsigned int parent_type;
1592 struct gpio_irq_chip *girq = &gc->irq;
1593 int ret;
1594
1595 /*
1596 * The nr_irqs parameter is always one except for PCI multi-MSI
1597 * so this should not happen.
1598 */
1599 WARN_ON(nr_irqs != 1);
1600
1601 ret = gc->irq.child_irq_domain_ops.translate(d, fwspec, &hwirq, &type);
1602 if (ret)
1603 return ret;
1604
1605 chip_dbg(gc, "allocate IRQ %d, hwirq %lu\n", irq, hwirq);
1606
1607 ret = girq->child_to_parent_hwirq(gc, hwirq, type,
1608 &parent_hwirq, &parent_type);
1609 if (ret) {
1610 chip_err(gc, "can't look up hwirq %lu\n", hwirq);
1611 return ret;
1612 }
1613 chip_dbg(gc, "found parent hwirq %u\n", parent_hwirq);
1614
1615 /*
1616 * We set handle_bad_irq because the .set_type() should
1617 * always be invoked and set the right type of handler.
1618 */
1619 irq_domain_set_info(d,
1620 irq,
1621 hwirq,
1622 gc->irq.chip,
1623 gc,
1624 girq->handler,
1625 NULL, NULL);
1626 irq_set_probe(irq);
1627
1628 /* This parent only handles asserted level IRQs */
1629 ret = girq->populate_parent_alloc_arg(gc, &gpio_parent_fwspec,
1630 parent_hwirq, parent_type);
1631 if (ret)
1632 return ret;
1633
1634 chip_dbg(gc, "alloc_irqs_parent for %d parent hwirq %d\n",
1635 irq, parent_hwirq);
1636 irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
1637 ret = irq_domain_alloc_irqs_parent(d, irq, 1, &gpio_parent_fwspec);
1638 /*
1639 * If the parent irqdomain is msi, the interrupts have already
1640 * been allocated, so the EEXIST is good.
1641 */
1642 if (irq_domain_is_msi(d->parent) && (ret == -EEXIST))
1643 ret = 0;
1644 if (ret)
1645 chip_err(gc,
1646 "failed to allocate parent hwirq %d for hwirq %lu\n",
1647 parent_hwirq, hwirq);
1648
1649 return ret;
1650 }
1651
gpiochip_child_offset_to_irq_noop(struct gpio_chip * gc,unsigned int offset)1652 static unsigned int gpiochip_child_offset_to_irq_noop(struct gpio_chip *gc,
1653 unsigned int offset)
1654 {
1655 return offset;
1656 }
1657
1658 /**
1659 * gpiochip_irq_domain_activate() - Lock a GPIO to be used as an IRQ
1660 * @domain: The IRQ domain used by this IRQ chip
1661 * @data: Outermost irq_data associated with the IRQ
1662 * @reserve: If set, only reserve an interrupt vector instead of assigning one
1663 *
1664 * This function is a wrapper that calls gpiochip_lock_as_irq() and is to be
1665 * used as the activate function for the &struct irq_domain_ops. The host_data
1666 * for the IRQ domain must be the &struct gpio_chip.
1667 *
1668 * Returns:
1669 * 0 on success, or negative errno on failure.
1670 */
gpiochip_irq_domain_activate(struct irq_domain * domain,struct irq_data * data,bool reserve)1671 static int gpiochip_irq_domain_activate(struct irq_domain *domain,
1672 struct irq_data *data, bool reserve)
1673 {
1674 struct gpio_chip *gc = domain->host_data;
1675 unsigned int hwirq = irqd_to_hwirq(data);
1676
1677 return gpiochip_lock_as_irq(gc, hwirq);
1678 }
1679
1680 /**
1681 * gpiochip_irq_domain_deactivate() - Unlock a GPIO used as an IRQ
1682 * @domain: The IRQ domain used by this IRQ chip
1683 * @data: Outermost irq_data associated with the IRQ
1684 *
1685 * This function is a wrapper that will call gpiochip_unlock_as_irq() and is to
1686 * be used as the deactivate function for the &struct irq_domain_ops. The
1687 * host_data for the IRQ domain must be the &struct gpio_chip.
1688 */
gpiochip_irq_domain_deactivate(struct irq_domain * domain,struct irq_data * data)1689 static void gpiochip_irq_domain_deactivate(struct irq_domain *domain,
1690 struct irq_data *data)
1691 {
1692 struct gpio_chip *gc = domain->host_data;
1693 unsigned int hwirq = irqd_to_hwirq(data);
1694
1695 return gpiochip_unlock_as_irq(gc, hwirq);
1696 }
1697
gpiochip_hierarchy_setup_domain_ops(struct irq_domain_ops * ops)1698 static void gpiochip_hierarchy_setup_domain_ops(struct irq_domain_ops *ops)
1699 {
1700 ops->activate = gpiochip_irq_domain_activate;
1701 ops->deactivate = gpiochip_irq_domain_deactivate;
1702 ops->alloc = gpiochip_hierarchy_irq_domain_alloc;
1703
1704 /*
1705 * We only allow overriding the translate() and free() functions for
1706 * hierarchical chips, and this should only be done if the user
1707 * really need something other than 1:1 translation for translate()
1708 * callback and free if user wants to free up any resources which
1709 * were allocated during callbacks, for example populate_parent_alloc_arg.
1710 */
1711 if (!ops->translate)
1712 ops->translate = gpiochip_hierarchy_irq_domain_translate;
1713 if (!ops->free)
1714 ops->free = irq_domain_free_irqs_common;
1715 }
1716
gpiochip_hierarchy_create_domain(struct gpio_chip * gc)1717 static struct irq_domain *gpiochip_hierarchy_create_domain(struct gpio_chip *gc)
1718 {
1719 struct irq_domain *domain;
1720
1721 if (!gc->irq.child_to_parent_hwirq ||
1722 !gc->irq.fwnode) {
1723 chip_err(gc, "missing irqdomain vital data\n");
1724 return ERR_PTR(-EINVAL);
1725 }
1726
1727 if (!gc->irq.child_offset_to_irq)
1728 gc->irq.child_offset_to_irq = gpiochip_child_offset_to_irq_noop;
1729
1730 if (!gc->irq.populate_parent_alloc_arg)
1731 gc->irq.populate_parent_alloc_arg =
1732 gpiochip_populate_parent_fwspec_twocell;
1733
1734 gpiochip_hierarchy_setup_domain_ops(&gc->irq.child_irq_domain_ops);
1735
1736 domain = irq_domain_create_hierarchy(
1737 gc->irq.parent_domain,
1738 0,
1739 gc->ngpio,
1740 gc->irq.fwnode,
1741 &gc->irq.child_irq_domain_ops,
1742 gc);
1743
1744 if (!domain)
1745 return ERR_PTR(-ENOMEM);
1746
1747 gpiochip_set_hierarchical_irqchip(gc, gc->irq.chip);
1748
1749 return domain;
1750 }
1751
gpiochip_hierarchy_is_hierarchical(struct gpio_chip * gc)1752 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
1753 {
1754 return !!gc->irq.parent_domain;
1755 }
1756
gpiochip_populate_parent_fwspec_twocell(struct gpio_chip * gc,union gpio_irq_fwspec * gfwspec,unsigned int parent_hwirq,unsigned int parent_type)1757 int gpiochip_populate_parent_fwspec_twocell(struct gpio_chip *gc,
1758 union gpio_irq_fwspec *gfwspec,
1759 unsigned int parent_hwirq,
1760 unsigned int parent_type)
1761 {
1762 struct irq_fwspec *fwspec = &gfwspec->fwspec;
1763
1764 fwspec->fwnode = gc->irq.parent_domain->fwnode;
1765 fwspec->param_count = 2;
1766 fwspec->param[0] = parent_hwirq;
1767 fwspec->param[1] = parent_type;
1768
1769 return 0;
1770 }
1771 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_twocell);
1772
gpiochip_populate_parent_fwspec_fourcell(struct gpio_chip * gc,union gpio_irq_fwspec * gfwspec,unsigned int parent_hwirq,unsigned int parent_type)1773 int gpiochip_populate_parent_fwspec_fourcell(struct gpio_chip *gc,
1774 union gpio_irq_fwspec *gfwspec,
1775 unsigned int parent_hwirq,
1776 unsigned int parent_type)
1777 {
1778 struct irq_fwspec *fwspec = &gfwspec->fwspec;
1779
1780 fwspec->fwnode = gc->irq.parent_domain->fwnode;
1781 fwspec->param_count = 4;
1782 fwspec->param[0] = 0;
1783 fwspec->param[1] = parent_hwirq;
1784 fwspec->param[2] = 0;
1785 fwspec->param[3] = parent_type;
1786
1787 return 0;
1788 }
1789 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_fourcell);
1790
1791 #else
1792
gpiochip_hierarchy_create_domain(struct gpio_chip * gc)1793 static struct irq_domain *gpiochip_hierarchy_create_domain(struct gpio_chip *gc)
1794 {
1795 return ERR_PTR(-EINVAL);
1796 }
1797
gpiochip_hierarchy_is_hierarchical(struct gpio_chip * gc)1798 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
1799 {
1800 return false;
1801 }
1802
1803 #endif /* CONFIG_IRQ_DOMAIN_HIERARCHY */
1804
1805 /**
1806 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
1807 * @d: the irqdomain used by this irqchip
1808 * @irq: the global irq number used by this GPIO irqchip irq
1809 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
1810 *
1811 * This function will set up the mapping for a certain IRQ line on a
1812 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
1813 * stored inside the gpiochip.
1814 *
1815 * Returns:
1816 * 0 on success, or negative errno on failure.
1817 */
gpiochip_irq_map(struct irq_domain * d,unsigned int irq,irq_hw_number_t hwirq)1818 static int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
1819 irq_hw_number_t hwirq)
1820 {
1821 struct gpio_chip *gc = d->host_data;
1822 int ret = 0;
1823
1824 if (!gpiochip_irqchip_irq_valid(gc, hwirq))
1825 return -ENXIO;
1826
1827 irq_set_chip_data(irq, gc);
1828 /*
1829 * This lock class tells lockdep that GPIO irqs are in a different
1830 * category than their parents, so it won't report false recursion.
1831 */
1832 irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
1833 irq_set_chip_and_handler(irq, gc->irq.chip, gc->irq.handler);
1834 /* Chips that use nested thread handlers have them marked */
1835 if (gc->irq.threaded)
1836 irq_set_nested_thread(irq, 1);
1837 irq_set_noprobe(irq);
1838
1839 if (gc->irq.num_parents == 1)
1840 ret = irq_set_parent(irq, gc->irq.parents[0]);
1841 else if (gc->irq.map)
1842 ret = irq_set_parent(irq, gc->irq.map[hwirq]);
1843
1844 if (ret < 0)
1845 return ret;
1846
1847 /*
1848 * No set-up of the hardware will happen if IRQ_TYPE_NONE
1849 * is passed as default type.
1850 */
1851 if (gc->irq.default_type != IRQ_TYPE_NONE)
1852 irq_set_irq_type(irq, gc->irq.default_type);
1853
1854 return 0;
1855 }
1856
gpiochip_irq_unmap(struct irq_domain * d,unsigned int irq)1857 static void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
1858 {
1859 struct gpio_chip *gc = d->host_data;
1860
1861 if (gc->irq.threaded)
1862 irq_set_nested_thread(irq, 0);
1863 irq_set_chip_and_handler(irq, NULL, NULL);
1864 irq_set_chip_data(irq, NULL);
1865 }
1866
gpiochip_irq_select(struct irq_domain * d,struct irq_fwspec * fwspec,enum irq_domain_bus_token bus_token)1867 static int gpiochip_irq_select(struct irq_domain *d, struct irq_fwspec *fwspec,
1868 enum irq_domain_bus_token bus_token)
1869 {
1870 struct fwnode_handle *fwnode = fwspec->fwnode;
1871 struct gpio_chip *gc = d->host_data;
1872 unsigned int index = fwspec->param[0];
1873
1874 if (fwspec->param_count == 3 && is_of_node(fwnode))
1875 return of_gpiochip_instance_match(gc, index);
1876
1877 /* Fallback for twocells */
1878 return (fwnode && (d->fwnode == fwnode) && (d->bus_token == bus_token));
1879 }
1880
1881 static const struct irq_domain_ops gpiochip_domain_ops = {
1882 .map = gpiochip_irq_map,
1883 .unmap = gpiochip_irq_unmap,
1884 .select = gpiochip_irq_select,
1885 /* Virtually all GPIO irqchips are twocell:ed */
1886 .xlate = irq_domain_xlate_twothreecell,
1887 };
1888
gpiochip_simple_create_domain(struct gpio_chip * gc)1889 static struct irq_domain *gpiochip_simple_create_domain(struct gpio_chip *gc)
1890 {
1891 struct fwnode_handle *fwnode = dev_fwnode(&gc->gpiodev->dev);
1892 struct irq_domain *domain;
1893
1894 domain = irq_domain_create_simple(fwnode, gc->ngpio, gc->irq.first,
1895 &gpiochip_domain_ops, gc);
1896 if (!domain)
1897 return ERR_PTR(-EINVAL);
1898
1899 return domain;
1900 }
1901
gpiochip_to_irq(struct gpio_chip * gc,unsigned int offset)1902 static int gpiochip_to_irq(struct gpio_chip *gc, unsigned int offset)
1903 {
1904 struct irq_domain *domain = gc->irq.domain;
1905
1906 /*
1907 * Avoid race condition with other code, which tries to lookup
1908 * an IRQ before the irqchip has been properly registered,
1909 * i.e. while gpiochip is still being brought up.
1910 */
1911 if (!gc->irq.initialized)
1912 return -EPROBE_DEFER;
1913
1914 if (!gpiochip_irqchip_irq_valid(gc, offset))
1915 return -ENXIO;
1916
1917 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
1918 if (irq_domain_is_hierarchy(domain)) {
1919 struct irq_fwspec spec;
1920
1921 spec.fwnode = domain->fwnode;
1922 spec.param_count = 2;
1923 spec.param[0] = gc->irq.child_offset_to_irq(gc, offset);
1924 spec.param[1] = IRQ_TYPE_NONE;
1925
1926 return irq_create_fwspec_mapping(&spec);
1927 }
1928 #endif
1929
1930 return irq_create_mapping(domain, offset);
1931 }
1932
gpiochip_irq_reqres(struct irq_data * d)1933 int gpiochip_irq_reqres(struct irq_data *d)
1934 {
1935 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1936 unsigned int hwirq = irqd_to_hwirq(d);
1937
1938 return gpiochip_reqres_irq(gc, hwirq);
1939 }
1940 EXPORT_SYMBOL(gpiochip_irq_reqres);
1941
gpiochip_irq_relres(struct irq_data * d)1942 void gpiochip_irq_relres(struct irq_data *d)
1943 {
1944 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1945 unsigned int hwirq = irqd_to_hwirq(d);
1946
1947 gpiochip_relres_irq(gc, hwirq);
1948 }
1949 EXPORT_SYMBOL(gpiochip_irq_relres);
1950
gpiochip_irq_mask(struct irq_data * d)1951 static void gpiochip_irq_mask(struct irq_data *d)
1952 {
1953 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1954 unsigned int hwirq = irqd_to_hwirq(d);
1955
1956 if (gc->irq.irq_mask)
1957 gc->irq.irq_mask(d);
1958 gpiochip_disable_irq(gc, hwirq);
1959 }
1960
gpiochip_irq_unmask(struct irq_data * d)1961 static void gpiochip_irq_unmask(struct irq_data *d)
1962 {
1963 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1964 unsigned int hwirq = irqd_to_hwirq(d);
1965
1966 gpiochip_enable_irq(gc, hwirq);
1967 if (gc->irq.irq_unmask)
1968 gc->irq.irq_unmask(d);
1969 }
1970
gpiochip_irq_enable(struct irq_data * d)1971 static void gpiochip_irq_enable(struct irq_data *d)
1972 {
1973 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1974 unsigned int hwirq = irqd_to_hwirq(d);
1975
1976 gpiochip_enable_irq(gc, hwirq);
1977 gc->irq.irq_enable(d);
1978 }
1979
gpiochip_irq_disable(struct irq_data * d)1980 static void gpiochip_irq_disable(struct irq_data *d)
1981 {
1982 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1983 unsigned int hwirq = irqd_to_hwirq(d);
1984
1985 gc->irq.irq_disable(d);
1986 gpiochip_disable_irq(gc, hwirq);
1987 }
1988
gpiochip_set_irq_hooks(struct gpio_chip * gc)1989 static void gpiochip_set_irq_hooks(struct gpio_chip *gc)
1990 {
1991 struct irq_chip *irqchip = gc->irq.chip;
1992
1993 if (irqchip->flags & IRQCHIP_IMMUTABLE)
1994 return;
1995
1996 chip_warn(gc, "not an immutable chip, please consider fixing it!\n");
1997
1998 if (!irqchip->irq_request_resources &&
1999 !irqchip->irq_release_resources) {
2000 irqchip->irq_request_resources = gpiochip_irq_reqres;
2001 irqchip->irq_release_resources = gpiochip_irq_relres;
2002 }
2003 if (WARN_ON(gc->irq.irq_enable))
2004 return;
2005 /* Check if the irqchip already has this hook... */
2006 if (irqchip->irq_enable == gpiochip_irq_enable ||
2007 irqchip->irq_mask == gpiochip_irq_mask) {
2008 /*
2009 * ...and if so, give a gentle warning that this is bad
2010 * practice.
2011 */
2012 chip_info(gc,
2013 "detected irqchip that is shared with multiple gpiochips: please fix the driver.\n");
2014 return;
2015 }
2016
2017 if (irqchip->irq_disable) {
2018 gc->irq.irq_disable = irqchip->irq_disable;
2019 irqchip->irq_disable = gpiochip_irq_disable;
2020 } else {
2021 gc->irq.irq_mask = irqchip->irq_mask;
2022 irqchip->irq_mask = gpiochip_irq_mask;
2023 }
2024
2025 if (irqchip->irq_enable) {
2026 gc->irq.irq_enable = irqchip->irq_enable;
2027 irqchip->irq_enable = gpiochip_irq_enable;
2028 } else {
2029 gc->irq.irq_unmask = irqchip->irq_unmask;
2030 irqchip->irq_unmask = gpiochip_irq_unmask;
2031 }
2032 }
2033
gpiochip_irqchip_add_allocated_domain(struct gpio_chip * gc,struct irq_domain * domain,bool allocated_externally)2034 static int gpiochip_irqchip_add_allocated_domain(struct gpio_chip *gc,
2035 struct irq_domain *domain,
2036 bool allocated_externally)
2037 {
2038 if (!domain)
2039 return -EINVAL;
2040
2041 if (gc->to_irq)
2042 chip_warn(gc, "to_irq is redefined in %s and you shouldn't rely on it\n", __func__);
2043
2044 gc->to_irq = gpiochip_to_irq;
2045 gc->irq.domain = domain;
2046 gc->irq.domain_is_allocated_externally = allocated_externally;
2047
2048 /*
2049 * Using barrier() here to prevent compiler from reordering
2050 * gc->irq.initialized before adding irqdomain.
2051 */
2052 barrier();
2053
2054 gc->irq.initialized = true;
2055
2056 return 0;
2057 }
2058
2059 /**
2060 * gpiochip_add_irqchip() - adds an IRQ chip to a GPIO chip
2061 * @gc: the GPIO chip to add the IRQ chip to
2062 * @lock_key: lockdep class for IRQ lock
2063 * @request_key: lockdep class for IRQ request
2064 *
2065 * Returns:
2066 * 0 on success, or a negative errno on failure.
2067 */
gpiochip_add_irqchip(struct gpio_chip * gc,struct lock_class_key * lock_key,struct lock_class_key * request_key)2068 static int gpiochip_add_irqchip(struct gpio_chip *gc,
2069 struct lock_class_key *lock_key,
2070 struct lock_class_key *request_key)
2071 {
2072 struct fwnode_handle *fwnode = dev_fwnode(&gc->gpiodev->dev);
2073 struct irq_chip *irqchip = gc->irq.chip;
2074 struct irq_domain *domain;
2075 unsigned int type;
2076 unsigned int i;
2077 int ret;
2078
2079 if (!irqchip)
2080 return 0;
2081
2082 if (gc->irq.parent_handler && gc->can_sleep) {
2083 chip_err(gc, "you cannot have chained interrupts on a chip that may sleep\n");
2084 return -EINVAL;
2085 }
2086
2087 type = gc->irq.default_type;
2088
2089 /*
2090 * Specifying a default trigger is a terrible idea if DT or ACPI is
2091 * used to configure the interrupts, as you may end up with
2092 * conflicting triggers. Tell the user, and reset to NONE.
2093 */
2094 if (WARN(fwnode && type != IRQ_TYPE_NONE,
2095 "%pfw: Ignoring %u default trigger\n", fwnode, type))
2096 type = IRQ_TYPE_NONE;
2097
2098 gc->irq.default_type = type;
2099 gc->irq.lock_key = lock_key;
2100 gc->irq.request_key = request_key;
2101
2102 /* If a parent irqdomain is provided, let's build a hierarchy */
2103 if (gpiochip_hierarchy_is_hierarchical(gc)) {
2104 domain = gpiochip_hierarchy_create_domain(gc);
2105 } else {
2106 domain = gpiochip_simple_create_domain(gc);
2107 }
2108 if (IS_ERR(domain))
2109 return PTR_ERR(domain);
2110
2111 if (gc->irq.parent_handler) {
2112 for (i = 0; i < gc->irq.num_parents; i++) {
2113 void *data;
2114
2115 if (gc->irq.per_parent_data)
2116 data = gc->irq.parent_handler_data_array[i];
2117 else
2118 data = gc->irq.parent_handler_data ?: gc;
2119
2120 /*
2121 * The parent IRQ chip is already using the chip_data
2122 * for this IRQ chip, so our callbacks simply use the
2123 * handler_data.
2124 */
2125 irq_set_chained_handler_and_data(gc->irq.parents[i],
2126 gc->irq.parent_handler,
2127 data);
2128 }
2129 }
2130
2131 gpiochip_set_irq_hooks(gc);
2132
2133 ret = gpiochip_irqchip_add_allocated_domain(gc, domain, false);
2134 if (ret)
2135 return ret;
2136
2137 acpi_gpiochip_request_interrupts(gc);
2138
2139 return 0;
2140 }
2141
2142 /**
2143 * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
2144 * @gc: the gpiochip to remove the irqchip from
2145 *
2146 * This is called only from gpiochip_remove()
2147 */
gpiochip_irqchip_remove(struct gpio_chip * gc)2148 static void gpiochip_irqchip_remove(struct gpio_chip *gc)
2149 {
2150 struct irq_chip *irqchip = gc->irq.chip;
2151 unsigned int offset;
2152
2153 acpi_gpiochip_free_interrupts(gc);
2154
2155 if (irqchip && gc->irq.parent_handler) {
2156 struct gpio_irq_chip *irq = &gc->irq;
2157 unsigned int i;
2158
2159 for (i = 0; i < irq->num_parents; i++)
2160 irq_set_chained_handler_and_data(irq->parents[i],
2161 NULL, NULL);
2162 }
2163
2164 /* Remove all IRQ mappings and delete the domain */
2165 if (!gc->irq.domain_is_allocated_externally && gc->irq.domain) {
2166 unsigned int irq;
2167
2168 for (offset = 0; offset < gc->ngpio; offset++) {
2169 if (!gpiochip_irqchip_irq_valid(gc, offset))
2170 continue;
2171
2172 irq = irq_find_mapping(gc->irq.domain, offset);
2173 irq_dispose_mapping(irq);
2174 }
2175
2176 irq_domain_remove(gc->irq.domain);
2177 }
2178
2179 if (irqchip && !(irqchip->flags & IRQCHIP_IMMUTABLE)) {
2180 if (irqchip->irq_request_resources == gpiochip_irq_reqres) {
2181 irqchip->irq_request_resources = NULL;
2182 irqchip->irq_release_resources = NULL;
2183 }
2184 if (irqchip->irq_enable == gpiochip_irq_enable) {
2185 irqchip->irq_enable = gc->irq.irq_enable;
2186 irqchip->irq_disable = gc->irq.irq_disable;
2187 }
2188 }
2189 gc->irq.irq_enable = NULL;
2190 gc->irq.irq_disable = NULL;
2191 gc->irq.chip = NULL;
2192
2193 gpiochip_irqchip_free_valid_mask(gc);
2194 }
2195
2196 /**
2197 * gpiochip_irqchip_add_domain() - adds an irqdomain to a gpiochip
2198 * @gc: the gpiochip to add the irqchip to
2199 * @domain: the irqdomain to add to the gpiochip
2200 *
2201 * This function adds an IRQ domain to the gpiochip.
2202 *
2203 * Returns:
2204 * 0 on success, or negative errno on failure.
2205 */
gpiochip_irqchip_add_domain(struct gpio_chip * gc,struct irq_domain * domain)2206 int gpiochip_irqchip_add_domain(struct gpio_chip *gc,
2207 struct irq_domain *domain)
2208 {
2209 return gpiochip_irqchip_add_allocated_domain(gc, domain, true);
2210 }
2211 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_domain);
2212
2213 #else /* CONFIG_GPIOLIB_IRQCHIP */
2214
gpiochip_add_irqchip(struct gpio_chip * gc,struct lock_class_key * lock_key,struct lock_class_key * request_key)2215 static inline int gpiochip_add_irqchip(struct gpio_chip *gc,
2216 struct lock_class_key *lock_key,
2217 struct lock_class_key *request_key)
2218 {
2219 return 0;
2220 }
gpiochip_irqchip_remove(struct gpio_chip * gc)2221 static void gpiochip_irqchip_remove(struct gpio_chip *gc) {}
2222
gpiochip_irqchip_init_hw(struct gpio_chip * gc)2223 static inline int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
2224 {
2225 return 0;
2226 }
2227
gpiochip_irqchip_init_valid_mask(struct gpio_chip * gc)2228 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
2229 {
2230 return 0;
2231 }
gpiochip_irqchip_free_valid_mask(struct gpio_chip * gc)2232 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc)
2233 { }
2234
2235 #endif /* CONFIG_GPIOLIB_IRQCHIP */
2236
2237 /**
2238 * gpiochip_generic_request() - request the gpio function for a pin
2239 * @gc: the gpiochip owning the GPIO
2240 * @offset: the offset of the GPIO to request for GPIO function
2241 *
2242 * Returns:
2243 * 0 on success, or negative errno on failure.
2244 */
gpiochip_generic_request(struct gpio_chip * gc,unsigned int offset)2245 int gpiochip_generic_request(struct gpio_chip *gc, unsigned int offset)
2246 {
2247 #ifdef CONFIG_PINCTRL
2248 if (list_empty(&gc->gpiodev->pin_ranges))
2249 return 0;
2250 #endif
2251
2252 return pinctrl_gpio_request(gc, offset);
2253 }
2254 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
2255
2256 /**
2257 * gpiochip_generic_free() - free the gpio function from a pin
2258 * @gc: the gpiochip to request the gpio function for
2259 * @offset: the offset of the GPIO to free from GPIO function
2260 */
gpiochip_generic_free(struct gpio_chip * gc,unsigned int offset)2261 void gpiochip_generic_free(struct gpio_chip *gc, unsigned int offset)
2262 {
2263 #ifdef CONFIG_PINCTRL
2264 if (list_empty(&gc->gpiodev->pin_ranges))
2265 return;
2266 #endif
2267
2268 pinctrl_gpio_free(gc, offset);
2269 }
2270 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
2271
2272 /**
2273 * gpiochip_generic_config() - apply configuration for a pin
2274 * @gc: the gpiochip owning the GPIO
2275 * @offset: the offset of the GPIO to apply the configuration
2276 * @config: the configuration to be applied
2277 *
2278 * Returns:
2279 * 0 on success, or negative errno on failure.
2280 */
gpiochip_generic_config(struct gpio_chip * gc,unsigned int offset,unsigned long config)2281 int gpiochip_generic_config(struct gpio_chip *gc, unsigned int offset,
2282 unsigned long config)
2283 {
2284 #ifdef CONFIG_PINCTRL
2285 if (list_empty(&gc->gpiodev->pin_ranges))
2286 return -ENOTSUPP;
2287 #endif
2288
2289 return pinctrl_gpio_set_config(gc, offset, config);
2290 }
2291 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
2292
2293 #ifdef CONFIG_PINCTRL
2294
2295 /**
2296 * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
2297 * @gc: the gpiochip to add the range for
2298 * @pctldev: the pin controller to map to
2299 * @gpio_offset: the start offset in the current gpio_chip number space
2300 * @pin_group: name of the pin group inside the pin controller
2301 *
2302 * Calling this function directly from a DeviceTree-supported
2303 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2304 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2305 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2306 *
2307 * Returns:
2308 * 0 on success, or negative errno on failure.
2309 */
gpiochip_add_pingroup_range(struct gpio_chip * gc,struct pinctrl_dev * pctldev,unsigned int gpio_offset,const char * pin_group)2310 int gpiochip_add_pingroup_range(struct gpio_chip *gc,
2311 struct pinctrl_dev *pctldev,
2312 unsigned int gpio_offset, const char *pin_group)
2313 {
2314 struct gpio_pin_range *pin_range;
2315 struct gpio_device *gdev = gc->gpiodev;
2316 int ret;
2317
2318 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2319 if (!pin_range) {
2320 chip_err(gc, "failed to allocate pin ranges\n");
2321 return -ENOMEM;
2322 }
2323
2324 /* Use local offset as range ID */
2325 pin_range->range.id = gpio_offset;
2326 pin_range->range.gc = gc;
2327 pin_range->range.name = gc->label;
2328 pin_range->range.base = gdev->base + gpio_offset;
2329 pin_range->pctldev = pctldev;
2330
2331 ret = pinctrl_get_group_pins(pctldev, pin_group,
2332 &pin_range->range.pins,
2333 &pin_range->range.npins);
2334 if (ret < 0) {
2335 kfree(pin_range);
2336 return ret;
2337 }
2338
2339 pinctrl_add_gpio_range(pctldev, &pin_range->range);
2340
2341 chip_dbg(gc, "created GPIO range %d->%d ==> %s PINGRP %s\n",
2342 gpio_offset, gpio_offset + pin_range->range.npins - 1,
2343 pinctrl_dev_get_devname(pctldev), pin_group);
2344
2345 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2346
2347 return 0;
2348 }
2349 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
2350
2351 /**
2352 * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
2353 * @gc: the gpiochip to add the range for
2354 * @pinctl_name: the dev_name() of the pin controller to map to
2355 * @gpio_offset: the start offset in the current gpio_chip number space
2356 * @pin_offset: the start offset in the pin controller number space
2357 * @npins: the number of pins from the offset of each pin space (GPIO and
2358 * pin controller) to accumulate in this range
2359 *
2360 * Calling this function directly from a DeviceTree-supported
2361 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2362 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2363 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2364 *
2365 * Returns:
2366 * 0 on success, or a negative errno on failure.
2367 */
gpiochip_add_pin_range(struct gpio_chip * gc,const char * pinctl_name,unsigned int gpio_offset,unsigned int pin_offset,unsigned int npins)2368 int gpiochip_add_pin_range(struct gpio_chip *gc, const char *pinctl_name,
2369 unsigned int gpio_offset, unsigned int pin_offset,
2370 unsigned int npins)
2371 {
2372 struct gpio_pin_range *pin_range;
2373 struct gpio_device *gdev = gc->gpiodev;
2374 int ret;
2375
2376 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2377 if (!pin_range) {
2378 chip_err(gc, "failed to allocate pin ranges\n");
2379 return -ENOMEM;
2380 }
2381
2382 /* Use local offset as range ID */
2383 pin_range->range.id = gpio_offset;
2384 pin_range->range.gc = gc;
2385 pin_range->range.name = gc->label;
2386 pin_range->range.base = gdev->base + gpio_offset;
2387 pin_range->range.pin_base = pin_offset;
2388 pin_range->range.npins = npins;
2389 pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
2390 &pin_range->range);
2391 if (IS_ERR(pin_range->pctldev)) {
2392 ret = PTR_ERR(pin_range->pctldev);
2393 chip_err(gc, "could not create pin range\n");
2394 kfree(pin_range);
2395 return ret;
2396 }
2397 chip_dbg(gc, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
2398 gpio_offset, gpio_offset + npins - 1,
2399 pinctl_name,
2400 pin_offset, pin_offset + npins - 1);
2401
2402 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2403
2404 return 0;
2405 }
2406 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
2407
2408 /**
2409 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2410 * @gc: the chip to remove all the mappings for
2411 */
gpiochip_remove_pin_ranges(struct gpio_chip * gc)2412 void gpiochip_remove_pin_ranges(struct gpio_chip *gc)
2413 {
2414 struct gpio_pin_range *pin_range, *tmp;
2415 struct gpio_device *gdev = gc->gpiodev;
2416
2417 list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2418 list_del(&pin_range->node);
2419 pinctrl_remove_gpio_range(pin_range->pctldev,
2420 &pin_range->range);
2421 kfree(pin_range);
2422 }
2423 }
2424 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
2425
2426 #endif /* CONFIG_PINCTRL */
2427
2428 /* These "optional" allocation calls help prevent drivers from stomping
2429 * on each other, and help provide better diagnostics in debugfs.
2430 * They're called even less than the "set direction" calls.
2431 */
gpiod_request_commit(struct gpio_desc * desc,const char * label)2432 static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
2433 {
2434 unsigned int offset;
2435 int ret;
2436
2437 CLASS(gpio_chip_guard, guard)(desc);
2438 if (!guard.gc)
2439 return -ENODEV;
2440
2441 if (test_and_set_bit(FLAG_REQUESTED, &desc->flags))
2442 return -EBUSY;
2443
2444 offset = gpio_chip_hwgpio(desc);
2445 if (!gpiochip_line_is_valid(guard.gc, offset))
2446 return -EINVAL;
2447
2448 /* NOTE: gpio_request() can be called in early boot,
2449 * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
2450 */
2451
2452 if (guard.gc->request) {
2453 ret = guard.gc->request(guard.gc, offset);
2454 if (ret > 0)
2455 ret = -EBADE;
2456 if (ret)
2457 goto out_clear_bit;
2458 }
2459
2460 if (guard.gc->get_direction)
2461 gpiod_get_direction(desc);
2462
2463 ret = desc_set_label(desc, label ? : "?");
2464 if (ret)
2465 goto out_clear_bit;
2466
2467 return 0;
2468
2469 out_clear_bit:
2470 clear_bit(FLAG_REQUESTED, &desc->flags);
2471 return ret;
2472 }
2473
gpiod_request(struct gpio_desc * desc,const char * label)2474 int gpiod_request(struct gpio_desc *desc, const char *label)
2475 {
2476 int ret = -EPROBE_DEFER;
2477
2478 VALIDATE_DESC(desc);
2479
2480 if (try_module_get(desc->gdev->owner)) {
2481 ret = gpiod_request_commit(desc, label);
2482 if (ret)
2483 module_put(desc->gdev->owner);
2484 else
2485 gpio_device_get(desc->gdev);
2486 }
2487
2488 if (ret)
2489 gpiod_dbg(desc, "%s: status %d\n", __func__, ret);
2490
2491 return ret;
2492 }
2493
gpiod_free_commit(struct gpio_desc * desc)2494 static void gpiod_free_commit(struct gpio_desc *desc)
2495 {
2496 unsigned long flags;
2497
2498 might_sleep();
2499
2500 CLASS(gpio_chip_guard, guard)(desc);
2501
2502 flags = READ_ONCE(desc->flags);
2503
2504 if (guard.gc && test_bit(FLAG_REQUESTED, &flags)) {
2505 if (guard.gc->free)
2506 guard.gc->free(guard.gc, gpio_chip_hwgpio(desc));
2507
2508 clear_bit(FLAG_ACTIVE_LOW, &flags);
2509 clear_bit(FLAG_REQUESTED, &flags);
2510 clear_bit(FLAG_OPEN_DRAIN, &flags);
2511 clear_bit(FLAG_OPEN_SOURCE, &flags);
2512 clear_bit(FLAG_PULL_UP, &flags);
2513 clear_bit(FLAG_PULL_DOWN, &flags);
2514 clear_bit(FLAG_BIAS_DISABLE, &flags);
2515 clear_bit(FLAG_EDGE_RISING, &flags);
2516 clear_bit(FLAG_EDGE_FALLING, &flags);
2517 clear_bit(FLAG_IS_HOGGED, &flags);
2518 #ifdef CONFIG_OF_DYNAMIC
2519 WRITE_ONCE(desc->hog, NULL);
2520 #endif
2521 desc_set_label(desc, NULL);
2522 WRITE_ONCE(desc->flags, flags);
2523 #ifdef CONFIG_GPIO_CDEV
2524 WRITE_ONCE(desc->debounce_period_us, 0);
2525 #endif
2526 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_RELEASED);
2527 }
2528 }
2529
gpiod_free(struct gpio_desc * desc)2530 void gpiod_free(struct gpio_desc *desc)
2531 {
2532 VALIDATE_DESC_VOID(desc);
2533
2534 gpiod_free_commit(desc);
2535 module_put(desc->gdev->owner);
2536 gpio_device_put(desc->gdev);
2537 }
2538
2539 /**
2540 * gpiochip_dup_line_label - Get a copy of the consumer label.
2541 * @gc: GPIO chip controlling this line.
2542 * @offset: Hardware offset of the line.
2543 *
2544 * Returns:
2545 * Pointer to a copy of the consumer label if the line is requested or NULL
2546 * if it's not. If a valid pointer was returned, it must be freed using
2547 * kfree(). In case of a memory allocation error, the function returns %ENOMEM.
2548 *
2549 * Must not be called from atomic context.
2550 */
gpiochip_dup_line_label(struct gpio_chip * gc,unsigned int offset)2551 char *gpiochip_dup_line_label(struct gpio_chip *gc, unsigned int offset)
2552 {
2553 struct gpio_desc *desc;
2554 char *label;
2555
2556 desc = gpiochip_get_desc(gc, offset);
2557 if (IS_ERR(desc))
2558 return NULL;
2559
2560 if (!test_bit(FLAG_REQUESTED, &desc->flags))
2561 return NULL;
2562
2563 guard(srcu)(&desc->gdev->desc_srcu);
2564
2565 label = kstrdup(gpiod_get_label(desc), GFP_KERNEL);
2566 if (!label)
2567 return ERR_PTR(-ENOMEM);
2568
2569 return label;
2570 }
2571 EXPORT_SYMBOL_GPL(gpiochip_dup_line_label);
2572
function_name_or_default(const char * con_id)2573 static inline const char *function_name_or_default(const char *con_id)
2574 {
2575 return con_id ?: "(default)";
2576 }
2577
2578 /**
2579 * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
2580 * @gc: GPIO chip
2581 * @hwnum: hardware number of the GPIO for which to request the descriptor
2582 * @label: label for the GPIO
2583 * @lflags: lookup flags for this GPIO or 0 if default, this can be used to
2584 * specify things like line inversion semantics with the machine flags
2585 * such as GPIO_OUT_LOW
2586 * @dflags: descriptor request flags for this GPIO or 0 if default, this
2587 * can be used to specify consumer semantics such as open drain
2588 *
2589 * Function allows GPIO chip drivers to request and use their own GPIO
2590 * descriptors via gpiolib API. Difference to gpiod_request() is that this
2591 * function will not increase reference count of the GPIO chip module. This
2592 * allows the GPIO chip module to be unloaded as needed (we assume that the
2593 * GPIO chip driver handles freeing the GPIOs it has requested).
2594 *
2595 * Returns:
2596 * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
2597 * code on failure.
2598 */
gpiochip_request_own_desc(struct gpio_chip * gc,unsigned int hwnum,const char * label,enum gpio_lookup_flags lflags,enum gpiod_flags dflags)2599 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *gc,
2600 unsigned int hwnum,
2601 const char *label,
2602 enum gpio_lookup_flags lflags,
2603 enum gpiod_flags dflags)
2604 {
2605 struct gpio_desc *desc = gpiochip_get_desc(gc, hwnum);
2606 const char *name = function_name_or_default(label);
2607 int ret;
2608
2609 if (IS_ERR(desc)) {
2610 chip_err(gc, "failed to get GPIO %s descriptor\n", name);
2611 return desc;
2612 }
2613
2614 ret = gpiod_request_commit(desc, label);
2615 if (ret < 0)
2616 return ERR_PTR(ret);
2617
2618 ret = gpiod_configure_flags(desc, label, lflags, dflags);
2619 if (ret) {
2620 gpiod_free_commit(desc);
2621 chip_err(gc, "setup of own GPIO %s failed\n", name);
2622 return ERR_PTR(ret);
2623 }
2624
2625 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_REQUESTED);
2626
2627 return desc;
2628 }
2629 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
2630
2631 /**
2632 * gpiochip_free_own_desc - Free GPIO requested by the chip driver
2633 * @desc: GPIO descriptor to free
2634 *
2635 * Function frees the given GPIO requested previously with
2636 * gpiochip_request_own_desc().
2637 */
gpiochip_free_own_desc(struct gpio_desc * desc)2638 void gpiochip_free_own_desc(struct gpio_desc *desc)
2639 {
2640 if (desc)
2641 gpiod_free_commit(desc);
2642 }
2643 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
2644
2645 /*
2646 * Drivers MUST set GPIO direction before making get/set calls. In
2647 * some cases this is done in early boot, before IRQs are enabled.
2648 *
2649 * As a rule these aren't called more than once (except for drivers
2650 * using the open-drain emulation idiom) so these are natural places
2651 * to accumulate extra debugging checks. Note that we can't (yet)
2652 * rely on gpio_request() having been called beforehand.
2653 */
2654
gpio_do_set_config(struct gpio_desc * desc,unsigned long config)2655 int gpio_do_set_config(struct gpio_desc *desc, unsigned long config)
2656 {
2657 int ret;
2658
2659 CLASS(gpio_chip_guard, guard)(desc);
2660 if (!guard.gc)
2661 return -ENODEV;
2662
2663 if (!guard.gc->set_config)
2664 return -ENOTSUPP;
2665
2666 ret = guard.gc->set_config(guard.gc, gpio_chip_hwgpio(desc), config);
2667 if (ret > 0)
2668 ret = -EBADE;
2669
2670 #ifdef CONFIG_GPIO_CDEV
2671 /*
2672 * Special case - if we're setting debounce period, we need to store
2673 * it in the descriptor in case user-space wants to know it.
2674 */
2675 if (!ret && pinconf_to_config_param(config) == PIN_CONFIG_INPUT_DEBOUNCE)
2676 WRITE_ONCE(desc->debounce_period_us,
2677 pinconf_to_config_argument(config));
2678 #endif
2679 return ret;
2680 }
2681
gpio_set_config_with_argument(struct gpio_desc * desc,enum pin_config_param mode,u32 argument)2682 static int gpio_set_config_with_argument(struct gpio_desc *desc,
2683 enum pin_config_param mode,
2684 u32 argument)
2685 {
2686 unsigned long config;
2687
2688 config = pinconf_to_config_packed(mode, argument);
2689 return gpio_do_set_config(desc, config);
2690 }
2691
gpio_set_config_with_argument_optional(struct gpio_desc * desc,enum pin_config_param mode,u32 argument)2692 static int gpio_set_config_with_argument_optional(struct gpio_desc *desc,
2693 enum pin_config_param mode,
2694 u32 argument)
2695 {
2696 struct device *dev = &desc->gdev->dev;
2697 int gpio = gpio_chip_hwgpio(desc);
2698 int ret;
2699
2700 ret = gpio_set_config_with_argument(desc, mode, argument);
2701 if (ret != -ENOTSUPP)
2702 return ret;
2703
2704 switch (mode) {
2705 case PIN_CONFIG_PERSIST_STATE:
2706 dev_dbg(dev, "Persistence not supported for GPIO %d\n", gpio);
2707 break;
2708 default:
2709 break;
2710 }
2711
2712 return 0;
2713 }
2714
gpio_set_config(struct gpio_desc * desc,enum pin_config_param mode)2715 static int gpio_set_config(struct gpio_desc *desc, enum pin_config_param mode)
2716 {
2717 return gpio_set_config_with_argument(desc, mode, 0);
2718 }
2719
gpio_set_bias(struct gpio_desc * desc)2720 static int gpio_set_bias(struct gpio_desc *desc)
2721 {
2722 enum pin_config_param bias;
2723 unsigned long flags;
2724 unsigned int arg;
2725
2726 flags = READ_ONCE(desc->flags);
2727
2728 if (test_bit(FLAG_BIAS_DISABLE, &flags))
2729 bias = PIN_CONFIG_BIAS_DISABLE;
2730 else if (test_bit(FLAG_PULL_UP, &flags))
2731 bias = PIN_CONFIG_BIAS_PULL_UP;
2732 else if (test_bit(FLAG_PULL_DOWN, &flags))
2733 bias = PIN_CONFIG_BIAS_PULL_DOWN;
2734 else
2735 return 0;
2736
2737 switch (bias) {
2738 case PIN_CONFIG_BIAS_PULL_DOWN:
2739 case PIN_CONFIG_BIAS_PULL_UP:
2740 arg = 1;
2741 break;
2742
2743 default:
2744 arg = 0;
2745 break;
2746 }
2747
2748 return gpio_set_config_with_argument_optional(desc, bias, arg);
2749 }
2750
2751 /**
2752 * gpio_set_debounce_timeout() - Set debounce timeout
2753 * @desc: GPIO descriptor to set the debounce timeout
2754 * @debounce: Debounce timeout in microseconds
2755 *
2756 * The function calls the certain GPIO driver to set debounce timeout
2757 * in the hardware.
2758 *
2759 * Returns:
2760 * 0 on success, or negative errno on failure.
2761 */
gpio_set_debounce_timeout(struct gpio_desc * desc,unsigned int debounce)2762 int gpio_set_debounce_timeout(struct gpio_desc *desc, unsigned int debounce)
2763 {
2764 int ret;
2765
2766 ret = gpio_set_config_with_argument_optional(desc,
2767 PIN_CONFIG_INPUT_DEBOUNCE,
2768 debounce);
2769 if (!ret)
2770 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
2771
2772 return ret;
2773 }
2774
gpiochip_direction_input(struct gpio_chip * gc,unsigned int offset)2775 static int gpiochip_direction_input(struct gpio_chip *gc, unsigned int offset)
2776 {
2777 int ret;
2778
2779 lockdep_assert_held(&gc->gpiodev->srcu);
2780
2781 if (WARN_ON(!gc->direction_input))
2782 return -EOPNOTSUPP;
2783
2784 ret = gc->direction_input(gc, offset);
2785 if (ret > 0)
2786 ret = -EBADE;
2787
2788 return ret;
2789 }
2790
gpiochip_direction_output(struct gpio_chip * gc,unsigned int offset,int value)2791 static int gpiochip_direction_output(struct gpio_chip *gc, unsigned int offset,
2792 int value)
2793 {
2794 int ret;
2795
2796 lockdep_assert_held(&gc->gpiodev->srcu);
2797
2798 if (WARN_ON(!gc->direction_output))
2799 return -EOPNOTSUPP;
2800
2801 ret = gc->direction_output(gc, offset, value);
2802 if (ret > 0)
2803 ret = -EBADE;
2804
2805 return ret;
2806 }
2807
2808 /**
2809 * gpiod_direction_input - set the GPIO direction to input
2810 * @desc: GPIO to set to input
2811 *
2812 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
2813 * be called safely on it.
2814 *
2815 * Returns:
2816 * 0 on success, or negative errno on failure.
2817 */
gpiod_direction_input(struct gpio_desc * desc)2818 int gpiod_direction_input(struct gpio_desc *desc)
2819 {
2820 int ret;
2821
2822 VALIDATE_DESC(desc);
2823
2824 ret = gpiod_direction_input_nonotify(desc);
2825 if (ret == 0)
2826 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
2827
2828 return ret;
2829 }
2830 EXPORT_SYMBOL_GPL(gpiod_direction_input);
2831
gpiod_direction_input_nonotify(struct gpio_desc * desc)2832 int gpiod_direction_input_nonotify(struct gpio_desc *desc)
2833 {
2834 int ret = 0, dir;
2835
2836 CLASS(gpio_chip_guard, guard)(desc);
2837 if (!guard.gc)
2838 return -ENODEV;
2839
2840 /*
2841 * It is legal to have no .get() and .direction_input() specified if
2842 * the chip is output-only, but you can't specify .direction_input()
2843 * and not support the .get() operation, that doesn't make sense.
2844 */
2845 if (!guard.gc->get && guard.gc->direction_input) {
2846 gpiod_warn(desc,
2847 "%s: missing get() but have direction_input()\n",
2848 __func__);
2849 return -EIO;
2850 }
2851
2852 /*
2853 * If we have a .direction_input() callback, things are simple,
2854 * just call it. Else we are some input-only chip so try to check the
2855 * direction (if .get_direction() is supported) else we silently
2856 * assume we are in input mode after this.
2857 */
2858 if (guard.gc->direction_input) {
2859 ret = gpiochip_direction_input(guard.gc,
2860 gpio_chip_hwgpio(desc));
2861 } else if (guard.gc->get_direction) {
2862 dir = gpiochip_get_direction(guard.gc, gpio_chip_hwgpio(desc));
2863 if (dir < 0)
2864 return dir;
2865
2866 if (dir != GPIO_LINE_DIRECTION_IN) {
2867 gpiod_warn(desc,
2868 "%s: missing direction_input() operation and line is output\n",
2869 __func__);
2870 return -EIO;
2871 }
2872 }
2873 if (ret == 0) {
2874 clear_bit(FLAG_IS_OUT, &desc->flags);
2875 ret = gpio_set_bias(desc);
2876 }
2877
2878 trace_gpio_direction(desc_to_gpio(desc), 1, ret);
2879
2880 return ret;
2881 }
2882
gpiochip_set(struct gpio_chip * gc,unsigned int offset,int value)2883 static int gpiochip_set(struct gpio_chip *gc, unsigned int offset, int value)
2884 {
2885 int ret;
2886
2887 lockdep_assert_held(&gc->gpiodev->srcu);
2888
2889 if (WARN_ON(unlikely(!gc->set)))
2890 return -EOPNOTSUPP;
2891
2892 ret = gc->set(gc, offset, value);
2893 if (ret > 0)
2894 ret = -EBADE;
2895
2896 return ret;
2897 }
2898
gpiod_direction_output_raw_commit(struct gpio_desc * desc,int value)2899 static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
2900 {
2901 int val = !!value, ret = 0, dir;
2902
2903 CLASS(gpio_chip_guard, guard)(desc);
2904 if (!guard.gc)
2905 return -ENODEV;
2906
2907 /*
2908 * It's OK not to specify .direction_output() if the gpiochip is
2909 * output-only, but if there is then not even a .set() operation it
2910 * is pretty tricky to drive the output line.
2911 */
2912 if (!guard.gc->set && !guard.gc->direction_output) {
2913 gpiod_warn(desc,
2914 "%s: missing set() and direction_output() operations\n",
2915 __func__);
2916 return -EIO;
2917 }
2918
2919 if (guard.gc->direction_output) {
2920 ret = gpiochip_direction_output(guard.gc,
2921 gpio_chip_hwgpio(desc), val);
2922 } else {
2923 /* Check that we are in output mode if we can */
2924 if (guard.gc->get_direction) {
2925 dir = gpiochip_get_direction(guard.gc,
2926 gpio_chip_hwgpio(desc));
2927 if (dir < 0)
2928 return dir;
2929
2930 if (dir != GPIO_LINE_DIRECTION_OUT) {
2931 gpiod_warn(desc,
2932 "%s: missing direction_output() operation\n",
2933 __func__);
2934 return -EIO;
2935 }
2936 }
2937 /*
2938 * If we can't actively set the direction, we are some
2939 * output-only chip, so just drive the output as desired.
2940 */
2941 ret = gpiochip_set(guard.gc, gpio_chip_hwgpio(desc), val);
2942 if (ret)
2943 return ret;
2944 }
2945
2946 if (!ret)
2947 set_bit(FLAG_IS_OUT, &desc->flags);
2948 trace_gpio_value(desc_to_gpio(desc), 0, val);
2949 trace_gpio_direction(desc_to_gpio(desc), 0, ret);
2950 return ret;
2951 }
2952
2953 /**
2954 * gpiod_direction_output_raw - set the GPIO direction to output
2955 * @desc: GPIO to set to output
2956 * @value: initial output value of the GPIO
2957 *
2958 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2959 * be called safely on it. The initial value of the output must be specified
2960 * as raw value on the physical line without regard for the ACTIVE_LOW status.
2961 *
2962 * Returns:
2963 * 0 on success, or negative errno on failure.
2964 */
gpiod_direction_output_raw(struct gpio_desc * desc,int value)2965 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2966 {
2967 int ret;
2968
2969 VALIDATE_DESC(desc);
2970
2971 ret = gpiod_direction_output_raw_commit(desc, value);
2972 if (ret == 0)
2973 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
2974
2975 return ret;
2976 }
2977 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
2978
2979 /**
2980 * gpiod_direction_output - set the GPIO direction to output
2981 * @desc: GPIO to set to output
2982 * @value: initial output value of the GPIO
2983 *
2984 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2985 * be called safely on it. The initial value of the output must be specified
2986 * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2987 * account.
2988 *
2989 * Returns:
2990 * 0 on success, or negative errno on failure.
2991 */
gpiod_direction_output(struct gpio_desc * desc,int value)2992 int gpiod_direction_output(struct gpio_desc *desc, int value)
2993 {
2994 int ret;
2995
2996 VALIDATE_DESC(desc);
2997
2998 ret = gpiod_direction_output_nonotify(desc, value);
2999 if (ret == 0)
3000 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
3001
3002 return ret;
3003 }
3004 EXPORT_SYMBOL_GPL(gpiod_direction_output);
3005
gpiod_direction_output_nonotify(struct gpio_desc * desc,int value)3006 int gpiod_direction_output_nonotify(struct gpio_desc *desc, int value)
3007 {
3008 unsigned long flags;
3009 int ret;
3010
3011 flags = READ_ONCE(desc->flags);
3012
3013 if (test_bit(FLAG_ACTIVE_LOW, &flags))
3014 value = !value;
3015 else
3016 value = !!value;
3017
3018 /* GPIOs used for enabled IRQs shall not be set as output */
3019 if (test_bit(FLAG_USED_AS_IRQ, &flags) &&
3020 test_bit(FLAG_IRQ_IS_ENABLED, &flags)) {
3021 gpiod_err(desc,
3022 "%s: tried to set a GPIO tied to an IRQ as output\n",
3023 __func__);
3024 return -EIO;
3025 }
3026
3027 if (test_bit(FLAG_OPEN_DRAIN, &flags)) {
3028 /* First see if we can enable open drain in hardware */
3029 ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_DRAIN);
3030 if (!ret)
3031 goto set_output_value;
3032 /* Emulate open drain by not actively driving the line high */
3033 if (value)
3034 goto set_output_flag;
3035 } else if (test_bit(FLAG_OPEN_SOURCE, &flags)) {
3036 ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_SOURCE);
3037 if (!ret)
3038 goto set_output_value;
3039 /* Emulate open source by not actively driving the line low */
3040 if (!value)
3041 goto set_output_flag;
3042 } else {
3043 gpio_set_config(desc, PIN_CONFIG_DRIVE_PUSH_PULL);
3044 }
3045
3046 set_output_value:
3047 ret = gpio_set_bias(desc);
3048 if (ret)
3049 return ret;
3050 return gpiod_direction_output_raw_commit(desc, value);
3051
3052 set_output_flag:
3053 ret = gpiod_direction_input_nonotify(desc);
3054 if (ret)
3055 return ret;
3056 /*
3057 * When emulating open-source or open-drain functionalities by not
3058 * actively driving the line (setting mode to input) we still need to
3059 * set the IS_OUT flag or otherwise we won't be able to set the line
3060 * value anymore.
3061 */
3062 set_bit(FLAG_IS_OUT, &desc->flags);
3063 return 0;
3064 }
3065
3066 #if IS_ENABLED(CONFIG_HTE)
3067 /**
3068 * gpiod_enable_hw_timestamp_ns - Enable hardware timestamp in nanoseconds.
3069 *
3070 * @desc: GPIO to enable.
3071 * @flags: Flags related to GPIO edge.
3072 *
3073 * Returns:
3074 * 0 on success, or negative errno on failure.
3075 */
gpiod_enable_hw_timestamp_ns(struct gpio_desc * desc,unsigned long flags)3076 int gpiod_enable_hw_timestamp_ns(struct gpio_desc *desc, unsigned long flags)
3077 {
3078 int ret;
3079
3080 VALIDATE_DESC(desc);
3081
3082 CLASS(gpio_chip_guard, guard)(desc);
3083 if (!guard.gc)
3084 return -ENODEV;
3085
3086 if (!guard.gc->en_hw_timestamp) {
3087 gpiod_warn(desc, "%s: hw ts not supported\n", __func__);
3088 return -ENOTSUPP;
3089 }
3090
3091 ret = guard.gc->en_hw_timestamp(guard.gc,
3092 gpio_chip_hwgpio(desc), flags);
3093 if (ret)
3094 gpiod_warn(desc, "%s: hw ts request failed\n", __func__);
3095
3096 return ret;
3097 }
3098 EXPORT_SYMBOL_GPL(gpiod_enable_hw_timestamp_ns);
3099
3100 /**
3101 * gpiod_disable_hw_timestamp_ns - Disable hardware timestamp.
3102 *
3103 * @desc: GPIO to disable.
3104 * @flags: Flags related to GPIO edge, same value as used during enable call.
3105 *
3106 * Returns:
3107 * 0 on success, or negative errno on failure.
3108 */
gpiod_disable_hw_timestamp_ns(struct gpio_desc * desc,unsigned long flags)3109 int gpiod_disable_hw_timestamp_ns(struct gpio_desc *desc, unsigned long flags)
3110 {
3111 int ret;
3112
3113 VALIDATE_DESC(desc);
3114
3115 CLASS(gpio_chip_guard, guard)(desc);
3116 if (!guard.gc)
3117 return -ENODEV;
3118
3119 if (!guard.gc->dis_hw_timestamp) {
3120 gpiod_warn(desc, "%s: hw ts not supported\n", __func__);
3121 return -ENOTSUPP;
3122 }
3123
3124 ret = guard.gc->dis_hw_timestamp(guard.gc, gpio_chip_hwgpio(desc),
3125 flags);
3126 if (ret)
3127 gpiod_warn(desc, "%s: hw ts release failed\n", __func__);
3128
3129 return ret;
3130 }
3131 EXPORT_SYMBOL_GPL(gpiod_disable_hw_timestamp_ns);
3132 #endif /* CONFIG_HTE */
3133
3134 /**
3135 * gpiod_set_config - sets @config for a GPIO
3136 * @desc: descriptor of the GPIO for which to set the configuration
3137 * @config: Same packed config format as generic pinconf
3138 *
3139 * Returns:
3140 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3141 * configuration.
3142 */
gpiod_set_config(struct gpio_desc * desc,unsigned long config)3143 int gpiod_set_config(struct gpio_desc *desc, unsigned long config)
3144 {
3145 int ret;
3146
3147 VALIDATE_DESC(desc);
3148
3149 ret = gpio_do_set_config(desc, config);
3150 if (!ret) {
3151 /* These are the only options we notify the userspace about. */
3152 switch (pinconf_to_config_param(config)) {
3153 case PIN_CONFIG_BIAS_DISABLE:
3154 case PIN_CONFIG_BIAS_PULL_DOWN:
3155 case PIN_CONFIG_BIAS_PULL_UP:
3156 case PIN_CONFIG_DRIVE_OPEN_DRAIN:
3157 case PIN_CONFIG_DRIVE_OPEN_SOURCE:
3158 case PIN_CONFIG_DRIVE_PUSH_PULL:
3159 case PIN_CONFIG_INPUT_DEBOUNCE:
3160 gpiod_line_state_notify(desc,
3161 GPIO_V2_LINE_CHANGED_CONFIG);
3162 break;
3163 default:
3164 break;
3165 }
3166 }
3167
3168 return ret;
3169 }
3170 EXPORT_SYMBOL_GPL(gpiod_set_config);
3171
3172 /**
3173 * gpiod_set_debounce - sets @debounce time for a GPIO
3174 * @desc: descriptor of the GPIO for which to set debounce time
3175 * @debounce: debounce time in microseconds
3176 *
3177 * Returns:
3178 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3179 * debounce time.
3180 */
gpiod_set_debounce(struct gpio_desc * desc,unsigned int debounce)3181 int gpiod_set_debounce(struct gpio_desc *desc, unsigned int debounce)
3182 {
3183 unsigned long config;
3184
3185 config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
3186 return gpiod_set_config(desc, config);
3187 }
3188 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
3189
3190 /**
3191 * gpiod_set_transitory - Lose or retain GPIO state on suspend or reset
3192 * @desc: descriptor of the GPIO for which to configure persistence
3193 * @transitory: True to lose state on suspend or reset, false for persistence
3194 *
3195 * Returns:
3196 * 0 on success, otherwise a negative error code.
3197 */
gpiod_set_transitory(struct gpio_desc * desc,bool transitory)3198 int gpiod_set_transitory(struct gpio_desc *desc, bool transitory)
3199 {
3200 VALIDATE_DESC(desc);
3201 /*
3202 * Handle FLAG_TRANSITORY first, enabling queries to gpiolib for
3203 * persistence state.
3204 */
3205 assign_bit(FLAG_TRANSITORY, &desc->flags, transitory);
3206
3207 /* If the driver supports it, set the persistence state now */
3208 return gpio_set_config_with_argument_optional(desc,
3209 PIN_CONFIG_PERSIST_STATE,
3210 !transitory);
3211 }
3212
3213 /**
3214 * gpiod_is_active_low - test whether a GPIO is active-low or not
3215 * @desc: the gpio descriptor to test
3216 *
3217 * Returns:
3218 * 1 if the GPIO is active-low, 0 otherwise.
3219 */
gpiod_is_active_low(const struct gpio_desc * desc)3220 int gpiod_is_active_low(const struct gpio_desc *desc)
3221 {
3222 VALIDATE_DESC(desc);
3223 return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
3224 }
3225 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
3226
3227 /**
3228 * gpiod_toggle_active_low - toggle whether a GPIO is active-low or not
3229 * @desc: the gpio descriptor to change
3230 */
gpiod_toggle_active_low(struct gpio_desc * desc)3231 void gpiod_toggle_active_low(struct gpio_desc *desc)
3232 {
3233 VALIDATE_DESC_VOID(desc);
3234 change_bit(FLAG_ACTIVE_LOW, &desc->flags);
3235 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
3236 }
3237 EXPORT_SYMBOL_GPL(gpiod_toggle_active_low);
3238
gpiochip_get(struct gpio_chip * gc,unsigned int offset)3239 static int gpiochip_get(struct gpio_chip *gc, unsigned int offset)
3240 {
3241 int ret;
3242
3243 lockdep_assert_held(&gc->gpiodev->srcu);
3244
3245 /* Make sure this is called after checking for gc->get(). */
3246 ret = gc->get(gc, offset);
3247 if (ret > 1)
3248 ret = -EBADE;
3249
3250 return ret;
3251 }
3252
gpio_chip_get_value(struct gpio_chip * gc,const struct gpio_desc * desc)3253 static int gpio_chip_get_value(struct gpio_chip *gc, const struct gpio_desc *desc)
3254 {
3255 return gc->get ? gpiochip_get(gc, gpio_chip_hwgpio(desc)) : -EIO;
3256 }
3257
3258 /* I/O calls are only valid after configuration completed; the relevant
3259 * "is this a valid GPIO" error checks should already have been done.
3260 *
3261 * "Get" operations are often inlinable as reading a pin value register,
3262 * and masking the relevant bit in that register.
3263 *
3264 * When "set" operations are inlinable, they involve writing that mask to
3265 * one register to set a low value, or a different register to set it high.
3266 * Otherwise locking is needed, so there may be little value to inlining.
3267 *
3268 *------------------------------------------------------------------------
3269 *
3270 * IMPORTANT!!! The hot paths -- get/set value -- assume that callers
3271 * have requested the GPIO. That can include implicit requesting by
3272 * a direction setting call. Marking a gpio as requested locks its chip
3273 * in memory, guaranteeing that these table lookups need no more locking
3274 * and that gpiochip_remove() will fail.
3275 *
3276 * REVISIT when debugging, consider adding some instrumentation to ensure
3277 * that the GPIO was actually requested.
3278 */
3279
gpiod_get_raw_value_commit(const struct gpio_desc * desc)3280 static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
3281 {
3282 struct gpio_device *gdev;
3283 struct gpio_chip *gc;
3284 int value;
3285
3286 /* FIXME Unable to use gpio_chip_guard due to const desc. */
3287 gdev = desc->gdev;
3288
3289 guard(srcu)(&gdev->srcu);
3290
3291 gc = srcu_dereference(gdev->chip, &gdev->srcu);
3292 if (!gc)
3293 return -ENODEV;
3294
3295 value = gpio_chip_get_value(gc, desc);
3296 value = value < 0 ? value : !!value;
3297 trace_gpio_value(desc_to_gpio(desc), 1, value);
3298 return value;
3299 }
3300
gpio_chip_get_multiple(struct gpio_chip * gc,unsigned long * mask,unsigned long * bits)3301 static int gpio_chip_get_multiple(struct gpio_chip *gc,
3302 unsigned long *mask, unsigned long *bits)
3303 {
3304 lockdep_assert_held(&gc->gpiodev->srcu);
3305
3306 if (gc->get_multiple) {
3307 int ret;
3308
3309 ret = gc->get_multiple(gc, mask, bits);
3310 if (ret > 0)
3311 return -EBADE;
3312 return ret;
3313 }
3314
3315 if (gc->get) {
3316 int i, value;
3317
3318 for_each_set_bit(i, mask, gc->ngpio) {
3319 value = gpiochip_get(gc, i);
3320 if (value < 0)
3321 return value;
3322 __assign_bit(i, bits, value);
3323 }
3324 return 0;
3325 }
3326 return -EIO;
3327 }
3328
3329 /* The 'other' chip must be protected with its GPIO device's SRCU. */
gpio_device_chip_cmp(struct gpio_device * gdev,struct gpio_chip * gc)3330 static bool gpio_device_chip_cmp(struct gpio_device *gdev, struct gpio_chip *gc)
3331 {
3332 guard(srcu)(&gdev->srcu);
3333
3334 return gc == srcu_dereference(gdev->chip, &gdev->srcu);
3335 }
3336
gpiod_get_array_value_complex(bool raw,bool can_sleep,unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)3337 int gpiod_get_array_value_complex(bool raw, bool can_sleep,
3338 unsigned int array_size,
3339 struct gpio_desc **desc_array,
3340 struct gpio_array *array_info,
3341 unsigned long *value_bitmap)
3342 {
3343 struct gpio_chip *gc;
3344 int ret, i = 0;
3345
3346 /*
3347 * Validate array_info against desc_array and its size.
3348 * It should immediately follow desc_array if both
3349 * have been obtained from the same gpiod_get_array() call.
3350 */
3351 if (array_info && array_info->desc == desc_array &&
3352 array_size <= array_info->size &&
3353 (void *)array_info == desc_array + array_info->size) {
3354 if (!can_sleep)
3355 WARN_ON(array_info->gdev->can_sleep);
3356
3357 guard(srcu)(&array_info->gdev->srcu);
3358 gc = srcu_dereference(array_info->gdev->chip,
3359 &array_info->gdev->srcu);
3360 if (!gc)
3361 return -ENODEV;
3362
3363 ret = gpio_chip_get_multiple(gc, array_info->get_mask,
3364 value_bitmap);
3365 if (ret)
3366 return ret;
3367
3368 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3369 bitmap_xor(value_bitmap, value_bitmap,
3370 array_info->invert_mask, array_size);
3371
3372 i = find_first_zero_bit(array_info->get_mask, array_size);
3373 if (i == array_size)
3374 return 0;
3375 } else {
3376 array_info = NULL;
3377 }
3378
3379 while (i < array_size) {
3380 DECLARE_BITMAP(fastpath_mask, FASTPATH_NGPIO);
3381 DECLARE_BITMAP(fastpath_bits, FASTPATH_NGPIO);
3382 unsigned long *mask, *bits;
3383 int first, j;
3384
3385 CLASS(gpio_chip_guard, guard)(desc_array[i]);
3386 if (!guard.gc)
3387 return -ENODEV;
3388
3389 if (likely(guard.gc->ngpio <= FASTPATH_NGPIO)) {
3390 mask = fastpath_mask;
3391 bits = fastpath_bits;
3392 } else {
3393 gfp_t flags = can_sleep ? GFP_KERNEL : GFP_ATOMIC;
3394
3395 mask = bitmap_alloc(guard.gc->ngpio, flags);
3396 if (!mask)
3397 return -ENOMEM;
3398
3399 bits = bitmap_alloc(guard.gc->ngpio, flags);
3400 if (!bits) {
3401 bitmap_free(mask);
3402 return -ENOMEM;
3403 }
3404 }
3405
3406 bitmap_zero(mask, guard.gc->ngpio);
3407
3408 if (!can_sleep)
3409 WARN_ON(guard.gc->can_sleep);
3410
3411 /* collect all inputs belonging to the same chip */
3412 first = i;
3413 do {
3414 const struct gpio_desc *desc = desc_array[i];
3415 int hwgpio = gpio_chip_hwgpio(desc);
3416
3417 __set_bit(hwgpio, mask);
3418 i++;
3419
3420 if (array_info)
3421 i = find_next_zero_bit(array_info->get_mask,
3422 array_size, i);
3423 } while ((i < array_size) &&
3424 gpio_device_chip_cmp(desc_array[i]->gdev, guard.gc));
3425
3426 ret = gpio_chip_get_multiple(guard.gc, mask, bits);
3427 if (ret) {
3428 if (mask != fastpath_mask)
3429 bitmap_free(mask);
3430 if (bits != fastpath_bits)
3431 bitmap_free(bits);
3432 return ret;
3433 }
3434
3435 for (j = first; j < i; ) {
3436 const struct gpio_desc *desc = desc_array[j];
3437 int hwgpio = gpio_chip_hwgpio(desc);
3438 int value = test_bit(hwgpio, bits);
3439
3440 if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3441 value = !value;
3442 __assign_bit(j, value_bitmap, value);
3443 trace_gpio_value(desc_to_gpio(desc), 1, value);
3444 j++;
3445
3446 if (array_info)
3447 j = find_next_zero_bit(array_info->get_mask, i,
3448 j);
3449 }
3450
3451 if (mask != fastpath_mask)
3452 bitmap_free(mask);
3453 if (bits != fastpath_bits)
3454 bitmap_free(bits);
3455 }
3456 return 0;
3457 }
3458
3459 /**
3460 * gpiod_get_raw_value() - return a gpio's raw value
3461 * @desc: gpio whose value will be returned
3462 *
3463 * Returns:
3464 * The GPIO's raw value, i.e. the value of the physical line disregarding
3465 * its ACTIVE_LOW status, or negative errno on failure.
3466 *
3467 * This function can be called from contexts where we cannot sleep, and will
3468 * complain if the GPIO chip functions potentially sleep.
3469 */
gpiod_get_raw_value(const struct gpio_desc * desc)3470 int gpiod_get_raw_value(const struct gpio_desc *desc)
3471 {
3472 VALIDATE_DESC(desc);
3473 /* Should be using gpiod_get_raw_value_cansleep() */
3474 WARN_ON(desc->gdev->can_sleep);
3475 return gpiod_get_raw_value_commit(desc);
3476 }
3477 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
3478
3479 /**
3480 * gpiod_get_value() - return a gpio's value
3481 * @desc: gpio whose value will be returned
3482 *
3483 * Returns:
3484 * The GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3485 * account, or negative errno on failure.
3486 *
3487 * This function can be called from contexts where we cannot sleep, and will
3488 * complain if the GPIO chip functions potentially sleep.
3489 */
gpiod_get_value(const struct gpio_desc * desc)3490 int gpiod_get_value(const struct gpio_desc *desc)
3491 {
3492 int value;
3493
3494 VALIDATE_DESC(desc);
3495 /* Should be using gpiod_get_value_cansleep() */
3496 WARN_ON(desc->gdev->can_sleep);
3497
3498 value = gpiod_get_raw_value_commit(desc);
3499 if (value < 0)
3500 return value;
3501
3502 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3503 value = !value;
3504
3505 return value;
3506 }
3507 EXPORT_SYMBOL_GPL(gpiod_get_value);
3508
3509 /**
3510 * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
3511 * @array_size: number of elements in the descriptor array / value bitmap
3512 * @desc_array: array of GPIO descriptors whose values will be read
3513 * @array_info: information on applicability of fast bitmap processing path
3514 * @value_bitmap: bitmap to store the read values
3515 *
3516 * Read the raw values of the GPIOs, i.e. the values of the physical lines
3517 * without regard for their ACTIVE_LOW status.
3518 *
3519 * This function can be called from contexts where we cannot sleep,
3520 * and it will complain if the GPIO chip functions potentially sleep.
3521 *
3522 * Returns:
3523 * 0 on success, or negative errno on failure.
3524 */
gpiod_get_raw_array_value(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)3525 int gpiod_get_raw_array_value(unsigned int array_size,
3526 struct gpio_desc **desc_array,
3527 struct gpio_array *array_info,
3528 unsigned long *value_bitmap)
3529 {
3530 if (!desc_array)
3531 return -EINVAL;
3532 return gpiod_get_array_value_complex(true, false, array_size,
3533 desc_array, array_info,
3534 value_bitmap);
3535 }
3536 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
3537
3538 /**
3539 * gpiod_get_array_value() - read values from an array of GPIOs
3540 * @array_size: number of elements in the descriptor array / value bitmap
3541 * @desc_array: array of GPIO descriptors whose values will be read
3542 * @array_info: information on applicability of fast bitmap processing path
3543 * @value_bitmap: bitmap to store the read values
3544 *
3545 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3546 * into account.
3547 *
3548 * This function can be called from contexts where we cannot sleep,
3549 * and it will complain if the GPIO chip functions potentially sleep.
3550 *
3551 * Returns:
3552 * 0 on success, or negative errno on failure.
3553 */
gpiod_get_array_value(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)3554 int gpiod_get_array_value(unsigned int array_size,
3555 struct gpio_desc **desc_array,
3556 struct gpio_array *array_info,
3557 unsigned long *value_bitmap)
3558 {
3559 if (!desc_array)
3560 return -EINVAL;
3561 return gpiod_get_array_value_complex(false, false, array_size,
3562 desc_array, array_info,
3563 value_bitmap);
3564 }
3565 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
3566
3567 /*
3568 * gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
3569 * @desc: gpio descriptor whose state need to be set.
3570 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3571 */
gpio_set_open_drain_value_commit(struct gpio_desc * desc,bool value)3572 static int gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
3573 {
3574 int ret = 0, offset = gpio_chip_hwgpio(desc);
3575
3576 CLASS(gpio_chip_guard, guard)(desc);
3577 if (!guard.gc)
3578 return -ENODEV;
3579
3580 if (value) {
3581 ret = gpiochip_direction_input(guard.gc, offset);
3582 } else {
3583 ret = gpiochip_direction_output(guard.gc, offset, 0);
3584 if (!ret)
3585 set_bit(FLAG_IS_OUT, &desc->flags);
3586 }
3587 trace_gpio_direction(desc_to_gpio(desc), value, ret);
3588 if (ret < 0)
3589 gpiod_err(desc,
3590 "%s: Error in set_value for open drain err %d\n",
3591 __func__, ret);
3592
3593 return ret;
3594 }
3595
3596 /*
3597 * _gpio_set_open_source_value() - Set the open source gpio's value.
3598 * @desc: gpio descriptor whose state need to be set.
3599 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3600 */
gpio_set_open_source_value_commit(struct gpio_desc * desc,bool value)3601 static int gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
3602 {
3603 int ret = 0, offset = gpio_chip_hwgpio(desc);
3604
3605 CLASS(gpio_chip_guard, guard)(desc);
3606 if (!guard.gc)
3607 return -ENODEV;
3608
3609 if (value) {
3610 ret = gpiochip_direction_output(guard.gc, offset, 1);
3611 if (!ret)
3612 set_bit(FLAG_IS_OUT, &desc->flags);
3613 } else {
3614 ret = gpiochip_direction_input(guard.gc, offset);
3615 }
3616 trace_gpio_direction(desc_to_gpio(desc), !value, ret);
3617 if (ret < 0)
3618 gpiod_err(desc,
3619 "%s: Error in set_value for open source err %d\n",
3620 __func__, ret);
3621
3622 return ret;
3623 }
3624
gpiod_set_raw_value_commit(struct gpio_desc * desc,bool value)3625 static int gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
3626 {
3627 if (unlikely(!test_bit(FLAG_IS_OUT, &desc->flags)))
3628 return -EPERM;
3629
3630 CLASS(gpio_chip_guard, guard)(desc);
3631 if (!guard.gc)
3632 return -ENODEV;
3633
3634 trace_gpio_value(desc_to_gpio(desc), 0, value);
3635 return gpiochip_set(guard.gc, gpio_chip_hwgpio(desc), value);
3636 }
3637
3638 /*
3639 * set multiple outputs on the same chip;
3640 * use the chip's set_multiple function if available;
3641 * otherwise set the outputs sequentially;
3642 * @chip: the GPIO chip we operate on
3643 * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
3644 * defines which outputs are to be changed
3645 * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
3646 * defines the values the outputs specified by mask are to be set to
3647 *
3648 * Returns: 0 on success, negative error number on failure.
3649 */
gpiochip_set_multiple(struct gpio_chip * gc,unsigned long * mask,unsigned long * bits)3650 static int gpiochip_set_multiple(struct gpio_chip *gc,
3651 unsigned long *mask, unsigned long *bits)
3652 {
3653 unsigned int i;
3654 int ret;
3655
3656 lockdep_assert_held(&gc->gpiodev->srcu);
3657
3658 if (gc->set_multiple) {
3659 ret = gc->set_multiple(gc, mask, bits);
3660 if (ret > 0)
3661 ret = -EBADE;
3662
3663 return ret;
3664 }
3665
3666 /* set outputs if the corresponding mask bit is set */
3667 for_each_set_bit(i, mask, gc->ngpio) {
3668 ret = gpiochip_set(gc, i, test_bit(i, bits));
3669 if (ret)
3670 break;
3671 }
3672
3673 return ret;
3674 }
3675
gpiod_set_array_value_complex(bool raw,bool can_sleep,unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)3676 int gpiod_set_array_value_complex(bool raw, bool can_sleep,
3677 unsigned int array_size,
3678 struct gpio_desc **desc_array,
3679 struct gpio_array *array_info,
3680 unsigned long *value_bitmap)
3681 {
3682 struct gpio_chip *gc;
3683 int i = 0, ret;
3684
3685 /*
3686 * Validate array_info against desc_array and its size.
3687 * It should immediately follow desc_array if both
3688 * have been obtained from the same gpiod_get_array() call.
3689 */
3690 if (array_info && array_info->desc == desc_array &&
3691 array_size <= array_info->size &&
3692 (void *)array_info == desc_array + array_info->size) {
3693 if (!can_sleep)
3694 WARN_ON(array_info->gdev->can_sleep);
3695
3696 for (i = 0; i < array_size; i++) {
3697 if (unlikely(!test_bit(FLAG_IS_OUT,
3698 &desc_array[i]->flags)))
3699 return -EPERM;
3700 }
3701
3702 guard(srcu)(&array_info->gdev->srcu);
3703 gc = srcu_dereference(array_info->gdev->chip,
3704 &array_info->gdev->srcu);
3705 if (!gc)
3706 return -ENODEV;
3707
3708 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3709 bitmap_xor(value_bitmap, value_bitmap,
3710 array_info->invert_mask, array_size);
3711
3712 ret = gpiochip_set_multiple(gc, array_info->set_mask,
3713 value_bitmap);
3714 if (ret)
3715 return ret;
3716
3717 i = find_first_zero_bit(array_info->set_mask, array_size);
3718 if (i == array_size)
3719 return 0;
3720 } else {
3721 array_info = NULL;
3722 }
3723
3724 while (i < array_size) {
3725 DECLARE_BITMAP(fastpath_mask, FASTPATH_NGPIO);
3726 DECLARE_BITMAP(fastpath_bits, FASTPATH_NGPIO);
3727 unsigned long *mask, *bits;
3728 int count = 0;
3729
3730 CLASS(gpio_chip_guard, guard)(desc_array[i]);
3731 if (!guard.gc)
3732 return -ENODEV;
3733
3734 if (likely(guard.gc->ngpio <= FASTPATH_NGPIO)) {
3735 mask = fastpath_mask;
3736 bits = fastpath_bits;
3737 } else {
3738 gfp_t flags = can_sleep ? GFP_KERNEL : GFP_ATOMIC;
3739
3740 mask = bitmap_alloc(guard.gc->ngpio, flags);
3741 if (!mask)
3742 return -ENOMEM;
3743
3744 bits = bitmap_alloc(guard.gc->ngpio, flags);
3745 if (!bits) {
3746 bitmap_free(mask);
3747 return -ENOMEM;
3748 }
3749 }
3750
3751 bitmap_zero(mask, guard.gc->ngpio);
3752
3753 if (!can_sleep)
3754 WARN_ON(guard.gc->can_sleep);
3755
3756 do {
3757 struct gpio_desc *desc = desc_array[i];
3758 int hwgpio = gpio_chip_hwgpio(desc);
3759 int value = test_bit(i, value_bitmap);
3760
3761 if (unlikely(!test_bit(FLAG_IS_OUT, &desc->flags)))
3762 return -EPERM;
3763
3764 /*
3765 * Pins applicable for fast input but not for
3766 * fast output processing may have been already
3767 * inverted inside the fast path, skip them.
3768 */
3769 if (!raw && !(array_info &&
3770 test_bit(i, array_info->invert_mask)) &&
3771 test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3772 value = !value;
3773 trace_gpio_value(desc_to_gpio(desc), 0, value);
3774 /*
3775 * collect all normal outputs belonging to the same chip
3776 * open drain and open source outputs are set individually
3777 */
3778 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
3779 gpio_set_open_drain_value_commit(desc, value);
3780 } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
3781 gpio_set_open_source_value_commit(desc, value);
3782 } else {
3783 __set_bit(hwgpio, mask);
3784 __assign_bit(hwgpio, bits, value);
3785 count++;
3786 }
3787 i++;
3788
3789 if (array_info)
3790 i = find_next_zero_bit(array_info->set_mask,
3791 array_size, i);
3792 } while ((i < array_size) &&
3793 gpio_device_chip_cmp(desc_array[i]->gdev, guard.gc));
3794 /* push collected bits to outputs */
3795 if (count != 0) {
3796 ret = gpiochip_set_multiple(guard.gc, mask, bits);
3797 if (ret)
3798 return ret;
3799 }
3800
3801 if (mask != fastpath_mask)
3802 bitmap_free(mask);
3803 if (bits != fastpath_bits)
3804 bitmap_free(bits);
3805 }
3806 return 0;
3807 }
3808
3809 /**
3810 * gpiod_set_raw_value() - assign a gpio's raw value
3811 * @desc: gpio whose value will be assigned
3812 * @value: value to assign
3813 *
3814 * Set the raw value of the GPIO, i.e. the value of its physical line without
3815 * regard for its ACTIVE_LOW status.
3816 *
3817 * This function can be called from contexts where we cannot sleep, and will
3818 * complain if the GPIO chip functions potentially sleep.
3819 *
3820 * Returns:
3821 * 0 on success, negative error number on failure.
3822 */
gpiod_set_raw_value(struct gpio_desc * desc,int value)3823 int gpiod_set_raw_value(struct gpio_desc *desc, int value)
3824 {
3825 VALIDATE_DESC(desc);
3826 /* Should be using gpiod_set_raw_value_cansleep() */
3827 WARN_ON(desc->gdev->can_sleep);
3828 return gpiod_set_raw_value_commit(desc, value);
3829 }
3830 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
3831
3832 /**
3833 * gpiod_set_value_nocheck() - set a GPIO line value without checking
3834 * @desc: the descriptor to set the value on
3835 * @value: value to set
3836 *
3837 * This sets the value of a GPIO line backing a descriptor, applying
3838 * different semantic quirks like active low and open drain/source
3839 * handling.
3840 *
3841 * Returns:
3842 * 0 on success, negative error number on failure.
3843 */
gpiod_set_value_nocheck(struct gpio_desc * desc,int value)3844 static int gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
3845 {
3846 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3847 value = !value;
3848
3849 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
3850 return gpio_set_open_drain_value_commit(desc, value);
3851 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
3852 return gpio_set_open_source_value_commit(desc, value);
3853
3854 return gpiod_set_raw_value_commit(desc, value);
3855 }
3856
3857 /**
3858 * gpiod_set_value() - assign a gpio's value
3859 * @desc: gpio whose value will be assigned
3860 * @value: value to assign
3861 *
3862 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
3863 * OPEN_DRAIN and OPEN_SOURCE flags into account.
3864 *
3865 * This function can be called from contexts where we cannot sleep, and will
3866 * complain if the GPIO chip functions potentially sleep.
3867 *
3868 * Returns:
3869 * 0 on success, negative error number on failure.
3870 */
gpiod_set_value(struct gpio_desc * desc,int value)3871 int gpiod_set_value(struct gpio_desc *desc, int value)
3872 {
3873 VALIDATE_DESC(desc);
3874 /* Should be using gpiod_set_value_cansleep() */
3875 WARN_ON(desc->gdev->can_sleep);
3876 return gpiod_set_value_nocheck(desc, value);
3877 }
3878 EXPORT_SYMBOL_GPL(gpiod_set_value);
3879
3880 /**
3881 * gpiod_set_raw_array_value() - assign values to an array of GPIOs
3882 * @array_size: number of elements in the descriptor array / value bitmap
3883 * @desc_array: array of GPIO descriptors whose values will be assigned
3884 * @array_info: information on applicability of fast bitmap processing path
3885 * @value_bitmap: bitmap of values to assign
3886 *
3887 * Set the raw values of the GPIOs, i.e. the values of the physical lines
3888 * without regard for their ACTIVE_LOW status.
3889 *
3890 * This function can be called from contexts where we cannot sleep, and will
3891 * complain if the GPIO chip functions potentially sleep.
3892 *
3893 * Returns:
3894 * 0 on success, or negative errno on failure.
3895 */
gpiod_set_raw_array_value(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)3896 int gpiod_set_raw_array_value(unsigned int array_size,
3897 struct gpio_desc **desc_array,
3898 struct gpio_array *array_info,
3899 unsigned long *value_bitmap)
3900 {
3901 if (!desc_array)
3902 return -EINVAL;
3903 return gpiod_set_array_value_complex(true, false, array_size,
3904 desc_array, array_info, value_bitmap);
3905 }
3906 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
3907
3908 /**
3909 * gpiod_set_array_value() - assign values to an array of GPIOs
3910 * @array_size: number of elements in the descriptor array / value bitmap
3911 * @desc_array: array of GPIO descriptors whose values will be assigned
3912 * @array_info: information on applicability of fast bitmap processing path
3913 * @value_bitmap: bitmap of values to assign
3914 *
3915 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3916 * into account.
3917 *
3918 * This function can be called from contexts where we cannot sleep, and will
3919 * complain if the GPIO chip functions potentially sleep.
3920 *
3921 * Returns:
3922 * 0 on success, or negative errno on failure.
3923 */
gpiod_set_array_value(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)3924 int gpiod_set_array_value(unsigned int array_size,
3925 struct gpio_desc **desc_array,
3926 struct gpio_array *array_info,
3927 unsigned long *value_bitmap)
3928 {
3929 if (!desc_array)
3930 return -EINVAL;
3931 return gpiod_set_array_value_complex(false, false, array_size,
3932 desc_array, array_info,
3933 value_bitmap);
3934 }
3935 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
3936
3937 /**
3938 * gpiod_cansleep() - report whether gpio value access may sleep
3939 * @desc: gpio to check
3940 *
3941 * Returns:
3942 * 0 for non-sleepable, 1 for sleepable, or an error code in case of error.
3943 */
gpiod_cansleep(const struct gpio_desc * desc)3944 int gpiod_cansleep(const struct gpio_desc *desc)
3945 {
3946 VALIDATE_DESC(desc);
3947 return desc->gdev->can_sleep;
3948 }
3949 EXPORT_SYMBOL_GPL(gpiod_cansleep);
3950
3951 /**
3952 * gpiod_set_consumer_name() - set the consumer name for the descriptor
3953 * @desc: gpio to set the consumer name on
3954 * @name: the new consumer name
3955 *
3956 * Returns:
3957 * 0 on success, or negative errno on failure.
3958 */
gpiod_set_consumer_name(struct gpio_desc * desc,const char * name)3959 int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
3960 {
3961 int ret;
3962
3963 VALIDATE_DESC(desc);
3964
3965 ret = desc_set_label(desc, name);
3966 if (ret == 0)
3967 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
3968
3969 return ret;
3970 }
3971 EXPORT_SYMBOL_GPL(gpiod_set_consumer_name);
3972
3973 /**
3974 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
3975 * @desc: gpio whose IRQ will be returned (already requested)
3976 *
3977 * Returns:
3978 * The IRQ corresponding to the passed GPIO, or an error code in case of error.
3979 */
gpiod_to_irq(const struct gpio_desc * desc)3980 int gpiod_to_irq(const struct gpio_desc *desc)
3981 {
3982 struct gpio_device *gdev;
3983 struct gpio_chip *gc;
3984 int offset;
3985 int ret;
3986
3987 ret = validate_desc(desc, __func__);
3988 if (ret <= 0)
3989 return -EINVAL;
3990
3991 gdev = desc->gdev;
3992 /* FIXME Cannot use gpio_chip_guard due to const desc. */
3993 guard(srcu)(&gdev->srcu);
3994 gc = srcu_dereference(gdev->chip, &gdev->srcu);
3995 if (!gc)
3996 return -ENODEV;
3997
3998 offset = gpio_chip_hwgpio(desc);
3999 if (gc->to_irq) {
4000 ret = gc->to_irq(gc, offset);
4001 if (ret)
4002 return ret;
4003
4004 /* Zero means NO_IRQ */
4005 return -ENXIO;
4006 }
4007 #ifdef CONFIG_GPIOLIB_IRQCHIP
4008 if (gc->irq.chip) {
4009 /*
4010 * Avoid race condition with other code, which tries to lookup
4011 * an IRQ before the irqchip has been properly registered,
4012 * i.e. while gpiochip is still being brought up.
4013 */
4014 return -EPROBE_DEFER;
4015 }
4016 #endif
4017 return -ENXIO;
4018 }
4019 EXPORT_SYMBOL_GPL(gpiod_to_irq);
4020
4021 /**
4022 * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
4023 * @gc: the chip the GPIO to lock belongs to
4024 * @offset: the offset of the GPIO to lock as IRQ
4025 *
4026 * This is used directly by GPIO drivers that want to lock down
4027 * a certain GPIO line to be used for IRQs.
4028 *
4029 * Returns:
4030 * 0 on success, or negative errno on failure.
4031 */
gpiochip_lock_as_irq(struct gpio_chip * gc,unsigned int offset)4032 int gpiochip_lock_as_irq(struct gpio_chip *gc, unsigned int offset)
4033 {
4034 struct gpio_desc *desc;
4035
4036 desc = gpiochip_get_desc(gc, offset);
4037 if (IS_ERR(desc))
4038 return PTR_ERR(desc);
4039
4040 /*
4041 * If it's fast: flush the direction setting if something changed
4042 * behind our back
4043 */
4044 if (!gc->can_sleep && gc->get_direction) {
4045 int dir = gpiod_get_direction(desc);
4046
4047 if (dir < 0) {
4048 chip_err(gc, "%s: cannot get GPIO direction\n",
4049 __func__);
4050 return dir;
4051 }
4052 }
4053
4054 /* To be valid for IRQ the line needs to be input or open drain */
4055 if (test_bit(FLAG_IS_OUT, &desc->flags) &&
4056 !test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
4057 chip_err(gc,
4058 "%s: tried to flag a GPIO set as output for IRQ\n",
4059 __func__);
4060 return -EIO;
4061 }
4062
4063 set_bit(FLAG_USED_AS_IRQ, &desc->flags);
4064 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4065
4066 return 0;
4067 }
4068 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
4069
4070 /**
4071 * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
4072 * @gc: the chip the GPIO to lock belongs to
4073 * @offset: the offset of the GPIO to lock as IRQ
4074 *
4075 * This is used directly by GPIO drivers that want to indicate
4076 * that a certain GPIO is no longer used exclusively for IRQ.
4077 */
gpiochip_unlock_as_irq(struct gpio_chip * gc,unsigned int offset)4078 void gpiochip_unlock_as_irq(struct gpio_chip *gc, unsigned int offset)
4079 {
4080 struct gpio_desc *desc;
4081
4082 desc = gpiochip_get_desc(gc, offset);
4083 if (IS_ERR(desc))
4084 return;
4085
4086 clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
4087 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4088 }
4089 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
4090
gpiochip_disable_irq(struct gpio_chip * gc,unsigned int offset)4091 void gpiochip_disable_irq(struct gpio_chip *gc, unsigned int offset)
4092 {
4093 struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
4094
4095 if (!IS_ERR(desc) &&
4096 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags)))
4097 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4098 }
4099 EXPORT_SYMBOL_GPL(gpiochip_disable_irq);
4100
gpiochip_enable_irq(struct gpio_chip * gc,unsigned int offset)4101 void gpiochip_enable_irq(struct gpio_chip *gc, unsigned int offset)
4102 {
4103 struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
4104
4105 if (!IS_ERR(desc) &&
4106 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags))) {
4107 /*
4108 * We must not be output when using IRQ UNLESS we are
4109 * open drain.
4110 */
4111 WARN_ON(test_bit(FLAG_IS_OUT, &desc->flags) &&
4112 !test_bit(FLAG_OPEN_DRAIN, &desc->flags));
4113 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4114 }
4115 }
4116 EXPORT_SYMBOL_GPL(gpiochip_enable_irq);
4117
gpiochip_line_is_irq(struct gpio_chip * gc,unsigned int offset)4118 bool gpiochip_line_is_irq(struct gpio_chip *gc, unsigned int offset)
4119 {
4120 if (offset >= gc->ngpio)
4121 return false;
4122
4123 return test_bit(FLAG_USED_AS_IRQ, &gc->gpiodev->descs[offset].flags);
4124 }
4125 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
4126
gpiochip_reqres_irq(struct gpio_chip * gc,unsigned int offset)4127 int gpiochip_reqres_irq(struct gpio_chip *gc, unsigned int offset)
4128 {
4129 int ret;
4130
4131 if (!try_module_get(gc->gpiodev->owner))
4132 return -ENODEV;
4133
4134 ret = gpiochip_lock_as_irq(gc, offset);
4135 if (ret) {
4136 chip_err(gc, "unable to lock HW IRQ %u for IRQ\n", offset);
4137 module_put(gc->gpiodev->owner);
4138 return ret;
4139 }
4140 return 0;
4141 }
4142 EXPORT_SYMBOL_GPL(gpiochip_reqres_irq);
4143
gpiochip_relres_irq(struct gpio_chip * gc,unsigned int offset)4144 void gpiochip_relres_irq(struct gpio_chip *gc, unsigned int offset)
4145 {
4146 gpiochip_unlock_as_irq(gc, offset);
4147 module_put(gc->gpiodev->owner);
4148 }
4149 EXPORT_SYMBOL_GPL(gpiochip_relres_irq);
4150
gpiochip_line_is_open_drain(struct gpio_chip * gc,unsigned int offset)4151 bool gpiochip_line_is_open_drain(struct gpio_chip *gc, unsigned int offset)
4152 {
4153 if (offset >= gc->ngpio)
4154 return false;
4155
4156 return test_bit(FLAG_OPEN_DRAIN, &gc->gpiodev->descs[offset].flags);
4157 }
4158 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
4159
gpiochip_line_is_open_source(struct gpio_chip * gc,unsigned int offset)4160 bool gpiochip_line_is_open_source(struct gpio_chip *gc, unsigned int offset)
4161 {
4162 if (offset >= gc->ngpio)
4163 return false;
4164
4165 return test_bit(FLAG_OPEN_SOURCE, &gc->gpiodev->descs[offset].flags);
4166 }
4167 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
4168
gpiochip_line_is_persistent(struct gpio_chip * gc,unsigned int offset)4169 bool gpiochip_line_is_persistent(struct gpio_chip *gc, unsigned int offset)
4170 {
4171 if (offset >= gc->ngpio)
4172 return false;
4173
4174 return !test_bit(FLAG_TRANSITORY, &gc->gpiodev->descs[offset].flags);
4175 }
4176 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
4177
4178 /**
4179 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
4180 * @desc: gpio whose value will be returned
4181 *
4182 * Returns:
4183 * The GPIO's raw value, i.e. the value of the physical line disregarding
4184 * its ACTIVE_LOW status, or negative errno on failure.
4185 *
4186 * This function is to be called from contexts that can sleep.
4187 */
gpiod_get_raw_value_cansleep(const struct gpio_desc * desc)4188 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
4189 {
4190 might_sleep();
4191 VALIDATE_DESC(desc);
4192 return gpiod_get_raw_value_commit(desc);
4193 }
4194 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
4195
4196 /**
4197 * gpiod_get_value_cansleep() - return a gpio's value
4198 * @desc: gpio whose value will be returned
4199 *
4200 * Returns:
4201 * The GPIO's logical value, i.e. taking the ACTIVE_LOW status into
4202 * account, or negative errno on failure.
4203 *
4204 * This function is to be called from contexts that can sleep.
4205 */
gpiod_get_value_cansleep(const struct gpio_desc * desc)4206 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
4207 {
4208 int value;
4209
4210 might_sleep();
4211 VALIDATE_DESC(desc);
4212 value = gpiod_get_raw_value_commit(desc);
4213 if (value < 0)
4214 return value;
4215
4216 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
4217 value = !value;
4218
4219 return value;
4220 }
4221 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
4222
4223 /**
4224 * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
4225 * @array_size: number of elements in the descriptor array / value bitmap
4226 * @desc_array: array of GPIO descriptors whose values will be read
4227 * @array_info: information on applicability of fast bitmap processing path
4228 * @value_bitmap: bitmap to store the read values
4229 *
4230 * Read the raw values of the GPIOs, i.e. the values of the physical lines
4231 * without regard for their ACTIVE_LOW status.
4232 *
4233 * This function is to be called from contexts that can sleep.
4234 *
4235 * Returns:
4236 * 0 on success, or negative errno on failure.
4237 */
gpiod_get_raw_array_value_cansleep(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)4238 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
4239 struct gpio_desc **desc_array,
4240 struct gpio_array *array_info,
4241 unsigned long *value_bitmap)
4242 {
4243 might_sleep();
4244 if (!desc_array)
4245 return -EINVAL;
4246 return gpiod_get_array_value_complex(true, true, array_size,
4247 desc_array, array_info,
4248 value_bitmap);
4249 }
4250 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
4251
4252 /**
4253 * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
4254 * @array_size: number of elements in the descriptor array / value bitmap
4255 * @desc_array: array of GPIO descriptors whose values will be read
4256 * @array_info: information on applicability of fast bitmap processing path
4257 * @value_bitmap: bitmap to store the read values
4258 *
4259 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4260 * into account.
4261 *
4262 * This function is to be called from contexts that can sleep.
4263 *
4264 * Returns:
4265 * 0 on success, or negative errno on failure.
4266 */
gpiod_get_array_value_cansleep(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)4267 int gpiod_get_array_value_cansleep(unsigned int array_size,
4268 struct gpio_desc **desc_array,
4269 struct gpio_array *array_info,
4270 unsigned long *value_bitmap)
4271 {
4272 might_sleep();
4273 if (!desc_array)
4274 return -EINVAL;
4275 return gpiod_get_array_value_complex(false, true, array_size,
4276 desc_array, array_info,
4277 value_bitmap);
4278 }
4279 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
4280
4281 /**
4282 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
4283 * @desc: gpio whose value will be assigned
4284 * @value: value to assign
4285 *
4286 * Set the raw value of the GPIO, i.e. the value of its physical line without
4287 * regard for its ACTIVE_LOW status.
4288 *
4289 * This function is to be called from contexts that can sleep.
4290 *
4291 * Returns:
4292 * 0 on success, negative error number on failure.
4293 */
gpiod_set_raw_value_cansleep(struct gpio_desc * desc,int value)4294 int gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
4295 {
4296 might_sleep();
4297 VALIDATE_DESC(desc);
4298 return gpiod_set_raw_value_commit(desc, value);
4299 }
4300 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
4301
4302 /**
4303 * gpiod_set_value_cansleep() - assign a gpio's value
4304 * @desc: gpio whose value will be assigned
4305 * @value: value to assign
4306 *
4307 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
4308 * account
4309 *
4310 * This function is to be called from contexts that can sleep.
4311 *
4312 * Returns:
4313 * 0 on success, negative error number on failure.
4314 */
gpiod_set_value_cansleep(struct gpio_desc * desc,int value)4315 int gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
4316 {
4317 might_sleep();
4318 VALIDATE_DESC(desc);
4319 return gpiod_set_value_nocheck(desc, value);
4320 }
4321 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
4322
4323 /**
4324 * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
4325 * @array_size: number of elements in the descriptor array / value bitmap
4326 * @desc_array: array of GPIO descriptors whose values will be assigned
4327 * @array_info: information on applicability of fast bitmap processing path
4328 * @value_bitmap: bitmap of values to assign
4329 *
4330 * Set the raw values of the GPIOs, i.e. the values of the physical lines
4331 * without regard for their ACTIVE_LOW status.
4332 *
4333 * This function is to be called from contexts that can sleep.
4334 *
4335 * Returns:
4336 * 0 on success, or negative errno on failure.
4337 */
gpiod_set_raw_array_value_cansleep(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)4338 int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
4339 struct gpio_desc **desc_array,
4340 struct gpio_array *array_info,
4341 unsigned long *value_bitmap)
4342 {
4343 might_sleep();
4344 if (!desc_array)
4345 return -EINVAL;
4346 return gpiod_set_array_value_complex(true, true, array_size, desc_array,
4347 array_info, value_bitmap);
4348 }
4349 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
4350
4351 /**
4352 * gpiod_add_lookup_tables() - register GPIO device consumers
4353 * @tables: list of tables of consumers to register
4354 * @n: number of tables in the list
4355 */
gpiod_add_lookup_tables(struct gpiod_lookup_table ** tables,size_t n)4356 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
4357 {
4358 unsigned int i;
4359
4360 guard(mutex)(&gpio_lookup_lock);
4361
4362 for (i = 0; i < n; i++)
4363 list_add_tail(&tables[i]->list, &gpio_lookup_list);
4364 }
4365
4366 /**
4367 * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
4368 * @array_size: number of elements in the descriptor array / value bitmap
4369 * @desc_array: array of GPIO descriptors whose values will be assigned
4370 * @array_info: information on applicability of fast bitmap processing path
4371 * @value_bitmap: bitmap of values to assign
4372 *
4373 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4374 * into account.
4375 *
4376 * This function is to be called from contexts that can sleep.
4377 *
4378 * Returns:
4379 * 0 on success, or negative errno on failure.
4380 */
gpiod_set_array_value_cansleep(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)4381 int gpiod_set_array_value_cansleep(unsigned int array_size,
4382 struct gpio_desc **desc_array,
4383 struct gpio_array *array_info,
4384 unsigned long *value_bitmap)
4385 {
4386 might_sleep();
4387 if (!desc_array)
4388 return -EINVAL;
4389 return gpiod_set_array_value_complex(false, true, array_size,
4390 desc_array, array_info,
4391 value_bitmap);
4392 }
4393 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
4394
gpiod_line_state_notify(struct gpio_desc * desc,unsigned long action)4395 void gpiod_line_state_notify(struct gpio_desc *desc, unsigned long action)
4396 {
4397 guard(read_lock_irqsave)(&desc->gdev->line_state_lock);
4398
4399 raw_notifier_call_chain(&desc->gdev->line_state_notifier, action, desc);
4400 }
4401
4402 /**
4403 * gpiod_add_lookup_table() - register GPIO device consumers
4404 * @table: table of consumers to register
4405 */
gpiod_add_lookup_table(struct gpiod_lookup_table * table)4406 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
4407 {
4408 gpiod_add_lookup_tables(&table, 1);
4409 }
4410 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
4411
4412 /**
4413 * gpiod_remove_lookup_table() - unregister GPIO device consumers
4414 * @table: table of consumers to unregister
4415 */
gpiod_remove_lookup_table(struct gpiod_lookup_table * table)4416 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
4417 {
4418 /* Nothing to remove */
4419 if (!table)
4420 return;
4421
4422 guard(mutex)(&gpio_lookup_lock);
4423
4424 list_del(&table->list);
4425 }
4426 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
4427
4428 /**
4429 * gpiod_add_hogs() - register a set of GPIO hogs from machine code
4430 * @hogs: table of gpio hog entries with a zeroed sentinel at the end
4431 */
gpiod_add_hogs(struct gpiod_hog * hogs)4432 void gpiod_add_hogs(struct gpiod_hog *hogs)
4433 {
4434 struct gpiod_hog *hog;
4435
4436 guard(mutex)(&gpio_machine_hogs_mutex);
4437
4438 for (hog = &hogs[0]; hog->chip_label; hog++) {
4439 list_add_tail(&hog->list, &gpio_machine_hogs);
4440
4441 /*
4442 * The chip may have been registered earlier, so check if it
4443 * exists and, if so, try to hog the line now.
4444 */
4445 struct gpio_device *gdev __free(gpio_device_put) =
4446 gpio_device_find_by_label(hog->chip_label);
4447 if (gdev)
4448 gpiochip_machine_hog(gpio_device_get_chip(gdev), hog);
4449 }
4450 }
4451 EXPORT_SYMBOL_GPL(gpiod_add_hogs);
4452
gpiod_remove_hogs(struct gpiod_hog * hogs)4453 void gpiod_remove_hogs(struct gpiod_hog *hogs)
4454 {
4455 struct gpiod_hog *hog;
4456
4457 guard(mutex)(&gpio_machine_hogs_mutex);
4458
4459 for (hog = &hogs[0]; hog->chip_label; hog++)
4460 list_del(&hog->list);
4461 }
4462 EXPORT_SYMBOL_GPL(gpiod_remove_hogs);
4463
gpiod_find_lookup_table(struct device * dev)4464 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
4465 {
4466 const char *dev_id = dev ? dev_name(dev) : NULL;
4467 struct gpiod_lookup_table *table;
4468
4469 list_for_each_entry(table, &gpio_lookup_list, list) {
4470 if (table->dev_id && dev_id) {
4471 /*
4472 * Valid strings on both ends, must be identical to have
4473 * a match
4474 */
4475 if (!strcmp(table->dev_id, dev_id))
4476 return table;
4477 } else {
4478 /*
4479 * One of the pointers is NULL, so both must be to have
4480 * a match
4481 */
4482 if (dev_id == table->dev_id)
4483 return table;
4484 }
4485 }
4486
4487 return NULL;
4488 }
4489
gpiod_find(struct device * dev,const char * con_id,unsigned int idx,unsigned long * flags)4490 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
4491 unsigned int idx, unsigned long *flags)
4492 {
4493 struct gpio_desc *desc = ERR_PTR(-ENOENT);
4494 struct gpiod_lookup_table *table;
4495 struct gpiod_lookup *p;
4496 struct gpio_chip *gc;
4497
4498 guard(mutex)(&gpio_lookup_lock);
4499
4500 table = gpiod_find_lookup_table(dev);
4501 if (!table)
4502 return desc;
4503
4504 for (p = &table->table[0]; p->key; p++) {
4505 /* idx must always match exactly */
4506 if (p->idx != idx)
4507 continue;
4508
4509 /* If the lookup entry has a con_id, require exact match */
4510 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
4511 continue;
4512
4513 if (p->chip_hwnum == U16_MAX) {
4514 desc = gpio_name_to_desc(p->key);
4515 if (desc) {
4516 *flags = p->flags;
4517 return desc;
4518 }
4519
4520 dev_warn(dev, "cannot find GPIO line %s, deferring\n",
4521 p->key);
4522 return ERR_PTR(-EPROBE_DEFER);
4523 }
4524
4525 struct gpio_device *gdev __free(gpio_device_put) =
4526 gpio_device_find_by_label(p->key);
4527 if (!gdev) {
4528 /*
4529 * As the lookup table indicates a chip with
4530 * p->key should exist, assume it may
4531 * still appear later and let the interested
4532 * consumer be probed again or let the Deferred
4533 * Probe infrastructure handle the error.
4534 */
4535 dev_warn(dev, "cannot find GPIO chip %s, deferring\n",
4536 p->key);
4537 return ERR_PTR(-EPROBE_DEFER);
4538 }
4539
4540 gc = gpio_device_get_chip(gdev);
4541
4542 if (gc->ngpio <= p->chip_hwnum) {
4543 dev_err(dev,
4544 "requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
4545 idx, p->chip_hwnum, gc->ngpio - 1,
4546 gc->label);
4547 return ERR_PTR(-EINVAL);
4548 }
4549
4550 desc = gpio_device_get_desc(gdev, p->chip_hwnum);
4551 *flags = p->flags;
4552
4553 return desc;
4554 }
4555
4556 return desc;
4557 }
4558
platform_gpio_count(struct device * dev,const char * con_id)4559 static int platform_gpio_count(struct device *dev, const char *con_id)
4560 {
4561 struct gpiod_lookup_table *table;
4562 struct gpiod_lookup *p;
4563 unsigned int count = 0;
4564
4565 scoped_guard(mutex, &gpio_lookup_lock) {
4566 table = gpiod_find_lookup_table(dev);
4567 if (!table)
4568 return -ENOENT;
4569
4570 for (p = &table->table[0]; p->key; p++) {
4571 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
4572 (!con_id && !p->con_id))
4573 count++;
4574 }
4575 }
4576
4577 if (!count)
4578 return -ENOENT;
4579
4580 return count;
4581 }
4582
gpiod_find_by_fwnode(struct fwnode_handle * fwnode,struct device * consumer,const char * con_id,unsigned int idx,enum gpiod_flags * flags,unsigned long * lookupflags)4583 static struct gpio_desc *gpiod_find_by_fwnode(struct fwnode_handle *fwnode,
4584 struct device *consumer,
4585 const char *con_id,
4586 unsigned int idx,
4587 enum gpiod_flags *flags,
4588 unsigned long *lookupflags)
4589 {
4590 const char *name = function_name_or_default(con_id);
4591 struct gpio_desc *desc = ERR_PTR(-ENOENT);
4592
4593 if (is_of_node(fwnode)) {
4594 dev_dbg(consumer, "using DT '%pfw' for '%s' GPIO lookup\n", fwnode, name);
4595 desc = of_find_gpio(to_of_node(fwnode), con_id, idx, lookupflags);
4596 } else if (is_acpi_node(fwnode)) {
4597 dev_dbg(consumer, "using ACPI '%pfw' for '%s' GPIO lookup\n", fwnode, name);
4598 desc = acpi_find_gpio(fwnode, con_id, idx, flags, lookupflags);
4599 } else if (is_software_node(fwnode)) {
4600 dev_dbg(consumer, "using swnode '%pfw' for '%s' GPIO lookup\n", fwnode, name);
4601 desc = swnode_find_gpio(fwnode, con_id, idx, lookupflags);
4602 }
4603
4604 return desc;
4605 }
4606
gpiod_find_and_request(struct device * consumer,struct fwnode_handle * fwnode,const char * con_id,unsigned int idx,enum gpiod_flags flags,const char * label,bool platform_lookup_allowed)4607 struct gpio_desc *gpiod_find_and_request(struct device *consumer,
4608 struct fwnode_handle *fwnode,
4609 const char *con_id,
4610 unsigned int idx,
4611 enum gpiod_flags flags,
4612 const char *label,
4613 bool platform_lookup_allowed)
4614 {
4615 unsigned long lookupflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4616 const char *name = function_name_or_default(con_id);
4617 /*
4618 * scoped_guard() is implemented as a for loop, meaning static
4619 * analyzers will complain about these two not being initialized.
4620 */
4621 struct gpio_desc *desc = NULL;
4622 int ret = 0;
4623
4624 scoped_guard(srcu, &gpio_devices_srcu) {
4625 desc = gpiod_find_by_fwnode(fwnode, consumer, con_id, idx,
4626 &flags, &lookupflags);
4627 if (gpiod_not_found(desc) && platform_lookup_allowed) {
4628 /*
4629 * Either we are not using DT or ACPI, or their lookup
4630 * did not return a result. In that case, use platform
4631 * lookup as a fallback.
4632 */
4633 dev_dbg(consumer,
4634 "using lookup tables for GPIO lookup\n");
4635 desc = gpiod_find(consumer, con_id, idx, &lookupflags);
4636 }
4637
4638 if (IS_ERR(desc)) {
4639 dev_dbg(consumer, "No GPIO consumer %s found\n", name);
4640 return desc;
4641 }
4642
4643 /*
4644 * If a connection label was passed use that, else attempt to use
4645 * the device name as label
4646 */
4647 ret = gpiod_request(desc, label);
4648 }
4649 if (ret) {
4650 if (!(ret == -EBUSY && flags & GPIOD_FLAGS_BIT_NONEXCLUSIVE))
4651 return ERR_PTR(ret);
4652
4653 /*
4654 * This happens when there are several consumers for
4655 * the same GPIO line: we just return here without
4656 * further initialization. It is a bit of a hack.
4657 * This is necessary to support fixed regulators.
4658 *
4659 * FIXME: Make this more sane and safe.
4660 */
4661 dev_info(consumer, "nonexclusive access to GPIO for %s\n", name);
4662 return desc;
4663 }
4664
4665 ret = gpiod_configure_flags(desc, con_id, lookupflags, flags);
4666 if (ret < 0) {
4667 gpiod_put(desc);
4668 dev_err(consumer, "setup of GPIO %s failed: %d\n", name, ret);
4669 return ERR_PTR(ret);
4670 }
4671
4672 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_REQUESTED);
4673
4674 return desc;
4675 }
4676
4677 /**
4678 * fwnode_gpiod_get_index - obtain a GPIO from firmware node
4679 * @fwnode: handle of the firmware node
4680 * @con_id: function within the GPIO consumer
4681 * @index: index of the GPIO to obtain for the consumer
4682 * @flags: GPIO initialization flags
4683 * @label: label to attach to the requested GPIO
4684 *
4685 * This function can be used for drivers that get their configuration
4686 * from opaque firmware.
4687 *
4688 * The function properly finds the corresponding GPIO using whatever is the
4689 * underlying firmware interface and then makes sure that the GPIO
4690 * descriptor is requested before it is returned to the caller.
4691 *
4692 * Returns:
4693 * On successful request the GPIO pin is configured in accordance with
4694 * provided @flags.
4695 *
4696 * In case of error an ERR_PTR() is returned.
4697 */
fwnode_gpiod_get_index(struct fwnode_handle * fwnode,const char * con_id,int index,enum gpiod_flags flags,const char * label)4698 struct gpio_desc *fwnode_gpiod_get_index(struct fwnode_handle *fwnode,
4699 const char *con_id,
4700 int index,
4701 enum gpiod_flags flags,
4702 const char *label)
4703 {
4704 return gpiod_find_and_request(NULL, fwnode, con_id, index, flags, label, false);
4705 }
4706 EXPORT_SYMBOL_GPL(fwnode_gpiod_get_index);
4707
4708 /**
4709 * gpiod_count - return the number of GPIOs associated with a device / function
4710 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4711 * @con_id: function within the GPIO consumer
4712 *
4713 * Returns:
4714 * The number of GPIOs associated with a device / function or -ENOENT if no
4715 * GPIO has been assigned to the requested function.
4716 */
gpiod_count(struct device * dev,const char * con_id)4717 int gpiod_count(struct device *dev, const char *con_id)
4718 {
4719 const struct fwnode_handle *fwnode = dev ? dev_fwnode(dev) : NULL;
4720 int count = -ENOENT;
4721
4722 if (is_of_node(fwnode))
4723 count = of_gpio_count(fwnode, con_id);
4724 else if (is_acpi_node(fwnode))
4725 count = acpi_gpio_count(fwnode, con_id);
4726 else if (is_software_node(fwnode))
4727 count = swnode_gpio_count(fwnode, con_id);
4728
4729 if (count < 0)
4730 count = platform_gpio_count(dev, con_id);
4731
4732 return count;
4733 }
4734 EXPORT_SYMBOL_GPL(gpiod_count);
4735
4736 /**
4737 * gpiod_get - obtain a GPIO for a given GPIO function
4738 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4739 * @con_id: function within the GPIO consumer
4740 * @flags: optional GPIO initialization flags
4741 *
4742 * Returns:
4743 * The GPIO descriptor corresponding to the function @con_id of device
4744 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
4745 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
4746 */
gpiod_get(struct device * dev,const char * con_id,enum gpiod_flags flags)4747 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
4748 enum gpiod_flags flags)
4749 {
4750 return gpiod_get_index(dev, con_id, 0, flags);
4751 }
4752 EXPORT_SYMBOL_GPL(gpiod_get);
4753
4754 /**
4755 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
4756 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4757 * @con_id: function within the GPIO consumer
4758 * @flags: optional GPIO initialization flags
4759 *
4760 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
4761 * the requested function it will return NULL. This is convenient for drivers
4762 * that need to handle optional GPIOs.
4763 *
4764 * Returns:
4765 * The GPIO descriptor corresponding to the function @con_id of device
4766 * dev, NULL if no GPIO has been assigned to the requested function, or
4767 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
4768 */
gpiod_get_optional(struct device * dev,const char * con_id,enum gpiod_flags flags)4769 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
4770 const char *con_id,
4771 enum gpiod_flags flags)
4772 {
4773 return gpiod_get_index_optional(dev, con_id, 0, flags);
4774 }
4775 EXPORT_SYMBOL_GPL(gpiod_get_optional);
4776
4777
4778 /**
4779 * gpiod_configure_flags - helper function to configure a given GPIO
4780 * @desc: gpio whose value will be assigned
4781 * @con_id: function within the GPIO consumer
4782 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
4783 * of_find_gpio() or of_get_gpio_hog()
4784 * @dflags: gpiod_flags - optional GPIO initialization flags
4785 *
4786 * Returns:
4787 * 0 on success, -ENOENT if no GPIO has been assigned to the
4788 * requested function and/or index, or another IS_ERR() code if an error
4789 * occurred while trying to acquire the GPIO.
4790 */
gpiod_configure_flags(struct gpio_desc * desc,const char * con_id,unsigned long lflags,enum gpiod_flags dflags)4791 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
4792 unsigned long lflags, enum gpiod_flags dflags)
4793 {
4794 const char *name = function_name_or_default(con_id);
4795 int ret;
4796
4797 if (lflags & GPIO_ACTIVE_LOW)
4798 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
4799
4800 if (lflags & GPIO_OPEN_DRAIN)
4801 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4802 else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
4803 /*
4804 * This enforces open drain mode from the consumer side.
4805 * This is necessary for some busses like I2C, but the lookup
4806 * should *REALLY* have specified them as open drain in the
4807 * first place, so print a little warning here.
4808 */
4809 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4810 gpiod_warn(desc,
4811 "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
4812 }
4813
4814 if (lflags & GPIO_OPEN_SOURCE)
4815 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
4816
4817 if (((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DOWN)) ||
4818 ((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DISABLE)) ||
4819 ((lflags & GPIO_PULL_DOWN) && (lflags & GPIO_PULL_DISABLE))) {
4820 gpiod_err(desc,
4821 "multiple pull-up, pull-down or pull-disable enabled, invalid configuration\n");
4822 return -EINVAL;
4823 }
4824
4825 if (lflags & GPIO_PULL_UP)
4826 set_bit(FLAG_PULL_UP, &desc->flags);
4827 else if (lflags & GPIO_PULL_DOWN)
4828 set_bit(FLAG_PULL_DOWN, &desc->flags);
4829 else if (lflags & GPIO_PULL_DISABLE)
4830 set_bit(FLAG_BIAS_DISABLE, &desc->flags);
4831
4832 ret = gpiod_set_transitory(desc, (lflags & GPIO_TRANSITORY));
4833 if (ret < 0)
4834 return ret;
4835
4836 /* No particular flag request, return here... */
4837 if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
4838 gpiod_dbg(desc, "no flags found for GPIO %s\n", name);
4839 return 0;
4840 }
4841
4842 /* Process flags */
4843 if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
4844 ret = gpiod_direction_output_nonotify(desc,
4845 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
4846 else
4847 ret = gpiod_direction_input_nonotify(desc);
4848
4849 return ret;
4850 }
4851
4852 /**
4853 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
4854 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4855 * @con_id: function within the GPIO consumer
4856 * @idx: index of the GPIO to obtain in the consumer
4857 * @flags: optional GPIO initialization flags
4858 *
4859 * This variant of gpiod_get() allows to access GPIOs other than the first
4860 * defined one for functions that define several GPIOs.
4861 *
4862 * Returns:
4863 * A valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
4864 * requested function and/or index, or another IS_ERR() code if an error
4865 * occurred while trying to acquire the GPIO.
4866 */
gpiod_get_index(struct device * dev,const char * con_id,unsigned int idx,enum gpiod_flags flags)4867 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
4868 const char *con_id,
4869 unsigned int idx,
4870 enum gpiod_flags flags)
4871 {
4872 struct fwnode_handle *fwnode = dev ? dev_fwnode(dev) : NULL;
4873 const char *devname = dev ? dev_name(dev) : "?";
4874 const char *label = con_id ?: devname;
4875
4876 return gpiod_find_and_request(dev, fwnode, con_id, idx, flags, label, true);
4877 }
4878 EXPORT_SYMBOL_GPL(gpiod_get_index);
4879
4880 /**
4881 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
4882 * function
4883 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4884 * @con_id: function within the GPIO consumer
4885 * @index: index of the GPIO to obtain in the consumer
4886 * @flags: optional GPIO initialization flags
4887 *
4888 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
4889 * specified index was assigned to the requested function it will return NULL.
4890 * This is convenient for drivers that need to handle optional GPIOs.
4891 *
4892 * Returns:
4893 * A valid GPIO descriptor, NULL if no GPIO has been assigned to the
4894 * requested function and/or index, or another IS_ERR() code if an error
4895 * occurred while trying to acquire the GPIO.
4896 */
gpiod_get_index_optional(struct device * dev,const char * con_id,unsigned int index,enum gpiod_flags flags)4897 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
4898 const char *con_id,
4899 unsigned int index,
4900 enum gpiod_flags flags)
4901 {
4902 struct gpio_desc *desc;
4903
4904 desc = gpiod_get_index(dev, con_id, index, flags);
4905 if (gpiod_not_found(desc))
4906 return NULL;
4907
4908 return desc;
4909 }
4910 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
4911
4912 /**
4913 * gpiod_hog - Hog the specified GPIO desc given the provided flags
4914 * @desc: gpio whose value will be assigned
4915 * @name: gpio line name
4916 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
4917 * of_find_gpio() or of_get_gpio_hog()
4918 * @dflags: gpiod_flags - optional GPIO initialization flags
4919 *
4920 * Returns:
4921 * 0 on success, or negative errno on failure.
4922 */
gpiod_hog(struct gpio_desc * desc,const char * name,unsigned long lflags,enum gpiod_flags dflags)4923 int gpiod_hog(struct gpio_desc *desc, const char *name,
4924 unsigned long lflags, enum gpiod_flags dflags)
4925 {
4926 struct gpio_device *gdev = desc->gdev;
4927 struct gpio_desc *local_desc;
4928 int hwnum;
4929 int ret;
4930
4931 CLASS(gpio_chip_guard, guard)(desc);
4932 if (!guard.gc)
4933 return -ENODEV;
4934
4935 if (test_and_set_bit(FLAG_IS_HOGGED, &desc->flags))
4936 return 0;
4937
4938 hwnum = gpio_chip_hwgpio(desc);
4939
4940 local_desc = gpiochip_request_own_desc(guard.gc, hwnum, name,
4941 lflags, dflags);
4942 if (IS_ERR(local_desc)) {
4943 clear_bit(FLAG_IS_HOGGED, &desc->flags);
4944 ret = PTR_ERR(local_desc);
4945 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
4946 name, gdev->label, hwnum, ret);
4947 return ret;
4948 }
4949
4950 gpiod_dbg(desc, "hogged as %s/%s\n",
4951 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
4952 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ?
4953 str_high_low(dflags & GPIOD_FLAGS_BIT_DIR_VAL) : "?");
4954
4955 return 0;
4956 }
4957
4958 /**
4959 * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
4960 * @gc: gpio chip to act on
4961 */
gpiochip_free_hogs(struct gpio_chip * gc)4962 static void gpiochip_free_hogs(struct gpio_chip *gc)
4963 {
4964 struct gpio_desc *desc;
4965
4966 for_each_gpio_desc_with_flag(gc, desc, FLAG_IS_HOGGED)
4967 gpiochip_free_own_desc(desc);
4968 }
4969
4970 /**
4971 * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
4972 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4973 * @con_id: function within the GPIO consumer
4974 * @flags: optional GPIO initialization flags
4975 *
4976 * This function acquires all the GPIOs defined under a given function.
4977 *
4978 * Returns:
4979 * The GPIO descriptors corresponding to the function @con_id of device
4980 * dev, -ENOENT if no GPIO has been assigned to the requested function,
4981 * or another IS_ERR() code if an error occurred while trying to acquire
4982 * the GPIOs.
4983 */
gpiod_get_array(struct device * dev,const char * con_id,enum gpiod_flags flags)4984 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
4985 const char *con_id,
4986 enum gpiod_flags flags)
4987 {
4988 struct gpio_desc *desc;
4989 struct gpio_descs *descs;
4990 struct gpio_device *gdev;
4991 struct gpio_array *array_info = NULL;
4992 int count, bitmap_size;
4993 unsigned long dflags;
4994 size_t descs_size;
4995
4996 count = gpiod_count(dev, con_id);
4997 if (count < 0)
4998 return ERR_PTR(count);
4999
5000 descs_size = struct_size(descs, desc, count);
5001 descs = kzalloc(descs_size, GFP_KERNEL);
5002 if (!descs)
5003 return ERR_PTR(-ENOMEM);
5004
5005 for (descs->ndescs = 0; descs->ndescs < count; descs->ndescs++) {
5006 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
5007 if (IS_ERR(desc)) {
5008 gpiod_put_array(descs);
5009 return ERR_CAST(desc);
5010 }
5011
5012 descs->desc[descs->ndescs] = desc;
5013
5014 gdev = gpiod_to_gpio_device(desc);
5015 /*
5016 * If pin hardware number of array member 0 is also 0, select
5017 * its chip as a candidate for fast bitmap processing path.
5018 */
5019 if (descs->ndescs == 0 && gpio_chip_hwgpio(desc) == 0) {
5020 struct gpio_descs *array;
5021
5022 bitmap_size = BITS_TO_LONGS(gdev->ngpio > count ?
5023 gdev->ngpio : count);
5024
5025 array = krealloc(descs, descs_size +
5026 struct_size(array_info, invert_mask, 3 * bitmap_size),
5027 GFP_KERNEL | __GFP_ZERO);
5028 if (!array) {
5029 gpiod_put_array(descs);
5030 return ERR_PTR(-ENOMEM);
5031 }
5032
5033 descs = array;
5034
5035 array_info = (void *)descs + descs_size;
5036 array_info->get_mask = array_info->invert_mask +
5037 bitmap_size;
5038 array_info->set_mask = array_info->get_mask +
5039 bitmap_size;
5040
5041 array_info->desc = descs->desc;
5042 array_info->size = count;
5043 array_info->gdev = gdev;
5044 bitmap_set(array_info->get_mask, descs->ndescs,
5045 count - descs->ndescs);
5046 bitmap_set(array_info->set_mask, descs->ndescs,
5047 count - descs->ndescs);
5048 descs->info = array_info;
5049 }
5050
5051 /* If there is no cache for fast bitmap processing path, continue */
5052 if (!array_info)
5053 continue;
5054
5055 /* Unmark array members which don't belong to the 'fast' chip */
5056 if (array_info->gdev != gdev) {
5057 __clear_bit(descs->ndescs, array_info->get_mask);
5058 __clear_bit(descs->ndescs, array_info->set_mask);
5059 }
5060 /*
5061 * Detect array members which belong to the 'fast' chip
5062 * but their pins are not in hardware order.
5063 */
5064 else if (gpio_chip_hwgpio(desc) != descs->ndescs) {
5065 /*
5066 * Don't use fast path if all array members processed so
5067 * far belong to the same chip as this one but its pin
5068 * hardware number is different from its array index.
5069 */
5070 if (bitmap_full(array_info->get_mask, descs->ndescs)) {
5071 array_info = NULL;
5072 } else {
5073 __clear_bit(descs->ndescs,
5074 array_info->get_mask);
5075 __clear_bit(descs->ndescs,
5076 array_info->set_mask);
5077 }
5078 } else {
5079 dflags = READ_ONCE(desc->flags);
5080 /* Exclude open drain or open source from fast output */
5081 if (test_bit(FLAG_OPEN_DRAIN, &dflags) ||
5082 test_bit(FLAG_OPEN_SOURCE, &dflags))
5083 __clear_bit(descs->ndescs,
5084 array_info->set_mask);
5085 /* Identify 'fast' pins which require invertion */
5086 if (gpiod_is_active_low(desc))
5087 __set_bit(descs->ndescs,
5088 array_info->invert_mask);
5089 }
5090 }
5091 if (array_info)
5092 dev_dbg(dev,
5093 "GPIO array info: chip=%s, size=%d, get_mask=%lx, set_mask=%lx, invert_mask=%lx\n",
5094 array_info->gdev->label, array_info->size,
5095 *array_info->get_mask, *array_info->set_mask,
5096 *array_info->invert_mask);
5097 return descs;
5098 }
5099 EXPORT_SYMBOL_GPL(gpiod_get_array);
5100
5101 /**
5102 * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
5103 * function
5104 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5105 * @con_id: function within the GPIO consumer
5106 * @flags: optional GPIO initialization flags
5107 *
5108 * This is equivalent to gpiod_get_array(), except that when no GPIO was
5109 * assigned to the requested function it will return NULL.
5110 *
5111 * Returns:
5112 * The GPIO descriptors corresponding to the function @con_id of device
5113 * dev, NULL if no GPIO has been assigned to the requested function,
5114 * or another IS_ERR() code if an error occurred while trying to acquire
5115 * the GPIOs.
5116 */
gpiod_get_array_optional(struct device * dev,const char * con_id,enum gpiod_flags flags)5117 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
5118 const char *con_id,
5119 enum gpiod_flags flags)
5120 {
5121 struct gpio_descs *descs;
5122
5123 descs = gpiod_get_array(dev, con_id, flags);
5124 if (gpiod_not_found(descs))
5125 return NULL;
5126
5127 return descs;
5128 }
5129 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
5130
5131 /**
5132 * gpiod_put - dispose of a GPIO descriptor
5133 * @desc: GPIO descriptor to dispose of
5134 *
5135 * No descriptor can be used after gpiod_put() has been called on it.
5136 */
gpiod_put(struct gpio_desc * desc)5137 void gpiod_put(struct gpio_desc *desc)
5138 {
5139 gpiod_free(desc);
5140 }
5141 EXPORT_SYMBOL_GPL(gpiod_put);
5142
5143 /**
5144 * gpiod_put_array - dispose of multiple GPIO descriptors
5145 * @descs: struct gpio_descs containing an array of descriptors
5146 */
gpiod_put_array(struct gpio_descs * descs)5147 void gpiod_put_array(struct gpio_descs *descs)
5148 {
5149 unsigned int i;
5150
5151 for (i = 0; i < descs->ndescs; i++)
5152 gpiod_put(descs->desc[i]);
5153
5154 kfree(descs);
5155 }
5156 EXPORT_SYMBOL_GPL(gpiod_put_array);
5157
gpio_stub_drv_probe(struct device * dev)5158 static int gpio_stub_drv_probe(struct device *dev)
5159 {
5160 /*
5161 * The DT node of some GPIO chips have a "compatible" property, but
5162 * never have a struct device added and probed by a driver to register
5163 * the GPIO chip with gpiolib. In such cases, fw_devlink=on will cause
5164 * the consumers of the GPIO chip to get probe deferred forever because
5165 * they will be waiting for a device associated with the GPIO chip
5166 * firmware node to get added and bound to a driver.
5167 *
5168 * To allow these consumers to probe, we associate the struct
5169 * gpio_device of the GPIO chip with the firmware node and then simply
5170 * bind it to this stub driver.
5171 */
5172 return 0;
5173 }
5174
5175 static struct device_driver gpio_stub_drv = {
5176 .name = "gpio_stub_drv",
5177 .bus = &gpio_bus_type,
5178 .probe = gpio_stub_drv_probe,
5179 };
5180
gpiolib_dev_init(void)5181 static int __init gpiolib_dev_init(void)
5182 {
5183 int ret;
5184
5185 /* Register GPIO sysfs bus */
5186 ret = bus_register(&gpio_bus_type);
5187 if (ret < 0) {
5188 pr_err("gpiolib: could not register GPIO bus type\n");
5189 return ret;
5190 }
5191
5192 ret = driver_register(&gpio_stub_drv);
5193 if (ret < 0) {
5194 pr_err("gpiolib: could not register GPIO stub driver\n");
5195 bus_unregister(&gpio_bus_type);
5196 return ret;
5197 }
5198
5199 ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, GPIOCHIP_NAME);
5200 if (ret < 0) {
5201 pr_err("gpiolib: failed to allocate char dev region\n");
5202 driver_unregister(&gpio_stub_drv);
5203 bus_unregister(&gpio_bus_type);
5204 return ret;
5205 }
5206
5207 gpiolib_initialized = true;
5208 gpiochip_setup_devs();
5209
5210 #if IS_ENABLED(CONFIG_OF_DYNAMIC) && IS_ENABLED(CONFIG_OF_GPIO)
5211 WARN_ON(of_reconfig_notifier_register(&gpio_of_notifier));
5212 #endif /* CONFIG_OF_DYNAMIC && CONFIG_OF_GPIO */
5213
5214 return ret;
5215 }
5216 core_initcall(gpiolib_dev_init);
5217
5218 #ifdef CONFIG_DEBUG_FS
5219
gpiolib_dbg_show(struct seq_file * s,struct gpio_device * gdev)5220 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
5221 {
5222 bool active_low, is_irq, is_out;
5223 struct gpio_desc *desc;
5224 unsigned int gpio = 0;
5225 struct gpio_chip *gc;
5226 unsigned long flags;
5227 int value;
5228
5229 guard(srcu)(&gdev->srcu);
5230
5231 gc = srcu_dereference(gdev->chip, &gdev->srcu);
5232 if (!gc) {
5233 seq_puts(s, "Underlying GPIO chip is gone\n");
5234 return;
5235 }
5236
5237 for_each_gpio_desc(gc, desc) {
5238 guard(srcu)(&desc->gdev->desc_srcu);
5239 flags = READ_ONCE(desc->flags);
5240 is_irq = test_bit(FLAG_USED_AS_IRQ, &flags);
5241 if (is_irq || test_bit(FLAG_REQUESTED, &flags)) {
5242 gpiod_get_direction(desc);
5243 is_out = test_bit(FLAG_IS_OUT, &flags);
5244 value = gpio_chip_get_value(gc, desc);
5245 active_low = test_bit(FLAG_ACTIVE_LOW, &flags);
5246 seq_printf(s, " gpio-%-3u (%-20.20s|%-20.20s) %s %s %s%s\n",
5247 gpio, desc->name ?: "", gpiod_get_label(desc),
5248 is_out ? "out" : "in ",
5249 value >= 0 ? str_hi_lo(value) : "? ",
5250 is_irq ? "IRQ " : "",
5251 active_low ? "ACTIVE LOW" : "");
5252 } else if (desc->name) {
5253 seq_printf(s, " gpio-%-3u (%-20.20s)\n", gpio, desc->name);
5254 }
5255
5256 gpio++;
5257 }
5258 }
5259
5260 struct gpiolib_seq_priv {
5261 bool newline;
5262 int idx;
5263 };
5264
gpiolib_seq_start(struct seq_file * s,loff_t * pos)5265 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
5266 {
5267 struct gpiolib_seq_priv *priv;
5268 struct gpio_device *gdev;
5269 loff_t index = *pos;
5270
5271 priv = kzalloc(sizeof(*priv), GFP_KERNEL);
5272 if (!priv)
5273 return NULL;
5274
5275 s->private = priv;
5276 if (*pos > 0)
5277 priv->newline = true;
5278 priv->idx = srcu_read_lock(&gpio_devices_srcu);
5279
5280 list_for_each_entry_srcu(gdev, &gpio_devices, list,
5281 srcu_read_lock_held(&gpio_devices_srcu)) {
5282 if (index-- == 0)
5283 return gdev;
5284 }
5285
5286 return NULL;
5287 }
5288
gpiolib_seq_next(struct seq_file * s,void * v,loff_t * pos)5289 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
5290 {
5291 struct gpiolib_seq_priv *priv = s->private;
5292 struct gpio_device *gdev = v, *next;
5293
5294 next = list_entry_rcu(gdev->list.next, struct gpio_device, list);
5295 gdev = &next->list == &gpio_devices ? NULL : next;
5296 priv->newline = true;
5297 ++*pos;
5298
5299 return gdev;
5300 }
5301
gpiolib_seq_stop(struct seq_file * s,void * v)5302 static void gpiolib_seq_stop(struct seq_file *s, void *v)
5303 {
5304 struct gpiolib_seq_priv *priv = s->private;
5305
5306 srcu_read_unlock(&gpio_devices_srcu, priv->idx);
5307 kfree(priv);
5308 }
5309
gpiolib_seq_show(struct seq_file * s,void * v)5310 static int gpiolib_seq_show(struct seq_file *s, void *v)
5311 {
5312 struct gpiolib_seq_priv *priv = s->private;
5313 struct gpio_device *gdev = v;
5314 struct gpio_chip *gc;
5315 struct device *parent;
5316
5317 if (priv->newline)
5318 seq_putc(s, '\n');
5319
5320 guard(srcu)(&gdev->srcu);
5321
5322 gc = srcu_dereference(gdev->chip, &gdev->srcu);
5323 if (!gc) {
5324 seq_printf(s, "%s: (dangling chip)\n", dev_name(&gdev->dev));
5325 return 0;
5326 }
5327
5328 seq_printf(s, "%s: %u GPIOs", dev_name(&gdev->dev), gdev->ngpio);
5329 parent = gc->parent;
5330 if (parent)
5331 seq_printf(s, ", parent: %s/%s",
5332 parent->bus ? parent->bus->name : "no-bus",
5333 dev_name(parent));
5334 if (gc->label)
5335 seq_printf(s, ", %s", gc->label);
5336 if (gc->can_sleep)
5337 seq_printf(s, ", can sleep");
5338 seq_printf(s, ":\n");
5339
5340 if (gc->dbg_show)
5341 gc->dbg_show(s, gc);
5342 else
5343 gpiolib_dbg_show(s, gdev);
5344
5345 return 0;
5346 }
5347
5348 static const struct seq_operations gpiolib_sops = {
5349 .start = gpiolib_seq_start,
5350 .next = gpiolib_seq_next,
5351 .stop = gpiolib_seq_stop,
5352 .show = gpiolib_seq_show,
5353 };
5354 DEFINE_SEQ_ATTRIBUTE(gpiolib);
5355
gpiolib_debugfs_init(void)5356 static int __init gpiolib_debugfs_init(void)
5357 {
5358 /* /sys/kernel/debug/gpio */
5359 debugfs_create_file("gpio", 0444, NULL, NULL, &gpiolib_fops);
5360 return 0;
5361 }
5362 subsys_initcall(gpiolib_debugfs_init);
5363
5364 #endif /* DEBUG_FS */
5365