gpio.txt 19.8 KB
Newer Older
D
David Brownell 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
GPIO Interfaces

This provides an overview of GPIO access conventions on Linux.


What is a GPIO?
===============
A "General Purpose Input/Output" (GPIO) is a flexible software-controlled
digital signal.  They are provided from many kinds of chip, and are familiar
to Linux developers working with embedded and custom hardware.  Each GPIO
represents a bit connected to a particular pin, or "ball" on Ball Grid Array
(BGA) packages.  Board schematics show which external hardware connects to
which GPIOs.  Drivers can be written generically, so that board setup code
passes such pin configuration data to drivers.

System-on-Chip (SOC) processors heavily rely on GPIOs.  In some cases, every
non-dedicated pin can be configured as a GPIO; and most chips have at least
several dozen of them.  Programmable logic devices (like FPGAs) can easily
provide GPIOs; multifunction chips like power managers, and audio codecs
often have a few such pins to help with pin scarcity on SOCs; and there are
also "GPIO Expander" chips that connect using the I2C or SPI serial busses.
Most PC southbridges have a few dozen GPIO-capable pins (with only the BIOS
firmware knowing how they're used).

The exact capabilities of GPIOs vary between systems.  Common options:

  - Output values are writable (high=1, low=0).  Some chips also have
    options about how that value is driven, so that for example only one
    value might be driven ... supporting "wire-OR" and similar schemes
30
    for the other value (notably, "open drain" signaling).
D
David Brownell 已提交
31 32 33 34

  - Input values are likewise readable (1, 0).  Some chips support readback
    of pins configured as "output", which is very useful in such "wire-OR"
    cases (to support bidirectional signaling).  GPIO controllers may have
35
    input de-glitch/debounce logic, sometimes with software controls.
D
David Brownell 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

  - Inputs can often be used as IRQ signals, often edge triggered but
    sometimes level triggered.  Such IRQs may be configurable as system
    wakeup events, to wake the system from a low power state.

  - Usually a GPIO will be configurable as either input or output, as needed
    by different product boards; single direction ones exist too.

  - Most GPIOs can be accessed while holding spinlocks, but those accessed
    through a serial bus normally can't.  Some systems support both types.

On a given board each GPIO is used for one specific purpose like monitoring
MMC/SD card insertion/removal, detecting card writeprotect status, driving
a LED, configuring a transceiver, bitbanging a serial bus, poking a hardware
watchdog, sensing a switch, and so on.


GPIO conventions
================
Note that this is called a "convention" because you don't need to do it this
way, and it's no crime if you don't.  There **are** cases where portability
is not the main issue; GPIOs are often used for the kind of board-specific
glue logic that may even change between board revisions, and can't ever be
used on a board that's wired differently.  Only least-common-denominator
functionality can be very portable.  Other features are platform-specific,
and that can be critical for glue logic.

63
Plus, this doesn't require any implementation framework, just an interface.
D
David Brownell 已提交
64 65
One platform might implement it as simple inline functions accessing chip
registers; another might implement it by delegating through abstractions
66 67 68 69
used for several very different kinds of GPIO controller.  (There is some
optional code supporting such an implementation strategy, described later
in this document, but drivers acting as clients to the GPIO interface must
not care how it's implemented.)
D
David Brownell 已提交
70 71

That said, if the convention is supported on their platform, drivers should
72 73 74
use it when possible.  Platforms should declare GENERIC_GPIO support in
Kconfig (boolean true), which multi-platform drivers can depend on when
using the include file:
D
David Brownell 已提交
75 76 77 78 79 80

	#include <asm/gpio.h>

If you stick to this convention then it'll be easier for other developers to
see what your code is doing, and help maintain it.

81 82 83
Note that these operations include I/O barriers on platforms which need to
use them; drivers don't need to add them explicitly.

D
David Brownell 已提交
84 85 86 87 88

Identifying GPIOs
-----------------
GPIOs are identified by unsigned integers in the range 0..MAX_INT.  That
reserves "negative" numbers for other purposes like marking signals as
D
David Brownell 已提交
89 90
"not available on this board", or indicating faults.  Code that doesn't
touch the underlying hardware treats these integers as opaque cookies.
D
David Brownell 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

Platforms define how they use those integers, and usually #define symbols
for the GPIO lines so that board-specific setup code directly corresponds
to the relevant schematics.  In contrast, drivers should only use GPIO
numbers passed to them from that setup code, using platform_data to hold
board-specific pin configuration data (along with other board specific
data they need).  That avoids portability problems.

So for example one platform uses numbers 32-159 for GPIOs; while another
uses numbers 0..63 with one set of GPIO controllers, 64-79 with another
type of GPIO controller, and on one particular board 80-95 with an FPGA.
The numbers need not be contiguous; either of those platforms could also
use numbers 2000-2063 to identify GPIOs in a bank of I2C GPIO expanders.

Whether a platform supports multiple GPIO controllers is currently a
platform-specific implementation issue.


Using GPIOs
-----------
One of the first things to do with a GPIO, often in board setup code when
setting up a platform_device using the GPIO, is mark its direction:

	/* set as input or output, returning 0 or negative errno */
	int gpio_direction_input(unsigned gpio);
116
	int gpio_direction_output(unsigned gpio, int value);
D
David Brownell 已提交
117 118 119

The return value is zero for success, else a negative errno.  It should
be checked, since the get/set calls don't have error returns and since
120 121 122
misconfiguration is possible.  You should normally issue these calls from
a task context.  However, for spinlock-safe GPIOs it's OK to use them
before tasking is enabled, as part of early board setup.
D
David Brownell 已提交
123

124 125 126
For output GPIOs, the value provided becomes the initial output value.
This helps avoid signal glitching during system startup.

127 128 129 130 131
For compatibility with legacy interfaces to GPIOs, setting the direction
of a GPIO implicitly requests that GPIO (see below) if it has not been
requested already.  That compatibility may be removed in the future;
explicitly requesting GPIOs is strongly preferred.

D
David Brownell 已提交
132 133 134 135 136 137 138 139 140 141 142 143
Setting the direction can fail if the GPIO number is invalid, or when
that particular GPIO can't be used in that mode.  It's generally a bad
idea to rely on boot firmware to have set the direction correctly, since
it probably wasn't validated to do more than boot Linux.  (Similarly,
that board setup code probably needs to multiplex that pin as a GPIO,
and configure pullups/pulldowns appropriately.)


Spinlock-Safe GPIO access
-------------------------
Most GPIO controllers can be accessed with memory read/write instructions.
That doesn't need to sleep, and can safely be done from inside IRQ handlers.
144
(That includes hardirq contexts on RT kernels.)
D
David Brownell 已提交
145 146 147 148 149 150 151 152 153 154 155 156

Use these calls to access such GPIOs:

	/* GPIO INPUT:  return zero or nonzero */
	int gpio_get_value(unsigned gpio);

	/* GPIO OUTPUT */
	void gpio_set_value(unsigned gpio, int value);

The values are boolean, zero for low, nonzero for high.  When reading the
value of an output pin, the value returned should be what's seen on the
pin ... that won't always match the specified output value, because of
157
issues including open-drain signaling and output latencies.
D
David Brownell 已提交
158 159

The get/set calls have no error returns because "invalid GPIO" should have
D
David Brownell 已提交
160
been reported earlier from gpio_direction_*().  However, note that not all
D
David Brownell 已提交
161
platforms can read the value of output pins; those that can't should always
D
David Brownell 已提交
162 163
return zero.  Also, using these calls for GPIOs that can't safely be accessed
without sleeping (see below) is an error.
D
David Brownell 已提交
164

D
David Brownell 已提交
165
Platform-specific implementations are encouraged to optimize the two
D
David Brownell 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
calls to access the GPIO value in cases where the GPIO number (and for
output, value) are constant.  It's normal for them to need only a couple
of instructions in such cases (reading or writing a hardware register),
and not to need spinlocks.  Such optimized calls can make bitbanging
applications a lot more efficient (in both space and time) than spending
dozens of instructions on subroutine calls.


GPIO access that may sleep
--------------------------
Some GPIO controllers must be accessed using message based busses like I2C
or SPI.  Commands to read or write those GPIO values require waiting to
get to the head of a queue to transmit a command and get its response.
This requires sleeping, which can't be done from inside IRQ handlers.

Platforms that support this type of GPIO distinguish them from other GPIOs
182 183
by returning nonzero from this call (which requires a valid GPIO number,
either explicitly or implicitly requested):
D
David Brownell 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214

	int gpio_cansleep(unsigned gpio);

To access such GPIOs, a different set of accessors is defined:

	/* GPIO INPUT:  return zero or nonzero, might sleep */
	int gpio_get_value_cansleep(unsigned gpio);

	/* GPIO OUTPUT, might sleep */
	void gpio_set_value_cansleep(unsigned gpio, int value);

Other than the fact that these calls might sleep, and will not be ignored
for GPIOs that can't be accessed from IRQ handlers, these calls act the
same as the spinlock-safe calls.


Claiming and Releasing GPIOs (OPTIONAL)
---------------------------------------
To help catch system configuration errors, two calls are defined.
However, many platforms don't currently support this mechanism.

	/* request GPIO, returning 0 or negative errno.
	 * non-null labels may be useful for diagnostics.
	 */
	int gpio_request(unsigned gpio, const char *label);

	/* release previously-claimed GPIO */
	void gpio_free(unsigned gpio);

Passing invalid GPIO numbers to gpio_request() will fail, as will requesting
GPIOs that have already been claimed with that call.  The return value of
215 216 217
gpio_request() must be checked.  You should normally issue these calls from
a task context.  However, for spinlock-safe GPIOs it's OK to request GPIOs
before tasking is enabled, as part of early board setup.
D
David Brownell 已提交
218 219 220 221

These calls serve two basic purposes.  One is marking the signals which
are actually in use as GPIOs, for better diagnostics; systems may have
several hundred potential GPIOs, but often only a dozen are used on any
222 223 224 225 226
given board.  Another is to catch conflicts, identifying errors when
(a) two or more drivers wrongly think they have exclusive use of that
signal, or (b) something wrongly believes it's safe to remove drivers
needed to manage a signal that's in active use.  That is, requesting a
GPIO can serve as a kind of lock.
D
David Brownell 已提交
227 228 229 230 231 232 233 234 235 236 237 238

These two calls are optional because not not all current Linux platforms
offer such functionality in their GPIO support; a valid implementation
could return success for all gpio_request() calls.  Unlike the other calls,
the state they represent doesn't normally match anything from a hardware
register; it's just a software bitmap which clearly is not necessary for
correct operation of hardware or (bug free) drivers.

Note that requesting a GPIO does NOT cause it to be configured in any
way; it just marks that GPIO as in use.  Separate code must handle any
pin setup (e.g. controlling which pin the GPIO uses, pullup/pulldown).

239 240 241
Also note that it's your responsibility to have stopped using a GPIO
before you free it.

D
David Brownell 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256

GPIOs mapped to IRQs
--------------------
GPIO numbers are unsigned integers; so are IRQ numbers.  These make up
two logically distinct namespaces (GPIO 0 need not use IRQ 0).  You can
map between them using calls like:

	/* map GPIO numbers to IRQ numbers */
	int gpio_to_irq(unsigned gpio);

	/* map IRQ numbers to GPIO numbers */
	int irq_to_gpio(unsigned irq);

Those return either the corresponding number in the other namespace, or
else a negative errno code if the mapping can't be done.  (For example,
257
some GPIOs can't be used as IRQs.)  It is an unchecked error to use a GPIO
D
David Brownell 已提交
258
number that wasn't set up as an input using gpio_direction_input(), or
D
David Brownell 已提交
259 260 261 262 263 264 265 266 267 268 269 270
to use an IRQ number that didn't originally come from gpio_to_irq().

These two mapping calls are expected to cost on the order of a single
addition or subtraction.  They're not allowed to sleep.

Non-error values returned from gpio_to_irq() can be passed to request_irq()
or free_irq().  They will often be stored into IRQ resources for platform
devices, by the board-specific initialization code.  Note that IRQ trigger
options are part of the IRQ interface, e.g. IRQF_TRIGGER_FALLING, as are
system wakeup capabilities.

Non-error values returned from irq_to_gpio() would most commonly be used
D
David Brownell 已提交
271 272
with gpio_get_value(), for example to initialize or update driver state
when the IRQ is edge-triggered.
D
David Brownell 已提交
273 274


275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
Emulating Open Drain Signals
----------------------------
Sometimes shared signals need to use "open drain" signaling, where only the
low signal level is actually driven.  (That term applies to CMOS transistors;
"open collector" is used for TTL.)  A pullup resistor causes the high signal
level.  This is sometimes called a "wire-AND"; or more practically, from the
negative logic (low=true) perspective this is a "wire-OR".

One common example of an open drain signal is a shared active-low IRQ line.
Also, bidirectional data bus signals sometimes use open drain signals.

Some GPIO controllers directly support open drain outputs; many don't.  When
you need open drain signaling but your hardware doesn't directly support it,
there's a common idiom you can use to emulate it with any GPIO pin that can
be used as either an input or an output:

 LOW:	gpio_direction_output(gpio, 0) ... this drives the signal
	and overrides the pullup.

 HIGH:	gpio_direction_input(gpio) ... this turns off the output,
	so the pullup (or some other device) controls the signal.

If you are "driving" the signal high but gpio_get_value(gpio) reports a low
value (after the appropriate rise time passes), you know some other component
is driving the shared signal low.  That's not necessarily an error.  As one
common example, that's how I2C clocks are stretched:  a slave that needs a
slower clock delays the rising edge of SCK, and the I2C master adjusts its
signaling rate accordingly.

D
David Brownell 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317

What do these conventions omit?
===============================
One of the biggest things these conventions omit is pin multiplexing, since
this is highly chip-specific and nonportable.  One platform might not need
explicit multiplexing; another might have just two options for use of any
given pin; another might have eight options per pin; another might be able
to route a given GPIO to any one of several pins.  (Yes, those examples all
come from systems that run Linux today.)

Related to multiplexing is configuration and enabling of the pullups or
pulldowns integrated on some platforms.  Not all platforms support them,
or support them in the same way; and any given board might use external
pullups (or pulldowns) so that the on-chip ones should not be used.
318
(When a circuit needs 5 kOhm, on-chip 100 kOhm resistors won't do.)
D
David Brownell 已提交
319 320 321 322

There are other system-specific mechanisms that are not specified here,
like the aforementioned options for input de-glitching and wire-OR output.
Hardware may support reading or writing GPIOs in gangs, but that's usually
D
David Brownell 已提交
323
configuration dependent:  for GPIOs sharing the same bank.  (GPIOs are
D
David Brownell 已提交
324
commonly grouped in banks of 16 or 32, with a given SOC having several such
325 326 327
banks.)  Some systems can trigger IRQs from output GPIOs, or read values
from pins not managed as GPIOs.  Code relying on such mechanisms will
necessarily be nonportable.
D
David Brownell 已提交
328

329
Dynamic definition of GPIOs is not currently standard; for example, as
D
David Brownell 已提交
330 331 332
a side effect of configuring an add-on board with some GPIO expanders.

These calls are purely for kernel space, but a userspace API could be built
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
on top of them.


GPIO implementor's framework (OPTIONAL)
=======================================
As noted earlier, there is an optional implementation framework making it
easier for platforms to support different kinds of GPIO controller using
the same programming interface.

As a debugging aid, if debugfs is available a /sys/kernel/debug/gpio file
will be found there.  That will list all the controllers registered through
this framework, and the state of the GPIOs currently in use.


Controller Drivers: gpio_chip
-----------------------------
In this framework each GPIO controller is packaged as a "struct gpio_chip"
with information common to each controller of that type:

 - methods to establish GPIO direction
 - methods used to access GPIO values
 - flag saying whether calls to its methods may sleep
 - optional debugfs dump method (showing extra state like pullup config)
 - label for diagnostics

There is also per-instance data, which may come from device.platform_data:
the number of its first GPIO, and how many GPIOs it exposes.

The code implementing a gpio_chip should support multiple instances of the
controller, possibly using the driver model.  That code will configure each
gpio_chip and issue gpiochip_add().  Removing a GPIO controller should be
rare; use gpiochip_remove() when it is unavoidable.

Most often a gpio_chip is part of an instance-specific structure with state
not exposed by the GPIO interfaces, such as addressing, power management,
and more.  Chips such as codecs will have complex non-GPIO state,

Any debugfs dump method should normally ignore signals which haven't been
requested as GPIOs.  They can use gpiochip_is_requested(), which returns
either NULL or the label associated with that GPIO when it was requested.


Platform Support
----------------
To support this framework, a platform's Kconfig will "select HAVE_GPIO_LIB"
and arrange that its <asm/gpio.h> includes <asm-generic/gpio.h> and defines
three functions: gpio_get_value(), gpio_set_value(), and gpio_cansleep().
They may also want to provide a custom value for ARCH_NR_GPIOS.

Trivial implementations of those functions can directly use framework
code, which always dispatches through the gpio_chip:

  #define gpio_get_value	__gpio_get_value
  #define gpio_set_value	__gpio_set_value
  #define gpio_cansleep		__gpio_cansleep

Fancier implementations could instead define those as inline functions with
logic optimizing access to specific SOC-based GPIOs.  For example, if the
referenced GPIO is the constant "12", getting or setting its value could
cost as little as two or three instructions, never sleeping.  When such an
optimization is not possible those calls must delegate to the framework
code, costing at least a few dozen instructions.  For bitbanged I/O, such
instruction savings can be significant.

For SOCs, platform-specific code defines and registers gpio_chip instances
for each bank of on-chip GPIOs.  Those GPIOs should be numbered/labeled to
match chip vendor documentation, and directly match board schematics.  They
may well start at zero and go up to a platform-specific limit.  Such GPIOs
are normally integrated into platform initialization to make them always be
available, from arch_initcall() or earlier; they can often serve as IRQs.


Board Support
-------------
For external GPIO controllers -- such as I2C or SPI expanders, ASICs, multi
function devices, FPGAs or CPLDs -- most often board-specific code handles
registering controller devices and ensures that their drivers know what GPIO
numbers to use with gpiochip_add().  Their numbers often start right after
platform-specific GPIOs.

For example, board setup code could create structures identifying the range
of GPIOs that chip will expose, and passes them to each GPIO expander chip
using platform_data.  Then the chip driver's probe() routine could pass that
data to gpiochip_add().

Initialization order can be important.  For example, when a device relies on
an I2C-based GPIO, its probe() routine should only be called after that GPIO
becomes available.  That may mean the device should not be registered until
calls for that GPIO can work.  One way to address such dependencies is for
such gpio_chip controllers to provide setup() and teardown() callbacks to
board specific code; those board specific callbacks would register devices
once all the necessary resources are available.