gpio: kill off set_irq_flags usage
[cascardo/linux.git] / drivers / gpio / gpiolib.c
1 #include <linux/kernel.h>
2 #include <linux/module.h>
3 #include <linux/interrupt.h>
4 #include <linux/irq.h>
5 #include <linux/spinlock.h>
6 #include <linux/list.h>
7 #include <linux/device.h>
8 #include <linux/err.h>
9 #include <linux/debugfs.h>
10 #include <linux/seq_file.h>
11 #include <linux/gpio.h>
12 #include <linux/of_gpio.h>
13 #include <linux/idr.h>
14 #include <linux/slab.h>
15 #include <linux/acpi.h>
16 #include <linux/gpio/driver.h>
17 #include <linux/gpio/machine.h>
18
19 #include "gpiolib.h"
20
21 #define CREATE_TRACE_POINTS
22 #include <trace/events/gpio.h>
23
24 /* Implementation infrastructure for GPIO interfaces.
25  *
26  * The GPIO programming interface allows for inlining speed-critical
27  * get/set operations for common cases, so that access to SOC-integrated
28  * GPIOs can sometimes cost only an instruction or two per bit.
29  */
30
31
32 /* When debugging, extend minimal trust to callers and platform code.
33  * Also emit diagnostic messages that may help initial bringup, when
34  * board setup or driver bugs are most common.
35  *
36  * Otherwise, minimize overhead in what may be bitbanging codepaths.
37  */
38 #ifdef  DEBUG
39 #define extra_checks    1
40 #else
41 #define extra_checks    0
42 #endif
43
44 /* gpio_lock prevents conflicts during gpio_desc[] table updates.
45  * While any GPIO is requested, its gpio_chip is not removable;
46  * each GPIO's "requested" flag serves as a lock and refcount.
47  */
48 DEFINE_SPINLOCK(gpio_lock);
49
50 #define GPIO_OFFSET_VALID(chip, offset) (offset >= 0 && offset < chip->ngpio)
51
52 static DEFINE_MUTEX(gpio_lookup_lock);
53 static LIST_HEAD(gpio_lookup_list);
54 LIST_HEAD(gpio_chips);
55
56
57 static void gpiochip_free_hogs(struct gpio_chip *chip);
58 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip);
59
60
61 static inline void desc_set_label(struct gpio_desc *d, const char *label)
62 {
63         d->label = label;
64 }
65
66 /**
67  * Convert a GPIO number to its descriptor
68  */
69 struct gpio_desc *gpio_to_desc(unsigned gpio)
70 {
71         struct gpio_chip *chip;
72         unsigned long flags;
73
74         spin_lock_irqsave(&gpio_lock, flags);
75
76         list_for_each_entry(chip, &gpio_chips, list) {
77                 if (chip->base <= gpio && chip->base + chip->ngpio > gpio) {
78                         spin_unlock_irqrestore(&gpio_lock, flags);
79                         return &chip->desc[gpio - chip->base];
80                 }
81         }
82
83         spin_unlock_irqrestore(&gpio_lock, flags);
84
85         if (!gpio_is_valid(gpio))
86                 WARN(1, "invalid GPIO %d\n", gpio);
87
88         return NULL;
89 }
90 EXPORT_SYMBOL_GPL(gpio_to_desc);
91
92 /**
93  * Get the GPIO descriptor corresponding to the given hw number for this chip.
94  */
95 struct gpio_desc *gpiochip_get_desc(struct gpio_chip *chip,
96                                     u16 hwnum)
97 {
98         if (hwnum >= chip->ngpio)
99                 return ERR_PTR(-EINVAL);
100
101         return &chip->desc[hwnum];
102 }
103
104 /**
105  * Convert a GPIO descriptor to the integer namespace.
106  * This should disappear in the future but is needed since we still
107  * use GPIO numbers for error messages and sysfs nodes
108  */
109 int desc_to_gpio(const struct gpio_desc *desc)
110 {
111         return desc->chip->base + (desc - &desc->chip->desc[0]);
112 }
113 EXPORT_SYMBOL_GPL(desc_to_gpio);
114
115
116 /**
117  * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
118  * @desc:       descriptor to return the chip of
119  */
120 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
121 {
122         return desc ? desc->chip : NULL;
123 }
124 EXPORT_SYMBOL_GPL(gpiod_to_chip);
125
126 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
127 static int gpiochip_find_base(int ngpio)
128 {
129         struct gpio_chip *chip;
130         int base = ARCH_NR_GPIOS - ngpio;
131
132         list_for_each_entry_reverse(chip, &gpio_chips, list) {
133                 /* found a free space? */
134                 if (chip->base + chip->ngpio <= base)
135                         break;
136                 else
137                         /* nope, check the space right before the chip */
138                         base = chip->base - ngpio;
139         }
140
141         if (gpio_is_valid(base)) {
142                 pr_debug("%s: found new base at %d\n", __func__, base);
143                 return base;
144         } else {
145                 pr_err("%s: cannot find free range\n", __func__);
146                 return -ENOSPC;
147         }
148 }
149
150 /**
151  * gpiod_get_direction - return the current direction of a GPIO
152  * @desc:       GPIO to get the direction of
153  *
154  * Return GPIOF_DIR_IN or GPIOF_DIR_OUT, or an error code in case of error.
155  *
156  * This function may sleep if gpiod_cansleep() is true.
157  */
158 int gpiod_get_direction(struct gpio_desc *desc)
159 {
160         struct gpio_chip        *chip;
161         unsigned                offset;
162         int                     status = -EINVAL;
163
164         chip = gpiod_to_chip(desc);
165         offset = gpio_chip_hwgpio(desc);
166
167         if (!chip->get_direction)
168                 return status;
169
170         status = chip->get_direction(chip, offset);
171         if (status > 0) {
172                 /* GPIOF_DIR_IN, or other positive */
173                 status = 1;
174                 clear_bit(FLAG_IS_OUT, &desc->flags);
175         }
176         if (status == 0) {
177                 /* GPIOF_DIR_OUT */
178                 set_bit(FLAG_IS_OUT, &desc->flags);
179         }
180         return status;
181 }
182 EXPORT_SYMBOL_GPL(gpiod_get_direction);
183
184 /*
185  * Add a new chip to the global chips list, keeping the list of chips sorted
186  * by base order.
187  *
188  * Return -EBUSY if the new chip overlaps with some other chip's integer
189  * space.
190  */
191 static int gpiochip_add_to_list(struct gpio_chip *chip)
192 {
193         struct list_head *pos;
194         struct gpio_chip *_chip;
195         int err = 0;
196
197         /* find where to insert our chip */
198         list_for_each(pos, &gpio_chips) {
199                 _chip = list_entry(pos, struct gpio_chip, list);
200                 /* shall we insert before _chip? */
201                 if (_chip->base >= chip->base + chip->ngpio)
202                         break;
203         }
204
205         /* are we stepping on the chip right before? */
206         if (pos != &gpio_chips && pos->prev != &gpio_chips) {
207                 _chip = list_entry(pos->prev, struct gpio_chip, list);
208                 if (_chip->base + _chip->ngpio > chip->base) {
209                         dev_err(chip->dev,
210                                "GPIO integer space overlap, cannot add chip\n");
211                         err = -EBUSY;
212                 }
213         }
214
215         if (!err)
216                 list_add_tail(&chip->list, pos);
217
218         return err;
219 }
220
221 /**
222  * gpiochip_add() - register a gpio_chip
223  * @chip: the chip to register, with chip->base initialized
224  * Context: potentially before irqs will work
225  *
226  * Returns a negative errno if the chip can't be registered, such as
227  * because the chip->base is invalid or already associated with a
228  * different chip.  Otherwise it returns zero as a success code.
229  *
230  * When gpiochip_add() is called very early during boot, so that GPIOs
231  * can be freely used, the chip->dev device must be registered before
232  * the gpio framework's arch_initcall().  Otherwise sysfs initialization
233  * for GPIOs will fail rudely.
234  *
235  * If chip->base is negative, this requests dynamic assignment of
236  * a range of valid GPIOs.
237  */
238 int gpiochip_add(struct gpio_chip *chip)
239 {
240         unsigned long   flags;
241         int             status = 0;
242         unsigned        id;
243         int             base = chip->base;
244         struct gpio_desc *descs;
245
246         descs = kcalloc(chip->ngpio, sizeof(descs[0]), GFP_KERNEL);
247         if (!descs)
248                 return -ENOMEM;
249
250         spin_lock_irqsave(&gpio_lock, flags);
251
252         if (base < 0) {
253                 base = gpiochip_find_base(chip->ngpio);
254                 if (base < 0) {
255                         status = base;
256                         spin_unlock_irqrestore(&gpio_lock, flags);
257                         goto err_free_descs;
258                 }
259                 chip->base = base;
260         }
261
262         status = gpiochip_add_to_list(chip);
263         if (status) {
264                 spin_unlock_irqrestore(&gpio_lock, flags);
265                 goto err_free_descs;
266         }
267
268         for (id = 0; id < chip->ngpio; id++) {
269                 struct gpio_desc *desc = &descs[id];
270
271                 desc->chip = chip;
272
273                 /* REVISIT: most hardware initializes GPIOs as inputs (often
274                  * with pullups enabled) so power usage is minimized. Linux
275                  * code should set the gpio direction first thing; but until
276                  * it does, and in case chip->get_direction is not set, we may
277                  * expose the wrong direction in sysfs.
278                  */
279                 desc->flags = !chip->direction_input ? (1 << FLAG_IS_OUT) : 0;
280         }
281
282         chip->desc = descs;
283
284         spin_unlock_irqrestore(&gpio_lock, flags);
285
286 #ifdef CONFIG_PINCTRL
287         INIT_LIST_HEAD(&chip->pin_ranges);
288 #endif
289
290         if (!chip->owner && chip->dev && chip->dev->driver)
291                 chip->owner = chip->dev->driver->owner;
292
293         of_gpiochip_add(chip);
294         acpi_gpiochip_add(chip);
295
296         status = gpiochip_sysfs_register(chip);
297         if (status)
298                 goto err_remove_chip;
299
300         pr_debug("%s: registered GPIOs %d to %d on device: %s\n", __func__,
301                 chip->base, chip->base + chip->ngpio - 1,
302                 chip->label ? : "generic");
303
304         return 0;
305
306 err_remove_chip:
307         acpi_gpiochip_remove(chip);
308         gpiochip_free_hogs(chip);
309         of_gpiochip_remove(chip);
310         spin_lock_irqsave(&gpio_lock, flags);
311         list_del(&chip->list);
312         spin_unlock_irqrestore(&gpio_lock, flags);
313         chip->desc = NULL;
314 err_free_descs:
315         kfree(descs);
316
317         /* failures here can mean systems won't boot... */
318         pr_err("%s: GPIOs %d..%d (%s) failed to register\n", __func__,
319                 chip->base, chip->base + chip->ngpio - 1,
320                 chip->label ? : "generic");
321         return status;
322 }
323 EXPORT_SYMBOL_GPL(gpiochip_add);
324
325 /**
326  * gpiochip_remove() - unregister a gpio_chip
327  * @chip: the chip to unregister
328  *
329  * A gpio_chip with any GPIOs still requested may not be removed.
330  */
331 void gpiochip_remove(struct gpio_chip *chip)
332 {
333         struct gpio_desc *desc;
334         unsigned long   flags;
335         unsigned        id;
336         bool            requested = false;
337
338         gpiochip_sysfs_unregister(chip);
339
340         gpiochip_irqchip_remove(chip);
341
342         acpi_gpiochip_remove(chip);
343         gpiochip_remove_pin_ranges(chip);
344         gpiochip_free_hogs(chip);
345         of_gpiochip_remove(chip);
346
347         spin_lock_irqsave(&gpio_lock, flags);
348         for (id = 0; id < chip->ngpio; id++) {
349                 desc = &chip->desc[id];
350                 desc->chip = NULL;
351                 if (test_bit(FLAG_REQUESTED, &desc->flags))
352                         requested = true;
353         }
354         list_del(&chip->list);
355         spin_unlock_irqrestore(&gpio_lock, flags);
356
357         if (requested)
358                 dev_crit(chip->dev, "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
359
360         kfree(chip->desc);
361         chip->desc = NULL;
362 }
363 EXPORT_SYMBOL_GPL(gpiochip_remove);
364
365 /**
366  * gpiochip_find() - iterator for locating a specific gpio_chip
367  * @data: data to pass to match function
368  * @callback: Callback function to check gpio_chip
369  *
370  * Similar to bus_find_device.  It returns a reference to a gpio_chip as
371  * determined by a user supplied @match callback.  The callback should return
372  * 0 if the device doesn't match and non-zero if it does.  If the callback is
373  * non-zero, this function will return to the caller and not iterate over any
374  * more gpio_chips.
375  */
376 struct gpio_chip *gpiochip_find(void *data,
377                                 int (*match)(struct gpio_chip *chip,
378                                              void *data))
379 {
380         struct gpio_chip *chip;
381         unsigned long flags;
382
383         spin_lock_irqsave(&gpio_lock, flags);
384         list_for_each_entry(chip, &gpio_chips, list)
385                 if (match(chip, data))
386                         break;
387
388         /* No match? */
389         if (&chip->list == &gpio_chips)
390                 chip = NULL;
391         spin_unlock_irqrestore(&gpio_lock, flags);
392
393         return chip;
394 }
395 EXPORT_SYMBOL_GPL(gpiochip_find);
396
397 static int gpiochip_match_name(struct gpio_chip *chip, void *data)
398 {
399         const char *name = data;
400
401         return !strcmp(chip->label, name);
402 }
403
404 static struct gpio_chip *find_chip_by_name(const char *name)
405 {
406         return gpiochip_find((void *)name, gpiochip_match_name);
407 }
408
409 #ifdef CONFIG_GPIOLIB_IRQCHIP
410
411 /*
412  * The following is irqchip helper code for gpiochips.
413  */
414
415 /**
416  * gpiochip_set_chained_irqchip() - sets a chained irqchip to a gpiochip
417  * @gpiochip: the gpiochip to set the irqchip chain to
418  * @irqchip: the irqchip to chain to the gpiochip
419  * @parent_irq: the irq number corresponding to the parent IRQ for this
420  * chained irqchip
421  * @parent_handler: the parent interrupt handler for the accumulated IRQ
422  * coming out of the gpiochip. If the interrupt is nested rather than
423  * cascaded, pass NULL in this handler argument
424  */
425 void gpiochip_set_chained_irqchip(struct gpio_chip *gpiochip,
426                                   struct irq_chip *irqchip,
427                                   int parent_irq,
428                                   irq_flow_handler_t parent_handler)
429 {
430         unsigned int offset;
431
432         if (!gpiochip->irqdomain) {
433                 chip_err(gpiochip, "called %s before setting up irqchip\n",
434                          __func__);
435                 return;
436         }
437
438         if (parent_handler) {
439                 if (gpiochip->can_sleep) {
440                         chip_err(gpiochip,
441                                  "you cannot have chained interrupts on a "
442                                  "chip that may sleep\n");
443                         return;
444                 }
445                 /*
446                  * The parent irqchip is already using the chip_data for this
447                  * irqchip, so our callbacks simply use the handler_data.
448                  */
449                 irq_set_chained_handler_and_data(parent_irq, parent_handler,
450                                                  gpiochip);
451
452                 gpiochip->irq_parent = parent_irq;
453         }
454
455         /* Set the parent IRQ for all affected IRQs */
456         for (offset = 0; offset < gpiochip->ngpio; offset++)
457                 irq_set_parent(irq_find_mapping(gpiochip->irqdomain, offset),
458                                parent_irq);
459 }
460 EXPORT_SYMBOL_GPL(gpiochip_set_chained_irqchip);
461
462 /*
463  * This lock class tells lockdep that GPIO irqs are in a different
464  * category than their parents, so it won't report false recursion.
465  */
466 static struct lock_class_key gpiochip_irq_lock_class;
467
468 /**
469  * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
470  * @d: the irqdomain used by this irqchip
471  * @irq: the global irq number used by this GPIO irqchip irq
472  * @hwirq: the local IRQ/GPIO line offset on this gpiochip
473  *
474  * This function will set up the mapping for a certain IRQ line on a
475  * gpiochip by assigning the gpiochip as chip data, and using the irqchip
476  * stored inside the gpiochip.
477  */
478 static int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
479                             irq_hw_number_t hwirq)
480 {
481         struct gpio_chip *chip = d->host_data;
482
483         irq_set_chip_data(irq, chip);
484         irq_set_lockdep_class(irq, &gpiochip_irq_lock_class);
485         irq_set_chip_and_handler(irq, chip->irqchip, chip->irq_handler);
486         /* Chips that can sleep need nested thread handlers */
487         if (chip->can_sleep && !chip->irq_not_threaded)
488                 irq_set_nested_thread(irq, 1);
489         irq_set_noprobe(irq);
490
491         /*
492          * No set-up of the hardware will happen if IRQ_TYPE_NONE
493          * is passed as default type.
494          */
495         if (chip->irq_default_type != IRQ_TYPE_NONE)
496                 irq_set_irq_type(irq, chip->irq_default_type);
497
498         return 0;
499 }
500
501 static void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
502 {
503         struct gpio_chip *chip = d->host_data;
504
505         if (chip->can_sleep)
506                 irq_set_nested_thread(irq, 0);
507         irq_set_chip_and_handler(irq, NULL, NULL);
508         irq_set_chip_data(irq, NULL);
509 }
510
511 static const struct irq_domain_ops gpiochip_domain_ops = {
512         .map    = gpiochip_irq_map,
513         .unmap  = gpiochip_irq_unmap,
514         /* Virtually all GPIO irqchips are twocell:ed */
515         .xlate  = irq_domain_xlate_twocell,
516 };
517
518 static int gpiochip_irq_reqres(struct irq_data *d)
519 {
520         struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
521
522         if (!try_module_get(chip->owner))
523                 return -ENODEV;
524
525         if (gpiochip_lock_as_irq(chip, d->hwirq)) {
526                 chip_err(chip,
527                         "unable to lock HW IRQ %lu for IRQ\n",
528                         d->hwirq);
529                 module_put(chip->owner);
530                 return -EINVAL;
531         }
532         return 0;
533 }
534
535 static void gpiochip_irq_relres(struct irq_data *d)
536 {
537         struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
538
539         gpiochip_unlock_as_irq(chip, d->hwirq);
540         module_put(chip->owner);
541 }
542
543 static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset)
544 {
545         return irq_find_mapping(chip->irqdomain, offset);
546 }
547
548 /**
549  * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
550  * @gpiochip: the gpiochip to remove the irqchip from
551  *
552  * This is called only from gpiochip_remove()
553  */
554 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip)
555 {
556         unsigned int offset;
557
558         acpi_gpiochip_free_interrupts(gpiochip);
559
560         if (gpiochip->irq_parent) {
561                 irq_set_chained_handler(gpiochip->irq_parent, NULL);
562                 irq_set_handler_data(gpiochip->irq_parent, NULL);
563         }
564
565         /* Remove all IRQ mappings and delete the domain */
566         if (gpiochip->irqdomain) {
567                 for (offset = 0; offset < gpiochip->ngpio; offset++)
568                         irq_dispose_mapping(
569                                 irq_find_mapping(gpiochip->irqdomain, offset));
570                 irq_domain_remove(gpiochip->irqdomain);
571         }
572
573         if (gpiochip->irqchip) {
574                 gpiochip->irqchip->irq_request_resources = NULL;
575                 gpiochip->irqchip->irq_release_resources = NULL;
576                 gpiochip->irqchip = NULL;
577         }
578 }
579
580 /**
581  * gpiochip_irqchip_add() - adds an irqchip to a gpiochip
582  * @gpiochip: the gpiochip to add the irqchip to
583  * @irqchip: the irqchip to add to the gpiochip
584  * @first_irq: if not dynamically assigned, the base (first) IRQ to
585  * allocate gpiochip irqs from
586  * @handler: the irq handler to use (often a predefined irq core function)
587  * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
588  * to have the core avoid setting up any default type in the hardware.
589  *
590  * This function closely associates a certain irqchip with a certain
591  * gpiochip, providing an irq domain to translate the local IRQs to
592  * global irqs in the gpiolib core, and making sure that the gpiochip
593  * is passed as chip data to all related functions. Driver callbacks
594  * need to use container_of() to get their local state containers back
595  * from the gpiochip passed as chip data. An irqdomain will be stored
596  * in the gpiochip that shall be used by the driver to handle IRQ number
597  * translation. The gpiochip will need to be initialized and registered
598  * before calling this function.
599  *
600  * This function will handle two cell:ed simple IRQs and assumes all
601  * the pins on the gpiochip can generate a unique IRQ. Everything else
602  * need to be open coded.
603  */
604 int gpiochip_irqchip_add(struct gpio_chip *gpiochip,
605                          struct irq_chip *irqchip,
606                          unsigned int first_irq,
607                          irq_flow_handler_t handler,
608                          unsigned int type)
609 {
610         struct device_node *of_node;
611         unsigned int offset;
612         unsigned irq_base = 0;
613
614         if (!gpiochip || !irqchip)
615                 return -EINVAL;
616
617         if (!gpiochip->dev) {
618                 pr_err("missing gpiochip .dev parent pointer\n");
619                 return -EINVAL;
620         }
621         of_node = gpiochip->dev->of_node;
622 #ifdef CONFIG_OF_GPIO
623         /*
624          * If the gpiochip has an assigned OF node this takes precedence
625          * FIXME: get rid of this and use gpiochip->dev->of_node everywhere
626          */
627         if (gpiochip->of_node)
628                 of_node = gpiochip->of_node;
629 #endif
630         gpiochip->irqchip = irqchip;
631         gpiochip->irq_handler = handler;
632         gpiochip->irq_default_type = type;
633         gpiochip->to_irq = gpiochip_to_irq;
634         gpiochip->irqdomain = irq_domain_add_simple(of_node,
635                                         gpiochip->ngpio, first_irq,
636                                         &gpiochip_domain_ops, gpiochip);
637         if (!gpiochip->irqdomain) {
638                 gpiochip->irqchip = NULL;
639                 return -EINVAL;
640         }
641         irqchip->irq_request_resources = gpiochip_irq_reqres;
642         irqchip->irq_release_resources = gpiochip_irq_relres;
643
644         /*
645          * Prepare the mapping since the irqchip shall be orthogonal to
646          * any gpiochip calls. If the first_irq was zero, this is
647          * necessary to allocate descriptors for all IRQs.
648          */
649         for (offset = 0; offset < gpiochip->ngpio; offset++) {
650                 irq_base = irq_create_mapping(gpiochip->irqdomain, offset);
651                 if (offset == 0)
652                         /*
653                          * Store the base into the gpiochip to be used when
654                          * unmapping the irqs.
655                          */
656                         gpiochip->irq_base = irq_base;
657         }
658
659         acpi_gpiochip_request_interrupts(gpiochip);
660
661         return 0;
662 }
663 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add);
664
665 #else /* CONFIG_GPIOLIB_IRQCHIP */
666
667 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {}
668
669 #endif /* CONFIG_GPIOLIB_IRQCHIP */
670
671 #ifdef CONFIG_PINCTRL
672
673 /**
674  * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
675  * @chip: the gpiochip to add the range for
676  * @pctldev: the pin controller to map to
677  * @gpio_offset: the start offset in the current gpio_chip number space
678  * @pin_group: name of the pin group inside the pin controller
679  */
680 int gpiochip_add_pingroup_range(struct gpio_chip *chip,
681                         struct pinctrl_dev *pctldev,
682                         unsigned int gpio_offset, const char *pin_group)
683 {
684         struct gpio_pin_range *pin_range;
685         int ret;
686
687         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
688         if (!pin_range) {
689                 chip_err(chip, "failed to allocate pin ranges\n");
690                 return -ENOMEM;
691         }
692
693         /* Use local offset as range ID */
694         pin_range->range.id = gpio_offset;
695         pin_range->range.gc = chip;
696         pin_range->range.name = chip->label;
697         pin_range->range.base = chip->base + gpio_offset;
698         pin_range->pctldev = pctldev;
699
700         ret = pinctrl_get_group_pins(pctldev, pin_group,
701                                         &pin_range->range.pins,
702                                         &pin_range->range.npins);
703         if (ret < 0) {
704                 kfree(pin_range);
705                 return ret;
706         }
707
708         pinctrl_add_gpio_range(pctldev, &pin_range->range);
709
710         chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n",
711                  gpio_offset, gpio_offset + pin_range->range.npins - 1,
712                  pinctrl_dev_get_devname(pctldev), pin_group);
713
714         list_add_tail(&pin_range->node, &chip->pin_ranges);
715
716         return 0;
717 }
718 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
719
720 /**
721  * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
722  * @chip: the gpiochip to add the range for
723  * @pinctrl_name: the dev_name() of the pin controller to map to
724  * @gpio_offset: the start offset in the current gpio_chip number space
725  * @pin_offset: the start offset in the pin controller number space
726  * @npins: the number of pins from the offset of each pin space (GPIO and
727  *      pin controller) to accumulate in this range
728  */
729 int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
730                            unsigned int gpio_offset, unsigned int pin_offset,
731                            unsigned int npins)
732 {
733         struct gpio_pin_range *pin_range;
734         int ret;
735
736         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
737         if (!pin_range) {
738                 chip_err(chip, "failed to allocate pin ranges\n");
739                 return -ENOMEM;
740         }
741
742         /* Use local offset as range ID */
743         pin_range->range.id = gpio_offset;
744         pin_range->range.gc = chip;
745         pin_range->range.name = chip->label;
746         pin_range->range.base = chip->base + gpio_offset;
747         pin_range->range.pin_base = pin_offset;
748         pin_range->range.npins = npins;
749         pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
750                         &pin_range->range);
751         if (IS_ERR(pin_range->pctldev)) {
752                 ret = PTR_ERR(pin_range->pctldev);
753                 chip_err(chip, "could not create pin range\n");
754                 kfree(pin_range);
755                 return ret;
756         }
757         chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
758                  gpio_offset, gpio_offset + npins - 1,
759                  pinctl_name,
760                  pin_offset, pin_offset + npins - 1);
761
762         list_add_tail(&pin_range->node, &chip->pin_ranges);
763
764         return 0;
765 }
766 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
767
768 /**
769  * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
770  * @chip: the chip to remove all the mappings for
771  */
772 void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
773 {
774         struct gpio_pin_range *pin_range, *tmp;
775
776         list_for_each_entry_safe(pin_range, tmp, &chip->pin_ranges, node) {
777                 list_del(&pin_range->node);
778                 pinctrl_remove_gpio_range(pin_range->pctldev,
779                                 &pin_range->range);
780                 kfree(pin_range);
781         }
782 }
783 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
784
785 #endif /* CONFIG_PINCTRL */
786
787 /* These "optional" allocation calls help prevent drivers from stomping
788  * on each other, and help provide better diagnostics in debugfs.
789  * They're called even less than the "set direction" calls.
790  */
791 static int __gpiod_request(struct gpio_desc *desc, const char *label)
792 {
793         struct gpio_chip        *chip = desc->chip;
794         int                     status;
795         unsigned long           flags;
796
797         spin_lock_irqsave(&gpio_lock, flags);
798
799         /* NOTE:  gpio_request() can be called in early boot,
800          * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
801          */
802
803         if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
804                 desc_set_label(desc, label ? : "?");
805                 status = 0;
806         } else {
807                 status = -EBUSY;
808                 goto done;
809         }
810
811         if (chip->request) {
812                 /* chip->request may sleep */
813                 spin_unlock_irqrestore(&gpio_lock, flags);
814                 status = chip->request(chip, gpio_chip_hwgpio(desc));
815                 spin_lock_irqsave(&gpio_lock, flags);
816
817                 if (status < 0) {
818                         desc_set_label(desc, NULL);
819                         clear_bit(FLAG_REQUESTED, &desc->flags);
820                         goto done;
821                 }
822         }
823         if (chip->get_direction) {
824                 /* chip->get_direction may sleep */
825                 spin_unlock_irqrestore(&gpio_lock, flags);
826                 gpiod_get_direction(desc);
827                 spin_lock_irqsave(&gpio_lock, flags);
828         }
829 done:
830         spin_unlock_irqrestore(&gpio_lock, flags);
831         return status;
832 }
833
834 int gpiod_request(struct gpio_desc *desc, const char *label)
835 {
836         int status = -EPROBE_DEFER;
837         struct gpio_chip *chip;
838
839         if (!desc) {
840                 pr_warn("%s: invalid GPIO\n", __func__);
841                 return -EINVAL;
842         }
843
844         chip = desc->chip;
845         if (!chip)
846                 goto done;
847
848         if (try_module_get(chip->owner)) {
849                 status = __gpiod_request(desc, label);
850                 if (status < 0)
851                         module_put(chip->owner);
852         }
853
854 done:
855         if (status)
856                 gpiod_dbg(desc, "%s: status %d\n", __func__, status);
857
858         return status;
859 }
860
861 static bool __gpiod_free(struct gpio_desc *desc)
862 {
863         bool                    ret = false;
864         unsigned long           flags;
865         struct gpio_chip        *chip;
866
867         might_sleep();
868
869         gpiod_unexport(desc);
870
871         spin_lock_irqsave(&gpio_lock, flags);
872
873         chip = desc->chip;
874         if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
875                 if (chip->free) {
876                         spin_unlock_irqrestore(&gpio_lock, flags);
877                         might_sleep_if(chip->can_sleep);
878                         chip->free(chip, gpio_chip_hwgpio(desc));
879                         spin_lock_irqsave(&gpio_lock, flags);
880                 }
881                 desc_set_label(desc, NULL);
882                 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
883                 clear_bit(FLAG_REQUESTED, &desc->flags);
884                 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
885                 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
886                 clear_bit(FLAG_IS_HOGGED, &desc->flags);
887                 ret = true;
888         }
889
890         spin_unlock_irqrestore(&gpio_lock, flags);
891         return ret;
892 }
893
894 void gpiod_free(struct gpio_desc *desc)
895 {
896         if (desc && __gpiod_free(desc))
897                 module_put(desc->chip->owner);
898         else
899                 WARN_ON(extra_checks);
900 }
901
902 /**
903  * gpiochip_is_requested - return string iff signal was requested
904  * @chip: controller managing the signal
905  * @offset: of signal within controller's 0..(ngpio - 1) range
906  *
907  * Returns NULL if the GPIO is not currently requested, else a string.
908  * The string returned is the label passed to gpio_request(); if none has been
909  * passed it is a meaningless, non-NULL constant.
910  *
911  * This function is for use by GPIO controller drivers.  The label can
912  * help with diagnostics, and knowing that the signal is used as a GPIO
913  * can help avoid accidentally multiplexing it to another controller.
914  */
915 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
916 {
917         struct gpio_desc *desc;
918
919         if (!GPIO_OFFSET_VALID(chip, offset))
920                 return NULL;
921
922         desc = &chip->desc[offset];
923
924         if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
925                 return NULL;
926         return desc->label;
927 }
928 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
929
930 /**
931  * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
932  * @desc: GPIO descriptor to request
933  * @label: label for the GPIO
934  *
935  * Function allows GPIO chip drivers to request and use their own GPIO
936  * descriptors via gpiolib API. Difference to gpiod_request() is that this
937  * function will not increase reference count of the GPIO chip module. This
938  * allows the GPIO chip module to be unloaded as needed (we assume that the
939  * GPIO chip driver handles freeing the GPIOs it has requested).
940  */
941 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *chip, u16 hwnum,
942                                             const char *label)
943 {
944         struct gpio_desc *desc = gpiochip_get_desc(chip, hwnum);
945         int err;
946
947         if (IS_ERR(desc)) {
948                 chip_err(chip, "failed to get GPIO descriptor\n");
949                 return desc;
950         }
951
952         err = __gpiod_request(desc, label);
953         if (err < 0)
954                 return ERR_PTR(err);
955
956         return desc;
957 }
958 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
959
960 /**
961  * gpiochip_free_own_desc - Free GPIO requested by the chip driver
962  * @desc: GPIO descriptor to free
963  *
964  * Function frees the given GPIO requested previously with
965  * gpiochip_request_own_desc().
966  */
967 void gpiochip_free_own_desc(struct gpio_desc *desc)
968 {
969         if (desc)
970                 __gpiod_free(desc);
971 }
972 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
973
974 /* Drivers MUST set GPIO direction before making get/set calls.  In
975  * some cases this is done in early boot, before IRQs are enabled.
976  *
977  * As a rule these aren't called more than once (except for drivers
978  * using the open-drain emulation idiom) so these are natural places
979  * to accumulate extra debugging checks.  Note that we can't (yet)
980  * rely on gpio_request() having been called beforehand.
981  */
982
983 /**
984  * gpiod_direction_input - set the GPIO direction to input
985  * @desc:       GPIO to set to input
986  *
987  * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
988  * be called safely on it.
989  *
990  * Return 0 in case of success, else an error code.
991  */
992 int gpiod_direction_input(struct gpio_desc *desc)
993 {
994         struct gpio_chip        *chip;
995         int                     status = -EINVAL;
996
997         if (!desc || !desc->chip) {
998                 pr_warn("%s: invalid GPIO\n", __func__);
999                 return -EINVAL;
1000         }
1001
1002         chip = desc->chip;
1003         if (!chip->get || !chip->direction_input) {
1004                 gpiod_warn(desc,
1005                         "%s: missing get() or direction_input() operations\n",
1006                         __func__);
1007                 return -EIO;
1008         }
1009
1010         status = chip->direction_input(chip, gpio_chip_hwgpio(desc));
1011         if (status == 0)
1012                 clear_bit(FLAG_IS_OUT, &desc->flags);
1013
1014         trace_gpio_direction(desc_to_gpio(desc), 1, status);
1015
1016         return status;
1017 }
1018 EXPORT_SYMBOL_GPL(gpiod_direction_input);
1019
1020 static int _gpiod_direction_output_raw(struct gpio_desc *desc, int value)
1021 {
1022         struct gpio_chip        *chip;
1023         int                     status = -EINVAL;
1024
1025         /* GPIOs used for IRQs shall not be set as output */
1026         if (test_bit(FLAG_USED_AS_IRQ, &desc->flags)) {
1027                 gpiod_err(desc,
1028                           "%s: tried to set a GPIO tied to an IRQ as output\n",
1029                           __func__);
1030                 return -EIO;
1031         }
1032
1033         /* Open drain pin should not be driven to 1 */
1034         if (value && test_bit(FLAG_OPEN_DRAIN,  &desc->flags))
1035                 return gpiod_direction_input(desc);
1036
1037         /* Open source pin should not be driven to 0 */
1038         if (!value && test_bit(FLAG_OPEN_SOURCE,  &desc->flags))
1039                 return gpiod_direction_input(desc);
1040
1041         chip = desc->chip;
1042         if (!chip->set || !chip->direction_output) {
1043                 gpiod_warn(desc,
1044                        "%s: missing set() or direction_output() operations\n",
1045                        __func__);
1046                 return -EIO;
1047         }
1048
1049         status = chip->direction_output(chip, gpio_chip_hwgpio(desc), value);
1050         if (status == 0)
1051                 set_bit(FLAG_IS_OUT, &desc->flags);
1052         trace_gpio_value(desc_to_gpio(desc), 0, value);
1053         trace_gpio_direction(desc_to_gpio(desc), 0, status);
1054         return status;
1055 }
1056
1057 /**
1058  * gpiod_direction_output_raw - set the GPIO direction to output
1059  * @desc:       GPIO to set to output
1060  * @value:      initial output value of the GPIO
1061  *
1062  * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
1063  * be called safely on it. The initial value of the output must be specified
1064  * as raw value on the physical line without regard for the ACTIVE_LOW status.
1065  *
1066  * Return 0 in case of success, else an error code.
1067  */
1068 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
1069 {
1070         if (!desc || !desc->chip) {
1071                 pr_warn("%s: invalid GPIO\n", __func__);
1072                 return -EINVAL;
1073         }
1074         return _gpiod_direction_output_raw(desc, value);
1075 }
1076 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
1077
1078 /**
1079  * gpiod_direction_output - set the GPIO direction to output
1080  * @desc:       GPIO to set to output
1081  * @value:      initial output value of the GPIO
1082  *
1083  * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
1084  * be called safely on it. The initial value of the output must be specified
1085  * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
1086  * account.
1087  *
1088  * Return 0 in case of success, else an error code.
1089  */
1090 int gpiod_direction_output(struct gpio_desc *desc, int value)
1091 {
1092         if (!desc || !desc->chip) {
1093                 pr_warn("%s: invalid GPIO\n", __func__);
1094                 return -EINVAL;
1095         }
1096         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1097                 value = !value;
1098         return _gpiod_direction_output_raw(desc, value);
1099 }
1100 EXPORT_SYMBOL_GPL(gpiod_direction_output);
1101
1102 /**
1103  * gpiod_set_debounce - sets @debounce time for a @gpio
1104  * @gpio: the gpio to set debounce time
1105  * @debounce: debounce time is microseconds
1106  *
1107  * returns -ENOTSUPP if the controller does not support setting
1108  * debounce.
1109  */
1110 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
1111 {
1112         struct gpio_chip        *chip;
1113
1114         if (!desc || !desc->chip) {
1115                 pr_warn("%s: invalid GPIO\n", __func__);
1116                 return -EINVAL;
1117         }
1118
1119         chip = desc->chip;
1120         if (!chip->set || !chip->set_debounce) {
1121                 gpiod_dbg(desc,
1122                           "%s: missing set() or set_debounce() operations\n",
1123                           __func__);
1124                 return -ENOTSUPP;
1125         }
1126
1127         return chip->set_debounce(chip, gpio_chip_hwgpio(desc), debounce);
1128 }
1129 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
1130
1131 /**
1132  * gpiod_is_active_low - test whether a GPIO is active-low or not
1133  * @desc: the gpio descriptor to test
1134  *
1135  * Returns 1 if the GPIO is active-low, 0 otherwise.
1136  */
1137 int gpiod_is_active_low(const struct gpio_desc *desc)
1138 {
1139         return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
1140 }
1141 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
1142
1143 /* I/O calls are only valid after configuration completed; the relevant
1144  * "is this a valid GPIO" error checks should already have been done.
1145  *
1146  * "Get" operations are often inlinable as reading a pin value register,
1147  * and masking the relevant bit in that register.
1148  *
1149  * When "set" operations are inlinable, they involve writing that mask to
1150  * one register to set a low value, or a different register to set it high.
1151  * Otherwise locking is needed, so there may be little value to inlining.
1152  *
1153  *------------------------------------------------------------------------
1154  *
1155  * IMPORTANT!!!  The hot paths -- get/set value -- assume that callers
1156  * have requested the GPIO.  That can include implicit requesting by
1157  * a direction setting call.  Marking a gpio as requested locks its chip
1158  * in memory, guaranteeing that these table lookups need no more locking
1159  * and that gpiochip_remove() will fail.
1160  *
1161  * REVISIT when debugging, consider adding some instrumentation to ensure
1162  * that the GPIO was actually requested.
1163  */
1164
1165 static bool _gpiod_get_raw_value(const struct gpio_desc *desc)
1166 {
1167         struct gpio_chip        *chip;
1168         bool value;
1169         int offset;
1170
1171         chip = desc->chip;
1172         offset = gpio_chip_hwgpio(desc);
1173         value = chip->get ? chip->get(chip, offset) : false;
1174         trace_gpio_value(desc_to_gpio(desc), 1, value);
1175         return value;
1176 }
1177
1178 /**
1179  * gpiod_get_raw_value() - return a gpio's raw value
1180  * @desc: gpio whose value will be returned
1181  *
1182  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
1183  * its ACTIVE_LOW status.
1184  *
1185  * This function should be called from contexts where we cannot sleep, and will
1186  * complain if the GPIO chip functions potentially sleep.
1187  */
1188 int gpiod_get_raw_value(const struct gpio_desc *desc)
1189 {
1190         if (!desc)
1191                 return 0;
1192         /* Should be using gpio_get_value_cansleep() */
1193         WARN_ON(desc->chip->can_sleep);
1194         return _gpiod_get_raw_value(desc);
1195 }
1196 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
1197
1198 /**
1199  * gpiod_get_value() - return a gpio's value
1200  * @desc: gpio whose value will be returned
1201  *
1202  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
1203  * account.
1204  *
1205  * This function should be called from contexts where we cannot sleep, and will
1206  * complain if the GPIO chip functions potentially sleep.
1207  */
1208 int gpiod_get_value(const struct gpio_desc *desc)
1209 {
1210         int value;
1211         if (!desc)
1212                 return 0;
1213         /* Should be using gpio_get_value_cansleep() */
1214         WARN_ON(desc->chip->can_sleep);
1215
1216         value = _gpiod_get_raw_value(desc);
1217         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1218                 value = !value;
1219
1220         return value;
1221 }
1222 EXPORT_SYMBOL_GPL(gpiod_get_value);
1223
1224 /*
1225  *  _gpio_set_open_drain_value() - Set the open drain gpio's value.
1226  * @desc: gpio descriptor whose state need to be set.
1227  * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
1228  */
1229 static void _gpio_set_open_drain_value(struct gpio_desc *desc, bool value)
1230 {
1231         int err = 0;
1232         struct gpio_chip *chip = desc->chip;
1233         int offset = gpio_chip_hwgpio(desc);
1234
1235         if (value) {
1236                 err = chip->direction_input(chip, offset);
1237                 if (!err)
1238                         clear_bit(FLAG_IS_OUT, &desc->flags);
1239         } else {
1240                 err = chip->direction_output(chip, offset, 0);
1241                 if (!err)
1242                         set_bit(FLAG_IS_OUT, &desc->flags);
1243         }
1244         trace_gpio_direction(desc_to_gpio(desc), value, err);
1245         if (err < 0)
1246                 gpiod_err(desc,
1247                           "%s: Error in set_value for open drain err %d\n",
1248                           __func__, err);
1249 }
1250
1251 /*
1252  *  _gpio_set_open_source_value() - Set the open source gpio's value.
1253  * @desc: gpio descriptor whose state need to be set.
1254  * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
1255  */
1256 static void _gpio_set_open_source_value(struct gpio_desc *desc, bool value)
1257 {
1258         int err = 0;
1259         struct gpio_chip *chip = desc->chip;
1260         int offset = gpio_chip_hwgpio(desc);
1261
1262         if (value) {
1263                 err = chip->direction_output(chip, offset, 1);
1264                 if (!err)
1265                         set_bit(FLAG_IS_OUT, &desc->flags);
1266         } else {
1267                 err = chip->direction_input(chip, offset);
1268                 if (!err)
1269                         clear_bit(FLAG_IS_OUT, &desc->flags);
1270         }
1271         trace_gpio_direction(desc_to_gpio(desc), !value, err);
1272         if (err < 0)
1273                 gpiod_err(desc,
1274                           "%s: Error in set_value for open source err %d\n",
1275                           __func__, err);
1276 }
1277
1278 static void _gpiod_set_raw_value(struct gpio_desc *desc, bool value)
1279 {
1280         struct gpio_chip        *chip;
1281
1282         chip = desc->chip;
1283         trace_gpio_value(desc_to_gpio(desc), 0, value);
1284         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
1285                 _gpio_set_open_drain_value(desc, value);
1286         else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
1287                 _gpio_set_open_source_value(desc, value);
1288         else
1289                 chip->set(chip, gpio_chip_hwgpio(desc), value);
1290 }
1291
1292 /*
1293  * set multiple outputs on the same chip;
1294  * use the chip's set_multiple function if available;
1295  * otherwise set the outputs sequentially;
1296  * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
1297  *        defines which outputs are to be changed
1298  * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
1299  *        defines the values the outputs specified by mask are to be set to
1300  */
1301 static void gpio_chip_set_multiple(struct gpio_chip *chip,
1302                                    unsigned long *mask, unsigned long *bits)
1303 {
1304         if (chip->set_multiple) {
1305                 chip->set_multiple(chip, mask, bits);
1306         } else {
1307                 int i;
1308                 for (i = 0; i < chip->ngpio; i++) {
1309                         if (mask[BIT_WORD(i)] == 0) {
1310                                 /* no more set bits in this mask word;
1311                                  * skip ahead to the next word */
1312                                 i = (BIT_WORD(i) + 1) * BITS_PER_LONG - 1;
1313                                 continue;
1314                         }
1315                         /* set outputs if the corresponding mask bit is set */
1316                         if (__test_and_clear_bit(i, mask))
1317                                 chip->set(chip, i, test_bit(i, bits));
1318                 }
1319         }
1320 }
1321
1322 static void gpiod_set_array_value_priv(bool raw, bool can_sleep,
1323                                        unsigned int array_size,
1324                                        struct gpio_desc **desc_array,
1325                                        int *value_array)
1326 {
1327         int i = 0;
1328
1329         while (i < array_size) {
1330                 struct gpio_chip *chip = desc_array[i]->chip;
1331                 unsigned long mask[BITS_TO_LONGS(chip->ngpio)];
1332                 unsigned long bits[BITS_TO_LONGS(chip->ngpio)];
1333                 int count = 0;
1334
1335                 if (!can_sleep)
1336                         WARN_ON(chip->can_sleep);
1337
1338                 memset(mask, 0, sizeof(mask));
1339                 do {
1340                         struct gpio_desc *desc = desc_array[i];
1341                         int hwgpio = gpio_chip_hwgpio(desc);
1342                         int value = value_array[i];
1343
1344                         if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1345                                 value = !value;
1346                         trace_gpio_value(desc_to_gpio(desc), 0, value);
1347                         /*
1348                          * collect all normal outputs belonging to the same chip
1349                          * open drain and open source outputs are set individually
1350                          */
1351                         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
1352                                 _gpio_set_open_drain_value(desc, value);
1353                         } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
1354                                 _gpio_set_open_source_value(desc, value);
1355                         } else {
1356                                 __set_bit(hwgpio, mask);
1357                                 if (value)
1358                                         __set_bit(hwgpio, bits);
1359                                 else
1360                                         __clear_bit(hwgpio, bits);
1361                                 count++;
1362                         }
1363                         i++;
1364                 } while ((i < array_size) && (desc_array[i]->chip == chip));
1365                 /* push collected bits to outputs */
1366                 if (count != 0)
1367                         gpio_chip_set_multiple(chip, mask, bits);
1368         }
1369 }
1370
1371 /**
1372  * gpiod_set_raw_value() - assign a gpio's raw value
1373  * @desc: gpio whose value will be assigned
1374  * @value: value to assign
1375  *
1376  * Set the raw value of the GPIO, i.e. the value of its physical line without
1377  * regard for its ACTIVE_LOW status.
1378  *
1379  * This function should be called from contexts where we cannot sleep, and will
1380  * complain if the GPIO chip functions potentially sleep.
1381  */
1382 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
1383 {
1384         if (!desc)
1385                 return;
1386         /* Should be using gpio_set_value_cansleep() */
1387         WARN_ON(desc->chip->can_sleep);
1388         _gpiod_set_raw_value(desc, value);
1389 }
1390 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
1391
1392 /**
1393  * gpiod_set_value() - assign a gpio's value
1394  * @desc: gpio whose value will be assigned
1395  * @value: value to assign
1396  *
1397  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
1398  * account
1399  *
1400  * This function should be called from contexts where we cannot sleep, and will
1401  * complain if the GPIO chip functions potentially sleep.
1402  */
1403 void gpiod_set_value(struct gpio_desc *desc, int value)
1404 {
1405         if (!desc)
1406                 return;
1407         /* Should be using gpio_set_value_cansleep() */
1408         WARN_ON(desc->chip->can_sleep);
1409         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1410                 value = !value;
1411         _gpiod_set_raw_value(desc, value);
1412 }
1413 EXPORT_SYMBOL_GPL(gpiod_set_value);
1414
1415 /**
1416  * gpiod_set_raw_array_value() - assign values to an array of GPIOs
1417  * @array_size: number of elements in the descriptor / value arrays
1418  * @desc_array: array of GPIO descriptors whose values will be assigned
1419  * @value_array: array of values to assign
1420  *
1421  * Set the raw values of the GPIOs, i.e. the values of the physical lines
1422  * without regard for their ACTIVE_LOW status.
1423  *
1424  * This function should be called from contexts where we cannot sleep, and will
1425  * complain if the GPIO chip functions potentially sleep.
1426  */
1427 void gpiod_set_raw_array_value(unsigned int array_size,
1428                          struct gpio_desc **desc_array, int *value_array)
1429 {
1430         if (!desc_array)
1431                 return;
1432         gpiod_set_array_value_priv(true, false, array_size, desc_array,
1433                                    value_array);
1434 }
1435 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
1436
1437 /**
1438  * gpiod_set_array_value() - assign values to an array of GPIOs
1439  * @array_size: number of elements in the descriptor / value arrays
1440  * @desc_array: array of GPIO descriptors whose values will be assigned
1441  * @value_array: array of values to assign
1442  *
1443  * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
1444  * into account.
1445  *
1446  * This function should be called from contexts where we cannot sleep, and will
1447  * complain if the GPIO chip functions potentially sleep.
1448  */
1449 void gpiod_set_array_value(unsigned int array_size,
1450                            struct gpio_desc **desc_array, int *value_array)
1451 {
1452         if (!desc_array)
1453                 return;
1454         gpiod_set_array_value_priv(false, false, array_size, desc_array,
1455                                    value_array);
1456 }
1457 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
1458
1459 /**
1460  * gpiod_cansleep() - report whether gpio value access may sleep
1461  * @desc: gpio to check
1462  *
1463  */
1464 int gpiod_cansleep(const struct gpio_desc *desc)
1465 {
1466         if (!desc)
1467                 return 0;
1468         return desc->chip->can_sleep;
1469 }
1470 EXPORT_SYMBOL_GPL(gpiod_cansleep);
1471
1472 /**
1473  * gpiod_to_irq() - return the IRQ corresponding to a GPIO
1474  * @desc: gpio whose IRQ will be returned (already requested)
1475  *
1476  * Return the IRQ corresponding to the passed GPIO, or an error code in case of
1477  * error.
1478  */
1479 int gpiod_to_irq(const struct gpio_desc *desc)
1480 {
1481         struct gpio_chip        *chip;
1482         int                     offset;
1483
1484         if (!desc)
1485                 return -EINVAL;
1486         chip = desc->chip;
1487         offset = gpio_chip_hwgpio(desc);
1488         return chip->to_irq ? chip->to_irq(chip, offset) : -ENXIO;
1489 }
1490 EXPORT_SYMBOL_GPL(gpiod_to_irq);
1491
1492 /**
1493  * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
1494  * @chip: the chip the GPIO to lock belongs to
1495  * @offset: the offset of the GPIO to lock as IRQ
1496  *
1497  * This is used directly by GPIO drivers that want to lock down
1498  * a certain GPIO line to be used for IRQs.
1499  */
1500 int gpiochip_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
1501 {
1502         if (offset >= chip->ngpio)
1503                 return -EINVAL;
1504
1505         if (test_bit(FLAG_IS_OUT, &chip->desc[offset].flags)) {
1506                 chip_err(chip,
1507                           "%s: tried to flag a GPIO set as output for IRQ\n",
1508                           __func__);
1509                 return -EIO;
1510         }
1511
1512         set_bit(FLAG_USED_AS_IRQ, &chip->desc[offset].flags);
1513         return 0;
1514 }
1515 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
1516
1517 /**
1518  * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
1519  * @chip: the chip the GPIO to lock belongs to
1520  * @offset: the offset of the GPIO to lock as IRQ
1521  *
1522  * This is used directly by GPIO drivers that want to indicate
1523  * that a certain GPIO is no longer used exclusively for IRQ.
1524  */
1525 void gpiochip_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
1526 {
1527         if (offset >= chip->ngpio)
1528                 return;
1529
1530         clear_bit(FLAG_USED_AS_IRQ, &chip->desc[offset].flags);
1531 }
1532 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
1533
1534 /**
1535  * gpiod_get_raw_value_cansleep() - return a gpio's raw value
1536  * @desc: gpio whose value will be returned
1537  *
1538  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
1539  * its ACTIVE_LOW status.
1540  *
1541  * This function is to be called from contexts that can sleep.
1542  */
1543 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
1544 {
1545         might_sleep_if(extra_checks);
1546         if (!desc)
1547                 return 0;
1548         return _gpiod_get_raw_value(desc);
1549 }
1550 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
1551
1552 /**
1553  * gpiod_get_value_cansleep() - return a gpio's value
1554  * @desc: gpio whose value will be returned
1555  *
1556  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
1557  * account.
1558  *
1559  * This function is to be called from contexts that can sleep.
1560  */
1561 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
1562 {
1563         int value;
1564
1565         might_sleep_if(extra_checks);
1566         if (!desc)
1567                 return 0;
1568
1569         value = _gpiod_get_raw_value(desc);
1570         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1571                 value = !value;
1572
1573         return value;
1574 }
1575 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
1576
1577 /**
1578  * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
1579  * @desc: gpio whose value will be assigned
1580  * @value: value to assign
1581  *
1582  * Set the raw value of the GPIO, i.e. the value of its physical line without
1583  * regard for its ACTIVE_LOW status.
1584  *
1585  * This function is to be called from contexts that can sleep.
1586  */
1587 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
1588 {
1589         might_sleep_if(extra_checks);
1590         if (!desc)
1591                 return;
1592         _gpiod_set_raw_value(desc, value);
1593 }
1594 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
1595
1596 /**
1597  * gpiod_set_value_cansleep() - assign a gpio's value
1598  * @desc: gpio whose value will be assigned
1599  * @value: value to assign
1600  *
1601  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
1602  * account
1603  *
1604  * This function is to be called from contexts that can sleep.
1605  */
1606 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
1607 {
1608         might_sleep_if(extra_checks);
1609         if (!desc)
1610                 return;
1611
1612         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1613                 value = !value;
1614         _gpiod_set_raw_value(desc, value);
1615 }
1616 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
1617
1618 /**
1619  * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
1620  * @array_size: number of elements in the descriptor / value arrays
1621  * @desc_array: array of GPIO descriptors whose values will be assigned
1622  * @value_array: array of values to assign
1623  *
1624  * Set the raw values of the GPIOs, i.e. the values of the physical lines
1625  * without regard for their ACTIVE_LOW status.
1626  *
1627  * This function is to be called from contexts that can sleep.
1628  */
1629 void gpiod_set_raw_array_value_cansleep(unsigned int array_size,
1630                                         struct gpio_desc **desc_array,
1631                                         int *value_array)
1632 {
1633         might_sleep_if(extra_checks);
1634         if (!desc_array)
1635                 return;
1636         gpiod_set_array_value_priv(true, true, array_size, desc_array,
1637                                    value_array);
1638 }
1639 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
1640
1641 /**
1642  * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
1643  * @array_size: number of elements in the descriptor / value arrays
1644  * @desc_array: array of GPIO descriptors whose values will be assigned
1645  * @value_array: array of values to assign
1646  *
1647  * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
1648  * into account.
1649  *
1650  * This function is to be called from contexts that can sleep.
1651  */
1652 void gpiod_set_array_value_cansleep(unsigned int array_size,
1653                                     struct gpio_desc **desc_array,
1654                                     int *value_array)
1655 {
1656         might_sleep_if(extra_checks);
1657         if (!desc_array)
1658                 return;
1659         gpiod_set_array_value_priv(false, true, array_size, desc_array,
1660                                    value_array);
1661 }
1662 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
1663
1664 /**
1665  * gpiod_add_lookup_table() - register GPIO device consumers
1666  * @table: table of consumers to register
1667  */
1668 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
1669 {
1670         mutex_lock(&gpio_lookup_lock);
1671
1672         list_add_tail(&table->list, &gpio_lookup_list);
1673
1674         mutex_unlock(&gpio_lookup_lock);
1675 }
1676
1677 static struct gpio_desc *of_find_gpio(struct device *dev, const char *con_id,
1678                                       unsigned int idx,
1679                                       enum gpio_lookup_flags *flags)
1680 {
1681         char prop_name[32]; /* 32 is max size of property name */
1682         enum of_gpio_flags of_flags;
1683         struct gpio_desc *desc;
1684         unsigned int i;
1685
1686         for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
1687                 if (con_id)
1688                         snprintf(prop_name, sizeof(prop_name), "%s-%s", con_id,
1689                                  gpio_suffixes[i]);
1690                 else
1691                         snprintf(prop_name, sizeof(prop_name), "%s",
1692                                  gpio_suffixes[i]);
1693
1694                 desc = of_get_named_gpiod_flags(dev->of_node, prop_name, idx,
1695                                                 &of_flags);
1696                 if (!IS_ERR(desc) || (PTR_ERR(desc) == -EPROBE_DEFER))
1697                         break;
1698         }
1699
1700         if (IS_ERR(desc))
1701                 return desc;
1702
1703         if (of_flags & OF_GPIO_ACTIVE_LOW)
1704                 *flags |= GPIO_ACTIVE_LOW;
1705
1706         return desc;
1707 }
1708
1709 static struct gpio_desc *acpi_find_gpio(struct device *dev, const char *con_id,
1710                                         unsigned int idx,
1711                                         enum gpio_lookup_flags *flags)
1712 {
1713         struct acpi_device *adev = ACPI_COMPANION(dev);
1714         struct acpi_gpio_info info;
1715         struct gpio_desc *desc;
1716         char propname[32];
1717         int i;
1718
1719         /* Try first from _DSD */
1720         for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
1721                 if (con_id && strcmp(con_id, "gpios")) {
1722                         snprintf(propname, sizeof(propname), "%s-%s",
1723                                  con_id, gpio_suffixes[i]);
1724                 } else {
1725                         snprintf(propname, sizeof(propname), "%s",
1726                                  gpio_suffixes[i]);
1727                 }
1728
1729                 desc = acpi_get_gpiod_by_index(adev, propname, idx, &info);
1730                 if (!IS_ERR(desc) || (PTR_ERR(desc) == -EPROBE_DEFER))
1731                         break;
1732         }
1733
1734         /* Then from plain _CRS GPIOs */
1735         if (IS_ERR(desc)) {
1736                 desc = acpi_get_gpiod_by_index(adev, NULL, idx, &info);
1737                 if (IS_ERR(desc))
1738                         return desc;
1739         }
1740
1741         if (info.active_low)
1742                 *flags |= GPIO_ACTIVE_LOW;
1743
1744         return desc;
1745 }
1746
1747 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
1748 {
1749         const char *dev_id = dev ? dev_name(dev) : NULL;
1750         struct gpiod_lookup_table *table;
1751
1752         mutex_lock(&gpio_lookup_lock);
1753
1754         list_for_each_entry(table, &gpio_lookup_list, list) {
1755                 if (table->dev_id && dev_id) {
1756                         /*
1757                          * Valid strings on both ends, must be identical to have
1758                          * a match
1759                          */
1760                         if (!strcmp(table->dev_id, dev_id))
1761                                 goto found;
1762                 } else {
1763                         /*
1764                          * One of the pointers is NULL, so both must be to have
1765                          * a match
1766                          */
1767                         if (dev_id == table->dev_id)
1768                                 goto found;
1769                 }
1770         }
1771         table = NULL;
1772
1773 found:
1774         mutex_unlock(&gpio_lookup_lock);
1775         return table;
1776 }
1777
1778 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
1779                                     unsigned int idx,
1780                                     enum gpio_lookup_flags *flags)
1781 {
1782         struct gpio_desc *desc = ERR_PTR(-ENOENT);
1783         struct gpiod_lookup_table *table;
1784         struct gpiod_lookup *p;
1785
1786         table = gpiod_find_lookup_table(dev);
1787         if (!table)
1788                 return desc;
1789
1790         for (p = &table->table[0]; p->chip_label; p++) {
1791                 struct gpio_chip *chip;
1792
1793                 /* idx must always match exactly */
1794                 if (p->idx != idx)
1795                         continue;
1796
1797                 /* If the lookup entry has a con_id, require exact match */
1798                 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
1799                         continue;
1800
1801                 chip = find_chip_by_name(p->chip_label);
1802
1803                 if (!chip) {
1804                         dev_err(dev, "cannot find GPIO chip %s\n",
1805                                 p->chip_label);
1806                         return ERR_PTR(-ENODEV);
1807                 }
1808
1809                 if (chip->ngpio <= p->chip_hwnum) {
1810                         dev_err(dev,
1811                                 "requested GPIO %d is out of range [0..%d] for chip %s\n",
1812                                 idx, chip->ngpio, chip->label);
1813                         return ERR_PTR(-EINVAL);
1814                 }
1815
1816                 desc = gpiochip_get_desc(chip, p->chip_hwnum);
1817                 *flags = p->flags;
1818
1819                 return desc;
1820         }
1821
1822         return desc;
1823 }
1824
1825 static int dt_gpio_count(struct device *dev, const char *con_id)
1826 {
1827         int ret;
1828         char propname[32];
1829         unsigned int i;
1830
1831         for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
1832                 if (con_id)
1833                         snprintf(propname, sizeof(propname), "%s-%s",
1834                                  con_id, gpio_suffixes[i]);
1835                 else
1836                         snprintf(propname, sizeof(propname), "%s",
1837                                  gpio_suffixes[i]);
1838
1839                 ret = of_gpio_named_count(dev->of_node, propname);
1840                 if (ret >= 0)
1841                         break;
1842         }
1843         return ret;
1844 }
1845
1846 static int platform_gpio_count(struct device *dev, const char *con_id)
1847 {
1848         struct gpiod_lookup_table *table;
1849         struct gpiod_lookup *p;
1850         unsigned int count = 0;
1851
1852         table = gpiod_find_lookup_table(dev);
1853         if (!table)
1854                 return -ENOENT;
1855
1856         for (p = &table->table[0]; p->chip_label; p++) {
1857                 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
1858                     (!con_id && !p->con_id))
1859                         count++;
1860         }
1861         if (!count)
1862                 return -ENOENT;
1863
1864         return count;
1865 }
1866
1867 /**
1868  * gpiod_count - return the number of GPIOs associated with a device / function
1869  *              or -ENOENT if no GPIO has been assigned to the requested function
1870  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
1871  * @con_id:     function within the GPIO consumer
1872  */
1873 int gpiod_count(struct device *dev, const char *con_id)
1874 {
1875         int count = -ENOENT;
1876
1877         if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
1878                 count = dt_gpio_count(dev, con_id);
1879         else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
1880                 count = acpi_gpio_count(dev, con_id);
1881
1882         if (count < 0)
1883                 count = platform_gpio_count(dev, con_id);
1884
1885         return count;
1886 }
1887 EXPORT_SYMBOL_GPL(gpiod_count);
1888
1889 /**
1890  * gpiod_get - obtain a GPIO for a given GPIO function
1891  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
1892  * @con_id:     function within the GPIO consumer
1893  * @flags:      optional GPIO initialization flags
1894  *
1895  * Return the GPIO descriptor corresponding to the function con_id of device
1896  * dev, -ENOENT if no GPIO has been assigned to the requested function, or
1897  * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
1898  */
1899 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
1900                                          enum gpiod_flags flags)
1901 {
1902         return gpiod_get_index(dev, con_id, 0, flags);
1903 }
1904 EXPORT_SYMBOL_GPL(gpiod_get);
1905
1906 /**
1907  * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
1908  * @dev: GPIO consumer, can be NULL for system-global GPIOs
1909  * @con_id: function within the GPIO consumer
1910  * @flags: optional GPIO initialization flags
1911  *
1912  * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
1913  * the requested function it will return NULL. This is convenient for drivers
1914  * that need to handle optional GPIOs.
1915  */
1916 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
1917                                                   const char *con_id,
1918                                                   enum gpiod_flags flags)
1919 {
1920         return gpiod_get_index_optional(dev, con_id, 0, flags);
1921 }
1922 EXPORT_SYMBOL_GPL(gpiod_get_optional);
1923
1924
1925 /**
1926  * gpiod_configure_flags - helper function to configure a given GPIO
1927  * @desc:       gpio whose value will be assigned
1928  * @con_id:     function within the GPIO consumer
1929  * @lflags:     gpio_lookup_flags - returned from of_find_gpio() or
1930  *              of_get_gpio_hog()
1931  * @dflags:     gpiod_flags - optional GPIO initialization flags
1932  *
1933  * Return 0 on success, -ENOENT if no GPIO has been assigned to the
1934  * requested function and/or index, or another IS_ERR() code if an error
1935  * occurred while trying to acquire the GPIO.
1936  */
1937 static int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
1938                 unsigned long lflags, enum gpiod_flags dflags)
1939 {
1940         int status;
1941
1942         if (lflags & GPIO_ACTIVE_LOW)
1943                 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
1944         if (lflags & GPIO_OPEN_DRAIN)
1945                 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
1946         if (lflags & GPIO_OPEN_SOURCE)
1947                 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
1948
1949         /* No particular flag request, return here... */
1950         if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
1951                 pr_debug("no flags found for %s\n", con_id);
1952                 return 0;
1953         }
1954
1955         /* Process flags */
1956         if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
1957                 status = gpiod_direction_output(desc,
1958                                               dflags & GPIOD_FLAGS_BIT_DIR_VAL);
1959         else
1960                 status = gpiod_direction_input(desc);
1961
1962         return status;
1963 }
1964
1965 /**
1966  * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
1967  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
1968  * @con_id:     function within the GPIO consumer
1969  * @idx:        index of the GPIO to obtain in the consumer
1970  * @flags:      optional GPIO initialization flags
1971  *
1972  * This variant of gpiod_get() allows to access GPIOs other than the first
1973  * defined one for functions that define several GPIOs.
1974  *
1975  * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
1976  * requested function and/or index, or another IS_ERR() code if an error
1977  * occurred while trying to acquire the GPIO.
1978  */
1979 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
1980                                                const char *con_id,
1981                                                unsigned int idx,
1982                                                enum gpiod_flags flags)
1983 {
1984         struct gpio_desc *desc = NULL;
1985         int status;
1986         enum gpio_lookup_flags lookupflags = 0;
1987
1988         dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
1989
1990         if (dev) {
1991                 /* Using device tree? */
1992                 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
1993                         dev_dbg(dev, "using device tree for GPIO lookup\n");
1994                         desc = of_find_gpio(dev, con_id, idx, &lookupflags);
1995                 } else if (ACPI_COMPANION(dev)) {
1996                         dev_dbg(dev, "using ACPI for GPIO lookup\n");
1997                         desc = acpi_find_gpio(dev, con_id, idx, &lookupflags);
1998                 }
1999         }
2000
2001         /*
2002          * Either we are not using DT or ACPI, or their lookup did not return
2003          * a result. In that case, use platform lookup as a fallback.
2004          */
2005         if (!desc || desc == ERR_PTR(-ENOENT)) {
2006                 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
2007                 desc = gpiod_find(dev, con_id, idx, &lookupflags);
2008         }
2009
2010         if (IS_ERR(desc)) {
2011                 dev_dbg(dev, "lookup for GPIO %s failed\n", con_id);
2012                 return desc;
2013         }
2014
2015         status = gpiod_request(desc, con_id);
2016         if (status < 0)
2017                 return ERR_PTR(status);
2018
2019         status = gpiod_configure_flags(desc, con_id, lookupflags, flags);
2020         if (status < 0) {
2021                 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
2022                 gpiod_put(desc);
2023                 return ERR_PTR(status);
2024         }
2025
2026         return desc;
2027 }
2028 EXPORT_SYMBOL_GPL(gpiod_get_index);
2029
2030 /**
2031  * fwnode_get_named_gpiod - obtain a GPIO from firmware node
2032  * @fwnode:     handle of the firmware node
2033  * @propname:   name of the firmware property representing the GPIO
2034  *
2035  * This function can be used for drivers that get their configuration
2036  * from firmware.
2037  *
2038  * Function properly finds the corresponding GPIO using whatever is the
2039  * underlying firmware interface and then makes sure that the GPIO
2040  * descriptor is requested before it is returned to the caller.
2041  *
2042  * In case of error an ERR_PTR() is returned.
2043  */
2044 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
2045                                          const char *propname)
2046 {
2047         struct gpio_desc *desc = ERR_PTR(-ENODEV);
2048         bool active_low = false;
2049         int ret;
2050
2051         if (!fwnode)
2052                 return ERR_PTR(-EINVAL);
2053
2054         if (is_of_node(fwnode)) {
2055                 enum of_gpio_flags flags;
2056
2057                 desc = of_get_named_gpiod_flags(to_of_node(fwnode), propname, 0,
2058                                                 &flags);
2059                 if (!IS_ERR(desc))
2060                         active_low = flags & OF_GPIO_ACTIVE_LOW;
2061         } else if (is_acpi_node(fwnode)) {
2062                 struct acpi_gpio_info info;
2063
2064                 desc = acpi_get_gpiod_by_index(to_acpi_node(fwnode), propname, 0,
2065                                                &info);
2066                 if (!IS_ERR(desc))
2067                         active_low = info.active_low;
2068         }
2069
2070         if (IS_ERR(desc))
2071                 return desc;
2072
2073         ret = gpiod_request(desc, NULL);
2074         if (ret)
2075                 return ERR_PTR(ret);
2076
2077         /* Only value flag can be set from both DT and ACPI is active_low */
2078         if (active_low)
2079                 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
2080
2081         return desc;
2082 }
2083 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
2084
2085 /**
2086  * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
2087  *                            function
2088  * @dev: GPIO consumer, can be NULL for system-global GPIOs
2089  * @con_id: function within the GPIO consumer
2090  * @index: index of the GPIO to obtain in the consumer
2091  * @flags: optional GPIO initialization flags
2092  *
2093  * This is equivalent to gpiod_get_index(), except that when no GPIO with the
2094  * specified index was assigned to the requested function it will return NULL.
2095  * This is convenient for drivers that need to handle optional GPIOs.
2096  */
2097 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
2098                                                         const char *con_id,
2099                                                         unsigned int index,
2100                                                         enum gpiod_flags flags)
2101 {
2102         struct gpio_desc *desc;
2103
2104         desc = gpiod_get_index(dev, con_id, index, flags);
2105         if (IS_ERR(desc)) {
2106                 if (PTR_ERR(desc) == -ENOENT)
2107                         return NULL;
2108         }
2109
2110         return desc;
2111 }
2112 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
2113
2114 /**
2115  * gpiod_hog - Hog the specified GPIO desc given the provided flags
2116  * @desc:       gpio whose value will be assigned
2117  * @name:       gpio line name
2118  * @lflags:     gpio_lookup_flags - returned from of_find_gpio() or
2119  *              of_get_gpio_hog()
2120  * @dflags:     gpiod_flags - optional GPIO initialization flags
2121  */
2122 int gpiod_hog(struct gpio_desc *desc, const char *name,
2123               unsigned long lflags, enum gpiod_flags dflags)
2124 {
2125         struct gpio_chip *chip;
2126         struct gpio_desc *local_desc;
2127         int hwnum;
2128         int status;
2129
2130         chip = gpiod_to_chip(desc);
2131         hwnum = gpio_chip_hwgpio(desc);
2132
2133         local_desc = gpiochip_request_own_desc(chip, hwnum, name);
2134         if (IS_ERR(local_desc)) {
2135                 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed\n",
2136                        name, chip->label, hwnum);
2137                 return PTR_ERR(local_desc);
2138         }
2139
2140         status = gpiod_configure_flags(desc, name, lflags, dflags);
2141         if (status < 0) {
2142                 pr_err("setup of hog GPIO %s (chip %s, offset %d) failed\n",
2143                        name, chip->label, hwnum);
2144                 gpiochip_free_own_desc(desc);
2145                 return status;
2146         }
2147
2148         /* Mark GPIO as hogged so it can be identified and removed later */
2149         set_bit(FLAG_IS_HOGGED, &desc->flags);
2150
2151         pr_info("GPIO line %d (%s) hogged as %s%s\n",
2152                 desc_to_gpio(desc), name,
2153                 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
2154                 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ?
2155                   (dflags&GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low":"");
2156
2157         return 0;
2158 }
2159
2160 /**
2161  * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
2162  * @chip:       gpio chip to act on
2163  *
2164  * This is only used by of_gpiochip_remove to free hogged gpios
2165  */
2166 static void gpiochip_free_hogs(struct gpio_chip *chip)
2167 {
2168         int id;
2169
2170         for (id = 0; id < chip->ngpio; id++) {
2171                 if (test_bit(FLAG_IS_HOGGED, &chip->desc[id].flags))
2172                         gpiochip_free_own_desc(&chip->desc[id]);
2173         }
2174 }
2175
2176 /**
2177  * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
2178  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
2179  * @con_id:     function within the GPIO consumer
2180  * @flags:      optional GPIO initialization flags
2181  *
2182  * This function acquires all the GPIOs defined under a given function.
2183  *
2184  * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
2185  * no GPIO has been assigned to the requested function, or another IS_ERR()
2186  * code if an error occurred while trying to acquire the GPIOs.
2187  */
2188 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
2189                                                 const char *con_id,
2190                                                 enum gpiod_flags flags)
2191 {
2192         struct gpio_desc *desc;
2193         struct gpio_descs *descs;
2194         int count;
2195
2196         count = gpiod_count(dev, con_id);
2197         if (count < 0)
2198                 return ERR_PTR(count);
2199
2200         descs = kzalloc(sizeof(*descs) + sizeof(descs->desc[0]) * count,
2201                         GFP_KERNEL);
2202         if (!descs)
2203                 return ERR_PTR(-ENOMEM);
2204
2205         for (descs->ndescs = 0; descs->ndescs < count; ) {
2206                 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
2207                 if (IS_ERR(desc)) {
2208                         gpiod_put_array(descs);
2209                         return ERR_CAST(desc);
2210                 }
2211                 descs->desc[descs->ndescs] = desc;
2212                 descs->ndescs++;
2213         }
2214         return descs;
2215 }
2216 EXPORT_SYMBOL_GPL(gpiod_get_array);
2217
2218 /**
2219  * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
2220  *                            function
2221  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
2222  * @con_id:     function within the GPIO consumer
2223  * @flags:      optional GPIO initialization flags
2224  *
2225  * This is equivalent to gpiod_get_array(), except that when no GPIO was
2226  * assigned to the requested function it will return NULL.
2227  */
2228 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
2229                                                         const char *con_id,
2230                                                         enum gpiod_flags flags)
2231 {
2232         struct gpio_descs *descs;
2233
2234         descs = gpiod_get_array(dev, con_id, flags);
2235         if (IS_ERR(descs) && (PTR_ERR(descs) == -ENOENT))
2236                 return NULL;
2237
2238         return descs;
2239 }
2240 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
2241
2242 /**
2243  * gpiod_put - dispose of a GPIO descriptor
2244  * @desc:       GPIO descriptor to dispose of
2245  *
2246  * No descriptor can be used after gpiod_put() has been called on it.
2247  */
2248 void gpiod_put(struct gpio_desc *desc)
2249 {
2250         gpiod_free(desc);
2251 }
2252 EXPORT_SYMBOL_GPL(gpiod_put);
2253
2254 /**
2255  * gpiod_put_array - dispose of multiple GPIO descriptors
2256  * @descs:      struct gpio_descs containing an array of descriptors
2257  */
2258 void gpiod_put_array(struct gpio_descs *descs)
2259 {
2260         unsigned int i;
2261
2262         for (i = 0; i < descs->ndescs; i++)
2263                 gpiod_put(descs->desc[i]);
2264
2265         kfree(descs);
2266 }
2267 EXPORT_SYMBOL_GPL(gpiod_put_array);
2268
2269 #ifdef CONFIG_DEBUG_FS
2270
2271 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_chip *chip)
2272 {
2273         unsigned                i;
2274         unsigned                gpio = chip->base;
2275         struct gpio_desc        *gdesc = &chip->desc[0];
2276         int                     is_out;
2277         int                     is_irq;
2278
2279         for (i = 0; i < chip->ngpio; i++, gpio++, gdesc++) {
2280                 if (!test_bit(FLAG_REQUESTED, &gdesc->flags))
2281                         continue;
2282
2283                 gpiod_get_direction(gdesc);
2284                 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
2285                 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
2286                 seq_printf(s, " gpio-%-3d (%-20.20s) %s %s %s",
2287                         gpio, gdesc->label,
2288                         is_out ? "out" : "in ",
2289                         chip->get
2290                                 ? (chip->get(chip, i) ? "hi" : "lo")
2291                                 : "?  ",
2292                         is_irq ? "IRQ" : "   ");
2293                 seq_printf(s, "\n");
2294         }
2295 }
2296
2297 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
2298 {
2299         unsigned long flags;
2300         struct gpio_chip *chip = NULL;
2301         loff_t index = *pos;
2302
2303         s->private = "";
2304
2305         spin_lock_irqsave(&gpio_lock, flags);
2306         list_for_each_entry(chip, &gpio_chips, list)
2307                 if (index-- == 0) {
2308                         spin_unlock_irqrestore(&gpio_lock, flags);
2309                         return chip;
2310                 }
2311         spin_unlock_irqrestore(&gpio_lock, flags);
2312
2313         return NULL;
2314 }
2315
2316 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
2317 {
2318         unsigned long flags;
2319         struct gpio_chip *chip = v;
2320         void *ret = NULL;
2321
2322         spin_lock_irqsave(&gpio_lock, flags);
2323         if (list_is_last(&chip->list, &gpio_chips))
2324                 ret = NULL;
2325         else
2326                 ret = list_entry(chip->list.next, struct gpio_chip, list);
2327         spin_unlock_irqrestore(&gpio_lock, flags);
2328
2329         s->private = "\n";
2330         ++*pos;
2331
2332         return ret;
2333 }
2334
2335 static void gpiolib_seq_stop(struct seq_file *s, void *v)
2336 {
2337 }
2338
2339 static int gpiolib_seq_show(struct seq_file *s, void *v)
2340 {
2341         struct gpio_chip *chip = v;
2342         struct device *dev;
2343
2344         seq_printf(s, "%sGPIOs %d-%d", (char *)s->private,
2345                         chip->base, chip->base + chip->ngpio - 1);
2346         dev = chip->dev;
2347         if (dev)
2348                 seq_printf(s, ", %s/%s", dev->bus ? dev->bus->name : "no-bus",
2349                         dev_name(dev));
2350         if (chip->label)
2351                 seq_printf(s, ", %s", chip->label);
2352         if (chip->can_sleep)
2353                 seq_printf(s, ", can sleep");
2354         seq_printf(s, ":\n");
2355
2356         if (chip->dbg_show)
2357                 chip->dbg_show(s, chip);
2358         else
2359                 gpiolib_dbg_show(s, chip);
2360
2361         return 0;
2362 }
2363
2364 static const struct seq_operations gpiolib_seq_ops = {
2365         .start = gpiolib_seq_start,
2366         .next = gpiolib_seq_next,
2367         .stop = gpiolib_seq_stop,
2368         .show = gpiolib_seq_show,
2369 };
2370
2371 static int gpiolib_open(struct inode *inode, struct file *file)
2372 {
2373         return seq_open(file, &gpiolib_seq_ops);
2374 }
2375
2376 static const struct file_operations gpiolib_operations = {
2377         .owner          = THIS_MODULE,
2378         .open           = gpiolib_open,
2379         .read           = seq_read,
2380         .llseek         = seq_lseek,
2381         .release        = seq_release,
2382 };
2383
2384 static int __init gpiolib_debugfs_init(void)
2385 {
2386         /* /sys/kernel/debug/gpio */
2387         (void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
2388                                 NULL, NULL, &gpiolib_operations);
2389         return 0;
2390 }
2391 subsys_initcall(gpiolib_debugfs_init);
2392
2393 #endif  /* DEBUG_FS */