gpiolib: allow GPIOs to be named
[linux-2.6] / drivers / gpio / gpiolib.c
1 #include <linux/kernel.h>
2 #include <linux/module.h>
3 #include <linux/irq.h>
4 #include <linux/spinlock.h>
5 #include <linux/device.h>
6 #include <linux/err.h>
7 #include <linux/debugfs.h>
8 #include <linux/seq_file.h>
9 #include <linux/gpio.h>
10
11
12 /* Optional implementation infrastructure for GPIO interfaces.
13  *
14  * Platforms may want to use this if they tend to use very many GPIOs
15  * that aren't part of a System-On-Chip core; or across I2C/SPI/etc.
16  *
17  * When kernel footprint or instruction count is an issue, simpler
18  * implementations may be preferred.  The GPIO programming interface
19  * allows for inlining speed-critical get/set operations for common
20  * cases, so that access to SOC-integrated GPIOs can sometimes cost
21  * only an instruction or two per bit.
22  */
23
24
25 /* When debugging, extend minimal trust to callers and platform code.
26  * Also emit diagnostic messages that may help initial bringup, when
27  * board setup or driver bugs are most common.
28  *
29  * Otherwise, minimize overhead in what may be bitbanging codepaths.
30  */
31 #ifdef  DEBUG
32 #define extra_checks    1
33 #else
34 #define extra_checks    0
35 #endif
36
37 /* gpio_lock prevents conflicts during gpio_desc[] table updates.
38  * While any GPIO is requested, its gpio_chip is not removable;
39  * each GPIO's "requested" flag serves as a lock and refcount.
40  */
41 static DEFINE_SPINLOCK(gpio_lock);
42
43 struct gpio_desc {
44         struct gpio_chip        *chip;
45         unsigned long           flags;
46 /* flag symbols are bit numbers */
47 #define FLAG_REQUESTED  0
48 #define FLAG_IS_OUT     1
49 #define FLAG_RESERVED   2
50 #define FLAG_EXPORT     3       /* protected by sysfs_lock */
51 #define FLAG_SYSFS      4       /* exported via /sys/class/gpio/control */
52
53 #ifdef CONFIG_DEBUG_FS
54         const char              *label;
55 #endif
56 };
57 static struct gpio_desc gpio_desc[ARCH_NR_GPIOS];
58
59 static inline void desc_set_label(struct gpio_desc *d, const char *label)
60 {
61 #ifdef CONFIG_DEBUG_FS
62         d->label = label;
63 #endif
64 }
65
66 /* Warn when drivers omit gpio_request() calls -- legal but ill-advised
67  * when setting direction, and otherwise illegal.  Until board setup code
68  * and drivers use explicit requests everywhere (which won't happen when
69  * those calls have no teeth) we can't avoid autorequesting.  This nag
70  * message should motivate switching to explicit requests... so should
71  * the weaker cleanup after faults, compared to gpio_request().
72  */
73 static int gpio_ensure_requested(struct gpio_desc *desc, unsigned offset)
74 {
75         if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
76                 struct gpio_chip *chip = desc->chip;
77                 int gpio = chip->base + offset;
78
79                 if (!try_module_get(chip->owner)) {
80                         pr_err("GPIO-%d: module can't be gotten \n", gpio);
81                         clear_bit(FLAG_REQUESTED, &desc->flags);
82                         /* lose */
83                         return -EIO;
84                 }
85                 pr_warning("GPIO-%d autorequested\n", gpio);
86                 desc_set_label(desc, "[auto]");
87                 /* caller must chip->request() w/o spinlock */
88                 if (chip->request)
89                         return 1;
90         }
91         return 0;
92 }
93
94 /* caller holds gpio_lock *OR* gpio is marked as requested */
95 static inline struct gpio_chip *gpio_to_chip(unsigned gpio)
96 {
97         return gpio_desc[gpio].chip;
98 }
99
100 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
101 static int gpiochip_find_base(int ngpio)
102 {
103         int i;
104         int spare = 0;
105         int base = -ENOSPC;
106
107         for (i = ARCH_NR_GPIOS - 1; i >= 0 ; i--) {
108                 struct gpio_desc *desc = &gpio_desc[i];
109                 struct gpio_chip *chip = desc->chip;
110
111                 if (!chip && !test_bit(FLAG_RESERVED, &desc->flags)) {
112                         spare++;
113                         if (spare == ngpio) {
114                                 base = i;
115                                 break;
116                         }
117                 } else {
118                         spare = 0;
119                         if (chip)
120                                 i -= chip->ngpio - 1;
121                 }
122         }
123
124         if (gpio_is_valid(base))
125                 pr_debug("%s: found new base at %d\n", __func__, base);
126         return base;
127 }
128
129 /**
130  * gpiochip_reserve() - reserve range of gpios to use with platform code only
131  * @start: starting gpio number
132  * @ngpio: number of gpios to reserve
133  * Context: platform init, potentially before irqs or kmalloc will work
134  *
135  * Returns a negative errno if any gpio within the range is already reserved
136  * or registered, else returns zero as a success code.  Use this function
137  * to mark a range of gpios as unavailable for dynamic gpio number allocation,
138  * for example because its driver support is not yet loaded.
139  */
140 int __init gpiochip_reserve(int start, int ngpio)
141 {
142         int ret = 0;
143         unsigned long flags;
144         int i;
145
146         if (!gpio_is_valid(start) || !gpio_is_valid(start + ngpio - 1))
147                 return -EINVAL;
148
149         spin_lock_irqsave(&gpio_lock, flags);
150
151         for (i = start; i < start + ngpio; i++) {
152                 struct gpio_desc *desc = &gpio_desc[i];
153
154                 if (desc->chip || test_bit(FLAG_RESERVED, &desc->flags)) {
155                         ret = -EBUSY;
156                         goto err;
157                 }
158
159                 set_bit(FLAG_RESERVED, &desc->flags);
160         }
161
162         pr_debug("%s: reserved gpios from %d to %d\n",
163                  __func__, start, start + ngpio - 1);
164 err:
165         spin_unlock_irqrestore(&gpio_lock, flags);
166
167         return ret;
168 }
169
170 #ifdef CONFIG_GPIO_SYSFS
171
172 /* lock protects against unexport_gpio() being called while
173  * sysfs files are active.
174  */
175 static DEFINE_MUTEX(sysfs_lock);
176
177 /*
178  * /sys/class/gpio/gpioN... only for GPIOs that are exported
179  *   /direction
180  *      * MAY BE OMITTED if kernel won't allow direction changes
181  *      * is read/write as "in" or "out"
182  *      * may also be written as "high" or "low", initializing
183  *        output value as specified ("out" implies "low")
184  *   /value
185  *      * always readable, subject to hardware behavior
186  *      * may be writable, as zero/nonzero
187  *
188  * REVISIT there will likely be an attribute for configuring async
189  * notifications, e.g. to specify polling interval or IRQ trigger type
190  * that would for example trigger a poll() on the "value".
191  */
192
193 static ssize_t gpio_direction_show(struct device *dev,
194                 struct device_attribute *attr, char *buf)
195 {
196         const struct gpio_desc  *desc = dev_get_drvdata(dev);
197         ssize_t                 status;
198
199         mutex_lock(&sysfs_lock);
200
201         if (!test_bit(FLAG_EXPORT, &desc->flags))
202                 status = -EIO;
203         else
204                 status = sprintf(buf, "%s\n",
205                         test_bit(FLAG_IS_OUT, &desc->flags)
206                                 ? "out" : "in");
207
208         mutex_unlock(&sysfs_lock);
209         return status;
210 }
211
212 static ssize_t gpio_direction_store(struct device *dev,
213                 struct device_attribute *attr, const char *buf, size_t size)
214 {
215         const struct gpio_desc  *desc = dev_get_drvdata(dev);
216         unsigned                gpio = desc - gpio_desc;
217         ssize_t                 status;
218
219         mutex_lock(&sysfs_lock);
220
221         if (!test_bit(FLAG_EXPORT, &desc->flags))
222                 status = -EIO;
223         else if (sysfs_streq(buf, "high"))
224                 status = gpio_direction_output(gpio, 1);
225         else if (sysfs_streq(buf, "out") || sysfs_streq(buf, "low"))
226                 status = gpio_direction_output(gpio, 0);
227         else if (sysfs_streq(buf, "in"))
228                 status = gpio_direction_input(gpio);
229         else
230                 status = -EINVAL;
231
232         mutex_unlock(&sysfs_lock);
233         return status ? : size;
234 }
235
236 static const DEVICE_ATTR(direction, 0644,
237                 gpio_direction_show, gpio_direction_store);
238
239 static ssize_t gpio_value_show(struct device *dev,
240                 struct device_attribute *attr, char *buf)
241 {
242         const struct gpio_desc  *desc = dev_get_drvdata(dev);
243         unsigned                gpio = desc - gpio_desc;
244         ssize_t                 status;
245
246         mutex_lock(&sysfs_lock);
247
248         if (!test_bit(FLAG_EXPORT, &desc->flags))
249                 status = -EIO;
250         else
251                 status = sprintf(buf, "%d\n", !!gpio_get_value_cansleep(gpio));
252
253         mutex_unlock(&sysfs_lock);
254         return status;
255 }
256
257 static ssize_t gpio_value_store(struct device *dev,
258                 struct device_attribute *attr, const char *buf, size_t size)
259 {
260         const struct gpio_desc  *desc = dev_get_drvdata(dev);
261         unsigned                gpio = desc - gpio_desc;
262         ssize_t                 status;
263
264         mutex_lock(&sysfs_lock);
265
266         if (!test_bit(FLAG_EXPORT, &desc->flags))
267                 status = -EIO;
268         else if (!test_bit(FLAG_IS_OUT, &desc->flags))
269                 status = -EPERM;
270         else {
271                 long            value;
272
273                 status = strict_strtol(buf, 0, &value);
274                 if (status == 0) {
275                         gpio_set_value_cansleep(gpio, value != 0);
276                         status = size;
277                 }
278         }
279
280         mutex_unlock(&sysfs_lock);
281         return status;
282 }
283
284 static /*const*/ DEVICE_ATTR(value, 0644,
285                 gpio_value_show, gpio_value_store);
286
287 static const struct attribute *gpio_attrs[] = {
288         &dev_attr_direction.attr,
289         &dev_attr_value.attr,
290         NULL,
291 };
292
293 static const struct attribute_group gpio_attr_group = {
294         .attrs = (struct attribute **) gpio_attrs,
295 };
296
297 /*
298  * /sys/class/gpio/gpiochipN/
299  *   /base ... matching gpio_chip.base (N)
300  *   /label ... matching gpio_chip.label
301  *   /ngpio ... matching gpio_chip.ngpio
302  */
303
304 static ssize_t chip_base_show(struct device *dev,
305                                struct device_attribute *attr, char *buf)
306 {
307         const struct gpio_chip  *chip = dev_get_drvdata(dev);
308
309         return sprintf(buf, "%d\n", chip->base);
310 }
311 static DEVICE_ATTR(base, 0444, chip_base_show, NULL);
312
313 static ssize_t chip_label_show(struct device *dev,
314                                struct device_attribute *attr, char *buf)
315 {
316         const struct gpio_chip  *chip = dev_get_drvdata(dev);
317
318         return sprintf(buf, "%s\n", chip->label ? : "");
319 }
320 static DEVICE_ATTR(label, 0444, chip_label_show, NULL);
321
322 static ssize_t chip_ngpio_show(struct device *dev,
323                                struct device_attribute *attr, char *buf)
324 {
325         const struct gpio_chip  *chip = dev_get_drvdata(dev);
326
327         return sprintf(buf, "%u\n", chip->ngpio);
328 }
329 static DEVICE_ATTR(ngpio, 0444, chip_ngpio_show, NULL);
330
331 static const struct attribute *gpiochip_attrs[] = {
332         &dev_attr_base.attr,
333         &dev_attr_label.attr,
334         &dev_attr_ngpio.attr,
335         NULL,
336 };
337
338 static const struct attribute_group gpiochip_attr_group = {
339         .attrs = (struct attribute **) gpiochip_attrs,
340 };
341
342 /*
343  * /sys/class/gpio/export ... write-only
344  *      integer N ... number of GPIO to export (full access)
345  * /sys/class/gpio/unexport ... write-only
346  *      integer N ... number of GPIO to unexport
347  */
348 static ssize_t export_store(struct class *class, const char *buf, size_t len)
349 {
350         long    gpio;
351         int     status;
352
353         status = strict_strtol(buf, 0, &gpio);
354         if (status < 0)
355                 goto done;
356
357         /* No extra locking here; FLAG_SYSFS just signifies that the
358          * request and export were done by on behalf of userspace, so
359          * they may be undone on its behalf too.
360          */
361
362         status = gpio_request(gpio, "sysfs");
363         if (status < 0)
364                 goto done;
365
366         status = gpio_export(gpio, true);
367         if (status < 0)
368                 gpio_free(gpio);
369         else
370                 set_bit(FLAG_SYSFS, &gpio_desc[gpio].flags);
371
372 done:
373         if (status)
374                 pr_debug("%s: status %d\n", __func__, status);
375         return status ? : len;
376 }
377
378 static ssize_t unexport_store(struct class *class, const char *buf, size_t len)
379 {
380         long    gpio;
381         int     status;
382
383         status = strict_strtol(buf, 0, &gpio);
384         if (status < 0)
385                 goto done;
386
387         status = -EINVAL;
388
389         /* reject bogus commands (gpio_unexport ignores them) */
390         if (!gpio_is_valid(gpio))
391                 goto done;
392
393         /* No extra locking here; FLAG_SYSFS just signifies that the
394          * request and export were done by on behalf of userspace, so
395          * they may be undone on its behalf too.
396          */
397         if (test_and_clear_bit(FLAG_SYSFS, &gpio_desc[gpio].flags)) {
398                 status = 0;
399                 gpio_free(gpio);
400         }
401 done:
402         if (status)
403                 pr_debug("%s: status %d\n", __func__, status);
404         return status ? : len;
405 }
406
407 static struct class_attribute gpio_class_attrs[] = {
408         __ATTR(export, 0200, NULL, export_store),
409         __ATTR(unexport, 0200, NULL, unexport_store),
410         __ATTR_NULL,
411 };
412
413 static struct class gpio_class = {
414         .name =         "gpio",
415         .owner =        THIS_MODULE,
416
417         .class_attrs =  gpio_class_attrs,
418 };
419
420
421 /**
422  * gpio_export - export a GPIO through sysfs
423  * @gpio: gpio to make available, already requested
424  * @direction_may_change: true if userspace may change gpio direction
425  * Context: arch_initcall or later
426  *
427  * When drivers want to make a GPIO accessible to userspace after they
428  * have requested it -- perhaps while debugging, or as part of their
429  * public interface -- they may use this routine.  If the GPIO can
430  * change direction (some can't) and the caller allows it, userspace
431  * will see "direction" sysfs attribute which may be used to change
432  * the gpio's direction.  A "value" attribute will always be provided.
433  *
434  * Returns zero on success, else an error.
435  */
436 int gpio_export(unsigned gpio, bool direction_may_change)
437 {
438         unsigned long           flags;
439         struct gpio_desc        *desc;
440         int                     status = -EINVAL;
441         char                    *ioname = NULL;
442
443         /* can't export until sysfs is available ... */
444         if (!gpio_class.p) {
445                 pr_debug("%s: called too early!\n", __func__);
446                 return -ENOENT;
447         }
448
449         if (!gpio_is_valid(gpio))
450                 goto done;
451
452         mutex_lock(&sysfs_lock);
453
454         spin_lock_irqsave(&gpio_lock, flags);
455         desc = &gpio_desc[gpio];
456         if (test_bit(FLAG_REQUESTED, &desc->flags)
457                         && !test_bit(FLAG_EXPORT, &desc->flags)) {
458                 status = 0;
459                 if (!desc->chip->direction_input
460                                 || !desc->chip->direction_output)
461                         direction_may_change = false;
462         }
463         spin_unlock_irqrestore(&gpio_lock, flags);
464
465         if (desc->chip->names && desc->chip->names[gpio - desc->chip->base])
466                 ioname = desc->chip->names[gpio - desc->chip->base];
467
468         if (status == 0) {
469                 struct device   *dev;
470
471                 dev = device_create(&gpio_class, desc->chip->dev, MKDEV(0, 0),
472                                     desc, ioname ? ioname : "gpio%d", gpio);
473                 if (dev) {
474                         if (direction_may_change)
475                                 status = sysfs_create_group(&dev->kobj,
476                                                 &gpio_attr_group);
477                         else
478                                 status = device_create_file(dev,
479                                                 &dev_attr_value);
480                         if (status != 0)
481                                 device_unregister(dev);
482                 } else
483                         status = -ENODEV;
484                 if (status == 0)
485                         set_bit(FLAG_EXPORT, &desc->flags);
486         }
487
488         mutex_unlock(&sysfs_lock);
489
490 done:
491         if (status)
492                 pr_debug("%s: gpio%d status %d\n", __func__, gpio, status);
493
494         return status;
495 }
496 EXPORT_SYMBOL_GPL(gpio_export);
497
498 static int match_export(struct device *dev, void *data)
499 {
500         return dev_get_drvdata(dev) == data;
501 }
502
503 /**
504  * gpio_unexport - reverse effect of gpio_export()
505  * @gpio: gpio to make unavailable
506  *
507  * This is implicit on gpio_free().
508  */
509 void gpio_unexport(unsigned gpio)
510 {
511         struct gpio_desc        *desc;
512         int                     status = -EINVAL;
513
514         if (!gpio_is_valid(gpio))
515                 goto done;
516
517         mutex_lock(&sysfs_lock);
518
519         desc = &gpio_desc[gpio];
520
521         if (test_bit(FLAG_EXPORT, &desc->flags)) {
522                 struct device   *dev = NULL;
523
524                 dev = class_find_device(&gpio_class, NULL, desc, match_export);
525                 if (dev) {
526                         clear_bit(FLAG_EXPORT, &desc->flags);
527                         put_device(dev);
528                         device_unregister(dev);
529                         status = 0;
530                 } else
531                         status = -ENODEV;
532         }
533
534         mutex_unlock(&sysfs_lock);
535 done:
536         if (status)
537                 pr_debug("%s: gpio%d status %d\n", __func__, gpio, status);
538 }
539 EXPORT_SYMBOL_GPL(gpio_unexport);
540
541 static int gpiochip_export(struct gpio_chip *chip)
542 {
543         int             status;
544         struct device   *dev;
545
546         /* Many systems register gpio chips for SOC support very early,
547          * before driver model support is available.  In those cases we
548          * export this later, in gpiolib_sysfs_init() ... here we just
549          * verify that _some_ field of gpio_class got initialized.
550          */
551         if (!gpio_class.p)
552                 return 0;
553
554         /* use chip->base for the ID; it's already known to be unique */
555         mutex_lock(&sysfs_lock);
556         dev = device_create(&gpio_class, chip->dev, MKDEV(0, 0), chip,
557                                 "gpiochip%d", chip->base);
558         if (dev) {
559                 status = sysfs_create_group(&dev->kobj,
560                                 &gpiochip_attr_group);
561         } else
562                 status = -ENODEV;
563         chip->exported = (status == 0);
564         mutex_unlock(&sysfs_lock);
565
566         if (status) {
567                 unsigned long   flags;
568                 unsigned        gpio;
569
570                 spin_lock_irqsave(&gpio_lock, flags);
571                 gpio = chip->base;
572                 while (gpio_desc[gpio].chip == chip)
573                         gpio_desc[gpio++].chip = NULL;
574                 spin_unlock_irqrestore(&gpio_lock, flags);
575
576                 pr_debug("%s: chip %s status %d\n", __func__,
577                                 chip->label, status);
578         }
579
580         return status;
581 }
582
583 static void gpiochip_unexport(struct gpio_chip *chip)
584 {
585         int                     status;
586         struct device           *dev;
587
588         mutex_lock(&sysfs_lock);
589         dev = class_find_device(&gpio_class, NULL, chip, match_export);
590         if (dev) {
591                 put_device(dev);
592                 device_unregister(dev);
593                 chip->exported = 0;
594                 status = 0;
595         } else
596                 status = -ENODEV;
597         mutex_unlock(&sysfs_lock);
598
599         if (status)
600                 pr_debug("%s: chip %s status %d\n", __func__,
601                                 chip->label, status);
602 }
603
604 static int __init gpiolib_sysfs_init(void)
605 {
606         int             status;
607         unsigned long   flags;
608         unsigned        gpio;
609
610         status = class_register(&gpio_class);
611         if (status < 0)
612                 return status;
613
614         /* Scan and register the gpio_chips which registered very
615          * early (e.g. before the class_register above was called).
616          *
617          * We run before arch_initcall() so chip->dev nodes can have
618          * registered, and so arch_initcall() can always gpio_export().
619          */
620         spin_lock_irqsave(&gpio_lock, flags);
621         for (gpio = 0; gpio < ARCH_NR_GPIOS; gpio++) {
622                 struct gpio_chip        *chip;
623
624                 chip = gpio_desc[gpio].chip;
625                 if (!chip || chip->exported)
626                         continue;
627
628                 spin_unlock_irqrestore(&gpio_lock, flags);
629                 status = gpiochip_export(chip);
630                 spin_lock_irqsave(&gpio_lock, flags);
631         }
632         spin_unlock_irqrestore(&gpio_lock, flags);
633
634
635         return status;
636 }
637 postcore_initcall(gpiolib_sysfs_init);
638
639 #else
640 static inline int gpiochip_export(struct gpio_chip *chip)
641 {
642         return 0;
643 }
644
645 static inline void gpiochip_unexport(struct gpio_chip *chip)
646 {
647 }
648
649 #endif /* CONFIG_GPIO_SYSFS */
650
651 /**
652  * gpiochip_add() - register a gpio_chip
653  * @chip: the chip to register, with chip->base initialized
654  * Context: potentially before irqs or kmalloc will work
655  *
656  * Returns a negative errno if the chip can't be registered, such as
657  * because the chip->base is invalid or already associated with a
658  * different chip.  Otherwise it returns zero as a success code.
659  *
660  * When gpiochip_add() is called very early during boot, so that GPIOs
661  * can be freely used, the chip->dev device must be registered before
662  * the gpio framework's arch_initcall().  Otherwise sysfs initialization
663  * for GPIOs will fail rudely.
664  *
665  * If chip->base is negative, this requests dynamic assignment of
666  * a range of valid GPIOs.
667  */
668 int gpiochip_add(struct gpio_chip *chip)
669 {
670         unsigned long   flags;
671         int             status = 0;
672         unsigned        id;
673         int             base = chip->base;
674
675         if ((!gpio_is_valid(base) || !gpio_is_valid(base + chip->ngpio - 1))
676                         && base >= 0) {
677                 status = -EINVAL;
678                 goto fail;
679         }
680
681         spin_lock_irqsave(&gpio_lock, flags);
682
683         if (base < 0) {
684                 base = gpiochip_find_base(chip->ngpio);
685                 if (base < 0) {
686                         status = base;
687                         goto unlock;
688                 }
689                 chip->base = base;
690         }
691
692         /* these GPIO numbers must not be managed by another gpio_chip */
693         for (id = base; id < base + chip->ngpio; id++) {
694                 if (gpio_desc[id].chip != NULL) {
695                         status = -EBUSY;
696                         break;
697                 }
698         }
699         if (status == 0) {
700                 for (id = base; id < base + chip->ngpio; id++) {
701                         gpio_desc[id].chip = chip;
702
703                         /* REVISIT:  most hardware initializes GPIOs as
704                          * inputs (often with pullups enabled) so power
705                          * usage is minimized.  Linux code should set the
706                          * gpio direction first thing; but until it does,
707                          * we may expose the wrong direction in sysfs.
708                          */
709                         gpio_desc[id].flags = !chip->direction_input
710                                 ? (1 << FLAG_IS_OUT)
711                                 : 0;
712                 }
713         }
714
715 unlock:
716         spin_unlock_irqrestore(&gpio_lock, flags);
717         if (status == 0)
718                 status = gpiochip_export(chip);
719 fail:
720         /* failures here can mean systems won't boot... */
721         if (status)
722                 pr_err("gpiochip_add: gpios %d..%d (%s) not registered\n",
723                         chip->base, chip->base + chip->ngpio - 1,
724                         chip->label ? : "generic");
725         return status;
726 }
727 EXPORT_SYMBOL_GPL(gpiochip_add);
728
729 /**
730  * gpiochip_remove() - unregister a gpio_chip
731  * @chip: the chip to unregister
732  *
733  * A gpio_chip with any GPIOs still requested may not be removed.
734  */
735 int gpiochip_remove(struct gpio_chip *chip)
736 {
737         unsigned long   flags;
738         int             status = 0;
739         unsigned        id;
740
741         spin_lock_irqsave(&gpio_lock, flags);
742
743         for (id = chip->base; id < chip->base + chip->ngpio; id++) {
744                 if (test_bit(FLAG_REQUESTED, &gpio_desc[id].flags)) {
745                         status = -EBUSY;
746                         break;
747                 }
748         }
749         if (status == 0) {
750                 for (id = chip->base; id < chip->base + chip->ngpio; id++)
751                         gpio_desc[id].chip = NULL;
752         }
753
754         spin_unlock_irqrestore(&gpio_lock, flags);
755
756         if (status == 0)
757                 gpiochip_unexport(chip);
758
759         return status;
760 }
761 EXPORT_SYMBOL_GPL(gpiochip_remove);
762
763
764 /* These "optional" allocation calls help prevent drivers from stomping
765  * on each other, and help provide better diagnostics in debugfs.
766  * They're called even less than the "set direction" calls.
767  */
768 int gpio_request(unsigned gpio, const char *label)
769 {
770         struct gpio_desc        *desc;
771         struct gpio_chip        *chip;
772         int                     status = -EINVAL;
773         unsigned long           flags;
774
775         spin_lock_irqsave(&gpio_lock, flags);
776
777         if (!gpio_is_valid(gpio))
778                 goto done;
779         desc = &gpio_desc[gpio];
780         chip = desc->chip;
781         if (chip == NULL)
782                 goto done;
783
784         if (!try_module_get(chip->owner))
785                 goto done;
786
787         /* NOTE:  gpio_request() can be called in early boot,
788          * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
789          */
790
791         if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
792                 desc_set_label(desc, label ? : "?");
793                 status = 0;
794         } else {
795                 status = -EBUSY;
796                 module_put(chip->owner);
797                 goto done;
798         }
799
800         if (chip->request) {
801                 /* chip->request may sleep */
802                 spin_unlock_irqrestore(&gpio_lock, flags);
803                 status = chip->request(chip, gpio - chip->base);
804                 spin_lock_irqsave(&gpio_lock, flags);
805
806                 if (status < 0) {
807                         desc_set_label(desc, NULL);
808                         module_put(chip->owner);
809                         clear_bit(FLAG_REQUESTED, &desc->flags);
810                 }
811         }
812
813 done:
814         if (status)
815                 pr_debug("gpio_request: gpio-%d (%s) status %d\n",
816                         gpio, label ? : "?", status);
817         spin_unlock_irqrestore(&gpio_lock, flags);
818         return status;
819 }
820 EXPORT_SYMBOL_GPL(gpio_request);
821
822 void gpio_free(unsigned gpio)
823 {
824         unsigned long           flags;
825         struct gpio_desc        *desc;
826         struct gpio_chip        *chip;
827
828         might_sleep();
829
830         if (!gpio_is_valid(gpio)) {
831                 WARN_ON(extra_checks);
832                 return;
833         }
834
835         gpio_unexport(gpio);
836
837         spin_lock_irqsave(&gpio_lock, flags);
838
839         desc = &gpio_desc[gpio];
840         chip = desc->chip;
841         if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
842                 if (chip->free) {
843                         spin_unlock_irqrestore(&gpio_lock, flags);
844                         might_sleep_if(extra_checks && chip->can_sleep);
845                         chip->free(chip, gpio - chip->base);
846                         spin_lock_irqsave(&gpio_lock, flags);
847                 }
848                 desc_set_label(desc, NULL);
849                 module_put(desc->chip->owner);
850                 clear_bit(FLAG_REQUESTED, &desc->flags);
851         } else
852                 WARN_ON(extra_checks);
853
854         spin_unlock_irqrestore(&gpio_lock, flags);
855 }
856 EXPORT_SYMBOL_GPL(gpio_free);
857
858
859 /**
860  * gpiochip_is_requested - return string iff signal was requested
861  * @chip: controller managing the signal
862  * @offset: of signal within controller's 0..(ngpio - 1) range
863  *
864  * Returns NULL if the GPIO is not currently requested, else a string.
865  * If debugfs support is enabled, the string returned is the label passed
866  * to gpio_request(); otherwise it is a meaningless constant.
867  *
868  * This function is for use by GPIO controller drivers.  The label can
869  * help with diagnostics, and knowing that the signal is used as a GPIO
870  * can help avoid accidentally multiplexing it to another controller.
871  */
872 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
873 {
874         unsigned gpio = chip->base + offset;
875
876         if (!gpio_is_valid(gpio) || gpio_desc[gpio].chip != chip)
877                 return NULL;
878         if (test_bit(FLAG_REQUESTED, &gpio_desc[gpio].flags) == 0)
879                 return NULL;
880 #ifdef CONFIG_DEBUG_FS
881         return gpio_desc[gpio].label;
882 #else
883         return "?";
884 #endif
885 }
886 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
887
888
889 /* Drivers MUST set GPIO direction before making get/set calls.  In
890  * some cases this is done in early boot, before IRQs are enabled.
891  *
892  * As a rule these aren't called more than once (except for drivers
893  * using the open-drain emulation idiom) so these are natural places
894  * to accumulate extra debugging checks.  Note that we can't (yet)
895  * rely on gpio_request() having been called beforehand.
896  */
897
898 int gpio_direction_input(unsigned gpio)
899 {
900         unsigned long           flags;
901         struct gpio_chip        *chip;
902         struct gpio_desc        *desc = &gpio_desc[gpio];
903         int                     status = -EINVAL;
904
905         spin_lock_irqsave(&gpio_lock, flags);
906
907         if (!gpio_is_valid(gpio))
908                 goto fail;
909         chip = desc->chip;
910         if (!chip || !chip->get || !chip->direction_input)
911                 goto fail;
912         gpio -= chip->base;
913         if (gpio >= chip->ngpio)
914                 goto fail;
915         status = gpio_ensure_requested(desc, gpio);
916         if (status < 0)
917                 goto fail;
918
919         /* now we know the gpio is valid and chip won't vanish */
920
921         spin_unlock_irqrestore(&gpio_lock, flags);
922
923         might_sleep_if(extra_checks && chip->can_sleep);
924
925         if (status) {
926                 status = chip->request(chip, gpio);
927                 if (status < 0) {
928                         pr_debug("GPIO-%d: chip request fail, %d\n",
929                                 chip->base + gpio, status);
930                         /* and it's not available to anyone else ...
931                          * gpio_request() is the fully clean solution.
932                          */
933                         goto lose;
934                 }
935         }
936
937         status = chip->direction_input(chip, gpio);
938         if (status == 0)
939                 clear_bit(FLAG_IS_OUT, &desc->flags);
940 lose:
941         return status;
942 fail:
943         spin_unlock_irqrestore(&gpio_lock, flags);
944         if (status)
945                 pr_debug("%s: gpio-%d status %d\n",
946                         __func__, gpio, status);
947         return status;
948 }
949 EXPORT_SYMBOL_GPL(gpio_direction_input);
950
951 int gpio_direction_output(unsigned gpio, int value)
952 {
953         unsigned long           flags;
954         struct gpio_chip        *chip;
955         struct gpio_desc        *desc = &gpio_desc[gpio];
956         int                     status = -EINVAL;
957
958         spin_lock_irqsave(&gpio_lock, flags);
959
960         if (!gpio_is_valid(gpio))
961                 goto fail;
962         chip = desc->chip;
963         if (!chip || !chip->set || !chip->direction_output)
964                 goto fail;
965         gpio -= chip->base;
966         if (gpio >= chip->ngpio)
967                 goto fail;
968         status = gpio_ensure_requested(desc, gpio);
969         if (status < 0)
970                 goto fail;
971
972         /* now we know the gpio is valid and chip won't vanish */
973
974         spin_unlock_irqrestore(&gpio_lock, flags);
975
976         might_sleep_if(extra_checks && chip->can_sleep);
977
978         if (status) {
979                 status = chip->request(chip, gpio);
980                 if (status < 0) {
981                         pr_debug("GPIO-%d: chip request fail, %d\n",
982                                 chip->base + gpio, status);
983                         /* and it's not available to anyone else ...
984                          * gpio_request() is the fully clean solution.
985                          */
986                         goto lose;
987                 }
988         }
989
990         status = chip->direction_output(chip, gpio, value);
991         if (status == 0)
992                 set_bit(FLAG_IS_OUT, &desc->flags);
993 lose:
994         return status;
995 fail:
996         spin_unlock_irqrestore(&gpio_lock, flags);
997         if (status)
998                 pr_debug("%s: gpio-%d status %d\n",
999                         __func__, gpio, status);
1000         return status;
1001 }
1002 EXPORT_SYMBOL_GPL(gpio_direction_output);
1003
1004
1005 /* I/O calls are only valid after configuration completed; the relevant
1006  * "is this a valid GPIO" error checks should already have been done.
1007  *
1008  * "Get" operations are often inlinable as reading a pin value register,
1009  * and masking the relevant bit in that register.
1010  *
1011  * When "set" operations are inlinable, they involve writing that mask to
1012  * one register to set a low value, or a different register to set it high.
1013  * Otherwise locking is needed, so there may be little value to inlining.
1014  *
1015  *------------------------------------------------------------------------
1016  *
1017  * IMPORTANT!!!  The hot paths -- get/set value -- assume that callers
1018  * have requested the GPIO.  That can include implicit requesting by
1019  * a direction setting call.  Marking a gpio as requested locks its chip
1020  * in memory, guaranteeing that these table lookups need no more locking
1021  * and that gpiochip_remove() will fail.
1022  *
1023  * REVISIT when debugging, consider adding some instrumentation to ensure
1024  * that the GPIO was actually requested.
1025  */
1026
1027 /**
1028  * __gpio_get_value() - return a gpio's value
1029  * @gpio: gpio whose value will be returned
1030  * Context: any
1031  *
1032  * This is used directly or indirectly to implement gpio_get_value().
1033  * It returns the zero or nonzero value provided by the associated
1034  * gpio_chip.get() method; or zero if no such method is provided.
1035  */
1036 int __gpio_get_value(unsigned gpio)
1037 {
1038         struct gpio_chip        *chip;
1039
1040         chip = gpio_to_chip(gpio);
1041         WARN_ON(extra_checks && chip->can_sleep);
1042         return chip->get ? chip->get(chip, gpio - chip->base) : 0;
1043 }
1044 EXPORT_SYMBOL_GPL(__gpio_get_value);
1045
1046 /**
1047  * __gpio_set_value() - assign a gpio's value
1048  * @gpio: gpio whose value will be assigned
1049  * @value: value to assign
1050  * Context: any
1051  *
1052  * This is used directly or indirectly to implement gpio_set_value().
1053  * It invokes the associated gpio_chip.set() method.
1054  */
1055 void __gpio_set_value(unsigned gpio, int value)
1056 {
1057         struct gpio_chip        *chip;
1058
1059         chip = gpio_to_chip(gpio);
1060         WARN_ON(extra_checks && chip->can_sleep);
1061         chip->set(chip, gpio - chip->base, value);
1062 }
1063 EXPORT_SYMBOL_GPL(__gpio_set_value);
1064
1065 /**
1066  * __gpio_cansleep() - report whether gpio value access will sleep
1067  * @gpio: gpio in question
1068  * Context: any
1069  *
1070  * This is used directly or indirectly to implement gpio_cansleep().  It
1071  * returns nonzero if access reading or writing the GPIO value can sleep.
1072  */
1073 int __gpio_cansleep(unsigned gpio)
1074 {
1075         struct gpio_chip        *chip;
1076
1077         /* only call this on GPIOs that are valid! */
1078         chip = gpio_to_chip(gpio);
1079
1080         return chip->can_sleep;
1081 }
1082 EXPORT_SYMBOL_GPL(__gpio_cansleep);
1083
1084 /**
1085  * __gpio_to_irq() - return the IRQ corresponding to a GPIO
1086  * @gpio: gpio whose IRQ will be returned (already requested)
1087  * Context: any
1088  *
1089  * This is used directly or indirectly to implement gpio_to_irq().
1090  * It returns the number of the IRQ signaled by this (input) GPIO,
1091  * or a negative errno.
1092  */
1093 int __gpio_to_irq(unsigned gpio)
1094 {
1095         struct gpio_chip        *chip;
1096
1097         chip = gpio_to_chip(gpio);
1098         return chip->to_irq ? chip->to_irq(chip, gpio - chip->base) : -ENXIO;
1099 }
1100 EXPORT_SYMBOL_GPL(__gpio_to_irq);
1101
1102
1103
1104 /* There's no value in making it easy to inline GPIO calls that may sleep.
1105  * Common examples include ones connected to I2C or SPI chips.
1106  */
1107
1108 int gpio_get_value_cansleep(unsigned gpio)
1109 {
1110         struct gpio_chip        *chip;
1111
1112         might_sleep_if(extra_checks);
1113         chip = gpio_to_chip(gpio);
1114         return chip->get ? chip->get(chip, gpio - chip->base) : 0;
1115 }
1116 EXPORT_SYMBOL_GPL(gpio_get_value_cansleep);
1117
1118 void gpio_set_value_cansleep(unsigned gpio, int value)
1119 {
1120         struct gpio_chip        *chip;
1121
1122         might_sleep_if(extra_checks);
1123         chip = gpio_to_chip(gpio);
1124         chip->set(chip, gpio - chip->base, value);
1125 }
1126 EXPORT_SYMBOL_GPL(gpio_set_value_cansleep);
1127
1128
1129 #ifdef CONFIG_DEBUG_FS
1130
1131 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_chip *chip)
1132 {
1133         unsigned                i;
1134         unsigned                gpio = chip->base;
1135         struct gpio_desc        *gdesc = &gpio_desc[gpio];
1136         int                     is_out;
1137
1138         for (i = 0; i < chip->ngpio; i++, gpio++, gdesc++) {
1139                 if (!test_bit(FLAG_REQUESTED, &gdesc->flags))
1140                         continue;
1141
1142                 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
1143                 seq_printf(s, " gpio-%-3d (%-20.20s) %s %s",
1144                         gpio, gdesc->label,
1145                         is_out ? "out" : "in ",
1146                         chip->get
1147                                 ? (chip->get(chip, i) ? "hi" : "lo")
1148                                 : "?  ");
1149
1150                 if (!is_out) {
1151                         int             irq = gpio_to_irq(gpio);
1152                         struct irq_desc *desc = irq_to_desc(irq);
1153
1154                         /* This races with request_irq(), set_irq_type(),
1155                          * and set_irq_wake() ... but those are "rare".
1156                          *
1157                          * More significantly, trigger type flags aren't
1158                          * currently maintained by genirq.
1159                          */
1160                         if (irq >= 0 && desc->action) {
1161                                 char *trigger;
1162
1163                                 switch (desc->status & IRQ_TYPE_SENSE_MASK) {
1164                                 case IRQ_TYPE_NONE:
1165                                         trigger = "(default)";
1166                                         break;
1167                                 case IRQ_TYPE_EDGE_FALLING:
1168                                         trigger = "edge-falling";
1169                                         break;
1170                                 case IRQ_TYPE_EDGE_RISING:
1171                                         trigger = "edge-rising";
1172                                         break;
1173                                 case IRQ_TYPE_EDGE_BOTH:
1174                                         trigger = "edge-both";
1175                                         break;
1176                                 case IRQ_TYPE_LEVEL_HIGH:
1177                                         trigger = "level-high";
1178                                         break;
1179                                 case IRQ_TYPE_LEVEL_LOW:
1180                                         trigger = "level-low";
1181                                         break;
1182                                 default:
1183                                         trigger = "?trigger?";
1184                                         break;
1185                                 }
1186
1187                                 seq_printf(s, " irq-%d %s%s",
1188                                         irq, trigger,
1189                                         (desc->status & IRQ_WAKEUP)
1190                                                 ? " wakeup" : "");
1191                         }
1192                 }
1193
1194                 seq_printf(s, "\n");
1195         }
1196 }
1197
1198 static int gpiolib_show(struct seq_file *s, void *unused)
1199 {
1200         struct gpio_chip        *chip = NULL;
1201         unsigned                gpio;
1202         int                     started = 0;
1203
1204         /* REVISIT this isn't locked against gpio_chip removal ... */
1205
1206         for (gpio = 0; gpio_is_valid(gpio); gpio++) {
1207                 struct device *dev;
1208
1209                 if (chip == gpio_desc[gpio].chip)
1210                         continue;
1211                 chip = gpio_desc[gpio].chip;
1212                 if (!chip)
1213                         continue;
1214
1215                 seq_printf(s, "%sGPIOs %d-%d",
1216                                 started ? "\n" : "",
1217                                 chip->base, chip->base + chip->ngpio - 1);
1218                 dev = chip->dev;
1219                 if (dev)
1220                         seq_printf(s, ", %s/%s",
1221                                 dev->bus ? dev->bus->name : "no-bus",
1222                                 dev_name(dev));
1223                 if (chip->label)
1224                         seq_printf(s, ", %s", chip->label);
1225                 if (chip->can_sleep)
1226                         seq_printf(s, ", can sleep");
1227                 seq_printf(s, ":\n");
1228
1229                 started = 1;
1230                 if (chip->dbg_show)
1231                         chip->dbg_show(s, chip);
1232                 else
1233                         gpiolib_dbg_show(s, chip);
1234         }
1235         return 0;
1236 }
1237
1238 static int gpiolib_open(struct inode *inode, struct file *file)
1239 {
1240         return single_open(file, gpiolib_show, NULL);
1241 }
1242
1243 static struct file_operations gpiolib_operations = {
1244         .open           = gpiolib_open,
1245         .read           = seq_read,
1246         .llseek         = seq_lseek,
1247         .release        = single_release,
1248 };
1249
1250 static int __init gpiolib_debugfs_init(void)
1251 {
1252         /* /sys/kernel/debug/gpio */
1253         (void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
1254                                 NULL, NULL, &gpiolib_operations);
1255         return 0;
1256 }
1257 subsys_initcall(gpiolib_debugfs_init);
1258
1259 #endif  /* DEBUG_FS */