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