]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/gpio/gpiolib.c
gpio: move gpio_ensure_requested() into legacy C file
[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
18 #include "gpiolib.h"
19
20 #define CREATE_TRACE_POINTS
21 #include <trace/events/gpio.h>
22
23 /* Implementation infrastructure for GPIO interfaces.
24  *
25  * The GPIO programming interface allows for inlining speed-critical
26  * get/set operations for common cases, so that access to SOC-integrated
27  * GPIOs can sometimes cost only an instruction or two per bit.
28  */
29
30
31 /* When debugging, extend minimal trust to callers and platform code.
32  * Also emit diagnostic messages that may help initial bringup, when
33  * board setup or driver bugs are most common.
34  *
35  * Otherwise, minimize overhead in what may be bitbanging codepaths.
36  */
37 #ifdef  DEBUG
38 #define extra_checks    1
39 #else
40 #define extra_checks    0
41 #endif
42
43 /* gpio_lock prevents conflicts during gpio_desc[] table updates.
44  * While any GPIO is requested, its gpio_chip is not removable;
45  * each GPIO's "requested" flag serves as a lock and refcount.
46  */
47 DEFINE_SPINLOCK(gpio_lock);
48
49 static struct gpio_desc gpio_desc[ARCH_NR_GPIOS];
50
51 #define GPIO_OFFSET_VALID(chip, offset) (offset >= 0 && offset < chip->ngpio)
52
53 static DEFINE_MUTEX(gpio_lookup_lock);
54 static LIST_HEAD(gpio_lookup_list);
55 LIST_HEAD(gpio_chips);
56
57 static inline void desc_set_label(struct gpio_desc *d, const char *label)
58 {
59         d->label = label;
60 }
61
62 /**
63  * Convert a GPIO number to its descriptor
64  */
65 struct gpio_desc *gpio_to_desc(unsigned gpio)
66 {
67         if (WARN(!gpio_is_valid(gpio), "invalid GPIO %d\n", gpio))
68                 return NULL;
69         else
70                 return &gpio_desc[gpio];
71 }
72 EXPORT_SYMBOL_GPL(gpio_to_desc);
73
74 /**
75  * Get the GPIO descriptor corresponding to the given hw number for this chip.
76  */
77 struct gpio_desc *gpiochip_get_desc(struct gpio_chip *chip,
78                                     u16 hwnum)
79 {
80         if (hwnum >= chip->ngpio)
81                 return ERR_PTR(-EINVAL);
82
83         return &chip->desc[hwnum];
84 }
85
86 /**
87  * Convert a GPIO descriptor to the integer namespace.
88  * This should disappear in the future but is needed since we still
89  * use GPIO numbers for error messages and sysfs nodes
90  */
91 int desc_to_gpio(const struct gpio_desc *desc)
92 {
93         return desc - &gpio_desc[0];
94 }
95 EXPORT_SYMBOL_GPL(desc_to_gpio);
96
97
98 /**
99  * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
100  * @desc:       descriptor to return the chip of
101  */
102 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
103 {
104         return desc ? desc->chip : NULL;
105 }
106 EXPORT_SYMBOL_GPL(gpiod_to_chip);
107
108 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
109 static int gpiochip_find_base(int ngpio)
110 {
111         struct gpio_chip *chip;
112         int base = ARCH_NR_GPIOS - ngpio;
113
114         list_for_each_entry_reverse(chip, &gpio_chips, list) {
115                 /* found a free space? */
116                 if (chip->base + chip->ngpio <= base)
117                         break;
118                 else
119                         /* nope, check the space right before the chip */
120                         base = chip->base - ngpio;
121         }
122
123         if (gpio_is_valid(base)) {
124                 pr_debug("%s: found new base at %d\n", __func__, base);
125                 return base;
126         } else {
127                 pr_err("%s: cannot find free range\n", __func__);
128                 return -ENOSPC;
129         }
130 }
131
132 /**
133  * gpiod_get_direction - return the current direction of a GPIO
134  * @desc:       GPIO to get the direction of
135  *
136  * Return GPIOF_DIR_IN or GPIOF_DIR_OUT, or an error code in case of error.
137  *
138  * This function may sleep if gpiod_cansleep() is true.
139  */
140 int gpiod_get_direction(const struct gpio_desc *desc)
141 {
142         struct gpio_chip        *chip;
143         unsigned                offset;
144         int                     status = -EINVAL;
145
146         chip = gpiod_to_chip(desc);
147         offset = gpio_chip_hwgpio(desc);
148
149         if (!chip->get_direction)
150                 return status;
151
152         status = chip->get_direction(chip, offset);
153         if (status > 0) {
154                 /* GPIOF_DIR_IN, or other positive */
155                 status = 1;
156                 /* FLAG_IS_OUT is just a cache of the result of get_direction(),
157                  * so it does not affect constness per se */
158                 clear_bit(FLAG_IS_OUT, &((struct gpio_desc *)desc)->flags);
159         }
160         if (status == 0) {
161                 /* GPIOF_DIR_OUT */
162                 set_bit(FLAG_IS_OUT, &((struct gpio_desc *)desc)->flags);
163         }
164         return status;
165 }
166 EXPORT_SYMBOL_GPL(gpiod_get_direction);
167
168 /*
169  * Add a new chip to the global chips list, keeping the list of chips sorted
170  * by base order.
171  *
172  * Return -EBUSY if the new chip overlaps with some other chip's integer
173  * space.
174  */
175 static int gpiochip_add_to_list(struct gpio_chip *chip)
176 {
177         struct list_head *pos = &gpio_chips;
178         struct gpio_chip *_chip;
179         int err = 0;
180
181         /* find where to insert our chip */
182         list_for_each(pos, &gpio_chips) {
183                 _chip = list_entry(pos, struct gpio_chip, list);
184                 /* shall we insert before _chip? */
185                 if (_chip->base >= chip->base + chip->ngpio)
186                         break;
187         }
188
189         /* are we stepping on the chip right before? */
190         if (pos != &gpio_chips && pos->prev != &gpio_chips) {
191                 _chip = list_entry(pos->prev, struct gpio_chip, list);
192                 if (_chip->base + _chip->ngpio > chip->base) {
193                         dev_err(chip->dev,
194                                "GPIO integer space overlap, cannot add chip\n");
195                         err = -EBUSY;
196                 }
197         }
198
199         if (!err)
200                 list_add_tail(&chip->list, pos);
201
202         return err;
203 }
204
205 /**
206  * gpiochip_add() - register a gpio_chip
207  * @chip: the chip to register, with chip->base initialized
208  * Context: potentially before irqs or kmalloc will work
209  *
210  * Returns a negative errno if the chip can't be registered, such as
211  * because the chip->base is invalid or already associated with a
212  * different chip.  Otherwise it returns zero as a success code.
213  *
214  * When gpiochip_add() is called very early during boot, so that GPIOs
215  * can be freely used, the chip->dev device must be registered before
216  * the gpio framework's arch_initcall().  Otherwise sysfs initialization
217  * for GPIOs will fail rudely.
218  *
219  * If chip->base is negative, this requests dynamic assignment of
220  * a range of valid GPIOs.
221  */
222 int gpiochip_add(struct gpio_chip *chip)
223 {
224         unsigned long   flags;
225         int             status = 0;
226         unsigned        id;
227         int             base = chip->base;
228
229         if ((!gpio_is_valid(base) || !gpio_is_valid(base + chip->ngpio - 1))
230                         && base >= 0) {
231                 status = -EINVAL;
232                 goto fail;
233         }
234
235         spin_lock_irqsave(&gpio_lock, flags);
236
237         if (base < 0) {
238                 base = gpiochip_find_base(chip->ngpio);
239                 if (base < 0) {
240                         status = base;
241                         goto unlock;
242                 }
243                 chip->base = base;
244         }
245
246         status = gpiochip_add_to_list(chip);
247
248         if (status == 0) {
249                 chip->desc = &gpio_desc[chip->base];
250
251                 for (id = 0; id < chip->ngpio; id++) {
252                         struct gpio_desc *desc = &chip->desc[id];
253                         desc->chip = chip;
254
255                         /* REVISIT:  most hardware initializes GPIOs as
256                          * inputs (often with pullups enabled) so power
257                          * usage is minimized.  Linux code should set the
258                          * gpio direction first thing; but until it does,
259                          * and in case chip->get_direction is not set,
260                          * we may expose the wrong direction in sysfs.
261                          */
262                         desc->flags = !chip->direction_input
263                                 ? (1 << FLAG_IS_OUT)
264                                 : 0;
265                 }
266         }
267
268         spin_unlock_irqrestore(&gpio_lock, flags);
269
270 #ifdef CONFIG_PINCTRL
271         INIT_LIST_HEAD(&chip->pin_ranges);
272 #endif
273
274         of_gpiochip_add(chip);
275         acpi_gpiochip_add(chip);
276
277         if (status)
278                 goto fail;
279
280         status = gpiochip_export(chip);
281         if (status)
282                 goto fail;
283
284         pr_debug("%s: registered GPIOs %d to %d on device: %s\n", __func__,
285                 chip->base, chip->base + chip->ngpio - 1,
286                 chip->label ? : "generic");
287
288         return 0;
289
290 unlock:
291         spin_unlock_irqrestore(&gpio_lock, flags);
292 fail:
293         /* failures here can mean systems won't boot... */
294         pr_err("%s: GPIOs %d..%d (%s) failed to register\n", __func__,
295                 chip->base, chip->base + chip->ngpio - 1,
296                 chip->label ? : "generic");
297         return status;
298 }
299 EXPORT_SYMBOL_GPL(gpiochip_add);
300
301 /* Forward-declaration */
302 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip);
303
304 /**
305  * gpiochip_remove() - unregister a gpio_chip
306  * @chip: the chip to unregister
307  *
308  * A gpio_chip with any GPIOs still requested may not be removed.
309  */
310 int gpiochip_remove(struct gpio_chip *chip)
311 {
312         unsigned long   flags;
313         int             status = 0;
314         unsigned        id;
315
316         acpi_gpiochip_remove(chip);
317
318         spin_lock_irqsave(&gpio_lock, flags);
319
320         gpiochip_irqchip_remove(chip);
321         gpiochip_remove_pin_ranges(chip);
322         of_gpiochip_remove(chip);
323
324         for (id = 0; id < chip->ngpio; id++) {
325                 if (test_bit(FLAG_REQUESTED, &chip->desc[id].flags)) {
326                         status = -EBUSY;
327                         break;
328                 }
329         }
330         if (status == 0) {
331                 for (id = 0; id < chip->ngpio; id++)
332                         chip->desc[id].chip = NULL;
333
334                 list_del(&chip->list);
335         }
336
337         spin_unlock_irqrestore(&gpio_lock, flags);
338
339         if (status == 0)
340                 gpiochip_unexport(chip);
341
342         return status;
343 }
344 EXPORT_SYMBOL_GPL(gpiochip_remove);
345
346 /**
347  * gpiochip_find() - iterator for locating a specific gpio_chip
348  * @data: data to pass to match function
349  * @callback: Callback function to check gpio_chip
350  *
351  * Similar to bus_find_device.  It returns a reference to a gpio_chip as
352  * determined by a user supplied @match callback.  The callback should return
353  * 0 if the device doesn't match and non-zero if it does.  If the callback is
354  * non-zero, this function will return to the caller and not iterate over any
355  * more gpio_chips.
356  */
357 struct gpio_chip *gpiochip_find(void *data,
358                                 int (*match)(struct gpio_chip *chip,
359                                              void *data))
360 {
361         struct gpio_chip *chip;
362         unsigned long flags;
363
364         spin_lock_irqsave(&gpio_lock, flags);
365         list_for_each_entry(chip, &gpio_chips, list)
366                 if (match(chip, data))
367                         break;
368
369         /* No match? */
370         if (&chip->list == &gpio_chips)
371                 chip = NULL;
372         spin_unlock_irqrestore(&gpio_lock, flags);
373
374         return chip;
375 }
376 EXPORT_SYMBOL_GPL(gpiochip_find);
377
378 static int gpiochip_match_name(struct gpio_chip *chip, void *data)
379 {
380         const char *name = data;
381
382         return !strcmp(chip->label, name);
383 }
384
385 static struct gpio_chip *find_chip_by_name(const char *name)
386 {
387         return gpiochip_find((void *)name, gpiochip_match_name);
388 }
389
390 #ifdef CONFIG_GPIOLIB_IRQCHIP
391
392 /*
393  * The following is irqchip helper code for gpiochips.
394  */
395
396 /**
397  * gpiochip_add_chained_irqchip() - adds a chained irqchip to a gpiochip
398  * @gpiochip: the gpiochip to add the irqchip to
399  * @irqchip: the irqchip to add to the gpiochip
400  * @parent_irq: the irq number corresponding to the parent IRQ for this
401  * chained irqchip
402  * @parent_handler: the parent interrupt handler for the accumulated IRQ
403  * coming out of the gpiochip
404  */
405 void gpiochip_set_chained_irqchip(struct gpio_chip *gpiochip,
406                                   struct irq_chip *irqchip,
407                                   int parent_irq,
408                                   irq_flow_handler_t parent_handler)
409 {
410         if (gpiochip->can_sleep) {
411                 chip_err(gpiochip, "you cannot have chained interrupts on a chip that may sleep\n");
412                 return;
413         }
414
415         irq_set_chained_handler(parent_irq, parent_handler);
416         /*
417          * The parent irqchip is already using the chip_data for this
418          * irqchip, so our callbacks simply use the handler_data.
419          */
420         irq_set_handler_data(parent_irq, gpiochip);
421 }
422 EXPORT_SYMBOL_GPL(gpiochip_set_chained_irqchip);
423
424 /*
425  * This lock class tells lockdep that GPIO irqs are in a different
426  * category than their parents, so it won't report false recursion.
427  */
428 static struct lock_class_key gpiochip_irq_lock_class;
429
430 /**
431  * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
432  * @d: the irqdomain used by this irqchip
433  * @irq: the global irq number used by this GPIO irqchip irq
434  * @hwirq: the local IRQ/GPIO line offset on this gpiochip
435  *
436  * This function will set up the mapping for a certain IRQ line on a
437  * gpiochip by assigning the gpiochip as chip data, and using the irqchip
438  * stored inside the gpiochip.
439  */
440 static int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
441                             irq_hw_number_t hwirq)
442 {
443         struct gpio_chip *chip = d->host_data;
444
445         irq_set_chip_data(irq, chip);
446         irq_set_lockdep_class(irq, &gpiochip_irq_lock_class);
447         irq_set_chip_and_handler(irq, chip->irqchip, chip->irq_handler);
448         /* Chips that can sleep need nested thread handlers */
449         if (chip->can_sleep)
450                 irq_set_nested_thread(irq, 1);
451 #ifdef CONFIG_ARM
452         set_irq_flags(irq, IRQF_VALID);
453 #else
454         irq_set_noprobe(irq);
455 #endif
456         /*
457          * No set-up of the hardware will happen if IRQ_TYPE_NONE
458          * is passed as default type.
459          */
460         if (chip->irq_default_type != IRQ_TYPE_NONE)
461                 irq_set_irq_type(irq, chip->irq_default_type);
462
463         return 0;
464 }
465
466 static void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
467 {
468         struct gpio_chip *chip = d->host_data;
469
470 #ifdef CONFIG_ARM
471         set_irq_flags(irq, 0);
472 #endif
473         if (chip->can_sleep)
474                 irq_set_nested_thread(irq, 0);
475         irq_set_chip_and_handler(irq, NULL, NULL);
476         irq_set_chip_data(irq, NULL);
477 }
478
479 static const struct irq_domain_ops gpiochip_domain_ops = {
480         .map    = gpiochip_irq_map,
481         .unmap  = gpiochip_irq_unmap,
482         /* Virtually all GPIO irqchips are twocell:ed */
483         .xlate  = irq_domain_xlate_twocell,
484 };
485
486 static int gpiochip_irq_reqres(struct irq_data *d)
487 {
488         struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
489
490         if (gpio_lock_as_irq(chip, d->hwirq)) {
491                 chip_err(chip,
492                         "unable to lock HW IRQ %lu for IRQ\n",
493                         d->hwirq);
494                 return -EINVAL;
495         }
496         return 0;
497 }
498
499 static void gpiochip_irq_relres(struct irq_data *d)
500 {
501         struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
502
503         gpio_unlock_as_irq(chip, d->hwirq);
504 }
505
506 static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset)
507 {
508         return irq_find_mapping(chip->irqdomain, offset);
509 }
510
511 /**
512  * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
513  * @gpiochip: the gpiochip to remove the irqchip from
514  *
515  * This is called only from gpiochip_remove()
516  */
517 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip)
518 {
519         unsigned int offset;
520
521         /* Remove all IRQ mappings and delete the domain */
522         if (gpiochip->irqdomain) {
523                 for (offset = 0; offset < gpiochip->ngpio; offset++)
524                         irq_dispose_mapping(gpiochip->irq_base + offset);
525                 irq_domain_remove(gpiochip->irqdomain);
526         }
527
528         if (gpiochip->irqchip) {
529                 gpiochip->irqchip->irq_request_resources = NULL;
530                 gpiochip->irqchip->irq_release_resources = NULL;
531                 gpiochip->irqchip = NULL;
532         }
533 }
534
535 /**
536  * gpiochip_irqchip_add() - adds an irqchip to a gpiochip
537  * @gpiochip: the gpiochip to add the irqchip to
538  * @irqchip: the irqchip to add to the gpiochip
539  * @first_irq: if not dynamically assigned, the base (first) IRQ to
540  * allocate gpiochip irqs from
541  * @handler: the irq handler to use (often a predefined irq core function)
542  * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
543  * to have the core avoid setting up any default type in the hardware.
544  *
545  * This function closely associates a certain irqchip with a certain
546  * gpiochip, providing an irq domain to translate the local IRQs to
547  * global irqs in the gpiolib core, and making sure that the gpiochip
548  * is passed as chip data to all related functions. Driver callbacks
549  * need to use container_of() to get their local state containers back
550  * from the gpiochip passed as chip data. An irqdomain will be stored
551  * in the gpiochip that shall be used by the driver to handle IRQ number
552  * translation. The gpiochip will need to be initialized and registered
553  * before calling this function.
554  *
555  * This function will handle two cell:ed simple IRQs and assumes all
556  * the pins on the gpiochip can generate a unique IRQ. Everything else
557  * need to be open coded.
558  */
559 int gpiochip_irqchip_add(struct gpio_chip *gpiochip,
560                          struct irq_chip *irqchip,
561                          unsigned int first_irq,
562                          irq_flow_handler_t handler,
563                          unsigned int type)
564 {
565         struct device_node *of_node;
566         unsigned int offset;
567         unsigned irq_base = 0;
568
569         if (!gpiochip || !irqchip)
570                 return -EINVAL;
571
572         if (!gpiochip->dev) {
573                 pr_err("missing gpiochip .dev parent pointer\n");
574                 return -EINVAL;
575         }
576         of_node = gpiochip->dev->of_node;
577 #ifdef CONFIG_OF_GPIO
578         /*
579          * If the gpiochip has an assigned OF node this takes precendence
580          * FIXME: get rid of this and use gpiochip->dev->of_node everywhere
581          */
582         if (gpiochip->of_node)
583                 of_node = gpiochip->of_node;
584 #endif
585         gpiochip->irqchip = irqchip;
586         gpiochip->irq_handler = handler;
587         gpiochip->irq_default_type = type;
588         gpiochip->to_irq = gpiochip_to_irq;
589         gpiochip->irqdomain = irq_domain_add_simple(of_node,
590                                         gpiochip->ngpio, first_irq,
591                                         &gpiochip_domain_ops, gpiochip);
592         if (!gpiochip->irqdomain) {
593                 gpiochip->irqchip = NULL;
594                 return -EINVAL;
595         }
596         irqchip->irq_request_resources = gpiochip_irq_reqres;
597         irqchip->irq_release_resources = gpiochip_irq_relres;
598
599         /*
600          * Prepare the mapping since the irqchip shall be orthogonal to
601          * any gpiochip calls. If the first_irq was zero, this is
602          * necessary to allocate descriptors for all IRQs.
603          */
604         for (offset = 0; offset < gpiochip->ngpio; offset++) {
605                 irq_base = irq_create_mapping(gpiochip->irqdomain, offset);
606                 if (offset == 0)
607                         /*
608                          * Store the base into the gpiochip to be used when
609                          * unmapping the irqs.
610                          */
611                         gpiochip->irq_base = irq_base;
612         }
613
614         return 0;
615 }
616 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add);
617
618 #else /* CONFIG_GPIOLIB_IRQCHIP */
619
620 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {}
621
622 #endif /* CONFIG_GPIOLIB_IRQCHIP */
623
624 #ifdef CONFIG_PINCTRL
625
626 /**
627  * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
628  * @chip: the gpiochip to add the range for
629  * @pinctrl: the dev_name() of the pin controller to map to
630  * @gpio_offset: the start offset in the current gpio_chip number space
631  * @pin_group: name of the pin group inside the pin controller
632  */
633 int gpiochip_add_pingroup_range(struct gpio_chip *chip,
634                         struct pinctrl_dev *pctldev,
635                         unsigned int gpio_offset, const char *pin_group)
636 {
637         struct gpio_pin_range *pin_range;
638         int ret;
639
640         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
641         if (!pin_range) {
642                 chip_err(chip, "failed to allocate pin ranges\n");
643                 return -ENOMEM;
644         }
645
646         /* Use local offset as range ID */
647         pin_range->range.id = gpio_offset;
648         pin_range->range.gc = chip;
649         pin_range->range.name = chip->label;
650         pin_range->range.base = chip->base + gpio_offset;
651         pin_range->pctldev = pctldev;
652
653         ret = pinctrl_get_group_pins(pctldev, pin_group,
654                                         &pin_range->range.pins,
655                                         &pin_range->range.npins);
656         if (ret < 0) {
657                 kfree(pin_range);
658                 return ret;
659         }
660
661         pinctrl_add_gpio_range(pctldev, &pin_range->range);
662
663         chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n",
664                  gpio_offset, gpio_offset + pin_range->range.npins - 1,
665                  pinctrl_dev_get_devname(pctldev), pin_group);
666
667         list_add_tail(&pin_range->node, &chip->pin_ranges);
668
669         return 0;
670 }
671 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
672
673 /**
674  * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
675  * @chip: the gpiochip to add the range for
676  * @pinctrl_name: the dev_name() of the pin controller to map to
677  * @gpio_offset: the start offset in the current gpio_chip number space
678  * @pin_offset: the start offset in the pin controller number space
679  * @npins: the number of pins from the offset of each pin space (GPIO and
680  *      pin controller) to accumulate in this range
681  */
682 int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
683                            unsigned int gpio_offset, unsigned int pin_offset,
684                            unsigned int npins)
685 {
686         struct gpio_pin_range *pin_range;
687         int ret;
688
689         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
690         if (!pin_range) {
691                 chip_err(chip, "failed to allocate pin ranges\n");
692                 return -ENOMEM;
693         }
694
695         /* Use local offset as range ID */
696         pin_range->range.id = gpio_offset;
697         pin_range->range.gc = chip;
698         pin_range->range.name = chip->label;
699         pin_range->range.base = chip->base + gpio_offset;
700         pin_range->range.pin_base = pin_offset;
701         pin_range->range.npins = npins;
702         pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
703                         &pin_range->range);
704         if (IS_ERR(pin_range->pctldev)) {
705                 ret = PTR_ERR(pin_range->pctldev);
706                 chip_err(chip, "could not create pin range\n");
707                 kfree(pin_range);
708                 return ret;
709         }
710         chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
711                  gpio_offset, gpio_offset + npins - 1,
712                  pinctl_name,
713                  pin_offset, pin_offset + npins - 1);
714
715         list_add_tail(&pin_range->node, &chip->pin_ranges);
716
717         return 0;
718 }
719 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
720
721 /**
722  * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
723  * @chip: the chip to remove all the mappings for
724  */
725 void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
726 {
727         struct gpio_pin_range *pin_range, *tmp;
728
729         list_for_each_entry_safe(pin_range, tmp, &chip->pin_ranges, node) {
730                 list_del(&pin_range->node);
731                 pinctrl_remove_gpio_range(pin_range->pctldev,
732                                 &pin_range->range);
733                 kfree(pin_range);
734         }
735 }
736 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
737
738 #endif /* CONFIG_PINCTRL */
739
740 /* These "optional" allocation calls help prevent drivers from stomping
741  * on each other, and help provide better diagnostics in debugfs.
742  * They're called even less than the "set direction" calls.
743  */
744 static int __gpiod_request(struct gpio_desc *desc, const char *label)
745 {
746         struct gpio_chip        *chip = desc->chip;
747         int                     status;
748         unsigned long           flags;
749
750         spin_lock_irqsave(&gpio_lock, flags);
751
752         /* NOTE:  gpio_request() can be called in early boot,
753          * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
754          */
755
756         if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
757                 desc_set_label(desc, label ? : "?");
758                 status = 0;
759         } else {
760                 status = -EBUSY;
761                 goto done;
762         }
763
764         if (chip->request) {
765                 /* chip->request may sleep */
766                 spin_unlock_irqrestore(&gpio_lock, flags);
767                 status = chip->request(chip, gpio_chip_hwgpio(desc));
768                 spin_lock_irqsave(&gpio_lock, flags);
769
770                 if (status < 0) {
771                         desc_set_label(desc, NULL);
772                         clear_bit(FLAG_REQUESTED, &desc->flags);
773                         goto done;
774                 }
775         }
776         if (chip->get_direction) {
777                 /* chip->get_direction may sleep */
778                 spin_unlock_irqrestore(&gpio_lock, flags);
779                 gpiod_get_direction(desc);
780                 spin_lock_irqsave(&gpio_lock, flags);
781         }
782 done:
783         spin_unlock_irqrestore(&gpio_lock, flags);
784         return status;
785 }
786
787 int gpiod_request(struct gpio_desc *desc, const char *label)
788 {
789         int status = -EPROBE_DEFER;
790         struct gpio_chip *chip;
791
792         if (!desc) {
793                 pr_warn("%s: invalid GPIO\n", __func__);
794                 return -EINVAL;
795         }
796
797         chip = desc->chip;
798         if (!chip)
799                 goto done;
800
801         if (try_module_get(chip->owner)) {
802                 status = __gpiod_request(desc, label);
803                 if (status < 0)
804                         module_put(chip->owner);
805         }
806
807 done:
808         if (status)
809                 gpiod_dbg(desc, "%s: status %d\n", __func__, status);
810
811         return status;
812 }
813
814 static bool __gpiod_free(struct gpio_desc *desc)
815 {
816         bool                    ret = false;
817         unsigned long           flags;
818         struct gpio_chip        *chip;
819
820         might_sleep();
821
822         gpiod_unexport(desc);
823
824         spin_lock_irqsave(&gpio_lock, flags);
825
826         chip = desc->chip;
827         if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
828                 if (chip->free) {
829                         spin_unlock_irqrestore(&gpio_lock, flags);
830                         might_sleep_if(chip->can_sleep);
831                         chip->free(chip, gpio_chip_hwgpio(desc));
832                         spin_lock_irqsave(&gpio_lock, flags);
833                 }
834                 desc_set_label(desc, NULL);
835                 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
836                 clear_bit(FLAG_REQUESTED, &desc->flags);
837                 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
838                 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
839                 ret = true;
840         }
841
842         spin_unlock_irqrestore(&gpio_lock, flags);
843         return ret;
844 }
845
846 void gpiod_free(struct gpio_desc *desc)
847 {
848         if (desc && __gpiod_free(desc))
849                 module_put(desc->chip->owner);
850         else
851                 WARN_ON(extra_checks);
852 }
853
854 /**
855  * gpiochip_is_requested - return string iff signal was requested
856  * @chip: controller managing the signal
857  * @offset: of signal within controller's 0..(ngpio - 1) range
858  *
859  * Returns NULL if the GPIO is not currently requested, else a string.
860  * The string returned is the label passed to gpio_request(); if none has been
861  * passed it is a meaningless, non-NULL constant.
862  *
863  * This function is for use by GPIO controller drivers.  The label can
864  * help with diagnostics, and knowing that the signal is used as a GPIO
865  * can help avoid accidentally multiplexing it to another controller.
866  */
867 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
868 {
869         struct gpio_desc *desc;
870
871         if (!GPIO_OFFSET_VALID(chip, offset))
872                 return NULL;
873
874         desc = &chip->desc[offset];
875
876         if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
877                 return NULL;
878         return desc->label;
879 }
880 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
881
882 /**
883  * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
884  * @desc: GPIO descriptor to request
885  * @label: label for the GPIO
886  *
887  * Function allows GPIO chip drivers to request and use their own GPIO
888  * descriptors via gpiolib API. Difference to gpiod_request() is that this
889  * function will not increase reference count of the GPIO chip module. This
890  * allows the GPIO chip module to be unloaded as needed (we assume that the
891  * GPIO chip driver handles freeing the GPIOs it has requested).
892  */
893 int gpiochip_request_own_desc(struct gpio_desc *desc, const char *label)
894 {
895         if (!desc || !desc->chip)
896                 return -EINVAL;
897
898         return __gpiod_request(desc, label);
899 }
900
901 /**
902  * gpiochip_free_own_desc - Free GPIO requested by the chip driver
903  * @desc: GPIO descriptor to free
904  *
905  * Function frees the given GPIO requested previously with
906  * gpiochip_request_own_desc().
907  */
908 void gpiochip_free_own_desc(struct gpio_desc *desc)
909 {
910         if (desc)
911                 __gpiod_free(desc);
912 }
913
914 /* Drivers MUST set GPIO direction before making get/set calls.  In
915  * some cases this is done in early boot, before IRQs are enabled.
916  *
917  * As a rule these aren't called more than once (except for drivers
918  * using the open-drain emulation idiom) so these are natural places
919  * to accumulate extra debugging checks.  Note that we can't (yet)
920  * rely on gpio_request() having been called beforehand.
921  */
922
923 /**
924  * gpiod_direction_input - set the GPIO direction to input
925  * @desc:       GPIO to set to input
926  *
927  * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
928  * be called safely on it.
929  *
930  * Return 0 in case of success, else an error code.
931  */
932 int gpiod_direction_input(struct gpio_desc *desc)
933 {
934         struct gpio_chip        *chip;
935         int                     status = -EINVAL;
936
937         if (!desc || !desc->chip) {
938                 pr_warn("%s: invalid GPIO\n", __func__);
939                 return -EINVAL;
940         }
941
942         chip = desc->chip;
943         if (!chip->get || !chip->direction_input) {
944                 gpiod_warn(desc,
945                         "%s: missing get() or direction_input() operations\n",
946                         __func__);
947                 return -EIO;
948         }
949
950         status = chip->direction_input(chip, gpio_chip_hwgpio(desc));
951         if (status == 0)
952                 clear_bit(FLAG_IS_OUT, &desc->flags);
953
954         trace_gpio_direction(desc_to_gpio(desc), 1, status);
955
956         return status;
957 }
958 EXPORT_SYMBOL_GPL(gpiod_direction_input);
959
960 static int _gpiod_direction_output_raw(struct gpio_desc *desc, int value)
961 {
962         struct gpio_chip        *chip;
963         int                     status = -EINVAL;
964
965         /* GPIOs used for IRQs shall not be set as output */
966         if (test_bit(FLAG_USED_AS_IRQ, &desc->flags)) {
967                 gpiod_err(desc,
968                           "%s: tried to set a GPIO tied to an IRQ as output\n",
969                           __func__);
970                 return -EIO;
971         }
972
973         /* Open drain pin should not be driven to 1 */
974         if (value && test_bit(FLAG_OPEN_DRAIN,  &desc->flags))
975                 return gpiod_direction_input(desc);
976
977         /* Open source pin should not be driven to 0 */
978         if (!value && test_bit(FLAG_OPEN_SOURCE,  &desc->flags))
979                 return gpiod_direction_input(desc);
980
981         chip = desc->chip;
982         if (!chip->set || !chip->direction_output) {
983                 gpiod_warn(desc,
984                        "%s: missing set() or direction_output() operations\n",
985                        __func__);
986                 return -EIO;
987         }
988
989         status = chip->direction_output(chip, gpio_chip_hwgpio(desc), value);
990         if (status == 0)
991                 set_bit(FLAG_IS_OUT, &desc->flags);
992         trace_gpio_value(desc_to_gpio(desc), 0, value);
993         trace_gpio_direction(desc_to_gpio(desc), 0, status);
994         return status;
995 }
996
997 /**
998  * gpiod_direction_output_raw - set the GPIO direction to output
999  * @desc:       GPIO to set to output
1000  * @value:      initial output value of the GPIO
1001  *
1002  * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
1003  * be called safely on it. The initial value of the output must be specified
1004  * as raw value on the physical line without regard for the ACTIVE_LOW status.
1005  *
1006  * Return 0 in case of success, else an error code.
1007  */
1008 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
1009 {
1010         if (!desc || !desc->chip) {
1011                 pr_warn("%s: invalid GPIO\n", __func__);
1012                 return -EINVAL;
1013         }
1014         return _gpiod_direction_output_raw(desc, value);
1015 }
1016 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
1017
1018 /**
1019  * gpiod_direction_output - set the GPIO direction to output
1020  * @desc:       GPIO to set to output
1021  * @value:      initial output value of the GPIO
1022  *
1023  * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
1024  * be called safely on it. The initial value of the output must be specified
1025  * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
1026  * account.
1027  *
1028  * Return 0 in case of success, else an error code.
1029  */
1030 int gpiod_direction_output(struct gpio_desc *desc, int value)
1031 {
1032         if (!desc || !desc->chip) {
1033                 pr_warn("%s: invalid GPIO\n", __func__);
1034                 return -EINVAL;
1035         }
1036         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1037                 value = !value;
1038         return _gpiod_direction_output_raw(desc, value);
1039 }
1040 EXPORT_SYMBOL_GPL(gpiod_direction_output);
1041
1042 /**
1043  * gpiod_set_debounce - sets @debounce time for a @gpio
1044  * @gpio: the gpio to set debounce time
1045  * @debounce: debounce time is microseconds
1046  *
1047  * returns -ENOTSUPP if the controller does not support setting
1048  * debounce.
1049  */
1050 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
1051 {
1052         struct gpio_chip        *chip;
1053
1054         if (!desc || !desc->chip) {
1055                 pr_warn("%s: invalid GPIO\n", __func__);
1056                 return -EINVAL;
1057         }
1058
1059         chip = desc->chip;
1060         if (!chip->set || !chip->set_debounce) {
1061                 gpiod_dbg(desc,
1062                           "%s: missing set() or set_debounce() operations\n",
1063                           __func__);
1064                 return -ENOTSUPP;
1065         }
1066
1067         return chip->set_debounce(chip, gpio_chip_hwgpio(desc), debounce);
1068 }
1069 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
1070
1071 /**
1072  * gpiod_is_active_low - test whether a GPIO is active-low or not
1073  * @desc: the gpio descriptor to test
1074  *
1075  * Returns 1 if the GPIO is active-low, 0 otherwise.
1076  */
1077 int gpiod_is_active_low(const struct gpio_desc *desc)
1078 {
1079         return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
1080 }
1081 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
1082
1083 /* I/O calls are only valid after configuration completed; the relevant
1084  * "is this a valid GPIO" error checks should already have been done.
1085  *
1086  * "Get" operations are often inlinable as reading a pin value register,
1087  * and masking the relevant bit in that register.
1088  *
1089  * When "set" operations are inlinable, they involve writing that mask to
1090  * one register to set a low value, or a different register to set it high.
1091  * Otherwise locking is needed, so there may be little value to inlining.
1092  *
1093  *------------------------------------------------------------------------
1094  *
1095  * IMPORTANT!!!  The hot paths -- get/set value -- assume that callers
1096  * have requested the GPIO.  That can include implicit requesting by
1097  * a direction setting call.  Marking a gpio as requested locks its chip
1098  * in memory, guaranteeing that these table lookups need no more locking
1099  * and that gpiochip_remove() will fail.
1100  *
1101  * REVISIT when debugging, consider adding some instrumentation to ensure
1102  * that the GPIO was actually requested.
1103  */
1104
1105 static bool _gpiod_get_raw_value(const struct gpio_desc *desc)
1106 {
1107         struct gpio_chip        *chip;
1108         bool value;
1109         int offset;
1110
1111         chip = desc->chip;
1112         offset = gpio_chip_hwgpio(desc);
1113         value = chip->get ? chip->get(chip, offset) : false;
1114         trace_gpio_value(desc_to_gpio(desc), 1, value);
1115         return value;
1116 }
1117
1118 /**
1119  * gpiod_get_raw_value() - return a gpio's raw value
1120  * @desc: gpio whose value will be returned
1121  *
1122  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
1123  * its ACTIVE_LOW status.
1124  *
1125  * This function should be called from contexts where we cannot sleep, and will
1126  * complain if the GPIO chip functions potentially sleep.
1127  */
1128 int gpiod_get_raw_value(const struct gpio_desc *desc)
1129 {
1130         if (!desc)
1131                 return 0;
1132         /* Should be using gpio_get_value_cansleep() */
1133         WARN_ON(desc->chip->can_sleep);
1134         return _gpiod_get_raw_value(desc);
1135 }
1136 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
1137
1138 /**
1139  * gpiod_get_value() - return a gpio's value
1140  * @desc: gpio whose value will be returned
1141  *
1142  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
1143  * account.
1144  *
1145  * This function should be called from contexts where we cannot sleep, and will
1146  * complain if the GPIO chip functions potentially sleep.
1147  */
1148 int gpiod_get_value(const struct gpio_desc *desc)
1149 {
1150         int value;
1151         if (!desc)
1152                 return 0;
1153         /* Should be using gpio_get_value_cansleep() */
1154         WARN_ON(desc->chip->can_sleep);
1155
1156         value = _gpiod_get_raw_value(desc);
1157         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1158                 value = !value;
1159
1160         return value;
1161 }
1162 EXPORT_SYMBOL_GPL(gpiod_get_value);
1163
1164 /*
1165  *  _gpio_set_open_drain_value() - Set the open drain gpio's value.
1166  * @desc: gpio descriptor whose state need to be set.
1167  * @value: Non-zero for setting it HIGH otherise it will set to LOW.
1168  */
1169 static void _gpio_set_open_drain_value(struct gpio_desc *desc, bool value)
1170 {
1171         int err = 0;
1172         struct gpio_chip *chip = desc->chip;
1173         int offset = gpio_chip_hwgpio(desc);
1174
1175         if (value) {
1176                 err = chip->direction_input(chip, offset);
1177                 if (!err)
1178                         clear_bit(FLAG_IS_OUT, &desc->flags);
1179         } else {
1180                 err = chip->direction_output(chip, offset, 0);
1181                 if (!err)
1182                         set_bit(FLAG_IS_OUT, &desc->flags);
1183         }
1184         trace_gpio_direction(desc_to_gpio(desc), value, err);
1185         if (err < 0)
1186                 gpiod_err(desc,
1187                           "%s: Error in set_value for open drain err %d\n",
1188                           __func__, err);
1189 }
1190
1191 /*
1192  *  _gpio_set_open_source_value() - Set the open source gpio's value.
1193  * @desc: gpio descriptor whose state need to be set.
1194  * @value: Non-zero for setting it HIGH otherise it will set to LOW.
1195  */
1196 static void _gpio_set_open_source_value(struct gpio_desc *desc, bool value)
1197 {
1198         int err = 0;
1199         struct gpio_chip *chip = desc->chip;
1200         int offset = gpio_chip_hwgpio(desc);
1201
1202         if (value) {
1203                 err = chip->direction_output(chip, offset, 1);
1204                 if (!err)
1205                         set_bit(FLAG_IS_OUT, &desc->flags);
1206         } else {
1207                 err = chip->direction_input(chip, offset);
1208                 if (!err)
1209                         clear_bit(FLAG_IS_OUT, &desc->flags);
1210         }
1211         trace_gpio_direction(desc_to_gpio(desc), !value, err);
1212         if (err < 0)
1213                 gpiod_err(desc,
1214                           "%s: Error in set_value for open source err %d\n",
1215                           __func__, err);
1216 }
1217
1218 static void _gpiod_set_raw_value(struct gpio_desc *desc, bool value)
1219 {
1220         struct gpio_chip        *chip;
1221
1222         chip = desc->chip;
1223         trace_gpio_value(desc_to_gpio(desc), 0, value);
1224         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
1225                 _gpio_set_open_drain_value(desc, value);
1226         else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
1227                 _gpio_set_open_source_value(desc, value);
1228         else
1229                 chip->set(chip, gpio_chip_hwgpio(desc), value);
1230 }
1231
1232 /**
1233  * gpiod_set_raw_value() - assign a gpio's raw value
1234  * @desc: gpio whose value will be assigned
1235  * @value: value to assign
1236  *
1237  * Set the raw value of the GPIO, i.e. the value of its physical line without
1238  * regard for its ACTIVE_LOW status.
1239  *
1240  * This function should be called from contexts where we cannot sleep, and will
1241  * complain if the GPIO chip functions potentially sleep.
1242  */
1243 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
1244 {
1245         if (!desc)
1246                 return;
1247         /* Should be using gpio_set_value_cansleep() */
1248         WARN_ON(desc->chip->can_sleep);
1249         _gpiod_set_raw_value(desc, value);
1250 }
1251 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
1252
1253 /**
1254  * gpiod_set_value() - assign a gpio's value
1255  * @desc: gpio whose value will be assigned
1256  * @value: value to assign
1257  *
1258  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
1259  * account
1260  *
1261  * This function should be called from contexts where we cannot sleep, and will
1262  * complain if the GPIO chip functions potentially sleep.
1263  */
1264 void gpiod_set_value(struct gpio_desc *desc, int value)
1265 {
1266         if (!desc)
1267                 return;
1268         /* Should be using gpio_set_value_cansleep() */
1269         WARN_ON(desc->chip->can_sleep);
1270         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1271                 value = !value;
1272         _gpiod_set_raw_value(desc, value);
1273 }
1274 EXPORT_SYMBOL_GPL(gpiod_set_value);
1275
1276 /**
1277  * gpiod_cansleep() - report whether gpio value access may sleep
1278  * @desc: gpio to check
1279  *
1280  */
1281 int gpiod_cansleep(const struct gpio_desc *desc)
1282 {
1283         if (!desc)
1284                 return 0;
1285         return desc->chip->can_sleep;
1286 }
1287 EXPORT_SYMBOL_GPL(gpiod_cansleep);
1288
1289 /**
1290  * gpiod_to_irq() - return the IRQ corresponding to a GPIO
1291  * @desc: gpio whose IRQ will be returned (already requested)
1292  *
1293  * Return the IRQ corresponding to the passed GPIO, or an error code in case of
1294  * error.
1295  */
1296 int gpiod_to_irq(const struct gpio_desc *desc)
1297 {
1298         struct gpio_chip        *chip;
1299         int                     offset;
1300
1301         if (!desc)
1302                 return -EINVAL;
1303         chip = desc->chip;
1304         offset = gpio_chip_hwgpio(desc);
1305         return chip->to_irq ? chip->to_irq(chip, offset) : -ENXIO;
1306 }
1307 EXPORT_SYMBOL_GPL(gpiod_to_irq);
1308
1309 /**
1310  * gpio_lock_as_irq() - lock a GPIO to be used as IRQ
1311  * @chip: the chip the GPIO to lock belongs to
1312  * @offset: the offset of the GPIO to lock as IRQ
1313  *
1314  * This is used directly by GPIO drivers that want to lock down
1315  * a certain GPIO line to be used for IRQs.
1316  */
1317 int gpio_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
1318 {
1319         if (offset >= chip->ngpio)
1320                 return -EINVAL;
1321
1322         if (test_bit(FLAG_IS_OUT, &chip->desc[offset].flags)) {
1323                 chip_err(chip,
1324                           "%s: tried to flag a GPIO set as output for IRQ\n",
1325                           __func__);
1326                 return -EIO;
1327         }
1328
1329         set_bit(FLAG_USED_AS_IRQ, &chip->desc[offset].flags);
1330         return 0;
1331 }
1332 EXPORT_SYMBOL_GPL(gpio_lock_as_irq);
1333
1334 /**
1335  * gpio_unlock_as_irq() - unlock a GPIO used as IRQ
1336  * @chip: the chip the GPIO to lock belongs to
1337  * @offset: the offset of the GPIO to lock as IRQ
1338  *
1339  * This is used directly by GPIO drivers that want to indicate
1340  * that a certain GPIO is no longer used exclusively for IRQ.
1341  */
1342 void gpio_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
1343 {
1344         if (offset >= chip->ngpio)
1345                 return;
1346
1347         clear_bit(FLAG_USED_AS_IRQ, &chip->desc[offset].flags);
1348 }
1349 EXPORT_SYMBOL_GPL(gpio_unlock_as_irq);
1350
1351 /**
1352  * gpiod_get_raw_value_cansleep() - return a gpio's raw value
1353  * @desc: gpio whose value will be returned
1354  *
1355  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
1356  * its ACTIVE_LOW status.
1357  *
1358  * This function is to be called from contexts that can sleep.
1359  */
1360 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
1361 {
1362         might_sleep_if(extra_checks);
1363         if (!desc)
1364                 return 0;
1365         return _gpiod_get_raw_value(desc);
1366 }
1367 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
1368
1369 /**
1370  * gpiod_get_value_cansleep() - return a gpio's value
1371  * @desc: gpio whose value will be returned
1372  *
1373  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
1374  * account.
1375  *
1376  * This function is to be called from contexts that can sleep.
1377  */
1378 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
1379 {
1380         int value;
1381
1382         might_sleep_if(extra_checks);
1383         if (!desc)
1384                 return 0;
1385
1386         value = _gpiod_get_raw_value(desc);
1387         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1388                 value = !value;
1389
1390         return value;
1391 }
1392 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
1393
1394 /**
1395  * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
1396  * @desc: gpio whose value will be assigned
1397  * @value: value to assign
1398  *
1399  * Set the raw value of the GPIO, i.e. the value of its physical line without
1400  * regard for its ACTIVE_LOW status.
1401  *
1402  * This function is to be called from contexts that can sleep.
1403  */
1404 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
1405 {
1406         might_sleep_if(extra_checks);
1407         if (!desc)
1408                 return;
1409         _gpiod_set_raw_value(desc, value);
1410 }
1411 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
1412
1413 /**
1414  * gpiod_set_value_cansleep() - assign a gpio's value
1415  * @desc: gpio whose value will be assigned
1416  * @value: value to assign
1417  *
1418  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
1419  * account
1420  *
1421  * This function is to be called from contexts that can sleep.
1422  */
1423 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
1424 {
1425         might_sleep_if(extra_checks);
1426         if (!desc)
1427                 return;
1428
1429         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1430                 value = !value;
1431         _gpiod_set_raw_value(desc, value);
1432 }
1433 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
1434
1435 /**
1436  * gpiod_add_lookup_table() - register GPIO device consumers
1437  * @table: table of consumers to register
1438  */
1439 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
1440 {
1441         mutex_lock(&gpio_lookup_lock);
1442
1443         list_add_tail(&table->list, &gpio_lookup_list);
1444
1445         mutex_unlock(&gpio_lookup_lock);
1446 }
1447
1448 static struct gpio_desc *of_find_gpio(struct device *dev, const char *con_id,
1449                                       unsigned int idx,
1450                                       enum gpio_lookup_flags *flags)
1451 {
1452         static const char *suffixes[] = { "gpios", "gpio" };
1453         char prop_name[32]; /* 32 is max size of property name */
1454         enum of_gpio_flags of_flags;
1455         struct gpio_desc *desc;
1456         unsigned int i;
1457
1458         for (i = 0; i < ARRAY_SIZE(suffixes); i++) {
1459                 if (con_id)
1460                         snprintf(prop_name, 32, "%s-%s", con_id, suffixes[i]);
1461                 else
1462                         snprintf(prop_name, 32, "%s", suffixes[i]);
1463
1464                 desc = of_get_named_gpiod_flags(dev->of_node, prop_name, idx,
1465                                                 &of_flags);
1466                 if (!IS_ERR(desc) || (PTR_ERR(desc) == -EPROBE_DEFER))
1467                         break;
1468         }
1469
1470         if (IS_ERR(desc))
1471                 return desc;
1472
1473         if (of_flags & OF_GPIO_ACTIVE_LOW)
1474                 *flags |= GPIO_ACTIVE_LOW;
1475
1476         return desc;
1477 }
1478
1479 static struct gpio_desc *acpi_find_gpio(struct device *dev, const char *con_id,
1480                                         unsigned int idx,
1481                                         enum gpio_lookup_flags *flags)
1482 {
1483         struct acpi_gpio_info info;
1484         struct gpio_desc *desc;
1485
1486         desc = acpi_get_gpiod_by_index(dev, idx, &info);
1487         if (IS_ERR(desc))
1488                 return desc;
1489
1490         if (info.gpioint && info.active_low)
1491                 *flags |= GPIO_ACTIVE_LOW;
1492
1493         return desc;
1494 }
1495
1496 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
1497 {
1498         const char *dev_id = dev ? dev_name(dev) : NULL;
1499         struct gpiod_lookup_table *table;
1500
1501         mutex_lock(&gpio_lookup_lock);
1502
1503         list_for_each_entry(table, &gpio_lookup_list, list) {
1504                 if (table->dev_id && dev_id) {
1505                         /*
1506                          * Valid strings on both ends, must be identical to have
1507                          * a match
1508                          */
1509                         if (!strcmp(table->dev_id, dev_id))
1510                                 goto found;
1511                 } else {
1512                         /*
1513                          * One of the pointers is NULL, so both must be to have
1514                          * a match
1515                          */
1516                         if (dev_id == table->dev_id)
1517                                 goto found;
1518                 }
1519         }
1520         table = NULL;
1521
1522 found:
1523         mutex_unlock(&gpio_lookup_lock);
1524         return table;
1525 }
1526
1527 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
1528                                     unsigned int idx,
1529                                     enum gpio_lookup_flags *flags)
1530 {
1531         struct gpio_desc *desc = ERR_PTR(-ENOENT);
1532         struct gpiod_lookup_table *table;
1533         struct gpiod_lookup *p;
1534
1535         table = gpiod_find_lookup_table(dev);
1536         if (!table)
1537                 return desc;
1538
1539         for (p = &table->table[0]; p->chip_label; p++) {
1540                 struct gpio_chip *chip;
1541
1542                 /* idx must always match exactly */
1543                 if (p->idx != idx)
1544                         continue;
1545
1546                 /* If the lookup entry has a con_id, require exact match */
1547                 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
1548                         continue;
1549
1550                 chip = find_chip_by_name(p->chip_label);
1551
1552                 if (!chip) {
1553                         dev_err(dev, "cannot find GPIO chip %s\n",
1554                                 p->chip_label);
1555                         return ERR_PTR(-ENODEV);
1556                 }
1557
1558                 if (chip->ngpio <= p->chip_hwnum) {
1559                         dev_err(dev,
1560                                 "requested GPIO %d is out of range [0..%d] for chip %s\n",
1561                                 idx, chip->ngpio, chip->label);
1562                         return ERR_PTR(-EINVAL);
1563                 }
1564
1565                 desc = gpiochip_get_desc(chip, p->chip_hwnum);
1566                 *flags = p->flags;
1567
1568                 return desc;
1569         }
1570
1571         return desc;
1572 }
1573
1574 /**
1575  * gpiod_get - obtain a GPIO for a given GPIO function
1576  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
1577  * @con_id:     function within the GPIO consumer
1578  *
1579  * Return the GPIO descriptor corresponding to the function con_id of device
1580  * dev, -ENOENT if no GPIO has been assigned to the requested function, or
1581  * another IS_ERR() code if an error occured while trying to acquire the GPIO.
1582  */
1583 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id)
1584 {
1585         return gpiod_get_index(dev, con_id, 0);
1586 }
1587 EXPORT_SYMBOL_GPL(gpiod_get);
1588
1589 /**
1590  * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
1591  * @dev: GPIO consumer, can be NULL for system-global GPIOs
1592  * @con_id: function within the GPIO consumer
1593  *
1594  * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
1595  * the requested function it will return NULL. This is convenient for drivers
1596  * that need to handle optional GPIOs.
1597  */
1598 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
1599                                                   const char *con_id)
1600 {
1601         return gpiod_get_index_optional(dev, con_id, 0);
1602 }
1603 EXPORT_SYMBOL_GPL(gpiod_get_optional);
1604
1605 /**
1606  * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
1607  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
1608  * @con_id:     function within the GPIO consumer
1609  * @idx:        index of the GPIO to obtain in the consumer
1610  *
1611  * This variant of gpiod_get() allows to access GPIOs other than the first
1612  * defined one for functions that define several GPIOs.
1613  *
1614  * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
1615  * requested function and/or index, or another IS_ERR() code if an error
1616  * occured while trying to acquire the GPIO.
1617  */
1618 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
1619                                                const char *con_id,
1620                                                unsigned int idx)
1621 {
1622         struct gpio_desc *desc = NULL;
1623         int status;
1624         enum gpio_lookup_flags flags = 0;
1625
1626         dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
1627
1628         /* Using device tree? */
1629         if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node) {
1630                 dev_dbg(dev, "using device tree for GPIO lookup\n");
1631                 desc = of_find_gpio(dev, con_id, idx, &flags);
1632         } else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev)) {
1633                 dev_dbg(dev, "using ACPI for GPIO lookup\n");
1634                 desc = acpi_find_gpio(dev, con_id, idx, &flags);
1635         }
1636
1637         /*
1638          * Either we are not using DT or ACPI, or their lookup did not return
1639          * a result. In that case, use platform lookup as a fallback.
1640          */
1641         if (!desc || desc == ERR_PTR(-ENOENT)) {
1642                 dev_dbg(dev, "using lookup tables for GPIO lookup");
1643                 desc = gpiod_find(dev, con_id, idx, &flags);
1644         }
1645
1646         if (IS_ERR(desc)) {
1647                 dev_dbg(dev, "lookup for GPIO %s failed\n", con_id);
1648                 return desc;
1649         }
1650
1651         status = gpiod_request(desc, con_id);
1652
1653         if (status < 0)
1654                 return ERR_PTR(status);
1655
1656         if (flags & GPIO_ACTIVE_LOW)
1657                 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
1658         if (flags & GPIO_OPEN_DRAIN)
1659                 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
1660         if (flags & GPIO_OPEN_SOURCE)
1661                 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
1662
1663         return desc;
1664 }
1665 EXPORT_SYMBOL_GPL(gpiod_get_index);
1666
1667 /**
1668  * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
1669  *                            function
1670  * @dev: GPIO consumer, can be NULL for system-global GPIOs
1671  * @con_id: function within the GPIO consumer
1672  * @index: index of the GPIO to obtain in the consumer
1673  *
1674  * This is equivalent to gpiod_get_index(), except that when no GPIO with the
1675  * specified index was assigned to the requested function it will return NULL.
1676  * This is convenient for drivers that need to handle optional GPIOs.
1677  */
1678 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
1679                                                         const char *con_id,
1680                                                         unsigned int index)
1681 {
1682         struct gpio_desc *desc;
1683
1684         desc = gpiod_get_index(dev, con_id, index);
1685         if (IS_ERR(desc)) {
1686                 if (PTR_ERR(desc) == -ENOENT)
1687                         return NULL;
1688         }
1689
1690         return desc;
1691 }
1692 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
1693
1694 /**
1695  * gpiod_put - dispose of a GPIO descriptor
1696  * @desc:       GPIO descriptor to dispose of
1697  *
1698  * No descriptor can be used after gpiod_put() has been called on it.
1699  */
1700 void gpiod_put(struct gpio_desc *desc)
1701 {
1702         gpiod_free(desc);
1703 }
1704 EXPORT_SYMBOL_GPL(gpiod_put);
1705
1706 #ifdef CONFIG_DEBUG_FS
1707
1708 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_chip *chip)
1709 {
1710         unsigned                i;
1711         unsigned                gpio = chip->base;
1712         struct gpio_desc        *gdesc = &chip->desc[0];
1713         int                     is_out;
1714         int                     is_irq;
1715
1716         for (i = 0; i < chip->ngpio; i++, gpio++, gdesc++) {
1717                 if (!test_bit(FLAG_REQUESTED, &gdesc->flags))
1718                         continue;
1719
1720                 gpiod_get_direction(gdesc);
1721                 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
1722                 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
1723                 seq_printf(s, " gpio-%-3d (%-20.20s) %s %s %s",
1724                         gpio, gdesc->label,
1725                         is_out ? "out" : "in ",
1726                         chip->get
1727                                 ? (chip->get(chip, i) ? "hi" : "lo")
1728                                 : "?  ",
1729                         is_irq ? "IRQ" : "   ");
1730                 seq_printf(s, "\n");
1731         }
1732 }
1733
1734 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
1735 {
1736         unsigned long flags;
1737         struct gpio_chip *chip = NULL;
1738         loff_t index = *pos;
1739
1740         s->private = "";
1741
1742         spin_lock_irqsave(&gpio_lock, flags);
1743         list_for_each_entry(chip, &gpio_chips, list)
1744                 if (index-- == 0) {
1745                         spin_unlock_irqrestore(&gpio_lock, flags);
1746                         return chip;
1747                 }
1748         spin_unlock_irqrestore(&gpio_lock, flags);
1749
1750         return NULL;
1751 }
1752
1753 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
1754 {
1755         unsigned long flags;
1756         struct gpio_chip *chip = v;
1757         void *ret = NULL;
1758
1759         spin_lock_irqsave(&gpio_lock, flags);
1760         if (list_is_last(&chip->list, &gpio_chips))
1761                 ret = NULL;
1762         else
1763                 ret = list_entry(chip->list.next, struct gpio_chip, list);
1764         spin_unlock_irqrestore(&gpio_lock, flags);
1765
1766         s->private = "\n";
1767         ++*pos;
1768
1769         return ret;
1770 }
1771
1772 static void gpiolib_seq_stop(struct seq_file *s, void *v)
1773 {
1774 }
1775
1776 static int gpiolib_seq_show(struct seq_file *s, void *v)
1777 {
1778         struct gpio_chip *chip = v;
1779         struct device *dev;
1780
1781         seq_printf(s, "%sGPIOs %d-%d", (char *)s->private,
1782                         chip->base, chip->base + chip->ngpio - 1);
1783         dev = chip->dev;
1784         if (dev)
1785                 seq_printf(s, ", %s/%s", dev->bus ? dev->bus->name : "no-bus",
1786                         dev_name(dev));
1787         if (chip->label)
1788                 seq_printf(s, ", %s", chip->label);
1789         if (chip->can_sleep)
1790                 seq_printf(s, ", can sleep");
1791         seq_printf(s, ":\n");
1792
1793         if (chip->dbg_show)
1794                 chip->dbg_show(s, chip);
1795         else
1796                 gpiolib_dbg_show(s, chip);
1797
1798         return 0;
1799 }
1800
1801 static const struct seq_operations gpiolib_seq_ops = {
1802         .start = gpiolib_seq_start,
1803         .next = gpiolib_seq_next,
1804         .stop = gpiolib_seq_stop,
1805         .show = gpiolib_seq_show,
1806 };
1807
1808 static int gpiolib_open(struct inode *inode, struct file *file)
1809 {
1810         return seq_open(file, &gpiolib_seq_ops);
1811 }
1812
1813 static const struct file_operations gpiolib_operations = {
1814         .owner          = THIS_MODULE,
1815         .open           = gpiolib_open,
1816         .read           = seq_read,
1817         .llseek         = seq_lseek,
1818         .release        = seq_release,
1819 };
1820
1821 static int __init gpiolib_debugfs_init(void)
1822 {
1823         /* /sys/kernel/debug/gpio */
1824         (void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
1825                                 NULL, NULL, &gpiolib_operations);
1826         return 0;
1827 }
1828 subsys_initcall(gpiolib_debugfs_init);
1829
1830 #endif  /* DEBUG_FS */