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