gpio.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. GPIO Interfaces
  2. This provides an overview of GPIO access conventions on Linux.
  3. What is a GPIO?
  4. ===============
  5. A "General Purpose Input/Output" (GPIO) is a flexible software-controlled
  6. digital signal. They are provided from many kinds of chip, and are familiar
  7. to Linux developers working with embedded and custom hardware. Each GPIO
  8. represents a bit connected to a particular pin, or "ball" on Ball Grid Array
  9. (BGA) packages. Board schematics show which external hardware connects to
  10. which GPIOs. Drivers can be written generically, so that board setup code
  11. passes such pin configuration data to drivers.
  12. System-on-Chip (SOC) processors heavily rely on GPIOs. In some cases, every
  13. non-dedicated pin can be configured as a GPIO; and most chips have at least
  14. several dozen of them. Programmable logic devices (like FPGAs) can easily
  15. provide GPIOs; multifunction chips like power managers, and audio codecs
  16. often have a few such pins to help with pin scarcity on SOCs; and there are
  17. also "GPIO Expander" chips that connect using the I2C or SPI serial busses.
  18. Most PC southbridges have a few dozen GPIO-capable pins (with only the BIOS
  19. firmware knowing how they're used).
  20. The exact capabilities of GPIOs vary between systems. Common options:
  21. - Output values are writable (high=1, low=0). Some chips also have
  22. options about how that value is driven, so that for example only one
  23. value might be driven ... supporting "wire-OR" and similar schemes
  24. for the other value (notably, "open drain" signaling).
  25. - Input values are likewise readable (1, 0). Some chips support readback
  26. of pins configured as "output", which is very useful in such "wire-OR"
  27. cases (to support bidirectional signaling). GPIO controllers may have
  28. input de-glitch logic, sometimes with software controls.
  29. - Inputs can often be used as IRQ signals, often edge triggered but
  30. sometimes level triggered. Such IRQs may be configurable as system
  31. wakeup events, to wake the system from a low power state.
  32. - Usually a GPIO will be configurable as either input or output, as needed
  33. by different product boards; single direction ones exist too.
  34. - Most GPIOs can be accessed while holding spinlocks, but those accessed
  35. through a serial bus normally can't. Some systems support both types.
  36. On a given board each GPIO is used for one specific purpose like monitoring
  37. MMC/SD card insertion/removal, detecting card writeprotect status, driving
  38. a LED, configuring a transceiver, bitbanging a serial bus, poking a hardware
  39. watchdog, sensing a switch, and so on.
  40. GPIO conventions
  41. ================
  42. Note that this is called a "convention" because you don't need to do it this
  43. way, and it's no crime if you don't. There **are** cases where portability
  44. is not the main issue; GPIOs are often used for the kind of board-specific
  45. glue logic that may even change between board revisions, and can't ever be
  46. used on a board that's wired differently. Only least-common-denominator
  47. functionality can be very portable. Other features are platform-specific,
  48. and that can be critical for glue logic.
  49. Plus, this doesn't define an implementation framework, just an interface.
  50. One platform might implement it as simple inline functions accessing chip
  51. registers; another might implement it by delegating through abstractions
  52. used for several very different kinds of GPIO controller.
  53. That said, if the convention is supported on their platform, drivers should
  54. use it when possible. Platforms should declare GENERIC_GPIO support in
  55. Kconfig (boolean true), which multi-platform drivers can depend on when
  56. using the include file:
  57. #include <asm/gpio.h>
  58. If you stick to this convention then it'll be easier for other developers to
  59. see what your code is doing, and help maintain it.
  60. Identifying GPIOs
  61. -----------------
  62. GPIOs are identified by unsigned integers in the range 0..MAX_INT. That
  63. reserves "negative" numbers for other purposes like marking signals as
  64. "not available on this board", or indicating faults. Code that doesn't
  65. touch the underlying hardware treats these integers as opaque cookies.
  66. Platforms define how they use those integers, and usually #define symbols
  67. for the GPIO lines so that board-specific setup code directly corresponds
  68. to the relevant schematics. In contrast, drivers should only use GPIO
  69. numbers passed to them from that setup code, using platform_data to hold
  70. board-specific pin configuration data (along with other board specific
  71. data they need). That avoids portability problems.
  72. So for example one platform uses numbers 32-159 for GPIOs; while another
  73. uses numbers 0..63 with one set of GPIO controllers, 64-79 with another
  74. type of GPIO controller, and on one particular board 80-95 with an FPGA.
  75. The numbers need not be contiguous; either of those platforms could also
  76. use numbers 2000-2063 to identify GPIOs in a bank of I2C GPIO expanders.
  77. Whether a platform supports multiple GPIO controllers is currently a
  78. platform-specific implementation issue.
  79. Using GPIOs
  80. -----------
  81. One of the first things to do with a GPIO, often in board setup code when
  82. setting up a platform_device using the GPIO, is mark its direction:
  83. /* set as input or output, returning 0 or negative errno */
  84. int gpio_direction_input(unsigned gpio);
  85. int gpio_direction_output(unsigned gpio, int value);
  86. The return value is zero for success, else a negative errno. It should
  87. be checked, since the get/set calls don't have error returns and since
  88. misconfiguration is possible. (These calls could sleep.)
  89. For output GPIOs, the value provided becomes the initial output value.
  90. This helps avoid signal glitching during system startup.
  91. Setting the direction can fail if the GPIO number is invalid, or when
  92. that particular GPIO can't be used in that mode. It's generally a bad
  93. idea to rely on boot firmware to have set the direction correctly, since
  94. it probably wasn't validated to do more than boot Linux. (Similarly,
  95. that board setup code probably needs to multiplex that pin as a GPIO,
  96. and configure pullups/pulldowns appropriately.)
  97. Spinlock-Safe GPIO access
  98. -------------------------
  99. Most GPIO controllers can be accessed with memory read/write instructions.
  100. That doesn't need to sleep, and can safely be done from inside IRQ handlers.
  101. Use these calls to access such GPIOs:
  102. /* GPIO INPUT: return zero or nonzero */
  103. int gpio_get_value(unsigned gpio);
  104. /* GPIO OUTPUT */
  105. void gpio_set_value(unsigned gpio, int value);
  106. The values are boolean, zero for low, nonzero for high. When reading the
  107. value of an output pin, the value returned should be what's seen on the
  108. pin ... that won't always match the specified output value, because of
  109. issues including wire-OR and output latencies.
  110. The get/set calls have no error returns because "invalid GPIO" should have
  111. been reported earlier in gpio_set_direction(). However, note that not all
  112. platforms can read the value of output pins; those that can't should always
  113. return zero. Also, using these calls for GPIOs that can't safely be accessed
  114. without sleeping (see below) is an error.
  115. Platform-specific implementations are encouraged to optimize the two
  116. calls to access the GPIO value in cases where the GPIO number (and for
  117. output, value) are constant. It's normal for them to need only a couple
  118. of instructions in such cases (reading or writing a hardware register),
  119. and not to need spinlocks. Such optimized calls can make bitbanging
  120. applications a lot more efficient (in both space and time) than spending
  121. dozens of instructions on subroutine calls.
  122. GPIO access that may sleep
  123. --------------------------
  124. Some GPIO controllers must be accessed using message based busses like I2C
  125. or SPI. Commands to read or write those GPIO values require waiting to
  126. get to the head of a queue to transmit a command and get its response.
  127. This requires sleeping, which can't be done from inside IRQ handlers.
  128. Platforms that support this type of GPIO distinguish them from other GPIOs
  129. by returning nonzero from this call:
  130. int gpio_cansleep(unsigned gpio);
  131. To access such GPIOs, a different set of accessors is defined:
  132. /* GPIO INPUT: return zero or nonzero, might sleep */
  133. int gpio_get_value_cansleep(unsigned gpio);
  134. /* GPIO OUTPUT, might sleep */
  135. void gpio_set_value_cansleep(unsigned gpio, int value);
  136. Other than the fact that these calls might sleep, and will not be ignored
  137. for GPIOs that can't be accessed from IRQ handlers, these calls act the
  138. same as the spinlock-safe calls.
  139. Claiming and Releasing GPIOs (OPTIONAL)
  140. ---------------------------------------
  141. To help catch system configuration errors, two calls are defined.
  142. However, many platforms don't currently support this mechanism.
  143. /* request GPIO, returning 0 or negative errno.
  144. * non-null labels may be useful for diagnostics.
  145. */
  146. int gpio_request(unsigned gpio, const char *label);
  147. /* release previously-claimed GPIO */
  148. void gpio_free(unsigned gpio);
  149. Passing invalid GPIO numbers to gpio_request() will fail, as will requesting
  150. GPIOs that have already been claimed with that call. The return value of
  151. gpio_request() must be checked. (These calls could sleep.)
  152. These calls serve two basic purposes. One is marking the signals which
  153. are actually in use as GPIOs, for better diagnostics; systems may have
  154. several hundred potential GPIOs, but often only a dozen are used on any
  155. given board. Another is to catch conflicts between drivers, reporting
  156. errors when drivers wrongly think they have exclusive use of that signal.
  157. These two calls are optional because not not all current Linux platforms
  158. offer such functionality in their GPIO support; a valid implementation
  159. could return success for all gpio_request() calls. Unlike the other calls,
  160. the state they represent doesn't normally match anything from a hardware
  161. register; it's just a software bitmap which clearly is not necessary for
  162. correct operation of hardware or (bug free) drivers.
  163. Note that requesting a GPIO does NOT cause it to be configured in any
  164. way; it just marks that GPIO as in use. Separate code must handle any
  165. pin setup (e.g. controlling which pin the GPIO uses, pullup/pulldown).
  166. GPIOs mapped to IRQs
  167. --------------------
  168. GPIO numbers are unsigned integers; so are IRQ numbers. These make up
  169. two logically distinct namespaces (GPIO 0 need not use IRQ 0). You can
  170. map between them using calls like:
  171. /* map GPIO numbers to IRQ numbers */
  172. int gpio_to_irq(unsigned gpio);
  173. /* map IRQ numbers to GPIO numbers */
  174. int irq_to_gpio(unsigned irq);
  175. Those return either the corresponding number in the other namespace, or
  176. else a negative errno code if the mapping can't be done. (For example,
  177. some GPIOs can't used as IRQs.) It is an unchecked error to use a GPIO
  178. number that hasn't been marked as an input using gpio_set_direction(), or
  179. to use an IRQ number that didn't originally come from gpio_to_irq().
  180. These two mapping calls are expected to cost on the order of a single
  181. addition or subtraction. They're not allowed to sleep.
  182. Non-error values returned from gpio_to_irq() can be passed to request_irq()
  183. or free_irq(). They will often be stored into IRQ resources for platform
  184. devices, by the board-specific initialization code. Note that IRQ trigger
  185. options are part of the IRQ interface, e.g. IRQF_TRIGGER_FALLING, as are
  186. system wakeup capabilities.
  187. Non-error values returned from irq_to_gpio() would most commonly be used
  188. with gpio_get_value(), for example to initialize or update driver state
  189. when the IRQ is edge-triggered.
  190. Emulating Open Drain Signals
  191. ----------------------------
  192. Sometimes shared signals need to use "open drain" signaling, where only the
  193. low signal level is actually driven. (That term applies to CMOS transistors;
  194. "open collector" is used for TTL.) A pullup resistor causes the high signal
  195. level. This is sometimes called a "wire-AND"; or more practically, from the
  196. negative logic (low=true) perspective this is a "wire-OR".
  197. One common example of an open drain signal is a shared active-low IRQ line.
  198. Also, bidirectional data bus signals sometimes use open drain signals.
  199. Some GPIO controllers directly support open drain outputs; many don't. When
  200. you need open drain signaling but your hardware doesn't directly support it,
  201. there's a common idiom you can use to emulate it with any GPIO pin that can
  202. be used as either an input or an output:
  203. LOW: gpio_direction_output(gpio, 0) ... this drives the signal
  204. and overrides the pullup.
  205. HIGH: gpio_direction_input(gpio) ... this turns off the output,
  206. so the pullup (or some other device) controls the signal.
  207. If you are "driving" the signal high but gpio_get_value(gpio) reports a low
  208. value (after the appropriate rise time passes), you know some other component
  209. is driving the shared signal low. That's not necessarily an error. As one
  210. common example, that's how I2C clocks are stretched: a slave that needs a
  211. slower clock delays the rising edge of SCK, and the I2C master adjusts its
  212. signaling rate accordingly.
  213. What do these conventions omit?
  214. ===============================
  215. One of the biggest things these conventions omit is pin multiplexing, since
  216. this is highly chip-specific and nonportable. One platform might not need
  217. explicit multiplexing; another might have just two options for use of any
  218. given pin; another might have eight options per pin; another might be able
  219. to route a given GPIO to any one of several pins. (Yes, those examples all
  220. come from systems that run Linux today.)
  221. Related to multiplexing is configuration and enabling of the pullups or
  222. pulldowns integrated on some platforms. Not all platforms support them,
  223. or support them in the same way; and any given board might use external
  224. pullups (or pulldowns) so that the on-chip ones should not be used.
  225. There are other system-specific mechanisms that are not specified here,
  226. like the aforementioned options for input de-glitching and wire-OR output.
  227. Hardware may support reading or writing GPIOs in gangs, but that's usually
  228. configuration dependent: for GPIOs sharing the same bank. (GPIOs are
  229. commonly grouped in banks of 16 or 32, with a given SOC having several such
  230. banks.) Some systems can trigger IRQs from output GPIOs. Code relying on
  231. such mechanisms will necessarily be nonportable.
  232. Dynamic definition of GPIOs is not currently supported; for example, as
  233. a side effect of configuring an add-on board with some GPIO expanders.
  234. These calls are purely for kernel space, but a userspace API could be built
  235. on top of it.