devres.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * drivers/gpio/devres.c - managed gpio resources
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License version 2
  6. * as published by the Free Software Foundation.
  7. *
  8. * You should have received a copy of the GNU General Public License
  9. * along with this program; if not, write to the Free Software
  10. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  11. *
  12. * This file is based on kernel/irq/devres.c
  13. *
  14. * Copyright (c) 2011 John Crispin <blogic@openwrt.org>
  15. */
  16. #include <linux/module.h>
  17. #include <linux/gpio.h>
  18. #include <linux/device.h>
  19. #include <linux/gfp.h>
  20. static void devm_gpio_release(struct device *dev, void *res)
  21. {
  22. unsigned *gpio = res;
  23. gpio_free(*gpio);
  24. }
  25. static int devm_gpio_match(struct device *dev, void *res, void *data)
  26. {
  27. unsigned *this = res, *gpio = data;
  28. return *this == *gpio;
  29. }
  30. /**
  31. * devm_gpio_request - request a gpio for a managed device
  32. * @dev: device to request the gpio for
  33. * @gpio: gpio to allocate
  34. * @label: the name of the requested gpio
  35. *
  36. * Except for the extra @dev argument, this function takes the
  37. * same arguments and performs the same function as
  38. * gpio_request(). GPIOs requested with this function will be
  39. * automatically freed on driver detach.
  40. *
  41. * If an GPIO allocated with this function needs to be freed
  42. * separately, devm_gpio_free() must be used.
  43. */
  44. int devm_gpio_request(struct device *dev, unsigned gpio, const char *label)
  45. {
  46. unsigned *dr;
  47. int rc;
  48. dr = devres_alloc(devm_gpio_release, sizeof(unsigned), GFP_KERNEL);
  49. if (!dr)
  50. return -ENOMEM;
  51. rc = gpio_request(gpio, label);
  52. if (rc) {
  53. devres_free(dr);
  54. return rc;
  55. }
  56. *dr = gpio;
  57. devres_add(dev, dr);
  58. return 0;
  59. }
  60. EXPORT_SYMBOL(devm_gpio_request);
  61. /**
  62. * devm_gpio_free - free an interrupt
  63. * @dev: device to free gpio for
  64. * @gpio: gpio to free
  65. *
  66. * Except for the extra @dev argument, this function takes the
  67. * same arguments and performs the same function as gpio_free().
  68. * This function instead of gpio_free() should be used to manually
  69. * free GPIOs allocated with devm_gpio_request().
  70. */
  71. void devm_gpio_free(struct device *dev, unsigned int gpio)
  72. {
  73. WARN_ON(devres_destroy(dev, devm_gpio_release, devm_gpio_match,
  74. &gpio));
  75. gpio_free(gpio);
  76. }
  77. EXPORT_SYMBOL(devm_gpio_free);