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