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