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