File Index
Files and directories
Sign in
FILE

gpiolib.c

File preview with syntax highlighting.

linux-6.19.14/drivers/gpio/gpiolib.c C
   1// SPDX-License-Identifier: GPL-2.0
   2
   3#include <linux/acpi.h>
   4#include <linux/array_size.h>
   5#include <linux/bitmap.h>
   6#include <linux/cleanup.h>
   7#include <linux/compat.h>
   8#include <linux/debugfs.h>
   9#include <linux/device.h>
  10#include <linux/err.h>
  11#include <linux/errno.h>
  12#include <linux/file.h>
  13#include <linux/fs.h>
  14#include <linux/idr.h>
  15#include <linux/interrupt.h>
  16#include <linux/irq.h>
  17#include <linux/irqdesc.h>
  18#include <linux/kernel.h>
  19#include <linux/list.h>
  20#include <linux/lockdep.h>
  21#include <linux/module.h>
  22#include <linux/nospec.h>
  23#include <linux/of.h>
  24#include <linux/pinctrl/consumer.h>
  25#include <linux/seq_file.h>
  26#include <linux/slab.h>
  27#include <linux/srcu.h>
  28#include <linux/string.h>
  29#include <linux/string_choices.h>
  30
  31#include <linux/gpio.h>
  32#include <linux/gpio/driver.h>
  33#include <linux/gpio/machine.h>
  34
  35#include <uapi/linux/gpio.h>
  36
  37#include "gpiolib-acpi.h"
  38#include "gpiolib-cdev.h"
  39#include "gpiolib-of.h"
  40#include "gpiolib-shared.h"
  41#include "gpiolib-swnode.h"
  42#include "gpiolib-sysfs.h"
  43#include "gpiolib.h"
  44
  45#define CREATE_TRACE_POINTS
  46#include <trace/events/gpio.h>
  47
  48/* Implementation infrastructure for GPIO interfaces.
  49 *
  50 * The GPIO programming interface allows for inlining speed-critical
  51 * get/set operations for common cases, so that access to SOC-integrated
  52 * GPIOs can sometimes cost only an instruction or two per bit.
  53 */
  54
  55/* Device and char device-related information */
  56static DEFINE_IDA(gpio_ida);
  57static dev_t gpio_devt;
  58#define GPIO_DEV_MAX 256 /* 256 GPIO chip devices supported */
  59
  60static int gpio_bus_match(struct device *dev, const struct device_driver *drv)
  61{
  62	struct fwnode_handle *fwnode = dev_fwnode(dev);
  63
  64	/*
  65	 * Only match if the fwnode doesn't already have a proper struct device
  66	 * created for it.
  67	 */
  68	if (fwnode && fwnode->dev != dev)
  69		return 0;
  70	return 1;
  71}
  72
  73static const struct bus_type gpio_bus_type = {
  74	.name = "gpio",
  75	.match = gpio_bus_match,
  76};
  77
  78/*
  79 * At the end we want all GPIOs to be dynamically allocated from 0.
  80 * However, some legacy drivers still perform fixed allocation.
  81 * Until they are all fixed, leave 0-512 space for them.
  82 */
  83#define GPIO_DYNAMIC_BASE	512
  84/*
  85 * Define the maximum of the possible GPIO in the global numberspace.
  86 * While the GPIO base and numbers are positive, we limit it with signed
  87 * maximum as a lot of code is using negative values for special cases.
  88 */
  89#define GPIO_DYNAMIC_MAX	INT_MAX
  90
  91/*
  92 * Number of GPIOs to use for the fast path in set array
  93 */
  94#define FASTPATH_NGPIO CONFIG_GPIOLIB_FASTPATH_LIMIT
  95
  96static DEFINE_MUTEX(gpio_lookup_lock);
  97static LIST_HEAD(gpio_lookup_list);
  98
  99static LIST_HEAD(gpio_devices);
 100/* Protects the GPIO device list against concurrent modifications. */
 101static DEFINE_MUTEX(gpio_devices_lock);
 102/* Ensures coherence during read-only accesses to the list of GPIO devices. */
 103DEFINE_STATIC_SRCU(gpio_devices_srcu);
 104
 105static DEFINE_MUTEX(gpio_machine_hogs_mutex);
 106static LIST_HEAD(gpio_machine_hogs);
 107
 108const char *const gpio_suffixes[] = { "gpios", "gpio", NULL };
 109
 110static void gpiochip_free_hogs(struct gpio_chip *gc);
 111static int gpiochip_add_irqchip(struct gpio_chip *gc,
 112				struct lock_class_key *lock_key,
 113				struct lock_class_key *request_key);
 114static void gpiochip_irqchip_remove(struct gpio_chip *gc);
 115static int gpiochip_irqchip_init_hw(struct gpio_chip *gc);
 116static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc);
 117static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc);
 118
 119static bool gpiolib_initialized;
 120
 121const char *gpiod_get_label(struct gpio_desc *desc)
 122{
 123	struct gpio_desc_label *label;
 124	unsigned long flags;
 125
 126	flags = READ_ONCE(desc->flags);
 127
 128	label = srcu_dereference_check(desc->label, &desc->gdev->desc_srcu,
 129				srcu_read_lock_held(&desc->gdev->desc_srcu));
 130
 131	if (test_bit(GPIOD_FLAG_USED_AS_IRQ, &flags))
 132		return label ? label->str : "interrupt";
 133
 134	if (!test_bit(GPIOD_FLAG_REQUESTED, &flags))
 135		return NULL;
 136
 137	return label ? label->str : NULL;
 138}
 139
 140static void desc_free_label(struct rcu_head *rh)
 141{
 142	kfree(container_of(rh, struct gpio_desc_label, rh));
 143}
 144
 145static int desc_set_label(struct gpio_desc *desc, const char *label)
 146{
 147	struct gpio_desc_label *new = NULL, *old;
 148
 149	if (label) {
 150		new = kzalloc(struct_size(new, str, strlen(label) + 1),
 151			      GFP_KERNEL);
 152		if (!new)
 153			return -ENOMEM;
 154
 155		strcpy(new->str, label);
 156	}
 157
 158	old = rcu_replace_pointer(desc->label, new, 1);
 159	if (old)
 160		call_srcu(&desc->gdev->desc_srcu, &old->rh, desc_free_label);
 161
 162	return 0;
 163}
 164
 165/**
 166 * gpio_to_desc - Convert a GPIO number to its descriptor
 167 * @gpio: global GPIO number
 168 *
 169 * Returns:
 170 * The GPIO descriptor associated with the given GPIO, or %NULL if no GPIO
 171 * with the given number exists in the system.
 172 */
 173struct gpio_desc *gpio_to_desc(unsigned gpio)
 174{
 175	struct gpio_device *gdev;
 176
 177	scoped_guard(srcu, &gpio_devices_srcu) {
 178		list_for_each_entry_srcu(gdev, &gpio_devices, list,
 179				srcu_read_lock_held(&gpio_devices_srcu)) {
 180			if (gdev->base <= gpio &&
 181			    gdev->base + gdev->ngpio > gpio)
 182				return &gdev->descs[gpio - gdev->base];
 183		}
 184	}
 185
 186	return NULL;
 187}
 188EXPORT_SYMBOL_GPL(gpio_to_desc);
 189
 190/* This function is deprecated and will be removed soon, don't use. */
 191struct gpio_desc *gpiochip_get_desc(struct gpio_chip *gc,
 192				    unsigned int hwnum)
 193{
 194	return gpio_device_get_desc(gc->gpiodev, hwnum);
 195}
 196
 197/**
 198 * gpio_device_get_desc() - get the GPIO descriptor corresponding to the given
 199 *                          hardware number for this GPIO device
 200 * @gdev: GPIO device to get the descriptor from
 201 * @hwnum: hardware number of the GPIO for this chip
 202 *
 203 * Returns:
 204 * A pointer to the GPIO descriptor or %EINVAL if no GPIO exists in the given
 205 * chip for the specified hardware number or %ENODEV if the underlying chip
 206 * already vanished.
 207 *
 208 * The reference count of struct gpio_device is *NOT* increased like when the
 209 * GPIO is being requested for exclusive usage. It's up to the caller to make
 210 * sure the GPIO device will stay alive together with the descriptor returned
 211 * by this function.
 212 */
 213struct gpio_desc *
 214gpio_device_get_desc(struct gpio_device *gdev, unsigned int hwnum)
 215{
 216	if (hwnum >= gdev->ngpio)
 217		return ERR_PTR(-EINVAL);
 218
 219	return &gdev->descs[array_index_nospec(hwnum, gdev->ngpio)];
 220}
 221EXPORT_SYMBOL_GPL(gpio_device_get_desc);
 222
 223/**
 224 * desc_to_gpio - convert a GPIO descriptor to the integer namespace
 225 * @desc: GPIO descriptor
 226 *
 227 * This should disappear in the future but is needed since we still
 228 * use GPIO numbers for error messages and sysfs nodes.
 229 *
 230 * Returns:
 231 * The global GPIO number for the GPIO specified by its descriptor.
 232 */
 233int desc_to_gpio(const struct gpio_desc *desc)
 234{
 235	return desc->gdev->base + (desc - &desc->gdev->descs[0]);
 236}
 237EXPORT_SYMBOL_GPL(desc_to_gpio);
 238
 239/**
 240 * gpiod_hwgpio - Return the GPIO number of the passed descriptor relative to
 241 *                its chip.
 242 * @desc: GPIO descriptor
 243 *
 244 * Returns:
 245 * Hardware offset of the GPIO represented by the descriptor.
 246 */
 247int gpiod_hwgpio(const struct gpio_desc *desc)
 248{
 249	return desc - &desc->gdev->descs[0];
 250}
 251EXPORT_SYMBOL_GPL(gpiod_hwgpio);
 252
 253/**
 254 * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
 255 * @desc:	descriptor to return the chip of
 256 *
 257 * *DEPRECATED*
 258 * This function is unsafe and should not be used. Using the chip address
 259 * without taking the SRCU read lock may result in dereferencing a dangling
 260 * pointer.
 261 *
 262 * Returns:
 263 * Address of the GPIO chip backing this device.
 264 */
 265struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
 266{
 267	if (!desc)
 268		return NULL;
 269
 270	return gpio_device_get_chip(desc->gdev);
 271}
 272EXPORT_SYMBOL_GPL(gpiod_to_chip);
 273
 274/**
 275 * gpiod_to_gpio_device() - Return the GPIO device to which this descriptor
 276 *                          belongs.
 277 * @desc: Descriptor for which to return the GPIO device.
 278 *
 279 * This *DOES NOT* increase the reference count of the GPIO device as it's
 280 * expected that the descriptor is requested and the users already holds a
 281 * reference to the device.
 282 *
 283 * Returns:
 284 * Address of the GPIO device owning this descriptor.
 285 */
 286struct gpio_device *gpiod_to_gpio_device(struct gpio_desc *desc)
 287{
 288	if (!desc)
 289		return NULL;
 290
 291	return desc->gdev;
 292}
 293EXPORT_SYMBOL_GPL(gpiod_to_gpio_device);
 294
 295/**
 296 * gpio_device_get_base() - Get the base GPIO number allocated by this device
 297 * @gdev: GPIO device
 298 *
 299 * Returns:
 300 * First GPIO number in the global GPIO numberspace for this device.
 301 */
 302int gpio_device_get_base(struct gpio_device *gdev)
 303{
 304	return gdev->base;
 305}
 306EXPORT_SYMBOL_GPL(gpio_device_get_base);
 307
 308/**
 309 * gpio_device_get_label() - Get the label of this GPIO device
 310 * @gdev: GPIO device
 311 *
 312 * Returns:
 313 * Pointer to the string containing the GPIO device label. The string's
 314 * lifetime is tied to that of the underlying GPIO device.
 315 */
 316const char *gpio_device_get_label(struct gpio_device *gdev)
 317{
 318	return gdev->label;
 319}
 320EXPORT_SYMBOL(gpio_device_get_label);
 321
 322/**
 323 * gpio_device_get_chip() - Get the gpio_chip implementation of this GPIO device
 324 * @gdev: GPIO device
 325 *
 326 * Returns:
 327 * Address of the GPIO chip backing this device.
 328 *
 329 * *DEPRECATED*
 330 * Until we can get rid of all non-driver users of struct gpio_chip, we must
 331 * provide a way of retrieving the pointer to it from struct gpio_device. This
 332 * is *NOT* safe as the GPIO API is considered to be hot-unpluggable and the
 333 * chip can dissapear at any moment (unlike reference-counted struct
 334 * gpio_device).
 335 *
 336 * Use at your own risk.
 337 */
 338struct gpio_chip *gpio_device_get_chip(struct gpio_device *gdev)
 339{
 340	return rcu_dereference_check(gdev->chip, 1);
 341}
 342EXPORT_SYMBOL_GPL(gpio_device_get_chip);
 343
 344/* dynamic allocation of GPIOs, e.g. on a hotplugged device */
 345static int gpiochip_find_base_unlocked(u16 ngpio)
 346{
 347	unsigned int base = GPIO_DYNAMIC_BASE;
 348	struct gpio_device *gdev;
 349
 350	list_for_each_entry_srcu(gdev, &gpio_devices, list,
 351				 lockdep_is_held(&gpio_devices_lock)) {
 352		/* found a free space? */
 353		if (gdev->base >= base + ngpio)
 354			break;
 355		/* nope, check the space right after the chip */
 356		base = gdev->base + gdev->ngpio;
 357		if (base < GPIO_DYNAMIC_BASE)
 358			base = GPIO_DYNAMIC_BASE;
 359		if (base > GPIO_DYNAMIC_MAX - ngpio)
 360			break;
 361	}
 362
 363	if (base <= GPIO_DYNAMIC_MAX - ngpio) {
 364		pr_debug("%s: found new base at %d\n", __func__, base);
 365		return base;
 366	} else {
 367		pr_err("%s: cannot find free range\n", __func__);
 368		return -ENOSPC;
 369	}
 370}
 371
 372/*
 373 * This descriptor validation needs to be inserted verbatim into each
 374 * function taking a descriptor, so we need to use a preprocessor
 375 * macro to avoid endless duplication. If the desc is NULL it is an
 376 * optional GPIO and calls should just bail out.
 377 */
 378static int validate_desc(const struct gpio_desc *desc, const char *func)
 379{
 380	if (!desc)
 381		return 0;
 382
 383	if (IS_ERR(desc)) {
 384		pr_warn("%s: invalid GPIO (errorpointer: %pe)\n", func, desc);
 385		return PTR_ERR(desc);
 386	}
 387
 388	return 1;
 389}
 390
 391#define VALIDATE_DESC(desc) do { \
 392	int __valid = validate_desc(desc, __func__); \
 393	if (__valid <= 0) \
 394		return __valid; \
 395	} while (0)
 396
 397#define VALIDATE_DESC_VOID(desc) do { \
 398	int __valid = validate_desc(desc, __func__); \
 399	if (__valid <= 0) \
 400		return; \
 401	} while (0)
 402
 403/**
 404 * gpiod_is_equal() - Check if two GPIO descriptors refer to the same pin.
 405 * @desc: Descriptor to compare.
 406 * @other: The second descriptor to compare against.
 407 *
 408 * Returns:
 409 * True if the descriptors refer to the same physical pin. False otherwise.
 410 */
 411bool gpiod_is_equal(const struct gpio_desc *desc, const struct gpio_desc *other)
 412{
 413	return validate_desc(desc, __func__) > 0 &&
 414	       !IS_ERR_OR_NULL(other) && desc == other;
 415}
 416EXPORT_SYMBOL_GPL(gpiod_is_equal);
 417
 418static int gpiochip_get_direction(struct gpio_chip *gc, unsigned int offset)
 419{
 420	int ret;
 421
 422	lockdep_assert_held(&gc->gpiodev->srcu);
 423
 424	if (WARN_ON(!gc->get_direction))
 425		return -EOPNOTSUPP;
 426
 427	ret = gc->get_direction(gc, offset);
 428	if (ret < 0)
 429		return ret;
 430
 431	if (ret != GPIO_LINE_DIRECTION_OUT && ret != GPIO_LINE_DIRECTION_IN)
 432		ret = -EBADE;
 433
 434	return ret;
 435}
 436
 437/**
 438 * gpiod_get_direction - return the current direction of a GPIO
 439 * @desc:	GPIO to get the direction of
 440 *
 441 * Returns:
 442 * 0 for output, 1 for input, or an error code in case of error.
 443 *
 444 * This function may sleep if gpiod_cansleep() is true.
 445 */
 446int gpiod_get_direction(struct gpio_desc *desc)
 447{
 448	unsigned long flags;
 449	unsigned int offset;
 450	int ret;
 451
 452	ret = validate_desc(desc, __func__);
 453	if (ret <= 0)
 454		return -EINVAL;
 455
 456	CLASS(gpio_chip_guard, guard)(desc);
 457	if (!guard.gc)
 458		return -ENODEV;
 459
 460	offset = gpiod_hwgpio(desc);
 461	flags = READ_ONCE(desc->flags);
 462
 463	/*
 464	 * Open drain emulation using input mode may incorrectly report
 465	 * input here, fix that up.
 466	 */
 467	if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &flags) &&
 468	    test_bit(GPIOD_FLAG_IS_OUT, &flags))
 469		return 0;
 470
 471	ret = gpiochip_get_direction(guard.gc, offset);
 472	if (ret < 0)
 473		return ret;
 474
 475	/*
 476	 * GPIO_LINE_DIRECTION_IN or other positive,
 477	 * otherwise GPIO_LINE_DIRECTION_OUT.
 478	 */
 479	if (ret > 0)
 480		ret = 1;
 481
 482	assign_bit(GPIOD_FLAG_IS_OUT, &flags, !ret);
 483	WRITE_ONCE(desc->flags, flags);
 484
 485	return ret;
 486}
 487EXPORT_SYMBOL_GPL(gpiod_get_direction);
 488
 489/*
 490 * Add a new chip to the global chips list, keeping the list of chips sorted
 491 * by range(means [base, base + ngpio - 1]) order.
 492 *
 493 * Returns:
 494 * -EBUSY if the new chip overlaps with some other chip's integer space.
 495 */
 496static int gpiodev_add_to_list_unlocked(struct gpio_device *gdev)
 497{
 498	struct gpio_device *prev, *next;
 499
 500	lockdep_assert_held(&gpio_devices_lock);
 501
 502	if (list_empty(&gpio_devices)) {
 503		/* initial entry in list */
 504		list_add_tail_rcu(&gdev->list, &gpio_devices);
 505		return 0;
 506	}
 507
 508	next = list_first_entry(&gpio_devices, struct gpio_device, list);
 509	if (gdev->base + gdev->ngpio <= next->base) {
 510		/* add before first entry */
 511		list_add_rcu(&gdev->list, &gpio_devices);
 512		return 0;
 513	}
 514
 515	prev = list_last_entry(&gpio_devices, struct gpio_device, list);
 516	if (prev->base + prev->ngpio <= gdev->base) {
 517		/* add behind last entry */
 518		list_add_tail_rcu(&gdev->list, &gpio_devices);
 519		return 0;
 520	}
 521
 522	list_for_each_entry_safe(prev, next, &gpio_devices, list) {
 523		/* at the end of the list */
 524		if (&next->list == &gpio_devices)
 525			break;
 526
 527		/* add between prev and next */
 528		if (prev->base + prev->ngpio <= gdev->base
 529				&& gdev->base + gdev->ngpio <= next->base) {
 530			list_add_rcu(&gdev->list, &prev->list);
 531			return 0;
 532		}
 533	}
 534
 535	synchronize_srcu(&gpio_devices_srcu);
 536
 537	return -EBUSY;
 538}
 539
 540/*
 541 * Convert a GPIO name to its descriptor
 542 * Note that there is no guarantee that GPIO names are globally unique!
 543 * Hence this function will return, if it exists, a reference to the first GPIO
 544 * line found that matches the given name.
 545 */
 546static struct gpio_desc *gpio_name_to_desc(const char * const name)
 547{
 548	struct gpio_device *gdev;
 549	struct gpio_desc *desc;
 550	struct gpio_chip *gc;
 551
 552	if (!name)
 553		return NULL;
 554
 555	guard(srcu)(&gpio_devices_srcu);
 556
 557	list_for_each_entry_srcu(gdev, &gpio_devices, list,
 558				 srcu_read_lock_held(&gpio_devices_srcu)) {
 559		guard(srcu)(&gdev->srcu);
 560
 561		gc = srcu_dereference(gdev->chip, &gdev->srcu);
 562		if (!gc)
 563			continue;
 564
 565		for_each_gpio_desc(gc, desc) {
 566			if (desc->name && !strcmp(desc->name, name))
 567				return desc;
 568		}
 569	}
 570
 571	return NULL;
 572}
 573
 574/*
 575 * Take the names from gc->names and assign them to their GPIO descriptors.
 576 * Warn if a name is already used for a GPIO line on a different GPIO chip.
 577 *
 578 * Note that:
 579 *   1. Non-unique names are still accepted,
 580 *   2. Name collisions within the same GPIO chip are not reported.
 581 */
 582static void gpiochip_set_desc_names(struct gpio_chip *gc)
 583{
 584	struct gpio_device *gdev = gc->gpiodev;
 585	int i;
 586
 587	/* First check all names if they are unique */
 588	for (i = 0; i != gc->ngpio; ++i) {
 589		struct gpio_desc *gpio;
 590
 591		gpio = gpio_name_to_desc(gc->names[i]);
 592		if (gpio)
 593			dev_warn(&gdev->dev,
 594				 "Detected name collision for GPIO name '%s'\n",
 595				 gc->names[i]);
 596	}
 597
 598	/* Then add all names to the GPIO descriptors */
 599	for (i = 0; i != gc->ngpio; ++i)
 600		gdev->descs[i].name = gc->names[i];
 601}
 602
 603/*
 604 * gpiochip_set_names - Set GPIO line names using device properties
 605 * @chip: GPIO chip whose lines should be named, if possible
 606 *
 607 * Looks for device property "gpio-line-names" and if it exists assigns
 608 * GPIO line names for the chip. The memory allocated for the assigned
 609 * names belong to the underlying firmware node and should not be released
 610 * by the caller.
 611 */
 612static int gpiochip_set_names(struct gpio_chip *chip)
 613{
 614	struct gpio_device *gdev = chip->gpiodev;
 615	struct device *dev = &gdev->dev;
 616	const char **names;
 617	int ret, i;
 618	int count;
 619
 620	count = device_property_string_array_count(dev, "gpio-line-names");
 621	if (count < 0)
 622		return 0;
 623
 624	/*
 625	 * When offset is set in the driver side we assume the driver internally
 626	 * is using more than one gpiochip per the same device. We have to stop
 627	 * setting friendly names if the specified ones with 'gpio-line-names'
 628	 * are less than the offset in the device itself. This means all the
 629	 * lines are not present for every single pin within all the internal
 630	 * gpiochips.
 631	 */
 632	if (count <= chip->offset) {
 633		dev_warn(dev, "gpio-line-names too short (length %d), cannot map names for the gpiochip at offset %u\n",
 634			 count, chip->offset);
 635		return 0;
 636	}
 637
 638	names = kcalloc(count, sizeof(*names), GFP_KERNEL);
 639	if (!names)
 640		return -ENOMEM;
 641
 642	ret = device_property_read_string_array(dev, "gpio-line-names",
 643						names, count);
 644	if (ret < 0) {
 645		dev_warn(dev, "failed to read GPIO line names\n");
 646		kfree(names);
 647		return ret;
 648	}
 649
 650	/*
 651	 * When more that one gpiochip per device is used, 'count' can
 652	 * contain at most number gpiochips x chip->ngpio. We have to
 653	 * correctly distribute all defined lines taking into account
 654	 * chip->offset as starting point from where we will assign
 655	 * the names to pins from the 'names' array. Since property
 656	 * 'gpio-line-names' cannot contains gaps, we have to be sure
 657	 * we only assign those pins that really exists since chip->ngpio
 658	 * can be different of the chip->offset.
 659	 */
 660	count = (count > chip->offset) ? count - chip->offset : count;
 661	if (count > chip->ngpio)
 662		count = chip->ngpio;
 663
 664	for (i = 0; i < count; i++) {
 665		/*
 666		 * Allow overriding "fixed" names provided by the GPIO
 667		 * provider. The "fixed" names are more often than not
 668		 * generic and less informative than the names given in
 669		 * device properties.
 670		 */
 671		if (names[chip->offset + i] && names[chip->offset + i][0])
 672			gdev->descs[i].name = names[chip->offset + i];
 673	}
 674
 675	kfree(names);
 676
 677	return 0;
 678}
 679
 680static unsigned long *gpiochip_allocate_mask(struct gpio_chip *gc)
 681{
 682	unsigned long *p;
 683
 684	p = bitmap_alloc(gc->ngpio, GFP_KERNEL);
 685	if (!p)
 686		return NULL;
 687
 688	/* Assume by default all GPIOs are valid */
 689	bitmap_fill(p, gc->ngpio);
 690
 691	return p;
 692}
 693
 694static void gpiochip_free_mask(unsigned long **p)
 695{
 696	bitmap_free(*p);
 697	*p = NULL;
 698}
 699
 700static unsigned int gpiochip_count_reserved_ranges(struct gpio_chip *gc)
 701{
 702	struct device *dev = &gc->gpiodev->dev;
 703	int size;
 704
 705	/* Format is "start, count, ..." */
 706	size = device_property_count_u32(dev, "gpio-reserved-ranges");
 707	if (size > 0 && size % 2 == 0)
 708		return size;
 709
 710	return 0;
 711}
 712
 713static int gpiochip_apply_reserved_ranges(struct gpio_chip *gc)
 714{
 715	struct device *dev = &gc->gpiodev->dev;
 716	unsigned int size;
 717	u32 *ranges;
 718	int ret;
 719
 720	size = gpiochip_count_reserved_ranges(gc);
 721	if (size == 0)
 722		return 0;
 723
 724	ranges = kmalloc_array(size, sizeof(*ranges), GFP_KERNEL);
 725	if (!ranges)
 726		return -ENOMEM;
 727
 728	ret = device_property_read_u32_array(dev, "gpio-reserved-ranges",
 729					     ranges, size);
 730	if (ret) {
 731		kfree(ranges);
 732		return ret;
 733	}
 734
 735	while (size) {
 736		u32 count = ranges[--size];
 737		u32 start = ranges[--size];
 738
 739		if (start >= gc->ngpio || start + count > gc->ngpio)
 740			continue;
 741
 742		bitmap_clear(gc->gpiodev->valid_mask, start, count);
 743	}
 744
 745	kfree(ranges);
 746	return 0;
 747}
 748
 749static int gpiochip_init_valid_mask(struct gpio_chip *gc)
 750{
 751	int ret;
 752
 753	if (!(gpiochip_count_reserved_ranges(gc) || gc->init_valid_mask))
 754		return 0;
 755
 756	gc->gpiodev->valid_mask = gpiochip_allocate_mask(gc);
 757	if (!gc->gpiodev->valid_mask)
 758		return -ENOMEM;
 759
 760	ret = gpiochip_apply_reserved_ranges(gc);
 761	if (ret)
 762		return ret;
 763
 764	if (gc->init_valid_mask)
 765		return gc->init_valid_mask(gc,
 766					   gc->gpiodev->valid_mask,
 767					   gc->ngpio);
 768
 769	return 0;
 770}
 771
 772static void gpiochip_free_valid_mask(struct gpio_chip *gc)
 773{
 774	gpiochip_free_mask(&gc->gpiodev->valid_mask);
 775}
 776
 777static int gpiochip_add_pin_ranges(struct gpio_chip *gc)
 778{
 779	/*
 780	 * Device Tree platforms are supposed to use "gpio-ranges"
 781	 * property. This check ensures that the ->add_pin_ranges()
 782	 * won't be called for them.
 783	 */
 784	if (device_property_present(&gc->gpiodev->dev, "gpio-ranges"))
 785		return 0;
 786
 787	if (gc->add_pin_ranges)
 788		return gc->add_pin_ranges(gc);
 789
 790	return 0;
 791}
 792
 793/**
 794 * gpiochip_query_valid_mask - return the GPIO validity information
 795 * @gc:	gpio chip which validity information is queried
 796 *
 797 * Returns: bitmap representing valid GPIOs or NULL if all GPIOs are valid
 798 *
 799 * Some GPIO chips may support configurations where some of the pins aren't
 800 * available. These chips can have valid_mask set to represent the valid
 801 * GPIOs. This function can be used to retrieve this information.
 802 */
 803const unsigned long *gpiochip_query_valid_mask(const struct gpio_chip *gc)
 804{
 805	return gc->gpiodev->valid_mask;
 806}
 807EXPORT_SYMBOL_GPL(gpiochip_query_valid_mask);
 808
 809bool gpiochip_line_is_valid(const struct gpio_chip *gc,
 810				unsigned int offset)
 811{
 812	/*
 813	 * hog pins are requested before registering GPIO chip
 814	 */
 815	if (!gc->gpiodev)
 816		return true;
 817
 818	/* No mask means all valid */
 819	if (likely(!gc->gpiodev->valid_mask))
 820		return true;
 821	return test_bit(offset, gc->gpiodev->valid_mask);
 822}
 823EXPORT_SYMBOL_GPL(gpiochip_line_is_valid);
 824
 825static void gpiod_free_irqs(struct gpio_desc *desc)
 826{
 827	int irq = gpiod_to_irq(desc);
 828	struct irq_desc *irqd = irq_to_desc(irq);
 829	void *cookie;
 830
 831	for (;;) {
 832		/*
 833		 * Make sure the action doesn't go away while we're
 834		 * dereferencing it. Retrieve and store the cookie value.
 835		 * If the irq is freed after we release the lock, that's
 836		 * alright - the underlying maple tree lookup will return NULL
 837		 * and nothing will happen in free_irq().
 838		 */
 839		scoped_guard(mutex, &irqd->request_mutex) {
 840			if (!irq_desc_has_action(irqd))
 841				return;
 842
 843			cookie = irqd->action->dev_id;
 844		}
 845
 846		free_irq(irq, cookie);
 847	}
 848}
 849
 850/*
 851 * The chip is going away but there may be users who had requested interrupts
 852 * on its GPIO lines who have no idea about its removal and have no way of
 853 * being notified about it. We need to free any interrupts still in use here or
 854 * we'll leak memory and resources (like procfs files).
 855 */
 856static void gpiochip_free_remaining_irqs(struct gpio_chip *gc)
 857{
 858	struct gpio_desc *desc;
 859
 860	for_each_gpio_desc_with_flag(gc, desc, GPIOD_FLAG_USED_AS_IRQ)
 861		gpiod_free_irqs(desc);
 862}
 863
 864static void gpiodev_release(struct device *dev)
 865{
 866	struct gpio_device *gdev = to_gpio_device(dev);
 867
 868	/* Call pending kfree()s for descriptor labels. */
 869	synchronize_srcu(&gdev->desc_srcu);
 870	cleanup_srcu_struct(&gdev->desc_srcu);
 871
 872	ida_free(&gpio_ida, gdev->id);
 873	kfree_const(gdev->label);
 874	kfree(gdev->descs);
 875	cleanup_srcu_struct(&gdev->srcu);
 876	kfree(gdev);
 877}
 878
 879static const struct device_type gpio_dev_type = {
 880	.name = "gpio_chip",
 881	.release = gpiodev_release,
 882};
 883
 884#ifdef CONFIG_GPIO_CDEV
 885#define gcdev_register(gdev, devt)	gpiolib_cdev_register((gdev), (devt))
 886#define gcdev_unregister(gdev)		gpiolib_cdev_unregister((gdev))
 887#else
 888/*
 889 * gpiolib_cdev_register() indirectly calls device_add(), which is still
 890 * required even when cdev is not selected.
 891 */
 892#define gcdev_register(gdev, devt)	device_add(&(gdev)->dev)
 893#define gcdev_unregister(gdev)		device_del(&(gdev)->dev)
 894#endif
 895
 896/*
 897 * An initial reference count has been held in gpiochip_add_data_with_key().
 898 * The caller should drop the reference via gpio_device_put() on errors.
 899 */
 900static int gpiochip_setup_dev(struct gpio_device *gdev)
 901{
 902	struct fwnode_handle *fwnode = dev_fwnode(&gdev->dev);
 903	int ret;
 904
 905	/*
 906	 * If fwnode doesn't belong to another device, it's safe to clear its
 907	 * initialized flag.
 908	 */
 909	if (fwnode && !fwnode->dev)
 910		fwnode_dev_initialized(fwnode, false);
 911
 912	ret = gcdev_register(gdev, gpio_devt);
 913	if (ret)
 914		return ret;
 915
 916	ret = gpiochip_sysfs_register(gdev);
 917	if (ret)
 918		goto err_remove_device;
 919
 920	dev_dbg(&gdev->dev, "registered GPIOs %u to %u on %s\n", gdev->base,
 921		gdev->base + gdev->ngpio - 1, gdev->label);
 922
 923	return 0;
 924
 925err_remove_device:
 926	gcdev_unregister(gdev);
 927	return ret;
 928}
 929
 930static void gpiochip_machine_hog(struct gpio_chip *gc, struct gpiod_hog *hog)
 931{
 932	struct gpio_desc *desc;
 933	int rv;
 934
 935	desc = gpiochip_get_desc(gc, hog->chip_hwnum);
 936	if (IS_ERR(desc)) {
 937		gpiochip_err(gc, "%s: unable to get GPIO desc: %ld\n",
 938			     __func__, PTR_ERR(desc));
 939		return;
 940	}
 941
 942	rv = gpiod_hog(desc, hog->line_name, hog->lflags, hog->dflags);
 943	if (rv)
 944		gpiod_err(desc, "%s: unable to hog GPIO line (%s:%u): %d\n",
 945			  __func__, gc->label, hog->chip_hwnum, rv);
 946}
 947
 948static void machine_gpiochip_add(struct gpio_chip *gc)
 949{
 950	struct gpiod_hog *hog;
 951
 952	guard(mutex)(&gpio_machine_hogs_mutex);
 953
 954	list_for_each_entry(hog, &gpio_machine_hogs, list) {
 955		if (!strcmp(gc->label, hog->chip_label))
 956			gpiochip_machine_hog(gc, hog);
 957	}
 958}
 959
 960static void gpiochip_setup_devs(void)
 961{
 962	struct gpio_device *gdev;
 963	int ret;
 964
 965	guard(srcu)(&gpio_devices_srcu);
 966
 967	list_for_each_entry_srcu(gdev, &gpio_devices, list,
 968				 srcu_read_lock_held(&gpio_devices_srcu)) {
 969		ret = gpiochip_setup_dev(gdev);
 970		if (ret) {
 971			gpio_device_put(gdev);
 972			dev_err(&gdev->dev,
 973				"Failed to initialize gpio device (%d)\n", ret);
 974		}
 975	}
 976}
 977
 978static void gpiochip_set_data(struct gpio_chip *gc, void *data)
 979{
 980	gc->gpiodev->data = data;
 981}
 982
 983/**
 984 * gpiochip_get_data() - get per-subdriver data for the chip
 985 * @gc: GPIO chip
 986 *
 987 * Returns:
 988 * The per-subdriver data for the chip.
 989 */
 990void *gpiochip_get_data(struct gpio_chip *gc)
 991{
 992	return gc->gpiodev->data;
 993}
 994EXPORT_SYMBOL_GPL(gpiochip_get_data);
 995
 996/*
 997 * If the calling driver provides the specific firmware node,
 998 * use it. Otherwise use the one from the parent device, if any.
 999 */
