cd-gpio.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  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. #include <linux/err.h>
  11. #include <linux/gpio.h>
  12. #include <linux/interrupt.h>
  13. #include <linux/jiffies.h>
  14. #include <linux/mmc/cd-gpio.h>
  15. #include <linux/mmc/host.h>
  16. #include <linux/module.h>
  17. #include <linux/slab.h>
  18. struct mmc_cd_gpio {
  19. unsigned int gpio;
  20. char label[0];
  21. };
  22. static irqreturn_t mmc_cd_gpio_irqt(int irq, void *dev_id)
  23. {
  24. /* Schedule a card detection after a debounce timeout */
  25. mmc_detect_change(dev_id, msecs_to_jiffies(100));
  26. return IRQ_HANDLED;
  27. }
  28. int mmc_cd_gpio_request(struct mmc_host *host, unsigned int gpio)
  29. {
  30. size_t len = strlen(dev_name(host->parent)) + 4;
  31. struct mmc_cd_gpio *cd;
  32. int irq = gpio_to_irq(gpio);
  33. int ret;
  34. if (irq < 0)
  35. return irq;
  36. cd = kmalloc(sizeof(*cd) + len, GFP_KERNEL);
  37. if (!cd)
  38. return -ENOMEM;
  39. snprintf(cd->label, len, "%s cd", dev_name(host->parent));
  40. ret = gpio_request_one(gpio, GPIOF_DIR_IN, cd->label);
  41. if (ret < 0)
  42. goto egpioreq;
  43. ret = request_threaded_irq(irq, NULL, mmc_cd_gpio_irqt,
  44. IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING |
  45. IRQF_ONESHOT, cd->label, host);
  46. if (ret < 0)
  47. goto eirqreq;
  48. cd->gpio = gpio;
  49. host->hotplug.irq = irq;
  50. host->hotplug.handler_priv = cd;
  51. return 0;
  52. eirqreq:
  53. gpio_free(gpio);
  54. egpioreq:
  55. kfree(cd);
  56. return ret;
  57. }
  58. EXPORT_SYMBOL(mmc_cd_gpio_request);
  59. void mmc_cd_gpio_free(struct mmc_host *host)
  60. {
  61. struct mmc_cd_gpio *cd = host->hotplug.handler_priv;
  62. if (!cd)
  63. return;
  64. free_irq(host->hotplug.irq, host);
  65. gpio_free(cd->gpio);
  66. kfree(cd);
  67. }
  68. EXPORT_SYMBOL(mmc_cd_gpio_free);