blob: 29de31e260dda56da18d0345f15a3886c6c1063a [file] [log] [blame]
Guennadi Liakhovetski349ab522011-12-25 21:36:02 +01001/*
2 * Generic GPIO card-detect helper
3 *
4 * Copyright (C) 2011, Guennadi Liakhovetski <g.liakhovetski@gmx.de>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2 as
8 * published by the Free Software Foundation.
9 */
10
11#include <linux/err.h>
12#include <linux/gpio.h>
13#include <linux/interrupt.h>
14#include <linux/jiffies.h>
15#include <linux/mmc/host.h>
16#include <linux/module.h>
17#include <linux/slab.h>
18
19struct mmc_cd_gpio {
20 unsigned int gpio;
21 char label[0];
22};
23
24static irqreturn_t mmc_cd_gpio_irqt(int irq, void *dev_id)
25{
26 /* Schedule a card detection after a debounce timeout */
27 mmc_detect_change(dev_id, msecs_to_jiffies(100));
28 return IRQ_HANDLED;
29}
30
Guennadi Liakhovetskic9b05462012-02-09 22:57:07 +010031int mmc_cd_gpio_request(struct mmc_host *host, unsigned int gpio)
Guennadi Liakhovetski349ab522011-12-25 21:36:02 +010032{
33 size_t len = strlen(dev_name(host->parent)) + 4;
Guennadi Liakhovetskic9b05462012-02-09 22:57:07 +010034 struct mmc_cd_gpio *cd;
35 int irq = gpio_to_irq(gpio);
Guennadi Liakhovetski349ab522011-12-25 21:36:02 +010036 int ret;
37
Guennadi Liakhovetskic9b05462012-02-09 22:57:07 +010038 if (irq < 0)
39 return irq;
40
41 cd = kmalloc(sizeof(*cd) + len, GFP_KERNEL);
Guennadi Liakhovetski349ab522011-12-25 21:36:02 +010042 if (!cd)
43 return -ENOMEM;
44
45 snprintf(cd->label, len, "%s cd", dev_name(host->parent));
46
47 ret = gpio_request_one(gpio, GPIOF_DIR_IN, cd->label);
48 if (ret < 0)
49 goto egpioreq;
50
51 ret = request_threaded_irq(irq, NULL, mmc_cd_gpio_irqt,
Guennadi Liakhovetskic9b05462012-02-09 22:57:07 +010052 IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
53 cd->label, host);
Guennadi Liakhovetski349ab522011-12-25 21:36:02 +010054 if (ret < 0)
55 goto eirqreq;
56
57 cd->gpio = gpio;
58 host->hotplug.irq = irq;
59 host->hotplug.handler_priv = cd;
60
61 return 0;
62
63eirqreq:
64 gpio_free(gpio);
65egpioreq:
66 kfree(cd);
67 return ret;
68}
69EXPORT_SYMBOL(mmc_cd_gpio_request);
70
71void mmc_cd_gpio_free(struct mmc_host *host)
72{
73 struct mmc_cd_gpio *cd = host->hotplug.handler_priv;
74
75 free_irq(host->hotplug.irq, host);
76 gpio_free(cd->gpio);
77 kfree(cd);
78}
79EXPORT_SYMBOL(mmc_cd_gpio_free);