1000static struct fwnode_handle *gpiochip_choose_fwnode(struct gpio_chip *gc)
1001{
1002	if (gc->fwnode)
1003		return gc->fwnode;
1004
1005	if (gc->parent)
1006		return dev_fwnode(gc->parent);
1007
1008	return NULL;
1009}
1010
1011int gpiochip_get_ngpios(struct gpio_chip *gc, struct device *dev)
1012{
1013	struct fwnode_handle *fwnode = gpiochip_choose_fwnode(gc);
1014	u32 ngpios = gc->ngpio;
1015	int ret;
1016
1017	if (ngpios == 0) {
1018		ret = fwnode_property_read_u32(fwnode, "ngpios", &ngpios);
1019		if (ret == -ENODATA)
1020			/*
1021			 * -ENODATA means that there is no property found and
1022			 * we want to issue the error message to the user.
1023			 * Besides that, we want to return different error code
1024			 * to state that supplied value is not valid.
1025			 */
1026			ngpios = 0;
1027		else if (ret)
1028			return ret;
1029
1030		gc->ngpio = ngpios;
1031	}
1032
1033	if (gc->ngpio == 0) {
1034		dev_err(dev, "tried to insert a GPIO chip with zero lines\n");
1035		return -EINVAL;
1036	}
1037
1038	if (gc->ngpio > FASTPATH_NGPIO)
1039		dev_warn(dev, "line cnt %u is greater than fast path cnt %u\n",
1040			 gc->ngpio, FASTPATH_NGPIO);
1041
1042	return 0;
1043}
1044EXPORT_SYMBOL_GPL(gpiochip_get_ngpios);
1045
1046int gpiochip_add_data_with_key(struct gpio_chip *gc, void *data,
1047			       struct lock_class_key *lock_key,
1048			       struct lock_class_key *request_key)
1049{
1050	struct gpio_device *gdev;
1051	unsigned int desc_index;
1052	int base = 0;
1053	int ret;
1054
1055	gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1056	if (!gdev)
1057		return -ENOMEM;
1058	gc->gpiodev = gdev;
1059	gpiochip_set_data(gc, data);
1060
1061	ret = ida_alloc(&gpio_ida, GFP_KERNEL);
1062	if (ret < 0)
1063		goto err_free_gdev;
1064	gdev->id = ret;
1065
1066	ret = init_srcu_struct(&gdev->srcu);
1067	if (ret)
1068		goto err_free_ida;
1069	rcu_assign_pointer(gdev->chip, gc);
1070
1071	ret = init_srcu_struct(&gdev->desc_srcu);
1072	if (ret)
1073		goto err_cleanup_gdev_srcu;
1074
1075	ret = dev_set_name(&gdev->dev, GPIOCHIP_NAME "%d", gdev->id);
1076	if (ret)
1077		goto err_cleanup_desc_srcu;
1078
1079	device_initialize(&gdev->dev);
1080	/*
1081	 * After this point any allocated resources to `gdev` will be
1082	 * free():ed by gpiodev_release().  If you add new resources
1083	 * then make sure they get free():ed there.
1084	 */
1085	gdev->dev.type = &gpio_dev_type;
1086	gdev->dev.bus = &gpio_bus_type;
1087	gdev->dev.parent = gc->parent;
1088	device_set_node(&gdev->dev, gpiochip_choose_fwnode(gc));
1089
1090	ret = gpiochip_get_ngpios(gc, &gdev->dev);
1091	if (ret)
1092		goto err_put_device;
1093	gdev->ngpio = gc->ngpio;
1094
1095	gdev->descs = kcalloc(gc->ngpio, sizeof(*gdev->descs), GFP_KERNEL);
1096	if (!gdev->descs) {
1097		ret = -ENOMEM;
1098		goto err_put_device;
1099	}
1100
1101	gdev->label = kstrdup_const(gc->label ?: "unknown", GFP_KERNEL);
1102	if (!gdev->label) {
1103		ret = -ENOMEM;
1104		goto err_put_device;
1105	}
1106
1107	gdev->can_sleep = gc->can_sleep;
1108	rwlock_init(&gdev->line_state_lock);
1109	RAW_INIT_NOTIFIER_HEAD(&gdev->line_state_notifier);
1110	BLOCKING_INIT_NOTIFIER_HEAD(&gdev->device_notifier);
1111#ifdef CONFIG_PINCTRL
1112	INIT_LIST_HEAD(&gdev->pin_ranges);
1113#endif
1114	if (gc->parent && gc->parent->driver)
1115		gdev->owner = gc->parent->driver->owner;
1116	else if (gc->owner)
1117		/* TODO: remove chip->owner */
1118		gdev->owner = gc->owner;
1119	else
1120		gdev->owner = THIS_MODULE;
1121
1122	scoped_guard(mutex, &gpio_devices_lock) {
1123		/*
1124		 * TODO: this allocates a Linux GPIO number base in the global
1125		 * GPIO numberspace for this chip. In the long run we want to
1126		 * get *rid* of this numberspace and use only descriptors, but
1127		 * it may be a pipe dream. It will not happen before we get rid
1128		 * of the sysfs interface anyways.
1129		 */
1130		base = gc->base;
1131		if (base < 0) {
1132			base = gpiochip_find_base_unlocked(gc->ngpio);
1133			if (base < 0) {
1134				ret = base;
1135				base = 0;
1136				goto err_put_device;
1137			}
1138
1139			/*
1140			 * TODO: it should not be necessary to reflect the
1141			 * assigned base outside of the GPIO subsystem. Go over
1142			 * drivers and see if anyone makes use of this, else
1143			 * drop this and assign a poison instead.
1144			 */
1145			gc->base = base;
1146		} else {
1147			dev_warn(&gdev->dev,
1148				 "Static allocation of GPIO base is deprecated, use dynamic allocation.\n");
1149		}
1150
1151		gdev->base = base;
1152
1153		ret = gpiodev_add_to_list_unlocked(gdev);
1154		if (ret) {
1155			gpiochip_err(gc, "GPIO integer space overlap, cannot add chip\n");
1156			goto err_put_device;
1157		}
1158	}
1159
1160	if (gc->names)
1161		gpiochip_set_desc_names(gc);
1162
1163	ret = gpiochip_set_names(gc);
1164	if (ret)
1165		goto err_remove_from_list;
1166
1167	ret = gpiochip_init_valid_mask(gc);
1168	if (ret)
1169		goto err_remove_from_list;
1170
1171	for (desc_index = 0; desc_index < gc->ngpio; desc_index++) {
1172		struct gpio_desc *desc = &gdev->descs[desc_index];
1173
1174		desc->gdev = gdev;
1175
1176		/*
1177		 * We would typically want to use gpiochip_get_direction() here
1178		 * but we must not check the return value and bail-out as pin
1179		 * controllers can have pins configured to alternate functions
1180		 * and return -EINVAL. Also: there's no need to take the SRCU
1181		 * lock here.
1182		 */
1183		if (gc->get_direction && gpiochip_line_is_valid(gc, desc_index))
1184			assign_bit(GPIOD_FLAG_IS_OUT, &desc->flags,
1185				   !gc->get_direction(gc, desc_index));
1186		else
1187			assign_bit(GPIOD_FLAG_IS_OUT,
1188				   &desc->flags, !gc->direction_input);
1189	}
1190
1191	ret = of_gpiochip_add(gc);
1192	if (ret)
1193		goto err_free_valid_mask;
1194
1195	ret = gpiochip_add_pin_ranges(gc);
1196	if (ret)
1197		goto err_remove_of_chip;
1198
1199	acpi_gpiochip_add(gc);
1200
1201	machine_gpiochip_add(gc);
1202
1203	ret = gpiochip_irqchip_init_valid_mask(gc);
1204	if (ret)
1205		goto err_free_hogs;
1206
1207	ret = gpiochip_irqchip_init_hw(gc);
1208	if (ret)
1209		goto err_remove_irqchip_mask;
1210
1211	ret = gpiochip_add_irqchip(gc, lock_key, request_key);
1212	if (ret)
1213		goto err_remove_irqchip_mask;
1214
1215	ret = gpiochip_setup_shared(gc);
1216	if (ret)
1217		goto err_remove_irqchip;
1218
1219	/*
1220	 * By first adding the chardev, and then adding the device,
1221	 * we get a device node entry in sysfs under
1222	 * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1223	 * coldplug of device nodes and other udev business.
1224	 * We can do this only if gpiolib has been initialized.
1225	 * Otherwise, defer until later.
1226	 */
1227	if (gpiolib_initialized) {
1228		ret = gpiochip_setup_dev(gdev);
1229		if (ret)
1230			goto err_teardown_shared;
1231	}
1232
1233	return 0;
1234
1235err_teardown_shared:
1236	gpio_device_teardown_shared(gdev);
1237err_remove_irqchip:
1238	gpiochip_irqchip_remove(gc);
1239err_remove_irqchip_mask:
1240	gpiochip_irqchip_free_valid_mask(gc);
1241err_free_hogs:
1242	gpiochip_free_hogs(gc);
1243	acpi_gpiochip_remove(gc);
1244	gpiochip_remove_pin_ranges(gc);
1245err_remove_of_chip:
1246	of_gpiochip_remove(gc);
1247err_free_valid_mask:
1248	gpiochip_free_valid_mask(gc);
1249err_remove_from_list:
1250	scoped_guard(mutex, &gpio_devices_lock)
1251		list_del_rcu(&gdev->list);
1252	synchronize_srcu(&gpio_devices_srcu);
1253err_put_device:
1254	gpio_device_put(gdev);
1255	goto err_print_message;
1256
1257err_cleanup_desc_srcu:
1258	cleanup_srcu_struct(&gdev->desc_srcu);
1259err_cleanup_gdev_srcu:
1260	cleanup_srcu_struct(&gdev->srcu);
1261err_free_ida:
1262	ida_free(&gpio_ida, gdev->id);
1263err_free_gdev:
1264	kfree(gdev);
1265
1266err_print_message:
1267	/* failures here can mean systems won't boot... */
1268	if (ret != -EPROBE_DEFER) {
1269		pr_err("%s: GPIOs %d..%d (%s) failed to register, %d\n", __func__,
1270		       base, base + (int)gc->ngpio - 1,
1271		       gc->label ? : "generic", ret);
1272	}
1273	return ret;
1274}
1275EXPORT_SYMBOL_GPL(gpiochip_add_data_with_key);
1276
1277/**
1278 * gpiochip_remove() - unregister a gpio_chip
1279 * @gc: the chip to unregister
1280 *
1281 * A gpio_chip with any GPIOs still requested may not be removed.
1282 */
1283void gpiochip_remove(struct gpio_chip *gc)
1284{
1285	struct gpio_device *gdev = gc->gpiodev;
1286
1287	/* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1288	gpiochip_sysfs_unregister(gdev);
1289	gpiochip_free_hogs(gc);
1290	gpiochip_free_remaining_irqs(gc);
1291
1292	scoped_guard(mutex, &gpio_devices_lock)
1293		list_del_rcu(&gdev->list);
1294	synchronize_srcu(&gpio_devices_srcu);
1295
1296	/* Numb the device, cancelling all outstanding operations */
1297	rcu_assign_pointer(gdev->chip, NULL);
1298	synchronize_srcu(&gdev->srcu);
1299	gpio_device_teardown_shared(gdev);
1300	gpiochip_irqchip_remove(gc);
1301	acpi_gpiochip_remove(gc);
1302	of_gpiochip_remove(gc);
1303	gpiochip_remove_pin_ranges(gc);
1304	gpiochip_free_valid_mask(gc);
1305	/*
1306	 * We accept no more calls into the driver from this point, so
1307	 * NULL the driver data pointer.
1308	 */
1309	gpiochip_set_data(gc, NULL);
1310
1311	/*
1312	 * The gpiochip side puts its use of the device to rest here:
1313	 * if there are no userspace clients, the chardev and device will
1314	 * be removed, else it will be dangling until the last user is
1315	 * gone.
1316	 */
1317	gcdev_unregister(gdev);
1318	gpio_device_put(gdev);
1319}
1320EXPORT_SYMBOL_GPL(gpiochip_remove);
1321
1322/**
1323 * gpio_device_find() - find a specific GPIO device
1324 * @data: data to pass to match function
1325 * @match: Callback function to check gpio_chip
1326 *
1327 * Returns:
1328 * New reference to struct gpio_device.
1329 *
1330 * Similar to bus_find_device(). It returns a reference to a gpio_device as
1331 * determined by a user supplied @match callback. The callback should return
1332 * 0 if the device doesn't match and non-zero if it does. If the callback
1333 * returns non-zero, this function will return to the caller and not iterate
1334 * over any more gpio_devices.
1335 *
1336 * The callback takes the GPIO chip structure as argument. During the execution
1337 * of the callback function the chip is protected from being freed. TODO: This
1338 * actually has yet to be implemented.
1339 *
1340 * If the function returns non-NULL, the returned reference must be freed by
1341 * the caller using gpio_device_put().
1342 */
1343struct gpio_device *gpio_device_find(const void *data,
1344				     int (*match)(struct gpio_chip *gc,
1345						  const void *data))
1346{
1347	struct gpio_device *gdev;
1348	struct gpio_chip *gc;
1349
1350	might_sleep();
1351
1352	guard(srcu)(&gpio_devices_srcu);
1353
1354	list_for_each_entry_srcu(gdev, &gpio_devices, list,
1355				 srcu_read_lock_held(&gpio_devices_srcu)) {
1356		if (!device_is_registered(&gdev->dev))
1357			continue;
1358
1359		guard(srcu)(&gdev->srcu);
1360
1361		gc = srcu_dereference(gdev->chip, &gdev->srcu);
1362
1363		if (gc && match(gc, data))
1364			return gpio_device_get(gdev);
1365	}
1366
1367	return NULL;
1368}
1369EXPORT_SYMBOL_GPL(gpio_device_find);
1370
1371static int gpio_chip_match_by_label(struct gpio_chip *gc, const void *label)
1372{
1373	return gc->label && !strcmp(gc->label, label);
1374}
1375
1376/**
1377 * gpio_device_find_by_label() - wrapper around gpio_device_find() finding the
1378 *                               GPIO device by its backing chip's label
1379 * @label: Label to lookup
1380 *
1381 * Returns:
1382 * Reference to the GPIO device or NULL. Reference must be released with
1383 * gpio_device_put().
1384 */
1385struct gpio_device *gpio_device_find_by_label(const char *label)
1386{
1387	return gpio_device_find((void *)label, gpio_chip_match_by_label);
1388}
1389EXPORT_SYMBOL_GPL(gpio_device_find_by_label);
1390
1391static int gpio_chip_match_by_fwnode(struct gpio_chip *gc, const void *fwnode)
1392{
1393	return device_match_fwnode(&gc->gpiodev->dev, fwnode);
1394}
1395
1396/**
1397 * gpio_device_find_by_fwnode() - wrapper around gpio_device_find() finding
1398 *                                the GPIO device by its fwnode
1399 * @fwnode: Firmware node to lookup
1400 *
1401 * Returns:
1402 * Reference to the GPIO device or NULL. Reference must be released with
1403 * gpio_device_put().
1404 */
1405struct gpio_device *gpio_device_find_by_fwnode(const struct fwnode_handle *fwnode)
1406{
1407	return gpio_device_find((void *)fwnode, gpio_chip_match_by_fwnode);
1408}
1409EXPORT_SYMBOL_GPL(gpio_device_find_by_fwnode);
1410
1411/**
1412 * gpio_device_get() - Increase the reference count of this GPIO device
1413 * @gdev: GPIO device to increase the refcount for
1414 *
1415 * Returns:
1416 * Pointer to @gdev.
1417 */
1418struct gpio_device *gpio_device_get(struct gpio_device *gdev)
1419{
1420	return to_gpio_device(get_device(&gdev->dev));
1421}
1422EXPORT_SYMBOL_GPL(gpio_device_get);
1423
1424/**
1425 * gpio_device_put() - Decrease the reference count of this GPIO device and
1426 *                     possibly free all resources associated with it.
1427 * @gdev: GPIO device to decrease the reference count for
1428 */
1429void gpio_device_put(struct gpio_device *gdev)
1430{
1431	put_device(&gdev->dev);
1432}
1433EXPORT_SYMBOL_GPL(gpio_device_put);
1434
1435/**
1436 * gpio_device_to_device() - Retrieve the address of the underlying struct
1437 *                           device.
1438 * @gdev: GPIO device for which to return the address.
1439 *
1440 * This does not increase the reference count of the GPIO device nor the
1441 * underlying struct device.
1442 *
1443 * Returns:
1444 * Address of struct device backing this GPIO device.
1445 */
1446struct device *gpio_device_to_device(struct gpio_device *gdev)
1447{
1448	return &gdev->dev;
1449}
1450EXPORT_SYMBOL_GPL(gpio_device_to_device);
1451
1452#ifdef CONFIG_GPIOLIB_IRQCHIP
1453
1454/*
1455 * The following is irqchip helper code for gpiochips.
1456 */
1457
1458static int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
1459{
1460	struct gpio_irq_chip *girq = &gc->irq;
1461
1462	if (!girq->init_hw)
1463		return 0;
1464
1465	return girq->init_hw(gc);
1466}
1467
1468static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
1469{
1470	struct gpio_irq_chip *girq = &gc->irq;
1471
1472	if (!girq->init_valid_mask)
1473		return 0;
1474
1475	girq->valid_mask = gpiochip_allocate_mask(gc);
1476	if (!girq->valid_mask)
1477		return -ENOMEM;
1478
1479	girq->init_valid_mask(gc, girq->valid_mask, gc->ngpio);
1480
1481	return 0;
1482}
1483
1484static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc)
1485{
1486	gpiochip_free_mask(&gc->irq.valid_mask);
1487}
1488
1489static bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gc,
1490				       unsigned int offset)
1491{
1492	if (!gpiochip_line_is_valid(gc, offset))
1493		return false;
1494	/* No mask means all valid */
1495	if (likely(!gc->irq.valid_mask))
1496		return true;
1497	return test_bit(offset, gc->irq.valid_mask);
1498}
1499
1500#ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
1501
1502/**
1503 * gpiochip_set_hierarchical_irqchip() - connects a hierarchical irqchip
1504 * to a gpiochip
1505 * @gc: the gpiochip to set the irqchip hierarchical handler to
1506 * @irqchip: the irqchip to handle this level of the hierarchy, the interrupt
1507 * will then percolate up to the parent
1508 */
1509static void gpiochip_set_hierarchical_irqchip(struct gpio_chip *gc,
1510					      struct irq_chip *irqchip)
1511{
1512	/* DT will deal with mapping each IRQ as we go along */
1513	if (is_of_node(gc->irq.fwnode))
1514		return;
1515
1516	/*
1517	 * This is for legacy and boardfile "irqchip" fwnodes: allocate
1518	 * irqs upfront instead of dynamically since we don't have the
1519	 * dynamic type of allocation that hardware description languages
1520	 * provide. Once all GPIO drivers using board files are gone from
1521	 * the kernel we can delete this code, but for a transitional period
1522	 * it is necessary to keep this around.
1523	 */
1524	if (is_fwnode_irqchip(gc->irq.fwnode)) {
1525		int i;
1526		int ret;
1527
1528		for (i = 0; i < gc->ngpio; i++) {
1529			struct irq_fwspec fwspec;
1530			unsigned int parent_hwirq;
1531			unsigned int parent_type;
1532			struct gpio_irq_chip *girq = &gc->irq;
1533
1534			/*
1535			 * We call the child to parent translation function
1536			 * only to check if the child IRQ is valid or not.
1537			 * Just pick the rising edge type here as that is what
1538			 * we likely need to support.
1539			 */
1540			ret = girq->child_to_parent_hwirq(gc, i,
1541							  IRQ_TYPE_EDGE_RISING,
1542							  &parent_hwirq,
1543							  &parent_type);
1544			if (ret) {
1545				gpiochip_err(gc, "skip set-up on hwirq %d\n", i);
1546				continue;
1547			}
1548
1549			fwspec.fwnode = gc->irq.fwnode;
1550			/* This is the hwirq for the GPIO line side of things */
1551			fwspec.param[0] = girq->child_offset_to_irq(gc, i);
1552			/* Just pick something */
1553			fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
1554			fwspec.param_count = 2;
1555			ret = irq_domain_alloc_irqs(gc->irq.domain, 1,
1556						    NUMA_NO_NODE, &fwspec);
1557			if (ret < 0) {
1558				gpiochip_err(gc,
1559					     "can not allocate irq for GPIO line %d parent hwirq %d in hierarchy domain: %d\n",
1560					     i, parent_hwirq, ret);
1561			}
1562		}
1563	}
1564
1565	gpiochip_err(gc, "%s unknown fwnode type proceed anyway\n", __func__);
1566
1567	return;
1568}
1569
1570static int gpiochip_hierarchy_irq_domain_translate(struct irq_domain *d,
1571						   struct irq_fwspec *fwspec,
1572						   unsigned long *hwirq,
1573						   unsigned int *type)
1574{
1575	/* We support standard DT translation */
1576	if (is_of_node(fwspec->fwnode))
1577		return irq_domain_translate_twothreecell(d, fwspec, hwirq, type);
1578
1579	/* This is for board files and others not using DT */
1580	if (is_fwnode_irqchip(fwspec->fwnode)) {
1581		int ret;
1582
1583		ret = irq_domain_translate_twocell(d, fwspec, hwirq, type);
1584		if (ret)
1585			return ret;
1586		WARN_ON(*type == IRQ_TYPE_NONE);
1587		return 0;
1588	}
1589	return -EINVAL;
1590}
1591
1592static int gpiochip_hierarchy_irq_domain_alloc(struct irq_domain *d,
1593					       unsigned int irq,
1594					       unsigned int nr_irqs,
1595					       void *data)
1596{
1597	struct gpio_chip *gc = d->host_data;
1598	irq_hw_number_t hwirq;
1599	unsigned int type = IRQ_TYPE_NONE;
1600	struct irq_fwspec *fwspec = data;
1601	union gpio_irq_fwspec gpio_parent_fwspec = {};
1602	unsigned int parent_hwirq;
1603	unsigned int parent_type;
1604	struct gpio_irq_chip *girq = &gc->irq;
1605	int ret;
1606
1607	/*
1608	 * The nr_irqs parameter is always one except for PCI multi-MSI
1609	 * so this should not happen.
1610	 */
1611	WARN_ON(nr_irqs != 1);
1612
1613	ret = gc->irq.child_irq_domain_ops.translate(d, fwspec, &hwirq, &type);
1614	if (ret)
1615		return ret;
1616
1617	gpiochip_dbg(gc, "allocate IRQ %d, hwirq %lu\n", irq, hwirq);
1618
1619	ret = girq->child_to_parent_hwirq(gc, hwirq, type,
1620					  &parent_hwirq, &parent_type);
1621	if (ret) {
1622		gpiochip_err(gc, "can't look up hwirq %lu\n", hwirq);
1623		return ret;
1624	}
1625	gpiochip_dbg(gc, "found parent hwirq %u\n", parent_hwirq);
1626
1627	/*
1628	 * We set handle_bad_irq because the .set_type() should
1629	 * always be invoked and set the right type of handler.
1630	 */
1631	irq_domain_set_info(d,
1632			    irq,
1633			    hwirq,
1634			    gc->irq.chip,
1635			    gc,
1636			    girq->handler,
1637			    NULL, NULL);
1638	irq_set_probe(irq);
1639
1640	/* This parent only handles asserted level IRQs */
1641	ret = girq->populate_parent_alloc_arg(gc, &gpio_parent_fwspec,
1642					      parent_hwirq, parent_type);
1643	if (ret)
1644		return ret;
1645
1646	gpiochip_dbg(gc, "alloc_irqs_parent for %d parent hwirq %d\n",
1647		     irq, parent_hwirq);
1648	irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
1649	ret = irq_domain_alloc_irqs_parent(d, irq, 1, &gpio_parent_fwspec);
1650	/*
1651	 * If the parent irqdomain is msi, the interrupts have already
1652	 * been allocated, so the EEXIST is good.
1653	 */
1654	if (irq_domain_is_msi(d->parent) && (ret == -EEXIST))
1655		ret = 0;
1656	if (ret)
1657		gpiochip_err(gc,
1658			     "failed to allocate parent hwirq %d for hwirq %lu\n",
1659			     parent_hwirq, hwirq);
1660
1661	return ret;
1662}
1663
1664static unsigned int gpiochip_child_offset_to_irq_noop(struct gpio_chip *gc,
1665						      unsigned int offset)
1666{
1667	return offset;
1668}
1669
1670/**
1671 * gpiochip_irq_domain_activate() - Lock a GPIO to be used as an IRQ
1672 * @domain: The IRQ domain used by this IRQ chip
1673 * @data: Outermost irq_data associated with the IRQ
1674 * @reserve: If set, only reserve an interrupt vector instead of assigning one
1675 *
1676 * This function is a wrapper that calls gpiochip_lock_as_irq() and is to be
1677 * used as the activate function for the &struct irq_domain_ops. The host_data
1678 * for the IRQ domain must be the &struct gpio_chip.
1679 *
1680 * Returns:
1681 * 0 on success, or negative errno on failure.
1682 */
1683static int gpiochip_irq_domain_activate(struct irq_domain *domain,
1684					struct irq_data *data, bool reserve)
1685{
1686	struct gpio_chip *gc = domain->host_data;
1687	unsigned int hwirq = irqd_to_hwirq(data);
1688
1689	return gpiochip_lock_as_irq(gc, hwirq);
1690}
1691
1692/**
1693 * gpiochip_irq_domain_deactivate() - Unlock a GPIO used as an IRQ
1694 * @domain: The IRQ domain used by this IRQ chip
1695 * @data: Outermost irq_data associated with the IRQ
1696 *
1697 * This function is a wrapper that will call gpiochip_unlock_as_irq() and is to
1698 * be used as the deactivate function for the &struct irq_domain_ops. The
1699 * host_data for the IRQ domain must be the &struct gpio_chip.
1700 */
1701static void gpiochip_irq_domain_deactivate(struct irq_domain *domain,
1702					   struct irq_data *data)
1703{
1704	struct gpio_chip *gc = domain->host_data;
1705	unsigned int hwirq = irqd_to_hwirq(data);
1706
1707	return gpiochip_unlock_as_irq(gc, hwirq);
1708}
1709
1710static void gpiochip_hierarchy_setup_domain_ops(struct irq_domain_ops *ops)
1711{
1712	ops->activate = gpiochip_irq_domain_activate;
1713	ops->deactivate = gpiochip_irq_domain_deactivate;
1714	ops->alloc = gpiochip_hierarchy_irq_domain_alloc;
1715
1716	/*
1717	 * We only allow overriding the translate() and free() functions for
1718	 * hierarchical chips, and this should only be done if the user
1719	 * really need something other than 1:1 translation for translate()
1720	 * callback and free if user wants to free up any resources which
1721	 * were allocated during callbacks, for example populate_parent_alloc_arg.
1722	 */
1723	if (!ops->translate)
1724		ops->translate = gpiochip_hierarchy_irq_domain_translate;
1725	if (!ops->free)
1726		ops->free = irq_domain_free_irqs_common;
1727}
1728
1729static struct irq_domain *gpiochip_hierarchy_create_domain(struct gpio_chip *gc)
1730{
1731	struct irq_domain *domain;
1732
1733	if (!gc->irq.child_to_parent_hwirq ||
1734	    !gc->irq.fwnode) {
1735		gpiochip_err(gc, "missing irqdomain vital data\n");
1736		return ERR_PTR(-EINVAL);
1737	}
1738
1739	if (!gc->irq.child_offset_to_irq)
1740		gc->irq.child_offset_to_irq = gpiochip_child_offset_to_irq_noop;
1741
1742	if (!gc->irq.populate_parent_alloc_arg)
1743		gc->irq.populate_parent_alloc_arg =
1744			gpiochip_populate_parent_fwspec_twocell;
1745
1746	gpiochip_hierarchy_setup_domain_ops(&gc->irq.child_irq_domain_ops);
1747
1748	domain = irq_domain_create_hierarchy(
1749		gc->irq.parent_domain,
1750		0,
1751		gc->ngpio,
1752		gc->irq.fwnode,
1753		&gc->irq.child_irq_domain_ops,
1754		gc);
1755
1756	if (!domain)
1757		return ERR_PTR(-ENOMEM);
1758
1759	gpiochip_set_hierarchical_irqchip(gc, gc->irq.chip);
1760
1761	return domain;
1762}
1763
1764static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
1765{
1766	return !!gc->irq.parent_domain;
1767}
1768
1769int gpiochip_populate_parent_fwspec_twocell(struct gpio_chip *gc,
1770					    union gpio_irq_fwspec *gfwspec,
1771					    unsigned int parent_hwirq,
1772					    unsigned int parent_type)
1773{
1774	struct irq_fwspec *fwspec = &gfwspec->fwspec;
1775
1776	fwspec->fwnode = gc->irq.parent_domain->fwnode;
1777	fwspec->param_count = 2;
1778	fwspec->param[0] = parent_hwirq;
1779	fwspec->param[1] = parent_type;
1780
1781	return 0;
1782}
1783EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_twocell);
1784
1785int gpiochip_populate_parent_fwspec_fourcell(struct gpio_chip *gc,
1786					     union gpio_irq_fwspec *gfwspec,
1787					     unsigned int parent_hwirq,
1788					     unsigned int parent_type)
1789{
1790	struct irq_fwspec *fwspec = &gfwspec->fwspec;
1791
1792	fwspec->fwnode = gc->irq.parent_domain->fwnode;
1793	fwspec->param_count = 4;
1794	fwspec->param[0] = 0;
1795	fwspec->param[1] = parent_hwirq;
1796	fwspec->param[2] = 0;
1797	fwspec->param[3] = parent_type;
1798
1799	return 0;
1800}
1801EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_fourcell);
1802
1803#else
1804
1805static struct irq_domain *gpiochip_hierarchy_create_domain(struct gpio_chip *gc)
1806{
1807	return ERR_PTR(-EINVAL);
1808}
1809
1810static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
1811{
1812	return false;
1813}
1814
1815#endif /* CONFIG_IRQ_DOMAIN_HIERARCHY */
1816
1817/**
1818 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
1819 * @d: the irqdomain used by this irqchip
1820 * @irq: the global irq number used by this GPIO irqchip irq
1821 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
1822 *
1823 * This function will set up the mapping for a certain IRQ line on a
1824 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
1825 * stored inside the gpiochip.
1826 *
1827 * Returns:
1828 * 0 on success, or negative errno on failure.
1829 */
1830static int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
1831			    irq_hw_number_t hwirq)
1832{
1833	struct gpio_chip *gc = d->host_data;
1834	int ret = 0;
1835
1836	if (!gpiochip_irqchip_irq_valid(gc, hwirq))
1837		return -ENXIO;
1838
1839	irq_set_chip_data(irq, gc);
1840	/*
1841	 * This lock class tells lockdep that GPIO irqs are in a different
1842	 * category than their parents, so it won't report false recursion.
1843	 */
1844	irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
1845	irq_set_chip_and_handler(irq, gc->irq.chip, gc->irq.handler);
1846	/* Chips that use nested thread handlers have them marked */
1847	if (gc->irq.threaded)
1848		irq_set_nested_thread(irq, 1);
1849	irq_set_noprobe(irq);
1850
1851	if (gc->irq.num_parents == 1)
1852		ret = irq_set_parent(irq, gc->irq.parents[0]);
1853	else if (gc->irq.map)
1854		ret = irq_set_parent(irq, gc->irq.map[hwirq]);
1855
1856	if (ret < 0)
1857		return ret;
1858
1859	/*
1860	 * No set-up of the hardware will happen if IRQ_TYPE_NONE
1861	 * is passed as default type.
1862	 */
1863	if (gc->irq.default_type != IRQ_TYPE_NONE)
1864		irq_set_irq_type(irq, gc->irq.default_type);
1865
1866	return 0;
1867}
1868
1869static void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
1870{
1871	struct gpio_chip *gc = d->host_data;
1872
1873	if (gc->irq.threaded)
1874		irq_set_nested_thread(irq, 0);
1875	irq_set_chip_and_handler(irq, NULL, NULL);
1876	irq_set_chip_data(irq, NULL);
1877}
1878
1879static int gpiochip_irq_select(struct irq_domain *d, struct irq_fwspec *fwspec,
1880			       enum irq_domain_bus_token bus_token)
1881{
1882	struct fwnode_handle *fwnode = fwspec->fwnode;
1883	struct gpio_chip *gc = d->host_data;
1884	unsigned int index = fwspec->param[0];
1885
1886	if (fwspec->param_count == 3 && is_of_node(fwnode))
1887		return of_gpiochip_instance_match(gc, index);
1888
1889	/* Fallback for twocells */
1890	return (fwnode && (d->fwnode == fwnode) && (d->bus_token == bus_token));
1891}
1892
1893static const struct irq_domain_ops gpiochip_domain_ops = {
1894	.map	= gpiochip_irq_map,
1895	.unmap	= gpiochip_irq_unmap,
1896	.select	= gpiochip_irq_select,
1897	/* Virtually all GPIO irqchips are twocell:ed */
1898	.xlate	= irq_domain_xlate_twothreecell,
1899};
1900
1901static struct irq_domain *gpiochip_simple_create_domain(struct gpio_chip *gc)
1902{
1903	struct fwnode_handle *fwnode = dev_fwnode(&gc->gpiodev->dev);
1904	struct irq_domain *domain;
1905
1906	domain = irq_domain_create_simple(fwnode, gc->ngpio, gc->irq.first,
1907					  &gpiochip_domain_ops, gc);
1908	if (!domain)
1909		return ERR_PTR(-EINVAL);
1910
1911	return domain;
1912}
1913
1914static int gpiochip_to_irq(struct gpio_chip *gc, unsigned int offset)
1915{
1916	struct irq_domain *domain = gc->irq.domain;
1917
1918	/*
1919	 * Avoid race condition with other code, which tries to lookup
1920	 * an IRQ before the irqchip has been properly registered,
1921	 * i.e. while gpiochip is still being brought up.
1922	 */
1923	if (!gc->irq.initialized)
1924		return -EPROBE_DEFER;
1925
1926	if (!gpiochip_irqchip_irq_valid(gc, offset))
1927		return -ENXIO;
1928
1929#ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
1930	if (irq_domain_is_hierarchy(domain)) {
1931		struct irq_fwspec spec;
1932
1933		spec.fwnode = domain->fwnode;
1934		spec.param_count = 2;
1935		spec.param[0] = gc->irq.child_offset_to_irq(gc, offset);
1936		spec.param[1] = IRQ_TYPE_NONE;
1937
1938		return irq_create_fwspec_mapping(&spec);
1939	}
1940#endif
1941
1942	return irq_create_mapping(domain, offset);
1943}
1944
1945int gpiochip_irq_reqres(struct irq_data *d)
1946{
1947	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1948	unsigned int hwirq = irqd_to_hwirq(d);
1949
1950	return gpiochip_reqres_irq(gc, hwirq);
1951}
1952EXPORT_SYMBOL(gpiochip_irq_reqres);
1953
1954void gpiochip_irq_relres(struct irq_data *d)
1955{
1956	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1957	unsigned int hwirq = irqd_to_hwirq(d);
1958
1959	gpiochip_relres_irq(gc, hwirq);
1960}
1961EXPORT_SYMBOL(gpiochip_irq_relres);
1962
1963static void gpiochip_irq_mask(struct irq_data *d)
1964{
1965	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1966	unsigned int hwirq = irqd_to_hwirq(d);
1967
1968	if (gc->irq.irq_mask)
1969		gc->irq.irq_mask(d);
1970	gpiochip_disable_irq(gc, hwirq);
1971}
1972
1973static void gpiochip_irq_unmask(struct irq_data *d)
1974{
1975	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1976	unsigned int hwirq = irqd_to_hwirq(d);
1977
1978	gpiochip_enable_irq(gc, hwirq);
1979	if (gc->irq.irq_unmask)
1980		gc->irq.irq_unmask(d);
1981}
1982
1983static void gpiochip_irq_enable(struct irq_data *d)
1984{
1985	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1986	unsigned int hwirq = irqd_to_hwirq(d);
1987
1988	gpiochip_enable_irq(gc, hwirq);
1989	gc->irq.irq_enable(d);
1990}
1991
1992static void gpiochip_irq_disable(struct irq_data *d)
1993{
1994	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1995	unsigned int hwirq = irqd_to_hwirq(d);
1996
1997	gc->irq.irq_disable(d);
1998	gpiochip_disable_irq(gc, hwirq);
1999}
2000
2001static void gpiochip_set_irq_hooks(struct gpio_chip *gc)
2002{
2003	struct irq_chip *irqchip = gc->irq.chip;
2004
2005	if (irqchip->flags & IRQCHIP_IMMUTABLE)
2006		return;
2007
2008	gpiochip_warn(gc, "not an immutable chip, please consider fixing it!\n");
2009
2010	if (!irqchip->irq_request_resources &&
2011	    !irqchip->irq_release_resources) {
2012		irqchip->irq_request_resources = gpiochip_irq_reqres;
2013		irqchip->irq_release_resources = gpiochip_irq_relres;
2014	}
2015	if (WARN_ON(gc->irq.irq_enable))
2016		return;
2017	/* Check if the irqchip already has this hook... */
2018	if (irqchip->irq_enable == gpiochip_irq_enable ||
2019		irqchip->irq_mask == gpiochip_irq_mask) {
2020		/*
2021		 * ...and if so, give a gentle warning that this is bad
2022		 * practice.
2023		 */
2024		gpiochip_info(gc,
2025			      "detected irqchip that is shared with multiple gpiochips: please fix the driver.\n");
2026		return;
2027	}
2028
2029	if (irqchip->irq_disable) {
2030		gc->irq.irq_disable = irqchip->irq_disable;
2031		irqchip->irq_disable = gpiochip_irq_disable;
2032	} else {
2033		gc->irq.irq_mask = irqchip->irq_mask;
2034		irqchip->irq_mask = gpiochip_irq_mask;
2035	}
2036
2037	if (irqchip->irq_enable) {
2038		gc->irq.irq_enable = irqchip->irq_enable;
2039		irqchip->irq_enable = gpiochip_irq_enable;
2040	} else {
2041		gc->irq.irq_unmask = irqchip->irq_unmask;
2042		irqchip->irq_unmask = gpiochip_irq_unmask;
2043	}
2044}
2045
2046static int gpiochip_irqchip_add_allocated_domain(struct gpio_chip *gc,
2047						 struct irq_domain *domain,
2048						 bool allocated_externally)
2049{
2050	if (!domain)
2051		return -EINVAL;
2052
2053	if (gc->to_irq)
2054		gpiochip_warn(gc, "to_irq is redefined in %s and you shouldn't rely on it\n",
2055			      __func__);
2056
2057	gc->to_irq = gpiochip_to_irq;
2058	gc->irq.domain = domain;
2059	gc->irq.domain_is_allocated_externally = allocated_externally;
2060
2061	/*
2062	 * Using barrier() here to prevent compiler from reordering
2063	 * gc->irq.initialized before adding irqdomain.
2064	 */
2065	barrier();
2066
2067	gc->irq.initialized = true;
2068
2069	return 0;
2070}
2071
2072/**
2073 * gpiochip_add_irqchip() - adds an IRQ chip to a GPIO chip
2074 * @gc: the GPIO chip to add the IRQ chip to
2075 * @lock_key: lockdep class for IRQ lock
2076 * @request_key: lockdep class for IRQ request
2077 *
2078 * Returns:
2079 * 0 on success, or a negative errno on failure.
2080 */
2081static int gpiochip_add_irqchip(struct gpio_chip *gc,
2082				struct lock_class_key *lock_key,
2083				struct lock_class_key *request_key)
2084{
2085	struct fwnode_handle *fwnode = dev_fwnode(&gc->gpiodev->dev);
2086	struct irq_chip *irqchip = gc->irq.chip;
2087	struct irq_domain *domain;
2088	unsigned int type;
2089	unsigned int i;
2090	int ret;
2091
2092	if (!irqchip)
2093		return 0;
2094
2095	if (gc->irq.parent_handler && gc->can_sleep) {
2096		gpiochip_err(gc, "you cannot have chained interrupts on a chip that may sleep\n");
2097		return -EINVAL;
2098	}
2099
2100	type = gc->irq.default_type;
2101
2102	/*
2103	 * Specifying a default trigger is a terrible idea if DT or ACPI is
2104	 * used to configure the interrupts, as you may end up with
2105	 * conflicting triggers. Tell the user, and reset to NONE.
2106	 */
2107	if (WARN(fwnode && type != IRQ_TYPE_NONE,
2108		 "%pfw: Ignoring %u default trigger\n", fwnode, type))
2109		type = IRQ_TYPE_NONE;
2110
2111	gc->irq.default_type = type;
2112	gc->irq.lock_key = lock_key;
2113	gc->irq.request_key = request_key;
2114
2115	/* If a parent irqdomain is provided, let's build a hierarchy */
2116	if (gpiochip_hierarchy_is_hierarchical(gc)) {
2117		domain = gpiochip_hierarchy_create_domain(gc);
2118	} else {
2119		domain = gpiochip_simple_create_domain(gc);
2120	}
2121	if (IS_ERR(domain))
2122		return PTR_ERR(domain);
2123
2124	if (gc->irq.parent_handler) {
2125		for (i = 0; i < gc->irq.num_parents; i++) {
2126			void *data;
2127
2128			if (gc->irq.per_parent_data)
2129				data = gc->irq.parent_handler_data_array[i];
2130			else
2131				data = gc->irq.parent_handler_data ?: gc;
2132
2133			/*
2134			 * The parent IRQ chip is already using the chip_data
2135			 * for this IRQ chip, so our callbacks simply use the
2136			 * handler_data.
2137			 */
2138			irq_set_chained_handler_and_data(gc->irq.parents[i],
2139							 gc->irq.parent_handler,
2140							 data);
2141		}
2142	}
2143
2144	gpiochip_set_irq_hooks(gc);
2145
2146	ret = gpiochip_irqchip_add_allocated_domain(gc, domain, false);
2147	if (ret)
2148		return ret;
2149
2150	acpi_gpiochip_request_interrupts(gc);
2151
2152	return 0;
2153}
2154
2155/**
2156 * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
2157 * @gc: the gpiochip to remove the irqchip from
2158 *
2159 * This is called only from gpiochip_remove()
2160 */
2161static void gpiochip_irqchip_remove(struct gpio_chip *gc)
2162{
2163	struct irq_chip *irqchip = gc->irq.chip;
2164	unsigned int offset;
2165
2166	acpi_gpiochip_free_interrupts(gc);
2167
2168	if (irqchip && gc->irq.parent_handler) {
2169		struct gpio_irq_chip *irq = &gc->irq;
2170		unsigned int i;
2171
2172		for (i = 0; i < irq->num_parents; i++)
2173			irq_set_chained_handler_and_data(irq->parents[i],
2174							 NULL, NULL);
2175	}
2176
2177	/* Remove all IRQ mappings and delete the domain */
2178	if (!gc->irq.domain_is_allocated_externally && gc->irq.domain) {
2179		unsigned int irq;
2180
2181		for (offset = 0; offset < gc->ngpio; offset++) {
2182			if (!gpiochip_irqchip_irq_valid(gc, offset))
2183				continue;
2184
2185			irq = irq_find_mapping(gc->irq.domain, offset);
2186			irq_dispose_mapping(irq);
2187		}
2188
2189		irq_domain_remove(gc->irq.domain);
2190	}
2191
2192	if (irqchip && !(irqchip->flags & IRQCHIP_IMMUTABLE)) {
2193		if (irqchip->irq_request_resources == gpiochip_irq_reqres) {
2194			irqchip->irq_request_resources = NULL;
2195			irqchip->irq_release_resources = NULL;
2196		}
2197		if (irqchip->irq_enable == gpiochip_irq_enable) {
2198			irqchip->irq_enable = gc->irq.irq_enable;
2199			irqchip->irq_disable = gc->irq.irq_disable;
2200		}
2201	}
2202	gc->irq.irq_enable = NULL;
2203	gc->irq.irq_disable = NULL;
2204	gc->irq.chip = NULL;
2205
2206	gpiochip_irqchip_free_valid_mask(gc);
2207}
2208
2209/**
2210 * gpiochip_irqchip_add_domain() - adds an irqdomain to a gpiochip
2211 * @gc: the gpiochip to add the irqchip to
2212 * @domain: the irqdomain to add to the gpiochip
2213 *
2214 * This function adds an IRQ domain to the gpiochip.
2215 *
2216 * Returns:
2217 * 0 on success, or negative errno on failure.
2218 */
2219int gpiochip_irqchip_add_domain(struct gpio_chip *gc,
2220				struct irq_domain *domain)
2221{
2222	return gpiochip_irqchip_add_allocated_domain(gc, domain, true);
2223}
2224EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_domain);
2225
2226#else /* CONFIG_GPIOLIB_IRQCHIP */
2227
2228static inline int gpiochip_add_irqchip(struct gpio_chip *gc,
2229				       struct lock_class_key *lock_key,
2230				       struct lock_class_key *request_key)
2231{
2232	return 0;
2233}
2234static void gpiochip_irqchip_remove(struct gpio_chip *gc) {}
2235
2236static inline int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
2237{
2238	return 0;
2239}
2240
2241static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
2242{
2243	return 0;
2244}
2245static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc)
2246{ }
2247
2248#endif /* CONFIG_GPIOLIB_IRQCHIP */
2249
2250/**
2251 * gpiochip_generic_request() - request the gpio function for a pin
2252 * @gc: the gpiochip owning the GPIO
2253 * @offset: the offset of the GPIO to request for GPIO function
2254 *
2255 * Returns:
2256 * 0 on success, or negative errno on failure.
2257 */
2258int gpiochip_generic_request(struct gpio_chip *gc, unsigned int offset)
2259{
2260#ifdef CONFIG_PINCTRL
2261	if (list_empty(&gc->gpiodev->pin_ranges))
2262		return 0;
2263#endif
2264
2265	return pinctrl_gpio_request(gc, offset);
2266}
2267EXPORT_SYMBOL_GPL(gpiochip_generic_request);
2268
2269/**
2270 * gpiochip_generic_free() - free the gpio function from a pin
2271 * @gc: the gpiochip to request the gpio function for
2272 * @offset: the offset of the GPIO to free from GPIO function
2273 */
2274void gpiochip_generic_free(struct gpio_chip *gc, unsigned int offset)
2275{
2276#ifdef CONFIG_PINCTRL
2277	if (list_empty(&gc->gpiodev->pin_ranges))
2278		return;
2279#endif
2280
2281	pinctrl_gpio_free(gc, offset);
2282}
2283EXPORT_SYMBOL_GPL(gpiochip_generic_free);
2284
2285/**
2286 * gpiochip_generic_config() - apply configuration for a pin
2287 * @gc: the gpiochip owning the GPIO
2288 * @offset: the offset of the GPIO to apply the configuration
2289 * @config: the configuration to be applied
2290 *
2291 * Returns:
2292 * 0 on success, or negative errno on failure.
2293 */
2294int gpiochip_generic_config(struct gpio_chip *gc, unsigned int offset,
2295			    unsigned long config)
2296{
2297#ifdef CONFIG_PINCTRL
2298	if (list_empty(&gc->gpiodev->pin_ranges))
2299		return -ENOTSUPP;
2300#endif
2301
2302	return pinctrl_gpio_set_config(gc, offset, config);
2303}
2304EXPORT_SYMBOL_GPL(gpiochip_generic_config);
2305
2306#ifdef CONFIG_PINCTRL
2307
2308/**
2309 * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
2310 * @gc: the gpiochip to add the range for
2311 * @pctldev: the pin controller to map to
2312 * @gpio_offset: the start offset in the current gpio_chip number space
2313 * @pin_group: name of the pin group inside the pin controller
2314 *
2315 * Calling this function directly from a DeviceTree-supported
2316 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2317 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2318 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2319 *
2320 * Returns:
2321 * 0 on success, or negative errno on failure.
2322 */
2323int gpiochip_add_pingroup_range(struct gpio_chip *gc,
2324			struct pinctrl_dev *pctldev,
2325			unsigned int gpio_offset, const char *pin_group)
2326{
2327	struct gpio_pin_range *pin_range;
2328	struct gpio_device *gdev = gc->gpiodev;
2329	int ret;
2330
2331	pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2332	if (!pin_range)
2333		return -ENOMEM;
2334
2335	/* Use local offset as range ID */
2336	pin_range->range.id = gpio_offset;
2337	pin_range->range.gc = gc;
2338	pin_range->range.name = gc->label;
2339	pin_range->range.base = gdev->base + gpio_offset;
2340	pin_range->pctldev = pctldev;
2341
2342	ret = pinctrl_get_group_pins(pctldev, pin_group,
2343					&pin_range->range.pins,
2344					&pin_range->range.npins);
2345	if (ret < 0) {
2346		kfree(pin_range);
2347		return ret;
2348	}
2349
2350	pinctrl_add_gpio_range(pctldev, &pin_range->range);
2351
2352	gpiochip_dbg(gc, "created GPIO range %d->%d ==> %s PINGRP %s\n",
2353		 gpio_offset, gpio_offset + pin_range->range.npins - 1,
2354		 pinctrl_dev_get_devname(pctldev), pin_group);
2355
2356	list_add_tail(&pin_range->node, &gdev->pin_ranges);
2357
2358	return 0;
2359}
2360EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
2361
2362/**
2363 * gpiochip_add_pin_range_with_pins() - add a range for GPIO <-> pin mapping
2364 * @gc: the gpiochip to add the range for
2365 * @pinctl_name: the dev_name() of the pin controller to map to
2366 * @gpio_offset: the start offset in the current gpio_chip number space
2367 * @pin_offset: the start offset in the pin controller number space
2368 * @pins: the list of non consecutive pins to accumulate in this range (if not
2369 *	NULL, pin_offset is ignored by pinctrl core)
2370 * @npins: the number of pins from the offset of each pin space (GPIO and
2371 *	pin controller) to accumulate in this range
2372 *
2373 * Calling this function directly from a DeviceTree-supported
2374 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2375 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2376 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2377 *
2378 * Returns:
2379 * 0 on success, or a negative errno on failure.
2380 */
2381int gpiochip_add_pin_range_with_pins(struct gpio_chip *gc,
2382				     const char *pinctl_name,
2383				     unsigned int gpio_offset,
2384				     unsigned int pin_offset,
2385				     unsigned int const *pins,
2386				     unsigned int npins)
2387{
2388	struct gpio_pin_range *pin_range;
2389	struct gpio_device *gdev = gc->gpiodev;
2390	int ret;
2391
2392	pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2393	if (!pin_range)
2394		return -ENOMEM;
2395
2396	/* Use local offset as range ID */
2397	pin_range->range.id = gpio_offset;
2398	pin_range->range.gc = gc;
2399	pin_range->range.name = gc->label;
2400	pin_range->range.base = gdev->base + gpio_offset;
2401	pin_range->range.pin_base = pin_offset;
2402	pin_range->range.pins = pins;
2403	pin_range->range.npins = npins;
2404	pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
2405			&pin_range->range);
2406	if (IS_ERR(pin_range->pctldev)) {
2407		ret = PTR_ERR(pin_range->pctldev);
2408		gpiochip_err(gc, "could not create pin range\n");
2409		kfree(pin_range);
2410		return ret;
2411	}
2412	if (pin_range->range.pins)
2413		gpiochip_dbg(gc, "created GPIO range %d->%d ==> %s %d sparse PIN range { %d, ... }",
2414			     gpio_offset, gpio_offset + npins - 1,
2415			     pinctl_name, npins, pins[0]);
2416	else
2417		gpiochip_dbg(gc, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
2418			     gpio_offset, gpio_offset + npins - 1, pinctl_name,
2419			     pin_offset, pin_offset + npins - 1);
2420
2421	list_add_tail(&pin_range->node, &gdev->pin_ranges);
2422
2423	return 0;
2424}
2425EXPORT_SYMBOL_GPL(gpiochip_add_pin_range_with_pins);
2426
2427/**
2428 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2429 * @gc: the chip to remove all the mappings for
2430 */
2431void gpiochip_remove_pin_ranges(struct gpio_chip *gc)
2432{
2433	struct gpio_pin_range *pin_range, *tmp;
2434	struct gpio_device *gdev = gc->gpiodev;
2435
2436	list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2437		list_del(&pin_range->node);
2438		pinctrl_remove_gpio_range(pin_range->pctldev,
2439				&pin_range->range);
2440		kfree(pin_range);
2441	}
2442}
2443EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
2444
2445#endif /* CONFIG_PINCTRL */
2446
2447/* These "optional" allocation calls help prevent drivers from stomping
2448 * on each other, and help provide better diagnostics in debugfs.
2449 * They're called even less than the "set direction" calls.
2450 */
2451int gpiod_request_commit(struct gpio_desc *desc, const char *label)
2452{
2453	unsigned int offset;
2454	int ret;
2455
2456	CLASS(gpio_chip_guard, guard)(desc);
2457	if (!guard.gc)
2458		return -ENODEV;
2459
2460	if (test_and_set_bit(GPIOD_FLAG_REQUESTED, &desc->flags))
2461		return -EBUSY;
2462
2463	offset = gpiod_hwgpio(desc);
2464	if (!gpiochip_line_is_valid(guard.gc, offset)) {
2465		ret = -EINVAL;
2466		goto out_clear_bit;
2467	}
2468
2469	/* NOTE:  gpio_request() can be called in early boot,
2470	 * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
2471	 */
2472
2473	if (guard.gc->request) {
2474		ret = guard.gc->request(guard.gc, offset);
2475		if (ret > 0)
2476			ret = -EBADE;
2477		if (ret)
2478			goto out_clear_bit;
2479	}
2480
2481	if (guard.gc->get_direction)
2482		gpiod_get_direction(desc);
2483
2484	ret = desc_set_label(desc, label ? : "?");
2485	if (ret)
2486		goto out_clear_bit;
2487
2488	return 0;
2489
2490out_clear_bit:
2491	clear_bit(GPIOD_FLAG_REQUESTED, &desc->flags);
2492	return ret;
2493}
2494
2495int gpiod_request(struct gpio_desc *desc, const char *label)
2496{
2497	int ret = -EPROBE_DEFER;
2498
2499	VALIDATE_DESC(desc);
2500
2501	if (try_module_get(desc->gdev->owner)) {
2502		ret = gpiod_request_commit(desc, label);
2503		if (ret)
2504			module_put(desc->gdev->owner);
2505		else
2506			gpio_device_get(desc->gdev);
2507	}
2508
2509	if (ret)
2510		gpiod_dbg(desc, "%s: status %d\n", __func__, ret);
2511
2512	return ret;
2513}
2514
2515void gpiod_free_commit(struct gpio_desc *desc)
2516{
2517	unsigned long flags;
2518
2519	might_sleep();
2520
2521	CLASS(gpio_chip_guard, guard)(desc);
2522
2523	flags = READ_ONCE(desc->flags);
2524
2525	if (guard.gc && test_bit(GPIOD_FLAG_REQUESTED, &flags)) {
2526		if (guard.gc->free)
2527			guard.gc->free(guard.gc, gpiod_hwgpio(desc));
2528
2529		clear_bit(GPIOD_FLAG_ACTIVE_LOW, &flags);
2530		clear_bit(GPIOD_FLAG_REQUESTED, &flags);
2531		clear_bit(GPIOD_FLAG_OPEN_DRAIN, &flags);
2532		clear_bit(GPIOD_FLAG_OPEN_SOURCE, &flags);
2533		clear_bit(GPIOD_FLAG_PULL_UP, &flags);
2534		clear_bit(GPIOD_FLAG_PULL_DOWN, &flags);
2535		clear_bit(GPIOD_FLAG_BIAS_DISABLE, &flags);
2536		clear_bit(GPIOD_FLAG_EDGE_RISING, &flags);
2537		clear_bit(GPIOD_FLAG_EDGE_FALLING, &flags);
2538		clear_bit(GPIOD_FLAG_IS_HOGGED, &flags);
2539#ifdef CONFIG_OF_DYNAMIC
2540		WRITE_ONCE(desc->hog, NULL);
2541#endif
2542		desc_set_label(desc, NULL);
2543		WRITE_ONCE(desc->flags, flags);
2544#ifdef CONFIG_GPIO_CDEV
2545		WRITE_ONCE(desc->debounce_period_us, 0);
2546#endif
2547		gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_RELEASED);
2548	}
2549}
2550
2551void gpiod_free(struct gpio_desc *desc)
2552{
2553	VALIDATE_DESC_VOID(desc);
2554
2555	gpiod_free_commit(desc);
2556	module_put(desc->gdev->owner);
2557	gpio_device_put(desc->gdev);
2558}
2559
2560/**
2561 * gpiochip_dup_line_label - Get a copy of the consumer label.
2562 * @gc: GPIO chip controlling this line.
2563 * @offset: Hardware offset of the line.
2564 *
2565 * Returns:
2566 * Pointer to a copy of the consumer label if the line is requested or NULL
2567 * if it's not. If a valid pointer was returned, it must be freed using
2568 * kfree(). In case of a memory allocation error, the function returns %ENOMEM.
2569 *
2570 * Must not be called from atomic context.
2571 */
2572char *gpiochip_dup_line_label(struct gpio_chip *gc, unsigned int offset)
2573{
2574	struct gpio_desc *desc;
2575	char *label;
2576
2577	desc = gpiochip_get_desc(gc, offset);
2578	if (IS_ERR(desc))
2579		return NULL;
2580
2581	if (!test_bit(GPIOD_FLAG_REQUESTED, &desc->flags))
2582		return NULL;
2583
2584	guard(srcu)(&desc->gdev->desc_srcu);
2585
2586	label = kstrdup(gpiod_get_label(desc), GFP_KERNEL);
2587	if (!label)
2588		return ERR_PTR(-ENOMEM);
2589
2590	return label;
2591}
2592EXPORT_SYMBOL_GPL(gpiochip_dup_line_label);
2593
2594static inline const char *function_name_or_default(const char *con_id)
2595{
2596	return con_id ?: "(default)";
2597}
2598
2599/**
2600 * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
2601 * @gc: GPIO chip
2602 * @hwnum: hardware number of the GPIO for which to request the descriptor
2603 * @label: label for the GPIO
2604 * @lflags: lookup flags for this GPIO or 0 if default, this can be used to
2605 * specify things like line inversion semantics with the machine flags
2606 * such as GPIO_OUT_LOW
2607 * @dflags: descriptor request flags for this GPIO or 0 if default, this
2608 * can be used to specify consumer semantics such as open drain
2609 *
2610 * Function allows GPIO chip drivers to request and use their own GPIO
2611 * descriptors via gpiolib API. Difference to gpiod_request() is that this
2612 * function will not increase reference count of the GPIO chip module. This
2613 * allows the GPIO chip module to be unloaded as needed (we assume that the
2614 * GPIO chip driver handles freeing the GPIOs it has requested).
2615 *
2616 * Returns:
2617 * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
2618 * code on failure.
2619 */
2620struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *gc,
2621					    unsigned int hwnum,
2622					    const char *label,
2623					    enum gpio_lookup_flags lflags,
2624					    enum gpiod_flags dflags)
2625{
2626	struct gpio_desc *desc = gpiochip_get_desc(gc, hwnum);
2627	const char *name = function_name_or_default(label);
2628	int ret;
2629
2630	if (IS_ERR(desc)) {
2631		gpiochip_err(gc, "failed to get GPIO %s descriptor\n", name);
2632		return desc;
2633	}
2634
2635	ret = gpiod_request_commit(desc, label);
2636	if (ret < 0)
2637		return ERR_PTR(ret);
2638
2639	ret = gpiod_configure_flags(desc, label, lflags, dflags);
2640	if (ret) {
2641		gpiod_free_commit(desc);
2642		gpiochip_err(gc, "setup of own GPIO %s failed\n", name);
2643		return ERR_PTR(ret);
2644	}
2645
2646	gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_REQUESTED);
2647
2648	return desc;
2649}
2650EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
2651
2652/**
2653 * gpiochip_free_own_desc - Free GPIO requested by the chip driver
2654 * @desc: GPIO descriptor to free
2655 *
2656 * Function frees the given GPIO requested previously with
2657 * gpiochip_request_own_desc().
2658 */
2659void gpiochip_free_own_desc(struct gpio_desc *desc)
2660{
2661	if (desc)
2662		gpiod_free_commit(desc);
2663}
2664EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
2665
2666/*
2667 * Drivers MUST set GPIO direction before making get/set calls.  In
2668 * some cases this is done in early boot, before IRQs are enabled.
2669 *
2670 * As a rule these aren't called more than once (except for drivers
2671 * using the open-drain emulation idiom) so these are natural places
2672 * to accumulate extra debugging checks.  Note that we can't (yet)
2673 * rely on gpio_request() having been called beforehand.
2674 */
2675
2676int gpio_do_set_config(struct gpio_desc *desc, unsigned long config)
2677{
2678	int ret;
2679
2680	CLASS(gpio_chip_guard, guard)(desc);
2681	if (!guard.gc)
2682		return -ENODEV;
2683
2684	if (!guard.gc->set_config)
2685		return -ENOTSUPP;
2686
2687	ret = guard.gc->set_config(guard.gc, gpiod_hwgpio(desc), config);
2688	if (ret > 0)
2689		ret = -EBADE;
2690
2691#ifdef CONFIG_GPIO_CDEV
2692	/*
2693	 * Special case - if we're setting debounce period, we need to store
2694	 * it in the descriptor in case user-space wants to know it.
2695	 */
2696	if (!ret && pinconf_to_config_param(config) == PIN_CONFIG_INPUT_DEBOUNCE)
2697		WRITE_ONCE(desc->debounce_period_us,
2698			   pinconf_to_config_argument(config));
2699#endif
2700	return ret;
2701}
2702
2703static int gpio_set_config_with_argument(struct gpio_desc *desc,
2704					 enum pin_config_param mode,
2705					 u32 argument)
2706{
2707	unsigned long config;
2708
2709	config = pinconf_to_config_packed(mode, argument);
2710	return gpio_do_set_config(desc, config);
2711}
2712
2713static int gpio_set_config_with_argument_optional(struct gpio_desc *desc,
2714						  enum pin_config_param mode,
2715						  u32 argument)
2716{
2717	struct device *dev = &desc->gdev->dev;
2718	int gpio = gpiod_hwgpio(desc);
2719	int ret;
2720
2721	ret = gpio_set_config_with_argument(desc, mode, argument);
2722	if (ret != -ENOTSUPP)
2723		return ret;
2724
2725	switch (mode) {
2726	case PIN_CONFIG_PERSIST_STATE:
2727		dev_dbg(dev, "Persistence not supported for GPIO %d\n", gpio);
2728		break;
2729	default:
2730		break;
2731	}
2732
2733	return 0;
2734}
2735
2736static int gpio_set_config(struct gpio_desc *desc, enum pin_config_param mode)
2737{
2738	return gpio_set_config_with_argument(desc, mode, 0);
2739}
2740
2741static int gpio_set_bias(struct gpio_desc *desc)
2742{
2743	enum pin_config_param bias;
2744	unsigned long flags;
2745	unsigned int arg;
2746
2747	flags = READ_ONCE(desc->flags);
2748
2749	if (test_bit(GPIOD_FLAG_BIAS_DISABLE, &flags))
2750		bias = PIN_CONFIG_BIAS_DISABLE;
2751	else if (test_bit(GPIOD_FLAG_PULL_UP, &flags))
2752		bias = PIN_CONFIG_BIAS_PULL_UP;
2753	else if (test_bit(GPIOD_FLAG_PULL_DOWN, &flags))
2754		bias = PIN_CONFIG_BIAS_PULL_DOWN;
2755	else
2756		return 0;
2757
2758	switch (bias) {
2759	case PIN_CONFIG_BIAS_PULL_DOWN:
2760	case PIN_CONFIG_BIAS_PULL_UP:
2761		arg = 1;
2762		break;
2763
2764	default:
2765		arg = 0;
2766		break;
2767	}
2768
2769	return gpio_set_config_with_argument_optional(desc, bias, arg);
2770}
2771
2772/**
2773 * gpio_set_debounce_timeout() - Set debounce timeout
2774 * @desc:	GPIO descriptor to set the debounce timeout
2775 * @debounce:	Debounce timeout in microseconds
2776 *
2777 * The function calls the certain GPIO driver to set debounce timeout
2778 * in the hardware.
2779 *
2780 * Returns:
2781 * 0 on success, or negative errno on failure.
2782 */
2783int gpio_set_debounce_timeout(struct gpio_desc *desc, unsigned int debounce)
2784{
2785	int ret;
2786
2787	ret = gpio_set_config_with_argument_optional(desc,
2788						     PIN_CONFIG_INPUT_DEBOUNCE,
2789						     debounce);
2790	if (!ret)
2791		gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
2792
2793	return ret;
2794}
2795
2796static int gpiochip_direction_input(struct gpio_chip *gc, unsigned int offset)
2797{
2798	int ret;
2799
2800	lockdep_assert_held(&gc->gpiodev->srcu);
2801
2802	if (WARN_ON(!gc->direction_input))
2803		return -EOPNOTSUPP;
2804
2805	ret = gc->direction_input(gc, offset);
2806	if (ret > 0)
2807		ret = -EBADE;
2808
2809	return ret;
2810}
2811
2812static int gpiochip_direction_output(struct gpio_chip *gc, unsigned int offset,
2813				     int value)
2814{
2815	int ret;
2816
2817	lockdep_assert_held(&gc->gpiodev->srcu);
2818
2819	if (WARN_ON(!gc->direction_output))
2820		return -EOPNOTSUPP;
2821
2822	ret = gc->direction_output(gc, offset, value);
2823	if (ret > 0)
2824		ret = -EBADE;
2825
2826	return ret;
2827}
2828
2829/**
2830 * gpiod_direction_input - set the GPIO direction to input
2831 * @desc:	GPIO to set to input
2832 *
2833 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
2834 * be called safely on it.
2835 *
2836 * Returns:
2837 * 0 on success, or negative errno on failure.
2838 */
2839int gpiod_direction_input(struct gpio_desc *desc)
2840{
2841	int ret;
2842
2843	VALIDATE_DESC(desc);
2844
2845	ret = gpiod_direction_input_nonotify(desc);
2846	if (ret == 0)
2847		gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
2848
2849	return ret;
2850}
2851EXPORT_SYMBOL_GPL(gpiod_direction_input);
2852
2853int gpiod_direction_input_nonotify(struct gpio_desc *desc)
2854{
2855	int ret = 0, dir;
2856
2857	CLASS(gpio_chip_guard, guard)(desc);
2858	if (!guard.gc)
2859		return -ENODEV;
2860
2861	/*
2862	 * It is legal to have no .get() and .direction_input() specified if
2863	 * the chip is output-only, but you can't specify .direction_input()
2864	 * and not support the .get() operation, that doesn't make sense.
2865	 */
2866	if (!guard.gc->get && guard.gc->direction_input) {
2867		gpiod_warn(desc,
2868			   "%s: missing get() but have direction_input()\n",
2869			   __func__);
2870		return -EIO;
2871	}
2872
2873	/*
2874	 * If we have a .direction_input() callback, things are simple,
2875	 * just call it. Else we are some input-only chip so try to check the
2876	 * direction (if .get_direction() is supported) else we silently
2877	 * assume we are in input mode after this.
2878	 */
2879	if (guard.gc->direction_input) {
2880		ret = gpiochip_direction_input(guard.gc,
2881					       gpiod_hwgpio(desc));
2882	} else if (guard.gc->get_direction) {
2883		dir = gpiochip_get_direction(guard.gc, gpiod_hwgpio(desc));
2884		if (dir < 0)
2885			return dir;
2886
2887		if (dir != GPIO_LINE_DIRECTION_IN) {
2888			gpiod_warn(desc,
2889				   "%s: missing direction_input() operation and line is output\n",
2890				    __func__);
2891			return -EIO;
2892		}
2893	}
2894	if (ret == 0) {
2895		clear_bit(GPIOD_FLAG_IS_OUT, &desc->flags);
2896		ret = gpio_set_bias(desc);
2897	}
2898
2899	trace_gpio_direction(desc_to_gpio(desc), 1, ret);
2900
2901	return ret;
2902}
2903
2904static int gpiochip_set(struct gpio_chip *gc, unsigned int offset, int value)
2905{
2906	int ret;
2907
2908	lockdep_assert_held(&gc->gpiodev->srcu);
2909
2910	if (WARN_ON(unlikely(!gc->set)))
2911		return -EOPNOTSUPP;
2912
2913	ret = gc->set(gc, offset, value);
2914	if (ret > 0)
2915		ret = -EBADE;
2916
2917	return ret;
2918}
2919
2920static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
2921{
2922	int val = !!value, ret = 0, dir;
2923
2924	CLASS(gpio_chip_guard, guard)(desc);
2925	if (!guard.gc)
2926		return -ENODEV;
2927
2928	/*
2929	 * It's OK not to specify .direction_output() if the gpiochip is
2930	 * output-only, but if there is then not even a .set() operation it
2931	 * is pretty tricky to drive the output line.
2932	 */
2933	if (!guard.gc->set && !guard.gc->direction_output) {
2934		gpiod_warn(desc,
2935			   "%s: missing set() and direction_output() operations\n",
2936			   __func__);
2937		return -EIO;
2938	}
2939
2940	if (guard.gc->direction_output) {
2941		ret = gpiochip_direction_output(guard.gc,
2942						gpiod_hwgpio(desc), val);
2943	} else {
2944		/* Check that we are in output mode if we can */
2945		if (guard.gc->get_direction) {
2946			dir = gpiochip_get_direction(guard.gc,
2947						     gpiod_hwgpio(desc));
2948			if (dir < 0)
2949				return dir;
2950
2951			if (dir != GPIO_LINE_DIRECTION_OUT) {
2952				gpiod_warn(desc,
2953					   "%s: missing direction_output() operation\n",
2954					   __func__);
2955				return -EIO;
2956			}
2957		}
2958		/*
2959		 * If we can't actively set the direction, we are some
2960		 * output-only chip, so just drive the output as desired.
2961		 */
2962		ret = gpiochip_set(guard.gc, gpiod_hwgpio(desc), val);
2963		if (ret)
2964			return ret;
2965	}
2966
2967	if (!ret)
2968		set_bit(GPIOD_FLAG_IS_OUT, &desc->flags);
2969	trace_gpio_value(desc_to_gpio(desc), 0, val);
2970	trace_gpio_direction(desc_to_gpio(desc), 0, ret);
2971	return ret;
2972}
2973
2974/**
2975 * gpiod_direction_output_raw - set the GPIO direction to output
2976 * @desc:	GPIO to set to output
2977 * @value:	initial output value of the GPIO
2978 *
2979 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2980 * be called safely on it. The initial value of the output must be specified
2981 * as raw value on the physical line without regard for the ACTIVE_LOW status.
2982 *
2983 * Returns:
2984 * 0 on success, or negative errno on failure.
2985 */
2986int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2987{
2988	int ret;
2989
2990	VALIDATE_DESC(desc);
2991
2992	ret = gpiod_direction_output_raw_commit(desc, value);
2993	if (ret == 0)
2994		gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
2995
2996	return ret;
2997}
2998EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
2999
3000/**
3001 * gpiod_direction_output - set the GPIO direction to output
3002 * @desc:	GPIO to set to output
3003 * @value:	initial output value of the GPIO
3004 *
3005 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
3006 * be called safely on it. The initial value of the output must be specified
3007 * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
3008 * account.
3009 *
3010 * Returns:
3011 * 0 on success, or negative errno on failure.
3012 */
3013int gpiod_direction_output(struct gpio_desc *desc, int value)
3014{
3015	int ret;
3016
3017	VALIDATE_DESC(desc);
3018
3019	ret = gpiod_direction_output_nonotify(desc, value);
3020	if (ret == 0)
3021		gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
3022
3023	return ret;
3024}
3025EXPORT_SYMBOL_GPL(gpiod_direction_output);
3026
3027int gpiod_direction_output_nonotify(struct gpio_desc *desc, int value)
3028{
3029	unsigned long flags;
3030	int ret;
3031
3032	flags = READ_ONCE(desc->flags);
3033
3034	if (test_bit(GPIOD_FLAG_ACTIVE_LOW, &flags))
3035		value = !value;
3036	else
3037		value = !!value;
3038
3039	/* GPIOs used for enabled IRQs shall not be set as output */
3040	if (test_bit(GPIOD_FLAG_USED_AS_IRQ, &flags) &&
3041	    test_bit(GPIOD_FLAG_IRQ_IS_ENABLED, &flags)) {
3042		gpiod_err(desc,
3043			  "%s: tried to set a GPIO tied to an IRQ as output\n",
3044			  __func__);
3045		return -EIO;
3046	}
3047
3048	if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &flags)) {
3049		/* First see if we can enable open drain in hardware */
3050		ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_DRAIN);
3051		if (!ret)
3052			goto set_output_value;
3053		/* Emulate open drain by not actively driving the line high */
3054		if (value)
3055			goto set_output_flag;
3056	} else if (test_bit(GPIOD_FLAG_OPEN_SOURCE, &flags)) {
3057		ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_SOURCE);
3058		if (!ret)
3059			goto set_output_value;
3060		/* Emulate open source by not actively driving the line low */
3061		if (!value)
3062			goto set_output_flag;
3063	} else {
3064		gpio_set_config(desc, PIN_CONFIG_DRIVE_PUSH_PULL);
3065	}
3066
3067set_output_value:
3068	ret = gpio_set_bias(desc);
3069	if (ret)
3070		return ret;
3071	return gpiod_direction_output_raw_commit(desc, value);
3072
3073set_output_flag:
3074	ret = gpiod_direction_input_nonotify(desc);
3075	if (ret)
3076		return ret;
3077	/*
3078	 * When emulating open-source or open-drain functionalities by not
3079	 * actively driving the line (setting mode to input) we still need to
3080	 * set the IS_OUT flag or otherwise we won't be able to set the line
3081	 * value anymore.
3082	 */
3083	set_bit(GPIOD_FLAG_IS_OUT, &desc->flags);
3084	return 0;
3085}
3086
3087#if IS_ENABLED(CONFIG_HTE)
3088/**
3089 * gpiod_enable_hw_timestamp_ns - Enable hardware timestamp in nanoseconds.
3090 *
3091 * @desc: GPIO to enable.
3092 * @flags: Flags related to GPIO edge.
3093 *
3094 * Returns:
3095 * 0 on success, or negative errno on failure.
3096 */
3097int gpiod_enable_hw_timestamp_ns(struct gpio_desc *desc, unsigned long flags)
3098{
3099	int ret;
3100
3101	VALIDATE_DESC(desc);
3102
3103	CLASS(gpio_chip_guard, guard)(desc);
3104	if (!guard.gc)
3105		return -ENODEV;
3106
3107	if (!guard.gc->en_hw_timestamp) {
3108		gpiod_warn(desc, "%s: hw ts not supported\n", __func__);
3109		return -ENOTSUPP;
3110	}
3111
3112	ret = guard.gc->en_hw_timestamp(guard.gc,
3113					gpiod_hwgpio(desc), flags);
3114	if (ret)
3115		gpiod_warn(desc, "%s: hw ts request failed\n", __func__);
3116
3117	return ret;
3118}
3119EXPORT_SYMBOL_GPL(gpiod_enable_hw_timestamp_ns);
3120
3121/**
3122 * gpiod_disable_hw_timestamp_ns - Disable hardware timestamp.
3123 *
3124 * @desc: GPIO to disable.
3125 * @flags: Flags related to GPIO edge, same value as used during enable call.
3126 *
3127 * Returns:
3128 * 0 on success, or negative errno on failure.
3129 */
3130int gpiod_disable_hw_timestamp_ns(struct gpio_desc *desc, unsigned long flags)
3131{
3132	int ret;
3133
3134	VALIDATE_DESC(desc);
3135
3136	CLASS(gpio_chip_guard, guard)(desc);
3137	if (!guard.gc)
3138		return -ENODEV;
3139
3140	if (!guard.gc->dis_hw_timestamp) {
3141		gpiod_warn(desc, "%s: hw ts not supported\n", __func__);
3142		return -ENOTSUPP;
3143	}
3144
3145	ret = guard.gc->dis_hw_timestamp(guard.gc, gpiod_hwgpio(desc),
3146					 flags);
3147	if (ret)
3148		gpiod_warn(desc, "%s: hw ts release failed\n", __func__);
3149
3150	return ret;
3151}
3152EXPORT_SYMBOL_GPL(gpiod_disable_hw_timestamp_ns);
3153#endif /* CONFIG_HTE */
3154
3155/**
3156 * gpiod_set_config - sets @config for a GPIO
3157 * @desc: descriptor of the GPIO for which to set the configuration
3158 * @config: Same packed config format as generic pinconf
3159 *
3160 * Returns:
3161 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3162 * configuration.
3163 */
3164int gpiod_set_config(struct gpio_desc *desc, unsigned long config)
3165{
3166	int ret;
3167
3168	VALIDATE_DESC(desc);
3169
3170	ret = gpio_do_set_config(desc, config);
3171	if (!ret) {
3172		/* These are the only options we notify the userspace about. */
3173		switch (pinconf_to_config_param(config)) {
3174		case PIN_CONFIG_BIAS_DISABLE:
3175		case PIN_CONFIG_BIAS_PULL_DOWN:
3176		case PIN_CONFIG_BIAS_PULL_UP:
3177		case PIN_CONFIG_DRIVE_OPEN_DRAIN:
3178		case PIN_CONFIG_DRIVE_OPEN_SOURCE:
3179		case PIN_CONFIG_DRIVE_PUSH_PULL:
3180		case PIN_CONFIG_INPUT_DEBOUNCE:
3181			gpiod_line_state_notify(desc,
3182						GPIO_V2_LINE_CHANGED_CONFIG);
3183			break;
3184		default:
3185			break;
3186		}
3187	}
3188
3189	return ret;
3190}
3191EXPORT_SYMBOL_GPL(gpiod_set_config);
3192
3193/**
3194 * gpiod_set_debounce - sets @debounce time for a GPIO
3195 * @desc: descriptor of the GPIO for which to set debounce time
3196 * @debounce: debounce time in microseconds
3197 *
3198 * Returns:
3199 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3200 * debounce time.
3201 */
3202int gpiod_set_debounce(struct gpio_desc *desc, unsigned int debounce)
3203{
3204	unsigned long config;
3205
3206	config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
3207	return gpiod_set_config(desc, config);
3208}
3209EXPORT_SYMBOL_GPL(gpiod_set_debounce);
3210
3211/**
3212 * gpiod_set_transitory - Lose or retain GPIO state on suspend or reset
3213 * @desc: descriptor of the GPIO for which to configure persistence
3214 * @transitory: True to lose state on suspend or reset, false for persistence
3215 *
3216 * Returns:
3217 * 0 on success, otherwise a negative error code.
3218 */
3219int gpiod_set_transitory(struct gpio_desc *desc, bool transitory)
3220{
3221	VALIDATE_DESC(desc);
3222	/*
3223	 * Handle GPIOD_FLAG_TRANSITORY first, enabling queries to gpiolib for
3224	 * persistence state.
3225	 */
3226	assign_bit(GPIOD_FLAG_TRANSITORY, &desc->flags, transitory);
3227
3228	/* If the driver supports it, set the persistence state now */
3229	return gpio_set_config_with_argument_optional(desc,
3230						      PIN_CONFIG_PERSIST_STATE,
3231						      !transitory);
3232}
3233
3234/**
3235 * gpiod_is_active_low - test whether a GPIO is active-low or not
3236 * @desc: the gpio descriptor to test
3237 *
3238 * Returns:
3239 * 1 if the GPIO is active-low, 0 otherwise.
3240 */
3241int gpiod_is_active_low(const struct gpio_desc *desc)
3242{
3243	VALIDATE_DESC(desc);
3244	return test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags);
3245}
3246EXPORT_SYMBOL_GPL(gpiod_is_active_low);
3247
3248/**
3249 * gpiod_toggle_active_low - toggle whether a GPIO is active-low or not
3250 * @desc: the gpio descriptor to change
3251 */
3252void gpiod_toggle_active_low(struct gpio_desc *desc)
3253{
3254	VALIDATE_DESC_VOID(desc);
3255	change_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags);
3256	gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
3257}
3258EXPORT_SYMBOL_GPL(gpiod_toggle_active_low);
3259
3260static int gpiochip_get(struct gpio_chip *gc, unsigned int offset)
3261{
3262	int ret;
3263
3264	lockdep_assert_held(&gc->gpiodev->srcu);
3265
3266	/* Make sure this is called after checking for gc->get(). */
3267	ret = gc->get(gc, offset);
3268	if (ret > 1) {
3269		gpiochip_warn(gc,
3270			"invalid return value from gc->get(): %d, consider fixing the driver\n",
3271			ret);
3272		ret = !!ret;
3273	}
3274
3275	return ret;
3276}
3277
3278static int gpio_chip_get_value(struct gpio_chip *gc, const struct gpio_desc *desc)
3279{
3280	return gc->get ? gpiochip_get(gc, gpiod_hwgpio(desc)) : -EIO;
3281}
3282
3283/* I/O calls are only valid after configuration completed; the relevant
3284 * "is this a valid GPIO" error checks should already have been done.
3285 *
3286 * "Get" operations are often inlinable as reading a pin value register,
3287 * and masking the relevant bit in that register.
3288 *
3289 * When "set" operations are inlinable, they involve writing that mask to
3290 * one register to set a low value, or a different register to set it high.
3291 * Otherwise locking is needed, so there may be little value to inlining.
3292 *
3293 *------------------------------------------------------------------------
3294 *
3295 * IMPORTANT!!!  The hot paths -- get/set value -- assume that callers
3296 * have requested the GPIO.  That can include implicit requesting by
3297 * a direction setting call.  Marking a gpio as requested locks its chip
3298 * in memory, guaranteeing that these table lookups need no more locking
3299 * and that gpiochip_remove() will fail.
3300 *
3301 * REVISIT when debugging, consider adding some instrumentation to ensure
3302 * that the GPIO was actually requested.
3303 */
3304
3305static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
3306{
3307	struct gpio_device *gdev;
3308	struct gpio_chip *gc;
3309	int value;
3310
3311	/* FIXME Unable to use gpio_chip_guard due to const desc. */
3312	gdev = desc->gdev;
3313
3314	guard(srcu)(&gdev->srcu);
3315
3316	gc = srcu_dereference(gdev->chip, &gdev->srcu);
3317	if (!gc)
3318		return -ENODEV;
3319
3320	value = gpio_chip_get_value(gc, desc);
3321	value = value < 0 ? value : !!value;
3322	trace_gpio_value(desc_to_gpio(desc), 1, value);
3323	return value;
3324}
3325
3326static int gpio_chip_get_multiple(struct gpio_chip *gc,
3327				  unsigned long *mask, unsigned long *bits)
3328{
3329	lockdep_assert_held(&gc->gpiodev->srcu);
3330
3331	if (gc->get_multiple) {
3332		int ret;
3333
3334		ret = gc->get_multiple(gc, mask, bits);
3335		if (ret > 0)
3336			return -EBADE;
3337		return ret;
3338	}
3339
3340	if (gc->get) {
3341		int i, value;
3342
3343		for_each_set_bit(i, mask, gc->ngpio) {
3344			value = gpiochip_get(gc, i);
3345			if (value < 0)
3346				return value;
3347			__assign_bit(i, bits, value);
3348		}
3349		return 0;
3350	}
3351	return -EIO;
3352}
3353
3354/* The 'other' chip must be protected with its GPIO device's SRCU. */
3355static bool gpio_device_chip_cmp(struct gpio_device *gdev, struct gpio_chip *gc)
3356{
3357	guard(srcu)(&gdev->srcu);
3358
3359	return gc == srcu_dereference(gdev->chip, &gdev->srcu);
3360}
3361
3362int gpiod_get_array_value_complex(bool raw, bool can_sleep,
3363				  unsigned int array_size,
3364				  struct gpio_desc **desc_array,
3365				  struct gpio_array *array_info,
3366				  unsigned long *value_bitmap)
3367{
3368	struct gpio_chip *gc;
3369	int ret, i = 0;
3370
3371	/*
3372	 * Validate array_info against desc_array and its size.
3373	 * It should immediately follow desc_array if both
3374	 * have been obtained from the same gpiod_get_array() call.
3375	 */
3376	if (array_info && array_info->desc == desc_array &&
3377	    array_size <= array_info->size &&
3378	    (void *)array_info == desc_array + array_info->size) {
3379		if (!can_sleep)
3380			WARN_ON(array_info->gdev->can_sleep);
3381
3382		guard(srcu)(&array_info->gdev->srcu);
3383		gc = srcu_dereference(array_info->gdev->chip,
3384				      &array_info->gdev->srcu);
3385		if (!gc)
3386			return -ENODEV;
3387
3388		ret = gpio_chip_get_multiple(gc, array_info->get_mask,
3389					     value_bitmap);
3390		if (ret)
3391			return ret;
3392
3393		if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3394			bitmap_xor(value_bitmap, value_bitmap,
3395				   array_info->invert_mask, array_size);
3396
3397		i = find_first_zero_bit(array_info->get_mask, array_size);
3398		if (i == array_size)
3399			return 0;
3400	} else {
3401		array_info = NULL;
3402	}
3403
3404	while (i < array_size) {
3405		DECLARE_BITMAP(fastpath_mask, FASTPATH_NGPIO);
3406		DECLARE_BITMAP(fastpath_bits, FASTPATH_NGPIO);
3407		unsigned long *mask, *bits;
3408		int first, j;
3409
3410		CLASS(gpio_chip_guard, guard)(desc_array[i]);
3411		if (!guard.gc)
3412			return -ENODEV;
3413
3414		if (likely(guard.gc->ngpio <= FASTPATH_NGPIO)) {
3415			mask = fastpath_mask;
3416			bits = fastpath_bits;
3417		} else {
3418			gfp_t flags = can_sleep ? GFP_KERNEL : GFP_ATOMIC;
3419
3420			mask = bitmap_alloc(guard.gc->ngpio, flags);
3421			if (!mask)
3422				return -ENOMEM;
3423
3424			bits = bitmap_alloc(guard.gc->ngpio, flags);
3425			if (!bits) {
3426				bitmap_free(mask);
3427				return -ENOMEM;
3428			}
3429		}
3430
3431		bitmap_zero(mask, guard.gc->ngpio);
3432
3433		if (!can_sleep)
3434			WARN_ON(guard.gc->can_sleep);
3435
3436		/* collect all inputs belonging to the same chip */
3437		first = i;
3438		do {
3439			const struct gpio_desc *desc = desc_array[i];
3440			int hwgpio = gpiod_hwgpio(desc);
3441
3442			__set_bit(hwgpio, mask);
3443			i++;
3444
3445			if (array_info)
3446				i = find_next_zero_bit(array_info->get_mask,
3447						       array_size, i);
3448		} while ((i < array_size) &&
3449			 gpio_device_chip_cmp(desc_array[i]->gdev, guard.gc));
3450
3451		ret = gpio_chip_get_multiple(guard.gc, mask, bits);
3452		if (ret) {
3453			if (mask != fastpath_mask)
3454				bitmap_free(mask);
3455			if (bits != fastpath_bits)
3456				bitmap_free(bits);
3457			return ret;
3458		}
3459
3460		for (j = first; j < i; ) {
3461			const struct gpio_desc *desc = desc_array[j];
3462			int hwgpio = gpiod_hwgpio(desc);
3463			int value = test_bit(hwgpio, bits);
3464
3465			if (!raw && test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags))
3466				value = !value;
3467			__assign_bit(j, value_bitmap, value);
3468			trace_gpio_value(desc_to_gpio(desc), 1, value);
3469			j++;
3470
3471			if (array_info)
3472				j = find_next_zero_bit(array_info->get_mask, i,
3473						       j);
3474		}
3475
3476		if (mask != fastpath_mask)
3477			bitmap_free(mask);
3478		if (bits != fastpath_bits)
3479			bitmap_free(bits);
3480	}
3481	return 0;
3482}
3483
3484/**
3485 * gpiod_get_raw_value() - return a gpio's raw value
3486 * @desc: gpio whose value will be returned
3487 *
3488 * Returns:
3489 * The GPIO's raw value, i.e. the value of the physical line disregarding
3490 * its ACTIVE_LOW status, or negative errno on failure.
3491 *
3492 * This function can be called from contexts where we cannot sleep, and will
3493 * complain if the GPIO chip functions potentially sleep.
3494 */
3495int gpiod_get_raw_value(const struct gpio_desc *desc)
3496{
3497	VALIDATE_DESC(desc);
3498	/* Should be using gpiod_get_raw_value_cansleep() */
3499	WARN_ON(desc->gdev->can_sleep);
3500	return gpiod_get_raw_value_commit(desc);
3501}
3502EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
3503
3504/**
3505 * gpiod_get_value() - return a gpio's value
3506 * @desc: gpio whose value will be returned
3507 *
3508 * Returns:
3509 * The GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3510 * account, or negative errno on failure.
3511 *
3512 * This function can be called from contexts where we cannot sleep, and will
3513 * complain if the GPIO chip functions potentially sleep.
3514 */
3515int gpiod_get_value(const struct gpio_desc *desc)
3516{
3517	int value;
3518
3519	VALIDATE_DESC(desc);
3520	/* Should be using gpiod_get_value_cansleep() */
3521	WARN_ON(desc->gdev->can_sleep);
3522
3523	value = gpiod_get_raw_value_commit(desc);
3524	if (value < 0)
3525		return value;
3526
3527	if (test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags))
3528		value = !value;
3529
3530	return value;
3531}
3532EXPORT_SYMBOL_GPL(gpiod_get_value);
3533
3534/**
3535 * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
3536 * @array_size: number of elements in the descriptor array / value bitmap
3537 * @desc_array: array of GPIO descriptors whose values will be read
3538 * @array_info: information on applicability of fast bitmap processing path
3539 * @value_bitmap: bitmap to store the read values
3540 *
3541 * Read the raw values of the GPIOs, i.e. the values of the physical lines
3542 * without regard for their ACTIVE_LOW status.
3543 *
3544 * This function can be called from contexts where we cannot sleep,
3545 * and it will complain if the GPIO chip functions potentially sleep.
3546 *
3547 * Returns:
3548 * 0 on success, or negative errno on failure.
3549 */
3550int gpiod_get_raw_array_value(unsigned int array_size,
3551			      struct gpio_desc **desc_array,
3552			      struct gpio_array *array_info,
3553			      unsigned long *value_bitmap)
3554{
3555	if (!desc_array)
3556		return -EINVAL;
3557	return gpiod_get_array_value_complex(true, false, array_size,
3558					     desc_array, array_info,
3559					     value_bitmap);
3560}
3561EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
3562
3563/**
3564 * gpiod_get_array_value() - read values from an array of GPIOs
3565 * @array_size: number of elements in the descriptor array / value bitmap
3566 * @desc_array: array of GPIO descriptors whose values will be read
3567 * @array_info: information on applicability of fast bitmap processing path
3568 * @value_bitmap: bitmap to store the read values
3569 *
3570 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3571 * into account.
3572 *
3573 * This function can be called from contexts where we cannot sleep,
3574 * and it will complain if the GPIO chip functions potentially sleep.
3575 *
3576 * Returns:
3577 * 0 on success, or negative errno on failure.
3578 */
3579int gpiod_get_array_value(unsigned int array_size,
3580			  struct gpio_desc **desc_array,
3581			  struct gpio_array *array_info,
3582			  unsigned long *value_bitmap)
3583{
3584	if (!desc_array)
3585		return -EINVAL;
3586	return gpiod_get_array_value_complex(false, false, array_size,
3587					     desc_array, array_info,
3588					     value_bitmap);
3589}
3590EXPORT_SYMBOL_GPL(gpiod_get_array_value);
3591
3592/*
3593 *  gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
3594 * @desc: gpio descriptor whose state need to be set.
3595 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3596 */
3597static int gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
3598{
3599	int ret = 0, offset = gpiod_hwgpio(desc);
3600
3601	CLASS(gpio_chip_guard, guard)(desc);
3602	if (!guard.gc)
3603		return -ENODEV;
3604
3605	if (value) {
3606		ret = gpiochip_direction_input(guard.gc, offset);
3607	} else {
3608		ret = gpiochip_direction_output(guard.gc, offset, 0);
3609		if (!ret)
3610			set_bit(GPIOD_FLAG_IS_OUT, &desc->flags);
3611	}
3612	trace_gpio_direction(desc_to_gpio(desc), value, ret);
3613	if (ret < 0)
3614		gpiod_err(desc,
3615			  "%s: Error in set_value for open drain err %d\n",
3616			  __func__, ret);
3617
3618	return ret;
3619}
3620
3621/*
3622 *  _gpio_set_open_source_value() - Set the open source gpio's value.
3623 * @desc: gpio descriptor whose state need to be set.
3624 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3625 */
3626static int gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
3627{
3628	int ret = 0, offset = gpiod_hwgpio(desc);
3629
3630	CLASS(gpio_chip_guard, guard)(desc);
3631	if (!guard.gc)
3632		return -ENODEV;
3633
3634	if (value) {
3635		ret = gpiochip_direction_output(guard.gc, offset, 1);
3636		if (!ret)
3637			set_bit(GPIOD_FLAG_IS_OUT, &desc->flags);
3638	} else {
3639		ret = gpiochip_direction_input(guard.gc, offset);
3640	}
3641	trace_gpio_direction(desc_to_gpio(desc), !value, ret);
3642	if (ret < 0)
3643		gpiod_err(desc,
3644			  "%s: Error in set_value for open source err %d\n",
3645			  __func__, ret);
3646
3647	return ret;
3648}
3649
3650static int gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
3651{
3652	if (unlikely(!test_bit(GPIOD_FLAG_IS_OUT, &desc->flags)))
3653		return -EPERM;
3654
3655	CLASS(gpio_chip_guard, guard)(desc);
3656	if (!guard.gc)
3657		return -ENODEV;
3658
3659	trace_gpio_value(desc_to_gpio(desc), 0, value);
3660	return gpiochip_set(guard.gc, gpiod_hwgpio(desc), value);
3661}
3662
3663/*
3664 * set multiple outputs on the same chip;
3665 * use the chip's set_multiple function if available;
3666 * otherwise set the outputs sequentially;
3667 * @chip: the GPIO chip we operate on
3668 * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
3669 *        defines which outputs are to be changed
3670 * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
3671 *        defines the values the outputs specified by mask are to be set to
3672 *
3673 * Returns: 0 on success, negative error number on failure.
3674 */
3675static int gpiochip_set_multiple(struct gpio_chip *gc,
3676				 unsigned long *mask, unsigned long *bits)
3677{
3678	unsigned int i;
3679	int ret;
3680
3681	lockdep_assert_held(&gc->gpiodev->srcu);
3682
3683	if (gc->set_multiple) {
3684		ret = gc->set_multiple(gc, mask, bits);
3685		if (ret > 0)
3686			ret = -EBADE;
3687
3688		return ret;
3689	}
3690
3691	/* set outputs if the corresponding mask bit is set */
3692	for_each_set_bit(i, mask, gc->ngpio) {
3693		ret = gpiochip_set(gc, i, test_bit(i, bits));
3694		if (ret)
3695			break;
3696	}
3697
3698	return ret;
3699}
3700
3701int gpiod_set_array_value_complex(bool raw, bool can_sleep,
3702				  unsigned int array_size,
3703				  struct gpio_desc **desc_array,
3704				  struct gpio_array *array_info,
3705				  unsigned long *value_bitmap)
3706{
3707	struct gpio_chip *gc;
3708	int i = 0, ret;
3709
3710	/*
3711	 * Validate array_info against desc_array and its size.
3712	 * It should immediately follow desc_array if both
3713	 * have been obtained from the same gpiod_get_array() call.
3714	 */
3715	if (array_info && array_info->desc == desc_array &&
3716	    array_size <= array_info->size &&
3717	    (void *)array_info == desc_array + array_info->size) {
3718		if (!can_sleep)
3719			WARN_ON(array_info->gdev->can_sleep);
3720
3721		for (i = 0; i < array_size; i++) {
3722			if (unlikely(!test_bit(GPIOD_FLAG_IS_OUT,
3723					       &desc_array[i]->flags)))
3724				return -EPERM;
3725		}
3726
3727		guard(srcu)(&array_info->gdev->srcu);
3728		gc = srcu_dereference(array_info->gdev->chip,
3729				      &array_info->gdev->srcu);
3730		if (!gc)
3731			return -ENODEV;
3732
3733		if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3734			bitmap_xor(value_bitmap, value_bitmap,
3735				   array_info->invert_mask, array_size);
3736
3737		ret = gpiochip_set_multiple(gc, array_info->set_mask,
3738					    value_bitmap);
3739		if (ret)
3740			return ret;
3741
3742		i = find_first_zero_bit(array_info->set_mask, array_size);
3743		if (i == array_size)
3744			return 0;
3745	} else {
3746		array_info = NULL;
3747	}
3748
3749	while (i < array_size) {
3750		DECLARE_BITMAP(fastpath_mask, FASTPATH_NGPIO);
3751		DECLARE_BITMAP(fastpath_bits, FASTPATH_NGPIO);
3752		unsigned long *mask, *bits;
3753		int count = 0;
3754
3755		CLASS(gpio_chip_guard, guard)(desc_array[i]);
3756		if (!guard.gc)
3757			return -ENODEV;
3758
3759		if (likely(guard.gc->ngpio <= FASTPATH_NGPIO)) {
3760			mask = fastpath_mask;
3761			bits = fastpath_bits;
3762		} else {
3763			gfp_t flags = can_sleep ? GFP_KERNEL : GFP_ATOMIC;
3764
3765			mask = bitmap_alloc(guard.gc->ngpio, flags);
3766			if (!mask)
3767				return -ENOMEM;
3768
3769			bits = bitmap_alloc(guard.gc->ngpio, flags);
3770			if (!bits) {
3771				bitmap_free(mask);
3772				return -ENOMEM;
3773			}
3774		}
3775
3776		bitmap_zero(mask, guard.gc->ngpio);
3777
3778		if (!can_sleep)
3779			WARN_ON(guard.gc->can_sleep);
3780
3781		do {
3782			struct gpio_desc *desc = desc_array[i];
3783			int hwgpio = gpiod_hwgpio(desc);
3784			int value = test_bit(i, value_bitmap);
3785
3786			if (unlikely(!test_bit(GPIOD_FLAG_IS_OUT, &desc->flags)))
3787				return -EPERM;
3788
3789			/*
3790			 * Pins applicable for fast input but not for
3791			 * fast output processing may have been already
3792			 * inverted inside the fast path, skip them.
3793			 */
3794			if (!raw && !(array_info &&
3795			    test_bit(i, array_info->invert_mask)) &&
3796			    test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags))
3797				value = !value;
3798			trace_gpio_value(desc_to_gpio(desc), 0, value);
3799			/*
3800			 * collect all normal outputs belonging to the same chip
3801			 * open drain and open source outputs are set individually
3802			 */
3803			if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
3804				gpio_set_open_drain_value_commit(desc, value);
3805			} else if (test_bit(GPIOD_FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
3806				gpio_set_open_source_value_commit(desc, value);
3807			} else {
3808				__set_bit(hwgpio, mask);
3809				__assign_bit(hwgpio, bits, value);
3810				count++;
3811			}
3812			i++;
3813
3814			if (array_info)
3815				i = find_next_zero_bit(array_info->set_mask,
3816						       array_size, i);
3817		} while ((i < array_size) &&
3818			 gpio_device_chip_cmp(desc_array[i]->gdev, guard.gc));
3819		/* push collected bits to outputs */
3820		if (count != 0) {
3821			ret = gpiochip_set_multiple(guard.gc, mask, bits);
3822			if (ret)
3823				return ret;
3824		}
3825
3826		if (mask != fastpath_mask)
3827			bitmap_free(mask);
3828		if (bits != fastpath_bits)
3829			bitmap_free(bits);
3830	}
3831	return 0;
3832}
3833
3834/**
3835 * gpiod_set_raw_value() - assign a gpio's raw value
3836 * @desc: gpio whose value will be assigned
3837 * @value: value to assign
3838 *
3839 * Set the raw value of the GPIO, i.e. the value of its physical line without
3840 * regard for its ACTIVE_LOW status.
3841 *
3842 * This function can be called from contexts where we cannot sleep, and will
3843 * complain if the GPIO chip functions potentially sleep.
3844 *
3845 * Returns:
3846 * 0 on success, negative error number on failure.
3847 */
3848int gpiod_set_raw_value(struct gpio_desc *desc, int value)
3849{
3850	VALIDATE_DESC(desc);
3851	/* Should be using gpiod_set_raw_value_cansleep() */
3852	WARN_ON(desc->gdev->can_sleep);
3853	return gpiod_set_raw_value_commit(desc, value);
3854}
3855EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
3856
3857/**
3858 * gpiod_set_value_nocheck() - set a GPIO line value without checking
3859 * @desc: the descriptor to set the value on
3860 * @value: value to set
3861 *
3862 * This sets the value of a GPIO line backing a descriptor, applying
3863 * different semantic quirks like active low and open drain/source
3864 * handling.
3865 *
3866 * Returns:
3867 * 0 on success, negative error number on failure.
3868 */
3869static int gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
3870{
3871	if (test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags))
3872		value = !value;
3873
3874	if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags))
3875		return gpio_set_open_drain_value_commit(desc, value);
3876	else if (test_bit(GPIOD_FLAG_OPEN_SOURCE, &desc->flags))
3877		return gpio_set_open_source_value_commit(desc, value);
3878
3879	return gpiod_set_raw_value_commit(desc, value);
3880}
3881
3882/**
3883 * gpiod_set_value() - assign a gpio's value
3884 * @desc: gpio whose value will be assigned
3885 * @value: value to assign
3886 *
3887 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
3888 * OPEN_DRAIN and OPEN_SOURCE flags into account.
3889 *
3890 * This function can be called from contexts where we cannot sleep, and will
3891 * complain if the GPIO chip functions potentially sleep.
3892 *
3893 * Returns:
3894 * 0 on success, negative error number on failure.
3895 */
3896int gpiod_set_value(struct gpio_desc *desc, int value)
3897{
3898	VALIDATE_DESC(desc);
3899	/* Should be using gpiod_set_value_cansleep() */
3900	WARN_ON(desc->gdev->can_sleep);
3901	return gpiod_set_value_nocheck(desc, value);
3902}
3903EXPORT_SYMBOL_GPL(gpiod_set_value);
3904
3905/**
3906 * gpiod_set_raw_array_value() - assign values to an array of GPIOs
3907 * @array_size: number of elements in the descriptor array / value bitmap
3908 * @desc_array: array of GPIO descriptors whose values will be assigned
3909 * @array_info: information on applicability of fast bitmap processing path
3910 * @value_bitmap: bitmap of values to assign
3911 *
3912 * Set the raw values of the GPIOs, i.e. the values of the physical lines
3913 * without regard for their ACTIVE_LOW status.
3914 *
3915 * This function can be called from contexts where we cannot sleep, and will
3916 * complain if the GPIO chip functions potentially sleep.
3917 *
3918 * Returns:
3919 * 0 on success, or negative errno on failure.
3920 */
3921int gpiod_set_raw_array_value(unsigned int array_size,
3922			      struct gpio_desc **desc_array,
3923			      struct gpio_array *array_info,
3924			      unsigned long *value_bitmap)
3925{
3926	if (!desc_array)
3927		return -EINVAL;
3928	return gpiod_set_array_value_complex(true, false, array_size,
3929					desc_array, array_info, value_bitmap);
3930}
3931EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
3932
3933/**
3934 * gpiod_set_array_value() - assign values to an array of GPIOs
3935 * @array_size: number of elements in the descriptor array / value bitmap
3936 * @desc_array: array of GPIO descriptors whose values will be assigned
3937 * @array_info: information on applicability of fast bitmap processing path
3938 * @value_bitmap: bitmap of values to assign
3939 *
3940 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3941 * into account.
3942 *
3943 * This function can be called from contexts where we cannot sleep, and will
3944 * complain if the GPIO chip functions potentially sleep.
3945 *
3946 * Returns:
3947 * 0 on success, or negative errno on failure.
3948 */
3949int gpiod_set_array_value(unsigned int array_size,
3950			  struct gpio_desc **desc_array,
3951			  struct gpio_array *array_info,
3952			  unsigned long *value_bitmap)
3953{
3954	if (!desc_array)
3955		return -EINVAL;
3956	return gpiod_set_array_value_complex(false, false, array_size,
3957					     desc_array, array_info,
3958					     value_bitmap);
3959}
3960EXPORT_SYMBOL_GPL(gpiod_set_array_value);
3961
3962/**
3963 * gpiod_cansleep() - report whether gpio value access may sleep
3964 * @desc: gpio to check
3965 *
3966 * Returns:
3967 * 0 for non-sleepable, 1 for sleepable, or an error code in case of error.
3968 */
3969int gpiod_cansleep(const struct gpio_desc *desc)
3970{
3971	VALIDATE_DESC(desc);
3972	return desc->gdev->can_sleep;
3973}
3974EXPORT_SYMBOL_GPL(gpiod_cansleep);
3975
3976/**
3977 * gpiod_set_consumer_name() - set the consumer name for the descriptor
3978 * @desc: gpio to set the consumer name on
3979 * @name: the new consumer name
3980 *
3981 * Returns:
3982 * 0 on success, or negative errno on failure.
3983 */
3984int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
3985{
3986	int ret;
3987
3988	VALIDATE_DESC(desc);
3989
3990	ret = desc_set_label(desc, name);
3991	if (ret == 0)
3992		gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
3993
3994	return ret;
3995}
3996EXPORT_SYMBOL_GPL(gpiod_set_consumer_name);
3997
3998/**
3999 * gpiod_is_shared() - check if this GPIO can be shared by multiple consumers
4000 * @desc: GPIO to inspect
4001 *
4002 * Returns:
4003 * True if this GPIO can be shared by multiple consumers at once. False if it's
4004 * a regular, exclusive GPIO.
4005 *
4006 * Note:
4007 * This function returning true does not mean that this GPIO is currently being
4008 * shared. It means the GPIO core has registered the fact that the firmware
4009 * configuration indicates that it can be shared by multiple consumers and is
4010 * in charge of arbitrating the access.
4011 */
4012bool gpiod_is_shared(const struct gpio_desc *desc)
4013{
4014	return test_bit(GPIOD_FLAG_SHARED_PROXY, &desc->flags);
4015}
4016EXPORT_SYMBOL_GPL(gpiod_is_shared);
4017
4018/**
4019 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
4020 * @desc: gpio whose IRQ will be returned (already requested)
4021 *
4022 * Returns:
4023 * The IRQ corresponding to the passed GPIO, or an error code in case of error.
4024 */
4025int gpiod_to_irq(const struct gpio_desc *desc)
4026{
4027	struct gpio_device *gdev;
4028	struct gpio_chip *gc;
4029	int offset;
4030	int ret;
4031
4032	ret = validate_desc(desc, __func__);
4033	if (ret <= 0)
4034		return -EINVAL;
4035
4036	gdev = desc->gdev;
4037	/* FIXME Cannot use gpio_chip_guard due to const desc. */
4038	guard(srcu)(&gdev->srcu);
4039	gc = srcu_dereference(gdev->chip, &gdev->srcu);
4040	if (!gc)
4041		return -ENODEV;
4042
4043	offset = gpiod_hwgpio(desc);
4044	if (gc->to_irq) {
4045		ret = gc->to_irq(gc, offset);
4046		if (ret)
4047			return ret;
4048
4049		/* Zero means NO_IRQ */
4050		return -ENXIO;
4051	}
4052#ifdef CONFIG_GPIOLIB_IRQCHIP
4053	if (gc->irq.chip) {
4054		/*
4055		 * Avoid race condition with other code, which tries to lookup
4056		 * an IRQ before the irqchip has been properly registered,
4057		 * i.e. while gpiochip is still being brought up.
4058		 */
4059		return -EPROBE_DEFER;
4060	}
4061#endif
4062	return -ENXIO;
4063}
4064EXPORT_SYMBOL_GPL(gpiod_to_irq);
4065
4066/**
4067 * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
4068 * @gc: the chip the GPIO to lock belongs to
4069 * @offset: the offset of the GPIO to lock as IRQ
4070 *
4071 * This is used directly by GPIO drivers that want to lock down
4072 * a certain GPIO line to be used for IRQs.
4073 *
4074 * Returns:
4075 * 0 on success, or negative errno on failure.
4076 */
4077int gpiochip_lock_as_irq(struct gpio_chip *gc, unsigned int offset)
4078{
4079	struct gpio_desc *desc;
4080
4081	desc = gpiochip_get_desc(gc, offset);
4082	if (IS_ERR(desc))
4083		return PTR_ERR(desc);
4084
4085	/*
4086	 * If it's fast: flush the direction setting if something changed
4087	 * behind our back
4088	 */
4089	if (!gc->can_sleep && gc->get_direction) {
4090		int dir = gpiod_get_direction(desc);
4091
4092		if (dir < 0) {
4093			gpiochip_err(gc, "%s: cannot get GPIO direction\n",
4094				     __func__);
4095			return dir;
4096		}
4097	}
4098
4099	/* To be valid for IRQ the line needs to be input or open drain */
4100	if (test_bit(GPIOD_FLAG_IS_OUT, &desc->flags) &&
4101	    !test_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags)) {
4102		gpiochip_err(gc,
4103			     "%s: tried to flag a GPIO set as output for IRQ\n",
4104			     __func__);
4105		return -EIO;
4106	}
4107
4108	set_bit(GPIOD_FLAG_USED_AS_IRQ, &desc->flags);
4109	set_bit(GPIOD_FLAG_IRQ_IS_ENABLED, &desc->flags);
4110
4111	return 0;
4112}
4113EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
4114
4115/**
4116 * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
4117 * @gc: the chip the GPIO to lock belongs to
4118 * @offset: the offset of the GPIO to lock as IRQ
4119 *
4120 * This is used directly by GPIO drivers that want to indicate
4121 * that a certain GPIO is no longer used exclusively for IRQ.
4122 */
4123void gpiochip_unlock_as_irq(struct gpio_chip *gc, unsigned int offset)
4124{
4125	struct gpio_desc *desc;
4126
4127	desc = gpiochip_get_desc(gc, offset);
4128	if (IS_ERR(desc))
4129		return;
4130
4131	clear_bit(GPIOD_FLAG_USED_AS_IRQ, &desc->flags);
4132	clear_bit(GPIOD_FLAG_IRQ_IS_ENABLED, &desc->flags);
4133}
4134EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
4135
4136void gpiochip_disable_irq(struct gpio_chip *gc, unsigned int offset)
4137{
4138	struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
4139
4140	if (!IS_ERR(desc) &&
4141	    !WARN_ON(!test_bit(GPIOD_FLAG_USED_AS_IRQ, &desc->flags)))
4142		clear_bit(GPIOD_FLAG_IRQ_IS_ENABLED, &desc->flags);
4143}
4144EXPORT_SYMBOL_GPL(gpiochip_disable_irq);
4145
4146void gpiochip_enable_irq(struct gpio_chip *gc, unsigned int offset)
4147{
4148	struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
4149
4150	if (!IS_ERR(desc) &&
4151	    !WARN_ON(!test_bit(GPIOD_FLAG_USED_AS_IRQ, &desc->flags))) {
4152		/*
4153		 * We must not be output when using IRQ UNLESS we are
4154		 * open drain.
4155		 */
4156		WARN_ON(test_bit(GPIOD_FLAG_IS_OUT, &desc->flags) &&
4157			!test_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags));
4158		set_bit(GPIOD_FLAG_IRQ_IS_ENABLED, &desc->flags);
4159	}
4160}
4161EXPORT_SYMBOL_GPL(gpiochip_enable_irq);
4162
4163bool gpiochip_line_is_irq(struct gpio_chip *gc, unsigned int offset)
4164{
4165	if (offset >= gc->ngpio)
4166		return false;
4167
4168	return test_bit(GPIOD_FLAG_USED_AS_IRQ, &gc->gpiodev->descs[offset].flags);
4169}
4170EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
4171
4172int gpiochip_reqres_irq(struct gpio_chip *gc, unsigned int offset)
4173{
4174	int ret;
4175
4176	if (!try_module_get(gc->gpiodev->owner))
4177		return -ENODEV;
4178
4179	ret = gpiochip_lock_as_irq(gc, offset);
4180	if (ret) {
4181		gpiochip_err(gc, "unable to lock HW IRQ %u for IRQ\n", offset);
4182		module_put(gc->gpiodev->owner);
4183		return ret;
4184	}
4185	return 0;
4186}
4187EXPORT_SYMBOL_GPL(gpiochip_reqres_irq);
4188
4189void gpiochip_relres_irq(struct gpio_chip *gc, unsigned int offset)
4190{
4191	gpiochip_unlock_as_irq(gc, offset);
4192	module_put(gc->gpiodev->owner);
4193}
4194EXPORT_SYMBOL_GPL(gpiochip_relres_irq);
4195
4196bool gpiochip_line_is_open_drain(struct gpio_chip *gc, unsigned int offset)
4197{
4198	if (offset >= gc->ngpio)
4199		return false;
4200
4201	return test_bit(GPIOD_FLAG_OPEN_DRAIN, &gc->gpiodev->descs[offset].flags);
4202}
4203EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
4204
4205bool gpiochip_line_is_open_source(struct gpio_chip *gc, unsigned int offset)
4206{
4207	if (offset >= gc->ngpio)
4208		return false;
4209
4210	return test_bit(GPIOD_FLAG_OPEN_SOURCE, &gc->gpiodev->descs[offset].flags);
4211}
4212EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
4213
4214bool gpiochip_line_is_persistent(struct gpio_chip *gc, unsigned int offset)
4215{
4216	if (offset >= gc->ngpio)
4217		return false;
4218
4219	return !test_bit(GPIOD_FLAG_TRANSITORY, &gc->gpiodev->descs[offset].flags);
4220}
4221EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
4222
4223/**
4224 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
4225 * @desc: gpio whose value will be returned
4226 *
4227 * Returns:
4228 * The GPIO's raw value, i.e. the value of the physical line disregarding
4229 * its ACTIVE_LOW status, or negative errno on failure.
4230 *
4231 * This function is to be called from contexts that can sleep.
4232 */
4233int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
4234{
4235	might_sleep();
4236	VALIDATE_DESC(desc);
4237	return gpiod_get_raw_value_commit(desc);
4238}
4239EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
4240
4241/**
4242 * gpiod_get_value_cansleep() - return a gpio's value
4243 * @desc: gpio whose value will be returned
4244 *
4245 * Returns:
4246 * The GPIO's logical value, i.e. taking the ACTIVE_LOW status into
4247 * account, or negative errno on failure.
4248 *
4249 * This function is to be called from contexts that can sleep.
4250 */
4251int gpiod_get_value_cansleep(const struct gpio_desc *desc)
4252{
4253	int value;
4254
4255	might_sleep();
4256	VALIDATE_DESC(desc);
4257	value = gpiod_get_raw_value_commit(desc);
4258	if (value < 0)
4259		return value;
4260
4261	if (test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags))
4262		value = !value;
4263
4264	return value;
4265}
4266EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
4267
4268/**
4269 * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
4270 * @array_size: number of elements in the descriptor array / value bitmap
4271 * @desc_array: array of GPIO descriptors whose values will be read
4272 * @array_info: information on applicability of fast bitmap processing path
4273 * @value_bitmap: bitmap to store the read values
4274 *
4275 * Read the raw values of the GPIOs, i.e. the values of the physical lines
4276 * without regard for their ACTIVE_LOW status.
4277 *
4278 * This function is to be called from contexts that can sleep.
4279 *
4280 * Returns:
4281 * 0 on success, or negative errno on failure.
4282 */
4283int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
4284				       struct gpio_desc **desc_array,
4285				       struct gpio_array *array_info,
4286				       unsigned long *value_bitmap)
4287{
4288	might_sleep();
4289	if (!desc_array)
4290		return -EINVAL;
4291	return gpiod_get_array_value_complex(true, true, array_size,
4292					     desc_array, array_info,
4293					     value_bitmap);
4294}
4295EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
4296
4297/**
4298 * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
4299 * @array_size: number of elements in the descriptor array / value bitmap
4300 * @desc_array: array of GPIO descriptors whose values will be read
4301 * @array_info: information on applicability of fast bitmap processing path
4302 * @value_bitmap: bitmap to store the read values
4303 *
4304 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4305 * into account.
4306 *
4307 * This function is to be called from contexts that can sleep.
4308 *
4309 * Returns:
4310 * 0 on success, or negative errno on failure.
4311 */
4312int gpiod_get_array_value_cansleep(unsigned int array_size,
4313				   struct gpio_desc **desc_array,
4314				   struct gpio_array *array_info,
4315				   unsigned long *value_bitmap)
4316{
4317	might_sleep();
4318	if (!desc_array)
4319		return -EINVAL;
4320	return gpiod_get_array_value_complex(false, true, array_size,
4321					     desc_array, array_info,
4322					     value_bitmap);
4323}
4324EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
4325
4326/**
4327 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
4328 * @desc: gpio whose value will be assigned
4329 * @value: value to assign
4330 *
4331 * Set the raw value of the GPIO, i.e. the value of its physical line without
4332 * regard for its ACTIVE_LOW status.
4333 *
4334 * This function is to be called from contexts that can sleep.
4335 *
4336 * Returns:
4337 * 0 on success, negative error number on failure.
4338 */
4339int gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
4340{
4341	might_sleep();
4342	VALIDATE_DESC(desc);
4343	return gpiod_set_raw_value_commit(desc, value);
4344}
4345EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
4346
4347/**
4348 * gpiod_set_value_cansleep() - assign a gpio's value
4349 * @desc: gpio whose value will be assigned
4350 * @value: value to assign
4351 *
4352 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
4353 * account
4354 *
4355 * This function is to be called from contexts that can sleep.
4356 *
4357 * Returns:
4358 * 0 on success, negative error number on failure.
4359 */
4360int gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
4361{
4362	might_sleep();
4363	VALIDATE_DESC(desc);
4364	return gpiod_set_value_nocheck(desc, value);
4365}
4366EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
4367
4368/**
4369 * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
4370 * @array_size: number of elements in the descriptor array / value bitmap
4371 * @desc_array: array of GPIO descriptors whose values will be assigned
4372 * @array_info: information on applicability of fast bitmap processing path
4373 * @value_bitmap: bitmap of values to assign
4374 *
4375 * Set the raw values of the GPIOs, i.e. the values of the physical lines
4376 * without regard for their ACTIVE_LOW status.
4377 *
4378 * This function is to be called from contexts that can sleep.
4379 *
4380 * Returns:
4381 * 0 on success, or negative errno on failure.
4382 */
4383int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
4384				       struct gpio_desc **desc_array,
4385				       struct gpio_array *array_info,
4386				       unsigned long *value_bitmap)
4387{
4388	might_sleep();
4389	if (!desc_array)
4390		return -EINVAL;
4391	return gpiod_set_array_value_complex(true, true, array_size, desc_array,
4392				      array_info, value_bitmap);
4393}
4394EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
4395
4396/**
4397 * gpiod_add_lookup_tables() - register GPIO device consumers
4398 * @tables: list of tables of consumers to register
4399 * @n: number of tables in the list
4400 */
4401void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
4402{
4403	unsigned int i;
4404
4405	guard(mutex)(&gpio_lookup_lock);
4406
4407	for (i = 0; i < n; i++)
4408		list_add_tail(&tables[i]->list, &gpio_lookup_list);
4409}
4410
4411/**
4412 * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
4413 * @array_size: number of elements in the descriptor array / value bitmap
4414 * @desc_array: array of GPIO descriptors whose values will be assigned
4415 * @array_info: information on applicability of fast bitmap processing path
4416 * @value_bitmap: bitmap of values to assign
4417 *
4418 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4419 * into account.
4420 *
4421 * This function is to be called from contexts that can sleep.
4422 *
4423 * Returns:
4424 * 0 on success, or negative errno on failure.
4425 */
4426int gpiod_set_array_value_cansleep(unsigned int array_size,
4427				   struct gpio_desc **desc_array,
4428				   struct gpio_array *array_info,
4429				   unsigned long *value_bitmap)
4430{
4431	might_sleep();
4432	if (!desc_array)
4433		return -EINVAL;
4434	return gpiod_set_array_value_complex(false, true, array_size,
4435					     desc_array, array_info,
4436					     value_bitmap);
4437}
4438EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
4439
4440void gpiod_line_state_notify(struct gpio_desc *desc, unsigned long action)
4441{
4442	guard(read_lock_irqsave)(&desc->gdev->line_state_lock);
4443
4444	raw_notifier_call_chain(&desc->gdev->line_state_notifier, action, desc);
4445}
4446
4447/**
4448 * gpiod_add_lookup_table() - register GPIO device consumers
4449 * @table: table of consumers to register
4450 */
4451void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
4452{
4453	gpiod_add_lookup_tables(&table, 1);
4454}
4455EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
4456
4457/**
4458 * gpiod_remove_lookup_table() - unregister GPIO device consumers
4459 * @table: table of consumers to unregister
4460 */
4461void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
4462{
4463	/* Nothing to remove */
4464	if (!table)
4465		return;
4466
4467	guard(mutex)(&gpio_lookup_lock);
4468
4469	list_del(&table->list);
4470}
4471EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
4472
4473/**
4474 * gpiod_add_hogs() - register a set of GPIO hogs from machine code
4475 * @hogs: table of gpio hog entries with a zeroed sentinel at the end
4476 */
4477void gpiod_add_hogs(struct gpiod_hog *hogs)
4478{
4479	struct gpiod_hog *hog;
4480
4481	guard(mutex)(&gpio_machine_hogs_mutex);
4482
4483	for (hog = &hogs[0]; hog->chip_label; hog++) {
4484		list_add_tail(&hog->list, &gpio_machine_hogs);
4485
4486		/*
4487		 * The chip may have been registered earlier, so check if it
4488		 * exists and, if so, try to hog the line now.
4489		 */
4490		struct gpio_device *gdev __free(gpio_device_put) =
4491				gpio_device_find_by_label(hog->chip_label);
4492		if (gdev)
4493			gpiochip_machine_hog(gpio_device_get_chip(gdev), hog);
4494	}
4495}
4496EXPORT_SYMBOL_GPL(gpiod_add_hogs);
4497
4498void gpiod_remove_hogs(struct gpiod_hog *hogs)
4499{
4500	struct gpiod_hog *hog;
4501
4502	guard(mutex)(&gpio_machine_hogs_mutex);
4503
4504	for (hog = &hogs[0]; hog->chip_label; hog++)
4505		list_del(&hog->list);
4506}
4507EXPORT_SYMBOL_GPL(gpiod_remove_hogs);
4508
4509static bool gpiod_match_lookup_table(struct device *dev,
4510				     const struct gpiod_lookup_table *table)
4511{
4512	const char *dev_id = dev ? dev_name(dev) : NULL;
4513
4514	lockdep_assert_held(&gpio_lookup_lock);
4515
4516	if (table->dev_id && dev_id) {
4517		/*
4518		 * Valid strings on both ends, must be identical to have
4519		 * a match
4520		 */
4521		if (!strcmp(table->dev_id, dev_id))
4522			return true;
4523	} else {
4524		/*
4525		 * One of the pointers is NULL, so both must be to have
4526		 * a match
4527		 */
4528		if (dev_id == table->dev_id)
4529			return true;
4530	}
4531
4532	return false;
4533}
4534
4535static struct gpio_desc *gpio_desc_table_match(struct device *dev, const char *con_id,
4536					       unsigned int idx, unsigned long *flags,
4537					       struct gpiod_lookup_table *table)
4538{
4539	struct gpio_desc *desc;
4540	struct gpiod_lookup *p;
4541	struct gpio_chip *gc;
4542
4543	lockdep_assert_held(&gpio_lookup_lock);
4544
4545	for (p = &table->table[0]; p->key; p++) {
4546		/* idx must always match exactly */
4547		if (p->idx != idx)
4548			continue;
4549
4550		/* If the lookup entry has a con_id, require exact match */
4551		if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
4552			continue;
4553
4554		if (p->chip_hwnum == U16_MAX) {
4555			desc = gpio_name_to_desc(p->key);
4556			if (desc) {
4557				*flags = p->flags;
4558				return desc;
4559			}
4560
4561			dev_warn(dev, "cannot find GPIO line %s, deferring\n",
4562				 p->key);
4563			return ERR_PTR(-EPROBE_DEFER);
4564		}
4565
4566		struct gpio_device *gdev __free(gpio_device_put) =
4567					gpio_device_find_by_label(p->key);
4568		if (!gdev) {
4569			/*
4570			 * As the lookup table indicates a chip with
4571			 * p->key should exist, assume it may
4572			 * still appear later and let the interested
4573			 * consumer be probed again or let the Deferred
4574			 * Probe infrastructure handle the error.
4575			 */
4576			dev_warn(dev, "cannot find GPIO chip %s, deferring\n",
4577				 p->key);
4578			return ERR_PTR(-EPROBE_DEFER);
4579		}
4580
4581		gc = gpio_device_get_chip(gdev);
4582
4583		if (gc->ngpio <= p->chip_hwnum) {
4584			dev_err(dev,
4585				"requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
4586				idx, p->chip_hwnum, gc->ngpio - 1,
4587				gc->label);
4588			return ERR_PTR(-EINVAL);
4589		}
4590
4591		desc = gpio_device_get_desc(gdev, p->chip_hwnum);
4592		*flags = p->flags;
4593
4594		return desc;
4595	}
4596
4597	return NULL;
4598}
4599
4600static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
4601				    unsigned int idx, unsigned long *flags)
4602{
4603	struct gpiod_lookup_table *table;
4604	struct gpio_desc *desc;
4605
4606	guard(mutex)(&gpio_lookup_lock);
4607
4608	list_for_each_entry(table, &gpio_lookup_list, list) {
4609		if (!gpiod_match_lookup_table(dev, table))
4610			continue;
4611
4612		desc = gpio_desc_table_match(dev, con_id, idx, flags, table);
4613		if (!desc)
4614			continue;
4615
4616		/* On IS_ERR() or match. */
4617		return desc;
4618	}
4619
4620	return ERR_PTR(-ENOENT);
4621}
4622
4623static int platform_gpio_count(struct device *dev, const char *con_id)
4624{
4625	struct gpiod_lookup_table *table;
4626	struct gpiod_lookup *p;
4627	unsigned int count = 0;
4628
4629	scoped_guard(mutex, &gpio_lookup_lock) {
4630		list_for_each_entry(table, &gpio_lookup_list, list) {
4631			if (!gpiod_match_lookup_table(dev, table))
4632				continue;
4633
4634			for (p = &table->table[0]; p->key; p++) {
4635				if ((con_id && p->con_id &&
4636				    !strcmp(con_id, p->con_id)) ||
4637				    (!con_id && !p->con_id))
4638					count++;
4639			}
4640		}
4641	}
4642
4643	if (!count)
4644		return -ENOENT;
4645
4646	return count;
4647}
4648
4649static struct gpio_desc *gpiod_find_by_fwnode(struct fwnode_handle *fwnode,
4650					      struct device *consumer,
4651					      const char *con_id,
4652					      unsigned int idx,
4653					      enum gpiod_flags *flags,
4654					      unsigned long *lookupflags)
4655{
4656	const char *name = function_name_or_default(con_id);
4657	struct gpio_desc *desc = ERR_PTR(-ENOENT);
4658
4659	if (is_of_node(fwnode)) {
4660		dev_dbg(consumer, "using DT '%pfw' for '%s' GPIO lookup\n", fwnode, name);
4661		desc = of_find_gpio(to_of_node(fwnode), con_id, idx, lookupflags);
4662	} else if (is_acpi_node(fwnode)) {
4663		dev_dbg(consumer, "using ACPI '%pfw' for '%s' GPIO lookup\n", fwnode, name);
4664		desc = acpi_find_gpio(fwnode, con_id, idx, flags, lookupflags);
4665	} else if (is_software_node(fwnode)) {
4666		dev_dbg(consumer, "using swnode '%pfw' for '%s' GPIO lookup\n", fwnode, name);
4667		desc = swnode_find_gpio(fwnode, con_id, idx, lookupflags);
4668	}
4669
4670	return desc;
4671}
4672
4673static struct gpio_desc *gpiod_fwnode_lookup(struct fwnode_handle *fwnode,
4674					     struct device *consumer,
4675					     const char *con_id,
4676					     unsigned int idx,
4677					     enum gpiod_flags *flags,
4678					     unsigned long *lookupflags)
4679{
4680	struct gpio_desc *desc;
4681
4682	desc = gpiod_find_by_fwnode(fwnode, consumer, con_id, idx, flags, lookupflags);
4683	if (gpiod_not_found(desc) && !IS_ERR_OR_NULL(fwnode))
4684		desc = gpiod_find_by_fwnode(fwnode->secondary, consumer, con_id,
4685					    idx, flags, lookupflags);
4686
4687	return desc;
4688}
4689
4690struct gpio_desc *gpiod_find_and_request(struct device *consumer,
4691					 struct fwnode_handle *fwnode,
4692					 const char *con_id,
4693					 unsigned int idx,
4694					 enum gpiod_flags flags,
4695					 const char *label,
4696					 bool platform_lookup_allowed)
4697{
4698	unsigned long lookupflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4699	const char *name = function_name_or_default(con_id);
4700	/*
4701	 * scoped_guard() is implemented as a for loop, meaning static
4702	 * analyzers will complain about these two not being initialized.
4703	 */
4704	struct gpio_desc *desc = NULL;
4705	int ret = 0;
4706
4707	scoped_guard(srcu, &gpio_devices_srcu) {
4708		desc = gpiod_fwnode_lookup(fwnode, consumer, con_id, idx,
4709					   &flags, &lookupflags);
4710		if (!IS_ERR_OR_NULL(desc) &&
4711		    test_bit(GPIOD_FLAG_SHARED, &desc->flags)) {
4712			/*
4713			 * We're dealing with a GPIO shared by multiple
4714			 * consumers. This is the moment to add the machine
4715			 * lookup table for the proxy device as previously
4716			 * we only knew the consumer's fwnode.
4717			 */
4718			ret = gpio_shared_add_proxy_lookup(consumer, fwnode,
4719							   con_id, lookupflags);
4720			if (ret)
4721				return ERR_PTR(ret);
4722
4723			/* Trigger platform lookup for shared GPIO proxy. */
4724			desc = ERR_PTR(-ENOENT);
4725			/* Trigger it even for fwnode-only gpiod_get(). */
4726			platform_lookup_allowed = true;
4727		}
4728
4729		if (gpiod_not_found(desc) && platform_lookup_allowed) {
4730			/*
4731			 * Either we are not using DT or ACPI, or their lookup
4732			 * did not return a result or this is a shared GPIO. In
4733			 * that case, use platform lookup as a fallback.
4734			 */
4735			dev_dbg(consumer,
4736				"using lookup tables for GPIO lookup\n");
4737			desc = gpiod_find(consumer, con_id, idx, &lookupflags);
4738		}
4739
4740		if (IS_ERR(desc)) {
4741			dev_dbg(consumer, "No GPIO consumer %s found\n", name);
4742			return desc;
4743		}
4744
4745		/*
4746		 * If a connection label was passed use that, else attempt to use
4747		 * the device name as label
4748		 */
4749		ret = gpiod_request(desc, label);
4750	}
4751	if (ret) {
4752		if (!(ret == -EBUSY && flags & GPIOD_FLAGS_BIT_NONEXCLUSIVE))
4753			return ERR_PTR(ret);
4754
4755		/*
4756		 * This happens when there are several consumers for the same
4757		 * GPIO line: we just return here without further
4758		 * initialization. It's a hack introduced long ago to support
4759		 * fixed regulators. We now have a better solution with
4760		 * automated scanning where affected platforms just need to
4761		 * select the provided Kconfig option.
4762		 *
4763		 * FIXME: Remove the GPIOD_FLAGS_BIT_NONEXCLUSIVE flag after
4764		 * making sure all platforms use the new mechanism.
4765		 */
4766		dev_info(consumer,
4767			 "nonexclusive access to GPIO for %s, consider updating your code to using gpio-shared-proxy\n",
4768			 name);
4769		return desc;
4770	}
4771
4772	ret = gpiod_configure_flags(desc, con_id, lookupflags, flags);
4773	if (ret < 0) {
4774		gpiod_put(desc);
4775		dev_err(consumer, "setup of GPIO %s failed: %d\n", name, ret);
4776		return ERR_PTR(ret);
4777	}
4778
4779	gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_REQUESTED);
4780
4781	return desc;
4782}
4783
4784/**
4785 * fwnode_gpiod_get_index - obtain a GPIO from firmware node
4786 * @fwnode:	handle of the firmware node
4787 * @con_id:	function within the GPIO consumer
4788 * @index:	index of the GPIO to obtain for the consumer
4789 * @flags:	GPIO initialization flags
4790 * @label:	label to attach to the requested GPIO
4791 *
4792 * This function can be used for drivers that get their configuration
4793 * from opaque firmware.
4794 *
4795 * The function properly finds the corresponding GPIO using whatever is the
4796 * underlying firmware interface and then makes sure that the GPIO
4797 * descriptor is requested before it is returned to the caller.
4798 *
4799 * Returns:
4800 * On successful request the GPIO pin is configured in accordance with
4801 * provided @flags.
4802 *
4803 * In case of error an ERR_PTR() is returned.
4804 */
4805struct gpio_desc *fwnode_gpiod_get_index(struct fwnode_handle *fwnode,
4806					 const char *con_id,
4807					 int index,
4808					 enum gpiod_flags flags,
4809					 const char *label)
4810{
4811	return gpiod_find_and_request(NULL, fwnode, con_id, index, flags, label, false);
4812}
4813EXPORT_SYMBOL_GPL(fwnode_gpiod_get_index);
4814
4815/**
4816 * gpiod_count - return the number of GPIOs associated with a device / function
4817 * @dev:	GPIO consumer, can be NULL for system-global GPIOs
4818 * @con_id:	function within the GPIO consumer
4819 *
4820 * Returns:
4821 * The number of GPIOs associated with a device / function or -ENOENT if no
4822 * GPIO has been assigned to the requested function.
4823 */
4824int gpiod_count(struct device *dev, const char *con_id)
4825{
4826	const struct fwnode_handle *fwnode = dev ? dev_fwnode(dev) : NULL;
4827	int count = -ENOENT;
4828
4829	if (is_of_node(fwnode))
4830		count = of_gpio_count(fwnode, con_id);
4831	else if (is_acpi_node(fwnode))
4832		count = acpi_gpio_count(fwnode, con_id);
4833	else if (is_software_node(fwnode))
4834		count = swnode_gpio_count(fwnode, con_id);
4835
4836	if (count < 0)
4837		count = platform_gpio_count(dev, con_id);
4838
4839	return count;
4840}
4841EXPORT_SYMBOL_GPL(gpiod_count);
4842
4843/**
4844 * gpiod_get - obtain a GPIO for a given GPIO function
4845 * @dev:	GPIO consumer, can be NULL for system-global GPIOs
4846 * @con_id:	function within the GPIO consumer
4847 * @flags:	optional GPIO initialization flags
4848 *
4849 * Returns:
4850 * The GPIO descriptor corresponding to the function @con_id of device
4851 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
4852 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
4853 */
4854struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
4855					 enum gpiod_flags flags)
4856{
4857	return gpiod_get_index(dev, con_id, 0, flags);
4858}
4859EXPORT_SYMBOL_GPL(gpiod_get);
4860
4861/**
4862 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
4863 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4864 * @con_id: function within the GPIO consumer
4865 * @flags: optional GPIO initialization flags
4866 *
4867 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
4868 * the requested function it will return NULL. This is convenient for drivers
4869 * that need to handle optional GPIOs.
4870 *
4871 * Returns:
4872 * The GPIO descriptor corresponding to the function @con_id of device
4873 * dev, NULL if no GPIO has been assigned to the requested function, or
4874 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
4875 */
4876struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
4877						  const char *con_id,
4878						  enum gpiod_flags flags)
4879{
4880	return gpiod_get_index_optional(dev, con_id, 0, flags);
4881}
4882EXPORT_SYMBOL_GPL(gpiod_get_optional);
4883
4884
4885/**
4886 * gpiod_configure_flags - helper function to configure a given GPIO
4887 * @desc:	gpio whose value will be assigned
4888 * @con_id:	function within the GPIO consumer
4889 * @lflags:	bitmask of gpio_lookup_flags GPIO_* values - returned from
4890 *		of_find_gpio() or of_get_gpio_hog()
4891 * @dflags:	gpiod_flags - optional GPIO initialization flags
4892 *
4893 * Returns:
4894 * 0 on success, -ENOENT if no GPIO has been assigned to the
4895 * requested function and/or index, or another IS_ERR() code if an error
4896 * occurred while trying to acquire the GPIO.
4897 */
4898int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
4899		unsigned long lflags, enum gpiod_flags dflags)
4900{
4901	const char *name = function_name_or_default(con_id);
4902	int ret;
4903
4904	if (lflags & GPIO_ACTIVE_LOW)
4905		set_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags);
4906
4907	if (lflags & GPIO_OPEN_DRAIN)
4908		set_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags);
4909	else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
4910		/*
4911		 * This enforces open drain mode from the consumer side.
4912		 * This is necessary for some busses like I2C, but the lookup
4913		 * should *REALLY* have specified them as open drain in the
4914		 * first place, so print a little warning here.
4915		 */
4916		set_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags);
4917		gpiod_warn(desc,
4918			   "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
4919	}
4920
4921	if (lflags & GPIO_OPEN_SOURCE)
4922		set_bit(GPIOD_FLAG_OPEN_SOURCE, &desc->flags);
4923
4924	if (((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DOWN)) ||
4925	    ((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DISABLE)) ||
4926	    ((lflags & GPIO_PULL_DOWN) && (lflags & GPIO_PULL_DISABLE))) {
4927		gpiod_err(desc,
4928			  "multiple pull-up, pull-down or pull-disable enabled, invalid configuration\n");
4929		return -EINVAL;
4930	}
4931
4932	if (lflags & GPIO_PULL_UP)
4933		set_bit(GPIOD_FLAG_PULL_UP, &desc->flags);
4934	else if (lflags & GPIO_PULL_DOWN)
4935		set_bit(GPIOD_FLAG_PULL_DOWN, &desc->flags);
4936	else if (lflags & GPIO_PULL_DISABLE)
4937		set_bit(GPIOD_FLAG_BIAS_DISABLE, &desc->flags);
4938
4939	ret = gpiod_set_transitory(desc, (lflags & GPIO_TRANSITORY));
4940	if (ret < 0)
4941		return ret;
4942
4943	/* No particular flag request, return here... */
4944	if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
4945		gpiod_dbg(desc, "no flags found for GPIO %s\n", name);
4946		return 0;
4947	}
4948
4949	/* Process flags */
4950	if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
4951		ret = gpiod_direction_output_nonotify(desc,
4952				!!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
4953	else
4954		ret = gpiod_direction_input_nonotify(desc);
4955
4956	return ret;
4957}
4958
4959/**
4960 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
4961 * @dev:	GPIO consumer, can be NULL for system-global GPIOs
4962 * @con_id:	function within the GPIO consumer
4963 * @idx:	index of the GPIO to obtain in the consumer
4964 * @flags:	optional GPIO initialization flags
4965 *
4966 * This variant of gpiod_get() allows to access GPIOs other than the first
4967 * defined one for functions that define several GPIOs.
4968 *
4969 * Returns:
4970 * A valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
4971 * requested function and/or index, or another IS_ERR() code if an error
4972 * occurred while trying to acquire the GPIO.
4973 */
4974struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
4975					       const char *con_id,
4976					       unsigned int idx,
4977					       enum gpiod_flags flags)
4978{
4979	struct fwnode_handle *fwnode = dev ? dev_fwnode(dev) : NULL;
4980	const char *devname = dev ? dev_name(dev) : "?";
4981	const char *label = con_id ?: devname;
4982
4983	return gpiod_find_and_request(dev, fwnode, con_id, idx, flags, label, true);
4984}
4985EXPORT_SYMBOL_GPL(gpiod_get_index);
4986
4987/**
4988 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
4989 *                            function
4990 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4991 * @con_id: function within the GPIO consumer
4992 * @index: index of the GPIO to obtain in the consumer
4993 * @flags: optional GPIO initialization flags
4994 *
4995 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
4996 * specified index was assigned to the requested function it will return NULL.
4997 * This is convenient for drivers that need to handle optional GPIOs.
4998 *
4999 * Returns:
5000 * A valid GPIO descriptor, NULL if no GPIO has been assigned to the
5001 * requested function and/or index, or another IS_ERR() code if an error
5002 * occurred while trying to acquire the GPIO.
5003 */
5004struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
5005							const char *con_id,
5006							unsigned int index,
5007							enum gpiod_flags flags)
5008{
5009	struct gpio_desc *desc;
5010
5011	desc = gpiod_get_index(dev, con_id, index, flags);
5012	if (gpiod_not_found(desc))
5013		return NULL;
5014
5015	return desc;
5016}
5017EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
5018
5019/**
5020 * gpiod_hog - Hog the specified GPIO desc given the provided flags
5021 * @desc:	gpio whose value will be assigned
5022 * @name:	gpio line name
5023 * @lflags:	bitmask of gpio_lookup_flags GPIO_* values - returned from
5024 *		of_find_gpio() or of_get_gpio_hog()
5025 * @dflags:	gpiod_flags - optional GPIO initialization flags
5026 *
5027 * Returns:
5028 * 0 on success, or negative errno on failure.
5029 */
5030int gpiod_hog(struct gpio_desc *desc, const char *name,
5031	      unsigned long lflags, enum gpiod_flags dflags)
5032{
5033	struct gpio_device *gdev = desc->gdev;
5034	struct gpio_desc *local_desc;
5035	int hwnum;
5036	int ret;
5037
5038	CLASS(gpio_chip_guard, guard)(desc);
5039	if (!guard.gc)
5040		return -ENODEV;
5041
5042	if (test_and_set_bit(GPIOD_FLAG_IS_HOGGED, &desc->flags))
5043		return 0;
5044
5045	hwnum = gpiod_hwgpio(desc);
5046
5047	local_desc = gpiochip_request_own_desc(guard.gc, hwnum, name,
5048					       lflags, dflags);
5049	if (IS_ERR(local_desc)) {
5050		clear_bit(GPIOD_FLAG_IS_HOGGED, &desc->flags);
5051		ret = PTR_ERR(local_desc);
5052		pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
5053		       name, gdev->label, hwnum, ret);
5054		return ret;
5055	}
5056
5057	gpiod_dbg(desc, "hogged as %s/%s\n",
5058		(dflags & GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
5059		(dflags & GPIOD_FLAGS_BIT_DIR_OUT) ?
5060		  str_high_low(dflags & GPIOD_FLAGS_BIT_DIR_VAL) : "?");
5061
5062	return 0;
5063}
5064
5065/**
5066 * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
5067 * @gc:	gpio chip to act on
5068 */
5069static void gpiochip_free_hogs(struct gpio_chip *gc)
5070{
5071	struct gpio_desc *desc;
5072
5073	for_each_gpio_desc_with_flag(gc, desc, GPIOD_FLAG_IS_HOGGED)
5074		gpiochip_free_own_desc(desc);
5075}
5076
5077/**
5078 * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
5079 * @dev:	GPIO consumer, can be NULL for system-global GPIOs
5080 * @con_id:	function within the GPIO consumer
5081 * @flags:	optional GPIO initialization flags
5082 *
5083 * This function acquires all the GPIOs defined under a given function.
5084 *
5085 * Returns:
5086 * The GPIO descriptors corresponding to the function @con_id of device
5087 * dev, -ENOENT if no GPIO has been assigned to the requested function,
5088 * or another IS_ERR() code if an error occurred while trying to acquire
5089 * the GPIOs.
5090 */
5091struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
5092						const char *con_id,
5093						enum gpiod_flags flags)
5094{
5095	struct gpio_desc *desc;
5096	struct gpio_descs *descs;
5097	struct gpio_device *gdev;
5098	struct gpio_array *array_info = NULL;
5099	int count, bitmap_size;
5100	unsigned long dflags;
5101	size_t descs_size;
5102
5103	count = gpiod_count(dev, con_id);
5104	if (count < 0)
5105		return ERR_PTR(count);
5106
5107	descs_size = struct_size(descs, desc, count);
5108	descs = kzalloc(descs_size, GFP_KERNEL);
5109	if (!descs)
5110		return ERR_PTR(-ENOMEM);
5111
5112	for (descs->ndescs = 0; descs->ndescs < count; descs->ndescs++) {
5113		desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
5114		if (IS_ERR(desc)) {
5115			gpiod_put_array(descs);
5116			return ERR_CAST(desc);
5117		}
5118
5119		descs->desc[descs->ndescs] = desc;
5120
5121		gdev = gpiod_to_gpio_device(desc);
5122		/*
5123		 * If pin hardware number of array member 0 is also 0, select
5124		 * its chip as a candidate for fast bitmap processing path.
5125		 */
5126		if (descs->ndescs == 0 && gpiod_hwgpio(desc) == 0) {
5127			struct gpio_descs *array;
5128
5129			bitmap_size = BITS_TO_LONGS(gdev->ngpio > count ?
5130						    gdev->ngpio : count);
5131
5132			array = krealloc(descs, descs_size +
5133					 struct_size(array_info, invert_mask, 3 * bitmap_size),
5134					 GFP_KERNEL | __GFP_ZERO);
5135			if (!array) {
5136				gpiod_put_array(descs);
5137				return ERR_PTR(-ENOMEM);
5138			}
5139
5140			descs = array;
5141
5142			array_info = (void *)descs + descs_size;
5143			array_info->get_mask = array_info->invert_mask +
5144						  bitmap_size;
5145			array_info->set_mask = array_info->get_mask +
5146						  bitmap_size;
5147
5148			array_info->desc = descs->desc;
5149			array_info->size = count;
5150			array_info->gdev = gdev;
5151			bitmap_set(array_info->get_mask, descs->ndescs,
5152				   count - descs->ndescs);
5153			bitmap_set(array_info->set_mask, descs->ndescs,
5154				   count - descs->ndescs);
5155			descs->info = array_info;
5156		}
5157
5158		/* If there is no cache for fast bitmap processing path, continue */
5159		if (!array_info)
5160			continue;
5161
5162		/* Unmark array members which don't belong to the 'fast' chip */
5163		if (array_info->gdev != gdev) {
5164			__clear_bit(descs->ndescs, array_info->get_mask);
5165			__clear_bit(descs->ndescs, array_info->set_mask);
5166		}
5167		/*
5168		 * Detect array members which belong to the 'fast' chip
5169		 * but their pins are not in hardware order.
5170		 */
5171		else if (gpiod_hwgpio(desc) != descs->ndescs) {
5172			/*
5173			 * Don't use fast path if all array members processed so
5174			 * far belong to the same chip as this one but its pin
5175			 * hardware number is different from its array index.
5176			 */
5177			if (bitmap_full(array_info->get_mask, descs->ndescs)) {
5178				array_info = NULL;
5179			} else {
5180				__clear_bit(descs->ndescs,
5181					    array_info->get_mask);
5182				__clear_bit(descs->ndescs,
5183					    array_info->set_mask);
5184			}
5185		} else {
5186			dflags = READ_ONCE(desc->flags);
5187			/* Exclude open drain or open source from fast output */
5188			if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &dflags) ||
5189			    test_bit(GPIOD_FLAG_OPEN_SOURCE, &dflags))
5190				__clear_bit(descs->ndescs,
5191					    array_info->set_mask);
5192			/* Identify 'fast' pins which require invertion */
5193			if (gpiod_is_active_low(desc))
5194				__set_bit(descs->ndescs,
5195					  array_info->invert_mask);
5196		}
5197	}
5198	if (array_info)
5199		dev_dbg(dev,
5200			"GPIO array info: chip=%s, size=%d, get_mask=%lx, set_mask=%lx, invert_mask=%lx\n",
5201			array_info->gdev->label, array_info->size,
5202			*array_info->get_mask, *array_info->set_mask,
5203			*array_info->invert_mask);
5204	return descs;
5205}
5206EXPORT_SYMBOL_GPL(gpiod_get_array);
5207
5208/**
5209 * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
5210 *                            function
5211 * @dev:	GPIO consumer, can be NULL for system-global GPIOs
5212 * @con_id:	function within the GPIO consumer
5213 * @flags:	optional GPIO initialization flags
5214 *
5215 * This is equivalent to gpiod_get_array(), except that when no GPIO was
5216 * assigned to the requested function it will return NULL.
5217 *
5218 * Returns:
5219 * The GPIO descriptors corresponding to the function @con_id of device
5220 * dev, NULL if no GPIO has been assigned to the requested function,
5221 * or another IS_ERR() code if an error occurred while trying to acquire
5222 * the GPIOs.
5223 */
5224struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
5225							const char *con_id,
5226							enum gpiod_flags flags)
5227{
5228	struct gpio_descs *descs;
5229
5230	descs = gpiod_get_array(dev, con_id, flags);
5231	if (gpiod_not_found(descs))
5232		return NULL;
5233
5234	return descs;
5235}
5236EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
5237
5238/**
5239 * gpiod_put - dispose of a GPIO descriptor
5240 * @desc:	GPIO descriptor to dispose of
5241 *
5242 * No descriptor can be used after gpiod_put() has been called on it.
5243 */
5244void gpiod_put(struct gpio_desc *desc)
5245{
5246	gpiod_free(desc);
5247}
5248EXPORT_SYMBOL_GPL(gpiod_put);
5249
5250/**
5251 * gpiod_put_array - dispose of multiple GPIO descriptors
5252 * @descs:	struct gpio_descs containing an array of descriptors
5253 */
5254void gpiod_put_array(struct gpio_descs *descs)
5255{
5256	unsigned int i;
5257
5258	for (i = 0; i < descs->ndescs; i++)
5259		gpiod_put(descs->desc[i]);
5260
5261	kfree(descs);
5262}
5263EXPORT_SYMBOL_GPL(gpiod_put_array);
5264
5265static int gpio_stub_drv_probe(struct device *dev)
5266{
5267	/*
5268	 * The DT node of some GPIO chips have a "compatible" property, but
5269	 * never have a struct device added and probed by a driver to register
5270	 * the GPIO chip with gpiolib. In such cases, fw_devlink=on will cause
5271	 * the consumers of the GPIO chip to get probe deferred forever because
5272	 * they will be waiting for a device associated with the GPIO chip
5273	 * firmware node to get added and bound to a driver.
5274	 *
5275	 * To allow these consumers to probe, we associate the struct
5276	 * gpio_device of the GPIO chip with the firmware node and then simply
5277	 * bind it to this stub driver.
5278	 */
5279	return 0;
5280}
5281
5282static struct device_driver gpio_stub_drv = {
5283	.name = "gpio_stub_drv",
5284	.bus = &gpio_bus_type,
5285	.probe = gpio_stub_drv_probe,
5286};
5287
5288static int __init gpiolib_dev_init(void)
5289{
5290	int ret;
5291
5292	/* Register GPIO sysfs bus */
5293	ret = bus_register(&gpio_bus_type);
5294	if (ret < 0) {
5295		pr_err("gpiolib: could not register GPIO bus type\n");
5296		return ret;
5297	}
5298
5299	ret = driver_register(&gpio_stub_drv);
5300	if (ret < 0) {
5301		pr_err("gpiolib: could not register GPIO stub driver\n");
5302		bus_unregister(&gpio_bus_type);
5303		return ret;
5304	}
5305
5306	ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, GPIOCHIP_NAME);
5307	if (ret < 0) {
5308		pr_err("gpiolib: failed to allocate char dev region\n");
5309		driver_unregister(&gpio_stub_drv);
5310		bus_unregister(&gpio_bus_type);
5311		return ret;
5312	}
5313
5314	gpiolib_initialized = true;
5315	gpiochip_setup_devs();
5316
5317#if IS_ENABLED(CONFIG_OF_DYNAMIC) && IS_ENABLED(CONFIG_OF_GPIO)
5318	WARN_ON(of_reconfig_notifier_register(&gpio_of_notifier));
5319#endif /* CONFIG_OF_DYNAMIC && CONFIG_OF_GPIO */
5320
5321	return ret;
5322}
5323core_initcall(gpiolib_dev_init);
5324
5325#ifdef CONFIG_DEBUG_FS
5326
5327static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
5328{
5329	bool active_low, is_irq, is_out;
5330	struct gpio_desc *desc;
5331	unsigned int gpio = 0;
5332	struct gpio_chip *gc;
5333	unsigned long flags;
5334	int value;
5335
5336	guard(srcu)(&gdev->srcu);
5337
5338	gc = srcu_dereference(gdev->chip, &gdev->srcu);
5339	if (!gc) {
5340		seq_puts(s, "Underlying GPIO chip is gone\n");
5341		return;
5342	}
5343
5344	for_each_gpio_desc(gc, desc) {
5345		guard(srcu)(&desc->gdev->desc_srcu);
5346		flags = READ_ONCE(desc->flags);
5347		is_irq = test_bit(GPIOD_FLAG_USED_AS_IRQ, &flags);
5348		if (is_irq || test_bit(GPIOD_FLAG_REQUESTED, &flags)) {
5349			gpiod_get_direction(desc);
5350			is_out = test_bit(GPIOD_FLAG_IS_OUT, &flags);
5351			value = gpio_chip_get_value(gc, desc);
5352			active_low = test_bit(GPIOD_FLAG_ACTIVE_LOW, &flags);
5353			seq_printf(s, " gpio-%-3u (%-20.20s|%-20.20s) %s %s %s%s\n",
5354				   gpio, desc->name ?: "", gpiod_get_label(desc),
5355				   is_out ? "out" : "in ",
5356				   value >= 0 ? str_hi_lo(value) : "?  ",
5357				   is_irq ? "IRQ " : "",
5358				   active_low ? "ACTIVE LOW" : "");
5359		} else if (desc->name) {
5360			seq_printf(s, " gpio-%-3u (%-20.20s)\n", gpio, desc->name);
5361		}
5362
5363		gpio++;
5364	}
5365}
5366
5367struct gpiolib_seq_priv {
5368	bool newline;
5369	int idx;
5370};
5371
5372static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
5373{
5374	struct gpiolib_seq_priv *priv;
5375	struct gpio_device *gdev;
5376	loff_t index = *pos;
5377
5378	s->private = NULL;
5379
5380	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
5381	if (!priv)
5382		return NULL;
5383
5384	s->private = priv;
5385	if (*pos > 0)
5386		priv->newline = true;
5387	priv->idx = srcu_read_lock(&gpio_devices_srcu);
5388
5389	list_for_each_entry_srcu(gdev, &gpio_devices, list,
5390				 srcu_read_lock_held(&gpio_devices_srcu)) {
5391		if (index-- == 0)
5392			return gdev;
5393	}
5394
5395	return NULL;
5396}
5397
5398static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
5399{
5400	struct gpiolib_seq_priv *priv = s->private;
5401	struct gpio_device *gdev = v, *next;
5402
5403	next = list_entry_rcu(gdev->list.next, struct gpio_device, list);
5404	gdev = &next->list == &gpio_devices ? NULL : next;
5405	priv->newline = true;
5406	++*pos;
5407
5408	return gdev;
5409}
5410
5411static void gpiolib_seq_stop(struct seq_file *s, void *v)
5412{
5413	struct gpiolib_seq_priv *priv;
5414
5415	priv = s->private;
5416	if (!priv)
5417		return;
5418
5419	srcu_read_unlock(&gpio_devices_srcu, priv->idx);
5420	kfree(priv);
5421}
5422
5423static int gpiolib_seq_show(struct seq_file *s, void *v)
5424{
5425	struct gpiolib_seq_priv *priv = s->private;
5426	struct gpio_device *gdev = v;
5427	struct gpio_chip *gc;
5428	struct device *parent;
5429
5430	if (priv->newline)
5431		seq_putc(s, '\n');
5432
5433	guard(srcu)(&gdev->srcu);
5434
5435	gc = srcu_dereference(gdev->chip, &gdev->srcu);
5436	if (!gc) {
5437		seq_printf(s, "%s: (dangling chip)\n", dev_name(&gdev->dev));
5438		return 0;
5439	}
5440
5441	seq_printf(s, "%s: %u GPIOs", dev_name(&gdev->dev), gdev->ngpio);
5442	parent = gc->parent;
5443	if (parent)
5444		seq_printf(s, ", parent: %s/%s",
5445			   parent->bus ? parent->bus->name : "no-bus",
5446			   dev_name(parent));
5447	if (gc->label)
5448		seq_printf(s, ", %s", gc->label);
5449	if (gc->can_sleep)
5450		seq_printf(s, ", can sleep");
5451	seq_printf(s, ":\n");
5452
5453	if (gc->dbg_show)
5454		gc->dbg_show(s, gc);
5455	else
5456		gpiolib_dbg_show(s, gdev);
5457
5458	return 0;
5459}
5460
5461static const struct seq_operations gpiolib_sops = {
5462	.start = gpiolib_seq_start,
5463	.next = gpiolib_seq_next,
5464	.stop = gpiolib_seq_stop,
5465	.show = gpiolib_seq_show,
5466};
5467DEFINE_SEQ_ATTRIBUTE(gpiolib);
5468
5469static int __init gpiolib_debugfs_init(void)
5470{
5471	/* /sys/kernel/debug/gpio */
5472	debugfs_create_file("gpio", 0444, NULL, NULL, &gpiolib_fops);
5473	return 0;
5474}
5475subsys_initcall(gpiolib_debugfs_init);
5476
5477#endif	/* DEBUG_FS */
~/ Read-only file preview.