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