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(GPIOD_FLAG_USED_AS_IRQ, &flags))
131 return label ? label->str : "interrupt";
132
133 if (!test_bit(GPIOD_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(GPIOD_FLAG_OPEN_DRAIN, &flags) &&
454 test_bit(GPIOD_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(GPIOD_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, GPIOD_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(GPIOD_FLAG_IS_OUT, &desc->flags,
1173 !gc->get_direction(gc, desc_index));
1174 else
1175 assign_bit(GPIOD_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_with_pins() - 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 * @pins: the list of non consecutive pins to accumulate in this range (if not
2358 * NULL, pin_offset is ignored by pinctrl core)
2359 * @npins: the number of pins from the offset of each pin space (GPIO and
2360 * pin controller) to accumulate in this range
2361 *
2362 * Calling this function directly from a DeviceTree-supported
2363 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2364 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2365 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2366 *
2367 * Returns:
2368 * 0 on success, or a negative errno on failure.
2369 */
gpiochip_add_pin_range_with_pins(struct gpio_chip * gc,const char * pinctl_name,unsigned int gpio_offset,unsigned int pin_offset,unsigned int const * pins,unsigned int npins)2370 int gpiochip_add_pin_range_with_pins(struct gpio_chip *gc,
2371 const char *pinctl_name,
2372 unsigned int gpio_offset,
2373 unsigned int pin_offset,
2374 unsigned int const *pins,
2375 unsigned int npins)
2376 {
2377 struct gpio_pin_range *pin_range;
2378 struct gpio_device *gdev = gc->gpiodev;
2379 int ret;
2380
2381 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2382 if (!pin_range) {
2383 chip_err(gc, "failed to allocate pin ranges\n");
2384 return -ENOMEM;
2385 }
2386
2387 /* Use local offset as range ID */
2388 pin_range->range.id = gpio_offset;
2389 pin_range->range.gc = gc;
2390 pin_range->range.name = gc->label;
2391 pin_range->range.base = gdev->base + gpio_offset;
2392 pin_range->range.pin_base = pin_offset;
2393 pin_range->range.pins = pins;
2394 pin_range->range.npins = npins;
2395 pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
2396 &pin_range->range);
2397 if (IS_ERR(pin_range->pctldev)) {
2398 ret = PTR_ERR(pin_range->pctldev);
2399 chip_err(gc, "could not create pin range\n");
2400 kfree(pin_range);
2401 return ret;
2402 }
2403 if (pin_range->range.pins)
2404 chip_dbg(gc, "created GPIO range %d->%d ==> %s %d sparse PIN range { %d, ... }",
2405 gpio_offset, gpio_offset + npins - 1,
2406 pinctl_name, npins, pins[0]);
2407 else
2408 chip_dbg(gc, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
2409 gpio_offset, gpio_offset + npins - 1,
2410 pinctl_name,
2411 pin_offset, pin_offset + npins - 1);
2412
2413 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2414
2415 return 0;
2416 }
2417 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range_with_pins);
2418
2419 /**
2420 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2421 * @gc: the chip to remove all the mappings for
2422 */
gpiochip_remove_pin_ranges(struct gpio_chip * gc)2423 void gpiochip_remove_pin_ranges(struct gpio_chip *gc)
2424 {
2425 struct gpio_pin_range *pin_range, *tmp;
2426 struct gpio_device *gdev = gc->gpiodev;
2427
2428 list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2429 list_del(&pin_range->node);
2430 pinctrl_remove_gpio_range(pin_range->pctldev,
2431 &pin_range->range);
2432 kfree(pin_range);
2433 }
2434 }
2435 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
2436
2437 #endif /* CONFIG_PINCTRL */
2438
2439 /* These "optional" allocation calls help prevent drivers from stomping
2440 * on each other, and help provide better diagnostics in debugfs.
2441 * They're called even less than the "set direction" calls.
2442 */
gpiod_request_commit(struct gpio_desc * desc,const char * label)2443 static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
2444 {
2445 unsigned int offset;
2446 int ret;
2447
2448 CLASS(gpio_chip_guard, guard)(desc);
2449 if (!guard.gc)
2450 return -ENODEV;
2451
2452 if (test_and_set_bit(GPIOD_FLAG_REQUESTED, &desc->flags))
2453 return -EBUSY;
2454
2455 offset = gpio_chip_hwgpio(desc);
2456 if (!gpiochip_line_is_valid(guard.gc, offset))
2457 return -EINVAL;
2458
2459 /* NOTE: gpio_request() can be called in early boot,
2460 * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
2461 */
2462
2463 if (guard.gc->request) {
2464 ret = guard.gc->request(guard.gc, offset);
2465 if (ret > 0)
2466 ret = -EBADE;
2467 if (ret)
2468 goto out_clear_bit;
2469 }
2470
2471 if (guard.gc->get_direction)
2472 gpiod_get_direction(desc);
2473
2474 ret = desc_set_label(desc, label ? : "?");
2475 if (ret)
2476 goto out_clear_bit;
2477
2478 return 0;
2479
2480 out_clear_bit:
2481 clear_bit(GPIOD_FLAG_REQUESTED, &desc->flags);
2482 return ret;
2483 }
2484
gpiod_request(struct gpio_desc * desc,const char * label)2485 int gpiod_request(struct gpio_desc *desc, const char *label)
2486 {
2487 int ret = -EPROBE_DEFER;
2488
2489 VALIDATE_DESC(desc);
2490
2491 if (try_module_get(desc->gdev->owner)) {
2492 ret = gpiod_request_commit(desc, label);
2493 if (ret)
2494 module_put(desc->gdev->owner);
2495 else
2496 gpio_device_get(desc->gdev);
2497 }
2498
2499 if (ret)
2500 gpiod_dbg(desc, "%s: status %d\n", __func__, ret);
2501
2502 return ret;
2503 }
2504
gpiod_free_commit(struct gpio_desc * desc)2505 static void gpiod_free_commit(struct gpio_desc *desc)
2506 {
2507 unsigned long flags;
2508
2509 might_sleep();
2510
2511 CLASS(gpio_chip_guard, guard)(desc);
2512
2513 flags = READ_ONCE(desc->flags);
2514
2515 if (guard.gc && test_bit(GPIOD_FLAG_REQUESTED, &flags)) {
2516 if (guard.gc->free)
2517 guard.gc->free(guard.gc, gpio_chip_hwgpio(desc));
2518
2519 clear_bit(GPIOD_FLAG_ACTIVE_LOW, &flags);
2520 clear_bit(GPIOD_FLAG_REQUESTED, &flags);
2521 clear_bit(GPIOD_FLAG_OPEN_DRAIN, &flags);
2522 clear_bit(GPIOD_FLAG_OPEN_SOURCE, &flags);
2523 clear_bit(GPIOD_FLAG_PULL_UP, &flags);
2524 clear_bit(GPIOD_FLAG_PULL_DOWN, &flags);
2525 clear_bit(GPIOD_FLAG_BIAS_DISABLE, &flags);
2526 clear_bit(GPIOD_FLAG_EDGE_RISING, &flags);
2527 clear_bit(GPIOD_FLAG_EDGE_FALLING, &flags);
2528 clear_bit(GPIOD_FLAG_IS_HOGGED, &flags);
2529 #ifdef CONFIG_OF_DYNAMIC
2530 WRITE_ONCE(desc->hog, NULL);
2531 #endif
2532 desc_set_label(desc, NULL);
2533 WRITE_ONCE(desc->flags, flags);
2534 #ifdef CONFIG_GPIO_CDEV
2535 WRITE_ONCE(desc->debounce_period_us, 0);
2536 #endif
2537 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_RELEASED);
2538 }
2539 }
2540
gpiod_free(struct gpio_desc * desc)2541 void gpiod_free(struct gpio_desc *desc)
2542 {
2543 VALIDATE_DESC_VOID(desc);
2544
2545 gpiod_free_commit(desc);
2546 module_put(desc->gdev->owner);
2547 gpio_device_put(desc->gdev);
2548 }
2549
2550 /**
2551 * gpiochip_dup_line_label - Get a copy of the consumer label.
2552 * @gc: GPIO chip controlling this line.
2553 * @offset: Hardware offset of the line.
2554 *
2555 * Returns:
2556 * Pointer to a copy of the consumer label if the line is requested or NULL
2557 * if it's not. If a valid pointer was returned, it must be freed using
2558 * kfree(). In case of a memory allocation error, the function returns %ENOMEM.
2559 *
2560 * Must not be called from atomic context.
2561 */
gpiochip_dup_line_label(struct gpio_chip * gc,unsigned int offset)2562 char *gpiochip_dup_line_label(struct gpio_chip *gc, unsigned int offset)
2563 {
2564 struct gpio_desc *desc;
2565 char *label;
2566
2567 desc = gpiochip_get_desc(gc, offset);
2568 if (IS_ERR(desc))
2569 return NULL;
2570
2571 if (!test_bit(GPIOD_FLAG_REQUESTED, &desc->flags))
2572 return NULL;
2573
2574 guard(srcu)(&desc->gdev->desc_srcu);
2575
2576 label = kstrdup(gpiod_get_label(desc), GFP_KERNEL);
2577 if (!label)
2578 return ERR_PTR(-ENOMEM);
2579
2580 return label;
2581 }
2582 EXPORT_SYMBOL_GPL(gpiochip_dup_line_label);
2583
function_name_or_default(const char * con_id)2584 static inline const char *function_name_or_default(const char *con_id)
2585 {
2586 return con_id ?: "(default)";
2587 }
2588
2589 /**
2590 * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
2591 * @gc: GPIO chip
2592 * @hwnum: hardware number of the GPIO for which to request the descriptor
2593 * @label: label for the GPIO
2594 * @lflags: lookup flags for this GPIO or 0 if default, this can be used to
2595 * specify things like line inversion semantics with the machine flags
2596 * such as GPIO_OUT_LOW
2597 * @dflags: descriptor request flags for this GPIO or 0 if default, this
2598 * can be used to specify consumer semantics such as open drain
2599 *
2600 * Function allows GPIO chip drivers to request and use their own GPIO
2601 * descriptors via gpiolib API. Difference to gpiod_request() is that this
2602 * function will not increase reference count of the GPIO chip module. This
2603 * allows the GPIO chip module to be unloaded as needed (we assume that the
2604 * GPIO chip driver handles freeing the GPIOs it has requested).
2605 *
2606 * Returns:
2607 * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
2608 * code on failure.
2609 */
gpiochip_request_own_desc(struct gpio_chip * gc,unsigned int hwnum,const char * label,enum gpio_lookup_flags lflags,enum gpiod_flags dflags)2610 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *gc,
2611 unsigned int hwnum,
2612 const char *label,
2613 enum gpio_lookup_flags lflags,
2614 enum gpiod_flags dflags)
2615 {
2616 struct gpio_desc *desc = gpiochip_get_desc(gc, hwnum);
2617 const char *name = function_name_or_default(label);
2618 int ret;
2619
2620 if (IS_ERR(desc)) {
2621 chip_err(gc, "failed to get GPIO %s descriptor\n", name);
2622 return desc;
2623 }
2624
2625 ret = gpiod_request_commit(desc, label);
2626 if (ret < 0)
2627 return ERR_PTR(ret);
2628
2629 ret = gpiod_configure_flags(desc, label, lflags, dflags);
2630 if (ret) {
2631 gpiod_free_commit(desc);
2632 chip_err(gc, "setup of own GPIO %s failed\n", name);
2633 return ERR_PTR(ret);
2634 }
2635
2636 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_REQUESTED);
2637
2638 return desc;
2639 }
2640 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
2641
2642 /**
2643 * gpiochip_free_own_desc - Free GPIO requested by the chip driver
2644 * @desc: GPIO descriptor to free
2645 *
2646 * Function frees the given GPIO requested previously with
2647 * gpiochip_request_own_desc().
2648 */
gpiochip_free_own_desc(struct gpio_desc * desc)2649 void gpiochip_free_own_desc(struct gpio_desc *desc)
2650 {
2651 if (desc)
2652 gpiod_free_commit(desc);
2653 }
2654 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
2655
2656 /*
2657 * Drivers MUST set GPIO direction before making get/set calls. In
2658 * some cases this is done in early boot, before IRQs are enabled.
2659 *
2660 * As a rule these aren't called more than once (except for drivers
2661 * using the open-drain emulation idiom) so these are natural places
2662 * to accumulate extra debugging checks. Note that we can't (yet)
2663 * rely on gpio_request() having been called beforehand.
2664 */
2665
gpio_do_set_config(struct gpio_desc * desc,unsigned long config)2666 int gpio_do_set_config(struct gpio_desc *desc, unsigned long config)
2667 {
2668 int ret;
2669
2670 CLASS(gpio_chip_guard, guard)(desc);
2671 if (!guard.gc)
2672 return -ENODEV;
2673
2674 if (!guard.gc->set_config)
2675 return -ENOTSUPP;
2676
2677 ret = guard.gc->set_config(guard.gc, gpio_chip_hwgpio(desc), config);
2678 if (ret > 0)
2679 ret = -EBADE;
2680
2681 #ifdef CONFIG_GPIO_CDEV
2682 /*
2683 * Special case - if we're setting debounce period, we need to store
2684 * it in the descriptor in case user-space wants to know it.
2685 */
2686 if (!ret && pinconf_to_config_param(config) == PIN_CONFIG_INPUT_DEBOUNCE)
2687 WRITE_ONCE(desc->debounce_period_us,
2688 pinconf_to_config_argument(config));
2689 #endif
2690 return ret;
2691 }
2692
gpio_set_config_with_argument(struct gpio_desc * desc,enum pin_config_param mode,u32 argument)2693 static int gpio_set_config_with_argument(struct gpio_desc *desc,
2694 enum pin_config_param mode,
2695 u32 argument)
2696 {
2697 unsigned long config;
2698
2699 config = pinconf_to_config_packed(mode, argument);
2700 return gpio_do_set_config(desc, config);
2701 }
2702
gpio_set_config_with_argument_optional(struct gpio_desc * desc,enum pin_config_param mode,u32 argument)2703 static int gpio_set_config_with_argument_optional(struct gpio_desc *desc,
2704 enum pin_config_param mode,
2705 u32 argument)
2706 {
2707 struct device *dev = &desc->gdev->dev;
2708 int gpio = gpio_chip_hwgpio(desc);
2709 int ret;
2710
2711 ret = gpio_set_config_with_argument(desc, mode, argument);
2712 if (ret != -ENOTSUPP)
2713 return ret;
2714
2715 switch (mode) {
2716 case PIN_CONFIG_PERSIST_STATE:
2717 dev_dbg(dev, "Persistence not supported for GPIO %d\n", gpio);
2718 break;
2719 default:
2720 break;
2721 }
2722
2723 return 0;
2724 }
2725
gpio_set_config(struct gpio_desc * desc,enum pin_config_param mode)2726 static int gpio_set_config(struct gpio_desc *desc, enum pin_config_param mode)
2727 {
2728 return gpio_set_config_with_argument(desc, mode, 0);
2729 }
2730
gpio_set_bias(struct gpio_desc * desc)2731 static int gpio_set_bias(struct gpio_desc *desc)
2732 {
2733 enum pin_config_param bias;
2734 unsigned long flags;
2735 unsigned int arg;
2736
2737 flags = READ_ONCE(desc->flags);
2738
2739 if (test_bit(GPIOD_FLAG_BIAS_DISABLE, &flags))
2740 bias = PIN_CONFIG_BIAS_DISABLE;
2741 else if (test_bit(GPIOD_FLAG_PULL_UP, &flags))
2742 bias = PIN_CONFIG_BIAS_PULL_UP;
2743 else if (test_bit(GPIOD_FLAG_PULL_DOWN, &flags))
2744 bias = PIN_CONFIG_BIAS_PULL_DOWN;
2745 else
2746 return 0;
2747
2748 switch (bias) {
2749 case PIN_CONFIG_BIAS_PULL_DOWN:
2750 case PIN_CONFIG_BIAS_PULL_UP:
2751 arg = 1;
2752 break;
2753
2754 default:
2755 arg = 0;
2756 break;
2757 }
2758
2759 return gpio_set_config_with_argument_optional(desc, bias, arg);
2760 }
2761
2762 /**
2763 * gpio_set_debounce_timeout() - Set debounce timeout
2764 * @desc: GPIO descriptor to set the debounce timeout
2765 * @debounce: Debounce timeout in microseconds
2766 *
2767 * The function calls the certain GPIO driver to set debounce timeout
2768 * in the hardware.
2769 *
2770 * Returns:
2771 * 0 on success, or negative errno on failure.
2772 */
gpio_set_debounce_timeout(struct gpio_desc * desc,unsigned int debounce)2773 int gpio_set_debounce_timeout(struct gpio_desc *desc, unsigned int debounce)
2774 {
2775 int ret;
2776
2777 ret = gpio_set_config_with_argument_optional(desc,
2778 PIN_CONFIG_INPUT_DEBOUNCE,
2779 debounce);
2780 if (!ret)
2781 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
2782
2783 return ret;
2784 }
2785
gpiochip_direction_input(struct gpio_chip * gc,unsigned int offset)2786 static int gpiochip_direction_input(struct gpio_chip *gc, unsigned int offset)
2787 {
2788 int ret;
2789
2790 lockdep_assert_held(&gc->gpiodev->srcu);
2791
2792 if (WARN_ON(!gc->direction_input))
2793 return -EOPNOTSUPP;
2794
2795 ret = gc->direction_input(gc, offset);
2796 if (ret > 0)
2797 ret = -EBADE;
2798
2799 return ret;
2800 }
2801
gpiochip_direction_output(struct gpio_chip * gc,unsigned int offset,int value)2802 static int gpiochip_direction_output(struct gpio_chip *gc, unsigned int offset,
2803 int value)
2804 {
2805 int ret;
2806
2807 lockdep_assert_held(&gc->gpiodev->srcu);
2808
2809 if (WARN_ON(!gc->direction_output))
2810 return -EOPNOTSUPP;
2811
2812 ret = gc->direction_output(gc, offset, value);
2813 if (ret > 0)
2814 ret = -EBADE;
2815
2816 return ret;
2817 }
2818
2819 /**
2820 * gpiod_direction_input - set the GPIO direction to input
2821 * @desc: GPIO to set to input
2822 *
2823 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
2824 * be called safely on it.
2825 *
2826 * Returns:
2827 * 0 on success, or negative errno on failure.
2828 */
gpiod_direction_input(struct gpio_desc * desc)2829 int gpiod_direction_input(struct gpio_desc *desc)
2830 {
2831 int ret;
2832
2833 VALIDATE_DESC(desc);
2834
2835 ret = gpiod_direction_input_nonotify(desc);
2836 if (ret == 0)
2837 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
2838
2839 return ret;
2840 }
2841 EXPORT_SYMBOL_GPL(gpiod_direction_input);
2842
gpiod_direction_input_nonotify(struct gpio_desc * desc)2843 int gpiod_direction_input_nonotify(struct gpio_desc *desc)
2844 {
2845 int ret = 0, dir;
2846
2847 CLASS(gpio_chip_guard, guard)(desc);
2848 if (!guard.gc)
2849 return -ENODEV;
2850
2851 /*
2852 * It is legal to have no .get() and .direction_input() specified if
2853 * the chip is output-only, but you can't specify .direction_input()
2854 * and not support the .get() operation, that doesn't make sense.
2855 */
2856 if (!guard.gc->get && guard.gc->direction_input) {
2857 gpiod_warn(desc,
2858 "%s: missing get() but have direction_input()\n",
2859 __func__);
2860 return -EIO;
2861 }
2862
2863 /*
2864 * If we have a .direction_input() callback, things are simple,
2865 * just call it. Else we are some input-only chip so try to check the
2866 * direction (if .get_direction() is supported) else we silently
2867 * assume we are in input mode after this.
2868 */
2869 if (guard.gc->direction_input) {
2870 ret = gpiochip_direction_input(guard.gc,
2871 gpio_chip_hwgpio(desc));
2872 } else if (guard.gc->get_direction) {
2873 dir = gpiochip_get_direction(guard.gc, gpio_chip_hwgpio(desc));
2874 if (dir < 0)
2875 return dir;
2876
2877 if (dir != GPIO_LINE_DIRECTION_IN) {
2878 gpiod_warn(desc,
2879 "%s: missing direction_input() operation and line is output\n",
2880 __func__);
2881 return -EIO;
2882 }
2883 }
2884 if (ret == 0) {
2885 clear_bit(GPIOD_FLAG_IS_OUT, &desc->flags);
2886 ret = gpio_set_bias(desc);
2887 }
2888
2889 trace_gpio_direction(desc_to_gpio(desc), 1, ret);
2890
2891 return ret;
2892 }
2893
gpiochip_set(struct gpio_chip * gc,unsigned int offset,int value)2894 static int gpiochip_set(struct gpio_chip *gc, unsigned int offset, int value)
2895 {
2896 int ret;
2897
2898 lockdep_assert_held(&gc->gpiodev->srcu);
2899
2900 if (WARN_ON(unlikely(!gc->set)))
2901 return -EOPNOTSUPP;
2902
2903 ret = gc->set(gc, offset, value);
2904 if (ret > 0)
2905 ret = -EBADE;
2906
2907 return ret;
2908 }
2909
gpiod_direction_output_raw_commit(struct gpio_desc * desc,int value)2910 static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
2911 {
2912 int val = !!value, ret = 0, dir;
2913
2914 CLASS(gpio_chip_guard, guard)(desc);
2915 if (!guard.gc)
2916 return -ENODEV;
2917
2918 /*
2919 * It's OK not to specify .direction_output() if the gpiochip is
2920 * output-only, but if there is then not even a .set() operation it
2921 * is pretty tricky to drive the output line.
2922 */
2923 if (!guard.gc->set && !guard.gc->direction_output) {
2924 gpiod_warn(desc,
2925 "%s: missing set() and direction_output() operations\n",
2926 __func__);
2927 return -EIO;
2928 }
2929
2930 if (guard.gc->direction_output) {
2931 ret = gpiochip_direction_output(guard.gc,
2932 gpio_chip_hwgpio(desc), val);
2933 } else {
2934 /* Check that we are in output mode if we can */
2935 if (guard.gc->get_direction) {
2936 dir = gpiochip_get_direction(guard.gc,
2937 gpio_chip_hwgpio(desc));
2938 if (dir < 0)
2939 return dir;
2940
2941 if (dir != GPIO_LINE_DIRECTION_OUT) {
2942 gpiod_warn(desc,
2943 "%s: missing direction_output() operation\n",
2944 __func__);
2945 return -EIO;
2946 }
2947 }
2948 /*
2949 * If we can't actively set the direction, we are some
2950 * output-only chip, so just drive the output as desired.
2951 */
2952 ret = gpiochip_set(guard.gc, gpio_chip_hwgpio(desc), val);
2953 if (ret)
2954 return ret;
2955 }
2956
2957 if (!ret)
2958 set_bit(GPIOD_FLAG_IS_OUT, &desc->flags);
2959 trace_gpio_value(desc_to_gpio(desc), 0, val);
2960 trace_gpio_direction(desc_to_gpio(desc), 0, ret);
2961 return ret;
2962 }
2963
2964 /**
2965 * gpiod_direction_output_raw - set the GPIO direction to output
2966 * @desc: GPIO to set to output
2967 * @value: initial output value of the GPIO
2968 *
2969 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2970 * be called safely on it. The initial value of the output must be specified
2971 * as raw value on the physical line without regard for the ACTIVE_LOW status.
2972 *
2973 * Returns:
2974 * 0 on success, or negative errno on failure.
2975 */
gpiod_direction_output_raw(struct gpio_desc * desc,int value)2976 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2977 {
2978 int ret;
2979
2980 VALIDATE_DESC(desc);
2981
2982 ret = gpiod_direction_output_raw_commit(desc, value);
2983 if (ret == 0)
2984 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
2985
2986 return ret;
2987 }
2988 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
2989
2990 /**
2991 * gpiod_direction_output - set the GPIO direction to output
2992 * @desc: GPIO to set to output
2993 * @value: initial output value of the GPIO
2994 *
2995 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2996 * be called safely on it. The initial value of the output must be specified
2997 * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2998 * account.
2999 *
3000 * Returns:
3001 * 0 on success, or negative errno on failure.
3002 */
gpiod_direction_output(struct gpio_desc * desc,int value)3003 int gpiod_direction_output(struct gpio_desc *desc, int value)
3004 {
3005 int ret;
3006
3007 VALIDATE_DESC(desc);
3008
3009 ret = gpiod_direction_output_nonotify(desc, value);
3010 if (ret == 0)
3011 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
3012
3013 return ret;
3014 }
3015 EXPORT_SYMBOL_GPL(gpiod_direction_output);
3016
gpiod_direction_output_nonotify(struct gpio_desc * desc,int value)3017 int gpiod_direction_output_nonotify(struct gpio_desc *desc, int value)
3018 {
3019 unsigned long flags;
3020 int ret;
3021
3022 flags = READ_ONCE(desc->flags);
3023
3024 if (test_bit(GPIOD_FLAG_ACTIVE_LOW, &flags))
3025 value = !value;
3026 else
3027 value = !!value;
3028
3029 /* GPIOs used for enabled IRQs shall not be set as output */
3030 if (test_bit(GPIOD_FLAG_USED_AS_IRQ, &flags) &&
3031 test_bit(GPIOD_FLAG_IRQ_IS_ENABLED, &flags)) {
3032 gpiod_err(desc,
3033 "%s: tried to set a GPIO tied to an IRQ as output\n",
3034 __func__);
3035 return -EIO;
3036 }
3037
3038 if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &flags)) {
3039 /* First see if we can enable open drain in hardware */
3040 ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_DRAIN);
3041 if (!ret)
3042 goto set_output_value;
3043 /* Emulate open drain by not actively driving the line high */
3044 if (value)
3045 goto set_output_flag;
3046 } else if (test_bit(GPIOD_FLAG_OPEN_SOURCE, &flags)) {
3047 ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_SOURCE);
3048 if (!ret)
3049 goto set_output_value;
3050 /* Emulate open source by not actively driving the line low */
3051 if (!value)
3052 goto set_output_flag;
3053 } else {
3054 gpio_set_config(desc, PIN_CONFIG_DRIVE_PUSH_PULL);
3055 }
3056
3057 set_output_value:
3058 ret = gpio_set_bias(desc);
3059 if (ret)
3060 return ret;
3061 return gpiod_direction_output_raw_commit(desc, value);
3062
3063 set_output_flag:
3064 ret = gpiod_direction_input_nonotify(desc);
3065 if (ret)
3066 return ret;
3067 /*
3068 * When emulating open-source or open-drain functionalities by not
3069 * actively driving the line (setting mode to input) we still need to
3070 * set the IS_OUT flag or otherwise we won't be able to set the line
3071 * value anymore.
3072 */
3073 set_bit(GPIOD_FLAG_IS_OUT, &desc->flags);
3074 return 0;
3075 }
3076
3077 #if IS_ENABLED(CONFIG_HTE)
3078 /**
3079 * gpiod_enable_hw_timestamp_ns - Enable hardware timestamp in nanoseconds.
3080 *
3081 * @desc: GPIO to enable.
3082 * @flags: Flags related to GPIO edge.
3083 *
3084 * Returns:
3085 * 0 on success, or negative errno on failure.
3086 */
gpiod_enable_hw_timestamp_ns(struct gpio_desc * desc,unsigned long flags)3087 int gpiod_enable_hw_timestamp_ns(struct gpio_desc *desc, unsigned long flags)
3088 {
3089 int ret;
3090
3091 VALIDATE_DESC(desc);
3092
3093 CLASS(gpio_chip_guard, guard)(desc);
3094 if (!guard.gc)
3095 return -ENODEV;
3096
3097 if (!guard.gc->en_hw_timestamp) {
3098 gpiod_warn(desc, "%s: hw ts not supported\n", __func__);
3099 return -ENOTSUPP;
3100 }
3101
3102 ret = guard.gc->en_hw_timestamp(guard.gc,
3103 gpio_chip_hwgpio(desc), flags);
3104 if (ret)
3105 gpiod_warn(desc, "%s: hw ts request failed\n", __func__);
3106
3107 return ret;
3108 }
3109 EXPORT_SYMBOL_GPL(gpiod_enable_hw_timestamp_ns);
3110
3111 /**
3112 * gpiod_disable_hw_timestamp_ns - Disable hardware timestamp.
3113 *
3114 * @desc: GPIO to disable.
3115 * @flags: Flags related to GPIO edge, same value as used during enable call.
3116 *
3117 * Returns:
3118 * 0 on success, or negative errno on failure.
3119 */
gpiod_disable_hw_timestamp_ns(struct gpio_desc * desc,unsigned long flags)3120 int gpiod_disable_hw_timestamp_ns(struct gpio_desc *desc, unsigned long flags)
3121 {
3122 int ret;
3123
3124 VALIDATE_DESC(desc);
3125
3126 CLASS(gpio_chip_guard, guard)(desc);
3127 if (!guard.gc)
3128 return -ENODEV;
3129
3130 if (!guard.gc->dis_hw_timestamp) {
3131 gpiod_warn(desc, "%s: hw ts not supported\n", __func__);
3132 return -ENOTSUPP;
3133 }
3134
3135 ret = guard.gc->dis_hw_timestamp(guard.gc, gpio_chip_hwgpio(desc),
3136 flags);
3137 if (ret)
3138 gpiod_warn(desc, "%s: hw ts release failed\n", __func__);
3139
3140 return ret;
3141 }
3142 EXPORT_SYMBOL_GPL(gpiod_disable_hw_timestamp_ns);
3143 #endif /* CONFIG_HTE */
3144
3145 /**
3146 * gpiod_set_config - sets @config for a GPIO
3147 * @desc: descriptor of the GPIO for which to set the configuration
3148 * @config: Same packed config format as generic pinconf
3149 *
3150 * Returns:
3151 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3152 * configuration.
3153 */
gpiod_set_config(struct gpio_desc * desc,unsigned long config)3154 int gpiod_set_config(struct gpio_desc *desc, unsigned long config)
3155 {
3156 int ret;
3157
3158 VALIDATE_DESC(desc);
3159
3160 ret = gpio_do_set_config(desc, config);
3161 if (!ret) {
3162 /* These are the only options we notify the userspace about. */
3163 switch (pinconf_to_config_param(config)) {
3164 case PIN_CONFIG_BIAS_DISABLE:
3165 case PIN_CONFIG_BIAS_PULL_DOWN:
3166 case PIN_CONFIG_BIAS_PULL_UP:
3167 case PIN_CONFIG_DRIVE_OPEN_DRAIN:
3168 case PIN_CONFIG_DRIVE_OPEN_SOURCE:
3169 case PIN_CONFIG_DRIVE_PUSH_PULL:
3170 case PIN_CONFIG_INPUT_DEBOUNCE:
3171 gpiod_line_state_notify(desc,
3172 GPIO_V2_LINE_CHANGED_CONFIG);
3173 break;
3174 default:
3175 break;
3176 }
3177 }
3178
3179 return ret;
3180 }
3181 EXPORT_SYMBOL_GPL(gpiod_set_config);
3182
3183 /**
3184 * gpiod_set_debounce - sets @debounce time for a GPIO
3185 * @desc: descriptor of the GPIO for which to set debounce time
3186 * @debounce: debounce time in microseconds
3187 *
3188 * Returns:
3189 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3190 * debounce time.
3191 */
gpiod_set_debounce(struct gpio_desc * desc,unsigned int debounce)3192 int gpiod_set_debounce(struct gpio_desc *desc, unsigned int debounce)
3193 {
3194 unsigned long config;
3195
3196 config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
3197 return gpiod_set_config(desc, config);
3198 }
3199 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
3200
3201 /**
3202 * gpiod_set_transitory - Lose or retain GPIO state on suspend or reset
3203 * @desc: descriptor of the GPIO for which to configure persistence
3204 * @transitory: True to lose state on suspend or reset, false for persistence
3205 *
3206 * Returns:
3207 * 0 on success, otherwise a negative error code.
3208 */
gpiod_set_transitory(struct gpio_desc * desc,bool transitory)3209 int gpiod_set_transitory(struct gpio_desc *desc, bool transitory)
3210 {
3211 VALIDATE_DESC(desc);
3212 /*
3213 * Handle GPIOD_FLAG_TRANSITORY first, enabling queries to gpiolib for
3214 * persistence state.
3215 */
3216 assign_bit(GPIOD_FLAG_TRANSITORY, &desc->flags, transitory);
3217
3218 /* If the driver supports it, set the persistence state now */
3219 return gpio_set_config_with_argument_optional(desc,
3220 PIN_CONFIG_PERSIST_STATE,
3221 !transitory);
3222 }
3223
3224 /**
3225 * gpiod_is_active_low - test whether a GPIO is active-low or not
3226 * @desc: the gpio descriptor to test
3227 *
3228 * Returns:
3229 * 1 if the GPIO is active-low, 0 otherwise.
3230 */
gpiod_is_active_low(const struct gpio_desc * desc)3231 int gpiod_is_active_low(const struct gpio_desc *desc)
3232 {
3233 VALIDATE_DESC(desc);
3234 return test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags);
3235 }
3236 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
3237
3238 /**
3239 * gpiod_toggle_active_low - toggle whether a GPIO is active-low or not
3240 * @desc: the gpio descriptor to change
3241 */
gpiod_toggle_active_low(struct gpio_desc * desc)3242 void gpiod_toggle_active_low(struct gpio_desc *desc)
3243 {
3244 VALIDATE_DESC_VOID(desc);
3245 change_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags);
3246 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
3247 }
3248 EXPORT_SYMBOL_GPL(gpiod_toggle_active_low);
3249
gpiochip_get(struct gpio_chip * gc,unsigned int offset)3250 static int gpiochip_get(struct gpio_chip *gc, unsigned int offset)
3251 {
3252 int ret;
3253
3254 lockdep_assert_held(&gc->gpiodev->srcu);
3255
3256 /* Make sure this is called after checking for gc->get(). */
3257 ret = gc->get(gc, offset);
3258 if (ret > 1)
3259 ret = -EBADE;
3260
3261 return ret;
3262 }
3263
gpio_chip_get_value(struct gpio_chip * gc,const struct gpio_desc * desc)3264 static int gpio_chip_get_value(struct gpio_chip *gc, const struct gpio_desc *desc)
3265 {
3266 return gc->get ? gpiochip_get(gc, gpio_chip_hwgpio(desc)) : -EIO;
3267 }
3268
3269 /* I/O calls are only valid after configuration completed; the relevant
3270 * "is this a valid GPIO" error checks should already have been done.
3271 *
3272 * "Get" operations are often inlinable as reading a pin value register,
3273 * and masking the relevant bit in that register.
3274 *
3275 * When "set" operations are inlinable, they involve writing that mask to
3276 * one register to set a low value, or a different register to set it high.
3277 * Otherwise locking is needed, so there may be little value to inlining.
3278 *
3279 *------------------------------------------------------------------------
3280 *
3281 * IMPORTANT!!! The hot paths -- get/set value -- assume that callers
3282 * have requested the GPIO. That can include implicit requesting by
3283 * a direction setting call. Marking a gpio as requested locks its chip
3284 * in memory, guaranteeing that these table lookups need no more locking
3285 * and that gpiochip_remove() will fail.
3286 *
3287 * REVISIT when debugging, consider adding some instrumentation to ensure
3288 * that the GPIO was actually requested.
3289 */
3290
gpiod_get_raw_value_commit(const struct gpio_desc * desc)3291 static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
3292 {
3293 struct gpio_device *gdev;
3294 struct gpio_chip *gc;
3295 int value;
3296
3297 /* FIXME Unable to use gpio_chip_guard due to const desc. */
3298 gdev = desc->gdev;
3299
3300 guard(srcu)(&gdev->srcu);
3301
3302 gc = srcu_dereference(gdev->chip, &gdev->srcu);
3303 if (!gc)
3304 return -ENODEV;
3305
3306 value = gpio_chip_get_value(gc, desc);
3307 value = value < 0 ? value : !!value;
3308 trace_gpio_value(desc_to_gpio(desc), 1, value);
3309 return value;
3310 }
3311
gpio_chip_get_multiple(struct gpio_chip * gc,unsigned long * mask,unsigned long * bits)3312 static int gpio_chip_get_multiple(struct gpio_chip *gc,
3313 unsigned long *mask, unsigned long *bits)
3314 {
3315 lockdep_assert_held(&gc->gpiodev->srcu);
3316
3317 if (gc->get_multiple) {
3318 int ret;
3319
3320 ret = gc->get_multiple(gc, mask, bits);
3321 if (ret > 0)
3322 return -EBADE;
3323 return ret;
3324 }
3325
3326 if (gc->get) {
3327 int i, value;
3328
3329 for_each_set_bit(i, mask, gc->ngpio) {
3330 value = gpiochip_get(gc, i);
3331 if (value < 0)
3332 return value;
3333 __assign_bit(i, bits, value);
3334 }
3335 return 0;
3336 }
3337 return -EIO;
3338 }
3339
3340 /* The 'other' chip must be protected with its GPIO device's SRCU. */
gpio_device_chip_cmp(struct gpio_device * gdev,struct gpio_chip * gc)3341 static bool gpio_device_chip_cmp(struct gpio_device *gdev, struct gpio_chip *gc)
3342 {
3343 guard(srcu)(&gdev->srcu);
3344
3345 return gc == srcu_dereference(gdev->chip, &gdev->srcu);
3346 }
3347
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)3348 int gpiod_get_array_value_complex(bool raw, bool can_sleep,
3349 unsigned int array_size,
3350 struct gpio_desc **desc_array,
3351 struct gpio_array *array_info,
3352 unsigned long *value_bitmap)
3353 {
3354 struct gpio_chip *gc;
3355 int ret, i = 0;
3356
3357 /*
3358 * Validate array_info against desc_array and its size.
3359 * It should immediately follow desc_array if both
3360 * have been obtained from the same gpiod_get_array() call.
3361 */
3362 if (array_info && array_info->desc == desc_array &&
3363 array_size <= array_info->size &&
3364 (void *)array_info == desc_array + array_info->size) {
3365 if (!can_sleep)
3366 WARN_ON(array_info->gdev->can_sleep);
3367
3368 guard(srcu)(&array_info->gdev->srcu);
3369 gc = srcu_dereference(array_info->gdev->chip,
3370 &array_info->gdev->srcu);
3371 if (!gc)
3372 return -ENODEV;
3373
3374 ret = gpio_chip_get_multiple(gc, array_info->get_mask,
3375 value_bitmap);
3376 if (ret)
3377 return ret;
3378
3379 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3380 bitmap_xor(value_bitmap, value_bitmap,
3381 array_info->invert_mask, array_size);
3382
3383 i = find_first_zero_bit(array_info->get_mask, array_size);
3384 if (i == array_size)
3385 return 0;
3386 } else {
3387 array_info = NULL;
3388 }
3389
3390 while (i < array_size) {
3391 DECLARE_BITMAP(fastpath_mask, FASTPATH_NGPIO);
3392 DECLARE_BITMAP(fastpath_bits, FASTPATH_NGPIO);
3393 unsigned long *mask, *bits;
3394 int first, j;
3395
3396 CLASS(gpio_chip_guard, guard)(desc_array[i]);
3397 if (!guard.gc)
3398 return -ENODEV;
3399
3400 if (likely(guard.gc->ngpio <= FASTPATH_NGPIO)) {
3401 mask = fastpath_mask;
3402 bits = fastpath_bits;
3403 } else {
3404 gfp_t flags = can_sleep ? GFP_KERNEL : GFP_ATOMIC;
3405
3406 mask = bitmap_alloc(guard.gc->ngpio, flags);
3407 if (!mask)
3408 return -ENOMEM;
3409
3410 bits = bitmap_alloc(guard.gc->ngpio, flags);
3411 if (!bits) {
3412 bitmap_free(mask);
3413 return -ENOMEM;
3414 }
3415 }
3416
3417 bitmap_zero(mask, guard.gc->ngpio);
3418
3419 if (!can_sleep)
3420 WARN_ON(guard.gc->can_sleep);
3421
3422 /* collect all inputs belonging to the same chip */
3423 first = i;
3424 do {
3425 const struct gpio_desc *desc = desc_array[i];
3426 int hwgpio = gpio_chip_hwgpio(desc);
3427
3428 __set_bit(hwgpio, mask);
3429 i++;
3430
3431 if (array_info)
3432 i = find_next_zero_bit(array_info->get_mask,
3433 array_size, i);
3434 } while ((i < array_size) &&
3435 gpio_device_chip_cmp(desc_array[i]->gdev, guard.gc));
3436
3437 ret = gpio_chip_get_multiple(guard.gc, mask, bits);
3438 if (ret) {
3439 if (mask != fastpath_mask)
3440 bitmap_free(mask);
3441 if (bits != fastpath_bits)
3442 bitmap_free(bits);
3443 return ret;
3444 }
3445
3446 for (j = first; j < i; ) {
3447 const struct gpio_desc *desc = desc_array[j];
3448 int hwgpio = gpio_chip_hwgpio(desc);
3449 int value = test_bit(hwgpio, bits);
3450
3451 if (!raw && test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags))
3452 value = !value;
3453 __assign_bit(j, value_bitmap, value);
3454 trace_gpio_value(desc_to_gpio(desc), 1, value);
3455 j++;
3456
3457 if (array_info)
3458 j = find_next_zero_bit(array_info->get_mask, i,
3459 j);
3460 }
3461
3462 if (mask != fastpath_mask)
3463 bitmap_free(mask);
3464 if (bits != fastpath_bits)
3465 bitmap_free(bits);
3466 }
3467 return 0;
3468 }
3469
3470 /**
3471 * gpiod_get_raw_value() - return a gpio's raw value
3472 * @desc: gpio whose value will be returned
3473 *
3474 * Returns:
3475 * The GPIO's raw value, i.e. the value of the physical line disregarding
3476 * its ACTIVE_LOW status, or negative errno on failure.
3477 *
3478 * This function can be called from contexts where we cannot sleep, and will
3479 * complain if the GPIO chip functions potentially sleep.
3480 */
gpiod_get_raw_value(const struct gpio_desc * desc)3481 int gpiod_get_raw_value(const struct gpio_desc *desc)
3482 {
3483 VALIDATE_DESC(desc);
3484 /* Should be using gpiod_get_raw_value_cansleep() */
3485 WARN_ON(desc->gdev->can_sleep);
3486 return gpiod_get_raw_value_commit(desc);
3487 }
3488 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
3489
3490 /**
3491 * gpiod_get_value() - return a gpio's value
3492 * @desc: gpio whose value will be returned
3493 *
3494 * Returns:
3495 * The GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3496 * account, or negative errno on failure.
3497 *
3498 * This function can be called from contexts where we cannot sleep, and will
3499 * complain if the GPIO chip functions potentially sleep.
3500 */
gpiod_get_value(const struct gpio_desc * desc)3501 int gpiod_get_value(const struct gpio_desc *desc)
3502 {
3503 int value;
3504
3505 VALIDATE_DESC(desc);
3506 /* Should be using gpiod_get_value_cansleep() */
3507 WARN_ON(desc->gdev->can_sleep);
3508
3509 value = gpiod_get_raw_value_commit(desc);
3510 if (value < 0)
3511 return value;
3512
3513 if (test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags))
3514 value = !value;
3515
3516 return value;
3517 }
3518 EXPORT_SYMBOL_GPL(gpiod_get_value);
3519
3520 /**
3521 * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
3522 * @array_size: number of elements in the descriptor array / value bitmap
3523 * @desc_array: array of GPIO descriptors whose values will be read
3524 * @array_info: information on applicability of fast bitmap processing path
3525 * @value_bitmap: bitmap to store the read values
3526 *
3527 * Read the raw values of the GPIOs, i.e. the values of the physical lines
3528 * without regard for their ACTIVE_LOW status.
3529 *
3530 * This function can be called from contexts where we cannot sleep,
3531 * and it will complain if the GPIO chip functions potentially sleep.
3532 *
3533 * Returns:
3534 * 0 on success, or negative errno on failure.
3535 */
gpiod_get_raw_array_value(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)3536 int gpiod_get_raw_array_value(unsigned int array_size,
3537 struct gpio_desc **desc_array,
3538 struct gpio_array *array_info,
3539 unsigned long *value_bitmap)
3540 {
3541 if (!desc_array)
3542 return -EINVAL;
3543 return gpiod_get_array_value_complex(true, false, array_size,
3544 desc_array, array_info,
3545 value_bitmap);
3546 }
3547 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
3548
3549 /**
3550 * gpiod_get_array_value() - read values from an array of GPIOs
3551 * @array_size: number of elements in the descriptor array / value bitmap
3552 * @desc_array: array of GPIO descriptors whose values will be read
3553 * @array_info: information on applicability of fast bitmap processing path
3554 * @value_bitmap: bitmap to store the read values
3555 *
3556 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3557 * into account.
3558 *
3559 * This function can be called from contexts where we cannot sleep,
3560 * and it will complain if the GPIO chip functions potentially sleep.
3561 *
3562 * Returns:
3563 * 0 on success, or negative errno on failure.
3564 */
gpiod_get_array_value(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)3565 int gpiod_get_array_value(unsigned int array_size,
3566 struct gpio_desc **desc_array,
3567 struct gpio_array *array_info,
3568 unsigned long *value_bitmap)
3569 {
3570 if (!desc_array)
3571 return -EINVAL;
3572 return gpiod_get_array_value_complex(false, false, array_size,
3573 desc_array, array_info,
3574 value_bitmap);
3575 }
3576 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
3577
3578 /*
3579 * gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
3580 * @desc: gpio descriptor whose state need to be set.
3581 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3582 */
gpio_set_open_drain_value_commit(struct gpio_desc * desc,bool value)3583 static int gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
3584 {
3585 int ret = 0, offset = gpio_chip_hwgpio(desc);
3586
3587 CLASS(gpio_chip_guard, guard)(desc);
3588 if (!guard.gc)
3589 return -ENODEV;
3590
3591 if (value) {
3592 ret = gpiochip_direction_input(guard.gc, offset);
3593 } else {
3594 ret = gpiochip_direction_output(guard.gc, offset, 0);
3595 if (!ret)
3596 set_bit(GPIOD_FLAG_IS_OUT, &desc->flags);
3597 }
3598 trace_gpio_direction(desc_to_gpio(desc), value, ret);
3599 if (ret < 0)
3600 gpiod_err(desc,
3601 "%s: Error in set_value for open drain err %d\n",
3602 __func__, ret);
3603
3604 return ret;
3605 }
3606
3607 /*
3608 * _gpio_set_open_source_value() - Set the open source gpio's value.
3609 * @desc: gpio descriptor whose state need to be set.
3610 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3611 */
gpio_set_open_source_value_commit(struct gpio_desc * desc,bool value)3612 static int gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
3613 {
3614 int ret = 0, offset = gpio_chip_hwgpio(desc);
3615
3616 CLASS(gpio_chip_guard, guard)(desc);
3617 if (!guard.gc)
3618 return -ENODEV;
3619
3620 if (value) {
3621 ret = gpiochip_direction_output(guard.gc, offset, 1);
3622 if (!ret)
3623 set_bit(GPIOD_FLAG_IS_OUT, &desc->flags);
3624 } else {
3625 ret = gpiochip_direction_input(guard.gc, offset);
3626 }
3627 trace_gpio_direction(desc_to_gpio(desc), !value, ret);
3628 if (ret < 0)
3629 gpiod_err(desc,
3630 "%s: Error in set_value for open source err %d\n",
3631 __func__, ret);
3632
3633 return ret;
3634 }
3635
gpiod_set_raw_value_commit(struct gpio_desc * desc,bool value)3636 static int gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
3637 {
3638 if (unlikely(!test_bit(GPIOD_FLAG_IS_OUT, &desc->flags)))
3639 return -EPERM;
3640
3641 CLASS(gpio_chip_guard, guard)(desc);
3642 if (!guard.gc)
3643 return -ENODEV;
3644
3645 trace_gpio_value(desc_to_gpio(desc), 0, value);
3646 return gpiochip_set(guard.gc, gpio_chip_hwgpio(desc), value);
3647 }
3648
3649 /*
3650 * set multiple outputs on the same chip;
3651 * use the chip's set_multiple function if available;
3652 * otherwise set the outputs sequentially;
3653 * @chip: the GPIO chip we operate on
3654 * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
3655 * defines which outputs are to be changed
3656 * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
3657 * defines the values the outputs specified by mask are to be set to
3658 *
3659 * Returns: 0 on success, negative error number on failure.
3660 */
gpiochip_set_multiple(struct gpio_chip * gc,unsigned long * mask,unsigned long * bits)3661 static int gpiochip_set_multiple(struct gpio_chip *gc,
3662 unsigned long *mask, unsigned long *bits)
3663 {
3664 unsigned int i;
3665 int ret;
3666
3667 lockdep_assert_held(&gc->gpiodev->srcu);
3668
3669 if (gc->set_multiple) {
3670 ret = gc->set_multiple(gc, mask, bits);
3671 if (ret > 0)
3672 ret = -EBADE;
3673
3674 return ret;
3675 }
3676
3677 /* set outputs if the corresponding mask bit is set */
3678 for_each_set_bit(i, mask, gc->ngpio) {
3679 ret = gpiochip_set(gc, i, test_bit(i, bits));
3680 if (ret)
3681 break;
3682 }
3683
3684 return ret;
3685 }
3686
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)3687 int gpiod_set_array_value_complex(bool raw, bool can_sleep,
3688 unsigned int array_size,
3689 struct gpio_desc **desc_array,
3690 struct gpio_array *array_info,
3691 unsigned long *value_bitmap)
3692 {
3693 struct gpio_chip *gc;
3694 int i = 0, ret;
3695
3696 /*
3697 * Validate array_info against desc_array and its size.
3698 * It should immediately follow desc_array if both
3699 * have been obtained from the same gpiod_get_array() call.
3700 */
3701 if (array_info && array_info->desc == desc_array &&
3702 array_size <= array_info->size &&
3703 (void *)array_info == desc_array + array_info->size) {
3704 if (!can_sleep)
3705 WARN_ON(array_info->gdev->can_sleep);
3706
3707 for (i = 0; i < array_size; i++) {
3708 if (unlikely(!test_bit(GPIOD_FLAG_IS_OUT,
3709 &desc_array[i]->flags)))
3710 return -EPERM;
3711 }
3712
3713 guard(srcu)(&array_info->gdev->srcu);
3714 gc = srcu_dereference(array_info->gdev->chip,
3715 &array_info->gdev->srcu);
3716 if (!gc)
3717 return -ENODEV;
3718
3719 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3720 bitmap_xor(value_bitmap, value_bitmap,
3721 array_info->invert_mask, array_size);
3722
3723 ret = gpiochip_set_multiple(gc, array_info->set_mask,
3724 value_bitmap);
3725 if (ret)
3726 return ret;
3727
3728 i = find_first_zero_bit(array_info->set_mask, array_size);
3729 if (i == array_size)
3730 return 0;
3731 } else {
3732 array_info = NULL;
3733 }
3734
3735 while (i < array_size) {
3736 DECLARE_BITMAP(fastpath_mask, FASTPATH_NGPIO);
3737 DECLARE_BITMAP(fastpath_bits, FASTPATH_NGPIO);
3738 unsigned long *mask, *bits;
3739 int count = 0;
3740
3741 CLASS(gpio_chip_guard, guard)(desc_array[i]);
3742 if (!guard.gc)
3743 return -ENODEV;
3744
3745 if (likely(guard.gc->ngpio <= FASTPATH_NGPIO)) {
3746 mask = fastpath_mask;
3747 bits = fastpath_bits;
3748 } else {
3749 gfp_t flags = can_sleep ? GFP_KERNEL : GFP_ATOMIC;
3750
3751 mask = bitmap_alloc(guard.gc->ngpio, flags);
3752 if (!mask)
3753 return -ENOMEM;
3754
3755 bits = bitmap_alloc(guard.gc->ngpio, flags);
3756 if (!bits) {
3757 bitmap_free(mask);
3758 return -ENOMEM;
3759 }
3760 }
3761
3762 bitmap_zero(mask, guard.gc->ngpio);
3763
3764 if (!can_sleep)
3765 WARN_ON(guard.gc->can_sleep);
3766
3767 do {
3768 struct gpio_desc *desc = desc_array[i];
3769 int hwgpio = gpio_chip_hwgpio(desc);
3770 int value = test_bit(i, value_bitmap);
3771
3772 if (unlikely(!test_bit(GPIOD_FLAG_IS_OUT, &desc->flags)))
3773 return -EPERM;
3774
3775 /*
3776 * Pins applicable for fast input but not for
3777 * fast output processing may have been already
3778 * inverted inside the fast path, skip them.
3779 */
3780 if (!raw && !(array_info &&
3781 test_bit(i, array_info->invert_mask)) &&
3782 test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags))
3783 value = !value;
3784 trace_gpio_value(desc_to_gpio(desc), 0, value);
3785 /*
3786 * collect all normal outputs belonging to the same chip
3787 * open drain and open source outputs are set individually
3788 */
3789 if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
3790 gpio_set_open_drain_value_commit(desc, value);
3791 } else if (test_bit(GPIOD_FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
3792 gpio_set_open_source_value_commit(desc, value);
3793 } else {
3794 __set_bit(hwgpio, mask);
3795 __assign_bit(hwgpio, bits, value);
3796 count++;
3797 }
3798 i++;
3799
3800 if (array_info)
3801 i = find_next_zero_bit(array_info->set_mask,
3802 array_size, i);
3803 } while ((i < array_size) &&
3804 gpio_device_chip_cmp(desc_array[i]->gdev, guard.gc));
3805 /* push collected bits to outputs */
3806 if (count != 0) {
3807 ret = gpiochip_set_multiple(guard.gc, mask, bits);
3808 if (ret)
3809 return ret;
3810 }
3811
3812 if (mask != fastpath_mask)
3813 bitmap_free(mask);
3814 if (bits != fastpath_bits)
3815 bitmap_free(bits);
3816 }
3817 return 0;
3818 }
3819
3820 /**
3821 * gpiod_set_raw_value() - assign a gpio's raw value
3822 * @desc: gpio whose value will be assigned
3823 * @value: value to assign
3824 *
3825 * Set the raw value of the GPIO, i.e. the value of its physical line without
3826 * regard for its ACTIVE_LOW status.
3827 *
3828 * This function can be called from contexts where we cannot sleep, and will
3829 * complain if the GPIO chip functions potentially sleep.
3830 *
3831 * Returns:
3832 * 0 on success, negative error number on failure.
3833 */
gpiod_set_raw_value(struct gpio_desc * desc,int value)3834 int gpiod_set_raw_value(struct gpio_desc *desc, int value)
3835 {
3836 VALIDATE_DESC(desc);
3837 /* Should be using gpiod_set_raw_value_cansleep() */
3838 WARN_ON(desc->gdev->can_sleep);
3839 return gpiod_set_raw_value_commit(desc, value);
3840 }
3841 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
3842
3843 /**
3844 * gpiod_set_value_nocheck() - set a GPIO line value without checking
3845 * @desc: the descriptor to set the value on
3846 * @value: value to set
3847 *
3848 * This sets the value of a GPIO line backing a descriptor, applying
3849 * different semantic quirks like active low and open drain/source
3850 * handling.
3851 *
3852 * Returns:
3853 * 0 on success, negative error number on failure.
3854 */
gpiod_set_value_nocheck(struct gpio_desc * desc,int value)3855 static int gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
3856 {
3857 if (test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags))
3858 value = !value;
3859
3860 if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags))
3861 return gpio_set_open_drain_value_commit(desc, value);
3862 else if (test_bit(GPIOD_FLAG_OPEN_SOURCE, &desc->flags))
3863 return gpio_set_open_source_value_commit(desc, value);
3864
3865 return gpiod_set_raw_value_commit(desc, value);
3866 }
3867
3868 /**
3869 * gpiod_set_value() - assign a gpio's value
3870 * @desc: gpio whose value will be assigned
3871 * @value: value to assign
3872 *
3873 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
3874 * OPEN_DRAIN and OPEN_SOURCE flags into account.
3875 *
3876 * This function can be called from contexts where we cannot sleep, and will
3877 * complain if the GPIO chip functions potentially sleep.
3878 *
3879 * Returns:
3880 * 0 on success, negative error number on failure.
3881 */
gpiod_set_value(struct gpio_desc * desc,int value)3882 int gpiod_set_value(struct gpio_desc *desc, int value)
3883 {
3884 VALIDATE_DESC(desc);
3885 /* Should be using gpiod_set_value_cansleep() */
3886 WARN_ON(desc->gdev->can_sleep);
3887 return gpiod_set_value_nocheck(desc, value);
3888 }
3889 EXPORT_SYMBOL_GPL(gpiod_set_value);
3890
3891 /**
3892 * gpiod_set_raw_array_value() - assign values to an array of GPIOs
3893 * @array_size: number of elements in the descriptor array / value bitmap
3894 * @desc_array: array of GPIO descriptors whose values will be assigned
3895 * @array_info: information on applicability of fast bitmap processing path
3896 * @value_bitmap: bitmap of values to assign
3897 *
3898 * Set the raw values of the GPIOs, i.e. the values of the physical lines
3899 * without regard for their ACTIVE_LOW status.
3900 *
3901 * This function can be called from contexts where we cannot sleep, and will
3902 * complain if the GPIO chip functions potentially sleep.
3903 *
3904 * Returns:
3905 * 0 on success, or negative errno on failure.
3906 */
gpiod_set_raw_array_value(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)3907 int gpiod_set_raw_array_value(unsigned int array_size,
3908 struct gpio_desc **desc_array,
3909 struct gpio_array *array_info,
3910 unsigned long *value_bitmap)
3911 {
3912 if (!desc_array)
3913 return -EINVAL;
3914 return gpiod_set_array_value_complex(true, false, array_size,
3915 desc_array, array_info, value_bitmap);
3916 }
3917 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
3918
3919 /**
3920 * gpiod_set_array_value() - assign values to an array of GPIOs
3921 * @array_size: number of elements in the descriptor array / value bitmap
3922 * @desc_array: array of GPIO descriptors whose values will be assigned
3923 * @array_info: information on applicability of fast bitmap processing path
3924 * @value_bitmap: bitmap of values to assign
3925 *
3926 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3927 * into account.
3928 *
3929 * This function can be called from contexts where we cannot sleep, and will
3930 * complain if the GPIO chip functions potentially sleep.
3931 *
3932 * Returns:
3933 * 0 on success, or negative errno on failure.
3934 */
gpiod_set_array_value(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)3935 int gpiod_set_array_value(unsigned int array_size,
3936 struct gpio_desc **desc_array,
3937 struct gpio_array *array_info,
3938 unsigned long *value_bitmap)
3939 {
3940 if (!desc_array)
3941 return -EINVAL;
3942 return gpiod_set_array_value_complex(false, false, array_size,
3943 desc_array, array_info,
3944 value_bitmap);
3945 }
3946 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
3947
3948 /**
3949 * gpiod_cansleep() - report whether gpio value access may sleep
3950 * @desc: gpio to check
3951 *
3952 * Returns:
3953 * 0 for non-sleepable, 1 for sleepable, or an error code in case of error.
3954 */
gpiod_cansleep(const struct gpio_desc * desc)3955 int gpiod_cansleep(const struct gpio_desc *desc)
3956 {
3957 VALIDATE_DESC(desc);
3958 return desc->gdev->can_sleep;
3959 }
3960 EXPORT_SYMBOL_GPL(gpiod_cansleep);
3961
3962 /**
3963 * gpiod_set_consumer_name() - set the consumer name for the descriptor
3964 * @desc: gpio to set the consumer name on
3965 * @name: the new consumer name
3966 *
3967 * Returns:
3968 * 0 on success, or negative errno on failure.
3969 */
gpiod_set_consumer_name(struct gpio_desc * desc,const char * name)3970 int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
3971 {
3972 int ret;
3973
3974 VALIDATE_DESC(desc);
3975
3976 ret = desc_set_label(desc, name);
3977 if (ret == 0)
3978 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
3979
3980 return ret;
3981 }
3982 EXPORT_SYMBOL_GPL(gpiod_set_consumer_name);
3983
3984 /**
3985 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
3986 * @desc: gpio whose IRQ will be returned (already requested)
3987 *
3988 * Returns:
3989 * The IRQ corresponding to the passed GPIO, or an error code in case of error.
3990 */
gpiod_to_irq(const struct gpio_desc * desc)3991 int gpiod_to_irq(const struct gpio_desc *desc)
3992 {
3993 struct gpio_device *gdev;
3994 struct gpio_chip *gc;
3995 int offset;
3996 int ret;
3997
3998 ret = validate_desc(desc, __func__);
3999 if (ret <= 0)
4000 return -EINVAL;
4001
4002 gdev = desc->gdev;
4003 /* FIXME Cannot use gpio_chip_guard due to const desc. */
4004 guard(srcu)(&gdev->srcu);
4005 gc = srcu_dereference(gdev->chip, &gdev->srcu);
4006 if (!gc)
4007 return -ENODEV;
4008
4009 offset = gpio_chip_hwgpio(desc);
4010 if (gc->to_irq) {
4011 ret = gc->to_irq(gc, offset);
4012 if (ret)
4013 return ret;
4014
4015 /* Zero means NO_IRQ */
4016 return -ENXIO;
4017 }
4018 #ifdef CONFIG_GPIOLIB_IRQCHIP
4019 if (gc->irq.chip) {
4020 /*
4021 * Avoid race condition with other code, which tries to lookup
4022 * an IRQ before the irqchip has been properly registered,
4023 * i.e. while gpiochip is still being brought up.
4024 */
4025 return -EPROBE_DEFER;
4026 }
4027 #endif
4028 return -ENXIO;
4029 }
4030 EXPORT_SYMBOL_GPL(gpiod_to_irq);
4031
4032 /**
4033 * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
4034 * @gc: the chip the GPIO to lock belongs to
4035 * @offset: the offset of the GPIO to lock as IRQ
4036 *
4037 * This is used directly by GPIO drivers that want to lock down
4038 * a certain GPIO line to be used for IRQs.
4039 *
4040 * Returns:
4041 * 0 on success, or negative errno on failure.
4042 */
gpiochip_lock_as_irq(struct gpio_chip * gc,unsigned int offset)4043 int gpiochip_lock_as_irq(struct gpio_chip *gc, unsigned int offset)
4044 {
4045 struct gpio_desc *desc;
4046
4047 desc = gpiochip_get_desc(gc, offset);
4048 if (IS_ERR(desc))
4049 return PTR_ERR(desc);
4050
4051 /*
4052 * If it's fast: flush the direction setting if something changed
4053 * behind our back
4054 */
4055 if (!gc->can_sleep && gc->get_direction) {
4056 int dir = gpiod_get_direction(desc);
4057
4058 if (dir < 0) {
4059 chip_err(gc, "%s: cannot get GPIO direction\n",
4060 __func__);
4061 return dir;
4062 }
4063 }
4064
4065 /* To be valid for IRQ the line needs to be input or open drain */
4066 if (test_bit(GPIOD_FLAG_IS_OUT, &desc->flags) &&
4067 !test_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags)) {
4068 chip_err(gc,
4069 "%s: tried to flag a GPIO set as output for IRQ\n",
4070 __func__);
4071 return -EIO;
4072 }
4073
4074 set_bit(GPIOD_FLAG_USED_AS_IRQ, &desc->flags);
4075 set_bit(GPIOD_FLAG_IRQ_IS_ENABLED, &desc->flags);
4076
4077 return 0;
4078 }
4079 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
4080
4081 /**
4082 * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
4083 * @gc: the chip the GPIO to lock belongs to
4084 * @offset: the offset of the GPIO to lock as IRQ
4085 *
4086 * This is used directly by GPIO drivers that want to indicate
4087 * that a certain GPIO is no longer used exclusively for IRQ.
4088 */
gpiochip_unlock_as_irq(struct gpio_chip * gc,unsigned int offset)4089 void gpiochip_unlock_as_irq(struct gpio_chip *gc, unsigned int offset)
4090 {
4091 struct gpio_desc *desc;
4092
4093 desc = gpiochip_get_desc(gc, offset);
4094 if (IS_ERR(desc))
4095 return;
4096
4097 clear_bit(GPIOD_FLAG_USED_AS_IRQ, &desc->flags);
4098 clear_bit(GPIOD_FLAG_IRQ_IS_ENABLED, &desc->flags);
4099 }
4100 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
4101
gpiochip_disable_irq(struct gpio_chip * gc,unsigned int offset)4102 void gpiochip_disable_irq(struct gpio_chip *gc, unsigned int offset)
4103 {
4104 struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
4105
4106 if (!IS_ERR(desc) &&
4107 !WARN_ON(!test_bit(GPIOD_FLAG_USED_AS_IRQ, &desc->flags)))
4108 clear_bit(GPIOD_FLAG_IRQ_IS_ENABLED, &desc->flags);
4109 }
4110 EXPORT_SYMBOL_GPL(gpiochip_disable_irq);
4111
gpiochip_enable_irq(struct gpio_chip * gc,unsigned int offset)4112 void gpiochip_enable_irq(struct gpio_chip *gc, unsigned int offset)
4113 {
4114 struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
4115
4116 if (!IS_ERR(desc) &&
4117 !WARN_ON(!test_bit(GPIOD_FLAG_USED_AS_IRQ, &desc->flags))) {
4118 /*
4119 * We must not be output when using IRQ UNLESS we are
4120 * open drain.
4121 */
4122 WARN_ON(test_bit(GPIOD_FLAG_IS_OUT, &desc->flags) &&
4123 !test_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags));
4124 set_bit(GPIOD_FLAG_IRQ_IS_ENABLED, &desc->flags);
4125 }
4126 }
4127 EXPORT_SYMBOL_GPL(gpiochip_enable_irq);
4128
gpiochip_line_is_irq(struct gpio_chip * gc,unsigned int offset)4129 bool gpiochip_line_is_irq(struct gpio_chip *gc, unsigned int offset)
4130 {
4131 if (offset >= gc->ngpio)
4132 return false;
4133
4134 return test_bit(GPIOD_FLAG_USED_AS_IRQ, &gc->gpiodev->descs[offset].flags);
4135 }
4136 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
4137
gpiochip_reqres_irq(struct gpio_chip * gc,unsigned int offset)4138 int gpiochip_reqres_irq(struct gpio_chip *gc, unsigned int offset)
4139 {
4140 int ret;
4141
4142 if (!try_module_get(gc->gpiodev->owner))
4143 return -ENODEV;
4144
4145 ret = gpiochip_lock_as_irq(gc, offset);
4146 if (ret) {
4147 chip_err(gc, "unable to lock HW IRQ %u for IRQ\n", offset);
4148 module_put(gc->gpiodev->owner);
4149 return ret;
4150 }
4151 return 0;
4152 }
4153 EXPORT_SYMBOL_GPL(gpiochip_reqres_irq);
4154
gpiochip_relres_irq(struct gpio_chip * gc,unsigned int offset)4155 void gpiochip_relres_irq(struct gpio_chip *gc, unsigned int offset)
4156 {
4157 gpiochip_unlock_as_irq(gc, offset);
4158 module_put(gc->gpiodev->owner);
4159 }
4160 EXPORT_SYMBOL_GPL(gpiochip_relres_irq);
4161
gpiochip_line_is_open_drain(struct gpio_chip * gc,unsigned int offset)4162 bool gpiochip_line_is_open_drain(struct gpio_chip *gc, unsigned int offset)
4163 {
4164 if (offset >= gc->ngpio)
4165 return false;
4166
4167 return test_bit(GPIOD_FLAG_OPEN_DRAIN, &gc->gpiodev->descs[offset].flags);
4168 }
4169 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
4170
gpiochip_line_is_open_source(struct gpio_chip * gc,unsigned int offset)4171 bool gpiochip_line_is_open_source(struct gpio_chip *gc, unsigned int offset)
4172 {
4173 if (offset >= gc->ngpio)
4174 return false;
4175
4176 return test_bit(GPIOD_FLAG_OPEN_SOURCE, &gc->gpiodev->descs[offset].flags);
4177 }
4178 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
4179
gpiochip_line_is_persistent(struct gpio_chip * gc,unsigned int offset)4180 bool gpiochip_line_is_persistent(struct gpio_chip *gc, unsigned int offset)
4181 {
4182 if (offset >= gc->ngpio)
4183 return false;
4184
4185 return !test_bit(GPIOD_FLAG_TRANSITORY, &gc->gpiodev->descs[offset].flags);
4186 }
4187 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
4188
4189 /**
4190 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
4191 * @desc: gpio whose value will be returned
4192 *
4193 * Returns:
4194 * The GPIO's raw value, i.e. the value of the physical line disregarding
4195 * its ACTIVE_LOW status, or negative errno on failure.
4196 *
4197 * This function is to be called from contexts that can sleep.
4198 */
gpiod_get_raw_value_cansleep(const struct gpio_desc * desc)4199 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
4200 {
4201 might_sleep();
4202 VALIDATE_DESC(desc);
4203 return gpiod_get_raw_value_commit(desc);
4204 }
4205 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
4206
4207 /**
4208 * gpiod_get_value_cansleep() - return a gpio's value
4209 * @desc: gpio whose value will be returned
4210 *
4211 * Returns:
4212 * The GPIO's logical value, i.e. taking the ACTIVE_LOW status into
4213 * account, or negative errno on failure.
4214 *
4215 * This function is to be called from contexts that can sleep.
4216 */
gpiod_get_value_cansleep(const struct gpio_desc * desc)4217 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
4218 {
4219 int value;
4220
4221 might_sleep();
4222 VALIDATE_DESC(desc);
4223 value = gpiod_get_raw_value_commit(desc);
4224 if (value < 0)
4225 return value;
4226
4227 if (test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags))
4228 value = !value;
4229
4230 return value;
4231 }
4232 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
4233
4234 /**
4235 * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
4236 * @array_size: number of elements in the descriptor array / value bitmap
4237 * @desc_array: array of GPIO descriptors whose values will be read
4238 * @array_info: information on applicability of fast bitmap processing path
4239 * @value_bitmap: bitmap to store the read values
4240 *
4241 * Read the raw values of the GPIOs, i.e. the values of the physical lines
4242 * without regard for their ACTIVE_LOW status.
4243 *
4244 * This function is to be called from contexts that can sleep.
4245 *
4246 * Returns:
4247 * 0 on success, or negative errno on failure.
4248 */
gpiod_get_raw_array_value_cansleep(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)4249 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
4250 struct gpio_desc **desc_array,
4251 struct gpio_array *array_info,
4252 unsigned long *value_bitmap)
4253 {
4254 might_sleep();
4255 if (!desc_array)
4256 return -EINVAL;
4257 return gpiod_get_array_value_complex(true, true, array_size,
4258 desc_array, array_info,
4259 value_bitmap);
4260 }
4261 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
4262
4263 /**
4264 * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
4265 * @array_size: number of elements in the descriptor array / value bitmap
4266 * @desc_array: array of GPIO descriptors whose values will be read
4267 * @array_info: information on applicability of fast bitmap processing path
4268 * @value_bitmap: bitmap to store the read values
4269 *
4270 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4271 * into account.
4272 *
4273 * This function is to be called from contexts that can sleep.
4274 *
4275 * Returns:
4276 * 0 on success, or negative errno on failure.
4277 */
gpiod_get_array_value_cansleep(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)4278 int gpiod_get_array_value_cansleep(unsigned int array_size,
4279 struct gpio_desc **desc_array,
4280 struct gpio_array *array_info,
4281 unsigned long *value_bitmap)
4282 {
4283 might_sleep();
4284 if (!desc_array)
4285 return -EINVAL;
4286 return gpiod_get_array_value_complex(false, true, array_size,
4287 desc_array, array_info,
4288 value_bitmap);
4289 }
4290 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
4291
4292 /**
4293 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
4294 * @desc: gpio whose value will be assigned
4295 * @value: value to assign
4296 *
4297 * Set the raw value of the GPIO, i.e. the value of its physical line without
4298 * regard for its ACTIVE_LOW status.
4299 *
4300 * This function is to be called from contexts that can sleep.
4301 *
4302 * Returns:
4303 * 0 on success, negative error number on failure.
4304 */
gpiod_set_raw_value_cansleep(struct gpio_desc * desc,int value)4305 int gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
4306 {
4307 might_sleep();
4308 VALIDATE_DESC(desc);
4309 return gpiod_set_raw_value_commit(desc, value);
4310 }
4311 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
4312
4313 /**
4314 * gpiod_set_value_cansleep() - assign a gpio's value
4315 * @desc: gpio whose value will be assigned
4316 * @value: value to assign
4317 *
4318 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
4319 * account
4320 *
4321 * This function is to be called from contexts that can sleep.
4322 *
4323 * Returns:
4324 * 0 on success, negative error number on failure.
4325 */
gpiod_set_value_cansleep(struct gpio_desc * desc,int value)4326 int gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
4327 {
4328 might_sleep();
4329 VALIDATE_DESC(desc);
4330 return gpiod_set_value_nocheck(desc, value);
4331 }
4332 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
4333
4334 /**
4335 * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
4336 * @array_size: number of elements in the descriptor array / value bitmap
4337 * @desc_array: array of GPIO descriptors whose values will be assigned
4338 * @array_info: information on applicability of fast bitmap processing path
4339 * @value_bitmap: bitmap of values to assign
4340 *
4341 * Set the raw values of the GPIOs, i.e. the values of the physical lines
4342 * without regard for their ACTIVE_LOW status.
4343 *
4344 * This function is to be called from contexts that can sleep.
4345 *
4346 * Returns:
4347 * 0 on success, or negative errno on failure.
4348 */
gpiod_set_raw_array_value_cansleep(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)4349 int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
4350 struct gpio_desc **desc_array,
4351 struct gpio_array *array_info,
4352 unsigned long *value_bitmap)
4353 {
4354 might_sleep();
4355 if (!desc_array)
4356 return -EINVAL;
4357 return gpiod_set_array_value_complex(true, true, array_size, desc_array,
4358 array_info, value_bitmap);
4359 }
4360 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
4361
4362 /**
4363 * gpiod_add_lookup_tables() - register GPIO device consumers
4364 * @tables: list of tables of consumers to register
4365 * @n: number of tables in the list
4366 */
gpiod_add_lookup_tables(struct gpiod_lookup_table ** tables,size_t n)4367 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
4368 {
4369 unsigned int i;
4370
4371 guard(mutex)(&gpio_lookup_lock);
4372
4373 for (i = 0; i < n; i++)
4374 list_add_tail(&tables[i]->list, &gpio_lookup_list);
4375 }
4376
4377 /**
4378 * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
4379 * @array_size: number of elements in the descriptor array / value bitmap
4380 * @desc_array: array of GPIO descriptors whose values will be assigned
4381 * @array_info: information on applicability of fast bitmap processing path
4382 * @value_bitmap: bitmap of values to assign
4383 *
4384 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4385 * into account.
4386 *
4387 * This function is to be called from contexts that can sleep.
4388 *
4389 * Returns:
4390 * 0 on success, or negative errno on failure.
4391 */
gpiod_set_array_value_cansleep(unsigned int array_size,struct gpio_desc ** desc_array,struct gpio_array * array_info,unsigned long * value_bitmap)4392 int gpiod_set_array_value_cansleep(unsigned int array_size,
4393 struct gpio_desc **desc_array,
4394 struct gpio_array *array_info,
4395 unsigned long *value_bitmap)
4396 {
4397 might_sleep();
4398 if (!desc_array)
4399 return -EINVAL;
4400 return gpiod_set_array_value_complex(false, true, array_size,
4401 desc_array, array_info,
4402 value_bitmap);
4403 }
4404 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
4405
gpiod_line_state_notify(struct gpio_desc * desc,unsigned long action)4406 void gpiod_line_state_notify(struct gpio_desc *desc, unsigned long action)
4407 {
4408 guard(read_lock_irqsave)(&desc->gdev->line_state_lock);
4409
4410 raw_notifier_call_chain(&desc->gdev->line_state_notifier, action, desc);
4411 }
4412
4413 /**
4414 * gpiod_add_lookup_table() - register GPIO device consumers
4415 * @table: table of consumers to register
4416 */
gpiod_add_lookup_table(struct gpiod_lookup_table * table)4417 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
4418 {
4419 gpiod_add_lookup_tables(&table, 1);
4420 }
4421 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
4422
4423 /**
4424 * gpiod_remove_lookup_table() - unregister GPIO device consumers
4425 * @table: table of consumers to unregister
4426 */
gpiod_remove_lookup_table(struct gpiod_lookup_table * table)4427 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
4428 {
4429 /* Nothing to remove */
4430 if (!table)
4431 return;
4432
4433 guard(mutex)(&gpio_lookup_lock);
4434
4435 list_del(&table->list);
4436 }
4437 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
4438
4439 /**
4440 * gpiod_add_hogs() - register a set of GPIO hogs from machine code
4441 * @hogs: table of gpio hog entries with a zeroed sentinel at the end
4442 */
gpiod_add_hogs(struct gpiod_hog * hogs)4443 void gpiod_add_hogs(struct gpiod_hog *hogs)
4444 {
4445 struct gpiod_hog *hog;
4446
4447 guard(mutex)(&gpio_machine_hogs_mutex);
4448
4449 for (hog = &hogs[0]; hog->chip_label; hog++) {
4450 list_add_tail(&hog->list, &gpio_machine_hogs);
4451
4452 /*
4453 * The chip may have been registered earlier, so check if it
4454 * exists and, if so, try to hog the line now.
4455 */
4456 struct gpio_device *gdev __free(gpio_device_put) =
4457 gpio_device_find_by_label(hog->chip_label);
4458 if (gdev)
4459 gpiochip_machine_hog(gpio_device_get_chip(gdev), hog);
4460 }
4461 }
4462 EXPORT_SYMBOL_GPL(gpiod_add_hogs);
4463
gpiod_remove_hogs(struct gpiod_hog * hogs)4464 void gpiod_remove_hogs(struct gpiod_hog *hogs)
4465 {
4466 struct gpiod_hog *hog;
4467
4468 guard(mutex)(&gpio_machine_hogs_mutex);
4469
4470 for (hog = &hogs[0]; hog->chip_label; hog++)
4471 list_del(&hog->list);
4472 }
4473 EXPORT_SYMBOL_GPL(gpiod_remove_hogs);
4474
gpiod_find_lookup_table(struct device * dev)4475 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
4476 {
4477 const char *dev_id = dev ? dev_name(dev) : NULL;
4478 struct gpiod_lookup_table *table;
4479
4480 list_for_each_entry(table, &gpio_lookup_list, list) {
4481 if (table->dev_id && dev_id) {
4482 /*
4483 * Valid strings on both ends, must be identical to have
4484 * a match
4485 */
4486 if (!strcmp(table->dev_id, dev_id))
4487 return table;
4488 } else {
4489 /*
4490 * One of the pointers is NULL, so both must be to have
4491 * a match
4492 */
4493 if (dev_id == table->dev_id)
4494 return table;
4495 }
4496 }
4497
4498 return NULL;
4499 }
4500
gpiod_find(struct device * dev,const char * con_id,unsigned int idx,unsigned long * flags)4501 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
4502 unsigned int idx, unsigned long *flags)
4503 {
4504 struct gpio_desc *desc = ERR_PTR(-ENOENT);
4505 struct gpiod_lookup_table *table;
4506 struct gpiod_lookup *p;
4507 struct gpio_chip *gc;
4508
4509 guard(mutex)(&gpio_lookup_lock);
4510
4511 table = gpiod_find_lookup_table(dev);
4512 if (!table)
4513 return desc;
4514
4515 for (p = &table->table[0]; p->key; p++) {
4516 /* idx must always match exactly */
4517 if (p->idx != idx)
4518 continue;
4519
4520 /* If the lookup entry has a con_id, require exact match */
4521 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
4522 continue;
4523
4524 if (p->chip_hwnum == U16_MAX) {
4525 desc = gpio_name_to_desc(p->key);
4526 if (desc) {
4527 *flags = p->flags;
4528 return desc;
4529 }
4530
4531 dev_warn(dev, "cannot find GPIO line %s, deferring\n",
4532 p->key);
4533 return ERR_PTR(-EPROBE_DEFER);
4534 }
4535
4536 struct gpio_device *gdev __free(gpio_device_put) =
4537 gpio_device_find_by_label(p->key);
4538 if (!gdev) {
4539 /*
4540 * As the lookup table indicates a chip with
4541 * p->key should exist, assume it may
4542 * still appear later and let the interested
4543 * consumer be probed again or let the Deferred
4544 * Probe infrastructure handle the error.
4545 */
4546 dev_warn(dev, "cannot find GPIO chip %s, deferring\n",
4547 p->key);
4548 return ERR_PTR(-EPROBE_DEFER);
4549 }
4550
4551 gc = gpio_device_get_chip(gdev);
4552
4553 if (gc->ngpio <= p->chip_hwnum) {
4554 dev_err(dev,
4555 "requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
4556 idx, p->chip_hwnum, gc->ngpio - 1,
4557 gc->label);
4558 return ERR_PTR(-EINVAL);
4559 }
4560
4561 desc = gpio_device_get_desc(gdev, p->chip_hwnum);
4562 *flags = p->flags;
4563
4564 return desc;
4565 }
4566
4567 return desc;
4568 }
4569
platform_gpio_count(struct device * dev,const char * con_id)4570 static int platform_gpio_count(struct device *dev, const char *con_id)
4571 {
4572 struct gpiod_lookup_table *table;
4573 struct gpiod_lookup *p;
4574 unsigned int count = 0;
4575
4576 scoped_guard(mutex, &gpio_lookup_lock) {
4577 table = gpiod_find_lookup_table(dev);
4578 if (!table)
4579 return -ENOENT;
4580
4581 for (p = &table->table[0]; p->key; p++) {
4582 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
4583 (!con_id && !p->con_id))
4584 count++;
4585 }
4586 }
4587
4588 if (!count)
4589 return -ENOENT;
4590
4591 return count;
4592 }
4593
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)4594 static struct gpio_desc *gpiod_find_by_fwnode(struct fwnode_handle *fwnode,
4595 struct device *consumer,
4596 const char *con_id,
4597 unsigned int idx,
4598 enum gpiod_flags *flags,
4599 unsigned long *lookupflags)
4600 {
4601 const char *name = function_name_or_default(con_id);
4602 struct gpio_desc *desc = ERR_PTR(-ENOENT);
4603
4604 if (is_of_node(fwnode)) {
4605 dev_dbg(consumer, "using DT '%pfw' for '%s' GPIO lookup\n", fwnode, name);
4606 desc = of_find_gpio(to_of_node(fwnode), con_id, idx, lookupflags);
4607 } else if (is_acpi_node(fwnode)) {
4608 dev_dbg(consumer, "using ACPI '%pfw' for '%s' GPIO lookup\n", fwnode, name);
4609 desc = acpi_find_gpio(fwnode, con_id, idx, flags, lookupflags);
4610 } else if (is_software_node(fwnode)) {
4611 dev_dbg(consumer, "using swnode '%pfw' for '%s' GPIO lookup\n", fwnode, name);
4612 desc = swnode_find_gpio(fwnode, con_id, idx, lookupflags);
4613 }
4614
4615 return desc;
4616 }
4617
gpiod_fwnode_lookup(struct fwnode_handle * fwnode,struct device * consumer,const char * con_id,unsigned int idx,enum gpiod_flags * flags,unsigned long * lookupflags)4618 static struct gpio_desc *gpiod_fwnode_lookup(struct fwnode_handle *fwnode,
4619 struct device *consumer,
4620 const char *con_id,
4621 unsigned int idx,
4622 enum gpiod_flags *flags,
4623 unsigned long *lookupflags)
4624 {
4625 struct gpio_desc *desc;
4626
4627 desc = gpiod_find_by_fwnode(fwnode, consumer, con_id, idx, flags, lookupflags);
4628 if (gpiod_not_found(desc) && !IS_ERR_OR_NULL(fwnode))
4629 desc = gpiod_find_by_fwnode(fwnode->secondary, consumer, con_id,
4630 idx, flags, lookupflags);
4631
4632 return desc;
4633 }
4634
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)4635 struct gpio_desc *gpiod_find_and_request(struct device *consumer,
4636 struct fwnode_handle *fwnode,
4637 const char *con_id,
4638 unsigned int idx,
4639 enum gpiod_flags flags,
4640 const char *label,
4641 bool platform_lookup_allowed)
4642 {
4643 unsigned long lookupflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4644 const char *name = function_name_or_default(con_id);
4645 /*
4646 * scoped_guard() is implemented as a for loop, meaning static
4647 * analyzers will complain about these two not being initialized.
4648 */
4649 struct gpio_desc *desc = NULL;
4650 int ret = 0;
4651
4652 scoped_guard(srcu, &gpio_devices_srcu) {
4653 desc = gpiod_fwnode_lookup(fwnode, consumer, con_id, idx,
4654 &flags, &lookupflags);
4655 if (gpiod_not_found(desc) && platform_lookup_allowed) {
4656 /*
4657 * Either we are not using DT or ACPI, or their lookup
4658 * did not return a result. In that case, use platform
4659 * lookup as a fallback.
4660 */
4661 dev_dbg(consumer,
4662 "using lookup tables for GPIO lookup\n");
4663 desc = gpiod_find(consumer, con_id, idx, &lookupflags);
4664 }
4665
4666 if (IS_ERR(desc)) {
4667 dev_dbg(consumer, "No GPIO consumer %s found\n", name);
4668 return desc;
4669 }
4670
4671 /*
4672 * If a connection label was passed use that, else attempt to use
4673 * the device name as label
4674 */
4675 ret = gpiod_request(desc, label);
4676 }
4677 if (ret) {
4678 if (!(ret == -EBUSY && flags & GPIOD_FLAGS_BIT_NONEXCLUSIVE))
4679 return ERR_PTR(ret);
4680
4681 /*
4682 * This happens when there are several consumers for
4683 * the same GPIO line: we just return here without
4684 * further initialization. It is a bit of a hack.
4685 * This is necessary to support fixed regulators.
4686 *
4687 * FIXME: Make this more sane and safe.
4688 */
4689 dev_info(consumer, "nonexclusive access to GPIO for %s\n", name);
4690 return desc;
4691 }
4692
4693 ret = gpiod_configure_flags(desc, con_id, lookupflags, flags);
4694 if (ret < 0) {
4695 gpiod_put(desc);
4696 dev_err(consumer, "setup of GPIO %s failed: %d\n", name, ret);
4697 return ERR_PTR(ret);
4698 }
4699
4700 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_REQUESTED);
4701
4702 return desc;
4703 }
4704
4705 /**
4706 * fwnode_gpiod_get_index - obtain a GPIO from firmware node
4707 * @fwnode: handle of the firmware node
4708 * @con_id: function within the GPIO consumer
4709 * @index: index of the GPIO to obtain for the consumer
4710 * @flags: GPIO initialization flags
4711 * @label: label to attach to the requested GPIO
4712 *
4713 * This function can be used for drivers that get their configuration
4714 * from opaque firmware.
4715 *
4716 * The function properly finds the corresponding GPIO using whatever is the
4717 * underlying firmware interface and then makes sure that the GPIO
4718 * descriptor is requested before it is returned to the caller.
4719 *
4720 * Returns:
4721 * On successful request the GPIO pin is configured in accordance with
4722 * provided @flags.
4723 *
4724 * In case of error an ERR_PTR() is returned.
4725 */
fwnode_gpiod_get_index(struct fwnode_handle * fwnode,const char * con_id,int index,enum gpiod_flags flags,const char * label)4726 struct gpio_desc *fwnode_gpiod_get_index(struct fwnode_handle *fwnode,
4727 const char *con_id,
4728 int index,
4729 enum gpiod_flags flags,
4730 const char *label)
4731 {
4732 return gpiod_find_and_request(NULL, fwnode, con_id, index, flags, label, false);
4733 }
4734 EXPORT_SYMBOL_GPL(fwnode_gpiod_get_index);
4735
4736 /**
4737 * gpiod_count - return the number of GPIOs associated with a device / function
4738 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4739 * @con_id: function within the GPIO consumer
4740 *
4741 * Returns:
4742 * The number of GPIOs associated with a device / function or -ENOENT if no
4743 * GPIO has been assigned to the requested function.
4744 */
gpiod_count(struct device * dev,const char * con_id)4745 int gpiod_count(struct device *dev, const char *con_id)
4746 {
4747 const struct fwnode_handle *fwnode = dev ? dev_fwnode(dev) : NULL;
4748 int count = -ENOENT;
4749
4750 if (is_of_node(fwnode))
4751 count = of_gpio_count(fwnode, con_id);
4752 else if (is_acpi_node(fwnode))
4753 count = acpi_gpio_count(fwnode, con_id);
4754 else if (is_software_node(fwnode))
4755 count = swnode_gpio_count(fwnode, con_id);
4756
4757 if (count < 0)
4758 count = platform_gpio_count(dev, con_id);
4759
4760 return count;
4761 }
4762 EXPORT_SYMBOL_GPL(gpiod_count);
4763
4764 /**
4765 * gpiod_get - obtain a GPIO for a given GPIO function
4766 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4767 * @con_id: function within the GPIO consumer
4768 * @flags: optional GPIO initialization flags
4769 *
4770 * Returns:
4771 * The GPIO descriptor corresponding to the function @con_id of device
4772 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
4773 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
4774 */
gpiod_get(struct device * dev,const char * con_id,enum gpiod_flags flags)4775 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
4776 enum gpiod_flags flags)
4777 {
4778 return gpiod_get_index(dev, con_id, 0, flags);
4779 }
4780 EXPORT_SYMBOL_GPL(gpiod_get);
4781
4782 /**
4783 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
4784 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4785 * @con_id: function within the GPIO consumer
4786 * @flags: optional GPIO initialization flags
4787 *
4788 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
4789 * the requested function it will return NULL. This is convenient for drivers
4790 * that need to handle optional GPIOs.
4791 *
4792 * Returns:
4793 * The GPIO descriptor corresponding to the function @con_id of device
4794 * dev, NULL if no GPIO has been assigned to the requested function, or
4795 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
4796 */
gpiod_get_optional(struct device * dev,const char * con_id,enum gpiod_flags flags)4797 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
4798 const char *con_id,
4799 enum gpiod_flags flags)
4800 {
4801 return gpiod_get_index_optional(dev, con_id, 0, flags);
4802 }
4803 EXPORT_SYMBOL_GPL(gpiod_get_optional);
4804
4805
4806 /**
4807 * gpiod_configure_flags - helper function to configure a given GPIO
4808 * @desc: gpio whose value will be assigned
4809 * @con_id: function within the GPIO consumer
4810 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
4811 * of_find_gpio() or of_get_gpio_hog()
4812 * @dflags: gpiod_flags - optional GPIO initialization flags
4813 *
4814 * Returns:
4815 * 0 on success, -ENOENT if no GPIO has been assigned to the
4816 * requested function and/or index, or another IS_ERR() code if an error
4817 * occurred while trying to acquire the GPIO.
4818 */
gpiod_configure_flags(struct gpio_desc * desc,const char * con_id,unsigned long lflags,enum gpiod_flags dflags)4819 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
4820 unsigned long lflags, enum gpiod_flags dflags)
4821 {
4822 const char *name = function_name_or_default(con_id);
4823 int ret;
4824
4825 if (lflags & GPIO_ACTIVE_LOW)
4826 set_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags);
4827
4828 if (lflags & GPIO_OPEN_DRAIN)
4829 set_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags);
4830 else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
4831 /*
4832 * This enforces open drain mode from the consumer side.
4833 * This is necessary for some busses like I2C, but the lookup
4834 * should *REALLY* have specified them as open drain in the
4835 * first place, so print a little warning here.
4836 */
4837 set_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags);
4838 gpiod_warn(desc,
4839 "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
4840 }
4841
4842 if (lflags & GPIO_OPEN_SOURCE)
4843 set_bit(GPIOD_FLAG_OPEN_SOURCE, &desc->flags);
4844
4845 if (((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DOWN)) ||
4846 ((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DISABLE)) ||
4847 ((lflags & GPIO_PULL_DOWN) && (lflags & GPIO_PULL_DISABLE))) {
4848 gpiod_err(desc,
4849 "multiple pull-up, pull-down or pull-disable enabled, invalid configuration\n");
4850 return -EINVAL;
4851 }
4852
4853 if (lflags & GPIO_PULL_UP)
4854 set_bit(GPIOD_FLAG_PULL_UP, &desc->flags);
4855 else if (lflags & GPIO_PULL_DOWN)
4856 set_bit(GPIOD_FLAG_PULL_DOWN, &desc->flags);
4857 else if (lflags & GPIO_PULL_DISABLE)
4858 set_bit(GPIOD_FLAG_BIAS_DISABLE, &desc->flags);
4859
4860 ret = gpiod_set_transitory(desc, (lflags & GPIO_TRANSITORY));
4861 if (ret < 0)
4862 return ret;
4863
4864 /* No particular flag request, return here... */
4865 if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
4866 gpiod_dbg(desc, "no flags found for GPIO %s\n", name);
4867 return 0;
4868 }
4869
4870 /* Process flags */
4871 if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
4872 ret = gpiod_direction_output_nonotify(desc,
4873 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
4874 else
4875 ret = gpiod_direction_input_nonotify(desc);
4876
4877 return ret;
4878 }
4879
4880 /**
4881 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
4882 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4883 * @con_id: function within the GPIO consumer
4884 * @idx: index of the GPIO to obtain in the consumer
4885 * @flags: optional GPIO initialization flags
4886 *
4887 * This variant of gpiod_get() allows to access GPIOs other than the first
4888 * defined one for functions that define several GPIOs.
4889 *
4890 * Returns:
4891 * A valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
4892 * requested function and/or index, or another IS_ERR() code if an error
4893 * occurred while trying to acquire the GPIO.
4894 */
gpiod_get_index(struct device * dev,const char * con_id,unsigned int idx,enum gpiod_flags flags)4895 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
4896 const char *con_id,
4897 unsigned int idx,
4898 enum gpiod_flags flags)
4899 {
4900 struct fwnode_handle *fwnode = dev ? dev_fwnode(dev) : NULL;
4901 const char *devname = dev ? dev_name(dev) : "?";
4902 const char *label = con_id ?: devname;
4903
4904 return gpiod_find_and_request(dev, fwnode, con_id, idx, flags, label, true);
4905 }
4906 EXPORT_SYMBOL_GPL(gpiod_get_index);
4907
4908 /**
4909 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
4910 * function
4911 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4912 * @con_id: function within the GPIO consumer
4913 * @index: index of the GPIO to obtain in the consumer
4914 * @flags: optional GPIO initialization flags
4915 *
4916 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
4917 * specified index was assigned to the requested function it will return NULL.
4918 * This is convenient for drivers that need to handle optional GPIOs.
4919 *
4920 * Returns:
4921 * A valid GPIO descriptor, NULL if no GPIO has been assigned to the
4922 * requested function and/or index, or another IS_ERR() code if an error
4923 * occurred while trying to acquire the GPIO.
4924 */
gpiod_get_index_optional(struct device * dev,const char * con_id,unsigned int index,enum gpiod_flags flags)4925 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
4926 const char *con_id,
4927 unsigned int index,
4928 enum gpiod_flags flags)
4929 {
4930 struct gpio_desc *desc;
4931
4932 desc = gpiod_get_index(dev, con_id, index, flags);
4933 if (gpiod_not_found(desc))
4934 return NULL;
4935
4936 return desc;
4937 }
4938 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
4939
4940 /**
4941 * gpiod_hog - Hog the specified GPIO desc given the provided flags
4942 * @desc: gpio whose value will be assigned
4943 * @name: gpio line name
4944 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
4945 * of_find_gpio() or of_get_gpio_hog()
4946 * @dflags: gpiod_flags - optional GPIO initialization flags
4947 *
4948 * Returns:
4949 * 0 on success, or negative errno on failure.
4950 */
gpiod_hog(struct gpio_desc * desc,const char * name,unsigned long lflags,enum gpiod_flags dflags)4951 int gpiod_hog(struct gpio_desc *desc, const char *name,
4952 unsigned long lflags, enum gpiod_flags dflags)
4953 {
4954 struct gpio_device *gdev = desc->gdev;
4955 struct gpio_desc *local_desc;
4956 int hwnum;
4957 int ret;
4958
4959 CLASS(gpio_chip_guard, guard)(desc);
4960 if (!guard.gc)
4961 return -ENODEV;
4962
4963 if (test_and_set_bit(GPIOD_FLAG_IS_HOGGED, &desc->flags))
4964 return 0;
4965
4966 hwnum = gpio_chip_hwgpio(desc);
4967
4968 local_desc = gpiochip_request_own_desc(guard.gc, hwnum, name,
4969 lflags, dflags);
4970 if (IS_ERR(local_desc)) {
4971 clear_bit(GPIOD_FLAG_IS_HOGGED, &desc->flags);
4972 ret = PTR_ERR(local_desc);
4973 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
4974 name, gdev->label, hwnum, ret);
4975 return ret;
4976 }
4977
4978 gpiod_dbg(desc, "hogged as %s/%s\n",
4979 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
4980 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ?
4981 str_high_low(dflags & GPIOD_FLAGS_BIT_DIR_VAL) : "?");
4982
4983 return 0;
4984 }
4985
4986 /**
4987 * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
4988 * @gc: gpio chip to act on
4989 */
gpiochip_free_hogs(struct gpio_chip * gc)4990 static void gpiochip_free_hogs(struct gpio_chip *gc)
4991 {
4992 struct gpio_desc *desc;
4993
4994 for_each_gpio_desc_with_flag(gc, desc, GPIOD_FLAG_IS_HOGGED)
4995 gpiochip_free_own_desc(desc);
4996 }
4997
4998 /**
4999 * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
5000 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5001 * @con_id: function within the GPIO consumer
5002 * @flags: optional GPIO initialization flags
5003 *
5004 * This function acquires all the GPIOs defined under a given function.
5005 *
5006 * Returns:
5007 * The GPIO descriptors corresponding to the function @con_id of device
5008 * dev, -ENOENT if no GPIO has been assigned to the requested function,
5009 * or another IS_ERR() code if an error occurred while trying to acquire
5010 * the GPIOs.
5011 */
gpiod_get_array(struct device * dev,const char * con_id,enum gpiod_flags flags)5012 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
5013 const char *con_id,
5014 enum gpiod_flags flags)
5015 {
5016 struct gpio_desc *desc;
5017 struct gpio_descs *descs;
5018 struct gpio_device *gdev;
5019 struct gpio_array *array_info = NULL;
5020 int count, bitmap_size;
5021 unsigned long dflags;
5022 size_t descs_size;
5023
5024 count = gpiod_count(dev, con_id);
5025 if (count < 0)
5026 return ERR_PTR(count);
5027
5028 descs_size = struct_size(descs, desc, count);
5029 descs = kzalloc(descs_size, GFP_KERNEL);
5030 if (!descs)
5031 return ERR_PTR(-ENOMEM);
5032
5033 for (descs->ndescs = 0; descs->ndescs < count; descs->ndescs++) {
5034 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
5035 if (IS_ERR(desc)) {
5036 gpiod_put_array(descs);
5037 return ERR_CAST(desc);
5038 }
5039
5040 descs->desc[descs->ndescs] = desc;
5041
5042 gdev = gpiod_to_gpio_device(desc);
5043 /*
5044 * If pin hardware number of array member 0 is also 0, select
5045 * its chip as a candidate for fast bitmap processing path.
5046 */
5047 if (descs->ndescs == 0 && gpio_chip_hwgpio(desc) == 0) {
5048 struct gpio_descs *array;
5049
5050 bitmap_size = BITS_TO_LONGS(gdev->ngpio > count ?
5051 gdev->ngpio : count);
5052
5053 array = krealloc(descs, descs_size +
5054 struct_size(array_info, invert_mask, 3 * bitmap_size),
5055 GFP_KERNEL | __GFP_ZERO);
5056 if (!array) {
5057 gpiod_put_array(descs);
5058 return ERR_PTR(-ENOMEM);
5059 }
5060
5061 descs = array;
5062
5063 array_info = (void *)descs + descs_size;
5064 array_info->get_mask = array_info->invert_mask +
5065 bitmap_size;
5066 array_info->set_mask = array_info->get_mask +
5067 bitmap_size;
5068
5069 array_info->desc = descs->desc;
5070 array_info->size = count;
5071 array_info->gdev = gdev;
5072 bitmap_set(array_info->get_mask, descs->ndescs,
5073 count - descs->ndescs);
5074 bitmap_set(array_info->set_mask, descs->ndescs,
5075 count - descs->ndescs);
5076 descs->info = array_info;
5077 }
5078
5079 /* If there is no cache for fast bitmap processing path, continue */
5080 if (!array_info)
5081 continue;
5082
5083 /* Unmark array members which don't belong to the 'fast' chip */
5084 if (array_info->gdev != gdev) {
5085 __clear_bit(descs->ndescs, array_info->get_mask);
5086 __clear_bit(descs->ndescs, array_info->set_mask);
5087 }
5088 /*
5089 * Detect array members which belong to the 'fast' chip
5090 * but their pins are not in hardware order.
5091 */
5092 else if (gpio_chip_hwgpio(desc) != descs->ndescs) {
5093 /*
5094 * Don't use fast path if all array members processed so
5095 * far belong to the same chip as this one but its pin
5096 * hardware number is different from its array index.
5097 */
5098 if (bitmap_full(array_info->get_mask, descs->ndescs)) {
5099 array_info = NULL;
5100 } else {
5101 __clear_bit(descs->ndescs,
5102 array_info->get_mask);
5103 __clear_bit(descs->ndescs,
5104 array_info->set_mask);
5105 }
5106 } else {
5107 dflags = READ_ONCE(desc->flags);
5108 /* Exclude open drain or open source from fast output */
5109 if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &dflags) ||
5110 test_bit(GPIOD_FLAG_OPEN_SOURCE, &dflags))
5111 __clear_bit(descs->ndescs,
5112 array_info->set_mask);
5113 /* Identify 'fast' pins which require invertion */
5114 if (gpiod_is_active_low(desc))
5115 __set_bit(descs->ndescs,
5116 array_info->invert_mask);
5117 }
5118 }
5119 if (array_info)
5120 dev_dbg(dev,
5121 "GPIO array info: chip=%s, size=%d, get_mask=%lx, set_mask=%lx, invert_mask=%lx\n",
5122 array_info->gdev->label, array_info->size,
5123 *array_info->get_mask, *array_info->set_mask,
5124 *array_info->invert_mask);
5125 return descs;
5126 }
5127 EXPORT_SYMBOL_GPL(gpiod_get_array);
5128
5129 /**
5130 * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
5131 * function
5132 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5133 * @con_id: function within the GPIO consumer
5134 * @flags: optional GPIO initialization flags
5135 *
5136 * This is equivalent to gpiod_get_array(), except that when no GPIO was
5137 * assigned to the requested function it will return NULL.
5138 *
5139 * Returns:
5140 * The GPIO descriptors corresponding to the function @con_id of device
5141 * dev, NULL if no GPIO has been assigned to the requested function,
5142 * or another IS_ERR() code if an error occurred while trying to acquire
5143 * the GPIOs.
5144 */
gpiod_get_array_optional(struct device * dev,const char * con_id,enum gpiod_flags flags)5145 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
5146 const char *con_id,
5147 enum gpiod_flags flags)
5148 {
5149 struct gpio_descs *descs;
5150
5151 descs = gpiod_get_array(dev, con_id, flags);
5152 if (gpiod_not_found(descs))
5153 return NULL;
5154
5155 return descs;
5156 }
5157 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
5158
5159 /**
5160 * gpiod_put - dispose of a GPIO descriptor
5161 * @desc: GPIO descriptor to dispose of
5162 *
5163 * No descriptor can be used after gpiod_put() has been called on it.
5164 */
gpiod_put(struct gpio_desc * desc)5165 void gpiod_put(struct gpio_desc *desc)
5166 {
5167 gpiod_free(desc);
5168 }
5169 EXPORT_SYMBOL_GPL(gpiod_put);
5170
5171 /**
5172 * gpiod_put_array - dispose of multiple GPIO descriptors
5173 * @descs: struct gpio_descs containing an array of descriptors
5174 */
gpiod_put_array(struct gpio_descs * descs)5175 void gpiod_put_array(struct gpio_descs *descs)
5176 {
5177 unsigned int i;
5178
5179 for (i = 0; i < descs->ndescs; i++)
5180 gpiod_put(descs->desc[i]);
5181
5182 kfree(descs);
5183 }
5184 EXPORT_SYMBOL_GPL(gpiod_put_array);
5185
gpio_stub_drv_probe(struct device * dev)5186 static int gpio_stub_drv_probe(struct device *dev)
5187 {
5188 /*
5189 * The DT node of some GPIO chips have a "compatible" property, but
5190 * never have a struct device added and probed by a driver to register
5191 * the GPIO chip with gpiolib. In such cases, fw_devlink=on will cause
5192 * the consumers of the GPIO chip to get probe deferred forever because
5193 * they will be waiting for a device associated with the GPIO chip
5194 * firmware node to get added and bound to a driver.
5195 *
5196 * To allow these consumers to probe, we associate the struct
5197 * gpio_device of the GPIO chip with the firmware node and then simply
5198 * bind it to this stub driver.
5199 */
5200 return 0;
5201 }
5202
5203 static struct device_driver gpio_stub_drv = {
5204 .name = "gpio_stub_drv",
5205 .bus = &gpio_bus_type,
5206 .probe = gpio_stub_drv_probe,
5207 };
5208
gpiolib_dev_init(void)5209 static int __init gpiolib_dev_init(void)
5210 {
5211 int ret;
5212
5213 /* Register GPIO sysfs bus */
5214 ret = bus_register(&gpio_bus_type);
5215 if (ret < 0) {
5216 pr_err("gpiolib: could not register GPIO bus type\n");
5217 return ret;
5218 }
5219
5220 ret = driver_register(&gpio_stub_drv);
5221 if (ret < 0) {
5222 pr_err("gpiolib: could not register GPIO stub driver\n");
5223 bus_unregister(&gpio_bus_type);
5224 return ret;
5225 }
5226
5227 ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, GPIOCHIP_NAME);
5228 if (ret < 0) {
5229 pr_err("gpiolib: failed to allocate char dev region\n");
5230 driver_unregister(&gpio_stub_drv);
5231 bus_unregister(&gpio_bus_type);
5232 return ret;
5233 }
5234
5235 gpiolib_initialized = true;
5236 gpiochip_setup_devs();
5237
5238 #if IS_ENABLED(CONFIG_OF_DYNAMIC) && IS_ENABLED(CONFIG_OF_GPIO)
5239 WARN_ON(of_reconfig_notifier_register(&gpio_of_notifier));
5240 #endif /* CONFIG_OF_DYNAMIC && CONFIG_OF_GPIO */
5241
5242 return ret;
5243 }
5244 core_initcall(gpiolib_dev_init);
5245
5246 #ifdef CONFIG_DEBUG_FS
5247
gpiolib_dbg_show(struct seq_file * s,struct gpio_device * gdev)5248 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
5249 {
5250 bool active_low, is_irq, is_out;
5251 struct gpio_desc *desc;
5252 unsigned int gpio = 0;
5253 struct gpio_chip *gc;
5254 unsigned long flags;
5255 int value;
5256
5257 guard(srcu)(&gdev->srcu);
5258
5259 gc = srcu_dereference(gdev->chip, &gdev->srcu);
5260 if (!gc) {
5261 seq_puts(s, "Underlying GPIO chip is gone\n");
5262 return;
5263 }
5264
5265 for_each_gpio_desc(gc, desc) {
5266 guard(srcu)(&desc->gdev->desc_srcu);
5267 flags = READ_ONCE(desc->flags);
5268 is_irq = test_bit(GPIOD_FLAG_USED_AS_IRQ, &flags);
5269 if (is_irq || test_bit(GPIOD_FLAG_REQUESTED, &flags)) {
5270 gpiod_get_direction(desc);
5271 is_out = test_bit(GPIOD_FLAG_IS_OUT, &flags);
5272 value = gpio_chip_get_value(gc, desc);
5273 active_low = test_bit(GPIOD_FLAG_ACTIVE_LOW, &flags);
5274 seq_printf(s, " gpio-%-3u (%-20.20s|%-20.20s) %s %s %s%s\n",
5275 gpio, desc->name ?: "", gpiod_get_label(desc),
5276 is_out ? "out" : "in ",
5277 value >= 0 ? str_hi_lo(value) : "? ",
5278 is_irq ? "IRQ " : "",
5279 active_low ? "ACTIVE LOW" : "");
5280 } else if (desc->name) {
5281 seq_printf(s, " gpio-%-3u (%-20.20s)\n", gpio, desc->name);
5282 }
5283
5284 gpio++;
5285 }
5286 }
5287
5288 struct gpiolib_seq_priv {
5289 bool newline;
5290 int idx;
5291 };
5292
gpiolib_seq_start(struct seq_file * s,loff_t * pos)5293 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
5294 {
5295 struct gpiolib_seq_priv *priv;
5296 struct gpio_device *gdev;
5297 loff_t index = *pos;
5298
5299 s->private = NULL;
5300
5301 priv = kzalloc(sizeof(*priv), GFP_KERNEL);
5302 if (!priv)
5303 return NULL;
5304
5305 s->private = priv;
5306 if (*pos > 0)
5307 priv->newline = true;
5308 priv->idx = srcu_read_lock(&gpio_devices_srcu);
5309
5310 list_for_each_entry_srcu(gdev, &gpio_devices, list,
5311 srcu_read_lock_held(&gpio_devices_srcu)) {
5312 if (index-- == 0)
5313 return gdev;
5314 }
5315
5316 return NULL;
5317 }
5318
gpiolib_seq_next(struct seq_file * s,void * v,loff_t * pos)5319 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
5320 {
5321 struct gpiolib_seq_priv *priv = s->private;
5322 struct gpio_device *gdev = v, *next;
5323
5324 next = list_entry_rcu(gdev->list.next, struct gpio_device, list);
5325 gdev = &next->list == &gpio_devices ? NULL : next;
5326 priv->newline = true;
5327 ++*pos;
5328
5329 return gdev;
5330 }
5331
gpiolib_seq_stop(struct seq_file * s,void * v)5332 static void gpiolib_seq_stop(struct seq_file *s, void *v)
5333 {
5334 struct gpiolib_seq_priv *priv;
5335
5336 priv = s->private;
5337 if (!priv)
5338 return;
5339
5340 srcu_read_unlock(&gpio_devices_srcu, priv->idx);
5341 kfree(priv);
5342 }
5343
gpiolib_seq_show(struct seq_file * s,void * v)5344 static int gpiolib_seq_show(struct seq_file *s, void *v)
5345 {
5346 struct gpiolib_seq_priv *priv = s->private;
5347 struct gpio_device *gdev = v;
5348 struct gpio_chip *gc;
5349 struct device *parent;
5350
5351 if (priv->newline)
5352 seq_putc(s, '\n');
5353
5354 guard(srcu)(&gdev->srcu);
5355
5356 gc = srcu_dereference(gdev->chip, &gdev->srcu);
5357 if (!gc) {
5358 seq_printf(s, "%s: (dangling chip)\n", dev_name(&gdev->dev));
5359 return 0;
5360 }
5361
5362 seq_printf(s, "%s: %u GPIOs", dev_name(&gdev->dev), gdev->ngpio);
5363 parent = gc->parent;
5364 if (parent)
5365 seq_printf(s, ", parent: %s/%s",
5366 parent->bus ? parent->bus->name : "no-bus",
5367 dev_name(parent));
5368 if (gc->label)
5369 seq_printf(s, ", %s", gc->label);
5370 if (gc->can_sleep)
5371 seq_printf(s, ", can sleep");
5372 seq_printf(s, ":\n");
5373
5374 if (gc->dbg_show)
5375 gc->dbg_show(s, gc);
5376 else
5377 gpiolib_dbg_show(s, gdev);
5378
5379 return 0;
5380 }
5381
5382 static const struct seq_operations gpiolib_sops = {
5383 .start = gpiolib_seq_start,
5384 .next = gpiolib_seq_next,
5385 .stop = gpiolib_seq_stop,
5386 .show = gpiolib_seq_show,
5387 };
5388 DEFINE_SEQ_ATTRIBUTE(gpiolib);
5389
gpiolib_debugfs_init(void)5390 static int __init gpiolib_debugfs_init(void)
5391 {
5392 /* /sys/kernel/debug/gpio */
5393 debugfs_create_file("gpio", 0444, NULL, NULL, &gpiolib_fops);
5394 return 0;
5395 }
5396 subsys_initcall(gpiolib_debugfs_init);
5397
5398 #endif /* DEBUG_FS */
5399