b64106f1cb7b90ac2c3595c5d1101cba93fa0e6a
[linux-block.git] / drivers / gpio / gpiolib-sysfs.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include <linux/bitops.h>
4 #include <linux/cleanup.h>
5 #include <linux/device.h>
6 #include <linux/init.h>
7 #include <linux/interrupt.h>
8 #include <linux/kdev_t.h>
9 #include <linux/kstrtox.h>
10 #include <linux/list.h>
11 #include <linux/mutex.h>
12 #include <linux/printk.h>
13 #include <linux/slab.h>
14 #include <linux/string.h>
15 #include <linux/srcu.h>
16 #include <linux/sysfs.h>
17 #include <linux/types.h>
18
19 #include <linux/gpio/consumer.h>
20 #include <linux/gpio/driver.h>
21
22 #include <uapi/linux/gpio.h>
23
24 #include "gpiolib.h"
25 #include "gpiolib-sysfs.h"
26
27 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
28
29 struct kernfs_node;
30
31 #define GPIO_IRQF_TRIGGER_NONE          0
32 #define GPIO_IRQF_TRIGGER_FALLING       BIT(0)
33 #define GPIO_IRQF_TRIGGER_RISING        BIT(1)
34 #define GPIO_IRQF_TRIGGER_BOTH          (GPIO_IRQF_TRIGGER_FALLING | \
35                                          GPIO_IRQF_TRIGGER_RISING)
36
37 enum {
38         GPIO_SYSFS_LINE_CLASS_ATTR_DIRECTION = 0,
39         GPIO_SYSFS_LINE_CLASS_ATTR_VALUE,
40         GPIO_SYSFS_LINE_CLASS_ATTR_EDGE,
41         GPIO_SYSFS_LINE_CLASS_ATTR_ACTIVE_LOW,
42         GPIO_SYSFS_LINE_CLASS_ATTR_SENTINEL,
43         GPIO_SYSFS_LINE_CLASS_ATTR_SIZE,
44 };
45
46 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
47
48 enum {
49         GPIO_SYSFS_LINE_CHIP_ATTR_DIRECTION = 0,
50         GPIO_SYSFS_LINE_CHIP_ATTR_VALUE,
51         GPIO_SYSFS_LINE_CHIP_ATTR_SENTINEL,
52         GPIO_SYSFS_LINE_CHIP_ATTR_SIZE,
53 };
54
55 struct gpiod_data {
56         struct list_head list;
57
58         struct gpio_desc *desc;
59         struct device *dev;
60
61         struct mutex mutex;
62 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
63         struct kernfs_node *value_kn;
64         int irq;
65         unsigned char irq_flags;
66 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
67
68         bool direction_can_change;
69
70         struct kobject *parent;
71         struct device_attribute dir_attr;
72         struct device_attribute val_attr;
73
74 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
75         struct device_attribute edge_attr;
76         struct device_attribute active_low_attr;
77
78         struct attribute *class_attrs[GPIO_SYSFS_LINE_CLASS_ATTR_SIZE];
79         struct attribute_group class_attr_group;
80         const struct attribute_group *class_attr_groups[2];
81 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
82
83         struct attribute *chip_attrs[GPIO_SYSFS_LINE_CHIP_ATTR_SIZE];
84         struct attribute_group chip_attr_group;
85         const struct attribute_group *chip_attr_groups[2];
86 };
87
88 struct gpiodev_data {
89         struct list_head exported_lines;
90         struct gpio_device *gdev;
91         struct device *cdev_id; /* Class device by GPIO device ID */
92 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
93         struct device *cdev_base; /* Class device by GPIO base */
94 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
95 };
96
97 /*
98  * Lock to serialise gpiod export and unexport, and prevent re-export of
99  * gpiod whose chip is being unregistered.
100  */
101 static DEFINE_MUTEX(sysfs_lock);
102
103 /*
104  * /sys/class/gpio/gpioN... only for GPIOs that are exported
105  *   /direction
106  *      * MAY BE OMITTED if kernel won't allow direction changes
107  *      * is read/write as "in" or "out"
108  *      * may also be written as "high" or "low", initializing
109  *        output value as specified ("out" implies "low")
110  *   /value
111  *      * always readable, subject to hardware behavior
112  *      * may be writable, as zero/nonzero
113  *   /edge
114  *      * configures behavior of poll(2) on /value
115  *      * available only if pin can generate IRQs on input
116  *      * is read/write as "none", "falling", "rising", or "both"
117  *   /active_low
118  *      * configures polarity of /value
119  *      * is read/write as zero/nonzero
120  *      * also affects existing and subsequent "falling" and "rising"
121  *        /edge configuration
122  */
123
124 static ssize_t direction_show(struct device *dev,
125                               struct device_attribute *attr, char *buf)
126 {
127         struct gpiod_data *data = container_of(attr, struct gpiod_data,
128                                                dir_attr);
129         struct gpio_desc *desc = data->desc;
130         int value;
131
132         scoped_guard(mutex, &data->mutex) {
133                 gpiod_get_direction(desc);
134                 value = !!test_bit(FLAG_IS_OUT, &desc->flags);
135         }
136
137         return sysfs_emit(buf, "%s\n", value ? "out" : "in");
138 }
139
140 static ssize_t direction_store(struct device *dev,
141                                struct device_attribute *attr, const char *buf,
142                                size_t size)
143 {
144         struct gpiod_data *data = container_of(attr, struct gpiod_data,
145                                                dir_attr);
146         struct gpio_desc *desc = data->desc;
147         ssize_t status;
148
149         guard(mutex)(&data->mutex);
150
151         if (sysfs_streq(buf, "high"))
152                 status = gpiod_direction_output_raw(desc, 1);
153         else if (sysfs_streq(buf, "out") || sysfs_streq(buf, "low"))
154                 status = gpiod_direction_output_raw(desc, 0);
155         else if (sysfs_streq(buf, "in"))
156                 status = gpiod_direction_input(desc);
157         else
158                 status = -EINVAL;
159
160         return status ? : size;
161 }
162
163 static ssize_t value_show(struct device *dev, struct device_attribute *attr,
164                           char *buf)
165 {
166         struct gpiod_data *data = container_of(attr, struct gpiod_data,
167                                                val_attr);
168         struct gpio_desc *desc = data->desc;
169         ssize_t status;
170
171         scoped_guard(mutex, &data->mutex)
172                 status = gpiod_get_value_cansleep(desc);
173
174         if (status < 0)
175                 return status;
176
177         return sysfs_emit(buf, "%zd\n", status);
178 }
179
180 static ssize_t value_store(struct device *dev, struct device_attribute *attr,
181                            const char *buf, size_t size)
182 {
183         struct gpiod_data *data = container_of(attr, struct gpiod_data,
184                                                val_attr);
185         struct gpio_desc *desc = data->desc;
186         ssize_t status;
187         long value;
188
189         status = kstrtol(buf, 0, &value);
190         if (status)
191                 return status;
192
193         guard(mutex)(&data->mutex);
194
195         status = gpiod_set_value_cansleep(desc, value);
196         if (status)
197                 return status;
198
199         return size;
200 }
201
202 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
203 static irqreturn_t gpio_sysfs_irq(int irq, void *priv)
204 {
205         struct gpiod_data *data = priv;
206
207         sysfs_notify_dirent(data->value_kn);
208
209         return IRQ_HANDLED;
210 }
211
212 /* Caller holds gpiod-data mutex. */
213 static int gpio_sysfs_request_irq(struct gpiod_data *data, unsigned char flags)
214 {
215         struct gpio_desc *desc = data->desc;
216         unsigned long irq_flags;
217         int ret;
218
219         CLASS(gpio_chip_guard, guard)(desc);
220         if (!guard.gc)
221                 return -ENODEV;
222
223         data->irq = gpiod_to_irq(desc);
224         if (data->irq < 0)
225                 return -EIO;
226
227         irq_flags = IRQF_SHARED;
228         if (flags & GPIO_IRQF_TRIGGER_FALLING) {
229                 irq_flags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
230                                 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
231                 set_bit(FLAG_EDGE_FALLING, &desc->flags);
232         }
233         if (flags & GPIO_IRQF_TRIGGER_RISING) {
234                 irq_flags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
235                                 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
236                 set_bit(FLAG_EDGE_RISING, &desc->flags);
237         }
238
239         /*
240          * FIXME: This should be done in the irq_request_resources callback
241          * when the irq is requested, but a few drivers currently fail to do
242          * so.
243          *
244          * Remove this redundant call (along with the corresponding unlock)
245          * when those drivers have been fixed.
246          */
247         ret = gpiochip_lock_as_irq(guard.gc, gpio_chip_hwgpio(desc));
248         if (ret < 0)
249                 goto err_clr_bits;
250
251         ret = request_any_context_irq(data->irq, gpio_sysfs_irq, irq_flags,
252                                 "gpiolib", data);
253         if (ret < 0)
254                 goto err_unlock;
255
256         data->irq_flags = flags;
257
258         return 0;
259
260 err_unlock:
261         gpiochip_unlock_as_irq(guard.gc, gpio_chip_hwgpio(desc));
262 err_clr_bits:
263         clear_bit(FLAG_EDGE_RISING, &desc->flags);
264         clear_bit(FLAG_EDGE_FALLING, &desc->flags);
265
266         return ret;
267 }
268
269 /*
270  * Caller holds gpiod-data mutex (unless called after class-device
271  * deregistration).
272  */
273 static void gpio_sysfs_free_irq(struct gpiod_data *data)
274 {
275         struct gpio_desc *desc = data->desc;
276
277         CLASS(gpio_chip_guard, guard)(desc);
278         if (!guard.gc)
279                 return;
280
281         data->irq_flags = 0;
282         free_irq(data->irq, data);
283         gpiochip_unlock_as_irq(guard.gc, gpio_chip_hwgpio(desc));
284         clear_bit(FLAG_EDGE_RISING, &desc->flags);
285         clear_bit(FLAG_EDGE_FALLING, &desc->flags);
286 }
287
288 static const char *const trigger_names[] = {
289         [GPIO_IRQF_TRIGGER_NONE]        = "none",
290         [GPIO_IRQF_TRIGGER_FALLING]     = "falling",
291         [GPIO_IRQF_TRIGGER_RISING]      = "rising",
292         [GPIO_IRQF_TRIGGER_BOTH]        = "both",
293 };
294
295 static ssize_t edge_show(struct device *dev, struct device_attribute *attr,
296                          char *buf)
297 {
298         struct gpiod_data *data = container_of(attr, struct gpiod_data,
299                                                edge_attr);
300         int flags;
301
302         scoped_guard(mutex, &data->mutex)
303                 flags = data->irq_flags;
304
305         if (flags >= ARRAY_SIZE(trigger_names))
306                 return 0;
307
308         return sysfs_emit(buf, "%s\n", trigger_names[flags]);
309 }
310
311 static ssize_t edge_store(struct device *dev, struct device_attribute *attr,
312                           const char *buf, size_t size)
313 {
314         struct gpiod_data *data = container_of(attr, struct gpiod_data,
315                                                edge_attr);
316         ssize_t status = size;
317         int flags;
318
319         flags = sysfs_match_string(trigger_names, buf);
320         if (flags < 0)
321                 return flags;
322
323         guard(mutex)(&data->mutex);
324
325         if (flags == data->irq_flags)
326                 return size;
327
328         if (data->irq_flags)
329                 gpio_sysfs_free_irq(data);
330
331         if (!flags)
332                 return size;
333
334         status = gpio_sysfs_request_irq(data, flags);
335         if (status)
336                 return status;
337
338         gpiod_line_state_notify(data->desc, GPIO_V2_LINE_CHANGED_CONFIG);
339
340         return size;
341 }
342
343 /* Caller holds gpiod-data mutex. */
344 static int gpio_sysfs_set_active_low(struct gpiod_data *data, int value)
345 {
346         unsigned int flags = data->irq_flags;
347         struct gpio_desc *desc = data->desc;
348         int status = 0;
349
350         if (!!test_bit(FLAG_ACTIVE_LOW, &desc->flags) == !!value)
351                 return 0;
352
353         assign_bit(FLAG_ACTIVE_LOW, &desc->flags, value);
354
355         /* reconfigure poll(2) support if enabled on one edge only */
356         if (flags == GPIO_IRQF_TRIGGER_FALLING ||
357             flags == GPIO_IRQF_TRIGGER_RISING) {
358                 gpio_sysfs_free_irq(data);
359                 status = gpio_sysfs_request_irq(data, flags);
360         }
361
362         gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
363
364         return status;
365 }
366
367 static ssize_t active_low_show(struct device *dev,
368                                struct device_attribute *attr, char *buf)
369 {
370         struct gpiod_data *data = container_of(attr, struct gpiod_data,
371                                                active_low_attr);
372         struct gpio_desc *desc = data->desc;
373         int value;
374
375         scoped_guard(mutex, &data->mutex)
376                 value = !!test_bit(FLAG_ACTIVE_LOW, &desc->flags);
377
378         return sysfs_emit(buf, "%d\n", value);
379 }
380
381 static ssize_t active_low_store(struct device *dev,
382                                 struct device_attribute *attr,
383                                 const char *buf, size_t size)
384 {
385         struct gpiod_data *data = container_of(attr, struct gpiod_data,
386                                                active_low_attr);
387         ssize_t status;
388         long value;
389
390         status = kstrtol(buf, 0, &value);
391         if (status)
392                 return status;
393
394         guard(mutex)(&data->mutex);
395
396         return gpio_sysfs_set_active_low(data, value) ?: size;
397 }
398 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
399
400 static umode_t gpio_is_visible(struct kobject *kobj, struct attribute *attr,
401                                int n)
402 {
403         struct device_attribute *dev_attr = container_of(attr,
404                                                 struct device_attribute, attr);
405         umode_t mode = attr->mode;
406         struct gpiod_data *data;
407
408         if (strcmp(attr->name, "direction") == 0) {
409                 data = container_of(dev_attr, struct gpiod_data, dir_attr);
410
411                 if (!data->direction_can_change)
412                         mode = 0;
413 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
414         } else if (strcmp(attr->name, "edge") == 0) {
415                 data = container_of(dev_attr, struct gpiod_data, edge_attr);
416
417                 if (gpiod_to_irq(data->desc) < 0)
418                         mode = 0;
419
420                 if (!data->direction_can_change &&
421                     test_bit(FLAG_IS_OUT, &data->desc->flags))
422                         mode = 0;
423 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
424         }
425
426         return mode;
427 }
428
429 /*
430  * /sys/class/gpio/gpiochipN/
431  *   /base ... matching gpio_chip.base (N)
432  *   /label ... matching gpio_chip.label
433  *   /ngpio ... matching gpio_chip.ngpio
434  *
435  * AND
436  *
437  * /sys/class/gpio/chipX/
438  *   /export ... export GPIO at given offset
439  *   /unexport ... unexport GPIO at given offset
440  *   /label ... matching gpio_chip.label
441  *   /ngpio ... matching gpio_chip.ngpio
442  */
443
444 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
445 static ssize_t base_show(struct device *dev, struct device_attribute *attr,
446                          char *buf)
447 {
448         const struct gpiodev_data *data = dev_get_drvdata(dev);
449
450         return sysfs_emit(buf, "%u\n", data->gdev->base);
451 }
452 static DEVICE_ATTR_RO(base);
453 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
454
455 static ssize_t label_show(struct device *dev, struct device_attribute *attr,
456                           char *buf)
457 {
458         const struct gpiodev_data *data = dev_get_drvdata(dev);
459
460         return sysfs_emit(buf, "%s\n", data->gdev->label);
461 }
462 static DEVICE_ATTR_RO(label);
463
464 static ssize_t ngpio_show(struct device *dev, struct device_attribute *attr,
465                           char *buf)
466 {
467         const struct gpiodev_data *data = dev_get_drvdata(dev);
468
469         return sysfs_emit(buf, "%u\n", data->gdev->ngpio);
470 }
471 static DEVICE_ATTR_RO(ngpio);
472
473 static int export_gpio_desc(struct gpio_desc *desc)
474 {
475         int offset, ret;
476
477         CLASS(gpio_chip_guard, guard)(desc);
478         if (!guard.gc)
479                 return -ENODEV;
480
481         offset = gpio_chip_hwgpio(desc);
482         if (!gpiochip_line_is_valid(guard.gc, offset)) {
483                 pr_debug_ratelimited("%s: GPIO %d masked\n", __func__,
484                                      gpio_chip_hwgpio(desc));
485                 return -EINVAL;
486         }
487
488         /*
489          * No extra locking here; FLAG_SYSFS just signifies that the
490          * request and export were done by on behalf of userspace, so
491          * they may be undone on its behalf too.
492          */
493
494         ret = gpiod_request_user(desc, "sysfs");
495         if (ret)
496                 return ret;
497
498         ret = gpiod_set_transitory(desc, false);
499         if (ret) {
500                 gpiod_free(desc);
501                 return ret;
502         }
503
504         ret = gpiod_export(desc, true);
505         if (ret < 0) {
506                 gpiod_free(desc);
507         } else {
508                 set_bit(FLAG_SYSFS, &desc->flags);
509                 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_REQUESTED);
510         }
511
512         return ret;
513 }
514
515 static int unexport_gpio_desc(struct gpio_desc *desc)
516 {
517         /*
518          * No extra locking here; FLAG_SYSFS just signifies that the
519          * request and export were done by on behalf of userspace, so
520          * they may be undone on its behalf too.
521          */
522         if (!test_and_clear_bit(FLAG_SYSFS, &desc->flags))
523                 return -EINVAL;
524
525         gpiod_unexport(desc);
526         gpiod_free(desc);
527
528         return 0;
529 }
530
531 static ssize_t do_chip_export_store(struct device *dev,
532                                     struct device_attribute *attr,
533                                     const char *buf, ssize_t size,
534                                     int (*handler)(struct gpio_desc *desc))
535 {
536         struct gpiodev_data *data = dev_get_drvdata(dev);
537         struct gpio_device *gdev = data->gdev;
538         struct gpio_desc *desc;
539         unsigned int gpio;
540         int ret;
541
542         ret = kstrtouint(buf, 0, &gpio);
543         if (ret)
544                 return ret;
545
546         desc = gpio_device_get_desc(gdev, gpio);
547         if (IS_ERR(desc))
548                 return PTR_ERR(desc);
549
550         ret = handler(desc);
551         if (ret)
552                 return ret;
553
554         return size;
555 }
556
557 static ssize_t chip_export_store(struct device *dev,
558                                  struct device_attribute *attr,
559                                  const char *buf, size_t size)
560 {
561         return do_chip_export_store(dev, attr, buf, size, export_gpio_desc);
562 }
563
564 static struct device_attribute dev_attr_export = __ATTR(export, 0200, NULL,
565                                                         chip_export_store);
566
567 static ssize_t chip_unexport_store(struct device *dev,
568                                    struct device_attribute *attr,
569                                    const char *buf, size_t size)
570 {
571         return do_chip_export_store(dev, attr, buf, size, unexport_gpio_desc);
572 }
573
574 static struct device_attribute dev_attr_unexport = __ATTR(unexport, 0200,
575                                                           NULL,
576                                                           chip_unexport_store);
577
578 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
579 static struct attribute *gpiochip_attrs[] = {
580         &dev_attr_base.attr,
581         &dev_attr_label.attr,
582         &dev_attr_ngpio.attr,
583         NULL,
584 };
585 ATTRIBUTE_GROUPS(gpiochip);
586 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
587
588 static struct attribute *gpiochip_ext_attrs[] = {
589         &dev_attr_label.attr,
590         &dev_attr_ngpio.attr,
591         &dev_attr_export.attr,
592         &dev_attr_unexport.attr,
593         NULL
594 };
595 ATTRIBUTE_GROUPS(gpiochip_ext);
596
597 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
598 /*
599  * /sys/class/gpio/export ... write-only
600  *      integer N ... number of GPIO to export (full access)
601  * /sys/class/gpio/unexport ... write-only
602  *      integer N ... number of GPIO to unexport
603  */
604 static ssize_t export_store(const struct class *class,
605                             const struct class_attribute *attr,
606                             const char *buf, size_t len)
607 {
608         struct gpio_desc *desc;
609         int status;
610         long gpio;
611
612         status = kstrtol(buf, 0, &gpio);
613         if (status)
614                 return status;
615
616         desc = gpio_to_desc(gpio);
617         /* reject invalid GPIOs */
618         if (!desc) {
619                 pr_debug_ratelimited("%s: invalid GPIO %ld\n", __func__, gpio);
620                 return -EINVAL;
621         }
622
623         status = export_gpio_desc(desc);
624         if (status)
625                 pr_debug("%s: status %d\n", __func__, status);
626         return status ? : len;
627 }
628 static CLASS_ATTR_WO(export);
629
630 static ssize_t unexport_store(const struct class *class,
631                               const struct class_attribute *attr,
632                               const char *buf, size_t len)
633 {
634         struct gpio_desc *desc;
635         int status;
636         long gpio;
637
638         status = kstrtol(buf, 0, &gpio);
639         if (status < 0)
640                 return status;
641
642         desc = gpio_to_desc(gpio);
643         /* reject bogus commands (gpiod_unexport() ignores them) */
644         if (!desc) {
645                 pr_debug_ratelimited("%s: invalid GPIO %ld\n", __func__, gpio);
646                 return -EINVAL;
647         }
648
649         status = unexport_gpio_desc(desc);
650         if (status)
651                 pr_debug("%s: status %d\n", __func__, status);
652         return status ? : len;
653 }
654 static CLASS_ATTR_WO(unexport);
655
656 static struct attribute *gpio_class_attrs[] = {
657         &class_attr_export.attr,
658         &class_attr_unexport.attr,
659         NULL,
660 };
661 ATTRIBUTE_GROUPS(gpio_class);
662 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
663
664 static const struct class gpio_class = {
665         .name =         "gpio",
666 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
667         .class_groups = gpio_class_groups,
668 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
669 };
670
671 static int match_gdev(struct device *dev, const void *desc)
672 {
673         struct gpiodev_data *data = dev_get_drvdata(dev);
674         const struct gpio_device *gdev = desc;
675
676         return data && data->gdev == gdev;
677 }
678
679 static struct gpiodev_data *
680 gdev_get_data(struct gpio_device *gdev) __must_hold(&sysfs_lock)
681 {
682         /*
683          * Find the first device in GPIO class that matches. Whether that's
684          * the one indexed by GPIO base or device ID doesn't matter, it has
685          * the same address set as driver data.
686          */
687         struct device *cdev __free(put_device) = class_find_device(&gpio_class,
688                                                                    NULL, gdev,
689                                                                    match_gdev);
690         if (!cdev)
691                 return NULL;
692
693         return dev_get_drvdata(cdev);
694 };
695
696 static void gpiod_attr_init(struct device_attribute *dev_attr, const char *name,
697                             ssize_t (*show)(struct device *dev,
698                                             struct device_attribute *attr,
699                                             char *buf),
700                             ssize_t (*store)(struct device *dev,
701                                              struct device_attribute *attr,
702                                              const char *buf, size_t count))
703 {
704         sysfs_attr_init(&dev_attr->attr);
705         dev_attr->attr.name = name;
706         dev_attr->attr.mode = 0644;
707         dev_attr->show = show;
708         dev_attr->store = store;
709 }
710
711 /**
712  * gpiod_export - export a GPIO through sysfs
713  * @desc: GPIO to make available, already requested
714  * @direction_may_change: true if userspace may change GPIO direction
715  * Context: arch_initcall or later
716  *
717  * When drivers want to make a GPIO accessible to userspace after they
718  * have requested it -- perhaps while debugging, or as part of their
719  * public interface -- they may use this routine.  If the GPIO can
720  * change direction (some can't) and the caller allows it, userspace
721  * will see "direction" sysfs attribute which may be used to change
722  * the gpio's direction.  A "value" attribute will always be provided.
723  *
724  * Returns:
725  * 0 on success, or negative errno on failure.
726  */
727 int gpiod_export(struct gpio_desc *desc, bool direction_may_change)
728 {
729         char *path __free(kfree) = NULL;
730         struct gpiodev_data *gdev_data;
731         struct gpiod_data *desc_data;
732         struct gpio_device *gdev;
733         struct attribute **attrs;
734         int status;
735
736         /* can't export until sysfs is available ... */
737         if (!class_is_registered(&gpio_class)) {
738                 pr_debug("%s: called too early!\n", __func__);
739                 return -ENOENT;
740         }
741
742         if (!desc) {
743                 pr_debug("%s: invalid gpio descriptor\n", __func__);
744                 return -EINVAL;
745         }
746
747         CLASS(gpio_chip_guard, guard)(desc);
748         if (!guard.gc)
749                 return -ENODEV;
750
751         if (test_and_set_bit(FLAG_EXPORT, &desc->flags))
752                 return -EPERM;
753
754         gdev = desc->gdev;
755
756         guard(mutex)(&sysfs_lock);
757
758         if (!test_bit(FLAG_REQUESTED, &desc->flags)) {
759                 gpiod_dbg(desc, "%s: unavailable (not requested)\n", __func__);
760                 status = -EPERM;
761                 goto err_clear_bit;
762         }
763
764         desc_data = kzalloc(sizeof(*desc_data), GFP_KERNEL);
765         if (!desc_data) {
766                 status = -ENOMEM;
767                 goto err_clear_bit;
768         }
769
770         desc_data->desc = desc;
771         mutex_init(&desc_data->mutex);
772         if (guard.gc->direction_input && guard.gc->direction_output)
773                 desc_data->direction_can_change = direction_may_change;
774         else
775                 desc_data->direction_can_change = false;
776
777         gpiod_attr_init(&desc_data->dir_attr, "direction",
778                         direction_show, direction_store);
779         gpiod_attr_init(&desc_data->val_attr, "value", value_show, value_store);
780
781 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
782         gpiod_attr_init(&desc_data->edge_attr, "edge", edge_show, edge_store);
783         gpiod_attr_init(&desc_data->active_low_attr, "active_low",
784                         active_low_show, active_low_store);
785
786         attrs = desc_data->class_attrs;
787         desc_data->class_attr_group.is_visible = gpio_is_visible;
788         attrs[GPIO_SYSFS_LINE_CLASS_ATTR_DIRECTION] = &desc_data->dir_attr.attr;
789         attrs[GPIO_SYSFS_LINE_CLASS_ATTR_VALUE] = &desc_data->val_attr.attr;
790         attrs[GPIO_SYSFS_LINE_CLASS_ATTR_EDGE] = &desc_data->edge_attr.attr;
791         attrs[GPIO_SYSFS_LINE_CLASS_ATTR_ACTIVE_LOW] = &desc_data->active_low_attr.attr;
792
793         desc_data->class_attr_group.attrs = desc_data->class_attrs;
794         desc_data->class_attr_groups[0] = &desc_data->class_attr_group;
795
796         /*
797          * Note: we need to continue passing desc_data here as there's still
798          * at least one known user of gpiod_export_link() in the tree. This
799          * function still uses class_find_device() internally.
800          */
801         desc_data->dev = device_create_with_groups(&gpio_class, &gdev->dev,
802                                                    MKDEV(0, 0), desc_data,
803                                                    desc_data->class_attr_groups,
804                                                    "gpio%u",
805                                                    desc_to_gpio(desc));
806         if (IS_ERR(desc_data->dev)) {
807                 status = PTR_ERR(desc_data->dev);
808                 goto err_free_data;
809         }
810
811         desc_data->value_kn = sysfs_get_dirent(desc_data->dev->kobj.sd,
812                                                        "value");
813         if (!desc_data->value_kn) {
814                 status = -ENODEV;
815                 goto err_unregister_device;
816         }
817 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
818
819         gdev_data = gdev_get_data(gdev);
820         if (!gdev_data) {
821                 status = -ENODEV;
822                 goto err_put_dirent;
823         }
824
825         desc_data->chip_attr_group.name = kasprintf(GFP_KERNEL, "gpio%u",
826                                                     gpio_chip_hwgpio(desc));
827         if (!desc_data->chip_attr_group.name) {
828                 status = -ENOMEM;
829                 goto err_put_dirent;
830         }
831
832         attrs = desc_data->chip_attrs;
833         desc_data->chip_attr_group.is_visible = gpio_is_visible;
834         attrs[GPIO_SYSFS_LINE_CHIP_ATTR_DIRECTION] = &desc_data->dir_attr.attr;
835         attrs[GPIO_SYSFS_LINE_CHIP_ATTR_VALUE] = &desc_data->val_attr.attr;
836
837         desc_data->chip_attr_group.attrs = attrs;
838         desc_data->chip_attr_groups[0] = &desc_data->chip_attr_group;
839
840         desc_data->parent = &gdev_data->cdev_id->kobj;
841         status = sysfs_create_groups(desc_data->parent,
842                                      desc_data->chip_attr_groups);
843         if (status)
844                 goto err_free_name;
845
846         path = kasprintf(GFP_KERNEL, "gpio%u/value", gpio_chip_hwgpio(desc));
847         if (!path) {
848                 status = -ENOMEM;
849                 goto err_remove_groups;
850         }
851
852         list_add(&desc_data->list, &gdev_data->exported_lines);
853
854         return 0;
855
856 err_remove_groups:
857         sysfs_remove_groups(desc_data->parent, desc_data->chip_attr_groups);
858 err_free_name:
859         kfree(desc_data->chip_attr_group.name);
860 err_put_dirent:
861 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
862         sysfs_put(desc_data->value_kn);
863 err_unregister_device:
864         device_unregister(desc_data->dev);
865 err_free_data:
866 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
867         kfree(desc_data);
868 err_clear_bit:
869         clear_bit(FLAG_EXPORT, &desc->flags);
870         gpiod_dbg(desc, "%s: status %d\n", __func__, status);
871         return status;
872 }
873 EXPORT_SYMBOL_GPL(gpiod_export);
874
875 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
876 static int match_export(struct device *dev, const void *desc)
877 {
878         struct gpiod_data *data = dev_get_drvdata(dev);
879
880         return gpiod_is_equal(data->desc, desc);
881 }
882 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
883
884 /**
885  * gpiod_export_link - create a sysfs link to an exported GPIO node
886  * @dev: device under which to create symlink
887  * @name: name of the symlink
888  * @desc: GPIO to create symlink to, already exported
889  *
890  * Set up a symlink from /sys/.../dev/name to /sys/class/gpio/gpioN
891  * node. Caller is responsible for unlinking.
892  *
893  * Returns:
894  * 0 on success, or negative errno on failure.
895  */
896 int gpiod_export_link(struct device *dev, const char *name,
897                       struct gpio_desc *desc)
898 {
899 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
900         struct device *cdev;
901         int ret;
902
903         if (!desc) {
904                 pr_warn("%s: invalid GPIO\n", __func__);
905                 return -EINVAL;
906         }
907
908         cdev = class_find_device(&gpio_class, NULL, desc, match_export);
909         if (!cdev)
910                 return -ENODEV;
911
912         ret = sysfs_create_link(&dev->kobj, &cdev->kobj, name);
913         put_device(cdev);
914
915         return ret;
916 #else
917         return -EOPNOTSUPP;
918 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
919 }
920 EXPORT_SYMBOL_GPL(gpiod_export_link);
921
922 /**
923  * gpiod_unexport - reverse effect of gpiod_export()
924  * @desc: GPIO to make unavailable
925  *
926  * This is implicit on gpiod_free().
927  */
928 void gpiod_unexport(struct gpio_desc *desc)
929 {
930         struct gpiod_data *tmp, *desc_data = NULL;
931         struct gpiodev_data *gdev_data;
932         struct gpio_device *gdev;
933
934         if (!desc) {
935                 pr_warn("%s: invalid GPIO\n", __func__);
936                 return;
937         }
938
939         scoped_guard(mutex, &sysfs_lock) {
940                 if (!test_bit(FLAG_EXPORT, &desc->flags))
941                         return;
942
943                 gdev = gpiod_to_gpio_device(desc);
944                 gdev_data = gdev_get_data(gdev);
945                 if (!gdev_data)
946                         return;
947
948                 list_for_each_entry(tmp, &gdev_data->exported_lines, list) {
949                         if (gpiod_is_equal(desc, tmp->desc)) {
950                                 desc_data = tmp;
951                                 break;
952                         }
953                 }
954
955                 if (!desc_data)
956                         return;
957
958                 list_del(&desc_data->list);
959                 clear_bit(FLAG_EXPORT, &desc->flags);
960 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
961                 sysfs_put(desc_data->value_kn);
962                 device_unregister(desc_data->dev);
963
964                 /*
965                  * Release irq after deregistration to prevent race with
966                  * edge_store.
967                  */
968                 if (desc_data->irq_flags)
969                         gpio_sysfs_free_irq(desc_data);
970 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
971
972                 sysfs_remove_groups(desc_data->parent,
973                                     desc_data->chip_attr_groups);
974         }
975
976         mutex_destroy(&desc_data->mutex);
977         kfree(desc_data);
978 }
979 EXPORT_SYMBOL_GPL(gpiod_unexport);
980
981 int gpiochip_sysfs_register(struct gpio_device *gdev)
982 {
983         struct gpiodev_data *data;
984         struct gpio_chip *chip;
985         struct device *parent;
986         int err;
987
988         /*
989          * Many systems add gpio chips for SOC support very early,
990          * before driver model support is available.  In those cases we
991          * register later, in gpiolib_sysfs_init() ... here we just
992          * verify that _some_ field of gpio_class got initialized.
993          */
994         if (!class_is_registered(&gpio_class))
995                 return 0;
996
997         guard(srcu)(&gdev->srcu);
998
999         chip = srcu_dereference(gdev->chip, &gdev->srcu);
1000         if (!chip)
1001                 return -ENODEV;
1002
1003         /*
1004          * For sysfs backward compatibility we need to preserve this
1005          * preferred parenting to the gpio_chip parent field, if set.
1006          */
1007         if (chip->parent)
1008                 parent = chip->parent;
1009         else
1010                 parent = &gdev->dev;
1011
1012         data = kmalloc(sizeof(*data), GFP_KERNEL);
1013         if (!data)
1014                 return -ENOMEM;
1015
1016         data->gdev = gdev;
1017         INIT_LIST_HEAD(&data->exported_lines);
1018
1019         guard(mutex)(&sysfs_lock);
1020
1021 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
1022         /* use chip->base for the ID; it's already known to be unique */
1023         data->cdev_base = device_create_with_groups(&gpio_class, parent,
1024                                                     MKDEV(0, 0), data,
1025                                                     gpiochip_groups,
1026                                                     GPIOCHIP_NAME "%d",
1027                                                     chip->base);
1028         if (IS_ERR(data->cdev_base)) {
1029                 err = PTR_ERR(data->cdev_base);
1030                 kfree(data);
1031                 return err;
1032         }
1033 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
1034
1035         data->cdev_id = device_create_with_groups(&gpio_class, parent,
1036                                                   MKDEV(0, 0), data,
1037                                                   gpiochip_ext_groups,
1038                                                   "chip%d", gdev->id);
1039         if (IS_ERR(data->cdev_id)) {
1040 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
1041                 device_unregister(data->cdev_base);
1042 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
1043                 err = PTR_ERR(data->cdev_id);
1044                 kfree(data);
1045                 return err;
1046         }
1047
1048         return 0;
1049 }
1050
1051 void gpiochip_sysfs_unregister(struct gpio_device *gdev)
1052 {
1053         struct gpiodev_data *data;
1054         struct gpio_desc *desc;
1055         struct gpio_chip *chip;
1056
1057         scoped_guard(mutex, &sysfs_lock) {
1058                 data = gdev_get_data(gdev);
1059                 if (!data)
1060                         return;
1061
1062 #if IS_ENABLED(CONFIG_GPIO_SYSFS_LEGACY)
1063                 device_unregister(data->cdev_base);
1064 #endif /* CONFIG_GPIO_SYSFS_LEGACY */
1065                 device_unregister(data->cdev_id);
1066                 kfree(data);
1067         }
1068
1069         guard(srcu)(&gdev->srcu);
1070
1071         chip = srcu_dereference(gdev->chip, &gdev->srcu);
1072         if (!chip)
1073                 return;
1074
1075         /* unregister gpiod class devices owned by sysfs */
1076         for_each_gpio_desc_with_flag(chip, desc, FLAG_SYSFS) {
1077                 gpiod_unexport(desc);
1078                 gpiod_free(desc);
1079         }
1080 }
1081
1082 /*
1083  * We're not really looking for a device - we just want to iterate over the
1084  * list and call this callback for each GPIO device. This is why this function
1085  * always returns 0.
1086  */
1087 static int gpiofind_sysfs_register(struct gpio_chip *gc, const void *data)
1088 {
1089         struct gpio_device *gdev = gc->gpiodev;
1090         int ret;
1091
1092         ret = gpiochip_sysfs_register(gdev);
1093         if (ret)
1094                 chip_err(gc, "failed to register the sysfs entry: %d\n", ret);
1095
1096         return 0;
1097 }
1098
1099 static int __init gpiolib_sysfs_init(void)
1100 {
1101         int status;
1102
1103         status = class_register(&gpio_class);
1104         if (status < 0)
1105                 return status;
1106
1107         /* Scan and register the gpio_chips which registered very
1108          * early (e.g. before the class_register above was called).
1109          *
1110          * We run before arch_initcall() so chip->dev nodes can have
1111          * registered, and so arch_initcall() can always gpiod_export().
1112          */
1113         (void)gpio_device_find(NULL, gpiofind_sysfs_register);
1114
1115         return 0;
1116 }
1117 postcore_initcall(gpiolib_sysfs_init);