blob: 8da724e2a0ff795d450e8b0b7b61118d7bf604a6 [file] [log] [blame]
David Brownell4c203862007-02-12 00:53:11 -08001GPIO Interfaces
2
3This provides an overview of GPIO access conventions on Linux.
4
5
6What is a GPIO?
7===============
8A "General Purpose Input/Output" (GPIO) is a flexible software-controlled
9digital signal. They are provided from many kinds of chip, and are familiar
10to Linux developers working with embedded and custom hardware. Each GPIO
11represents a bit connected to a particular pin, or "ball" on Ball Grid Array
12(BGA) packages. Board schematics show which external hardware connects to
13which GPIOs. Drivers can be written generically, so that board setup code
14passes such pin configuration data to drivers.
15
16System-on-Chip (SOC) processors heavily rely on GPIOs. In some cases, every
17non-dedicated pin can be configured as a GPIO; and most chips have at least
18several dozen of them. Programmable logic devices (like FPGAs) can easily
19provide GPIOs; multifunction chips like power managers, and audio codecs
20often have a few such pins to help with pin scarcity on SOCs; and there are
21also "GPIO Expander" chips that connect using the I2C or SPI serial busses.
22Most PC southbridges have a few dozen GPIO-capable pins (with only the BIOS
23firmware knowing how they're used).
24
25The exact capabilities of GPIOs vary between systems. Common options:
26
27 - Output values are writable (high=1, low=0). Some chips also have
28 options about how that value is driven, so that for example only one
29 value might be driven ... supporting "wire-OR" and similar schemes
David Brownell1668be72007-04-11 23:28:42 -070030 for the other value (notably, "open drain" signaling).
David Brownell4c203862007-02-12 00:53:11 -080031
32 - Input values are likewise readable (1, 0). Some chips support readback
33 of pins configured as "output", which is very useful in such "wire-OR"
34 cases (to support bidirectional signaling). GPIO controllers may have
David Brownell7c2db752008-02-04 22:28:21 -080035 input de-glitch/debounce logic, sometimes with software controls.
David Brownell4c203862007-02-12 00:53:11 -080036
37 - Inputs can often be used as IRQ signals, often edge triggered but
38 sometimes level triggered. Such IRQs may be configurable as system
39 wakeup events, to wake the system from a low power state.
40
41 - Usually a GPIO will be configurable as either input or output, as needed
42 by different product boards; single direction ones exist too.
43
44 - Most GPIOs can be accessed while holding spinlocks, but those accessed
45 through a serial bus normally can't. Some systems support both types.
46
47On a given board each GPIO is used for one specific purpose like monitoring
48MMC/SD card insertion/removal, detecting card writeprotect status, driving
49a LED, configuring a transceiver, bitbanging a serial bus, poking a hardware
50watchdog, sensing a switch, and so on.
51
52
53GPIO conventions
54================
55Note that this is called a "convention" because you don't need to do it this
56way, and it's no crime if you don't. There **are** cases where portability
57is not the main issue; GPIOs are often used for the kind of board-specific
58glue logic that may even change between board revisions, and can't ever be
59used on a board that's wired differently. Only least-common-denominator
60functionality can be very portable. Other features are platform-specific,
61and that can be critical for glue logic.
62
David Brownell7c2db752008-02-04 22:28:21 -080063Plus, this doesn't require any implementation framework, just an interface.
David Brownell4c203862007-02-12 00:53:11 -080064One platform might implement it as simple inline functions accessing chip
65registers; another might implement it by delegating through abstractions
David Brownell7c2db752008-02-04 22:28:21 -080066used for several very different kinds of GPIO controller. (There is some
67optional code supporting such an implementation strategy, described later
68in this document, but drivers acting as clients to the GPIO interface must
69not care how it's implemented.)
David Brownell4c203862007-02-12 00:53:11 -080070
71That said, if the convention is supported on their platform, drivers should
David Brownell32993b72007-05-10 22:22:17 -070072use it when possible. Platforms should declare GENERIC_GPIO support in
73Kconfig (boolean true), which multi-platform drivers can depend on when
74using the include file:
David Brownell4c203862007-02-12 00:53:11 -080075
76 #include <asm/gpio.h>
77
78If you stick to this convention then it'll be easier for other developers to
79see what your code is doing, and help maintain it.
80
David Brownella0a99832007-07-19 01:47:52 -070081Note that these operations include I/O barriers on platforms which need to
82use them; drivers don't need to add them explicitly.
83
David Brownell4c203862007-02-12 00:53:11 -080084
85Identifying GPIOs
86-----------------
87GPIOs are identified by unsigned integers in the range 0..MAX_INT. That
88reserves "negative" numbers for other purposes like marking signals as
David Brownellf5de6112007-02-16 01:27:14 -080089"not available on this board", or indicating faults. Code that doesn't
90touch the underlying hardware treats these integers as opaque cookies.
David Brownell4c203862007-02-12 00:53:11 -080091
92Platforms define how they use those integers, and usually #define symbols
93for the GPIO lines so that board-specific setup code directly corresponds
94to the relevant schematics. In contrast, drivers should only use GPIO
95numbers passed to them from that setup code, using platform_data to hold
96board-specific pin configuration data (along with other board specific
97data they need). That avoids portability problems.
98
99So for example one platform uses numbers 32-159 for GPIOs; while another
100uses numbers 0..63 with one set of GPIO controllers, 64-79 with another
101type of GPIO controller, and on one particular board 80-95 with an FPGA.
102The numbers need not be contiguous; either of those platforms could also
103use numbers 2000-2063 to identify GPIOs in a bank of I2C GPIO expanders.
104
105Whether a platform supports multiple GPIO controllers is currently a
106platform-specific implementation issue.
107
108
109Using GPIOs
110-----------
111One of the first things to do with a GPIO, often in board setup code when
112setting up a platform_device using the GPIO, is mark its direction:
113
114 /* set as input or output, returning 0 or negative errno */
115 int gpio_direction_input(unsigned gpio);
David Brownell28735a72007-03-16 13:38:14 -0800116 int gpio_direction_output(unsigned gpio, int value);
David Brownell4c203862007-02-12 00:53:11 -0800117
118The return value is zero for success, else a negative errno. It should
119be checked, since the get/set calls don't have error returns and since
David Brownell83c65902007-05-16 22:11:13 -0700120misconfiguration is possible. You should normally issue these calls from
121a task context. However, for spinlock-safe GPIOs it's OK to use them
122before tasking is enabled, as part of early board setup.
David Brownell4c203862007-02-12 00:53:11 -0800123
David Brownell28735a72007-03-16 13:38:14 -0800124For output GPIOs, the value provided becomes the initial output value.
125This helps avoid signal glitching during system startup.
126
David Brownell7c2db752008-02-04 22:28:21 -0800127For compatibility with legacy interfaces to GPIOs, setting the direction
128of a GPIO implicitly requests that GPIO (see below) if it has not been
129requested already. That compatibility may be removed in the future;
130explicitly requesting GPIOs is strongly preferred.
131
David Brownell4c203862007-02-12 00:53:11 -0800132Setting the direction can fail if the GPIO number is invalid, or when
133that particular GPIO can't be used in that mode. It's generally a bad
134idea to rely on boot firmware to have set the direction correctly, since
135it probably wasn't validated to do more than boot Linux. (Similarly,
136that board setup code probably needs to multiplex that pin as a GPIO,
137and configure pullups/pulldowns appropriately.)
138
139
140Spinlock-Safe GPIO access
141-------------------------
142Most GPIO controllers can be accessed with memory read/write instructions.
143That doesn't need to sleep, and can safely be done from inside IRQ handlers.
David Brownell7c2db752008-02-04 22:28:21 -0800144(That includes hardirq contexts on RT kernels.)
David Brownell4c203862007-02-12 00:53:11 -0800145
146Use these calls to access such GPIOs:
147
148 /* GPIO INPUT: return zero or nonzero */
149 int gpio_get_value(unsigned gpio);
150
151 /* GPIO OUTPUT */
152 void gpio_set_value(unsigned gpio, int value);
153
154The values are boolean, zero for low, nonzero for high. When reading the
155value of an output pin, the value returned should be what's seen on the
156pin ... that won't always match the specified output value, because of
David Brownell7c2db752008-02-04 22:28:21 -0800157issues including open-drain signaling and output latencies.
David Brownell4c203862007-02-12 00:53:11 -0800158
159The get/set calls have no error returns because "invalid GPIO" should have
David Brownellbe1ff382007-07-23 18:43:57 -0700160been reported earlier from gpio_direction_*(). However, note that not all
David Brownell4c203862007-02-12 00:53:11 -0800161platforms can read the value of output pins; those that can't should always
David Brownellf5de6112007-02-16 01:27:14 -0800162return zero. Also, using these calls for GPIOs that can't safely be accessed
163without sleeping (see below) is an error.
David Brownell4c203862007-02-12 00:53:11 -0800164
David Brownellf5de6112007-02-16 01:27:14 -0800165Platform-specific implementations are encouraged to optimize the two
David Brownell4c203862007-02-12 00:53:11 -0800166calls to access the GPIO value in cases where the GPIO number (and for
167output, value) are constant. It's normal for them to need only a couple
168of instructions in such cases (reading or writing a hardware register),
169and not to need spinlocks. Such optimized calls can make bitbanging
170applications a lot more efficient (in both space and time) than spending
171dozens of instructions on subroutine calls.
172
173
174GPIO access that may sleep
175--------------------------
176Some GPIO controllers must be accessed using message based busses like I2C
177or SPI. Commands to read or write those GPIO values require waiting to
178get to the head of a queue to transmit a command and get its response.
179This requires sleeping, which can't be done from inside IRQ handlers.
180
181Platforms that support this type of GPIO distinguish them from other GPIOs
David Brownell7c2db752008-02-04 22:28:21 -0800182by returning nonzero from this call (which requires a valid GPIO number,
183either explicitly or implicitly requested):
David Brownell4c203862007-02-12 00:53:11 -0800184
185 int gpio_cansleep(unsigned gpio);
186
187To access such GPIOs, a different set of accessors is defined:
188
189 /* GPIO INPUT: return zero or nonzero, might sleep */
190 int gpio_get_value_cansleep(unsigned gpio);
191
192 /* GPIO OUTPUT, might sleep */
193 void gpio_set_value_cansleep(unsigned gpio, int value);
194
195Other than the fact that these calls might sleep, and will not be ignored
196for GPIOs that can't be accessed from IRQ handlers, these calls act the
197same as the spinlock-safe calls.
198
199
200Claiming and Releasing GPIOs (OPTIONAL)
201---------------------------------------
202To help catch system configuration errors, two calls are defined.
203However, many platforms don't currently support this mechanism.
204
205 /* request GPIO, returning 0 or negative errno.
206 * non-null labels may be useful for diagnostics.
207 */
208 int gpio_request(unsigned gpio, const char *label);
209
210 /* release previously-claimed GPIO */
211 void gpio_free(unsigned gpio);
212
213Passing invalid GPIO numbers to gpio_request() will fail, as will requesting
214GPIOs that have already been claimed with that call. The return value of
David Brownell83c65902007-05-16 22:11:13 -0700215gpio_request() must be checked. You should normally issue these calls from
216a task context. However, for spinlock-safe GPIOs it's OK to request GPIOs
217before tasking is enabled, as part of early board setup.
David Brownell4c203862007-02-12 00:53:11 -0800218
219These calls serve two basic purposes. One is marking the signals which
220are actually in use as GPIOs, for better diagnostics; systems may have
221several hundred potential GPIOs, but often only a dozen are used on any
David Brownell7c2db752008-02-04 22:28:21 -0800222given board. Another is to catch conflicts, identifying errors when
223(a) two or more drivers wrongly think they have exclusive use of that
224signal, or (b) something wrongly believes it's safe to remove drivers
225needed to manage a signal that's in active use. That is, requesting a
226GPIO can serve as a kind of lock.
David Brownell4c203862007-02-12 00:53:11 -0800227
228These two calls are optional because not not all current Linux platforms
229offer such functionality in their GPIO support; a valid implementation
230could return success for all gpio_request() calls. Unlike the other calls,
231the state they represent doesn't normally match anything from a hardware
232register; it's just a software bitmap which clearly is not necessary for
233correct operation of hardware or (bug free) drivers.
234
235Note that requesting a GPIO does NOT cause it to be configured in any
236way; it just marks that GPIO as in use. Separate code must handle any
237pin setup (e.g. controlling which pin the GPIO uses, pullup/pulldown).
238
David Brownell7c2db752008-02-04 22:28:21 -0800239Also note that it's your responsibility to have stopped using a GPIO
240before you free it.
241
David Brownell4c203862007-02-12 00:53:11 -0800242
243GPIOs mapped to IRQs
244--------------------
245GPIO numbers are unsigned integers; so are IRQ numbers. These make up
246two logically distinct namespaces (GPIO 0 need not use IRQ 0). You can
247map between them using calls like:
248
249 /* map GPIO numbers to IRQ numbers */
250 int gpio_to_irq(unsigned gpio);
251
252 /* map IRQ numbers to GPIO numbers */
253 int irq_to_gpio(unsigned irq);
254
255Those return either the corresponding number in the other namespace, or
256else a negative errno code if the mapping can't be done. (For example,
David Brownell7c2db752008-02-04 22:28:21 -0800257some GPIOs can't be used as IRQs.) It is an unchecked error to use a GPIO
David Brownellbe1ff382007-07-23 18:43:57 -0700258number that wasn't set up as an input using gpio_direction_input(), or
David Brownell4c203862007-02-12 00:53:11 -0800259to use an IRQ number that didn't originally come from gpio_to_irq().
260
261These two mapping calls are expected to cost on the order of a single
262addition or subtraction. They're not allowed to sleep.
263
264Non-error values returned from gpio_to_irq() can be passed to request_irq()
265or free_irq(). They will often be stored into IRQ resources for platform
266devices, by the board-specific initialization code. Note that IRQ trigger
267options are part of the IRQ interface, e.g. IRQF_TRIGGER_FALLING, as are
268system wakeup capabilities.
269
270Non-error values returned from irq_to_gpio() would most commonly be used
David Brownellf5de6112007-02-16 01:27:14 -0800271with gpio_get_value(), for example to initialize or update driver state
272when the IRQ is edge-triggered.
David Brownell4c203862007-02-12 00:53:11 -0800273
274
David Brownell1668be72007-04-11 23:28:42 -0700275Emulating Open Drain Signals
276----------------------------
277Sometimes shared signals need to use "open drain" signaling, where only the
278low signal level is actually driven. (That term applies to CMOS transistors;
279"open collector" is used for TTL.) A pullup resistor causes the high signal
280level. This is sometimes called a "wire-AND"; or more practically, from the
281negative logic (low=true) perspective this is a "wire-OR".
282
283One common example of an open drain signal is a shared active-low IRQ line.
284Also, bidirectional data bus signals sometimes use open drain signals.
285
286Some GPIO controllers directly support open drain outputs; many don't. When
287you need open drain signaling but your hardware doesn't directly support it,
288there's a common idiom you can use to emulate it with any GPIO pin that can
289be used as either an input or an output:
290
291 LOW: gpio_direction_output(gpio, 0) ... this drives the signal
292 and overrides the pullup.
293
294 HIGH: gpio_direction_input(gpio) ... this turns off the output,
295 so the pullup (or some other device) controls the signal.
296
297If you are "driving" the signal high but gpio_get_value(gpio) reports a low
298value (after the appropriate rise time passes), you know some other component
299is driving the shared signal low. That's not necessarily an error. As one
300common example, that's how I2C clocks are stretched: a slave that needs a
301slower clock delays the rising edge of SCK, and the I2C master adjusts its
302signaling rate accordingly.
303
David Brownell4c203862007-02-12 00:53:11 -0800304
305What do these conventions omit?
306===============================
307One of the biggest things these conventions omit is pin multiplexing, since
308this is highly chip-specific and nonportable. One platform might not need
309explicit multiplexing; another might have just two options for use of any
310given pin; another might have eight options per pin; another might be able
311to route a given GPIO to any one of several pins. (Yes, those examples all
312come from systems that run Linux today.)
313
314Related to multiplexing is configuration and enabling of the pullups or
315pulldowns integrated on some platforms. Not all platforms support them,
316or support them in the same way; and any given board might use external
317pullups (or pulldowns) so that the on-chip ones should not be used.
David Brownell7c2db752008-02-04 22:28:21 -0800318(When a circuit needs 5 kOhm, on-chip 100 kOhm resistors won't do.)
David Brownell4c203862007-02-12 00:53:11 -0800319
320There are other system-specific mechanisms that are not specified here,
321like the aforementioned options for input de-glitching and wire-OR output.
322Hardware may support reading or writing GPIOs in gangs, but that's usually
David Brownellf5de6112007-02-16 01:27:14 -0800323configuration dependent: for GPIOs sharing the same bank. (GPIOs are
David Brownell4c203862007-02-12 00:53:11 -0800324commonly grouped in banks of 16 or 32, with a given SOC having several such
David Brownell7c2db752008-02-04 22:28:21 -0800325banks.) Some systems can trigger IRQs from output GPIOs, or read values
326from pins not managed as GPIOs. Code relying on such mechanisms will
327necessarily be nonportable.
David Brownell4c203862007-02-12 00:53:11 -0800328
David Brownell7c2db752008-02-04 22:28:21 -0800329Dynamic definition of GPIOs is not currently standard; for example, as
David Brownell4c203862007-02-12 00:53:11 -0800330a side effect of configuring an add-on board with some GPIO expanders.
331
332These calls are purely for kernel space, but a userspace API could be built
David Brownell7c2db752008-02-04 22:28:21 -0800333on top of them.
334
335
336GPIO implementor's framework (OPTIONAL)
337=======================================
338As noted earlier, there is an optional implementation framework making it
339easier for platforms to support different kinds of GPIO controller using
340the same programming interface.
341
342As a debugging aid, if debugfs is available a /sys/kernel/debug/gpio file
343will be found there. That will list all the controllers registered through
344this framework, and the state of the GPIOs currently in use.
345
346
347Controller Drivers: gpio_chip
348-----------------------------
349In this framework each GPIO controller is packaged as a "struct gpio_chip"
350with information common to each controller of that type:
351
352 - methods to establish GPIO direction
353 - methods used to access GPIO values
354 - flag saying whether calls to its methods may sleep
355 - optional debugfs dump method (showing extra state like pullup config)
356 - label for diagnostics
357
358There is also per-instance data, which may come from device.platform_data:
359the number of its first GPIO, and how many GPIOs it exposes.
360
361The code implementing a gpio_chip should support multiple instances of the
362controller, possibly using the driver model. That code will configure each
363gpio_chip and issue gpiochip_add(). Removing a GPIO controller should be
364rare; use gpiochip_remove() when it is unavoidable.
365
366Most often a gpio_chip is part of an instance-specific structure with state
367not exposed by the GPIO interfaces, such as addressing, power management,
368and more. Chips such as codecs will have complex non-GPIO state,
369
370Any debugfs dump method should normally ignore signals which haven't been
371requested as GPIOs. They can use gpiochip_is_requested(), which returns
372either NULL or the label associated with that GPIO when it was requested.
373
374
375Platform Support
376----------------
377To support this framework, a platform's Kconfig will "select HAVE_GPIO_LIB"
378and arrange that its <asm/gpio.h> includes <asm-generic/gpio.h> and defines
379three functions: gpio_get_value(), gpio_set_value(), and gpio_cansleep().
380They may also want to provide a custom value for ARCH_NR_GPIOS.
381
382Trivial implementations of those functions can directly use framework
383code, which always dispatches through the gpio_chip:
384
385 #define gpio_get_value __gpio_get_value
386 #define gpio_set_value __gpio_set_value
387 #define gpio_cansleep __gpio_cansleep
388
389Fancier implementations could instead define those as inline functions with
390logic optimizing access to specific SOC-based GPIOs. For example, if the
391referenced GPIO is the constant "12", getting or setting its value could
392cost as little as two or three instructions, never sleeping. When such an
393optimization is not possible those calls must delegate to the framework
394code, costing at least a few dozen instructions. For bitbanged I/O, such
395instruction savings can be significant.
396
397For SOCs, platform-specific code defines and registers gpio_chip instances
398for each bank of on-chip GPIOs. Those GPIOs should be numbered/labeled to
399match chip vendor documentation, and directly match board schematics. They
400may well start at zero and go up to a platform-specific limit. Such GPIOs
401are normally integrated into platform initialization to make them always be
402available, from arch_initcall() or earlier; they can often serve as IRQs.
403
404
405Board Support
406-------------
407For external GPIO controllers -- such as I2C or SPI expanders, ASICs, multi
408function devices, FPGAs or CPLDs -- most often board-specific code handles
409registering controller devices and ensures that their drivers know what GPIO
410numbers to use with gpiochip_add(). Their numbers often start right after
411platform-specific GPIOs.
412
413For example, board setup code could create structures identifying the range
414of GPIOs that chip will expose, and passes them to each GPIO expander chip
415using platform_data. Then the chip driver's probe() routine could pass that
416data to gpiochip_add().
417
418Initialization order can be important. For example, when a device relies on
419an I2C-based GPIO, its probe() routine should only be called after that GPIO
420becomes available. That may mean the device should not be registered until
421calls for that GPIO can work. One way to address such dependencies is for
422such gpio_chip controllers to provide setup() and teardown() callbacks to
423board specific code; those board specific callbacks would register devices
424once all the necessary resources are available.