linux/drivers/gpio/gpiolib.c
<<
>>
Prefs
   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/list.h>
   7#include <linux/device.h>
   8#include <linux/err.h>
   9#include <linux/debugfs.h>
  10#include <linux/seq_file.h>
  11#include <linux/gpio.h>
  12#include <linux/of_gpio.h>
  13#include <linux/idr.h>
  14#include <linux/slab.h>
  15#include <linux/acpi.h>
  16#include <linux/gpio/driver.h>
  17#include <linux/pinctrl/consumer.h>
  18
  19#include "gpiolib.h"
  20
  21#define CREATE_TRACE_POINTS
  22#include <trace/events/gpio.h>
  23
  24/* Implementation infrastructure for GPIO interfaces.
  25 *
  26 * The GPIO programming interface allows for inlining speed-critical
  27 * get/set operations for common cases, so that access to SOC-integrated
  28 * GPIOs can sometimes cost only an instruction or two per bit.
  29 */
  30
  31
  32/* When debugging, extend minimal trust to callers and platform code.
  33 * Also emit diagnostic messages that may help initial bringup, when
  34 * board setup or driver bugs are most common.
  35 *
  36 * Otherwise, minimize overhead in what may be bitbanging codepaths.
  37 */
  38#ifdef  DEBUG
  39#define extra_checks    1
  40#else
  41#define extra_checks    0
  42#endif
  43
  44/* Device and char device-related information */
  45static DEFINE_IDA(gpio_ida);
  46
  47/* gpio_lock prevents conflicts during gpio_desc[] table updates.
  48 * While any GPIO is requested, its gpio_chip is not removable;
  49 * each GPIO's "requested" flag serves as a lock and refcount.
  50 */
  51static DEFINE_SPINLOCK(gpio_lock);
  52
  53struct gpio_desc {
  54        struct gpio_chip        *chip;
  55        unsigned long           flags;
  56/* flag symbols are bit numbers */
  57#define FLAG_REQUESTED  0
  58#define FLAG_IS_OUT     1
  59#define FLAG_EXPORT     2       /* protected by sysfs_lock */
  60#define FLAG_SYSFS      3       /* exported via /sys/class/gpio/control */
  61#define FLAG_TRIG_FALL  4       /* trigger on falling edge */
  62#define FLAG_TRIG_RISE  5       /* trigger on rising edge */
  63#define FLAG_ACTIVE_LOW 6       /* value has active low */
  64#define FLAG_OPEN_DRAIN 7       /* Gpio is open drain type */
  65#define FLAG_OPEN_SOURCE 8      /* Gpio is open source type */
  66#define FLAG_USED_AS_IRQ 9      /* GPIO is connected to an IRQ */
  67
  68#define ID_SHIFT        16      /* add new flags before this one */
  69
  70#define GPIO_FLAGS_MASK         ((1 << ID_SHIFT) - 1)
  71#define GPIO_TRIGGER_MASK       (BIT(FLAG_TRIG_FALL) | BIT(FLAG_TRIG_RISE))
  72
  73#ifdef CONFIG_DEBUG_FS
  74        const char              *label;
  75#endif
  76};
  77
  78#define GPIO_OFFSET_VALID(chip, offset) (offset >= 0 && offset < chip->ngpio)
  79
  80static DEFINE_MUTEX(gpio_lookup_lock);
  81static LIST_HEAD(gpio_lookup_list);
  82LIST_HEAD(gpio_devices);
  83
  84#ifdef CONFIG_GPIO_SYSFS
  85static DEFINE_IDR(dirent_idr);
  86#endif
  87
  88static int gpiod_request(struct gpio_desc *desc, const char *label);
  89static void gpiod_free(struct gpio_desc *desc);
  90
  91/* With descriptor prefix */
  92
  93#ifdef CONFIG_DEBUG_FS
  94#define gpiod_emerg(desc, fmt, ...)                                            \
  95        pr_emerg("gpio-%d (%s): " fmt, desc_to_gpio(desc), desc->label ? : "?",\
  96                 ##__VA_ARGS__)
  97#define gpiod_crit(desc, fmt, ...)                                             \
  98        pr_crit("gpio-%d (%s): " fmt, desc_to_gpio(desc), desc->label ? : "?", \
  99                 ##__VA_ARGS__)
 100#define gpiod_err(desc, fmt, ...)                                              \
 101        pr_err("gpio-%d (%s): " fmt, desc_to_gpio(desc), desc->label ? : "?",  \
 102                 ##__VA_ARGS__)
 103#define gpiod_warn(desc, fmt, ...)                                             \
 104        pr_warn("gpio-%d (%s): " fmt, desc_to_gpio(desc), desc->label ? : "?", \
 105                 ##__VA_ARGS__)
 106#define gpiod_info(desc, fmt, ...)                                             \
 107        pr_info("gpio-%d (%s): " fmt, desc_to_gpio(desc), desc->label ? : "?", \
 108                ##__VA_ARGS__)
 109#define gpiod_dbg(desc, fmt, ...)                                              \
 110        pr_debug("gpio-%d (%s): " fmt, desc_to_gpio(desc), desc->label ? : "?",\
 111                 ##__VA_ARGS__)
 112#else
 113#define gpiod_emerg(desc, fmt, ...)                                     \
 114        pr_emerg("gpio-%d: " fmt, desc_to_gpio(desc), ##__VA_ARGS__)
 115#define gpiod_crit(desc, fmt, ...)                                      \
 116        pr_crit("gpio-%d: " fmt, desc_to_gpio(desc), ##__VA_ARGS__)
 117#define gpiod_err(desc, fmt, ...)                                       \
 118        pr_err("gpio-%d: " fmt, desc_to_gpio(desc), ##__VA_ARGS__)
 119#define gpiod_warn(desc, fmt, ...)                                      \
 120        pr_warn("gpio-%d: " fmt, desc_to_gpio(desc), ##__VA_ARGS__)
 121#define gpiod_info(desc, fmt, ...)                                      \
 122        pr_info("gpio-%d: " fmt, desc_to_gpio(desc), ##__VA_ARGS__)
 123#define gpiod_dbg(desc, fmt, ...)                                       \
 124        pr_debug("gpio-%d: " fmt, desc_to_gpio(desc), ##__VA_ARGS__)
 125#endif
 126
 127/* With chip prefix */
 128
 129#define chip_emerg(chip, fmt, ...)                                      \
 130        pr_emerg("GPIO chip %s: " fmt, chip->label, ##__VA_ARGS__)
 131#define chip_crit(chip, fmt, ...)                                       \
 132        pr_crit("GPIO chip %s: " fmt, chip->label, ##__VA_ARGS__)
 133#define chip_err(chip, fmt, ...)                                        \
 134        pr_err("GPIO chip %s: " fmt, chip->label, ##__VA_ARGS__)
 135#define chip_warn(chip, fmt, ...)                                       \
 136        pr_warn("GPIO chip %s: " fmt, chip->label, ##__VA_ARGS__)
 137#define chip_info(chip, fmt, ...)                                       \
 138        pr_info("GPIO chip %s: " fmt, chip->label, ##__VA_ARGS__)
 139#define chip_dbg(chip, fmt, ...)                                        \
 140        pr_debug("GPIO chip %s: " fmt, chip->label, ##__VA_ARGS__)
 141
 142static inline void desc_set_label(struct gpio_desc *d, const char *label)
 143{
 144#ifdef CONFIG_DEBUG_FS
 145        d->label = label;
 146#endif
 147}
 148
 149/*
 150 * Return the GPIO number of the passed descriptor relative to its chip
 151 */
 152static int gpio_chip_hwgpio(const struct gpio_desc *desc)
 153{
 154        return desc - &desc->chip->desc[0];
 155}
 156
 157/**
 158 * Convert a GPIO number to its descriptor
 159 */
 160struct gpio_desc *gpio_to_desc(unsigned gpio)
 161{
 162        struct gpio_device *gdev;
 163        unsigned long flags;
 164
 165        spin_lock_irqsave(&gpio_lock, flags);
 166
 167        list_for_each_entry(gdev, &gpio_devices, list) {
 168                if (gdev->base <= gpio &&
 169                    gdev->base + gdev->ngpio > gpio) {
 170                        spin_unlock_irqrestore(&gpio_lock, flags);
 171                        return &gdev->chip->desc[gpio - gdev->base];
 172                }
 173        }
 174
 175        spin_unlock_irqrestore(&gpio_lock, flags);
 176
 177        WARN(1, "invalid GPIO %d\n", gpio);
 178        return NULL;
 179}
 180EXPORT_SYMBOL_GPL(gpio_to_desc);
 181
 182/**
 183 * Convert an offset on a certain chip to a corresponding descriptor
 184 */
 185static struct gpio_desc *gpiochip_offset_to_desc(struct gpio_chip *chip,
 186                                                 unsigned int offset)
 187{
 188        if (offset >= chip->ngpio)
 189                return ERR_PTR(-EINVAL);
 190
 191        return &chip->desc[offset];
 192}
 193
 194/**
 195 * Convert a GPIO descriptor to the integer namespace.
 196 * This should disappear in the future but is needed since we still
 197 * use GPIO numbers for error messages and sysfs nodes
 198 */
 199int desc_to_gpio(const struct gpio_desc *desc)
 200{
 201        return desc->chip->base + (desc - &desc->chip->desc[0]);
 202}
 203EXPORT_SYMBOL_GPL(desc_to_gpio);
 204
 205
 206/* Warn when drivers omit gpio_request() calls -- legal but ill-advised
 207 * when setting direction, and otherwise illegal.  Until board setup code
 208 * and drivers use explicit requests everywhere (which won't happen when
 209 * those calls have no teeth) we can't avoid autorequesting.  This nag
 210 * message should motivate switching to explicit requests... so should
 211 * the weaker cleanup after faults, compared to gpio_request().
 212 *
 213 * NOTE: the autorequest mechanism is going away; at this point it's
 214 * only "legal" in the sense that (old) code using it won't break yet,
 215 * but instead only triggers a WARN() stack dump.
 216 */
 217static int gpio_ensure_requested(struct gpio_desc *desc)
 218{
 219        const struct gpio_chip *chip = desc->chip;
 220        const int gpio = desc_to_gpio(desc);
 221
 222        if (WARN(test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0,
 223                        "autorequest GPIO-%d\n", gpio)) {
 224                if (!try_module_get(chip->gpiodev->owner)) {
 225                        gpiod_err(desc, "%s: module can't be gotten\n",
 226                                        __func__);
 227                        clear_bit(FLAG_REQUESTED, &desc->flags);
 228                        /* lose */
 229                        return -EIO;
 230                }
 231                desc_set_label(desc, "[auto]");
 232                /* caller must chip->request() w/o spinlock */
 233                if (chip->request)
 234                        return 1;
 235        }
 236        return 0;
 237}
 238
 239/**
 240 * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
 241 * @desc:       descriptor to return the chip of
 242 */
 243struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
 244{
 245        return desc ? desc->chip : NULL;
 246}
 247EXPORT_SYMBOL_GPL(gpiod_to_chip);
 248
 249/* dynamic allocation of GPIOs, e.g. on a hotplugged device */
 250static int gpiochip_find_base(int ngpio)
 251{
 252        struct gpio_device *gdev;
 253        int base = ARCH_NR_GPIOS - ngpio;
 254
 255        list_for_each_entry_reverse(gdev, &gpio_devices, list) {
 256                /* found a free space? */
 257                if (gdev->base + gdev->ngpio <= base)
 258                        break;
 259                else
 260                        /* nope, check the space right before the chip */
 261                        base = gdev->base - ngpio;
 262        }
 263
 264        if (gpio_is_valid(base)) {
 265                pr_debug("%s: found new base at %d\n", __func__, base);
 266                return base;
 267        } else {
 268                pr_err("%s: cannot find free range\n", __func__);
 269                return -ENOSPC;
 270        }
 271}
 272
 273/**
 274 * gpiod_get_direction - return the current direction of a GPIO
 275 * @desc:       GPIO to get the direction of
 276 *
 277 * Return GPIOF_DIR_IN or GPIOF_DIR_OUT, or an error code in case of error.
 278 *
 279 * This function may sleep if gpiod_cansleep() is true.
 280 */
 281int gpiod_get_direction(const struct gpio_desc *desc)
 282{
 283        struct gpio_chip        *chip;
 284        unsigned                offset;
 285        int                     status = -EINVAL;
 286
 287        chip = gpiod_to_chip(desc);
 288        offset = gpio_chip_hwgpio(desc);
 289
 290        if (!chip->get_direction)
 291                return status;
 292
 293        status = chip->get_direction(chip, offset);
 294        if (status > 0) {
 295                /* GPIOF_DIR_IN, or other positive */
 296                status = 1;
 297                /* FLAG_IS_OUT is just a cache of the result of get_direction(),
 298                 * so it does not affect constness per se */
 299                clear_bit(FLAG_IS_OUT, &((struct gpio_desc *)desc)->flags);
 300        }
 301        if (status == 0) {
 302                /* GPIOF_DIR_OUT */
 303                set_bit(FLAG_IS_OUT, &((struct gpio_desc *)desc)->flags);
 304        }
 305        return status;
 306}
 307EXPORT_SYMBOL_GPL(gpiod_get_direction);
 308
 309#ifdef CONFIG_GPIO_SYSFS
 310
 311/* lock protects against unexport_gpio() being called while
 312 * sysfs files are active.
 313 */
 314static DEFINE_MUTEX(sysfs_lock);
 315
 316/*
 317 * /sys/class/gpio/gpioN... only for GPIOs that are exported
 318 *   /direction
 319 *      * MAY BE OMITTED if kernel won't allow direction changes
 320 *      * is read/write as "in" or "out"
 321 *      * may also be written as "high" or "low", initializing
 322 *        output value as specified ("out" implies "low")
 323 *   /value
 324 *      * always readable, subject to hardware behavior
 325 *      * may be writable, as zero/nonzero
 326 *   /edge
 327 *      * configures behavior of poll(2) on /value
 328 *      * available only if pin can generate IRQs on input
 329 *      * is read/write as "none", "falling", "rising", or "both"
 330 *   /active_low
 331 *      * configures polarity of /value
 332 *      * is read/write as zero/nonzero
 333 *      * also affects existing and subsequent "falling" and "rising"
 334 *        /edge configuration
 335 */
 336
 337static ssize_t gpio_direction_show(struct device *dev,
 338                struct device_attribute *attr, char *buf)
 339{
 340        const struct gpio_desc  *desc = dev_get_drvdata(dev);
 341        ssize_t                 status;
 342
 343        mutex_lock(&sysfs_lock);
 344
 345        if (!test_bit(FLAG_EXPORT, &desc->flags)) {
 346                status = -EIO;
 347        } else {
 348                gpiod_get_direction(desc);
 349                status = sprintf(buf, "%s\n",
 350                        test_bit(FLAG_IS_OUT, &desc->flags)
 351                                ? "out" : "in");
 352        }
 353
 354        mutex_unlock(&sysfs_lock);
 355        return status;
 356}
 357
 358static ssize_t gpio_direction_store(struct device *dev,
 359                struct device_attribute *attr, const char *buf, size_t size)
 360{
 361        struct gpio_desc        *desc = dev_get_drvdata(dev);
 362        ssize_t                 status;
 363
 364        mutex_lock(&sysfs_lock);
 365
 366        if (!test_bit(FLAG_EXPORT, &desc->flags))
 367                status = -EIO;
 368        else if (sysfs_streq(buf, "high"))
 369                status = gpiod_direction_output(desc, 1);
 370        else if (sysfs_streq(buf, "out") || sysfs_streq(buf, "low"))
 371                status = gpiod_direction_output(desc, 0);
 372        else if (sysfs_streq(buf, "in"))
 373                status = gpiod_direction_input(desc);
 374        else
 375                status = -EINVAL;
 376
 377        mutex_unlock(&sysfs_lock);
 378        return status ? : size;
 379}
 380
 381static /* const */ DEVICE_ATTR(direction, 0644,
 382                gpio_direction_show, gpio_direction_store);
 383
 384static ssize_t gpio_value_show(struct device *dev,
 385                struct device_attribute *attr, char *buf)
 386{
 387        struct gpio_desc        *desc = dev_get_drvdata(dev);
 388        ssize_t                 status;
 389
 390        mutex_lock(&sysfs_lock);
 391
 392        if (!test_bit(FLAG_EXPORT, &desc->flags))
 393                status = -EIO;
 394        else
 395                status = sprintf(buf, "%d\n", gpiod_get_value_cansleep(desc));
 396
 397        mutex_unlock(&sysfs_lock);
 398        return status;
 399}
 400
 401static ssize_t gpio_value_store(struct device *dev,
 402                struct device_attribute *attr, const char *buf, size_t size)
 403{
 404        struct gpio_desc        *desc = dev_get_drvdata(dev);
 405        ssize_t                 status;
 406
 407        mutex_lock(&sysfs_lock);
 408
 409        if (!test_bit(FLAG_EXPORT, &desc->flags))
 410                status = -EIO;
 411        else if (!test_bit(FLAG_IS_OUT, &desc->flags))
 412                status = -EPERM;
 413        else {
 414                long            value;
 415
 416                status = kstrtol(buf, 0, &value);
 417                if (status == 0) {
 418                        gpiod_set_value_cansleep(desc, value);
 419                        status = size;
 420                }
 421        }
 422
 423        mutex_unlock(&sysfs_lock);
 424        return status;
 425}
 426
 427static const DEVICE_ATTR(value, 0644,
 428                gpio_value_show, gpio_value_store);
 429
 430static irqreturn_t gpio_sysfs_irq(int irq, void *priv)
 431{
 432        struct kernfs_node      *value_sd = priv;
 433
 434        sysfs_notify_dirent(value_sd);
 435        return IRQ_HANDLED;
 436}
 437
 438static int gpio_setup_irq(struct gpio_desc *desc, struct device *dev,
 439                unsigned long gpio_flags)
 440{
 441        struct kernfs_node      *value_sd;
 442        unsigned long           irq_flags;
 443        int                     ret, irq, id;
 444
 445        if ((desc->flags & GPIO_TRIGGER_MASK) == gpio_flags)
 446                return 0;
 447
 448        irq = gpiod_to_irq(desc);
 449        if (irq < 0)
 450                return -EIO;
 451
 452        id = desc->flags >> ID_SHIFT;
 453        value_sd = idr_find(&dirent_idr, id);
 454        if (value_sd)
 455                free_irq(irq, value_sd);
 456
 457        desc->flags &= ~GPIO_TRIGGER_MASK;
 458
 459        if (!gpio_flags) {
 460                gpiod_unlock_as_irq(desc);
 461                ret = 0;
 462                goto free_id;
 463        }
 464
 465        irq_flags = IRQF_SHARED;
 466        if (test_bit(FLAG_TRIG_FALL, &gpio_flags))
 467                irq_flags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
 468                        IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
 469        if (test_bit(FLAG_TRIG_RISE, &gpio_flags))
 470                irq_flags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
 471                        IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
 472
 473        if (!value_sd) {
 474                value_sd = sysfs_get_dirent(dev->kobj.sd, "value");
 475                if (!value_sd) {
 476                        ret = -ENODEV;
 477                        goto err_out;
 478                }
 479
 480                ret = idr_alloc(&dirent_idr, value_sd, 1, 0, GFP_KERNEL);
 481                if (ret < 0)
 482                        goto free_sd;
 483                id = ret;
 484
 485                desc->flags &= GPIO_FLAGS_MASK;
 486                desc->flags |= (unsigned long)id << ID_SHIFT;
 487
 488                if (desc->flags >> ID_SHIFT != id) {
 489                        ret = -ERANGE;
 490                        goto free_id;
 491                }
 492        }
 493
 494        ret = request_any_context_irq(irq, gpio_sysfs_irq, irq_flags,
 495                                "gpiolib", value_sd);
 496        if (ret < 0)
 497                goto free_id;
 498
 499        ret = gpiod_lock_as_irq(desc);
 500        if (ret < 0) {
 501                gpiod_warn(desc, "failed to flag the GPIO for IRQ\n");
 502                goto free_id;
 503        }
 504
 505        desc->flags |= gpio_flags;
 506        return 0;
 507
 508free_id:
 509        idr_remove(&dirent_idr, id);
 510        desc->flags &= GPIO_FLAGS_MASK;
 511free_sd:
 512        if (value_sd)
 513                sysfs_put(value_sd);
 514err_out:
 515        return ret;
 516}
 517
 518static const struct {
 519        const char *name;
 520        unsigned long flags;
 521} trigger_types[] = {
 522        { "none",    0 },
 523        { "falling", BIT(FLAG_TRIG_FALL) },
 524        { "rising",  BIT(FLAG_TRIG_RISE) },
 525        { "both",    BIT(FLAG_TRIG_FALL) | BIT(FLAG_TRIG_RISE) },
 526};
 527
 528static ssize_t gpio_edge_show(struct device *dev,
 529                struct device_attribute *attr, char *buf)
 530{
 531        const struct gpio_desc  *desc = dev_get_drvdata(dev);
 532        ssize_t                 status;
 533
 534        mutex_lock(&sysfs_lock);
 535
 536        if (!test_bit(FLAG_EXPORT, &desc->flags))
 537                status = -EIO;
 538        else {
 539                int i;
 540
 541                status = 0;
 542                for (i = 0; i < ARRAY_SIZE(trigger_types); i++)
 543                        if ((desc->flags & GPIO_TRIGGER_MASK)
 544                                        == trigger_types[i].flags) {
 545                                status = sprintf(buf, "%s\n",
 546                                                 trigger_types[i].name);
 547                                break;
 548                        }
 549        }
 550
 551        mutex_unlock(&sysfs_lock);
 552        return status;
 553}
 554
 555static ssize_t gpio_edge_store(struct device *dev,
 556                struct device_attribute *attr, const char *buf, size_t size)
 557{
 558        struct gpio_desc        *desc = dev_get_drvdata(dev);
 559        ssize_t                 status;
 560        int                     i;
 561
 562        for (i = 0; i < ARRAY_SIZE(trigger_types); i++)
 563                if (sysfs_streq(trigger_types[i].name, buf))
 564                        goto found;
 565        return -EINVAL;
 566
 567found:
 568        mutex_lock(&sysfs_lock);
 569
 570        if (!test_bit(FLAG_EXPORT, &desc->flags))
 571                status = -EIO;
 572        else {
 573                status = gpio_setup_irq(desc, dev, trigger_types[i].flags);
 574                if (!status)
 575                        status = size;
 576        }
 577
 578        mutex_unlock(&sysfs_lock);
 579
 580        return status;
 581}
 582
 583static DEVICE_ATTR(edge, 0644, gpio_edge_show, gpio_edge_store);
 584
 585static int sysfs_set_active_low(struct gpio_desc *desc, struct device *dev,
 586                                int value)
 587{
 588        int                     status = 0;
 589
 590        if (!!test_bit(FLAG_ACTIVE_LOW, &desc->flags) == !!value)
 591                return 0;
 592
 593        if (value)
 594                set_bit(FLAG_ACTIVE_LOW, &desc->flags);
 595        else
 596                clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
 597
 598        /* reconfigure poll(2) support if enabled on one edge only */
 599        if (dev != NULL && (!!test_bit(FLAG_TRIG_RISE, &desc->flags) ^
 600                                !!test_bit(FLAG_TRIG_FALL, &desc->flags))) {
 601                unsigned long trigger_flags = desc->flags & GPIO_TRIGGER_MASK;
 602
 603                gpio_setup_irq(desc, dev, 0);
 604                status = gpio_setup_irq(desc, dev, trigger_flags);
 605        }
 606
 607        return status;
 608}
 609
 610static ssize_t gpio_active_low_show(struct device *dev,
 611                struct device_attribute *attr, char *buf)
 612{
 613        const struct gpio_desc  *desc = dev_get_drvdata(dev);
 614        ssize_t                 status;
 615
 616        mutex_lock(&sysfs_lock);
 617
 618        if (!test_bit(FLAG_EXPORT, &desc->flags))
 619                status = -EIO;
 620        else
 621                status = sprintf(buf, "%d\n",
 622                                !!test_bit(FLAG_ACTIVE_LOW, &desc->flags));
 623
 624        mutex_unlock(&sysfs_lock);
 625
 626        return status;
 627}
 628
 629static ssize_t gpio_active_low_store(struct device *dev,
 630                struct device_attribute *attr, const char *buf, size_t size)
 631{
 632        struct gpio_desc        *desc = dev_get_drvdata(dev);
 633        ssize_t                 status;
 634
 635        mutex_lock(&sysfs_lock);
 636
 637        if (!test_bit(FLAG_EXPORT, &desc->flags)) {
 638                status = -EIO;
 639        } else {
 640                long            value;
 641
 642                status = kstrtol(buf, 0, &value);
 643                if (status == 0)
 644                        status = sysfs_set_active_low(desc, dev, value != 0);
 645        }
 646
 647        mutex_unlock(&sysfs_lock);
 648
 649        return status ? : size;
 650}
 651
 652static const DEVICE_ATTR(active_low, 0644,
 653                gpio_active_low_show, gpio_active_low_store);
 654
 655static const struct attribute *gpio_attrs[] = {
 656        &dev_attr_value.attr,
 657        &dev_attr_active_low.attr,
 658        NULL,
 659};
 660
 661static const struct attribute_group gpio_attr_group = {
 662        .attrs = (struct attribute **) gpio_attrs,
 663};
 664
 665/*
 666 * /sys/class/gpio/gpiochipN/
 667 *   /base ... matching gpio_chip.base (N)
 668 *   /label ... matching gpio_chip.label
 669 *   /ngpio ... matching gpio_chip.ngpio
 670 */
 671
 672static ssize_t chip_base_show(struct device *dev,
 673                               struct device_attribute *attr, char *buf)
 674{
 675        const struct gpio_chip  *chip = dev_get_drvdata(dev);
 676
 677        return sprintf(buf, "%d\n", chip->base);
 678}
 679static DEVICE_ATTR(base, 0444, chip_base_show, NULL);
 680
 681static ssize_t chip_label_show(struct device *dev,
 682                               struct device_attribute *attr, char *buf)
 683{
 684        const struct gpio_chip  *chip = dev_get_drvdata(dev);
 685
 686        return sprintf(buf, "%s\n", chip->label ? : "");
 687}
 688static DEVICE_ATTR(label, 0444, chip_label_show, NULL);
 689
 690static ssize_t chip_ngpio_show(struct device *dev,
 691                               struct device_attribute *attr, char *buf)
 692{
 693        const struct gpio_chip  *chip = dev_get_drvdata(dev);
 694
 695        return sprintf(buf, "%u\n", chip->ngpio);
 696}
 697static DEVICE_ATTR(ngpio, 0444, chip_ngpio_show, NULL);
 698
 699static const struct attribute *gpiochip_attrs[] = {
 700        &dev_attr_base.attr,
 701        &dev_attr_label.attr,
 702        &dev_attr_ngpio.attr,
 703        NULL,
 704};
 705
 706static const struct attribute_group gpiochip_attr_group = {
 707        .attrs = (struct attribute **) gpiochip_attrs,
 708};
 709
 710/*
 711 * /sys/class/gpio/export ... write-only
 712 *      integer N ... number of GPIO to export (full access)
 713 * /sys/class/gpio/unexport ... write-only
 714 *      integer N ... number of GPIO to unexport
 715 */
 716static ssize_t export_store(struct class *class,
 717                                struct class_attribute *attr,
 718                                const char *buf, size_t len)
 719{
 720        long                    gpio;
 721        struct gpio_desc        *desc;
 722        int                     status;
 723
 724        status = kstrtol(buf, 0, &gpio);
 725        if (status < 0)
 726                goto done;
 727
 728        desc = gpio_to_desc(gpio);
 729        /* reject invalid GPIOs */
 730        if (!desc) {
 731                pr_warn("%s: invalid GPIO %ld\n", __func__, gpio);
 732                return -EINVAL;
 733        }
 734
 735        /* No extra locking here; FLAG_SYSFS just signifies that the
 736         * request and export were done by on behalf of userspace, so
 737         * they may be undone on its behalf too.
 738         */
 739
 740        status = gpiod_request(desc, "sysfs");
 741        if (status < 0) {
 742                if (status == -EPROBE_DEFER)
 743                        status = -ENODEV;
 744                goto done;
 745        }
 746        status = gpiod_export(desc, true);
 747        if (status < 0)
 748                gpiod_free(desc);
 749        else
 750                set_bit(FLAG_SYSFS, &desc->flags);
 751
 752done:
 753        if (status)
 754                pr_debug("%s: status %d\n", __func__, status);
 755        return status ? : len;
 756}
 757
 758static ssize_t unexport_store(struct class *class,
 759                                struct class_attribute *attr,
 760                                const char *buf, size_t len)
 761{
 762        long                    gpio;
 763        struct gpio_desc        *desc;
 764        int                     status;
 765
 766        status = kstrtol(buf, 0, &gpio);
 767        if (status < 0)
 768                goto done;
 769
 770        desc = gpio_to_desc(gpio);
 771        /* reject bogus commands (gpio_unexport ignores them) */
 772        if (!desc) {
 773                pr_warn("%s: invalid GPIO %ld\n", __func__, gpio);
 774                return -EINVAL;
 775        }
 776
 777        status = -EINVAL;
 778
 779        /* No extra locking here; FLAG_SYSFS just signifies that the
 780         * request and export were done by on behalf of userspace, so
 781         * they may be undone on its behalf too.
 782         */
 783        if (test_and_clear_bit(FLAG_SYSFS, &desc->flags)) {
 784                status = 0;
 785                gpiod_free(desc);
 786        }
 787done:
 788        if (status)
 789                pr_debug("%s: status %d\n", __func__, status);
 790        return status ? : len;
 791}
 792
 793static struct class_attribute gpio_class_attrs[] = {
 794        __ATTR(export, 0200, NULL, export_store),
 795        __ATTR(unexport, 0200, NULL, unexport_store),
 796        __ATTR_NULL,
 797};
 798
 799static struct class gpio_class = {
 800        .name =         "gpio",
 801        .owner =        THIS_MODULE,
 802
 803        .class_attrs =  gpio_class_attrs,
 804};
 805
 806
 807/**
 808 * gpiod_export - export a GPIO through sysfs
 809 * @gpio: gpio to make available, already requested
 810 * @direction_may_change: true if userspace may change gpio direction
 811 * Context: arch_initcall or later
 812 *
 813 * When drivers want to make a GPIO accessible to userspace after they
 814 * have requested it -- perhaps while debugging, or as part of their
 815 * public interface -- they may use this routine.  If the GPIO can
 816 * change direction (some can't) and the caller allows it, userspace
 817 * will see "direction" sysfs attribute which may be used to change
 818 * the gpio's direction.  A "value" attribute will always be provided.
 819 *
 820 * Returns zero on success, else an error.
 821 */
 822int gpiod_export(struct gpio_desc *desc, bool direction_may_change)
 823{
 824        struct gpio_chip        *chip;
 825        struct gpio_device      *gdev;
 826        unsigned long           flags;
 827        int                     status;
 828        const char              *ioname = NULL;
 829        struct device           *dev;
 830        int                     offset;
 831
 832        /* can't export until sysfs is available ... */
 833        if (!gpio_class.p) {
 834                pr_debug("%s: called too early!\n", __func__);
 835                return -ENOENT;
 836        }
 837
 838        if (!desc) {
 839                pr_debug("%s: invalid gpio descriptor\n", __func__);
 840                return -EINVAL;
 841        }
 842
 843        chip = desc->chip;
 844        gdev = chip->gpiodev;
 845
 846        mutex_lock(&sysfs_lock);
 847
 848        spin_lock_irqsave(&gpio_lock, flags);
 849        if (!test_bit(FLAG_REQUESTED, &desc->flags) ||
 850             test_bit(FLAG_EXPORT, &desc->flags)) {
 851                spin_unlock_irqrestore(&gpio_lock, flags);
 852                gpiod_dbg(desc, "%s: unavailable (requested=%d, exported=%d)\n",
 853                                __func__,
 854                                test_bit(FLAG_REQUESTED, &desc->flags),
 855                                test_bit(FLAG_EXPORT, &desc->flags));
 856                status = -EPERM;
 857                goto fail_unlock;
 858        }
 859
 860        if (!chip->direction_input || !chip->direction_output)
 861                direction_may_change = false;
 862        spin_unlock_irqrestore(&gpio_lock, flags);
 863
 864        offset = gpio_chip_hwgpio(desc);
 865        if (chip->names && chip->names[offset])
 866                ioname = chip->names[offset];
 867
 868        dev = device_create(&gpio_class, &gdev->dev, MKDEV(0, 0),
 869                            desc, ioname ? ioname : "gpio%u",
 870                            desc_to_gpio(desc));
 871        if (IS_ERR(dev)) {
 872                status = PTR_ERR(dev);
 873                goto fail_unlock;
 874        }
 875
 876        status = sysfs_create_group(&dev->kobj, &gpio_attr_group);
 877        if (status)
 878                goto fail_unregister_device;
 879
 880        if (direction_may_change) {
 881                status = device_create_file(dev, &dev_attr_direction);
 882                if (status)
 883                        goto fail_unregister_device;
 884        }
 885
 886        if (gpiod_to_irq(desc) >= 0 && (direction_may_change ||
 887                                       !test_bit(FLAG_IS_OUT, &desc->flags))) {
 888                status = device_create_file(dev, &dev_attr_edge);
 889                if (status)
 890                        goto fail_unregister_device;
 891        }
 892
 893        set_bit(FLAG_EXPORT, &desc->flags);
 894        mutex_unlock(&sysfs_lock);
 895        return 0;
 896
 897fail_unregister_device:
 898        device_unregister(dev);
 899fail_unlock:
 900        mutex_unlock(&sysfs_lock);
 901        gpiod_dbg(desc, "%s: status %d\n", __func__, status);
 902        return status;
 903}
 904EXPORT_SYMBOL_GPL(gpiod_export);
 905
 906static int match_export(struct device *dev, const void *data)
 907{
 908        return dev_get_drvdata(dev) == data;
 909}
 910
 911/**
 912 * gpiod_export_link - create a sysfs link to an exported GPIO node
 913 * @dev: device under which to create symlink
 914 * @name: name of the symlink
 915 * @gpio: gpio to create symlink to, already exported
 916 *
 917 * Set up a symlink from /sys/.../dev/name to /sys/class/gpio/gpioN
 918 * node. Caller is responsible for unlinking.
 919 *
 920 * Returns zero on success, else an error.
 921 */
 922int gpiod_export_link(struct device *dev, const char *name,
 923                      struct gpio_desc *desc)
 924{
 925        int                     status = -EINVAL;
 926
 927        if (!desc) {
 928                pr_warn("%s: invalid GPIO\n", __func__);
 929                return -EINVAL;
 930        }
 931
 932        mutex_lock(&sysfs_lock);
 933
 934        if (test_bit(FLAG_EXPORT, &desc->flags)) {
 935                struct device *tdev;
 936
 937                tdev = class_find_device(&gpio_class, NULL, desc, match_export);
 938                if (tdev != NULL) {
 939                        status = sysfs_create_link(&dev->kobj, &tdev->kobj,
 940                                                name);
 941                } else {
 942                        status = -ENODEV;
 943                }
 944        }
 945
 946        mutex_unlock(&sysfs_lock);
 947
 948        if (status)
 949                gpiod_dbg(desc, "%s: status %d\n", __func__, status);
 950
 951        return status;
 952}
 953EXPORT_SYMBOL_GPL(gpiod_export_link);
 954
 955/**
 956 * gpiod_sysfs_set_active_low - set the polarity of gpio sysfs value
 957 * @gpio: gpio to change
 958 * @value: non-zero to use active low, i.e. inverted values
 959 *
 960 * Set the polarity of /sys/class/gpio/gpioN/value sysfs attribute.
 961 * The GPIO does not have to be exported yet.  If poll(2) support has
 962 * been enabled for either rising or falling edge, it will be
 963 * reconfigured to follow the new polarity.
 964 *
 965 * Returns zero on success, else an error.
 966 */
 967int gpiod_sysfs_set_active_low(struct gpio_desc *desc, int value)
 968{
 969        struct device           *dev = NULL;
 970        int                     status = -EINVAL;
 971
 972        if (!desc) {
 973                pr_warn("%s: invalid GPIO\n", __func__);
 974                return -EINVAL;
 975        }
 976
 977        mutex_lock(&sysfs_lock);
 978
 979        if (test_bit(FLAG_EXPORT, &desc->flags)) {
 980                dev = class_find_device(&gpio_class, NULL, desc, match_export);
 981                if (dev == NULL) {
 982                        status = -ENODEV;
 983                        goto unlock;
 984                }
 985        }
 986
 987        status = sysfs_set_active_low(desc, dev, value);
 988
 989unlock:
 990        mutex_unlock(&sysfs_lock);
 991
 992        if (status)
 993                gpiod_dbg(desc, "%s: status %d\n", __func__, status);
 994
 995        return status;
 996}
 997EXPORT_SYMBOL_GPL(gpiod_sysfs_set_active_low);
 998
 999/**
1000 * gpiod_unexport - reverse effect of gpio_export()
1001 * @gpio: gpio to make unavailable
1002 *
1003 * This is implicit on gpio_free().
1004 */
1005void gpiod_unexport(struct gpio_desc *desc)
1006{
1007        int                     status = 0;
1008        struct device           *dev = NULL;
1009
1010        if (!desc) {
1011                pr_warn("%s: invalid GPIO\n", __func__);
1012                return;
1013        }
1014
1015        mutex_lock(&sysfs_lock);
1016
1017        if (test_bit(FLAG_EXPORT, &desc->flags)) {
1018
1019                dev = class_find_device(&gpio_class, NULL, desc, match_export);
1020                if (dev) {
1021                        gpio_setup_irq(desc, dev, 0);
1022                        clear_bit(FLAG_EXPORT, &desc->flags);
1023                } else
1024                        status = -ENODEV;
1025        }
1026
1027        mutex_unlock(&sysfs_lock);
1028
1029        if (dev) {
1030                device_unregister(dev);
1031                put_device(dev);
1032        }
1033
1034        if (status)
1035                gpiod_dbg(desc, "%s: status %d\n", __func__, status);
1036}
1037EXPORT_SYMBOL_GPL(gpiod_unexport);
1038
1039int gpiochip_sysfs_register(struct gpio_chip *chip)
1040{
1041        int             status;
1042        struct device   *dev;
1043
1044        /*
1045         * Many systems add gpio chips for SOC support very early,
1046         * before driver model support is available.  In those cases we
1047         * register later, in gpiolib_sysfs_init() ... here we just
1048         * verify that _some_ field of gpio_class got initialized.
1049         */
1050        if (!gpio_class.p)
1051                return 0;
1052
1053        /* use chip->base for the ID; it's already known to be unique */
1054        mutex_lock(&sysfs_lock);
1055        dev = device_create(&gpio_class, chip->dev, MKDEV(0, 0), chip,
1056                                "gpiochip%d", chip->base);
1057        if (!IS_ERR(dev)) {
1058                status = sysfs_create_group(&dev->kobj,
1059                                &gpiochip_attr_group);
1060        } else
1061                status = PTR_ERR(dev);
1062        chip->exported = (status == 0);
1063        mutex_unlock(&sysfs_lock);
1064
1065        if (status) {
1066                unsigned long   flags;
1067                unsigned        gpio;
1068
1069                spin_lock_irqsave(&gpio_lock, flags);
1070                gpio = 0;
1071                while (gpio < chip->ngpio)
1072                        chip->desc[gpio++].chip = NULL;
1073                spin_unlock_irqrestore(&gpio_lock, flags);
1074
1075                chip_dbg(chip, "%s: status %d\n", __func__, status);
1076        }
1077
1078        return status;
1079}
1080
1081void gpiochip_sysfs_unregister(struct gpio_chip *chip)
1082{
1083        int                     status;
1084        struct device           *dev;
1085
1086        mutex_lock(&sysfs_lock);
1087        dev = class_find_device(&gpio_class, NULL, chip, match_export);
1088        if (dev) {
1089                put_device(dev);
1090                device_unregister(dev);
1091                chip->exported = false;
1092                status = 0;
1093        } else
1094                status = -ENODEV;
1095        mutex_unlock(&sysfs_lock);
1096
1097        if (status)
1098                chip_dbg(chip, "%s: status %d\n", __func__, status);
1099}
1100
1101static int __init gpiolib_sysfs_init(void)
1102{
1103        int             status;
1104        unsigned long   flags;
1105        struct gpio_device *gdev;
1106
1107        status = class_register(&gpio_class);
1108        if (status < 0)
1109                return status;
1110
1111        /* Scan and register the gpio_chips which registered very
1112         * early (e.g. before the class_register above was called).
1113         *
1114         * We run before arch_initcall() so chip->dev nodes can have
1115         * registered, and so arch_initcall() can always gpio_export().
1116         */
1117        spin_lock_irqsave(&gpio_lock, flags);
1118        list_for_each_entry(gdev, &gpio_devices, list) {
1119                if (!gdev->chip || gdev->chip->exported)
1120                        continue;
1121
1122                spin_unlock_irqrestore(&gpio_lock, flags);
1123                status = gpiochip_sysfs_register(gdev->chip);
1124                spin_lock_irqsave(&gpio_lock, flags);
1125        }
1126        spin_unlock_irqrestore(&gpio_lock, flags);
1127
1128
1129        return status;
1130}
1131postcore_initcall(gpiolib_sysfs_init);
1132
1133#else
1134static inline int gpiochip_export(struct gpio_chip *chip)
1135{
1136        return 0;
1137}
1138
1139static inline void gpiochip_unexport(struct gpio_chip *chip)
1140{
1141}
1142
1143#endif /* CONFIG_GPIO_SYSFS */
1144
1145/*
1146 * Add a new chip to the global chips list, keeping the list of chips sorted
1147 * by range(means [base, base + ngpio - 1]) order.
1148 *
1149 * Return -EBUSY if the new chip overlaps with some other chip's integer
1150 * space.
1151 */
1152static int gpiodev_add_to_list(struct gpio_device *gdev)
1153{
1154        struct gpio_device *prev, *next;
1155
1156        if (list_empty(&gpio_devices)) {
1157                /* initial entry in list */
1158                list_add_tail(&gdev->list, &gpio_devices);
1159                return 0;
1160        }
1161
1162        next = list_entry(gpio_devices.next, struct gpio_device, list);
1163        if (gdev->base + gdev->ngpio <= next->base) {
1164                /* add before first entry */
1165                list_add(&gdev->list, &gpio_devices);
1166                return 0;
1167        }
1168
1169        prev = list_entry(gpio_devices.prev, struct gpio_device, list);
1170        if (prev->base + prev->ngpio <= gdev->base) {
1171                /* add behind last entry */
1172                list_add_tail(&gdev->list, &gpio_devices);
1173                return 0;
1174        }
1175
1176        list_for_each_entry_safe(prev, next, &gpio_devices, list) {
1177                /* at the end of the list */
1178                if (&next->list == &gpio_devices)
1179                        break;
1180                /* add between prev and next */
1181                if (prev->base + prev->ngpio <= gdev->base
1182                                && gdev->base + gdev->ngpio <= next->base) {
1183                        list_add(&gdev->list, &prev->list);
1184                        return 0;
1185                }
1186        }
1187
1188        dev_err(&gdev->dev, "GPIO integer space overlap, cannot add chip\n");
1189        return -EBUSY;
1190}
1191
1192static void gpiodevice_release(struct device *dev)
1193{
1194        struct gpio_device *gdev = dev_get_drvdata(dev);
1195
1196        list_del(&gdev->list);
1197        ida_simple_remove(&gpio_ida, gdev->id);
1198}
1199
1200/**
1201 * gpiochip_add_data() - register a gpio_chip
1202 * @chip: the chip to register, with chip->base initialized
1203 * Context: potentially before irqs will work
1204 *
1205 * Returns a negative errno if the chip can't be registered, such as
1206 * because the chip->base is invalid or already associated with a
1207 * different chip.  Otherwise it returns zero as a success code.
1208 *
1209 * When gpiochip_add_data() is called very early during boot, so that GPIOs
1210 * can be freely used, the chip->dev device must be registered before
1211 * the gpio framework's arch_initcall().  Otherwise sysfs initialization
1212 * for GPIOs will fail rudely.
1213 *
1214 * If chip->base is negative, this requests dynamic assignment of
1215 * a range of valid GPIOs.
1216 */
1217int gpiochip_add_data(struct gpio_chip *chip, void *data)
1218{
1219        unsigned long   flags;
1220        int             status = 0;
1221        unsigned        i;
1222        int             base = chip->base;
1223        struct gpio_desc *descs;
1224        struct gpio_device *gdev;
1225
1226        /*
1227         * First: allocate and populate the internal stat container, and
1228         * set up the struct device.
1229         */
1230        gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1231        if (!gdev)
1232                return -ENOMEM;
1233
1234        gdev->chip = chip;
1235        chip->gpiodev = gdev;
1236        if (chip->dev) {
1237                gdev->dev.parent = chip->dev;
1238                gdev->dev.of_node = chip->dev->of_node;
1239        } else {
1240#ifdef CONFIG_OF_GPIO
1241        /* If the gpiochip has an assigned OF node this takes precedence */
1242                if (chip->of_node)
1243                        gdev->dev.of_node = chip->of_node;
1244#endif
1245        }
1246        gdev->id = ida_simple_get(&gpio_ida, 0, 0, GFP_KERNEL);
1247        if (gdev->id < 0) {
1248                status = gdev->id;
1249                goto err_free_gdev;
1250        }
1251        dev_set_name(&gdev->dev, "gpiochip%d", gdev->id);
1252        device_initialize(&gdev->dev);
1253        dev_set_drvdata(&gdev->dev, gdev);
1254        if (chip->dev && chip->dev->driver)
1255                gdev->owner = chip->dev->driver->owner;
1256        else if (chip->gpiodev->owner)
1257                /* TODO: remove chip->gpiodev->owner */
1258                gdev->owner = chip->gpiodev->owner;
1259        else
1260                gdev->owner = THIS_MODULE;
1261
1262        /* FIXME: devm_kcalloc() these and move to gpio_device */
1263        descs = kcalloc(chip->ngpio, sizeof(descs[0]), GFP_KERNEL);
1264        if (!descs) {
1265                status = -ENOMEM;
1266                goto err_free_gdev;
1267        }
1268
1269        /* FIXME: move driver data into gpio_device dev_set_drvdata() */
1270
1271        chip->data = data;
1272
1273        if (chip->ngpio == 0) {
1274                chip_err(chip, "tried to insert a GPIO chip with zero lines\n");
1275                status = -EINVAL;
1276                goto err_free_descs;
1277        }
1278
1279        gdev->ngpio = chip->ngpio;
1280
1281        spin_lock_irqsave(&gpio_lock, flags);
1282
1283        if (base < 0) {
1284                base = gpiochip_find_base(chip->ngpio);
1285                if (base < 0) {
1286                        status = base;
1287                        goto unlock;
1288                }
1289                chip->base = base;
1290        }
1291        gdev->base = base;
1292
1293        status = gpiodev_add_to_list(gdev);
1294        if (status)
1295                goto unlock;
1296
1297        for (i = 0; i < chip->ngpio; i++) {
1298                struct gpio_desc *desc = &descs[i];
1299
1300                /* REVISIT: maybe a pointer to gpio_device is better */
1301                desc->chip = chip;
1302
1303                /* REVISIT:  most hardware initializes GPIOs as
1304                 * inputs (often with pullups enabled) so power
1305                 * usage is minimized.  Linux code should set the
1306                 * gpio direction first thing; but until it does,
1307                 * and in case chip->get_direction is not set,
1308                 * we may expose the wrong direction in sysfs.
1309                 */
1310                desc->flags = !chip->direction_input
1311                        ? (1 << FLAG_IS_OUT)
1312                        : 0;
1313        }
1314        chip->desc = descs;
1315
1316        spin_unlock_irqrestore(&gpio_lock, flags);
1317
1318#ifdef CONFIG_PINCTRL
1319        /* FIXME: move pin ranges to gpio_device */
1320        INIT_LIST_HEAD(&chip->pin_ranges);
1321#endif
1322
1323        of_gpiochip_add(chip);
1324        acpi_gpiochip_add(chip);
1325
1326        status = device_add(&gdev->dev);
1327        if (status)
1328                goto err_remove_from_list;
1329
1330        status = gpiochip_sysfs_register(chip);
1331        if (status)
1332                goto err_remove_device;
1333
1334        /* From this point, the .release() function cleans up gpio_device */
1335        gdev->dev.release = gpiodevice_release;
1336        get_device(&gdev->dev);
1337
1338        pr_debug("%s: registered GPIOs %d to %d on device: %s\n", __func__,
1339                gdev->base, gdev->base + chip->ngpio - 1,
1340                chip->label ? : "generic");
1341
1342        return 0;
1343
1344err_remove_device:
1345        device_del(&gdev->dev);
1346err_remove_from_list:
1347        list_del(&gdev->list);
1348unlock:
1349        spin_unlock_irqrestore(&gpio_lock, flags);
1350err_free_descs:
1351        kfree(descs);
1352err_free_gdev:
1353        ida_simple_remove(&gpio_ida, gdev->id);
1354        kfree(gdev);
1355        /* failures here can mean systems won't boot... */
1356        pr_err("%s: GPIOs %d..%d (%s) failed to register\n", __func__,
1357                gdev->base, gdev->base + gdev->ngpio - 1,
1358                chip->label ? : "generic");
1359        return status;
1360}
1361EXPORT_SYMBOL_GPL(gpiochip_add_data);
1362
1363/* Forward-declaration */
1364static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip);
1365
1366/**
1367 * gpiochip_remove() - unregister a gpio_chip
1368 * @chip: the chip to unregister
1369 *
1370 * A gpio_chip with any GPIOs still requested may not be removed.
1371 */
1372int gpiochip_remove(struct gpio_chip *chip)
1373{
1374        struct gpio_device *gdev = chip->gpiodev;
1375        unsigned long   flags;
1376        int             status = 0;
1377        unsigned        id;
1378
1379        spin_lock_irqsave(&gpio_lock, flags);
1380
1381        gpiochip_irqchip_remove(chip);
1382        gpiochip_remove_pin_ranges(chip);
1383        of_gpiochip_remove(chip);
1384        acpi_gpiochip_remove(chip);
1385
1386        for (id = 0; id < gdev->ngpio; id++) {
1387                if (test_bit(FLAG_REQUESTED, &chip->desc[id].flags)) {
1388                        status = -EBUSY;
1389                        break;
1390                }
1391        }
1392        if (status == 0) {
1393                for (id = 0; id < chip->ngpio; id++)
1394                        chip->desc[id].chip = NULL;
1395
1396                list_del(&gdev->list);
1397        }
1398
1399        spin_unlock_irqrestore(&gpio_lock, flags);
1400
1401        if (status == 0) {
1402                /* Numb the device, cancelling all outstanding operations */
1403                gdev->chip = NULL;
1404                /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1405                gpiochip_sysfs_unregister(chip);
1406                /* FIXME: need to be moved to gpio_device and held there */
1407                kfree(chip->desc);
1408                chip->desc = NULL;
1409
1410                /*
1411                 * The gpiochip side puts its use of the device to rest here:
1412                 * if there are no userspace clients, the chardev and device will
1413                 * be removed, else it will be dangling until the last user is
1414                 * gone.
1415                 */
1416                put_device(&gdev->dev);
1417        }
1418        return status;
1419}
1420EXPORT_SYMBOL_GPL(gpiochip_remove);
1421
1422/**
1423 * gpiochip_find() - iterator for locating a specific gpio_chip
1424 * @data: data to pass to match function
1425 * @callback: Callback function to check gpio_chip
1426 *
1427 * Similar to bus_find_device.  It returns a reference to a gpio_chip as
1428 * determined by a user supplied @match callback.  The callback should return
1429 * 0 if the device doesn't match and non-zero if it does.  If the callback is
1430 * non-zero, this function will return to the caller and not iterate over any
1431 * more gpio_chips.
1432 */
1433struct gpio_chip *gpiochip_find(void *data,
1434                                int (*match)(struct gpio_chip *chip,
1435                                             void *data))
1436{
1437        struct gpio_device *gdev;
1438        struct gpio_chip *chip;
1439        unsigned long flags;
1440
1441        spin_lock_irqsave(&gpio_lock, flags);
1442        list_for_each_entry(gdev, &gpio_devices, list)
1443                if (match(gdev->chip, data))
1444                        break;
1445
1446        /* No match? */
1447        if (&gdev->list == &gpio_devices)
1448                chip = NULL;
1449        else
1450                chip = gdev->chip;
1451
1452        spin_unlock_irqrestore(&gpio_lock, flags);
1453
1454        return chip;
1455}
1456EXPORT_SYMBOL_GPL(gpiochip_find);
1457
1458static int gpiochip_match_name(struct gpio_chip *chip, void *data)
1459{
1460        const char *name = data;
1461
1462        return !strcmp(chip->label, name);
1463}
1464
1465static struct gpio_chip *find_chip_by_name(const char *name)
1466{
1467        return gpiochip_find((void *)name, gpiochip_match_name);
1468}
1469
1470#ifdef CONFIG_GPIOLIB_IRQCHIP
1471
1472/*
1473 * The following is irqchip helper code for gpiochips.
1474 */
1475
1476/**
1477 * gpiochip_set_chained_irqchip() - sets a chained irqchip to a gpiochip
1478 * @gpiochip: the gpiochip to set the irqchip chain to
1479 * @irqchip: the irqchip to chain to the gpiochip
1480 * @parent_irq: the irq number corresponding to the parent IRQ for this
1481 * chained irqchip
1482 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1483 * coming out of the gpiochip. If the interrupt is nested rather than
1484 * cascaded, pass NULL in this handler argument
1485 */
1486void gpiochip_set_chained_irqchip(struct gpio_chip *gpiochip,
1487                                  struct irq_chip *irqchip,
1488                                  int parent_irq,
1489                                  irq_flow_handler_t parent_handler)
1490{
1491        unsigned int offset;
1492
1493        if (!gpiochip->irqdomain) {
1494                chip_err(gpiochip, "called %s before setting up irqchip\n",
1495                         __func__);
1496                return;
1497        }
1498
1499        if (parent_handler) {
1500                if (gpiochip->can_sleep) {
1501                        chip_err(gpiochip,
1502                                 "you cannot have chained interrupts on a "
1503                                 "chip that may sleep\n");
1504                        return;
1505                }
1506                irq_set_chained_handler(parent_irq, parent_handler);
1507                /*
1508                 * The parent irqchip is already using the chip_data for this
1509                 * irqchip, so our callbacks simply use the handler_data.
1510                 */
1511                irq_set_handler_data(parent_irq, gpiochip);
1512        }
1513
1514        /* Set the parent IRQ for all affected IRQs */
1515        for (offset = 0; offset < gpiochip->ngpio; offset++)
1516                irq_set_parent(irq_find_mapping(gpiochip->irqdomain, offset),
1517                               parent_irq);
1518}
1519EXPORT_SYMBOL_GPL(gpiochip_set_chained_irqchip);
1520
1521/**
1522 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
1523 * @d: the irqdomain used by this irqchip
1524 * @irq: the global irq number used by this GPIO irqchip irq
1525 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
1526 *
1527 * This function will set up the mapping for a certain IRQ line on a
1528 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
1529 * stored inside the gpiochip.
1530 */
1531static int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
1532                            irq_hw_number_t hwirq)
1533{
1534        struct gpio_chip *chip = d->host_data;
1535
1536        irq_set_chip_data(irq, chip);
1537        irq_set_chip_and_handler(irq, chip->irqchip, chip->irq_handler);
1538        /* Chips that can sleep need nested thread handlers */
1539        if (chip->can_sleep)
1540                irq_set_nested_thread(irq, 1);
1541#ifdef CONFIG_ARM
1542        set_irq_flags(irq, IRQF_VALID);
1543#else
1544        irq_set_noprobe(irq);
1545#endif
1546        /*
1547         * No set-up of the hardware will happen if IRQ_TYPE_NONE
1548         * is passed as default type.
1549         */
1550        if (chip->irq_default_type != IRQ_TYPE_NONE)
1551                irq_set_irq_type(irq, chip->irq_default_type);
1552
1553        return 0;
1554}
1555
1556static void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
1557{
1558        struct gpio_chip *chip = d->host_data;
1559
1560#ifdef CONFIG_ARM
1561        set_irq_flags(irq, 0);
1562#endif
1563        if (chip->can_sleep)
1564                irq_set_nested_thread(irq, 0);
1565        irq_set_chip_and_handler(irq, NULL, NULL);
1566        irq_set_chip_data(irq, NULL);
1567}
1568
1569static const struct irq_domain_ops gpiochip_domain_ops = {
1570        .map    = gpiochip_irq_map,
1571        .unmap  = gpiochip_irq_unmap,
1572        /* Virtually all GPIO irqchips are twocell:ed */
1573        .xlate  = irq_domain_xlate_twocell,
1574};
1575
1576static int gpiochip_irq_reqres(struct irq_data *d)
1577{
1578        struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1579
1580        if (gpio_lock_as_irq(chip, d->hwirq)) {
1581                chip_err(chip,
1582                        "unable to lock HW IRQ %lu for IRQ\n",
1583                        d->hwirq);
1584                return -EINVAL;
1585        }
1586        return 0;
1587}
1588
1589static void gpiochip_irq_relres(struct irq_data *d)
1590{
1591        struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1592
1593        gpio_unlock_as_irq(chip, d->hwirq);
1594}
1595
1596static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset)
1597{
1598        return irq_find_mapping(chip->irqdomain, offset);
1599}
1600
1601/**
1602 * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
1603 * @gpiochip: the gpiochip to remove the irqchip from
1604 *
1605 * This is called only from gpiochip_remove()
1606 */
1607static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip)
1608{
1609        unsigned int offset;
1610
1611        /* Remove all IRQ mappings and delete the domain */
1612        if (gpiochip->irqdomain) {
1613                for (offset = 0; offset < gpiochip->ngpio; offset++)
1614                        irq_dispose_mapping(gpiochip->irq_base + offset);
1615                irq_domain_remove(gpiochip->irqdomain);
1616        }
1617
1618        if (gpiochip->irqchip) {
1619                gpiochip->irqchip->irq_request_resources = NULL;
1620                gpiochip->irqchip->irq_release_resources = NULL;
1621                gpiochip->irqchip = NULL;
1622        }
1623}
1624
1625/**
1626 * gpiochip_irqchip_add() - adds an irqchip to a gpiochip
1627 * @gpiochip: the gpiochip to add the irqchip to
1628 * @irqchip: the irqchip to add to the gpiochip
1629 * @first_irq: if not dynamically assigned, the base (first) IRQ to
1630 * allocate gpiochip irqs from
1631 * @handler: the irq handler to use (often a predefined irq core function)
1632 * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
1633 * to have the core avoid setting up any default type in the hardware.
1634 *
1635 * This function closely associates a certain irqchip with a certain
1636 * gpiochip, providing an irq domain to translate the local IRQs to
1637 * global irqs in the gpiolib core, and making sure that the gpiochip
1638 * is passed as chip data to all related functions. Driver callbacks
1639 * need to use container_of() to get their local state containers back
1640 * from the gpiochip passed as chip data. An irqdomain will be stored
1641 * in the gpiochip that shall be used by the driver to handle IRQ number
1642 * translation. The gpiochip will need to be initialized and registered
1643 * before calling this function.
1644 *
1645 * This function will handle two cell:ed simple IRQs and assumes all
1646 * the pins on the gpiochip can generate a unique IRQ. Everything else
1647 * need to be open coded.
1648 */
1649int gpiochip_irqchip_add(struct gpio_chip *gpiochip,
1650                         struct irq_chip *irqchip,
1651                         unsigned int first_irq,
1652                         irq_flow_handler_t handler,
1653                         unsigned int type)
1654{
1655        struct device_node *of_node;
1656        unsigned int offset;
1657        unsigned irq_base = 0;
1658
1659        if (!gpiochip || !irqchip)
1660                return -EINVAL;
1661
1662        if (!gpiochip->dev) {
1663                pr_err("missing gpiochip .dev parent pointer\n");
1664                return -EINVAL;
1665        }
1666        of_node = gpiochip->dev->of_node;
1667#ifdef CONFIG_OF_GPIO
1668        /*
1669         * If the gpiochip has an assigned OF node this takes precendence
1670         * FIXME: get rid of this and use gpiochip->dev->of_node everywhere
1671         */
1672        if (gpiochip->of_node)
1673                of_node = gpiochip->of_node;
1674#endif
1675        gpiochip->irqchip = irqchip;
1676        gpiochip->irq_handler = handler;
1677        gpiochip->irq_default_type = type;
1678        gpiochip->to_irq = gpiochip_to_irq;
1679        gpiochip->irqdomain = irq_domain_add_simple(of_node,
1680                                        gpiochip->ngpio, first_irq,
1681                                        &gpiochip_domain_ops, gpiochip);
1682        if (!gpiochip->irqdomain) {
1683                gpiochip->irqchip = NULL;
1684                return -EINVAL;
1685        }
1686        irqchip->irq_request_resources = gpiochip_irq_reqres;
1687        irqchip->irq_release_resources = gpiochip_irq_relres;
1688
1689        /*
1690         * Prepare the mapping since the irqchip shall be orthogonal to
1691         * any gpiochip calls. If the first_irq was zero, this is
1692         * necessary to allocate descriptors for all IRQs.
1693         */
1694        for (offset = 0; offset < gpiochip->ngpio; offset++) {
1695                irq_base = irq_create_mapping(gpiochip->irqdomain, offset);
1696                if (offset == 0)
1697                        /*
1698                         * Store the base into the gpiochip to be used when
1699                         * unmapping the irqs.
1700                         */
1701                        gpiochip->irq_base = irq_base;
1702        }
1703
1704        return 0;
1705}
1706EXPORT_SYMBOL_GPL(gpiochip_irqchip_add);
1707
1708#else /* CONFIG_GPIOLIB_IRQCHIP */
1709
1710static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {}
1711
1712#endif /* CONFIG_GPIOLIB_IRQCHIP */
1713
1714/**
1715 * gpiochip_generic_config() - apply configuration for a pin
1716 * @chip: the gpiochip owning the GPIO
1717 * @offset: the offset of the GPIO to apply the configuration
1718 * @config: the configuration to be applied
1719 */
1720int gpiochip_generic_config(struct gpio_chip *chip, unsigned offset,
1721                            unsigned long config)
1722{
1723        return pinctrl_gpio_set_config(chip->gpiodev->base + offset, config);
1724}
1725EXPORT_SYMBOL_GPL(gpiochip_generic_config);
1726
1727#ifdef CONFIG_PINCTRL
1728
1729/**
1730 * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
1731 * @chip: the gpiochip to add the range for
1732 * @pinctrl: the dev_name() of the pin controller to map to
1733 * @gpio_offset: the start offset in the current gpio_chip number space
1734 * @pin_group: name of the pin group inside the pin controller
1735 */
1736int gpiochip_add_pingroup_range(struct gpio_chip *chip,
1737                        struct pinctrl_dev *pctldev,
1738                        unsigned int gpio_offset, const char *pin_group)
1739{
1740        struct gpio_pin_range *pin_range;
1741        struct gpio_device *gdev = chip->gpiodev;
1742        int ret;
1743
1744        pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1745        if (!pin_range) {
1746                chip_err(chip, "failed to allocate pin ranges\n");
1747                return -ENOMEM;
1748        }
1749
1750        /* Use local offset as range ID */
1751        pin_range->range.id = gpio_offset;
1752        pin_range->range.gc = chip;
1753        pin_range->range.name = chip->label;
1754        pin_range->range.base = gdev->base + gpio_offset;
1755        pin_range->pctldev = pctldev;
1756
1757        ret = pinctrl_get_group_pins(pctldev, pin_group,
1758                                        &pin_range->range.pins,
1759                                        &pin_range->range.npins);
1760        if (ret < 0) {
1761                kfree(pin_range);
1762                return ret;
1763        }
1764
1765        pinctrl_add_gpio_range(pctldev, &pin_range->range);
1766
1767        chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n",
1768                 gpio_offset, gpio_offset + pin_range->range.npins - 1,
1769                 pinctrl_dev_get_devname(pctldev), pin_group);
1770
1771        list_add_tail(&pin_range->node, &chip->pin_ranges);
1772
1773        return 0;
1774}
1775EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
1776
1777/**
1778 * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
1779 * @chip: the gpiochip to add the range for
1780 * @pinctrl_name: the dev_name() of the pin controller to map to
1781 * @gpio_offset: the start offset in the current gpio_chip number space
1782 * @pin_offset: the start offset in the pin controller number space
1783 * @npins: the number of pins from the offset of each pin space (GPIO and
1784 *      pin controller) to accumulate in this range
1785 */
1786int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
1787                           unsigned int gpio_offset, unsigned int pin_offset,
1788                           unsigned int npins)
1789{
1790        struct gpio_pin_range *pin_range;
1791        struct gpio_device *gdev = chip->gpiodev;
1792        int ret;
1793
1794        pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1795        if (!pin_range) {
1796                chip_err(chip, "failed to allocate pin ranges\n");
1797                return -ENOMEM;
1798        }
1799
1800        /* Use local offset as range ID */
1801        pin_range->range.id = gpio_offset;
1802        pin_range->range.gc = chip;
1803        pin_range->range.name = chip->label;
1804        pin_range->range.base = gdev->base + gpio_offset;
1805        pin_range->range.pin_base = pin_offset;
1806        pin_range->range.npins = npins;
1807        pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
1808                        &pin_range->range);
1809        if (IS_ERR(pin_range->pctldev)) {
1810                ret = PTR_ERR(pin_range->pctldev);
1811                chip_err(chip, "could not create pin range\n");
1812                kfree(pin_range);
1813                return ret;
1814        }
1815        chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
1816                 gpio_offset, gpio_offset + npins - 1,
1817                 pinctl_name,
1818                 pin_offset, pin_offset + npins - 1);
1819
1820        list_add_tail(&pin_range->node, &chip->pin_ranges);
1821
1822        return 0;
1823}
1824EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
1825
1826bool gpiochip_line_is_irq(struct gpio_chip *chip, unsigned int offset)
1827{
1828        struct gpio_desc *desc;
1829
1830        if (offset >= chip->ngpio)
1831                return false;
1832
1833        desc = &chip->desc[offset];
1834
1835        return test_bit(FLAG_USED_AS_IRQ, &desc->flags);
1836}
1837EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
1838
1839/**
1840 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
1841 * @chip: the chip to remove all the mappings for
1842 */
1843void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
1844{
1845        struct gpio_pin_range *pin_range, *tmp;
1846
1847        list_for_each_entry_safe(pin_range, tmp, &chip->pin_ranges, node) {
1848                list_del(&pin_range->node);
1849                pinctrl_remove_gpio_range(pin_range->pctldev,
1850                                &pin_range->range);
1851                kfree(pin_range);
1852        }
1853}
1854EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
1855
1856#endif /* CONFIG_PINCTRL */
1857
1858/* These "optional" allocation calls help prevent drivers from stomping
1859 * on each other, and help provide better diagnostics in debugfs.
1860 * They're called even less than the "set direction" calls.
1861 */
1862static int gpiod_request(struct gpio_desc *desc, const char *label)
1863{
1864        struct gpio_chip        *chip;
1865        int                     status = -EPROBE_DEFER;
1866        unsigned long           flags;
1867
1868        if (!desc) {
1869                pr_warn("%s: invalid GPIO\n", __func__);
1870                return -EINVAL;
1871        }
1872
1873        spin_lock_irqsave(&gpio_lock, flags);
1874
1875        chip = desc->chip;
1876        if (chip == NULL)
1877                goto done;
1878
1879        if (!try_module_get(chip->gpiodev->owner))
1880                goto done;
1881
1882        /* NOTE:  gpio_request() can be called in early boot,
1883         * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
1884         */
1885
1886        if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
1887                desc_set_label(desc, label ? : "?");
1888                status = 0;
1889        } else {
1890                status = -EBUSY;
1891                module_put(chip->gpiodev->owner);
1892                goto done;
1893        }
1894
1895        if (chip->request) {
1896                /* chip->request may sleep */
1897                spin_unlock_irqrestore(&gpio_lock, flags);
1898                status = chip->request(chip, gpio_chip_hwgpio(desc));
1899                spin_lock_irqsave(&gpio_lock, flags);
1900
1901                if (status < 0) {
1902                        desc_set_label(desc, NULL);
1903                        module_put(chip->gpiodev->owner);
1904                        clear_bit(FLAG_REQUESTED, &desc->flags);
1905                        goto done;
1906                }
1907        }
1908        if (chip->get_direction) {
1909                /* chip->get_direction may sleep */
1910                spin_unlock_irqrestore(&gpio_lock, flags);
1911                gpiod_get_direction(desc);
1912                spin_lock_irqsave(&gpio_lock, flags);
1913        }
1914done:
1915        if (status)
1916                gpiod_dbg(desc, "%s: status %d\n", __func__, status);
1917        spin_unlock_irqrestore(&gpio_lock, flags);
1918        return status;
1919}
1920
1921int gpio_request(unsigned gpio, const char *label)
1922{
1923        return gpiod_request(gpio_to_desc(gpio), label);
1924}
1925EXPORT_SYMBOL_GPL(gpio_request);
1926
1927static void gpiod_free(struct gpio_desc *desc)
1928{
1929        unsigned long           flags;
1930        struct gpio_chip        *chip;
1931
1932        might_sleep();
1933
1934        if (!desc) {
1935                WARN_ON(extra_checks);
1936                return;
1937        }
1938
1939        gpiod_unexport(desc);
1940
1941        spin_lock_irqsave(&gpio_lock, flags);
1942
1943        chip = desc->chip;
1944        if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
1945                if (chip->free) {
1946                        spin_unlock_irqrestore(&gpio_lock, flags);
1947                        might_sleep_if(chip->can_sleep);
1948                        chip->free(chip, gpio_chip_hwgpio(desc));
1949                        spin_lock_irqsave(&gpio_lock, flags);
1950                }
1951                desc_set_label(desc, NULL);
1952                module_put(desc->chip->gpiodev->owner);
1953                clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
1954                clear_bit(FLAG_REQUESTED, &desc->flags);
1955                clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
1956                clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
1957        } else
1958                WARN_ON(extra_checks);
1959
1960        spin_unlock_irqrestore(&gpio_lock, flags);
1961}
1962
1963void gpio_free(unsigned gpio)
1964{
1965        gpiod_free(gpio_to_desc(gpio));
1966}
1967EXPORT_SYMBOL_GPL(gpio_free);
1968
1969/**
1970 * gpio_request_one - request a single GPIO with initial configuration
1971 * @gpio:       the GPIO number
1972 * @flags:      GPIO configuration as specified by GPIOF_*
1973 * @label:      a literal description string of this GPIO
1974 */
1975int gpio_request_one(unsigned gpio, unsigned long flags, const char *label)
1976{
1977        struct gpio_desc *desc;
1978        int err;
1979
1980        desc = gpio_to_desc(gpio);
1981
1982        err = gpiod_request(desc, label);
1983        if (err)
1984                return err;
1985
1986        if (flags & GPIOF_OPEN_DRAIN)
1987                set_bit(FLAG_OPEN_DRAIN, &desc->flags);
1988
1989        if (flags & GPIOF_OPEN_SOURCE)
1990                set_bit(FLAG_OPEN_SOURCE, &desc->flags);
1991
1992        if (flags & GPIOF_DIR_IN)
1993                err = gpiod_direction_input(desc);
1994        else
1995                err = gpiod_direction_output(desc,
1996                                (flags & GPIOF_INIT_HIGH) ? 1 : 0);
1997
1998        if (err)
1999                goto free_gpio;
2000
2001        if (flags & GPIOF_EXPORT) {
2002                err = gpiod_export(desc, flags & GPIOF_EXPORT_CHANGEABLE);
2003                if (err)
2004                        goto free_gpio;
2005        }
2006
2007        return 0;
2008
2009 free_gpio:
2010        gpiod_free(desc);
2011        return err;
2012}
2013EXPORT_SYMBOL_GPL(gpio_request_one);
2014
2015/**
2016 * gpio_request_array - request multiple GPIOs in a single call
2017 * @array:      array of the 'struct gpio'
2018 * @num:        how many GPIOs in the array
2019 */
2020int gpio_request_array(const struct gpio *array, size_t num)
2021{
2022        int i, err;
2023
2024        for (i = 0; i < num; i++, array++) {
2025                err = gpio_request_one(array->gpio, array->flags, array->label);
2026                if (err)
2027                        goto err_free;
2028        }
2029        return 0;
2030
2031err_free:
2032        while (i--)
2033                gpio_free((--array)->gpio);
2034        return err;
2035}
2036EXPORT_SYMBOL_GPL(gpio_request_array);
2037
2038/**
2039 * gpio_free_array - release multiple GPIOs in a single call
2040 * @array:      array of the 'struct gpio'
2041 * @num:        how many GPIOs in the array
2042 */
2043void gpio_free_array(const struct gpio *array, size_t num)
2044{
2045        while (num--)
2046                gpio_free((array++)->gpio);
2047}
2048EXPORT_SYMBOL_GPL(gpio_free_array);
2049
2050/**
2051 * gpiochip_is_requested - return string iff signal was requested
2052 * @chip: controller managing the signal
2053 * @offset: of signal within controller's 0..(ngpio - 1) range
2054 *
2055 * Returns NULL if the GPIO is not currently requested, else a string.
2056 * If debugfs support is enabled, the string returned is the label passed
2057 * to gpio_request(); otherwise it is a meaningless constant.
2058 *
2059 * This function is for use by GPIO controller drivers.  The label can
2060 * help with diagnostics, and knowing that the signal is used as a GPIO
2061 * can help avoid accidentally multiplexing it to another controller.
2062 */
2063const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
2064{
2065        struct gpio_desc *desc;
2066
2067        if (!GPIO_OFFSET_VALID(chip, offset))
2068                return NULL;
2069
2070        desc = &chip->desc[offset];
2071
2072        if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
2073                return NULL;
2074#ifdef CONFIG_DEBUG_FS
2075        return desc->label;
2076#else
2077        return "?";
2078#endif
2079}
2080EXPORT_SYMBOL_GPL(gpiochip_is_requested);
2081
2082
2083/* Drivers MUST set GPIO direction before making get/set calls.  In
2084 * some cases this is done in early boot, before IRQs are enabled.
2085 *
2086 * As a rule these aren't called more than once (except for drivers
2087 * using the open-drain emulation idiom) so these are natural places
2088 * to accumulate extra debugging checks.  Note that we can't (yet)
2089 * rely on gpio_request() having been called beforehand.
2090 */
2091
2092/**
2093 * gpiod_direction_input - set the GPIO direction to input
2094 * @desc:       GPIO to set to input
2095 *
2096 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
2097 * be called safely on it.
2098 *
2099 * Return 0 in case of success, else an error code.
2100 */
2101int gpiod_direction_input(struct gpio_desc *desc)
2102{
2103        unsigned long           flags;
2104        struct gpio_chip        *chip;
2105        int                     status = -EINVAL;
2106        int                     offset;
2107
2108        if (!desc || !desc->chip) {
2109                pr_warn("%s: invalid GPIO\n", __func__);
2110                return -EINVAL;
2111        }
2112
2113        chip = desc->chip;
2114        if (!chip->get || !chip->direction_input) {
2115                gpiod_warn(desc,
2116                        "%s: missing get() or direction_input() operations\n",
2117                        __func__);
2118                return -EIO;
2119        }
2120
2121        spin_lock_irqsave(&gpio_lock, flags);
2122
2123        status = gpio_ensure_requested(desc);
2124        if (status < 0)
2125                goto fail;
2126
2127        /* now we know the gpio is valid and chip won't vanish */
2128
2129        spin_unlock_irqrestore(&gpio_lock, flags);
2130
2131        might_sleep_if(chip->can_sleep);
2132
2133        offset = gpio_chip_hwgpio(desc);
2134        if (status) {
2135                status = chip->request(chip, offset);
2136                if (status < 0) {
2137                        gpiod_dbg(desc, "%s: chip request fail, %d\n",
2138                                        __func__, status);
2139                        /* and it's not available to anyone else ...
2140                         * gpio_request() is the fully clean solution.
2141                         */
2142                        goto lose;
2143                }
2144        }
2145
2146        status = chip->direction_input(chip, offset);
2147        if (status == 0)
2148                clear_bit(FLAG_IS_OUT, &desc->flags);
2149
2150        trace_gpio_direction(desc_to_gpio(desc), 1, status);
2151lose:
2152        return status;
2153fail:
2154        spin_unlock_irqrestore(&gpio_lock, flags);
2155        if (status)
2156                gpiod_dbg(desc, "%s: status %d\n", __func__, status);
2157        return status;
2158}
2159EXPORT_SYMBOL_GPL(gpiod_direction_input);
2160
2161/**
2162 * gpiod_direction_output - set the GPIO direction to input
2163 * @desc:       GPIO to set to output
2164 * @value:      initial output value of the GPIO
2165 *
2166 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2167 * be called safely on it. The initial value of the output must be specified.
2168 *
2169 * Return 0 in case of success, else an error code.
2170 */
2171int gpiod_direction_output(struct gpio_desc *desc, int value)
2172{
2173        unsigned long           flags;
2174        struct gpio_chip        *chip;
2175        int                     status = -EINVAL;
2176        int offset;
2177
2178        if (!desc || !desc->chip) {
2179                pr_warn("%s: invalid GPIO\n", __func__);
2180                return -EINVAL;
2181        }
2182
2183        /* GPIOs used for IRQs shall not be set as output */
2184        if (test_bit(FLAG_USED_AS_IRQ, &desc->flags)) {
2185                gpiod_err(desc,
2186                          "%s: tried to set a GPIO tied to an IRQ as output\n",
2187                          __func__);
2188                return -EIO;
2189        }
2190
2191        /* Open drain pin should not be driven to 1 */
2192        if (value && test_bit(FLAG_OPEN_DRAIN,  &desc->flags))
2193                return gpiod_direction_input(desc);
2194
2195        /* Open source pin should not be driven to 0 */
2196        if (!value && test_bit(FLAG_OPEN_SOURCE,  &desc->flags))
2197                return gpiod_direction_input(desc);
2198
2199        chip = desc->chip;
2200        if (!chip->set || !chip->direction_output) {
2201                gpiod_warn(desc,
2202                       "%s: missing set() or direction_output() operations\n",
2203                       __func__);
2204                return -EIO;
2205        }
2206
2207        spin_lock_irqsave(&gpio_lock, flags);
2208
2209        status = gpio_ensure_requested(desc);
2210        if (status < 0)
2211                goto fail;
2212
2213        /* now we know the gpio is valid and chip won't vanish */
2214
2215        spin_unlock_irqrestore(&gpio_lock, flags);
2216
2217        might_sleep_if(chip->can_sleep);
2218
2219        offset = gpio_chip_hwgpio(desc);
2220        if (status) {
2221                status = chip->request(chip, offset);
2222                if (status < 0) {
2223                        gpiod_dbg(desc, "%s: chip request fail, %d\n",
2224                                        __func__, status);
2225                        /* and it's not available to anyone else ...
2226                         * gpio_request() is the fully clean solution.
2227                         */
2228                        goto lose;
2229                }
2230        }
2231
2232        status = chip->direction_output(chip, offset, value);
2233        if (status == 0)
2234                set_bit(FLAG_IS_OUT, &desc->flags);
2235        trace_gpio_value(desc_to_gpio(desc), 0, value);
2236        trace_gpio_direction(desc_to_gpio(desc), 0, status);
2237lose:
2238        return status;
2239fail:
2240        spin_unlock_irqrestore(&gpio_lock, flags);
2241        if (status)
2242                gpiod_dbg(desc, "%s: gpio status %d\n", __func__, status);
2243        return status;
2244}
2245EXPORT_SYMBOL_GPL(gpiod_direction_output);
2246
2247/**
2248 * gpiod_set_debounce - sets @debounce time for a @gpio
2249 * @gpio: the gpio to set debounce time
2250 * @debounce: debounce time is microseconds
2251 *
2252 * returns -ENOTSUPP if the controller does not support setting
2253 * debounce.
2254 */
2255int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
2256{
2257        unsigned long           flags;
2258        struct gpio_chip        *chip;
2259        unsigned long           config;
2260        int                     status = -EINVAL;
2261        int                     offset;
2262
2263        if (!desc || !desc->chip) {
2264                pr_warn("%s: invalid GPIO\n", __func__);
2265                return -EINVAL;
2266        }
2267
2268        chip = desc->chip;
2269        if (!chip->set || !chip->set_config) {
2270                gpiod_dbg(desc,
2271                          "%s: missing set() or set_config() operations\n",
2272                          __func__);
2273                return -ENOTSUPP;
2274        }
2275
2276        spin_lock_irqsave(&gpio_lock, flags);
2277
2278        status = gpio_ensure_requested(desc);
2279        if (status < 0)
2280                goto fail;
2281
2282        /* now we know the gpio is valid and chip won't vanish */
2283
2284        spin_unlock_irqrestore(&gpio_lock, flags);
2285
2286        might_sleep_if(chip->can_sleep);
2287
2288        offset = gpio_chip_hwgpio(desc);
2289        config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
2290        return chip->set_config(chip, offset, config);
2291
2292fail:
2293        spin_unlock_irqrestore(&gpio_lock, flags);
2294        if (status)
2295                gpiod_dbg(desc, "%s: status %d\n", __func__, status);
2296
2297        return status;
2298}
2299EXPORT_SYMBOL_GPL(gpiod_set_debounce);
2300
2301/**
2302 * gpiod_is_active_low - test whether a GPIO is active-low or not
2303 * @desc: the gpio descriptor to test
2304 *
2305 * Returns 1 if the GPIO is active-low, 0 otherwise.
2306 */
2307int gpiod_is_active_low(const struct gpio_desc *desc)
2308{
2309        return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
2310}
2311EXPORT_SYMBOL_GPL(gpiod_is_active_low);
2312
2313/* I/O calls are only valid after configuration completed; the relevant
2314 * "is this a valid GPIO" error checks should already have been done.
2315 *
2316 * "Get" operations are often inlinable as reading a pin value register,
2317 * and masking the relevant bit in that register.
2318 *
2319 * When "set" operations are inlinable, they involve writing that mask to
2320 * one register to set a low value, or a different register to set it high.
2321 * Otherwise locking is needed, so there may be little value to inlining.
2322 *
2323 *------------------------------------------------------------------------
2324 *
2325 * IMPORTANT!!!  The hot paths -- get/set value -- assume that callers
2326 * have requested the GPIO.  That can include implicit requesting by
2327 * a direction setting call.  Marking a gpio as requested locks its chip
2328 * in memory, guaranteeing that these table lookups need no more locking
2329 * and that gpiochip_remove() will fail.
2330 *
2331 * REVISIT when debugging, consider adding some instrumentation to ensure
2332 * that the GPIO was actually requested.
2333 */
2334
2335static int _gpiod_get_raw_value(const struct gpio_desc *desc)
2336{
2337        struct gpio_chip        *chip;
2338        int value;
2339        int offset;
2340
2341        chip = desc->chip;
2342        offset = gpio_chip_hwgpio(desc);
2343        value = chip->get ? chip->get(chip, offset) : 0;
2344        trace_gpio_value(desc_to_gpio(desc), 1, value);
2345        return value;
2346}
2347
2348/**
2349 * gpiod_get_raw_value() - return a gpio's raw value
2350 * @desc: gpio whose value will be returned
2351 *
2352 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2353 * its ACTIVE_LOW status.
2354 *
2355 * This function should be called from contexts where we cannot sleep, and will
2356 * complain if the GPIO chip functions potentially sleep.
2357 */
2358int gpiod_get_raw_value(const struct gpio_desc *desc)
2359{
2360        if (!desc)
2361                return 0;
2362        /* Should be using gpio_get_value_cansleep() */
2363        WARN_ON(desc->chip->can_sleep);
2364        return _gpiod_get_raw_value(desc);
2365}
2366EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
2367
2368/**
2369 * gpiod_get_value() - return a gpio's value
2370 * @desc: gpio whose value will be returned
2371 *
2372 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2373 * account.
2374 *
2375 * This function should be called from contexts where we cannot sleep, and will
2376 * complain if the GPIO chip functions potentially sleep.
2377 */
2378int gpiod_get_value(const struct gpio_desc *desc)
2379{
2380        int value;
2381        if (!desc)
2382                return 0;
2383        /* Should be using gpio_get_value_cansleep() */
2384        WARN_ON(desc->chip->can_sleep);
2385
2386        value = _gpiod_get_raw_value(desc);
2387        if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2388                value = !value;
2389
2390        return value;
2391}
2392EXPORT_SYMBOL_GPL(gpiod_get_value);
2393
2394/*
2395 *  _gpio_set_open_drain_value() - Set the open drain gpio's value.
2396 * @desc: gpio descriptor whose state need to be set.
2397 * @value: Non-zero for setting it HIGH otherise it will set to LOW.
2398 */
2399static void _gpio_set_open_drain_value(struct gpio_desc *desc, int value)
2400{
2401        int err = 0;
2402        struct gpio_chip *chip = desc->chip;
2403        int offset = gpio_chip_hwgpio(desc);
2404
2405        if (value) {
2406                err = chip->direction_input(chip, offset);
2407                if (!err)
2408                        clear_bit(FLAG_IS_OUT, &desc->flags);
2409        } else {
2410                err = chip->direction_output(chip, offset, 0);
2411                if (!err)
2412                        set_bit(FLAG_IS_OUT, &desc->flags);
2413        }
2414        trace_gpio_direction(desc_to_gpio(desc), value, err);
2415        if (err < 0)
2416                gpiod_err(desc,
2417                          "%s: Error in set_value for open drain err %d\n",
2418                          __func__, err);
2419}
2420
2421/*
2422 *  _gpio_set_open_source_value() - Set the open source gpio's value.
2423 * @desc: gpio descriptor whose state need to be set.
2424 * @value: Non-zero for setting it HIGH otherise it will set to LOW.
2425 */
2426static void _gpio_set_open_source_value(struct gpio_desc *desc, int value)
2427{
2428        int err = 0;
2429        struct gpio_chip *chip = desc->chip;
2430        int offset = gpio_chip_hwgpio(desc);
2431
2432        if (value) {
2433                err = chip->direction_output(chip, offset, 1);
2434                if (!err)
2435                        set_bit(FLAG_IS_OUT, &desc->flags);
2436        } else {
2437                err = chip->direction_input(chip, offset);
2438                if (!err)
2439                        clear_bit(FLAG_IS_OUT, &desc->flags);
2440        }
2441        trace_gpio_direction(desc_to_gpio(desc), !value, err);
2442        if (err < 0)
2443                gpiod_err(desc,
2444                          "%s: Error in set_value for open source err %d\n",
2445                          __func__, err);
2446}
2447
2448static void _gpiod_set_raw_value(struct gpio_desc *desc, int value)
2449{
2450        struct gpio_chip        *chip;
2451
2452        chip = desc->chip;
2453        trace_gpio_value(desc_to_gpio(desc), 0, value);
2454        if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2455                _gpio_set_open_drain_value(desc, value);
2456        else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2457                _gpio_set_open_source_value(desc, value);
2458        else
2459                chip->set(chip, gpio_chip_hwgpio(desc), value);
2460}
2461
2462/**
2463 * gpiod_set_raw_value() - assign a gpio's raw value
2464 * @desc: gpio whose value will be assigned
2465 * @value: value to assign
2466 *
2467 * Set the raw value of the GPIO, i.e. the value of its physical line without
2468 * regard for its ACTIVE_LOW status.
2469 *
2470 * This function should be called from contexts where we cannot sleep, and will
2471 * complain if the GPIO chip functions potentially sleep.
2472 */
2473void gpiod_set_raw_value(struct gpio_desc *desc, int value)
2474{
2475        if (!desc)
2476                return;
2477        /* Should be using gpio_set_value_cansleep() */
2478        WARN_ON(desc->chip->can_sleep);
2479        _gpiod_set_raw_value(desc, value);
2480}
2481EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
2482
2483/**
2484 * gpiod_set_value() - assign a gpio's value
2485 * @desc: gpio whose value will be assigned
2486 * @value: value to assign
2487 *
2488 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2489 * account
2490 *
2491 * This function should be called from contexts where we cannot sleep, and will
2492 * complain if the GPIO chip functions potentially sleep.
2493 */
2494void gpiod_set_value(struct gpio_desc *desc, int value)
2495{
2496        if (!desc)
2497                return;
2498        /* Should be using gpio_set_value_cansleep() */
2499        WARN_ON(desc->chip->can_sleep);
2500        if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2501                value = !value;
2502        _gpiod_set_raw_value(desc, value);
2503}
2504EXPORT_SYMBOL_GPL(gpiod_set_value);
2505
2506/**
2507 * gpiod_cansleep() - report whether gpio value access may sleep
2508 * @desc: gpio to check
2509 *
2510 */
2511int gpiod_cansleep(const struct gpio_desc *desc)
2512{
2513        if (!desc)
2514                return 0;
2515        return desc->chip->can_sleep;
2516}
2517EXPORT_SYMBOL_GPL(gpiod_cansleep);
2518
2519/**
2520 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
2521 * @desc: gpio whose IRQ will be returned (already requested)
2522 *
2523 * Return the IRQ corresponding to the passed GPIO, or an error code in case of
2524 * error.
2525 */
2526int gpiod_to_irq(const struct gpio_desc *desc)
2527{
2528        struct gpio_chip        *chip;
2529        int                     offset;
2530
2531        if (!desc)
2532                return -EINVAL;
2533        chip = desc->chip;
2534        offset = gpio_chip_hwgpio(desc);
2535        return chip->to_irq ? chip->to_irq(chip, offset) : -ENXIO;
2536}
2537EXPORT_SYMBOL_GPL(gpiod_to_irq);
2538
2539/**
2540 * gpiod_lock_as_irq() - lock a GPIO to be used as IRQ
2541 * @gpio: the GPIO line to lock as used for IRQ
2542 *
2543 * This is used directly by GPIO drivers that want to lock down
2544 * a certain GPIO line to be used as IRQs, for example in the
2545 * .to_irq() callback of their gpio_chip, or in the .irq_enable()
2546 * of its irq_chip implementation if the GPIO is known from that
2547 * code.
2548 */
2549int gpiod_lock_as_irq(struct gpio_desc *desc)
2550{
2551        if (!desc)
2552                return -EINVAL;
2553
2554        if (test_bit(FLAG_IS_OUT, &desc->flags)) {
2555                gpiod_err(desc,
2556                          "%s: tried to flag a GPIO set as output for IRQ\n",
2557                          __func__);
2558                return -EIO;
2559        }
2560
2561        set_bit(FLAG_USED_AS_IRQ, &desc->flags);
2562        return 0;
2563}
2564EXPORT_SYMBOL_GPL(gpiod_lock_as_irq);
2565
2566int gpio_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
2567{
2568        return gpiod_lock_as_irq(gpiochip_offset_to_desc(chip, offset));
2569}
2570EXPORT_SYMBOL_GPL(gpio_lock_as_irq);
2571
2572/**
2573 * gpiod_unlock_as_irq() - unlock a GPIO used as IRQ
2574 * @gpio: the GPIO line to unlock from IRQ usage
2575 *
2576 * This is used directly by GPIO drivers that want to indicate
2577 * that a certain GPIO is no longer used exclusively for IRQ.
2578 */
2579void gpiod_unlock_as_irq(struct gpio_desc *desc)
2580{
2581        if (!desc)
2582                return;
2583
2584        clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
2585}
2586EXPORT_SYMBOL_GPL(gpiod_unlock_as_irq);
2587
2588void gpio_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
2589{
2590        return gpiod_unlock_as_irq(gpiochip_offset_to_desc(chip, offset));
2591}
2592EXPORT_SYMBOL_GPL(gpio_unlock_as_irq);
2593
2594/**
2595 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
2596 * @desc: gpio whose value will be returned
2597 *
2598 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2599 * its ACTIVE_LOW status.
2600 *
2601 * This function is to be called from contexts that can sleep.
2602 */
2603int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
2604{
2605        might_sleep_if(extra_checks);
2606        if (!desc)
2607                return 0;
2608        return _gpiod_get_raw_value(desc);
2609}
2610EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
2611
2612/**
2613 * gpiod_get_value_cansleep() - return a gpio's value
2614 * @desc: gpio whose value will be returned
2615 *
2616 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2617 * account.
2618 *
2619 * This function is to be called from contexts that can sleep.
2620 */
2621int gpiod_get_value_cansleep(const struct gpio_desc *desc)
2622{
2623        int value;
2624
2625        might_sleep_if(extra_checks);
2626        if (!desc)
2627                return 0;
2628
2629        value = _gpiod_get_raw_value(desc);
2630        if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2631                value = !value;
2632
2633        return value;
2634}
2635EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
2636
2637/**
2638 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
2639 * @desc: gpio whose value will be assigned
2640 * @value: value to assign
2641 *
2642 * Set the raw value of the GPIO, i.e. the value of its physical line without
2643 * regard for its ACTIVE_LOW status.
2644 *
2645 * This function is to be called from contexts that can sleep.
2646 */
2647void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
2648{
2649        might_sleep_if(extra_checks);
2650        if (!desc)
2651                return;
2652        _gpiod_set_raw_value(desc, value);
2653}
2654EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
2655
2656/**
2657 * gpiod_set_value_cansleep() - assign a gpio's value
2658 * @desc: gpio whose value will be assigned
2659 * @value: value to assign
2660 *
2661 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2662 * account
2663 *
2664 * This function is to be called from contexts that can sleep.
2665 */
2666void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
2667{
2668        might_sleep_if(extra_checks);
2669        if (!desc)
2670                return;
2671
2672        if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2673                value = !value;
2674        _gpiod_set_raw_value(desc, value);
2675}
2676EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
2677
2678/**
2679 * gpiod_add_lookup_table() - register GPIO device consumers
2680 * @table: table of consumers to register
2681 */
2682void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
2683{
2684        mutex_lock(&gpio_lookup_lock);
2685
2686        list_add_tail(&table->list, &gpio_lookup_list);
2687
2688        mutex_unlock(&gpio_lookup_lock);
2689}
2690
2691#ifdef CONFIG_OF
2692static struct gpio_desc *of_find_gpio(struct device *dev, const char *con_id,
2693                                      unsigned int idx,
2694                                      enum gpio_lookup_flags *flags)
2695{
2696        char prop_name[32]; /* 32 is max size of property name */
2697        enum of_gpio_flags of_flags;
2698        struct gpio_desc *desc;
2699
2700        if (con_id)
2701                snprintf(prop_name, 32, "%s-gpios", con_id);
2702        else
2703                snprintf(prop_name, 32, "gpios");
2704
2705        desc = of_get_named_gpiod_flags(dev->of_node, prop_name, idx,
2706                                        &of_flags);
2707
2708        if (IS_ERR(desc))
2709                return desc;
2710
2711        if (of_flags & OF_GPIO_ACTIVE_LOW)
2712                *flags |= GPIO_ACTIVE_LOW;
2713
2714        return desc;
2715}
2716#else
2717static struct gpio_desc *of_find_gpio(struct device *dev, const char *con_id,
2718                                      unsigned int idx,
2719                                      enum gpio_lookup_flags *flags)
2720{
2721        return ERR_PTR(-ENODEV);
2722}
2723#endif
2724
2725static struct gpio_desc *acpi_find_gpio(struct device *dev, const char *con_id,
2726                                        unsigned int idx,
2727                                        enum gpio_lookup_flags *flags)
2728{
2729        static const char * const suffixes[] = { "gpios", "gpio" };
2730        struct acpi_device *adev = ACPI_COMPANION(dev);
2731        struct acpi_gpio_info info;
2732        struct gpio_desc *desc;
2733        char propname[32];
2734        int i;
2735
2736        /* Try first from _DSD */
2737        for (i = 0; i < ARRAY_SIZE(suffixes); i++) {
2738                if (con_id && strcmp(con_id, "gpios")) {
2739                        snprintf(propname, sizeof(propname), "%s-%s",
2740                                 con_id, suffixes[i]);
2741                } else {
2742                        snprintf(propname, sizeof(propname), "%s",
2743                                 suffixes[i]);
2744                }
2745
2746                desc = acpi_get_gpiod_by_index(adev, propname, idx, &info);
2747                if (!IS_ERR(desc) || (PTR_ERR(desc) == -EPROBE_DEFER))
2748                        break;
2749        }
2750
2751        /* Then from plain _CRS GPIOs */
2752        if (IS_ERR(desc)) {
2753                desc = acpi_get_gpiod_by_index(adev, NULL, idx, &info);
2754                if (IS_ERR(desc))
2755                        return desc;
2756        }
2757
2758        if (info.active_low)
2759                *flags |= GPIO_ACTIVE_LOW;
2760
2761        return desc;
2762}
2763
2764static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
2765{
2766        const char *dev_id = dev ? dev_name(dev) : NULL;
2767        struct gpiod_lookup_table *table;
2768
2769        mutex_lock(&gpio_lookup_lock);
2770
2771        list_for_each_entry(table, &gpio_lookup_list, list) {
2772                if (table->dev_id && dev_id) {
2773                        /*
2774                         * Valid strings on both ends, must be identical to have
2775                         * a match
2776                         */
2777                        if (!strcmp(table->dev_id, dev_id))
2778                                goto found;
2779                } else {
2780                        /*
2781                         * One of the pointers is NULL, so both must be to have
2782                         * a match
2783                         */
2784                        if (dev_id == table->dev_id)
2785                                goto found;
2786                }
2787        }
2788        table = NULL;
2789
2790found:
2791        mutex_unlock(&gpio_lookup_lock);
2792        return table;
2793}
2794
2795static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
2796                                    unsigned int idx,
2797                                    enum gpio_lookup_flags *flags)
2798{
2799        struct gpio_desc *desc = ERR_PTR(-ENOENT);
2800        struct gpiod_lookup_table *table;
2801        struct gpiod_lookup *p;
2802
2803        table = gpiod_find_lookup_table(dev);
2804        if (!table)
2805                return desc;
2806
2807        for (p = &table->table[0]; p->chip_label; p++) {
2808                struct gpio_chip *chip;
2809
2810                /* idx must always match exactly */
2811                if (p->idx != idx)
2812                        continue;
2813
2814                /* If the lookup entry has a con_id, require exact match */
2815                if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
2816                        continue;
2817
2818                chip = find_chip_by_name(p->chip_label);
2819
2820                if (!chip) {
2821                        dev_err(dev, "cannot find GPIO chip %s\n",
2822                                p->chip_label);
2823                        return ERR_PTR(-ENODEV);
2824                }
2825
2826                if (chip->ngpio <= p->chip_hwnum) {
2827                        dev_err(dev,
2828                                "requested GPIO %d is out of range [0..%d] for chip %s\n",
2829                                idx, chip->ngpio, chip->label);
2830                        return ERR_PTR(-EINVAL);
2831                }
2832
2833                desc = gpiochip_offset_to_desc(chip, p->chip_hwnum);
2834                *flags = p->flags;
2835
2836                return desc;
2837        }
2838
2839        return desc;
2840}
2841
2842/**
2843 * gpio_get - obtain a GPIO for a given GPIO function
2844 * @dev:        GPIO consumer, can be NULL for system-global GPIOs
2845 * @con_id:     function within the GPIO consumer
2846 * @flags:      optional GPIO initialization flags
2847 *
2848 * Return the GPIO descriptor corresponding to the function con_id of device
2849 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
2850 * another IS_ERR() code if an error occured while trying to acquire the GPIO.
2851 */
2852struct gpio_desc *__must_check __gpiod_get(struct device *dev, const char *con_id,
2853                                         enum gpiod_flags flags)
2854{
2855        return gpiod_get_index(dev, con_id, 0, flags);
2856}
2857EXPORT_SYMBOL_GPL(__gpiod_get);
2858
2859/**
2860 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
2861 * @dev: GPIO consumer, can be NULL for system-global GPIOs
2862 * @con_id: function within the GPIO consumer
2863 * @flags: optional GPIO initialization flags
2864 *
2865 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
2866 * the requested function it will return NULL. This is convenient for drivers
2867 * that need to handle optional GPIOs.
2868 */
2869struct gpio_desc *__must_check __gpiod_get_optional(struct device *dev,
2870                                                  const char *con_id,
2871                                                  enum gpiod_flags flags)
2872{
2873        return gpiod_get_index_optional(dev, con_id, 0, flags);
2874}
2875EXPORT_SYMBOL_GPL(__gpiod_get_optional);
2876
2877/**
2878 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
2879 * @dev:        GPIO consumer, can be NULL for system-global GPIOs
2880 * @con_id:     function within the GPIO consumer
2881 * @idx:        index of the GPIO to obtain in the consumer
2882 * @flags:      optional GPIO initialization flags
2883 *
2884 * This variant of gpiod_get() allows to access GPIOs other than the first
2885 * defined one for functions that define several GPIOs.
2886 *
2887 * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
2888 * requested function and/or index, or another IS_ERR() code if an error
2889 * occured while trying to acquire the GPIO.
2890 */
2891struct gpio_desc *__must_check __gpiod_get_index(struct device *dev,
2892                                               const char *con_id,
2893                                               unsigned int idx,
2894                                               enum gpiod_flags flags)
2895{
2896        struct gpio_desc *desc = NULL;
2897        int status;
2898        enum gpio_lookup_flags lookupflags = 0;
2899
2900        dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
2901
2902        /* Using device tree? */
2903        if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node) {
2904                dev_dbg(dev, "using device tree for GPIO lookup\n");
2905                desc = of_find_gpio(dev, con_id, idx, &lookupflags);
2906        } else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev)) {
2907                dev_dbg(dev, "using ACPI for GPIO lookup\n");
2908                desc = acpi_find_gpio(dev, con_id, idx, &lookupflags);
2909        }
2910
2911        /*
2912         * Either we are not using DT or ACPI, or their lookup did not return
2913         * a result. In that case, use platform lookup as a fallback.
2914         */
2915        if (!desc || desc == ERR_PTR(-ENOENT)) {
2916                dev_dbg(dev, "using lookup tables for GPIO lookup");
2917                desc = gpiod_find(dev, con_id, idx, &lookupflags);
2918        }
2919
2920        if (IS_ERR(desc)) {
2921                dev_dbg(dev, "lookup for GPIO %s failed\n", con_id);
2922                return desc;
2923        }
2924
2925        status = gpiod_request(desc, con_id);
2926
2927        if (status < 0)
2928                return ERR_PTR(status);
2929
2930        if (lookupflags & GPIO_ACTIVE_LOW)
2931                set_bit(FLAG_ACTIVE_LOW, &desc->flags);
2932        if (lookupflags & GPIO_OPEN_DRAIN)
2933                set_bit(FLAG_OPEN_DRAIN, &desc->flags);
2934        if (lookupflags & GPIO_OPEN_SOURCE)
2935                set_bit(FLAG_OPEN_SOURCE, &desc->flags);
2936
2937        /* No particular flag request, return here... */
2938        if (flags & GPIOD_FLAGS_BIT_DIR_SET)
2939                return desc;
2940
2941        /* Process flags */
2942        if (flags & GPIOD_FLAGS_BIT_DIR_OUT)
2943                status = gpiod_direction_output(desc,
2944                                              flags & GPIOD_FLAGS_BIT_DIR_VAL);
2945        else
2946                status = gpiod_direction_input(desc);
2947
2948        if (status < 0) {
2949                dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
2950                gpiod_put(desc);
2951                return ERR_PTR(status);
2952        }
2953
2954        return desc;
2955}
2956EXPORT_SYMBOL_GPL(__gpiod_get_index);
2957
2958/**
2959 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
2960 *                            function
2961 * @dev: GPIO consumer, can be NULL for system-global GPIOs
2962 * @con_id: function within the GPIO consumer
2963 * @index: index of the GPIO to obtain in the consumer
2964 * @flags: optional GPIO initialization flags
2965 *
2966 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
2967 * specified index was assigned to the requested function it will return NULL.
2968 * This is convenient for drivers that need to handle optional GPIOs.
2969 */
2970struct gpio_desc *__must_check __gpiod_get_index_optional(struct device *dev,
2971                                                        const char *con_id,
2972                                                        unsigned int index,
2973                                                        enum gpiod_flags flags)
2974{
2975        struct gpio_desc *desc;
2976
2977        desc = gpiod_get_index(dev, con_id, index, flags);
2978        if (IS_ERR(desc)) {
2979                if (PTR_ERR(desc) == -ENOENT)
2980                        return NULL;
2981        }
2982
2983        return desc;
2984}
2985EXPORT_SYMBOL_GPL(__gpiod_get_index_optional);
2986
2987/**
2988 * gpiod_put - dispose of a GPIO descriptor
2989 * @desc:       GPIO descriptor to dispose of
2990 *
2991 * No descriptor can be used after gpiod_put() has been called on it.
2992 */
2993void gpiod_put(struct gpio_desc *desc)
2994{
2995        gpiod_free(desc);
2996}
2997EXPORT_SYMBOL_GPL(gpiod_put);
2998
2999#ifdef CONFIG_DEBUG_FS
3000
3001static void gpiolib_dbg_show(struct seq_file *s, struct gpio_chip *chip)
3002{
3003        unsigned                i;
3004        struct gpio_device *gdev = chip->gpiodev;
3005        unsigned                gpio = gdev->base;
3006        struct gpio_desc        *gdesc = &chip->desc[0];
3007        int                     is_out;
3008        int                     is_irq;
3009
3010        for (i = 0; i < chip->ngpio; i++, gpio++, gdesc++) {
3011                if (!test_bit(FLAG_REQUESTED, &gdesc->flags))
3012                        continue;
3013
3014                gpiod_get_direction(gdesc);
3015                is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
3016                is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
3017                seq_printf(s, " gpio-%-3d (%-20.20s) %s %s %s",
3018                        gpio, gdesc->label,
3019                        is_out ? "out" : "in ",
3020                        chip->get
3021                                ? (chip->get(chip, i) ? "hi" : "lo")
3022                                : "?  ",
3023                        is_irq ? "IRQ" : "   ");
3024                seq_printf(s, "\n");
3025        }
3026}
3027
3028static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
3029{
3030        unsigned long flags;
3031        struct gpio_device *gdev = NULL;
3032        loff_t index = *pos;
3033
3034        s->private = "";
3035
3036        spin_lock_irqsave(&gpio_lock, flags);
3037        list_for_each_entry(gdev, &gpio_devices, list)
3038                if (index-- == 0) {
3039                        spin_unlock_irqrestore(&gpio_lock, flags);
3040                        return gdev;
3041                }
3042        spin_unlock_irqrestore(&gpio_lock, flags);
3043
3044        return NULL;
3045}
3046
3047static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
3048{
3049        unsigned long flags;
3050        struct gpio_device *gdev = v;
3051        void *ret = NULL;
3052
3053        spin_lock_irqsave(&gpio_lock, flags);
3054        if (list_is_last(&gdev->list, &gpio_devices))
3055                ret = NULL;
3056        else
3057                ret = list_entry(gdev->list.next, struct gpio_device, list);
3058        spin_unlock_irqrestore(&gpio_lock, flags);
3059
3060        s->private = "\n";
3061        ++*pos;
3062
3063        return ret;
3064}
3065
3066static void gpiolib_seq_stop(struct seq_file *s, void *v)
3067{
3068}
3069
3070static int gpiolib_seq_show(struct seq_file *s, void *v)
3071{
3072        struct gpio_device *gdev = v;
3073        struct gpio_chip *chip = gdev->chip;
3074        struct device *parent;
3075
3076        if (!chip) {
3077                seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
3078                           dev_name(&gdev->dev));
3079                return 0;
3080        }
3081
3082        seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
3083                   dev_name(&gdev->dev),
3084                   gdev->base, gdev->base + chip->ngpio - 1);
3085        parent = chip->dev;
3086        if (parent)
3087                seq_printf(s, ", parent: %s/%s",
3088                           parent->bus ? parent->bus->name : "no-bus",
3089                           dev_name(parent));
3090        if (chip->label)
3091                seq_printf(s, ", %s", chip->label);
3092        if (chip->can_sleep)
3093                seq_printf(s, ", can sleep");
3094        seq_printf(s, ":\n");
3095
3096        if (chip->dbg_show)
3097                chip->dbg_show(s, chip);
3098        else
3099                gpiolib_dbg_show(s, chip);
3100
3101        return 0;
3102}
3103
3104static const struct seq_operations gpiolib_seq_ops = {
3105        .start = gpiolib_seq_start,
3106        .next = gpiolib_seq_next,
3107        .stop = gpiolib_seq_stop,
3108        .show = gpiolib_seq_show,
3109};
3110
3111static int gpiolib_open(struct inode *inode, struct file *file)
3112{
3113        return seq_open(file, &gpiolib_seq_ops);
3114}
3115
3116static const struct file_operations gpiolib_operations = {
3117        .owner          = THIS_MODULE,
3118        .open           = gpiolib_open,
3119        .read           = seq_read,
3120        .llseek         = seq_lseek,
3121        .release        = seq_release,
3122};
3123
3124static int __init gpiolib_debugfs_init(void)
3125{
3126        /* /sys/kernel/debug/gpio */
3127        (void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
3128                                NULL, NULL, &gpiolib_operations);
3129        return 0;
3130}
3131subsys_initcall(gpiolib_debugfs_init);
3132
3133#endif  /* DEBUG_FS */
3134