gpiolib.c 87.5 KB
Newer Older
1 2
#include <linux/kernel.h>
#include <linux/module.h>
3
#include <linux/interrupt.h>
4 5
#include <linux/irq.h>
#include <linux/spinlock.h>
6
#include <linux/list.h>
David Brownell's avatar
David Brownell committed
7 8 9 10 11
#include <linux/device.h>
#include <linux/err.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/gpio.h>
12
#include <linux/of_gpio.h>
13
#include <linux/idr.h>
14
#include <linux/slab.h>
15
#include <linux/acpi.h>
16
#include <linux/gpio/driver.h>
17
#include <linux/gpio/machine.h>
18
#include <linux/pinctrl/consumer.h>
19
#include <linux/idr.h>
20 21 22
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
23
#include <linux/compat.h>
24
#include <linux/anon_inodes.h>
25
#include <uapi/linux/gpio.h>
26

27 28
#include "gpiolib.h"

29 30
#define CREATE_TRACE_POINTS
#include <trace/events/gpio.h>
31

32
/* Implementation infrastructure for GPIO interfaces.
33
 *
34 35 36
 * The GPIO programming interface allows for inlining speed-critical
 * get/set operations for common cases, so that access to SOC-integrated
 * GPIOs can sometimes cost only an instruction or two per bit.
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
 */


/* When debugging, extend minimal trust to callers and platform code.
 * Also emit diagnostic messages that may help initial bringup, when
 * board setup or driver bugs are most common.
 *
 * Otherwise, minimize overhead in what may be bitbanging codepaths.
 */
#ifdef	DEBUG
#define	extra_checks	1
#else
#define	extra_checks	0
#endif

52 53
/* Device and char device-related information */
static DEFINE_IDA(gpio_ida);
54 55 56 57 58
static dev_t gpio_devt;
#define GPIO_DEV_MAX 256 /* 256 GPIO chip devices supported */
static struct bus_type gpio_bus_type = {
	.name = "gpio",
};
59

60 61 62 63
/* gpio_lock prevents conflicts during gpio_desc[] table updates.
 * While any GPIO is requested, its gpio_chip is not removable;
 * each GPIO's "requested" flag serves as a lock and refcount.
 */
64
DEFINE_SPINLOCK(gpio_lock);
65

66 67
static DEFINE_MUTEX(gpio_lookup_lock);
static LIST_HEAD(gpio_lookup_list);
68
LIST_HEAD(gpio_devices);
69 70 71 72

static void gpiochip_free_hogs(struct gpio_chip *chip);
static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip);

73
static bool gpiolib_initialized;
74

75 76 77 78 79
static inline void desc_set_label(struct gpio_desc *d, const char *label)
{
	d->label = label;
}

80 81 82
/**
 * Convert a GPIO number to its descriptor
 */
83
struct gpio_desc *gpio_to_desc(unsigned gpio)
84
{
85
	struct gpio_device *gdev;
86 87 88 89
	unsigned long flags;

	spin_lock_irqsave(&gpio_lock, flags);

90
	list_for_each_entry(gdev, &gpio_devices, list) {
91 92
		if (gdev->base <= gpio &&
		    gdev->base + gdev->ngpio > gpio) {
93
			spin_unlock_irqrestore(&gpio_lock, flags);
94
			return &gdev->descs[gpio - gdev->base];
95 96 97 98 99
		}
	}

	spin_unlock_irqrestore(&gpio_lock, flags);

100 101 102
	if (!gpio_is_valid(gpio))
		WARN(1, "invalid GPIO %d\n", gpio);

103
	return NULL;
104
}
105
EXPORT_SYMBOL_GPL(gpio_to_desc);
106

107
/**
108
 * Get the GPIO descriptor corresponding to the given hw number for this chip.
109
 */
110 111
struct gpio_desc *gpiochip_get_desc(struct gpio_chip *chip,
				    u16 hwnum)
112
{
113 114 115
	struct gpio_device *gdev = chip->gpiodev;

	if (hwnum >= gdev->ngpio)
116
		return ERR_PTR(-EINVAL);
117

118
	return &gdev->descs[hwnum];
119
}
120 121 122 123 124 125

/**
 * Convert a GPIO descriptor to the integer namespace.
 * This should disappear in the future but is needed since we still
 * use GPIO numbers for error messages and sysfs nodes
 */
126
int desc_to_gpio(const struct gpio_desc *desc)
127
{
128
	return desc->gdev->base + (desc - &desc->gdev->descs[0]);
129
}
130
EXPORT_SYMBOL_GPL(desc_to_gpio);
131 132


133 134 135 136 137
/**
 * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
 * @desc:	descriptor to return the chip of
 */
struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
138
{
139 140 141
	if (!desc || !desc->gdev || !desc->gdev->chip)
		return NULL;
	return desc->gdev->chip;
142
}
143
EXPORT_SYMBOL_GPL(gpiod_to_chip);
144

