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