gpiolib: remove gpiochip_reserve()
[platform/adaptation/renesas_rcar/renesas_kernel.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/device.h>
7 #include <linux/err.h>
8 #include <linux/debugfs.h>
9 #include <linux/seq_file.h>
10 #include <linux/gpio.h>
11 #include <linux/of_gpio.h>
12 #include <linux/idr.h>
13 #include <linux/slab.h>
14
15 #define CREATE_TRACE_POINTS
16 #include <trace/events/gpio.h>
17
18 /* Optional implementation infrastructure for GPIO interfaces.
19  *
20  * Platforms may want to use this if they tend to use very many GPIOs
21  * that aren't part of a System-On-Chip core; or across I2C/SPI/etc.
22  *
23  * When kernel footprint or instruction count is an issue, simpler
24  * implementations may be preferred.  The GPIO programming interface
25  * allows for inlining speed-critical get/set operations for common
26  * cases, so that access to SOC-integrated GPIOs can sometimes cost
27  * 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 static DEFINE_SPINLOCK(gpio_lock);
48
49 struct gpio_desc {
50         struct gpio_chip        *chip;
51         unsigned long           flags;
52 /* flag symbols are bit numbers */
53 #define FLAG_REQUESTED  0
54 #define FLAG_IS_OUT     1
55 #define FLAG_EXPORT     2       /* protected by sysfs_lock */
56 #define FLAG_SYSFS      3       /* exported via /sys/class/gpio/control */
57 #define FLAG_TRIG_FALL  4       /* trigger on falling edge */
58 #define FLAG_TRIG_RISE  5       /* trigger on rising edge */
59 #define FLAG_ACTIVE_LOW 6       /* sysfs value has active low */
60 #define FLAG_OPEN_DRAIN 7       /* Gpio is open drain type */
61 #define FLAG_OPEN_SOURCE 8      /* Gpio is open source type */
62
63 #define ID_SHIFT        16      /* add new flags before this one */
64
65 #define GPIO_FLAGS_MASK         ((1 << ID_SHIFT) - 1)
66 #define GPIO_TRIGGER_MASK       (BIT(FLAG_TRIG_FALL) | BIT(FLAG_TRIG_RISE))
67
68 #ifdef CONFIG_DEBUG_FS
69         const char              *label;
70 #endif
71 };
72 static struct gpio_desc gpio_desc[ARCH_NR_GPIOS];
73
74 #ifdef CONFIG_GPIO_SYSFS
75 static DEFINE_IDR(dirent_idr);
76 #endif
77
78 static inline void desc_set_label(struct gpio_desc *d, const char *label)
79 {
80 #ifdef CONFIG_DEBUG_FS
81         d->label = label;
82 #endif
83 }
84
85 /* Warn when drivers omit gpio_request() calls -- legal but ill-advised
86  * when setting direction, and otherwise illegal.  Until board setup code
87  * and drivers use explicit requests everywhere (which won't happen when
88  * those calls have no teeth) we can't avoid autorequesting.  This nag
89  * message should motivate switching to explicit requests... so should
90  * the weaker cleanup after faults, compared to gpio_request().
91  *
92  * NOTE: the autorequest mechanism is going away; at this point it's
93  * only "legal" in the sense that (old) code using it won't break yet,
94  * but instead only triggers a WARN() stack dump.
95  */
96 static int gpio_ensure_requested(struct gpio_desc *desc, unsigned offset)
97 {
98         const struct gpio_chip *chip = desc->chip;
99         const int gpio = chip->base + offset;
100
101         if (WARN(test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0,
102                         "autorequest GPIO-%d\n", gpio)) {
103                 if (!try_module_get(chip->owner)) {
104                         pr_err("GPIO-%d: module can't be gotten \n", gpio);
105                         clear_bit(FLAG_REQUESTED, &desc->flags);
106                         /* lose */
107                         return -EIO;
108                 }
109                 desc_set_label(desc, "[auto]");
110                 /* caller must chip->request() w/o spinlock */
111                 if (chip->request)
112                         return 1;
113         }
114         return 0;
115 }
116
117 /* caller holds gpio_lock *OR* gpio is marked as requested */
118 struct gpio_chip *gpio_to_chip(unsigned gpio)
119 {
120         return gpio_desc[gpio].chip;
121 }
122
123 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
124 static int gpiochip_find_base(int ngpio)
125 {
126         int i;
127         int spare = 0;
128         int base = -ENOSPC;
129
130         for (i = ARCH_NR_GPIOS - 1; i >= 0 ; i--) {
131                 struct gpio_desc *desc = &gpio_desc[i];
132                 struct gpio_chip *chip = desc->chip;
133
134                 if (!chip) {
135                         spare++;
136                         if (spare == ngpio) {
137                                 base = i;
138                                 break;
139                         }
140                 } else {
141                         spare = 0;
142                         if (chip)
143                                 i -= chip->ngpio - 1;
144                 }
145         }
146
147         if (gpio_is_valid(base))
148                 pr_debug("%s: found new base at %d\n", __func__, base);
149         return base;
150 }
151
152 /* caller ensures gpio is valid and requested, chip->get_direction may sleep  */
153 static int gpio_get_direction(unsigned gpio)
154 {
155         struct gpio_chip        *chip;
156         struct gpio_desc        *desc = &gpio_desc[gpio];
157         int                     status = -EINVAL;
158
159         chip = gpio_to_chip(gpio);
160         gpio -= chip->base;
161
162         if (!chip->get_direction)
163                 return status;
164
165         status = chip->get_direction(chip, gpio);
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
178 #ifdef CONFIG_GPIO_SYSFS
179
180 /* lock protects against unexport_gpio() being called while
181  * sysfs files are active.
182  */
183 static DEFINE_MUTEX(sysfs_lock);
184
185 /*
186  * /sys/class/gpio/gpioN... only for GPIOs that are exported
187  *   /direction
188  *      * MAY BE OMITTED if kernel won't allow direction changes
189  *      * is read/write as "in" or "out"
190  *      * may also be written as "high" or "low", initializing
191  *        output value as specified ("out" implies "low")
192  *   /value
193  *      * always readable, subject to hardware behavior
194  *      * may be writable, as zero/nonzero
195  *   /edge
196  *      * configures behavior of poll(2) on /value
197  *      * available only if pin can generate IRQs on input
198  *      * is read/write as "none", "falling", "rising", or "both"
199  *   /active_low
200  *      * configures polarity of /value
201  *      * is read/write as zero/nonzero
202  *      * also affects existing and subsequent "falling" and "rising"
203  *        /edge configuration
204  */
205
206 static ssize_t gpio_direction_show(struct device *dev,
207                 struct device_attribute *attr, char *buf)
208 {
209         const struct gpio_desc  *desc = dev_get_drvdata(dev);
210         unsigned                gpio = desc - gpio_desc;
211         ssize_t                 status;
212
213         mutex_lock(&sysfs_lock);
214
215         if (!test_bit(FLAG_EXPORT, &desc->flags))
216                 status = -EIO;
217         else
218                 gpio_get_direction(gpio);
219                 status = sprintf(buf, "%s\n",
220                         test_bit(FLAG_IS_OUT, &desc->flags)
221                                 ? "out" : "in");
222
223         mutex_unlock(&sysfs_lock);
224         return status;
225 }
226
227 static ssize_t gpio_direction_store(struct device *dev,
228                 struct device_attribute *attr, const char *buf, size_t size)
229 {
230         const struct gpio_desc  *desc = dev_get_drvdata(dev);
231         unsigned                gpio = desc - gpio_desc;
232         ssize_t                 status;
233
234         mutex_lock(&sysfs_lock);
235
236         if (!test_bit(FLAG_EXPORT, &desc->flags))
237                 status = -EIO;
238         else if (sysfs_streq(buf, "high"))
239                 status = gpio_direction_output(gpio, 1);
240         else if (sysfs_streq(buf, "out") || sysfs_streq(buf, "low"))
241                 status = gpio_direction_output(gpio, 0);
242         else if (sysfs_streq(buf, "in"))
243                 status = gpio_direction_input(gpio);
244         else
245                 status = -EINVAL;
246
247         mutex_unlock(&sysfs_lock);
248         return status ? : size;
249 }
250
251 static /* const */ DEVICE_ATTR(direction, 0644,
252                 gpio_direction_show, gpio_direction_store);
253
254 static ssize_t gpio_value_show(struct device *dev,
255                 struct device_attribute *attr, char *buf)
256 {
257         const struct gpio_desc  *desc = dev_get_drvdata(dev);
258         unsigned                gpio = desc - gpio_desc;
259         ssize_t                 status;
260
261         mutex_lock(&sysfs_lock);
262
263         if (!test_bit(FLAG_EXPORT, &desc->flags)) {
264                 status = -EIO;
265         } else {
266                 int value;
267
268                 value = !!gpio_get_value_cansleep(gpio);
269                 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
270                         value = !value;
271
272                 status = sprintf(buf, "%d\n", value);
273         }
274
275         mutex_unlock(&sysfs_lock);
276         return status;
277 }
278
279 static ssize_t gpio_value_store(struct device *dev,
280                 struct device_attribute *attr, const char *buf, size_t size)
281 {
282         const struct gpio_desc  *desc = dev_get_drvdata(dev);
283         unsigned                gpio = desc - gpio_desc;
284         ssize_t                 status;
285
286         mutex_lock(&sysfs_lock);
287
288         if (!test_bit(FLAG_EXPORT, &desc->flags))
289                 status = -EIO;
290         else if (!test_bit(FLAG_IS_OUT, &desc->flags))
291                 status = -EPERM;
292         else {
293                 long            value;
294
295                 status = strict_strtol(buf, 0, &value);
296                 if (status == 0) {
297                         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
298                                 value = !value;
299                         gpio_set_value_cansleep(gpio, value != 0);
300                         status = size;
301                 }
302         }
303
304         mutex_unlock(&sysfs_lock);
305         return status;
306 }
307
308 static const DEVICE_ATTR(value, 0644,
309                 gpio_value_show, gpio_value_store);
310
311 static irqreturn_t gpio_sysfs_irq(int irq, void *priv)
312 {
313         struct sysfs_dirent     *value_sd = priv;
314
315         sysfs_notify_dirent(value_sd);
316         return IRQ_HANDLED;
317 }
318
319 static int gpio_setup_irq(struct gpio_desc *desc, struct device *dev,
320                 unsigned long gpio_flags)
321 {
322         struct sysfs_dirent     *value_sd;
323         unsigned long           irq_flags;
324         int                     ret, irq, id;
325
326         if ((desc->flags & GPIO_TRIGGER_MASK) == gpio_flags)
327                 return 0;
328
329         irq = gpio_to_irq(desc - gpio_desc);
330         if (irq < 0)
331                 return -EIO;
332
333         id = desc->flags >> ID_SHIFT;
334         value_sd = idr_find(&dirent_idr, id);
335         if (value_sd)
336                 free_irq(irq, value_sd);
337
338         desc->flags &= ~GPIO_TRIGGER_MASK;
339
340         if (!gpio_flags) {
341                 ret = 0;
342                 goto free_id;
343         }
344
345         irq_flags = IRQF_SHARED;
346         if (test_bit(FLAG_TRIG_FALL, &gpio_flags))
347                 irq_flags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
348                         IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
349         if (test_bit(FLAG_TRIG_RISE, &gpio_flags))
350                 irq_flags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
351                         IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
352
353         if (!value_sd) {
354                 value_sd = sysfs_get_dirent(dev->kobj.sd, NULL, "value");
355                 if (!value_sd) {
356                         ret = -ENODEV;
357                         goto err_out;
358                 }
359
360                 do {
361                         ret = -ENOMEM;
362                         if (idr_pre_get(&dirent_idr, GFP_KERNEL))
363                                 ret = idr_get_new_above(&dirent_idr, value_sd,
364                                                         1, &id);
365                 } while (ret == -EAGAIN);
366
367                 if (ret)
368                         goto free_sd;
369
370                 desc->flags &= GPIO_FLAGS_MASK;
371                 desc->flags |= (unsigned long)id << ID_SHIFT;
372
373                 if (desc->flags >> ID_SHIFT != id) {
374                         ret = -ERANGE;
375                         goto free_id;
376                 }
377         }
378
379         ret = request_any_context_irq(irq, gpio_sysfs_irq, irq_flags,
380                                 "gpiolib", value_sd);
381         if (ret < 0)
382                 goto free_id;
383
384         desc->flags |= gpio_flags;
385         return 0;
386
387 free_id:
388         idr_remove(&dirent_idr, id);
389         desc->flags &= GPIO_FLAGS_MASK;
390 free_sd:
391         if (value_sd)
392                 sysfs_put(value_sd);
393 err_out:
394         return ret;
395 }
396
397 static const struct {
398         const char *name;
399         unsigned long flags;
400 } trigger_types[] = {
401         { "none",    0 },
402         { "falling", BIT(FLAG_TRIG_FALL) },
403         { "rising",  BIT(FLAG_TRIG_RISE) },
404         { "both",    BIT(FLAG_TRIG_FALL) | BIT(FLAG_TRIG_RISE) },
405 };
406
407 static ssize_t gpio_edge_show(struct device *dev,
408                 struct device_attribute *attr, char *buf)
409 {
410         const struct gpio_desc  *desc = dev_get_drvdata(dev);
411         ssize_t                 status;
412
413         mutex_lock(&sysfs_lock);
414
415         if (!test_bit(FLAG_EXPORT, &desc->flags))
416                 status = -EIO;
417         else {
418                 int i;
419
420                 status = 0;
421                 for (i = 0; i < ARRAY_SIZE(trigger_types); i++)
422                         if ((desc->flags & GPIO_TRIGGER_MASK)
423                                         == trigger_types[i].flags) {
424                                 status = sprintf(buf, "%s\n",
425                                                  trigger_types[i].name);
426                                 break;
427                         }
428         }
429
430         mutex_unlock(&sysfs_lock);
431         return status;
432 }
433
434 static ssize_t gpio_edge_store(struct device *dev,
435                 struct device_attribute *attr, const char *buf, size_t size)
436 {
437         struct gpio_desc        *desc = dev_get_drvdata(dev);
438         ssize_t                 status;
439         int                     i;
440
441         for (i = 0; i < ARRAY_SIZE(trigger_types); i++)
442                 if (sysfs_streq(trigger_types[i].name, buf))
443                         goto found;
444         return -EINVAL;
445
446 found:
447         mutex_lock(&sysfs_lock);
448
449         if (!test_bit(FLAG_EXPORT, &desc->flags))
450                 status = -EIO;
451         else {
452                 status = gpio_setup_irq(desc, dev, trigger_types[i].flags);
453                 if (!status)
454                         status = size;
455         }
456
457         mutex_unlock(&sysfs_lock);
458
459         return status;
460 }
461
462 static DEVICE_ATTR(edge, 0644, gpio_edge_show, gpio_edge_store);
463
464 static int sysfs_set_active_low(struct gpio_desc *desc, struct device *dev,
465                                 int value)
466 {
467         int                     status = 0;
468
469         if (!!test_bit(FLAG_ACTIVE_LOW, &desc->flags) == !!value)
470                 return 0;
471
472         if (value)
473                 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
474         else
475                 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
476
477         /* reconfigure poll(2) support if enabled on one edge only */
478         if (dev != NULL && (!!test_bit(FLAG_TRIG_RISE, &desc->flags) ^
479                                 !!test_bit(FLAG_TRIG_FALL, &desc->flags))) {
480                 unsigned long trigger_flags = desc->flags & GPIO_TRIGGER_MASK;
481
482                 gpio_setup_irq(desc, dev, 0);
483                 status = gpio_setup_irq(desc, dev, trigger_flags);
484         }
485
486         return status;
487 }
488
489 static ssize_t gpio_active_low_show(struct device *dev,
490                 struct device_attribute *attr, char *buf)
491 {
492         const struct gpio_desc  *desc = dev_get_drvdata(dev);
493         ssize_t                 status;
494
495         mutex_lock(&sysfs_lock);
496
497         if (!test_bit(FLAG_EXPORT, &desc->flags))
498                 status = -EIO;
499         else
500                 status = sprintf(buf, "%d\n",
501                                 !!test_bit(FLAG_ACTIVE_LOW, &desc->flags));
502
503         mutex_unlock(&sysfs_lock);
504
505         return status;
506 }
507
508 static ssize_t gpio_active_low_store(struct device *dev,
509                 struct device_attribute *attr, const char *buf, size_t size)
510 {
511         struct gpio_desc        *desc = dev_get_drvdata(dev);
512         ssize_t                 status;
513
514         mutex_lock(&sysfs_lock);
515
516         if (!test_bit(FLAG_EXPORT, &desc->flags)) {
517                 status = -EIO;
518         } else {
519                 long            value;
520
521                 status = strict_strtol(buf, 0, &value);
522                 if (status == 0)
523                         status = sysfs_set_active_low(desc, dev, value != 0);
524         }
525
526         mutex_unlock(&sysfs_lock);
527
528         return status ? : size;
529 }
530
531 static const DEVICE_ATTR(active_low, 0644,
532                 gpio_active_low_show, gpio_active_low_store);
533
534 static const struct attribute *gpio_attrs[] = {
535         &dev_attr_value.attr,
536         &dev_attr_active_low.attr,
537         NULL,
538 };
539
540 static const struct attribute_group gpio_attr_group = {
541         .attrs = (struct attribute **) gpio_attrs,
542 };
543
544 /*
545  * /sys/class/gpio/gpiochipN/
546  *   /base ... matching gpio_chip.base (N)
547  *   /label ... matching gpio_chip.label
548  *   /ngpio ... matching gpio_chip.ngpio
549  */
550
551 static ssize_t chip_base_show(struct device *dev,
552                                struct device_attribute *attr, char *buf)
553 {
554         const struct gpio_chip  *chip = dev_get_drvdata(dev);
555
556         return sprintf(buf, "%d\n", chip->base);
557 }
558 static DEVICE_ATTR(base, 0444, chip_base_show, NULL);
559
560 static ssize_t chip_label_show(struct device *dev,
561                                struct device_attribute *attr, char *buf)
562 {
563         const struct gpio_chip  *chip = dev_get_drvdata(dev);
564
565         return sprintf(buf, "%s\n", chip->label ? : "");
566 }
567 static DEVICE_ATTR(label, 0444, chip_label_show, NULL);
568
569 static ssize_t chip_ngpio_show(struct device *dev,
570                                struct device_attribute *attr, char *buf)
571 {
572         const struct gpio_chip  *chip = dev_get_drvdata(dev);
573
574         return sprintf(buf, "%u\n", chip->ngpio);
575 }
576 static DEVICE_ATTR(ngpio, 0444, chip_ngpio_show, NULL);
577
578 static const struct attribute *gpiochip_attrs[] = {
579         &dev_attr_base.attr,
580         &dev_attr_label.attr,
581         &dev_attr_ngpio.attr,
582         NULL,
583 };
584
585 static const struct attribute_group gpiochip_attr_group = {
586         .attrs = (struct attribute **) gpiochip_attrs,
587 };
588
589 /*
590  * /sys/class/gpio/export ... write-only
591  *      integer N ... number of GPIO to export (full access)
592  * /sys/class/gpio/unexport ... write-only
593  *      integer N ... number of GPIO to unexport
594  */
595 static ssize_t export_store(struct class *class,
596                                 struct class_attribute *attr,
597                                 const char *buf, size_t len)
598 {
599         long    gpio;
600         int     status;
601
602         status = strict_strtol(buf, 0, &gpio);
603         if (status < 0)
604                 goto done;
605
606         /* No extra locking here; FLAG_SYSFS just signifies that the
607          * request and export were done by on behalf of userspace, so
608          * they may be undone on its behalf too.
609          */
610
611         status = gpio_request(gpio, "sysfs");
612         if (status < 0) {
613                 if (status == -EPROBE_DEFER)
614                         status = -ENODEV;
615                 goto done;
616         }
617         status = gpio_export(gpio, true);
618         if (status < 0)
619                 gpio_free(gpio);
620         else
621                 set_bit(FLAG_SYSFS, &gpio_desc[gpio].flags);
622
623 done:
624         if (status)
625                 pr_debug("%s: status %d\n", __func__, status);
626         return status ? : len;
627 }
628
629 static ssize_t unexport_store(struct class *class,
630                                 struct class_attribute *attr,
631                                 const char *buf, size_t len)
632 {
633         long    gpio;
634         int     status;
635
636         status = strict_strtol(buf, 0, &gpio);
637         if (status < 0)
638                 goto done;
639
640         status = -EINVAL;
641
642         /* reject bogus commands (gpio_unexport ignores them) */
643         if (!gpio_is_valid(gpio))
644                 goto done;
645
646         /* No extra locking here; FLAG_SYSFS just signifies that the
647          * request and export were done by on behalf of userspace, so
648          * they may be undone on its behalf too.
649          */
650         if (test_and_clear_bit(FLAG_SYSFS, &gpio_desc[gpio].flags)) {
651                 status = 0;
652                 gpio_free(gpio);
653         }
654 done:
655         if (status)
656                 pr_debug("%s: status %d\n", __func__, status);
657         return status ? : len;
658 }
659
660 static struct class_attribute gpio_class_attrs[] = {
661         __ATTR(export, 0200, NULL, export_store),
662         __ATTR(unexport, 0200, NULL, unexport_store),
663         __ATTR_NULL,
664 };
665
666 static struct class gpio_class = {
667         .name =         "gpio",
668         .owner =        THIS_MODULE,
669
670         .class_attrs =  gpio_class_attrs,
671 };
672
673
674 /**
675  * gpio_export - export a GPIO through sysfs
676  * @gpio: gpio to make available, already requested
677  * @direction_may_change: true if userspace may change gpio direction
678  * Context: arch_initcall or later
679  *
680  * When drivers want to make a GPIO accessible to userspace after they
681  * have requested it -- perhaps while debugging, or as part of their
682  * public interface -- they may use this routine.  If the GPIO can
683  * change direction (some can't) and the caller allows it, userspace
684  * will see "direction" sysfs attribute which may be used to change
685  * the gpio's direction.  A "value" attribute will always be provided.
686  *
687  * Returns zero on success, else an error.
688  */
689 int gpio_export(unsigned gpio, bool direction_may_change)
690 {
691         unsigned long           flags;
692         struct gpio_desc        *desc;
693         int                     status;
694         const char              *ioname = NULL;
695         struct device           *dev;
696
697         /* can't export until sysfs is available ... */
698         if (!gpio_class.p) {
699                 pr_debug("%s: called too early!\n", __func__);
700                 return -ENOENT;
701         }
702
703         if (!gpio_is_valid(gpio)) {
704                 pr_debug("%s: gpio %d is not valid\n", __func__, gpio);
705                 return -EINVAL;
706         }
707
708         mutex_lock(&sysfs_lock);
709
710         spin_lock_irqsave(&gpio_lock, flags);
711         desc = &gpio_desc[gpio];
712         if (!test_bit(FLAG_REQUESTED, &desc->flags) ||
713              test_bit(FLAG_EXPORT, &desc->flags)) {
714                 spin_unlock_irqrestore(&gpio_lock, flags);
715                 pr_debug("%s: gpio %d unavailable (requested=%d, exported=%d)\n",
716                                 __func__, gpio,
717                                 test_bit(FLAG_REQUESTED, &desc->flags),
718                                 test_bit(FLAG_EXPORT, &desc->flags));
719                 status = -EPERM;
720                 goto fail_unlock;
721         }
722
723         if (!desc->chip->direction_input || !desc->chip->direction_output)
724                 direction_may_change = false;
725         spin_unlock_irqrestore(&gpio_lock, flags);
726
727         if (desc->chip->names && desc->chip->names[gpio - desc->chip->base])
728                 ioname = desc->chip->names[gpio - desc->chip->base];
729
730         dev = device_create(&gpio_class, desc->chip->dev, MKDEV(0, 0),
731                             desc, ioname ? ioname : "gpio%u", gpio);
732         if (IS_ERR(dev)) {
733                 status = PTR_ERR(dev);
734                 goto fail_unlock;
735         }
736
737         status = sysfs_create_group(&dev->kobj, &gpio_attr_group);
738         if (status)
739                 goto fail_unregister_device;
740
741         if (direction_may_change) {
742                 status = device_create_file(dev, &dev_attr_direction);
743                 if (status)
744                         goto fail_unregister_device;
745         }
746
747         if (gpio_to_irq(gpio) >= 0 && (direction_may_change ||
748                                        !test_bit(FLAG_IS_OUT, &desc->flags))) {
749                 status = device_create_file(dev, &dev_attr_edge);
750                 if (status)
751                         goto fail_unregister_device;
752         }
753
754         set_bit(FLAG_EXPORT, &desc->flags);
755         mutex_unlock(&sysfs_lock);
756         return 0;
757
758 fail_unregister_device:
759         device_unregister(dev);
760 fail_unlock:
761         mutex_unlock(&sysfs_lock);
762         pr_debug("%s: gpio%d status %d\n", __func__, gpio, status);
763         return status;
764 }
765 EXPORT_SYMBOL_GPL(gpio_export);
766
767 static int match_export(struct device *dev, void *data)
768 {
769         return dev_get_drvdata(dev) == data;
770 }
771
772 /**
773  * gpio_export_link - create a sysfs link to an exported GPIO node
774  * @dev: device under which to create symlink
775  * @name: name of the symlink
776  * @gpio: gpio to create symlink to, already exported
777  *
778  * Set up a symlink from /sys/.../dev/name to /sys/class/gpio/gpioN
779  * node. Caller is responsible for unlinking.
780  *
781  * Returns zero on success, else an error.
782  */
783 int gpio_export_link(struct device *dev, const char *name, unsigned gpio)
784 {
785         struct gpio_desc        *desc;
786         int                     status = -EINVAL;
787
788         if (!gpio_is_valid(gpio))
789                 goto done;
790
791         mutex_lock(&sysfs_lock);
792
793         desc = &gpio_desc[gpio];
794
795         if (test_bit(FLAG_EXPORT, &desc->flags)) {
796                 struct device *tdev;
797
798                 tdev = class_find_device(&gpio_class, NULL, desc, match_export);
799                 if (tdev != NULL) {
800                         status = sysfs_create_link(&dev->kobj, &tdev->kobj,
801                                                 name);
802                 } else {
803                         status = -ENODEV;
804                 }
805         }
806
807         mutex_unlock(&sysfs_lock);
808
809 done:
810         if (status)
811                 pr_debug("%s: gpio%d status %d\n", __func__, gpio, status);
812
813         return status;
814 }
815 EXPORT_SYMBOL_GPL(gpio_export_link);
816
817
818 /**
819  * gpio_sysfs_set_active_low - set the polarity of gpio sysfs value
820  * @gpio: gpio to change
821  * @value: non-zero to use active low, i.e. inverted values
822  *
823  * Set the polarity of /sys/class/gpio/gpioN/value sysfs attribute.
824  * The GPIO does not have to be exported yet.  If poll(2) support has
825  * been enabled for either rising or falling edge, it will be
826  * reconfigured to follow the new polarity.
827  *
828  * Returns zero on success, else an error.
829  */
830 int gpio_sysfs_set_active_low(unsigned gpio, int value)
831 {
832         struct gpio_desc        *desc;
833         struct device           *dev = NULL;
834         int                     status = -EINVAL;
835
836         if (!gpio_is_valid(gpio))
837                 goto done;
838
839         mutex_lock(&sysfs_lock);
840
841         desc = &gpio_desc[gpio];
842
843         if (test_bit(FLAG_EXPORT, &desc->flags)) {
844                 dev = class_find_device(&gpio_class, NULL, desc, match_export);
845                 if (dev == NULL) {
846                         status = -ENODEV;
847                         goto unlock;
848                 }
849         }
850
851         status = sysfs_set_active_low(desc, dev, value);
852
853 unlock:
854         mutex_unlock(&sysfs_lock);
855
856 done:
857         if (status)
858                 pr_debug("%s: gpio%d status %d\n", __func__, gpio, status);
859
860         return status;
861 }
862 EXPORT_SYMBOL_GPL(gpio_sysfs_set_active_low);
863
864 /**
865  * gpio_unexport - reverse effect of gpio_export()
866  * @gpio: gpio to make unavailable
867  *
868  * This is implicit on gpio_free().
869  */
870 void gpio_unexport(unsigned gpio)
871 {
872         struct gpio_desc        *desc;
873         int                     status = 0;
874         struct device           *dev = NULL;
875
876         if (!gpio_is_valid(gpio)) {
877                 status = -EINVAL;
878                 goto done;
879         }
880
881         mutex_lock(&sysfs_lock);
882
883         desc = &gpio_desc[gpio];
884
885         if (test_bit(FLAG_EXPORT, &desc->flags)) {
886
887                 dev = class_find_device(&gpio_class, NULL, desc, match_export);
888                 if (dev) {
889                         gpio_setup_irq(desc, dev, 0);
890                         clear_bit(FLAG_EXPORT, &desc->flags);
891                 } else
892                         status = -ENODEV;
893         }
894
895         mutex_unlock(&sysfs_lock);
896         if (dev) {
897                 device_unregister(dev);
898                 put_device(dev);
899         }
900 done:
901         if (status)
902                 pr_debug("%s: gpio%d status %d\n", __func__, gpio, status);
903 }
904 EXPORT_SYMBOL_GPL(gpio_unexport);
905
906 static int gpiochip_export(struct gpio_chip *chip)
907 {
908         int             status;
909         struct device   *dev;
910
911         /* Many systems register gpio chips for SOC support very early,
912          * before driver model support is available.  In those cases we
913          * export this later, in gpiolib_sysfs_init() ... here we just
914          * verify that _some_ field of gpio_class got initialized.
915          */
916         if (!gpio_class.p)
917                 return 0;
918
919         /* use chip->base for the ID; it's already known to be unique */
920         mutex_lock(&sysfs_lock);
921         dev = device_create(&gpio_class, chip->dev, MKDEV(0, 0), chip,
922                                 "gpiochip%d", chip->base);
923         if (!IS_ERR(dev)) {
924                 status = sysfs_create_group(&dev->kobj,
925                                 &gpiochip_attr_group);
926         } else
927                 status = PTR_ERR(dev);
928         chip->exported = (status == 0);
929         mutex_unlock(&sysfs_lock);
930
931         if (status) {
932                 unsigned long   flags;
933                 unsigned        gpio;
934
935                 spin_lock_irqsave(&gpio_lock, flags);
936                 gpio = chip->base;
937                 while (gpio_desc[gpio].chip == chip)
938                         gpio_desc[gpio++].chip = NULL;
939                 spin_unlock_irqrestore(&gpio_lock, flags);
940
941                 pr_debug("%s: chip %s status %d\n", __func__,
942                                 chip->label, status);
943         }
944
945         return status;
946 }
947
948 static void gpiochip_unexport(struct gpio_chip *chip)
949 {
950         int                     status;
951         struct device           *dev;
952
953         mutex_lock(&sysfs_lock);
954         dev = class_find_device(&gpio_class, NULL, chip, match_export);
955         if (dev) {
956                 put_device(dev);
957                 device_unregister(dev);
958                 chip->exported = 0;
959                 status = 0;
960         } else
961                 status = -ENODEV;
962         mutex_unlock(&sysfs_lock);
963
964         if (status)
965                 pr_debug("%s: chip %s status %d\n", __func__,
966                                 chip->label, status);
967 }
968
969 static int __init gpiolib_sysfs_init(void)
970 {
971         int             status;
972         unsigned long   flags;
973         unsigned        gpio;
974
975         status = class_register(&gpio_class);
976         if (status < 0)
977                 return status;
978
979         /* Scan and register the gpio_chips which registered very
980          * early (e.g. before the class_register above was called).
981          *
982          * We run before arch_initcall() so chip->dev nodes can have
983          * registered, and so arch_initcall() can always gpio_export().
984          */
985         spin_lock_irqsave(&gpio_lock, flags);
986         for (gpio = 0; gpio < ARCH_NR_GPIOS; gpio++) {
987                 struct gpio_chip        *chip;
988
989                 chip = gpio_desc[gpio].chip;
990                 if (!chip || chip->exported)
991                         continue;
992
993                 spin_unlock_irqrestore(&gpio_lock, flags);
994                 status = gpiochip_export(chip);
995                 spin_lock_irqsave(&gpio_lock, flags);
996         }
997         spin_unlock_irqrestore(&gpio_lock, flags);
998
999
1000         return status;
1001 }
1002 postcore_initcall(gpiolib_sysfs_init);
1003
1004 #else
1005 static inline int gpiochip_export(struct gpio_chip *chip)
1006 {
1007         return 0;
1008 }
1009
1010 static inline void gpiochip_unexport(struct gpio_chip *chip)
1011 {
1012 }
1013
1014 #endif /* CONFIG_GPIO_SYSFS */
1015
1016 /**
1017  * gpiochip_add() - register a gpio_chip
1018  * @chip: the chip to register, with chip->base initialized
1019  * Context: potentially before irqs or kmalloc will work
1020  *
1021  * Returns a negative errno if the chip can't be registered, such as
1022  * because the chip->base is invalid or already associated with a
1023  * different chip.  Otherwise it returns zero as a success code.
1024  *
1025  * When gpiochip_add() is called very early during boot, so that GPIOs
1026  * can be freely used, the chip->dev device must be registered before
1027  * the gpio framework's arch_initcall().  Otherwise sysfs initialization
1028  * for GPIOs will fail rudely.
1029  *
1030  * If chip->base is negative, this requests dynamic assignment of
1031  * a range of valid GPIOs.
1032  */
1033 int gpiochip_add(struct gpio_chip *chip)
1034 {
1035         unsigned long   flags;
1036         int             status = 0;
1037         unsigned        id;
1038         int             base = chip->base;
1039
1040         if ((!gpio_is_valid(base) || !gpio_is_valid(base + chip->ngpio - 1))
1041                         && base >= 0) {
1042                 status = -EINVAL;
1043                 goto fail;
1044         }
1045
1046         spin_lock_irqsave(&gpio_lock, flags);
1047
1048         if (base < 0) {
1049                 base = gpiochip_find_base(chip->ngpio);
1050                 if (base < 0) {
1051                         status = base;
1052                         goto unlock;
1053                 }
1054                 chip->base = base;
1055         }
1056
1057         /* these GPIO numbers must not be managed by another gpio_chip */
1058         for (id = base; id < base + chip->ngpio; id++) {
1059                 if (gpio_desc[id].chip != NULL) {
1060                         status = -EBUSY;
1061                         break;
1062                 }
1063         }
1064         if (status == 0) {
1065                 for (id = base; id < base + chip->ngpio; id++) {
1066                         gpio_desc[id].chip = chip;
1067
1068                         /* REVISIT:  most hardware initializes GPIOs as
1069                          * inputs (often with pullups enabled) so power
1070                          * usage is minimized.  Linux code should set the
1071                          * gpio direction first thing; but until it does,
1072                          * and in case chip->get_direction is not set,
1073                          * we may expose the wrong direction in sysfs.
1074                          */
1075                         gpio_desc[id].flags = !chip->direction_input
1076                                 ? (1 << FLAG_IS_OUT)
1077                                 : 0;
1078                 }
1079         }
1080
1081 #ifdef CONFIG_PINCTRL
1082         INIT_LIST_HEAD(&chip->pin_ranges);
1083 #endif
1084
1085         of_gpiochip_add(chip);
1086
1087 unlock:
1088         spin_unlock_irqrestore(&gpio_lock, flags);
1089
1090         if (status)
1091                 goto fail;
1092
1093         status = gpiochip_export(chip);
1094         if (status)
1095                 goto fail;
1096
1097         pr_debug("gpiochip_add: registered GPIOs %d to %d on device: %s\n",
1098                 chip->base, chip->base + chip->ngpio - 1,
1099                 chip->label ? : "generic");
1100
1101         return 0;
1102 fail:
1103         /* failures here can mean systems won't boot... */
1104         pr_err("gpiochip_add: gpios %d..%d (%s) failed to register\n",
1105                 chip->base, chip->base + chip->ngpio - 1,
1106                 chip->label ? : "generic");
1107         return status;
1108 }
1109 EXPORT_SYMBOL_GPL(gpiochip_add);
1110
1111 /**
1112  * gpiochip_remove() - unregister a gpio_chip
1113  * @chip: the chip to unregister
1114  *
1115  * A gpio_chip with any GPIOs still requested may not be removed.
1116  */
1117 int gpiochip_remove(struct gpio_chip *chip)
1118 {
1119         unsigned long   flags;
1120         int             status = 0;
1121         unsigned        id;
1122
1123         spin_lock_irqsave(&gpio_lock, flags);
1124
1125         gpiochip_remove_pin_ranges(chip);
1126         of_gpiochip_remove(chip);
1127
1128         for (id = chip->base; id < chip->base + chip->ngpio; id++) {
1129                 if (test_bit(FLAG_REQUESTED, &gpio_desc[id].flags)) {
1130                         status = -EBUSY;
1131                         break;
1132                 }
1133         }
1134         if (status == 0) {
1135                 for (id = chip->base; id < chip->base + chip->ngpio; id++)
1136                         gpio_desc[id].chip = NULL;
1137         }
1138
1139         spin_unlock_irqrestore(&gpio_lock, flags);
1140
1141         if (status == 0)
1142                 gpiochip_unexport(chip);
1143
1144         return status;
1145 }
1146 EXPORT_SYMBOL_GPL(gpiochip_remove);
1147
1148 /**
1149  * gpiochip_find() - iterator for locating a specific gpio_chip
1150  * @data: data to pass to match function
1151  * @callback: Callback function to check gpio_chip
1152  *
1153  * Similar to bus_find_device.  It returns a reference to a gpio_chip as
1154  * determined by a user supplied @match callback.  The callback should return
1155  * 0 if the device doesn't match and non-zero if it does.  If the callback is
1156  * non-zero, this function will return to the caller and not iterate over any
1157  * more gpio_chips.
1158  */
1159 struct gpio_chip *gpiochip_find(void *data,
1160                                 int (*match)(struct gpio_chip *chip,
1161                                              void *data))
1162 {
1163         struct gpio_chip *chip = NULL;
1164         unsigned long flags;
1165         int i;
1166
1167         spin_lock_irqsave(&gpio_lock, flags);
1168         for (i = 0; i < ARCH_NR_GPIOS; i++) {
1169                 if (!gpio_desc[i].chip)
1170                         continue;
1171
1172                 if (match(gpio_desc[i].chip, data)) {
1173                         chip = gpio_desc[i].chip;
1174                         break;
1175                 }
1176         }
1177         spin_unlock_irqrestore(&gpio_lock, flags);
1178
1179         return chip;
1180 }
1181 EXPORT_SYMBOL_GPL(gpiochip_find);
1182
1183 #ifdef CONFIG_PINCTRL
1184
1185 /**
1186  * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
1187  * @chip: the gpiochip to add the range for
1188  * @pinctrl_name: the dev_name() of the pin controller to map to
1189  * @gpio_offset: the start offset in the current gpio_chip number space
1190  * @pin_offset: the start offset in the pin controller number space
1191  * @npins: the number of pins from the offset of each pin space (GPIO and
1192  *      pin controller) to accumulate in this range
1193  */
1194 int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
1195                            unsigned int gpio_offset, unsigned int pin_offset,
1196                            unsigned int npins)
1197 {
1198         struct gpio_pin_range *pin_range;
1199         int ret;
1200
1201         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1202         if (!pin_range) {
1203                 pr_err("%s: GPIO chip: failed to allocate pin ranges\n",
1204                                 chip->label);
1205                 return -ENOMEM;
1206         }
1207
1208         /* Use local offset as range ID */
1209         pin_range->range.id = gpio_offset;
1210         pin_range->range.gc = chip;
1211         pin_range->range.name = chip->label;
1212         pin_range->range.base = chip->base + gpio_offset;
1213         pin_range->range.pin_base = pin_offset;
1214         pin_range->range.npins = npins;
1215         pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
1216                         &pin_range->range);
1217         if (IS_ERR(pin_range->pctldev)) {
1218                 ret = PTR_ERR(pin_range->pctldev);
1219                 pr_err("%s: GPIO chip: could not create pin range\n",
1220                        chip->label);
1221                 kfree(pin_range);
1222                 return ret;
1223         }
1224         pr_debug("GPIO chip %s: created GPIO range %d->%d ==> %s PIN %d->%d\n",
1225                  chip->label, gpio_offset, gpio_offset + npins - 1,
1226                  pinctl_name,
1227                  pin_offset, pin_offset + npins - 1);
1228
1229         list_add_tail(&pin_range->node, &chip->pin_ranges);
1230
1231         return 0;
1232 }
1233 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
1234
1235 /**
1236  * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
1237  * @chip: the chip to remove all the mappings for
1238  */
1239 void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
1240 {
1241         struct gpio_pin_range *pin_range, *tmp;
1242
1243         list_for_each_entry_safe(pin_range, tmp, &chip->pin_ranges, node) {
1244                 list_del(&pin_range->node);
1245                 pinctrl_remove_gpio_range(pin_range->pctldev,
1246                                 &pin_range->range);
1247                 kfree(pin_range);
1248         }
1249 }
1250 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
1251
1252 #endif /* CONFIG_PINCTRL */
1253
1254 /* These "optional" allocation calls help prevent drivers from stomping
1255  * on each other, and help provide better diagnostics in debugfs.
1256  * They're called even less than the "set direction" calls.
1257  */
1258 int gpio_request(unsigned gpio, const char *label)
1259 {
1260         struct gpio_desc        *desc;
1261         struct gpio_chip        *chip;
1262         int                     status = -EPROBE_DEFER;
1263         unsigned long           flags;
1264
1265         spin_lock_irqsave(&gpio_lock, flags);
1266
1267         if (!gpio_is_valid(gpio)) {
1268                 status = -EINVAL;
1269                 goto done;
1270         }
1271         desc = &gpio_desc[gpio];
1272         chip = desc->chip;
1273         if (chip == NULL)
1274                 goto done;
1275
1276         if (!try_module_get(chip->owner))
1277                 goto done;
1278
1279         /* NOTE:  gpio_request() can be called in early boot,
1280          * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
1281          */
1282
1283         if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
1284                 desc_set_label(desc, label ? : "?");
1285                 status = 0;
1286         } else {
1287                 status = -EBUSY;
1288                 module_put(chip->owner);
1289                 goto done;
1290         }
1291
1292         if (chip->request) {
1293                 /* chip->request may sleep */
1294                 spin_unlock_irqrestore(&gpio_lock, flags);
1295                 status = chip->request(chip, gpio - chip->base);
1296                 spin_lock_irqsave(&gpio_lock, flags);
1297
1298                 if (status < 0) {
1299                         desc_set_label(desc, NULL);
1300                         module_put(chip->owner);
1301                         clear_bit(FLAG_REQUESTED, &desc->flags);
1302                         goto done;
1303                 }
1304         }
1305         if (chip->get_direction) {
1306                 /* chip->get_direction may sleep */
1307                 spin_unlock_irqrestore(&gpio_lock, flags);
1308                 gpio_get_direction(gpio);
1309                 spin_lock_irqsave(&gpio_lock, flags);
1310         }
1311 done:
1312         if (status)
1313                 pr_debug("gpio_request: gpio-%d (%s) status %d\n",
1314                         gpio, label ? : "?", status);
1315         spin_unlock_irqrestore(&gpio_lock, flags);
1316         return status;
1317 }
1318 EXPORT_SYMBOL_GPL(gpio_request);
1319
1320 void gpio_free(unsigned gpio)
1321 {
1322         unsigned long           flags;
1323         struct gpio_desc        *desc;
1324         struct gpio_chip        *chip;
1325
1326         might_sleep();
1327
1328         if (!gpio_is_valid(gpio)) {
1329                 WARN_ON(extra_checks);
1330                 return;
1331         }
1332
1333         gpio_unexport(gpio);
1334
1335         spin_lock_irqsave(&gpio_lock, flags);
1336
1337         desc = &gpio_desc[gpio];
1338         chip = desc->chip;
1339         if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
1340                 if (chip->free) {
1341                         spin_unlock_irqrestore(&gpio_lock, flags);
1342                         might_sleep_if(chip->can_sleep);
1343                         chip->free(chip, gpio - chip->base);
1344                         spin_lock_irqsave(&gpio_lock, flags);
1345                 }
1346                 desc_set_label(desc, NULL);
1347                 module_put(desc->chip->owner);
1348                 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
1349                 clear_bit(FLAG_REQUESTED, &desc->flags);
1350                 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
1351                 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
1352         } else
1353                 WARN_ON(extra_checks);
1354
1355         spin_unlock_irqrestore(&gpio_lock, flags);
1356 }
1357 EXPORT_SYMBOL_GPL(gpio_free);
1358
1359 /**
1360  * gpio_request_one - request a single GPIO with initial configuration
1361  * @gpio:       the GPIO number
1362  * @flags:      GPIO configuration as specified by GPIOF_*
1363  * @label:      a literal description string of this GPIO
1364  */
1365 int gpio_request_one(unsigned gpio, unsigned long flags, const char *label)
1366 {
1367         int err;
1368
1369         err = gpio_request(gpio, label);
1370         if (err)
1371                 return err;
1372
1373         if (flags & GPIOF_OPEN_DRAIN)
1374                 set_bit(FLAG_OPEN_DRAIN, &gpio_desc[gpio].flags);
1375
1376         if (flags & GPIOF_OPEN_SOURCE)
1377                 set_bit(FLAG_OPEN_SOURCE, &gpio_desc[gpio].flags);
1378
1379         if (flags & GPIOF_DIR_IN)
1380                 err = gpio_direction_input(gpio);
1381         else
1382                 err = gpio_direction_output(gpio,
1383                                 (flags & GPIOF_INIT_HIGH) ? 1 : 0);
1384
1385         if (err)
1386                 goto free_gpio;
1387
1388         if (flags & GPIOF_EXPORT) {
1389                 err = gpio_export(gpio, flags & GPIOF_EXPORT_CHANGEABLE);
1390                 if (err)
1391                         goto free_gpio;
1392         }
1393
1394         return 0;
1395
1396  free_gpio:
1397         gpio_free(gpio);
1398         return err;
1399 }
1400 EXPORT_SYMBOL_GPL(gpio_request_one);
1401
1402 /**
1403  * gpio_request_array - request multiple GPIOs in a single call
1404  * @array:      array of the 'struct gpio'
1405  * @num:        how many GPIOs in the array
1406  */
1407 int gpio_request_array(const struct gpio *array, size_t num)
1408 {
1409         int i, err;
1410
1411         for (i = 0; i < num; i++, array++) {
1412                 err = gpio_request_one(array->gpio, array->flags, array->label);
1413                 if (err)
1414                         goto err_free;
1415         }
1416         return 0;
1417
1418 err_free:
1419         while (i--)
1420                 gpio_free((--array)->gpio);
1421         return err;
1422 }
1423 EXPORT_SYMBOL_GPL(gpio_request_array);
1424
1425 /**
1426  * gpio_free_array - release multiple GPIOs in a single call
1427  * @array:      array of the 'struct gpio'
1428  * @num:        how many GPIOs in the array
1429  */
1430 void gpio_free_array(const struct gpio *array, size_t num)
1431 {
1432         while (num--)
1433                 gpio_free((array++)->gpio);
1434 }
1435 EXPORT_SYMBOL_GPL(gpio_free_array);
1436
1437 /**
1438  * gpiochip_is_requested - return string iff signal was requested
1439  * @chip: controller managing the signal
1440  * @offset: of signal within controller's 0..(ngpio - 1) range
1441  *
1442  * Returns NULL if the GPIO is not currently requested, else a string.
1443  * If debugfs support is enabled, the string returned is the label passed
1444  * to gpio_request(); otherwise it is a meaningless constant.
1445  *
1446  * This function is for use by GPIO controller drivers.  The label can
1447  * help with diagnostics, and knowing that the signal is used as a GPIO
1448  * can help avoid accidentally multiplexing it to another controller.
1449  */
1450 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
1451 {
1452         unsigned gpio = chip->base + offset;
1453
1454         if (!gpio_is_valid(gpio) || gpio_desc[gpio].chip != chip)
1455                 return NULL;
1456         if (test_bit(FLAG_REQUESTED, &gpio_desc[gpio].flags) == 0)
1457                 return NULL;
1458 #ifdef CONFIG_DEBUG_FS
1459         return gpio_desc[gpio].label;
1460 #else
1461         return "?";
1462 #endif
1463 }
1464 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
1465
1466
1467 /* Drivers MUST set GPIO direction before making get/set calls.  In
1468  * some cases this is done in early boot, before IRQs are enabled.
1469  *
1470  * As a rule these aren't called more than once (except for drivers
1471  * using the open-drain emulation idiom) so these are natural places
1472  * to accumulate extra debugging checks.  Note that we can't (yet)
1473  * rely on gpio_request() having been called beforehand.
1474  */
1475
1476 int gpio_direction_input(unsigned gpio)
1477 {
1478         unsigned long           flags;
1479         struct gpio_chip        *chip;
1480         struct gpio_desc        *desc = &gpio_desc[gpio];
1481         int                     status = -EINVAL;
1482
1483         spin_lock_irqsave(&gpio_lock, flags);
1484
1485         if (!gpio_is_valid(gpio))
1486                 goto fail;
1487         chip = desc->chip;
1488         if (!chip || !chip->get || !chip->direction_input)
1489                 goto fail;
1490         gpio -= chip->base;
1491         if (gpio >= chip->ngpio)
1492                 goto fail;
1493         status = gpio_ensure_requested(desc, gpio);
1494         if (status < 0)
1495                 goto fail;
1496
1497         /* now we know the gpio is valid and chip won't vanish */
1498
1499         spin_unlock_irqrestore(&gpio_lock, flags);
1500
1501         might_sleep_if(chip->can_sleep);
1502
1503         if (status) {
1504                 status = chip->request(chip, gpio);
1505                 if (status < 0) {
1506                         pr_debug("GPIO-%d: chip request fail, %d\n",
1507                                 chip->base + gpio, status);
1508                         /* and it's not available to anyone else ...
1509                          * gpio_request() is the fully clean solution.
1510                          */
1511                         goto lose;
1512                 }
1513         }
1514
1515         status = chip->direction_input(chip, gpio);
1516         if (status == 0)
1517                 clear_bit(FLAG_IS_OUT, &desc->flags);
1518
1519         trace_gpio_direction(chip->base + gpio, 1, status);
1520 lose:
1521         return status;
1522 fail:
1523         spin_unlock_irqrestore(&gpio_lock, flags);
1524         if (status)
1525                 pr_debug("%s: gpio-%d status %d\n",
1526                         __func__, gpio, status);
1527         return status;
1528 }
1529 EXPORT_SYMBOL_GPL(gpio_direction_input);
1530
1531 int gpio_direction_output(unsigned gpio, int value)
1532 {
1533         unsigned long           flags;
1534         struct gpio_chip        *chip;
1535         struct gpio_desc        *desc = &gpio_desc[gpio];
1536         int                     status = -EINVAL;
1537
1538         /* Open drain pin should not be driven to 1 */
1539         if (value && test_bit(FLAG_OPEN_DRAIN,  &desc->flags))
1540                 return gpio_direction_input(gpio);
1541
1542         /* Open source pin should not be driven to 0 */
1543         if (!value && test_bit(FLAG_OPEN_SOURCE,  &desc->flags))
1544                 return gpio_direction_input(gpio);
1545
1546         spin_lock_irqsave(&gpio_lock, flags);
1547
1548         if (!gpio_is_valid(gpio))
1549                 goto fail;
1550         chip = desc->chip;
1551         if (!chip || !chip->set || !chip->direction_output)
1552                 goto fail;
1553         gpio -= chip->base;
1554         if (gpio >= chip->ngpio)
1555                 goto fail;
1556         status = gpio_ensure_requested(desc, gpio);
1557         if (status < 0)
1558                 goto fail;
1559
1560         /* now we know the gpio is valid and chip won't vanish */
1561
1562         spin_unlock_irqrestore(&gpio_lock, flags);
1563
1564         might_sleep_if(chip->can_sleep);
1565
1566         if (status) {
1567                 status = chip->request(chip, gpio);
1568                 if (status < 0) {
1569                         pr_debug("GPIO-%d: chip request fail, %d\n",
1570                                 chip->base + gpio, status);
1571                         /* and it's not available to anyone else ...
1572                          * gpio_request() is the fully clean solution.
1573                          */
1574                         goto lose;
1575                 }
1576         }
1577
1578         status = chip->direction_output(chip, gpio, value);
1579         if (status == 0)
1580                 set_bit(FLAG_IS_OUT, &desc->flags);
1581         trace_gpio_value(chip->base + gpio, 0, value);
1582         trace_gpio_direction(chip->base + gpio, 0, status);
1583 lose:
1584         return status;
1585 fail:
1586         spin_unlock_irqrestore(&gpio_lock, flags);
1587         if (status)
1588                 pr_debug("%s: gpio-%d status %d\n",
1589                         __func__, gpio, status);
1590         return status;
1591 }
1592 EXPORT_SYMBOL_GPL(gpio_direction_output);
1593
1594 /**
1595  * gpio_set_debounce - sets @debounce time for a @gpio
1596  * @gpio: the gpio to set debounce time
1597  * @debounce: debounce time is microseconds
1598  */
1599 int gpio_set_debounce(unsigned gpio, unsigned debounce)
1600 {
1601         unsigned long           flags;
1602         struct gpio_chip        *chip;
1603         struct gpio_desc        *desc = &gpio_desc[gpio];
1604         int                     status = -EINVAL;
1605
1606         spin_lock_irqsave(&gpio_lock, flags);
1607
1608         if (!gpio_is_valid(gpio))
1609                 goto fail;
1610         chip = desc->chip;
1611         if (!chip || !chip->set || !chip->set_debounce)
1612                 goto fail;
1613         gpio -= chip->base;
1614         if (gpio >= chip->ngpio)
1615                 goto fail;
1616         status = gpio_ensure_requested(desc, gpio);
1617         if (status < 0)
1618                 goto fail;
1619
1620         /* now we know the gpio is valid and chip won't vanish */
1621
1622         spin_unlock_irqrestore(&gpio_lock, flags);
1623
1624         might_sleep_if(chip->can_sleep);
1625
1626         return chip->set_debounce(chip, gpio, debounce);
1627
1628 fail:
1629         spin_unlock_irqrestore(&gpio_lock, flags);
1630         if (status)
1631                 pr_debug("%s: gpio-%d status %d\n",
1632                         __func__, gpio, status);
1633
1634         return status;
1635 }
1636 EXPORT_SYMBOL_GPL(gpio_set_debounce);
1637
1638 /* I/O calls are only valid after configuration completed; the relevant
1639  * "is this a valid GPIO" error checks should already have been done.
1640  *
1641  * "Get" operations are often inlinable as reading a pin value register,
1642  * and masking the relevant bit in that register.
1643  *
1644  * When "set" operations are inlinable, they involve writing that mask to
1645  * one register to set a low value, or a different register to set it high.
1646  * Otherwise locking is needed, so there may be little value to inlining.
1647  *
1648  *------------------------------------------------------------------------
1649  *
1650  * IMPORTANT!!!  The hot paths -- get/set value -- assume that callers
1651  * have requested the GPIO.  That can include implicit requesting by
1652  * a direction setting call.  Marking a gpio as requested locks its chip
1653  * in memory, guaranteeing that these table lookups need no more locking
1654  * and that gpiochip_remove() will fail.
1655  *
1656  * REVISIT when debugging, consider adding some instrumentation to ensure
1657  * that the GPIO was actually requested.
1658  */
1659
1660 /**
1661  * __gpio_get_value() - return a gpio's value
1662  * @gpio: gpio whose value will be returned
1663  * Context: any
1664  *
1665  * This is used directly or indirectly to implement gpio_get_value().
1666  * It returns the zero or nonzero value provided by the associated
1667  * gpio_chip.get() method; or zero if no such method is provided.
1668  */
1669 int __gpio_get_value(unsigned gpio)
1670 {
1671         struct gpio_chip        *chip;
1672         int value;
1673
1674         chip = gpio_to_chip(gpio);
1675         /* Should be using gpio_get_value_cansleep() */
1676         WARN_ON(chip->can_sleep);
1677         value = chip->get ? chip->get(chip, gpio - chip->base) : 0;
1678         trace_gpio_value(gpio, 1, value);
1679         return value;
1680 }
1681 EXPORT_SYMBOL_GPL(__gpio_get_value);
1682
1683 /*
1684  *  _gpio_set_open_drain_value() - Set the open drain gpio's value.
1685  * @gpio: Gpio whose state need to be set.
1686  * @chip: Gpio chip.
1687  * @value: Non-zero for setting it HIGH otherise it will set to LOW.
1688  */
1689 static void _gpio_set_open_drain_value(unsigned gpio,
1690                         struct gpio_chip *chip, int value)
1691 {
1692         int err = 0;
1693         if (value) {
1694                 err = chip->direction_input(chip, gpio - chip->base);
1695                 if (!err)
1696                         clear_bit(FLAG_IS_OUT, &gpio_desc[gpio].flags);
1697         } else {
1698                 err = chip->direction_output(chip, gpio - chip->base, 0);
1699                 if (!err)
1700                         set_bit(FLAG_IS_OUT, &gpio_desc[gpio].flags);
1701         }
1702         trace_gpio_direction(gpio, value, err);
1703         if (err < 0)
1704                 pr_err("%s: Error in set_value for open drain gpio%d err %d\n",
1705                                         __func__, gpio, err);
1706 }
1707
1708 /*
1709  *  _gpio_set_open_source() - Set the open source gpio's value.
1710  * @gpio: Gpio whose state need to be set.
1711  * @chip: Gpio chip.
1712  * @value: Non-zero for setting it HIGH otherise it will set to LOW.
1713  */
1714 static void _gpio_set_open_source_value(unsigned gpio,
1715                         struct gpio_chip *chip, int value)
1716 {
1717         int err = 0;
1718         if (value) {
1719                 err = chip->direction_output(chip, gpio - chip->base, 1);
1720                 if (!err)
1721                         set_bit(FLAG_IS_OUT, &gpio_desc[gpio].flags);
1722         } else {
1723                 err = chip->direction_input(chip, gpio - chip->base);
1724                 if (!err)
1725                         clear_bit(FLAG_IS_OUT, &gpio_desc[gpio].flags);
1726         }
1727         trace_gpio_direction(gpio, !value, err);
1728         if (err < 0)
1729                 pr_err("%s: Error in set_value for open source gpio%d err %d\n",
1730                                         __func__, gpio, err);
1731 }
1732
1733
1734 /**
1735  * __gpio_set_value() - assign a gpio's value
1736  * @gpio: gpio whose value will be assigned
1737  * @value: value to assign
1738  * Context: any
1739  *
1740  * This is used directly or indirectly to implement gpio_set_value().
1741  * It invokes the associated gpio_chip.set() method.
1742  */
1743 void __gpio_set_value(unsigned gpio, int value)
1744 {
1745         struct gpio_chip        *chip;
1746
1747         chip = gpio_to_chip(gpio);
1748         /* Should be using gpio_set_value_cansleep() */
1749         WARN_ON(chip->can_sleep);
1750         trace_gpio_value(gpio, 0, value);
1751         if (test_bit(FLAG_OPEN_DRAIN,  &gpio_desc[gpio].flags))
1752                 _gpio_set_open_drain_value(gpio, chip, value);
1753         else if (test_bit(FLAG_OPEN_SOURCE,  &gpio_desc[gpio].flags))
1754                 _gpio_set_open_source_value(gpio, chip, value);
1755         else
1756                 chip->set(chip, gpio - chip->base, value);
1757 }
1758 EXPORT_SYMBOL_GPL(__gpio_set_value);
1759
1760 /**
1761  * __gpio_cansleep() - report whether gpio value access will sleep
1762  * @gpio: gpio in question
1763  * Context: any
1764  *
1765  * This is used directly or indirectly to implement gpio_cansleep().  It
1766  * returns nonzero if access reading or writing the GPIO value can sleep.
1767  */
1768 int __gpio_cansleep(unsigned gpio)
1769 {
1770         struct gpio_chip        *chip;
1771
1772         /* only call this on GPIOs that are valid! */
1773         chip = gpio_to_chip(gpio);
1774
1775         return chip->can_sleep;
1776 }
1777 EXPORT_SYMBOL_GPL(__gpio_cansleep);
1778
1779 /**
1780  * __gpio_to_irq() - return the IRQ corresponding to a GPIO
1781  * @gpio: gpio whose IRQ will be returned (already requested)
1782  * Context: any
1783  *
1784  * This is used directly or indirectly to implement gpio_to_irq().
1785  * It returns the number of the IRQ signaled by this (input) GPIO,
1786  * or a negative errno.
1787  */
1788 int __gpio_to_irq(unsigned gpio)
1789 {
1790         struct gpio_chip        *chip;
1791
1792         chip = gpio_to_chip(gpio);
1793         return chip->to_irq ? chip->to_irq(chip, gpio - chip->base) : -ENXIO;
1794 }
1795 EXPORT_SYMBOL_GPL(__gpio_to_irq);
1796
1797
1798
1799 /* There's no value in making it easy to inline GPIO calls that may sleep.
1800  * Common examples include ones connected to I2C or SPI chips.
1801  */
1802
1803 int gpio_get_value_cansleep(unsigned gpio)
1804 {
1805         struct gpio_chip        *chip;
1806         int value;
1807
1808         might_sleep_if(extra_checks);
1809         chip = gpio_to_chip(gpio);
1810         value = chip->get ? chip->get(chip, gpio - chip->base) : 0;
1811         trace_gpio_value(gpio, 1, value);
1812         return value;
1813 }
1814 EXPORT_SYMBOL_GPL(gpio_get_value_cansleep);
1815
1816 void gpio_set_value_cansleep(unsigned gpio, int value)
1817 {
1818         struct gpio_chip        *chip;
1819
1820         might_sleep_if(extra_checks);
1821         chip = gpio_to_chip(gpio);
1822         trace_gpio_value(gpio, 0, value);
1823         if (test_bit(FLAG_OPEN_DRAIN,  &gpio_desc[gpio].flags))
1824                 _gpio_set_open_drain_value(gpio, chip, value);
1825         else if (test_bit(FLAG_OPEN_SOURCE,  &gpio_desc[gpio].flags))
1826                 _gpio_set_open_source_value(gpio, chip, value);
1827         else
1828                 chip->set(chip, gpio - chip->base, value);
1829 }
1830 EXPORT_SYMBOL_GPL(gpio_set_value_cansleep);
1831
1832
1833 #ifdef CONFIG_DEBUG_FS
1834
1835 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_chip *chip)
1836 {
1837         unsigned                i;
1838         unsigned                gpio = chip->base;
1839         struct gpio_desc        *gdesc = &gpio_desc[gpio];
1840         int                     is_out;
1841
1842         for (i = 0; i < chip->ngpio; i++, gpio++, gdesc++) {
1843                 if (!test_bit(FLAG_REQUESTED, &gdesc->flags))
1844                         continue;
1845
1846                 gpio_get_direction(gpio);
1847                 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
1848                 seq_printf(s, " gpio-%-3d (%-20.20s) %s %s",
1849                         gpio, gdesc->label,
1850                         is_out ? "out" : "in ",
1851                         chip->get
1852                                 ? (chip->get(chip, i) ? "hi" : "lo")
1853                                 : "?  ");
1854                 seq_printf(s, "\n");
1855         }
1856 }
1857
1858 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
1859 {
1860         struct gpio_chip *chip = NULL;
1861         unsigned int gpio;
1862         void *ret = NULL;
1863         loff_t index = 0;
1864
1865         /* REVISIT this isn't locked against gpio_chip removal ... */
1866
1867         for (gpio = 0; gpio_is_valid(gpio); gpio++) {
1868                 if (gpio_desc[gpio].chip == chip)
1869                         continue;
1870
1871                 chip = gpio_desc[gpio].chip;
1872                 if (!chip)
1873                         continue;
1874
1875                 if (index++ >= *pos) {
1876                         ret = chip;
1877                         break;
1878                 }
1879         }
1880
1881         s->private = "";
1882
1883         return ret;
1884 }
1885
1886 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
1887 {
1888         struct gpio_chip *chip = v;
1889         unsigned int gpio;
1890         void *ret = NULL;
1891
1892         /* skip GPIOs provided by the current chip */
1893         for (gpio = chip->base + chip->ngpio; gpio_is_valid(gpio); gpio++) {
1894                 chip = gpio_desc[gpio].chip;
1895                 if (chip) {
1896                         ret = chip;
1897                         break;
1898                 }
1899         }
1900
1901         s->private = "\n";
1902         ++*pos;
1903
1904         return ret;
1905 }
1906
1907 static void gpiolib_seq_stop(struct seq_file *s, void *v)
1908 {
1909 }
1910
1911 static int gpiolib_seq_show(struct seq_file *s, void *v)
1912 {
1913         struct gpio_chip *chip = v;
1914         struct device *dev;
1915
1916         seq_printf(s, "%sGPIOs %d-%d", (char *)s->private,
1917                         chip->base, chip->base + chip->ngpio - 1);
1918         dev = chip->dev;
1919         if (dev)
1920                 seq_printf(s, ", %s/%s", dev->bus ? dev->bus->name : "no-bus",
1921                         dev_name(dev));
1922         if (chip->label)
1923                 seq_printf(s, ", %s", chip->label);
1924         if (chip->can_sleep)
1925                 seq_printf(s, ", can sleep");
1926         seq_printf(s, ":\n");
1927
1928         if (chip->dbg_show)
1929                 chip->dbg_show(s, chip);
1930         else
1931                 gpiolib_dbg_show(s, chip);
1932
1933         return 0;
1934 }
1935
1936 static const struct seq_operations gpiolib_seq_ops = {
1937         .start = gpiolib_seq_start,
1938         .next = gpiolib_seq_next,
1939         .stop = gpiolib_seq_stop,
1940         .show = gpiolib_seq_show,
1941 };
1942
1943 static int gpiolib_open(struct inode *inode, struct file *file)
1944 {
1945         return seq_open(file, &gpiolib_seq_ops);
1946 }
1947
1948 static const struct file_operations gpiolib_operations = {
1949         .owner          = THIS_MODULE,
1950         .open           = gpiolib_open,
1951         .read           = seq_read,
1952         .llseek         = seq_lseek,
1953         .release        = seq_release,
1954 };
1955
1956 static int __init gpiolib_debugfs_init(void)
1957 {
1958         /* /sys/kernel/debug/gpio */
1959         (void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
1960                                 NULL, NULL, &gpiolib_operations);
1961         return 0;
1962 }
1963 subsys_initcall(gpiolib_debugfs_init);
1964
1965 #endif  /* DEBUG_FS */