145 146 147
/* dynamic allocation of GPIOs, e.g. on a hotplugged device */
static int gpiochip_find_base(int ngpio)
{
148
	struct gpio_device *gdev;
149
	int base = ARCH_NR_GPIOS - ngpio;
150

151
	list_for_each_entry_reverse(gdev, &gpio_devices, list) {
152
		/* found a free space? */
153
		if (gdev->base + gdev->ngpio <= base)
154 155 156
			break;
		else
			/* nope, check the space right before the chip */
157
			base = gdev->base - ngpio;
158 159
	}

160
	if (gpio_is_valid(base)) {
161
		pr_debug("%s: found new base at %d\n", __func__, base);
162 163 164 165
		return base;
	} else {
		pr_err("%s: cannot find free range\n", __func__);
		return -ENOSPC;
Anton Vorontsov's avatar
Anton Vorontsov committed
166 167 168
	}
}

169 170 171 172 173 174 175 176
/**
 * gpiod_get_direction - return the current direction of a GPIO
 * @desc:	GPIO to get the direction of
 *
 * Return GPIOF_DIR_IN or GPIOF_DIR_OUT, or an error code in case of error.
 *
 * This function may sleep if gpiod_cansleep() is true.
 */
177
int gpiod_get_direction(struct gpio_desc *desc)
178 179
{
	struct gpio_chip	*chip;
180
	unsigned		offset;
181 182
	int			status = -EINVAL;

183 184
	chip = gpiod_to_chip(desc);
	offset = gpio_chip_hwgpio(desc);
185 186 187 188

	if (!chip->get_direction)
		return status;

189
	status = chip->get_direction(chip, offset);
190 191 192
	if (status > 0) {
		/* GPIOF_DIR_IN, or other positive */
		status = 1;
193
		clear_bit(FLAG_IS_OUT, &desc->flags);
194 195 196
	}
	if (status == 0) {
		/* GPIOF_DIR_OUT */
197
		set_bit(FLAG_IS_OUT, &desc->flags);
198 199 200
	}
	return status;
}
201
EXPORT_SYMBOL_GPL(gpiod_get_direction);
202

203 204
/*
 * Add a new chip to the global chips list, keeping the list of chips sorted
205
 * by range(means [base, base + ngpio - 1]) order.
206 207 208 209
 *
 * Return -EBUSY if the new chip overlaps with some other chip's integer
 * space.
 */
210
static int gpiodev_add_to_list(struct gpio_device *gdev)
211
{
212
	struct gpio_device *prev, *next;
213

214
	if (list_empty(&gpio_devices)) {
215
		/* initial entry in list */
216
		list_add_tail(&gdev->list, &gpio_devices);
217
		return 0;
218 219
	}

220 221 222 223 224
	next = list_entry(gpio_devices.next, struct gpio_device, list);
	if (gdev->base + gdev->ngpio <= next->base) {
		/* add before first entry */
		list_add(&gdev->list, &gpio_devices);
		return 0;
225 226
	}

227 228 229 230
	prev = list_entry(gpio_devices.prev, struct gpio_device, list);
	if (prev->base + prev->ngpio <= gdev->base) {
		/* add behind last entry */
		list_add_tail(&gdev->list, &gpio_devices);
231
		return 0;
232 233
	}

234 235 236 237
	list_for_each_entry_safe(prev, next, &gpio_devices, list) {
		/* at the end of the list */
		if (&next->list == &gpio_devices)
			break;
238

239 240 241 242 243 244 245 246 247 248
		/* add between prev and next */
		if (prev->base + prev->ngpio <= gdev->base
				&& gdev->base + gdev->ngpio <= next->base) {
			list_add(&gdev->list, &prev->list);
			return 0;
		}
	}

	dev_err(&gdev->dev, "GPIO integer space overlap, cannot add chip\n");
	return -EBUSY;
249 250
}

251 252 253 254 255
/**
 * Convert a GPIO name to its descriptor
 */
static struct gpio_desc *gpio_name_to_desc(const char * const name)
{
256
	struct gpio_device *gdev;
257 258 259 260
	unsigned long flags;

	spin_lock_irqsave(&gpio_lock, flags);

261
	list_for_each_entry(gdev, &gpio_devices, list) {
262 263
		int i;

264 265
		for (i = 0; i != gdev->ngpio; ++i) {
			struct gpio_desc *desc = &gdev->descs[i];
266

267
			if (!desc->name || !name)
268 269
				continue;

270
			if (!strcmp(desc->name, name)) {
271
				spin_unlock_irqrestore(&gpio_lock, flags);
272
				return desc;
273 274 275 276 277 278 279 280 281
			}
		}
	}

	spin_unlock_irqrestore(&gpio_lock, flags);

	return NULL;
}

282 283 284 285
/*
 * Takes the names from gc->names and checks if they are all unique. If they
 * are, they are assigned to their gpio descriptors.
 *
286
 * Warning if one of the names is already used for a different GPIO.
287 288 289
 */
static int gpiochip_set_desc_names(struct gpio_chip *gc)
{
290
	struct gpio_device *gdev = gc->gpiodev;
291 292 293 294 295 296 297 298 299 300
	int i;

	if (!gc->names)
		return 0;

	/* First check all names if they are unique */
	for (i = 0; i != gc->ngpio; ++i) {
		struct gpio_desc *gpio;

		gpio = gpio_name_to_desc(gc->names[i]);
301
		if (gpio)
302
			dev_warn(&gdev->dev,
303
				 "Detected name collision for GPIO name '%s'\n",
304
				 gc->names[i]);
305 306 307 308
	}

	/* Then add all names to the GPIO descriptors */
	for (i = 0; i != gc->ngpio; ++i)
309
		gdev->descs[i].name = gc->names[i];
310 311 312 313

	return 0;
}

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
/*
 * GPIO line handle management
 */

/**
 * struct linehandle_state - contains the state of a userspace handle
 * @gdev: the GPIO device the handle pertains to
 * @label: consumer label used to tag descriptors
 * @descs: the GPIO descriptors held by this handle
 * @numdescs: the number of descriptors held in the descs array
 */
struct linehandle_state {
	struct gpio_device *gdev;
	const char *label;
	struct gpio_desc *descs[GPIOHANDLES_MAX];
	u32 numdescs;
};

static long linehandle_ioctl(struct file *filep, unsigned int cmd,
			     unsigned long arg)
{
	struct linehandle_state *lh = filep->private_data;
	void __user *ip = (void __user *)arg;
	struct gpiohandle_data ghd;
	int i;

	if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
		int val;

		/* TODO: check if descriptors are really input */
		for (i = 0; i < lh->numdescs; i++) {
			val = gpiod_get_value_cansleep(lh->descs[i]);
			if (val < 0)
				return val;
			ghd.values[i] = val;
		}

		if (copy_to_user(ip, &ghd, sizeof(ghd)))
			return -EFAULT;

		return 0;
	} else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
		int vals[GPIOHANDLES_MAX];

		/* TODO: check if descriptors are really output */
		if (copy_from_user(&ghd, ip, sizeof(ghd)))
			return -EFAULT;

		/* Clamp all values to [0,1] */
		for (i = 0; i < lh->numdescs; i++)
			vals[i] = !!ghd.values[i];

		/* Reuse the array setting function */
		gpiod_set_array_value_complex(false,
					      true,
					      lh->numdescs,
					      lh->descs,
					      vals);
		return 0;
	}
	return -EINVAL;
}

#ifdef CONFIG_COMPAT
static long linehandle_ioctl_compat(struct file *filep, unsigned int cmd,
			     unsigned long arg)
{
	return linehandle_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
}
#endif

static int linehandle_release(struct inode *inode, struct file *filep)
{
	struct linehandle_state *lh = filep->private_data;
	struct gpio_device *gdev = lh->gdev;
	int i;

	for (i = 0; i < lh->numdescs; i++)
		gpiod_free(lh->descs[i]);
	kfree(lh->label);
	kfree(lh);
	put_device(&gdev->dev);
	return 0;
}

static const struct file_operations linehandle_fileops = {
	.release = linehandle_release,
	.owner = THIS_MODULE,
	.llseek = noop_llseek,
	.unlocked_ioctl = linehandle_ioctl,
#ifdef CONFIG_COMPAT
	.compat_ioctl = linehandle_ioctl_compat,
#endif
};

static int linehandle_create(struct gpio_device *gdev, void __user *ip)
{
	struct gpiohandle_request handlereq;
	struct linehandle_state *lh;
	int fd, i, ret;

	if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
		return -EFAULT;
	if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
		return -EINVAL;

	lh = kzalloc(sizeof(*lh), GFP_KERNEL);
	if (!lh)
		return -ENOMEM;
	lh->gdev = gdev;
	get_device(&gdev->dev);

	/* Make sure this is terminated */
	handlereq.consumer_label[sizeof(handlereq.consumer_label)-1] = '\0';
	if (strlen(handlereq.consumer_label)) {
		lh->label = kstrdup(handlereq.consumer_label,
				    GFP_KERNEL);
		if (!lh->label) {
			ret = -ENOMEM;
			goto out_free_lh;
		}
	}

	/* Request each GPIO */
	for (i = 0; i < handlereq.lines; i++) {
		u32 offset = handlereq.lineoffsets[i];
		u32 lflags = handlereq.flags;
		struct gpio_desc *desc;

		desc = &gdev->descs[offset];
		ret = gpiod_request(desc, lh->label);
		if (ret)
			goto out_free_descs;
		lh->descs[i] = desc;

		if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
			set_bit(FLAG_ACTIVE_LOW, &desc->flags);
		if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
			set_bit(FLAG_OPEN_DRAIN, &desc->flags);
		if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
			set_bit(FLAG_OPEN_SOURCE, &desc->flags);

		/*
		 * Lines have to be requested explicitly for input
		 * or output, else the line will be treated "as is".
		 */
		if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
			int val = !!handlereq.default_values[i];

			ret = gpiod_direction_output(desc, val);
			if (ret)
				goto out_free_descs;
		} else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
			ret = gpiod_direction_input(desc);
			if (ret)
				goto out_free_descs;
		}
		dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
			offset);
	}
	lh->numdescs = handlereq.lines;

	fd = anon_inode_getfd("gpio-linehandle",
			      &linehandle_fileops,
			      lh,
			      O_RDONLY | O_CLOEXEC);
	if (fd < 0) {
		ret = fd;
		goto out_free_descs;
	}

	handlereq.fd = fd;
	if (copy_to_user(ip, &handlereq, sizeof(handlereq)))
		return -EFAULT;

	dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
		lh->numdescs);

	return 0;

out_free_descs:
	for (; i >= 0; i--)
		gpiod_free(lh->descs[i]);
	kfree(lh->label);
out_free_lh:
	kfree(lh);
	put_device(&gdev->dev);
	return ret;
}

504 505 506 507 508 509 510
/**
 * gpio_ioctl() - ioctl handler for the GPIO chardev
 */
static long gpio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
	struct gpio_device *gdev = filp->private_data;
	struct gpio_chip *chip = gdev->chip;
511
	void __user *ip = (void __user *)arg;
512 513 514 515 516

	/* We fail any subsequent ioctl():s when the chip is gone */
	if (!chip)
		return -ENODEV;

517
	/* Fill in the struct and pass to userspace */
518
	if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
519 520
		struct gpiochip_info chipinfo;

521 522 523
		strncpy(chipinfo.name, dev_name(&gdev->dev),
			sizeof(chipinfo.name));
		chipinfo.name[sizeof(chipinfo.name)-1] = '\0';
524 525 526
		strncpy(chipinfo.label, gdev->label,
			sizeof(chipinfo.label));
		chipinfo.label[sizeof(chipinfo.label)-1] = '\0';
527
		chipinfo.lines = gdev->ngpio;
528 529 530
		if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
			return -EFAULT;
		return 0;
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
	} else if (cmd == GPIO_GET_LINEINFO_IOCTL) {
		struct gpioline_info lineinfo;
		struct gpio_desc *desc;

		if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
			return -EFAULT;
		if (lineinfo.line_offset > gdev->ngpio)
			return -EINVAL;

		desc = &gdev->descs[lineinfo.line_offset];
		if (desc->name) {
			strncpy(lineinfo.name, desc->name,
				sizeof(lineinfo.name));
			lineinfo.name[sizeof(lineinfo.name)-1] = '\0';
		} else {
			lineinfo.name[0] = '\0';
		}
		if (desc->label) {
549 550 551
			strncpy(lineinfo.consumer, desc->label,
				sizeof(lineinfo.consumer));
			lineinfo.consumer[sizeof(lineinfo.consumer)-1] = '\0';
552
		} else {
553
			lineinfo.consumer[0] = '\0';
554 555 556 557 558 559 560
		}

		/*
		 * Userspace only need to know that the kernel is using
		 * this GPIO so it can't use it.
		 */
		lineinfo.flags = 0;
561 562 563 564 565
		if (test_bit(FLAG_REQUESTED, &desc->flags) ||
		    test_bit(FLAG_IS_HOGGED, &desc->flags) ||
		    test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
		    test_bit(FLAG_EXPORT, &desc->flags) ||
		    test_bit(FLAG_SYSFS, &desc->flags))
566
			lineinfo.flags |= GPIOLINE_FLAG_KERNEL;
567
		if (test_bit(FLAG_IS_OUT, &desc->flags))
568
			lineinfo.flags |= GPIOLINE_FLAG_IS_OUT;
569
		if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
570
			lineinfo.flags |= GPIOLINE_FLAG_ACTIVE_LOW;
571
		if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
572
			lineinfo.flags |= GPIOLINE_FLAG_OPEN_DRAIN;
573
		if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
574 575 576 577 578
			lineinfo.flags |= GPIOLINE_FLAG_OPEN_SOURCE;

		if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
			return -EFAULT;
		return 0;
579 580
	} else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
		return linehandle_create(gdev, ip);
581 582 583 584
	}
	return -EINVAL;
}

585 586 587 588 589 590 591 592
#ifdef CONFIG_COMPAT
static long gpio_ioctl_compat(struct file *filp, unsigned int cmd,
			      unsigned long arg)
{
	return gpio_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
}
#endif

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
/**
 * gpio_chrdev_open() - open the chardev for ioctl operations
 * @inode: inode for this chardev
 * @filp: file struct for storing private data
 * Returns 0 on success
 */
static int gpio_chrdev_open(struct inode *inode, struct file *filp)
{
	struct gpio_device *gdev = container_of(inode->i_cdev,
					      struct gpio_device, chrdev);

	/* Fail on open if the backing gpiochip is gone */
	if (!gdev || !gdev->chip)
		return -ENODEV;
	get_device(&gdev->dev);
	filp->private_data = gdev;
	return 0;
}

/**
 * gpio_chrdev_release() - close chardev after ioctl operations
 * @inode: inode for this chardev
 * @filp: file struct for storing private data
 * Returns 0 on success
 */
static int gpio_chrdev_release(struct inode *inode, struct file *filp)
{
	struct gpio_device *gdev = container_of(inode->i_cdev,
					      struct gpio_device, chrdev);

	if (!gdev)
		return -ENODEV;
	put_device(&gdev->dev);
	return 0;
}


static const struct file_operations gpio_fileops = {
	.release = gpio_chrdev_release,
	.open = gpio_chrdev_open,
	.owner = THIS_MODULE,
	.llseek = noop_llseek,
	.unlocked_ioctl = gpio_ioctl,
636 637 638
#ifdef CONFIG_COMPAT
	.compat_ioctl = gpio_ioctl_compat,
#endif
639 640
};

641 642 643 644
static void gpiodevice_release(struct device *dev)
{
	struct gpio_device *gdev = dev_get_drvdata(dev);

645
	cdev_del(&gdev->chrdev);
646 647
	list_del(&gdev->list);
	ida_simple_remove(&gpio_ida, gdev->id);
648 649
	kfree(gdev->label);
	kfree(gdev->descs);
650
	kfree(gdev);
651 652
}

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
static int gpiochip_setup_dev(struct gpio_device *gdev)
{
	int status;

	cdev_init(&gdev->chrdev, &gpio_fileops);
	gdev->chrdev.owner = THIS_MODULE;
	gdev->chrdev.kobj.parent = &gdev->dev.kobj;
	gdev->dev.devt = MKDEV(MAJOR(gpio_devt), gdev->id);
	status = cdev_add(&gdev->chrdev, gdev->dev.devt, 1);
	if (status < 0)
		chip_warn(gdev->chip, "failed to add char device %d:%d\n",
			  MAJOR(gpio_devt), gdev->id);
	else
		chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
			 MAJOR(gpio_devt), gdev->id);
	status = device_add(&gdev->dev);
	if (status)
		goto err_remove_chardev;

	status = gpiochip_sysfs_register(gdev);
	if (status)
		goto err_remove_device;

	/* From this point, the .release() function cleans up gpio_device */
	gdev->dev.release = gpiodevice_release;
	get_device(&gdev->dev);
	pr_debug("%s: registered GPIOs %d to %d on device: %s (%s)\n",
		 __func__, gdev->base, gdev->base + gdev->ngpio - 1,
		 dev_name(&gdev->dev), gdev->chip->label ? : "generic");

	return 0;

err_remove_device:
	device_del(&gdev->dev);
err_remove_chardev:
	cdev_del(&gdev->chrdev);
	return status;
}

static void gpiochip_setup_devs(void)
{
	struct gpio_device *gdev;
	int err;

	list_for_each_entry(gdev, &gpio_devices, list) {
		err = gpiochip_setup_dev(gdev);
		if (err)
			pr_err("%s: Failed to initialize gpio device (%d)\n",
			       dev_name(&gdev->dev), err);
	}
}

705
/**
706
 * gpiochip_add_data() - register a gpio_chip
707
 * @chip: the chip to register, with chip->base initialized
708
 * Context: potentially before irqs will work
709 710 711 712
 *
 * Returns a negative errno if the chip can't be registered, such as
 * because the chip->base is invalid or already associated with a
 * different chip.  Otherwise it returns zero as a success code.
713
 *
714
 * When gpiochip_add_data() is called very early during boot, so that GPIOs
715
 * can be freely used, the chip->parent device must be registered before
David Brownell's avatar
David Brownell committed
716 717 718
 * the gpio framework's arch_initcall().  Otherwise sysfs initialization
 * for GPIOs will fail rudely.
 *
719 720 721
 * gpiochip_add_data() must only be called after gpiolib initialization,
 * ie after core_initcall().
 *
722 723
 * If chip->base is negative, this requests dynamic assignment of
 * a range of valid GPIOs.
724
 */
725
int gpiochip_add_data(struct gpio_chip *chip, void *data)
726 727 728
{
	unsigned long	flags;
	int		status = 0;
729
	unsigned	i;
730
	int		base = chip->base;
731
	struct gpio_device *gdev;
732

733 734 735 736
	/*
	 * First: allocate and populate the internal stat container, and
	 * set up the struct device.
	 */
737
	gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
738
	if (!gdev)
739
		return -ENOMEM;
740
	gdev->dev.bus = &gpio_bus_type;
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
	gdev->chip = chip;
	chip->gpiodev = gdev;
	if (chip->parent) {
		gdev->dev.parent = chip->parent;
		gdev->dev.of_node = chip->parent->of_node;
	} else {
#ifdef CONFIG_OF_GPIO
	/* If the gpiochip has an assigned OF node this takes precedence */
		if (chip->of_node)
			gdev->dev.of_node = chip->of_node;
#endif
	}
	gdev->id = ida_simple_get(&gpio_ida, 0, 0, GFP_KERNEL);
	if (gdev->id < 0) {
		status = gdev->id;
		goto err_free_gdev;
	}
	dev_set_name(&gdev->dev, "gpiochip%d", gdev->id);
	device_initialize(&gdev->dev);
	dev_set_drvdata(&gdev->dev, gdev);
	if (chip->parent && chip->parent->driver)
		gdev->owner = chip->parent->driver->owner;
	else if (chip->owner)
		/* TODO: remove chip->owner */
		gdev->owner = chip->owner;
	else
		gdev->owner = THIS_MODULE;
768

769
	gdev->descs = kcalloc(chip->ngpio, sizeof(gdev->descs[0]), GFP_KERNEL);
770
	if (!gdev->descs) {
771 772 773 774
		status = -ENOMEM;
		goto err_free_gdev;
	}

775 776
	if (chip->ngpio == 0) {
		chip_err(chip, "tried to insert a GPIO chip with zero lines\n");
777
		status = -EINVAL;
778
		goto err_free_descs;
779
	}
780 781

	if (chip->label)
782
		gdev->label = kstrdup(chip->label, GFP_KERNEL);
783
	else
784
		gdev->label = kstrdup("unknown", GFP_KERNEL);
785 786
	if (!gdev->label) {
		status = -ENOMEM;
787
		goto err_free_descs;
788 789
	}

790
	gdev->ngpio = chip->ngpio;
791
	gdev->data = data;
792

793 794
	spin_lock_irqsave(&gpio_lock, flags);

795 796 797 798 799 800 801
	/*
	 * TODO: this allocates a Linux GPIO number base in the global
	 * GPIO numberspace for this chip. In the long run we want to
	 * get *rid* of this numberspace and use only descriptors, but
	 * it may be a pipe dream. It will not happen before we get rid
	 * of the sysfs interface anyways.
	 */
802 803 804 805
	if (base < 0) {
		base = gpiochip_find_base(chip->ngpio);
		if (base < 0) {
			status = base;
806
			spin_unlock_irqrestore(&gpio_lock, flags);
807
			goto err_free_label;
808
		}
809 810 811 812 813 814
		/*
		 * TODO: it should not be necessary to reflect the assigned
		 * base outside of the GPIO subsystem. Go over drivers and
		 * see if anyone makes use of this, else drop this and assign
		 * a poison instead.
		 */
815 816
		chip->base = base;
	}
817
	gdev->base = base;
818

819
	status = gpiodev_add_to_list(gdev);
820 821
	if (status) {
		spin_unlock_irqrestore(&gpio_lock, flags);
822
		goto err_free_label;
823
	}
824

825 826
	spin_unlock_irqrestore(&gpio_lock, flags);

827
	for (i = 0; i < chip->ngpio; i++) {
828
		struct gpio_desc *desc = &gdev->descs[i];
829

830
		desc->gdev = gdev;
831 832 833 834 835 836 837
		/*
		 * REVISIT: most hardware initializes GPIOs as inputs
		 * (often with pullups enabled) so power usage is
		 * minimized. Linux code should set the gpio direction
		 * first thing; but until it does, and in case
		 * chip->get_direction is not set, we may expose the
		 * wrong direction in sysfs.
838
		 */
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855

		if (chip->get_direction) {
			/*
			 * If we have .get_direction, set up the initial
			 * direction flag from the hardware.
			 */
			int dir = chip->get_direction(chip, i);

			if (!dir)
				set_bit(FLAG_IS_OUT, &desc->flags);
		} else if (!chip->direction_input) {
			/*
			 * If the chip lacks the .direction_input callback
			 * we logically assume all lines are outputs.
			 */
			set_bit(FLAG_IS_OUT, &desc->flags);
		}
856
	}
857

858
#ifdef CONFIG_PINCTRL
859
	INIT_LIST_HEAD(&gdev->pin_ranges);
860 861
#endif

862 863 864 865
	status = gpiochip_set_desc_names(chip);
	if (status)
		goto err_remove_from_list;

866 867 868 869
	status = of_gpiochip_add(chip);
	if (status)
		goto err_remove_chip;

870
	acpi_gpiochip_add(chip);
871

872 873 874 875 876
	/*
	 * By first adding the chardev, and then adding the device,
	 * we get a device node entry in sysfs under
	 * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
	 * coldplug of device nodes and other udev business.
877 878
	 * We can do this only if gpiolib has been initialized.
	 * Otherwise, defer until later.
879
	 */
880 881 882 883 884
	if (gpiolib_initialized) {
		status = gpiochip_setup_dev(gdev);
		if (status)
			goto err_remove_chip;
	}
885
	return 0;
886

887 888
err_remove_chip:
	acpi_gpiochip_remove(chip);
889
	gpiochip_free_hogs(chip);
890
	of_gpiochip_remove(chip);
891
err_remove_from_list:
892
	spin_lock_irqsave(&gpio_lock, flags);
893
	list_del(&gdev->list);
894
	spin_unlock_irqrestore(&gpio_lock, flags);
895 896 897 898
err_free_label:
	kfree(gdev->label);
err_free_descs:
	kfree(gdev->descs);
899 900
err_free_gdev:
	ida_simple_remove(&gpio_ida, gdev->id);
901
	/* failures here can mean systems won't boot... */
902
	pr_err("%s: GPIOs %d..%d (%s) failed to register\n", __func__,
903 904 905
	       gdev->base, gdev->base + gdev->ngpio - 1,
	       chip->label ? : "generic");
	kfree(gdev);
906 907
	return status;
}
908
EXPORT_SYMBOL_GPL(gpiochip_add_data);
909

910 911 912 913 914 915 916 917 918
/**
 * gpiochip_get_data() - get per-subdriver data for the chip
 */
void *gpiochip_get_data(struct gpio_chip *chip)
{
	return chip->gpiodev->data;
}
EXPORT_SYMBOL_GPL(gpiochip_get_data);

919 920 921 922 923 924
/**
 * gpiochip_remove() - unregister a gpio_chip
 * @chip: the chip to unregister
 *
 * A gpio_chip with any GPIOs still requested may not be removed.
 */
925
void gpiochip_remove(struct gpio_chip *chip)
926
{
927
	struct gpio_device *gdev = chip->gpiodev;
Johan Hovold's avatar
Johan Hovold committed
928
	struct gpio_desc *desc;
929
	unsigned long	flags;
930
	unsigned	i;
Johan Hovold's avatar
Johan Hovold committed
931
	bool		requested = false;
932

933
	/* FIXME: should the legacy sysfs handling be moved to gpio_device? */
934
	gpiochip_sysfs_unregister(gdev);
935 936
	/* Numb the device, cancelling all outstanding operations */
	gdev->chip = NULL;
937
	gpiochip_irqchip_remove(chip);
938
	acpi_gpiochip_remove(chip);
939
	gpiochip_remove_pin_ranges(chip);
940
	gpiochip_free_hogs(chip);
941
	of_gpiochip_remove(chip);
942 943 944 945 946
	/*
	 * We accept no more calls into the driver from this point, so
	 * NULL the driver data pointer
	 */
	gdev->data = NULL;
947

948
	spin_lock_irqsave(&gpio_lock, flags);
949
	for (i = 0; i < gdev->ngpio; i++) {
950
		desc = &gdev->descs[i];
Johan Hovold's avatar
Johan Hovold committed
951 952
		if (test_bit(FLAG_REQUESTED, &desc->flags))
			requested = true;
953 954
	}
	spin_unlock_irqrestore(&gpio_lock, flags);
955

Johan Hovold's avatar
Johan Hovold committed
956
	if (requested)
957
		dev_crit(&gdev->dev,
958
			 "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
Johan Hovold's avatar
Johan Hovold committed
959

960 961 962 963 964 965 966
	/*
	 * The gpiochip side puts its use of the device to rest here:
	 * if there are no userspace clients, the chardev and device will
	 * be removed, else it will be dangling until the last user is
	 * gone.
	 */
	put_device(&gdev->dev);
967 968 969
}
EXPORT_SYMBOL_GPL(gpiochip_remove);

970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
static void devm_gpio_chip_release(struct device *dev, void *res)
{
	struct gpio_chip *chip = *(struct gpio_chip **)res;

	gpiochip_remove(chip);
}

static int devm_gpio_chip_match(struct device *dev, void *res, void *data)

{
	struct gpio_chip **r = res;

	if (!r || !*r) {
		WARN_ON(!r || !*r);
		return 0;
	}

	return *r == data;
}

/**
 * devm_gpiochip_add_data() - Resource manager piochip_add_data()
 * @dev: the device pointer on which irq_chip belongs to.
 * @chip: the chip to register, with chip->base initialized
 * Context: potentially before irqs will work
 *
 * Returns a negative errno if the chip can't be registered, such as
 * because the chip->base is invalid or already associated with a
 * different chip.  Otherwise it returns zero as a success code.
 *
 * The gpio chip automatically be released when the device is unbound.
 */
int devm_gpiochip_add_data(struct device *dev, struct gpio_chip *chip,
			   void *data)
{
	struct gpio_chip **ptr;
	int ret;

	ptr = devres_alloc(devm_gpio_chip_release, sizeof(*ptr),
			     GFP_KERNEL);
	if (!ptr)
		return -ENOMEM;

	ret = gpiochip_add_data(chip, data);
	if (ret < 0) {
		devres_free(ptr);
		return ret;
	}

	*ptr = chip;
	devres_add(dev, ptr);

	return 0;
}
EXPORT_SYMBOL_GPL(devm_gpiochip_add_data);

/**
 * devm_gpiochip_remove() - Resource manager of gpiochip_remove()
 * @dev: device for which which resource was allocated
 * @chip: the chip to remove
 *
 * A gpio_chip with any GPIOs still requested may not be removed.
 */
void devm_gpiochip_remove(struct device *dev, struct gpio_chip *chip)
{
	int ret;

	ret = devres_release(dev, devm_gpio_chip_release,
			     devm_gpio_chip_match, chip);
	if (!ret)
		WARN_ON(ret);
}
EXPORT_SYMBOL_GPL(devm_gpiochip_remove);

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
/**
 * gpiochip_find() - iterator for locating a specific gpio_chip
 * @data: data to pass to match function
 * @callback: Callback function to check gpio_chip
 *
 * Similar to bus_find_device.  It returns a reference to a gpio_chip as
 * determined by a user supplied @match callback.  The callback should return
 * 0 if the device doesn't match and non-zero if it does.  If the callback is
 * non-zero, this function will return to the caller and not iterate over any
 * more gpio_chips.
 */
1055
struct gpio_chip *gpiochip_find(void *data,
1056
				int (*match)(struct gpio_chip *chip,
1057
					     void *data))
1058
{
1059
	struct gpio_device *gdev;
1060
	struct gpio_chip *chip;
1061 1062 1063
	unsigned long flags;

	spin_lock_irqsave(&gpio_lock, flags);
1064 1065
	list_for_each_entry(gdev, &gpio_devices, list)
		if (match(gdev->chip, data))
1066
			break;
1067 1068

	/* No match? */
1069
	if (&gdev->list == &gpio_devices)
1070
		chip = NULL;
1071 1072 1073
	else
		chip = gdev->chip;

1074 1075 1076 1077
	spin_unlock_irqrestore(&gpio_lock, flags);

	return chip;
}
Jean Delvare's avatar
Jean Delvare committed
1078
EXPORT_SYMBOL_GPL(gpiochip_find);
1079

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
static int gpiochip_match_name(struct gpio_chip *chip, void *data)
{
	const char *name = data;

	return !strcmp(chip->label, name);
}

static struct gpio_chip *find_chip_by_name(const char *name)
{
	return gpiochip_find((void *)name, gpiochip_match_name);
}

1092 1093 1094 1095 1096 1097 1098
#ifdef CONFIG_GPIOLIB_IRQCHIP

/*
 * The following is irqchip helper code for gpiochips.
 */

/**
1099 1100 1101
 * gpiochip_set_chained_irqchip() - sets a chained irqchip to a gpiochip
 * @gpiochip: the gpiochip to set the irqchip chain to
 * @irqchip: the irqchip to chain to the gpiochip
1102 1103 1104
 * @parent_irq: the irq number corresponding to the parent IRQ for this
 * chained irqchip
 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1105 1106
 * coming out of the gpiochip. If the interrupt is nested rather than
 * cascaded, pass NULL in this handler argument
1107 1108 1109 1110 1111 1112
 */
void gpiochip_set_chained_irqchip(struct gpio_chip *gpiochip,
				  struct irq_chip *irqchip,
				  int parent_irq,
				  irq_flow_handler_t parent_handler)
{
1113 1114 1115 1116 1117
	unsigned int offset;

	if (!gpiochip->irqdomain) {
		chip_err(gpiochip, "called %s before setting up irqchip\n",
			 __func__);
1118 1119 1120
		return;
	}

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
	if (parent_handler) {
		if (gpiochip->can_sleep) {
			chip_err(gpiochip,
				 "you cannot have chained interrupts on a "
				 "chip that may sleep\n");
			return;
		}
		/*
		 * The parent irqchip is already using the chip_data for this
		 * irqchip, so our callbacks simply use the handler_data.
		 */
1132 1133
		irq_set_chained_handler_and_data(parent_irq, parent_handler,
						 gpiochip);
1134 1135

		gpiochip->irq_parent = parent_irq;
1136
	}
1137 1138 1139 1140 1141

	/* Set the parent IRQ for all affected IRQs */
	for (offset = 0; offset < gpiochip->ngpio; offset++)
		irq_set_parent(irq_find_mapping(gpiochip->irqdomain, offset),
			       parent_irq);
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
}
EXPORT_SYMBOL_GPL(gpiochip_set_chained_irqchip);

/**
 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
 * @d: the irqdomain used by this irqchip
 * @irq: the global irq number used by this GPIO irqchip irq
 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
 *
 * This function will set up the mapping for a certain IRQ line on a
 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
 * stored inside the gpiochip.
 */
static int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
			    irq_hw_number_t hwirq)
{
	struct gpio_chip *chip = d->host_data;

	irq_set_chip_data(irq, chip);
1161 1162 1163 1164 1165
	/*
	 * This lock class tells lockdep that GPIO irqs are in a different
	 * category than their parents, so it won't report false recursion.
	 */
	irq_set_lockdep_class(irq, chip->lock_key);
1166
	irq_set_chip_and_handler(irq, chip->irqchip, chip->irq_handler);
1167
	/* Chips that can sleep need nested thread handlers */
1168
	if (chip->can_sleep && !chip->irq_not_threaded)
1169
		irq_set_nested_thread(irq, 1);
1170
	irq_set_noprobe(irq);
1171

1172 1173 1174 1175 1176 1177
	/*
	 * No set-up of the hardware will happen if IRQ_TYPE_NONE
	 * is passed as default type.
	 */
	if (chip->irq_default_type != IRQ_TYPE_NONE)
		irq_set_irq_type(irq, chip->irq_default_type);
1178 1179 1180 1181

	return 0;
}