0001 ======================
0002 Legacy GPIO Interfaces
0003 ======================
0004
0005 This provides an overview of GPIO access conventions on Linux.
0006
0007 These calls use the gpio_* naming prefix. No other calls should use that
0008 prefix, or the related __gpio_* prefix.
0009
0010
0011 What is a GPIO?
0012 ===============
0013 A "General Purpose Input/Output" (GPIO) is a flexible software-controlled
0014 digital signal. They are provided from many kinds of chip, and are familiar
0015 to Linux developers working with embedded and custom hardware. Each GPIO
0016 represents a bit connected to a particular pin, or "ball" on Ball Grid Array
0017 (BGA) packages. Board schematics show which external hardware connects to
0018 which GPIOs. Drivers can be written generically, so that board setup code
0019 passes such pin configuration data to drivers.
0020
0021 System-on-Chip (SOC) processors heavily rely on GPIOs. In some cases, every
0022 non-dedicated pin can be configured as a GPIO; and most chips have at least
0023 several dozen of them. Programmable logic devices (like FPGAs) can easily
0024 provide GPIOs; multifunction chips like power managers, and audio codecs
0025 often have a few such pins to help with pin scarcity on SOCs; and there are
0026 also "GPIO Expander" chips that connect using the I2C or SPI serial busses.
0027 Most PC southbridges have a few dozen GPIO-capable pins (with only the BIOS
0028 firmware knowing how they're used).
0029
0030 The exact capabilities of GPIOs vary between systems. Common options:
0031
0032 - Output values are writable (high=1, low=0). Some chips also have
0033 options about how that value is driven, so that for example only one
0034 value might be driven ... supporting "wire-OR" and similar schemes
0035 for the other value (notably, "open drain" signaling).
0036
0037 - Input values are likewise readable (1, 0). Some chips support readback
0038 of pins configured as "output", which is very useful in such "wire-OR"
0039 cases (to support bidirectional signaling). GPIO controllers may have
0040 input de-glitch/debounce logic, sometimes with software controls.
0041
0042 - Inputs can often be used as IRQ signals, often edge triggered but
0043 sometimes level triggered. Such IRQs may be configurable as system
0044 wakeup events, to wake the system from a low power state.
0045
0046 - Usually a GPIO will be configurable as either input or output, as needed
0047 by different product boards; single direction ones exist too.
0048
0049 - Most GPIOs can be accessed while holding spinlocks, but those accessed
0050 through a serial bus normally can't. Some systems support both types.
0051
0052 On a given board each GPIO is used for one specific purpose like monitoring
0053 MMC/SD card insertion/removal, detecting card writeprotect status, driving
0054 a LED, configuring a transceiver, bitbanging a serial bus, poking a hardware
0055 watchdog, sensing a switch, and so on.
0056
0057
0058 GPIO conventions
0059 ================
0060 Note that this is called a "convention" because you don't need to do it this
0061 way, and it's no crime if you don't. There **are** cases where portability
0062 is not the main issue; GPIOs are often used for the kind of board-specific
0063 glue logic that may even change between board revisions, and can't ever be
0064 used on a board that's wired differently. Only least-common-denominator
0065 functionality can be very portable. Other features are platform-specific,
0066 and that can be critical for glue logic.
0067
0068 Plus, this doesn't require any implementation framework, just an interface.
0069 One platform might implement it as simple inline functions accessing chip
0070 registers; another might implement it by delegating through abstractions
0071 used for several very different kinds of GPIO controller. (There is some
0072 optional code supporting such an implementation strategy, described later
0073 in this document, but drivers acting as clients to the GPIO interface must
0074 not care how it's implemented.)
0075
0076 That said, if the convention is supported on their platform, drivers should
0077 use it when possible. Platforms must select GPIOLIB if GPIO functionality
0078 is strictly required. Drivers that can't work without
0079 standard GPIO calls should have Kconfig entries which depend on GPIOLIB. The
0080 GPIO calls are available, either as "real code" or as optimized-away stubs,
0081 when drivers use the include file:
0082
0083 #include <linux/gpio.h>
0084
0085 If you stick to this convention then it'll be easier for other developers to
0086 see what your code is doing, and help maintain it.
0087
0088 Note that these operations include I/O barriers on platforms which need to
0089 use them; drivers don't need to add them explicitly.
0090
0091
0092 Identifying GPIOs
0093 -----------------
0094 GPIOs are identified by unsigned integers in the range 0..MAX_INT. That
0095 reserves "negative" numbers for other purposes like marking signals as
0096 "not available on this board", or indicating faults. Code that doesn't
0097 touch the underlying hardware treats these integers as opaque cookies.
0098
0099 Platforms define how they use those integers, and usually #define symbols
0100 for the GPIO lines so that board-specific setup code directly corresponds
0101 to the relevant schematics. In contrast, drivers should only use GPIO
0102 numbers passed to them from that setup code, using platform_data to hold
0103 board-specific pin configuration data (along with other board specific
0104 data they need). That avoids portability problems.
0105
0106 So for example one platform uses numbers 32-159 for GPIOs; while another
0107 uses numbers 0..63 with one set of GPIO controllers, 64-79 with another
0108 type of GPIO controller, and on one particular board 80-95 with an FPGA.
0109 The numbers need not be contiguous; either of those platforms could also
0110 use numbers 2000-2063 to identify GPIOs in a bank of I2C GPIO expanders.
0111
0112 If you want to initialize a structure with an invalid GPIO number, use
0113 some negative number (perhaps "-EINVAL"); that will never be valid. To
0114 test if such number from such a structure could reference a GPIO, you
0115 may use this predicate:
0116
0117 int gpio_is_valid(int number);
0118
0119 A number that's not valid will be rejected by calls which may request
0120 or free GPIOs (see below). Other numbers may also be rejected; for
0121 example, a number might be valid but temporarily unused on a given board.
0122
0123 Whether a platform supports multiple GPIO controllers is a platform-specific
0124 implementation issue, as are whether that support can leave "holes" in the space
0125 of GPIO numbers, and whether new controllers can be added at runtime. Such issues
0126 can affect things including whether adjacent GPIO numbers are both valid.
0127
0128 Using GPIOs
0129 -----------
0130 The first thing a system should do with a GPIO is allocate it, using
0131 the gpio_request() call; see later.
0132
0133 One of the next things to do with a GPIO, often in board setup code when
0134 setting up a platform_device using the GPIO, is mark its direction::
0135
0136 /* set as input or output, returning 0 or negative errno */
0137 int gpio_direction_input(unsigned gpio);
0138 int gpio_direction_output(unsigned gpio, int value);
0139
0140 The return value is zero for success, else a negative errno. It should
0141 be checked, since the get/set calls don't have error returns and since
0142 misconfiguration is possible. You should normally issue these calls from
0143 a task context. However, for spinlock-safe GPIOs it's OK to use them
0144 before tasking is enabled, as part of early board setup.
0145
0146 For output GPIOs, the value provided becomes the initial output value.
0147 This helps avoid signal glitching during system startup.
0148
0149 For compatibility with legacy interfaces to GPIOs, setting the direction
0150 of a GPIO implicitly requests that GPIO (see below) if it has not been
0151 requested already. That compatibility is being removed from the optional
0152 gpiolib framework.
0153
0154 Setting the direction can fail if the GPIO number is invalid, or when
0155 that particular GPIO can't be used in that mode. It's generally a bad
0156 idea to rely on boot firmware to have set the direction correctly, since
0157 it probably wasn't validated to do more than boot Linux. (Similarly,
0158 that board setup code probably needs to multiplex that pin as a GPIO,
0159 and configure pullups/pulldowns appropriately.)
0160
0161
0162 Spinlock-Safe GPIO access
0163 -------------------------
0164 Most GPIO controllers can be accessed with memory read/write instructions.
0165 Those don't need to sleep, and can safely be done from inside hard
0166 (nonthreaded) IRQ handlers and similar contexts.
0167
0168 Use the following calls to access such GPIOs,
0169 for which gpio_cansleep() will always return false (see below)::
0170
0171 /* GPIO INPUT: return zero or nonzero */
0172 int gpio_get_value(unsigned gpio);
0173
0174 /* GPIO OUTPUT */
0175 void gpio_set_value(unsigned gpio, int value);
0176
0177 The values are boolean, zero for low, nonzero for high. When reading the
0178 value of an output pin, the value returned should be what's seen on the
0179 pin ... that won't always match the specified output value, because of
0180 issues including open-drain signaling and output latencies.
0181
0182 The get/set calls have no error returns because "invalid GPIO" should have
0183 been reported earlier from gpio_direction_*(). However, note that not all
0184 platforms can read the value of output pins; those that can't should always
0185 return zero. Also, using these calls for GPIOs that can't safely be accessed
0186 without sleeping (see below) is an error.
0187
0188 Platform-specific implementations are encouraged to optimize the two
0189 calls to access the GPIO value in cases where the GPIO number (and for
0190 output, value) are constant. It's normal for them to need only a couple
0191 of instructions in such cases (reading or writing a hardware register),
0192 and not to need spinlocks. Such optimized calls can make bitbanging
0193 applications a lot more efficient (in both space and time) than spending
0194 dozens of instructions on subroutine calls.
0195
0196
0197 GPIO access that may sleep
0198 --------------------------
0199 Some GPIO controllers must be accessed using message based busses like I2C
0200 or SPI. Commands to read or write those GPIO values require waiting to
0201 get to the head of a queue to transmit a command and get its response.
0202 This requires sleeping, which can't be done from inside IRQ handlers.
0203
0204 Platforms that support this type of GPIO distinguish them from other GPIOs
0205 by returning nonzero from this call (which requires a valid GPIO number,
0206 which should have been previously allocated with gpio_request)::
0207
0208 int gpio_cansleep(unsigned gpio);
0209
0210 To access such GPIOs, a different set of accessors is defined::
0211
0212 /* GPIO INPUT: return zero or nonzero, might sleep */
0213 int gpio_get_value_cansleep(unsigned gpio);
0214
0215 /* GPIO OUTPUT, might sleep */
0216 void gpio_set_value_cansleep(unsigned gpio, int value);
0217
0218
0219 Accessing such GPIOs requires a context which may sleep, for example
0220 a threaded IRQ handler, and those accessors must be used instead of
0221 spinlock-safe accessors without the cansleep() name suffix.
0222
0223 Other than the fact that these accessors might sleep, and will work
0224 on GPIOs that can't be accessed from hardIRQ handlers, these calls act
0225 the same as the spinlock-safe calls.
0226
0227 **IN ADDITION** calls to setup and configure such GPIOs must be made
0228 from contexts which may sleep, since they may need to access the GPIO
0229 controller chip too (These setup calls are usually made from board
0230 setup or driver probe/teardown code, so this is an easy constraint.)::
0231
0232 gpio_direction_input()
0233 gpio_direction_output()
0234 gpio_request()
0235
0236 ## gpio_request_one()
0237 ## gpio_request_array()
0238 ## gpio_free_array()
0239
0240 gpio_free()
0241 gpio_set_debounce()
0242
0243
0244
0245 Claiming and Releasing GPIOs
0246 ----------------------------
0247 To help catch system configuration errors, two calls are defined::
0248
0249 /* request GPIO, returning 0 or negative errno.
0250 * non-null labels may be useful for diagnostics.
0251 */
0252 int gpio_request(unsigned gpio, const char *label);
0253
0254 /* release previously-claimed GPIO */
0255 void gpio_free(unsigned gpio);
0256
0257 Passing invalid GPIO numbers to gpio_request() will fail, as will requesting
0258 GPIOs that have already been claimed with that call. The return value of
0259 gpio_request() must be checked. You should normally issue these calls from
0260 a task context. However, for spinlock-safe GPIOs it's OK to request GPIOs
0261 before tasking is enabled, as part of early board setup.
0262
0263 These calls serve two basic purposes. One is marking the signals which
0264 are actually in use as GPIOs, for better diagnostics; systems may have
0265 several hundred potential GPIOs, but often only a dozen are used on any
0266 given board. Another is to catch conflicts, identifying errors when
0267 (a) two or more drivers wrongly think they have exclusive use of that
0268 signal, or (b) something wrongly believes it's safe to remove drivers
0269 needed to manage a signal that's in active use. That is, requesting a
0270 GPIO can serve as a kind of lock.
0271
0272 Some platforms may also use knowledge about what GPIOs are active for
0273 power management, such as by powering down unused chip sectors and, more
0274 easily, gating off unused clocks.
0275
0276 For GPIOs that use pins known to the pinctrl subsystem, that subsystem should
0277 be informed of their use; a gpiolib driver's .request() operation may call
0278 pinctrl_gpio_request(), and a gpiolib driver's .free() operation may call
0279 pinctrl_gpio_free(). The pinctrl subsystem allows a pinctrl_gpio_request()
0280 to succeed concurrently with a pin or pingroup being "owned" by a device for
0281 pin multiplexing.
0282
0283 Any programming of pin multiplexing hardware that is needed to route the
0284 GPIO signal to the appropriate pin should occur within a GPIO driver's
0285 .direction_input() or .direction_output() operations, and occur after any
0286 setup of an output GPIO's value. This allows a glitch-free migration from a
0287 pin's special function to GPIO. This is sometimes required when using a GPIO
0288 to implement a workaround on signals typically driven by a non-GPIO HW block.
0289
0290 Some platforms allow some or all GPIO signals to be routed to different pins.
0291 Similarly, other aspects of the GPIO or pin may need to be configured, such as
0292 pullup/pulldown. Platform software should arrange that any such details are
0293 configured prior to gpio_request() being called for those GPIOs, e.g. using
0294 the pinctrl subsystem's mapping table, so that GPIO users need not be aware
0295 of these details.
0296
0297 Also note that it's your responsibility to have stopped using a GPIO
0298 before you free it.
0299
0300 Considering in most cases GPIOs are actually configured right after they
0301 are claimed, three additional calls are defined::
0302
0303 /* request a single GPIO, with initial configuration specified by
0304 * 'flags', identical to gpio_request() wrt other arguments and
0305 * return value
0306 */
0307 int gpio_request_one(unsigned gpio, unsigned long flags, const char *label);
0308
0309 /* request multiple GPIOs in a single call
0310 */
0311 int gpio_request_array(struct gpio *array, size_t num);
0312
0313 /* release multiple GPIOs in a single call
0314 */
0315 void gpio_free_array(struct gpio *array, size_t num);
0316
0317 where 'flags' is currently defined to specify the following properties:
0318
0319 * GPIOF_DIR_IN - to configure direction as input
0320 * GPIOF_DIR_OUT - to configure direction as output
0321
0322 * GPIOF_INIT_LOW - as output, set initial level to LOW
0323 * GPIOF_INIT_HIGH - as output, set initial level to HIGH
0324 * GPIOF_OPEN_DRAIN - gpio pin is open drain type.
0325 * GPIOF_OPEN_SOURCE - gpio pin is open source type.
0326
0327 * GPIOF_EXPORT_DIR_FIXED - export gpio to sysfs, keep direction
0328 * GPIOF_EXPORT_DIR_CHANGEABLE - also export, allow changing direction
0329
0330 since GPIOF_INIT_* are only valid when configured as output, so group valid
0331 combinations as:
0332
0333 * GPIOF_IN - configure as input
0334 * GPIOF_OUT_INIT_LOW - configured as output, initial level LOW
0335 * GPIOF_OUT_INIT_HIGH - configured as output, initial level HIGH
0336
0337 When setting the flag as GPIOF_OPEN_DRAIN then it will assume that pins is
0338 open drain type. Such pins will not be driven to 1 in output mode. It is
0339 require to connect pull-up on such pins. By enabling this flag, gpio lib will
0340 make the direction to input when it is asked to set value of 1 in output mode
0341 to make the pin HIGH. The pin is make to LOW by driving value 0 in output mode.
0342
0343 When setting the flag as GPIOF_OPEN_SOURCE then it will assume that pins is
0344 open source type. Such pins will not be driven to 0 in output mode. It is
0345 require to connect pull-down on such pin. By enabling this flag, gpio lib will
0346 make the direction to input when it is asked to set value of 0 in output mode
0347 to make the pin LOW. The pin is make to HIGH by driving value 1 in output mode.
0348
0349 In the future, these flags can be extended to support more properties.
0350
0351 Further more, to ease the claim/release of multiple GPIOs, 'struct gpio' is
0352 introduced to encapsulate all three fields as::
0353
0354 struct gpio {
0355 unsigned gpio;
0356 unsigned long flags;
0357 const char *label;
0358 };
0359
0360 A typical example of usage::
0361
0362 static struct gpio leds_gpios[] = {
0363 { 32, GPIOF_OUT_INIT_HIGH, "Power LED" }, /* default to ON */
0364 { 33, GPIOF_OUT_INIT_LOW, "Green LED" }, /* default to OFF */
0365 { 34, GPIOF_OUT_INIT_LOW, "Red LED" }, /* default to OFF */
0366 { 35, GPIOF_OUT_INIT_LOW, "Blue LED" }, /* default to OFF */
0367 { ... },
0368 };
0369
0370 err = gpio_request_one(31, GPIOF_IN, "Reset Button");
0371 if (err)
0372 ...
0373
0374 err = gpio_request_array(leds_gpios, ARRAY_SIZE(leds_gpios));
0375 if (err)
0376 ...
0377
0378 gpio_free_array(leds_gpios, ARRAY_SIZE(leds_gpios));
0379
0380
0381 GPIOs mapped to IRQs
0382 --------------------
0383 GPIO numbers are unsigned integers; so are IRQ numbers. These make up
0384 two logically distinct namespaces (GPIO 0 need not use IRQ 0). You can
0385 map between them using calls like::
0386
0387 /* map GPIO numbers to IRQ numbers */
0388 int gpio_to_irq(unsigned gpio);
0389
0390 /* map IRQ numbers to GPIO numbers (avoid using this) */
0391 int irq_to_gpio(unsigned irq);
0392
0393 Those return either the corresponding number in the other namespace, or
0394 else a negative errno code if the mapping can't be done. (For example,
0395 some GPIOs can't be used as IRQs.) It is an unchecked error to use a GPIO
0396 number that wasn't set up as an input using gpio_direction_input(), or
0397 to use an IRQ number that didn't originally come from gpio_to_irq().
0398
0399 These two mapping calls are expected to cost on the order of a single
0400 addition or subtraction. They're not allowed to sleep.
0401
0402 Non-error values returned from gpio_to_irq() can be passed to request_irq()
0403 or free_irq(). They will often be stored into IRQ resources for platform
0404 devices, by the board-specific initialization code. Note that IRQ trigger
0405 options are part of the IRQ interface, e.g. IRQF_TRIGGER_FALLING, as are
0406 system wakeup capabilities.
0407
0408 Non-error values returned from irq_to_gpio() would most commonly be used
0409 with gpio_get_value(), for example to initialize or update driver state
0410 when the IRQ is edge-triggered. Note that some platforms don't support
0411 this reverse mapping, so you should avoid using it.
0412
0413
0414 Emulating Open Drain Signals
0415 ----------------------------
0416 Sometimes shared signals need to use "open drain" signaling, where only the
0417 low signal level is actually driven. (That term applies to CMOS transistors;
0418 "open collector" is used for TTL.) A pullup resistor causes the high signal
0419 level. This is sometimes called a "wire-AND"; or more practically, from the
0420 negative logic (low=true) perspective this is a "wire-OR".
0421
0422 One common example of an open drain signal is a shared active-low IRQ line.
0423 Also, bidirectional data bus signals sometimes use open drain signals.
0424
0425 Some GPIO controllers directly support open drain outputs; many don't. When
0426 you need open drain signaling but your hardware doesn't directly support it,
0427 there's a common idiom you can use to emulate it with any GPIO pin that can
0428 be used as either an input or an output:
0429
0430 LOW: gpio_direction_output(gpio, 0) ... this drives the signal
0431 and overrides the pullup.
0432
0433 HIGH: gpio_direction_input(gpio) ... this turns off the output,
0434 so the pullup (or some other device) controls the signal.
0435
0436 If you are "driving" the signal high but gpio_get_value(gpio) reports a low
0437 value (after the appropriate rise time passes), you know some other component
0438 is driving the shared signal low. That's not necessarily an error. As one
0439 common example, that's how I2C clocks are stretched: a slave that needs a
0440 slower clock delays the rising edge of SCK, and the I2C master adjusts its
0441 signaling rate accordingly.
0442
0443
0444 GPIO controllers and the pinctrl subsystem
0445 ------------------------------------------
0446
0447 A GPIO controller on a SOC might be tightly coupled with the pinctrl
0448 subsystem, in the sense that the pins can be used by other functions
0449 together with an optional gpio feature. We have already covered the
0450 case where e.g. a GPIO controller need to reserve a pin or set the
0451 direction of a pin by calling any of::
0452
0453 pinctrl_gpio_request()
0454 pinctrl_gpio_free()
0455 pinctrl_gpio_direction_input()
0456 pinctrl_gpio_direction_output()
0457
0458 But how does the pin control subsystem cross-correlate the GPIO
0459 numbers (which are a global business) to a certain pin on a certain
0460 pin controller?
0461
0462 This is done by registering "ranges" of pins, which are essentially
0463 cross-reference tables. These are described in
0464 Documentation/driver-api/pin-control.rst
0465
0466 While the pin allocation is totally managed by the pinctrl subsystem,
0467 gpio (under gpiolib) is still maintained by gpio drivers. It may happen
0468 that different pin ranges in a SoC is managed by different gpio drivers.
0469
0470 This makes it logical to let gpio drivers announce their pin ranges to
0471 the pin ctrl subsystem before it will call 'pinctrl_gpio_request' in order
0472 to request the corresponding pin to be prepared by the pinctrl subsystem
0473 before any gpio usage.
0474
0475 For this, the gpio controller can register its pin range with pinctrl
0476 subsystem. There are two ways of doing it currently: with or without DT.
0477
0478 For with DT support refer to Documentation/devicetree/bindings/gpio/gpio.txt.
0479
0480 For non-DT support, user can call gpiochip_add_pin_range() with appropriate
0481 parameters to register a range of gpio pins with a pinctrl driver. For this
0482 exact name string of pinctrl device has to be passed as one of the
0483 argument to this routine.
0484
0485
0486 What do these conventions omit?
0487 ===============================
0488 One of the biggest things these conventions omit is pin multiplexing, since
0489 this is highly chip-specific and nonportable. One platform might not need
0490 explicit multiplexing; another might have just two options for use of any
0491 given pin; another might have eight options per pin; another might be able
0492 to route a given GPIO to any one of several pins. (Yes, those examples all
0493 come from systems that run Linux today.)
0494
0495 Related to multiplexing is configuration and enabling of the pullups or
0496 pulldowns integrated on some platforms. Not all platforms support them,
0497 or support them in the same way; and any given board might use external
0498 pullups (or pulldowns) so that the on-chip ones should not be used.
0499 (When a circuit needs 5 kOhm, on-chip 100 kOhm resistors won't do.)
0500 Likewise drive strength (2 mA vs 20 mA) and voltage (1.8V vs 3.3V) is a
0501 platform-specific issue, as are models like (not) having a one-to-one
0502 correspondence between configurable pins and GPIOs.
0503
0504 There are other system-specific mechanisms that are not specified here,
0505 like the aforementioned options for input de-glitching and wire-OR output.
0506 Hardware may support reading or writing GPIOs in gangs, but that's usually
0507 configuration dependent: for GPIOs sharing the same bank. (GPIOs are
0508 commonly grouped in banks of 16 or 32, with a given SOC having several such
0509 banks.) Some systems can trigger IRQs from output GPIOs, or read values
0510 from pins not managed as GPIOs. Code relying on such mechanisms will
0511 necessarily be nonportable.
0512
0513 Dynamic definition of GPIOs is not currently standard; for example, as
0514 a side effect of configuring an add-on board with some GPIO expanders.
0515
0516
0517 GPIO implementor's framework (OPTIONAL)
0518 =======================================
0519 As noted earlier, there is an optional implementation framework making it
0520 easier for platforms to support different kinds of GPIO controller using
0521 the same programming interface. This framework is called "gpiolib".
0522
0523 As a debugging aid, if debugfs is available a /sys/kernel/debug/gpio file
0524 will be found there. That will list all the controllers registered through
0525 this framework, and the state of the GPIOs currently in use.
0526
0527
0528 Controller Drivers: gpio_chip
0529 -----------------------------
0530 In this framework each GPIO controller is packaged as a "struct gpio_chip"
0531 with information common to each controller of that type:
0532
0533 - methods to establish GPIO direction
0534 - methods used to access GPIO values
0535 - flag saying whether calls to its methods may sleep
0536 - optional debugfs dump method (showing extra state like pullup config)
0537 - label for diagnostics
0538
0539 There is also per-instance data, which may come from device.platform_data:
0540 the number of its first GPIO, and how many GPIOs it exposes.
0541
0542 The code implementing a gpio_chip should support multiple instances of the
0543 controller, possibly using the driver model. That code will configure each
0544 gpio_chip and issue gpiochip_add(). Removing a GPIO controller should be
0545 rare; use gpiochip_remove() when it is unavoidable.
0546
0547 Most often a gpio_chip is part of an instance-specific structure with state
0548 not exposed by the GPIO interfaces, such as addressing, power management,
0549 and more. Chips such as codecs will have complex non-GPIO state.
0550
0551 Any debugfs dump method should normally ignore signals which haven't been
0552 requested as GPIOs. They can use gpiochip_is_requested(), which returns
0553 either NULL or the label associated with that GPIO when it was requested.
0554
0555
0556 Platform Support
0557 ----------------
0558 To force-enable this framework, a platform's Kconfig will "select" GPIOLIB,
0559 else it is up to the user to configure support for GPIO.
0560
0561 It may also provide a custom value for ARCH_NR_GPIOS, so that it better
0562 reflects the number of GPIOs in actual use on that platform, without
0563 wasting static table space. (It should count both built-in/SoC GPIOs and
0564 also ones on GPIO expanders.
0565
0566 If neither of these options are selected, the platform does not support
0567 GPIOs through GPIO-lib and the code cannot be enabled by the user.
0568
0569 Trivial implementations of those functions can directly use framework
0570 code, which always dispatches through the gpio_chip::
0571
0572 #define gpio_get_value __gpio_get_value
0573 #define gpio_set_value __gpio_set_value
0574 #define gpio_cansleep __gpio_cansleep
0575
0576 Fancier implementations could instead define those as inline functions with
0577 logic optimizing access to specific SOC-based GPIOs. For example, if the
0578 referenced GPIO is the constant "12", getting or setting its value could
0579 cost as little as two or three instructions, never sleeping. When such an
0580 optimization is not possible those calls must delegate to the framework
0581 code, costing at least a few dozen instructions. For bitbanged I/O, such
0582 instruction savings can be significant.
0583
0584 For SOCs, platform-specific code defines and registers gpio_chip instances
0585 for each bank of on-chip GPIOs. Those GPIOs should be numbered/labeled to
0586 match chip vendor documentation, and directly match board schematics. They
0587 may well start at zero and go up to a platform-specific limit. Such GPIOs
0588 are normally integrated into platform initialization to make them always be
0589 available, from arch_initcall() or earlier; they can often serve as IRQs.
0590
0591
0592 Board Support
0593 -------------
0594 For external GPIO controllers -- such as I2C or SPI expanders, ASICs, multi
0595 function devices, FPGAs or CPLDs -- most often board-specific code handles
0596 registering controller devices and ensures that their drivers know what GPIO
0597 numbers to use with gpiochip_add(). Their numbers often start right after
0598 platform-specific GPIOs.
0599
0600 For example, board setup code could create structures identifying the range
0601 of GPIOs that chip will expose, and passes them to each GPIO expander chip
0602 using platform_data. Then the chip driver's probe() routine could pass that
0603 data to gpiochip_add().
0604
0605 Initialization order can be important. For example, when a device relies on
0606 an I2C-based GPIO, its probe() routine should only be called after that GPIO
0607 becomes available. That may mean the device should not be registered until
0608 calls for that GPIO can work. One way to address such dependencies is for
0609 such gpio_chip controllers to provide setup() and teardown() callbacks to
0610 board specific code; those board specific callbacks would register devices
0611 once all the necessary resources are available, and remove them later when
0612 the GPIO controller device becomes unavailable.
0613
0614
0615 Sysfs Interface for Userspace (OPTIONAL)
0616 ========================================
0617 Platforms which use the "gpiolib" implementors framework may choose to
0618 configure a sysfs user interface to GPIOs. This is different from the
0619 debugfs interface, since it provides control over GPIO direction and
0620 value instead of just showing a gpio state summary. Plus, it could be
0621 present on production systems without debugging support.
0622
0623 Given appropriate hardware documentation for the system, userspace could
0624 know for example that GPIO #23 controls the write protect line used to
0625 protect boot loader segments in flash memory. System upgrade procedures
0626 may need to temporarily remove that protection, first importing a GPIO,
0627 then changing its output state, then updating the code before re-enabling
0628 the write protection. In normal use, GPIO #23 would never be touched,
0629 and the kernel would have no need to know about it.
0630
0631 Again depending on appropriate hardware documentation, on some systems
0632 userspace GPIO can be used to determine system configuration data that
0633 standard kernels won't know about. And for some tasks, simple userspace
0634 GPIO drivers could be all that the system really needs.
0635
0636 Note that standard kernel drivers exist for common "LEDs and Buttons"
0637 GPIO tasks: "leds-gpio" and "gpio_keys", respectively. Use those
0638 instead of talking directly to the GPIOs; they integrate with kernel
0639 frameworks better than your userspace code could.
0640
0641
0642 Paths in Sysfs
0643 --------------
0644 There are three kinds of entry in /sys/class/gpio:
0645
0646 - Control interfaces used to get userspace control over GPIOs;
0647
0648 - GPIOs themselves; and
0649
0650 - GPIO controllers ("gpio_chip" instances).
0651
0652 That's in addition to standard files including the "device" symlink.
0653
0654 The control interfaces are write-only:
0655
0656 /sys/class/gpio/
0657
0658 "export" ... Userspace may ask the kernel to export control of
0659 a GPIO to userspace by writing its number to this file.
0660
0661 Example: "echo 19 > export" will create a "gpio19" node
0662 for GPIO #19, if that's not requested by kernel code.
0663
0664 "unexport" ... Reverses the effect of exporting to userspace.
0665
0666 Example: "echo 19 > unexport" will remove a "gpio19"
0667 node exported using the "export" file.
0668
0669 GPIO signals have paths like /sys/class/gpio/gpio42/ (for GPIO #42)
0670 and have the following read/write attributes:
0671
0672 /sys/class/gpio/gpioN/
0673
0674 "direction" ... reads as either "in" or "out". This value may
0675 normally be written. Writing as "out" defaults to
0676 initializing the value as low. To ensure glitch free
0677 operation, values "low" and "high" may be written to
0678 configure the GPIO as an output with that initial value.
0679
0680 Note that this attribute *will not exist* if the kernel
0681 doesn't support changing the direction of a GPIO, or
0682 it was exported by kernel code that didn't explicitly
0683 allow userspace to reconfigure this GPIO's direction.
0684
0685 "value" ... reads as either 0 (low) or 1 (high). If the GPIO
0686 is configured as an output, this value may be written;
0687 any nonzero value is treated as high.
0688
0689 If the pin can be configured as interrupt-generating interrupt
0690 and if it has been configured to generate interrupts (see the
0691 description of "edge"), you can poll(2) on that file and
0692 poll(2) will return whenever the interrupt was triggered. If
0693 you use poll(2), set the events POLLPRI. If you use select(2),
0694 set the file descriptor in exceptfds. After poll(2) returns,
0695 either lseek(2) to the beginning of the sysfs file and read the
0696 new value or close the file and re-open it to read the value.
0697
0698 "edge" ... reads as either "none", "rising", "falling", or
0699 "both". Write these strings to select the signal edge(s)
0700 that will make poll(2) on the "value" file return.
0701
0702 This file exists only if the pin can be configured as an
0703 interrupt generating input pin.
0704
0705 "active_low" ... reads as either 0 (false) or 1 (true). Write
0706 any nonzero value to invert the value attribute both
0707 for reading and writing. Existing and subsequent
0708 poll(2) support configuration via the edge attribute
0709 for "rising" and "falling" edges will follow this
0710 setting.
0711
0712 GPIO controllers have paths like /sys/class/gpio/gpiochip42/ (for the
0713 controller implementing GPIOs starting at #42) and have the following
0714 read-only attributes:
0715
0716 /sys/class/gpio/gpiochipN/
0717
0718 "base" ... same as N, the first GPIO managed by this chip
0719
0720 "label" ... provided for diagnostics (not always unique)
0721
0722 "ngpio" ... how many GPIOs this manges (N to N + ngpio - 1)
0723
0724 Board documentation should in most cases cover what GPIOs are used for
0725 what purposes. However, those numbers are not always stable; GPIOs on
0726 a daughtercard might be different depending on the base board being used,
0727 or other cards in the stack. In such cases, you may need to use the
0728 gpiochip nodes (possibly in conjunction with schematics) to determine
0729 the correct GPIO number to use for a given signal.
0730
0731
0732 Exporting from Kernel code
0733 --------------------------
0734 Kernel code can explicitly manage exports of GPIOs which have already been
0735 requested using gpio_request()::
0736
0737 /* export the GPIO to userspace */
0738 int gpio_export(unsigned gpio, bool direction_may_change);
0739
0740 /* reverse gpio_export() */
0741 void gpio_unexport();
0742
0743 /* create a sysfs link to an exported GPIO node */
0744 int gpio_export_link(struct device *dev, const char *name,
0745 unsigned gpio)
0746
0747 After a kernel driver requests a GPIO, it may only be made available in
0748 the sysfs interface by gpio_export(). The driver can control whether the
0749 signal direction may change. This helps drivers prevent userspace code
0750 from accidentally clobbering important system state.
0751
0752 This explicit exporting can help with debugging (by making some kinds
0753 of experiments easier), or can provide an always-there interface that's
0754 suitable for documenting as part of a board support package.
0755
0756 After the GPIO has been exported, gpio_export_link() allows creating
0757 symlinks from elsewhere in sysfs to the GPIO sysfs node. Drivers can
0758 use this to provide the interface under their own device in sysfs with
0759 a descriptive name.
0760
0761
0762 API Reference
0763 =============
0764
0765 The functions listed in this section are deprecated. The GPIO descriptor based
0766 API should be used in new code.
0767
0768 .. kernel-doc:: drivers/gpio/gpiolib-legacy.c
0769 :export: