cd-gpio.c 1.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * Generic GPIO card-detect helper
 *
 * Copyright (C) 2011, Guennadi Liakhovetski <g.liakhovetski@gmx.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */

#include <linux/err.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/jiffies.h>
15
#include <linux/mmc/cd-gpio.h>
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <linux/mmc/host.h>
#include <linux/module.h>
#include <linux/slab.h>

struct mmc_cd_gpio {
	unsigned int gpio;
	char label[0];
};

static irqreturn_t mmc_cd_gpio_irqt(int irq, void *dev_id)
{
	/* Schedule a card detection after a debounce timeout */
	mmc_detect_change(dev_id, msecs_to_jiffies(100));
	return IRQ_HANDLED;
}

32
int mmc_cd_gpio_request(struct mmc_host *host, unsigned int gpio)
33 34
{
	size_t len = strlen(dev_name(host->parent)) + 4;
35 36
	struct mmc_cd_gpio *cd;
	int irq = gpio_to_irq(gpio);
37 38
	int ret;

39 40 41 42
	if (irq < 0)
		return irq;

	cd = kmalloc(sizeof(*cd) + len, GFP_KERNEL);
43 44 45 46 47 48 49 50 51 52
	if (!cd)
		return -ENOMEM;

	snprintf(cd->label, len, "%s cd", dev_name(host->parent));

	ret = gpio_request_one(gpio, GPIOF_DIR_IN, cd->label);
	if (ret < 0)
		goto egpioreq;

	ret = request_threaded_irq(irq, NULL, mmc_cd_gpio_irqt,
53 54
				   IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING |
				   IRQF_ONESHOT, cd->label, host);
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
	if (ret < 0)
		goto eirqreq;

	cd->gpio = gpio;
	host->hotplug.irq = irq;
	host->hotplug.handler_priv = cd;

	return 0;

eirqreq:
	gpio_free(gpio);
egpioreq:
	kfree(cd);
	return ret;
}
EXPORT_SYMBOL(mmc_cd_gpio_request);

void mmc_cd_gpio_free(struct mmc_host *host)
{
	struct mmc_cd_gpio *cd = host->hotplug.handler_priv;

76 77 78
	if (!cd)
		return;

79 80 81 82 83
	free_irq(host->hotplug.irq, host);
	gpio_free(cd->gpio);
	kfree(cd);
}
EXPORT_SYMBOL(mmc_cd_gpio_free);