URL
https://opencores.org/ocsvn/test_project/test_project/trunk
Subversion Repositories test_project
[/] [test_project/] [trunk/] [linux_sd_driver/] [Documentation/] [gpio.txt] - Rev 62
Compare with Previous | Blame | View Log
GPIO InterfacesThis provides an overview of GPIO access conventions on Linux.What is a GPIO?===============A "General Purpose Input/Output" (GPIO) is a flexible software-controlleddigital signal. They are provided from many kinds of chip, and are familiarto Linux developers working with embedded and custom hardware. Each GPIOrepresents a bit connected to a particular pin, or "ball" on Ball Grid Array(BGA) packages. Board schematics show which external hardware connects towhich GPIOs. Drivers can be written generically, so that board setup codepasses such pin configuration data to drivers.System-on-Chip (SOC) processors heavily rely on GPIOs. In some cases, everynon-dedicated pin can be configured as a GPIO; and most chips have at leastseveral dozen of them. Programmable logic devices (like FPGAs) can easilyprovide GPIOs; multifunction chips like power managers, and audio codecsoften have a few such pins to help with pin scarcity on SOCs; and there arealso "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 BIOSfirmware 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 haveoptions about how that value is driven, so that for example only onevalue might be driven ... supporting "wire-OR" and similar schemesfor the other value (notably, "open drain" signaling).- Input values are likewise readable (1, 0). Some chips support readbackof pins configured as "output", which is very useful in such "wire-OR"cases (to support bidirectional signaling). GPIO controllers may haveinput de-glitch logic, sometimes with software controls.- Inputs can often be used as IRQ signals, often edge triggered butsometimes level triggered. Such IRQs may be configurable as systemwakeup events, to wake the system from a low power state.- Usually a GPIO will be configurable as either input or output, as neededby different product boards; single direction ones exist too.- Most GPIOs can be accessed while holding spinlocks, but those accessedthrough a serial bus normally can't. Some systems support both types.On a given board each GPIO is used for one specific purpose like monitoringMMC/SD card insertion/removal, detecting card writeprotect status, drivinga LED, configuring a transceiver, bitbanging a serial bus, poking a hardwarewatchdog, sensing a switch, and so on.GPIO conventions================Note that this is called a "convention" because you don't need to do it thisway, and it's no crime if you don't. There **are** cases where portabilityis not the main issue; GPIOs are often used for the kind of board-specificglue logic that may even change between board revisions, and can't ever beused on a board that's wired differently. Only least-common-denominatorfunctionality can be very portable. Other features are platform-specific,and that can be critical for glue logic.Plus, this doesn't define an implementation framework, just an interface.One platform might implement it as simple inline functions accessing chipregisters; another might implement it by delegating through abstractionsused for several very different kinds of GPIO controller.That said, if the convention is supported on their platform, drivers shoulduse it when possible. Platforms should declare GENERIC_GPIO support inKconfig (boolean true), which multi-platform drivers can depend on whenusing the include file:#include <asm/gpio.h>If you stick to this convention then it'll be easier for other developers tosee what your code is doing, and help maintain it.Note that these operations include I/O barriers on platforms which need touse them; drivers don't need to add them explicitly.Identifying GPIOs-----------------GPIOs are identified by unsigned integers in the range 0..MAX_INT. Thatreserves "negative" numbers for other purposes like marking signals as"not available on this board", or indicating faults. Code that doesn'ttouch the underlying hardware treats these integers as opaque cookies.Platforms define how they use those integers, and usually #define symbolsfor the GPIO lines so that board-specific setup code directly correspondsto the relevant schematics. In contrast, drivers should only use GPIOnumbers passed to them from that setup code, using platform_data to holdboard-specific pin configuration data (along with other board specificdata they need). That avoids portability problems.So for example one platform uses numbers 32-159 for GPIOs; while anotheruses numbers 0..63 with one set of GPIO controllers, 64-79 with anothertype of GPIO controller, and on one particular board 80-95 with an FPGA.The numbers need not be contiguous; either of those platforms could alsouse numbers 2000-2063 to identify GPIOs in a bank of I2C GPIO expanders.Whether a platform supports multiple GPIO controllers is currently aplatform-specific implementation issue.Using GPIOs-----------One of the first things to do with a GPIO, often in board setup code whensetting 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);int gpio_direction_output(unsigned gpio, int value);The return value is zero for success, else a negative errno. It shouldbe checked, since the get/set calls don't have error returns and sincemisconfiguration is possible. You should normally issue these calls froma task context. However, for spinlock-safe GPIOs it's OK to use thembefore tasking is enabled, as part of early board setup.For output GPIOs, the value provided becomes the initial output value.This helps avoid signal glitching during system startup.Setting the direction can fail if the GPIO number is invalid, or whenthat particular GPIO can't be used in that mode. It's generally a badidea to rely on boot firmware to have set the direction correctly, sinceit 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.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 thevalue of an output pin, the value returned should be what's seen on thepin ... that won't always match the specified output value, because ofissues including wire-OR and output latencies.The get/set calls have no error returns because "invalid GPIO" should havebeen reported earlier from gpio_direction_*(). However, note that not allplatforms can read the value of output pins; those that can't should alwaysreturn zero. Also, using these calls for GPIOs that can't safely be accessedwithout sleeping (see below) is an error.Platform-specific implementations are encouraged to optimize the twocalls to access the GPIO value in cases where the GPIO number (and foroutput, value) are constant. It's normal for them to need only a coupleof instructions in such cases (reading or writing a hardware register),and not to need spinlocks. Such optimized calls can make bitbangingapplications a lot more efficient (in both space and time) than spendingdozens of instructions on subroutine calls.GPIO access that may sleep--------------------------Some GPIO controllers must be accessed using message based busses like I2Cor SPI. Commands to read or write those GPIO values require waiting toget 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 GPIOsby returning nonzero from this call: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 ignoredfor GPIOs that can't be accessed from IRQ handlers, these calls act thesame 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 requestingGPIOs that have already been claimed with that call. The return value ofgpio_request() must be checked. You should normally issue these calls froma task context. However, for spinlock-safe GPIOs it's OK to request GPIOsbefore tasking is enabled, as part of early board setup.These calls serve two basic purposes. One is marking the signals whichare actually in use as GPIOs, for better diagnostics; systems may haveseveral hundred potential GPIOs, but often only a dozen are used on anygiven board. Another is to catch conflicts between drivers, reportingerrors when drivers wrongly think they have exclusive use of that signal.These two calls are optional because not not all current Linux platformsoffer such functionality in their GPIO support; a valid implementationcould return success for all gpio_request() calls. Unlike the other calls,the state they represent doesn't normally match anything from a hardwareregister; it's just a software bitmap which clearly is not necessary forcorrect operation of hardware or (bug free) drivers.Note that requesting a GPIO does NOT cause it to be configured in anyway; it just marks that GPIO as in use. Separate code must handle anypin setup (e.g. controlling which pin the GPIO uses, pullup/pulldown).GPIOs mapped to IRQs--------------------GPIO numbers are unsigned integers; so are IRQ numbers. These make uptwo logically distinct namespaces (GPIO 0 need not use IRQ 0). You canmap 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, orelse a negative errno code if the mapping can't be done. (For example,some GPIOs can't used as IRQs.) It is an unchecked error to use a GPIOnumber that wasn't set up as an input using gpio_direction_input(), orto 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 singleaddition 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 platformdevices, by the board-specific initialization code. Note that IRQ triggeroptions are part of the IRQ interface, e.g. IRQF_TRIGGER_FALLING, as aresystem wakeup capabilities.Non-error values returned from irq_to_gpio() would most commonly be usedwith gpio_get_value(), for example to initialize or update driver statewhen the IRQ is edge-triggered.Emulating Open Drain Signals----------------------------Sometimes shared signals need to use "open drain" signaling, where only thelow signal level is actually driven. (That term applies to CMOS transistors;"open collector" is used for TTL.) A pullup resistor causes the high signallevel. This is sometimes called a "wire-AND"; or more practically, from thenegative 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. Whenyou 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 canbe used as either an input or an output:LOW: gpio_direction_output(gpio, 0) ... this drives the signaland 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 lowvalue (after the appropriate rise time passes), you know some other componentis driving the shared signal low. That's not necessarily an error. As onecommon example, that's how I2C clocks are stretched: a slave that needs aslower clock delays the rising edge of SCK, and the I2C master adjusts itssignaling rate accordingly.What do these conventions omit?===============================One of the biggest things these conventions omit is pin multiplexing, sincethis is highly chip-specific and nonportable. One platform might not needexplicit multiplexing; another might have just two options for use of anygiven pin; another might have eight options per pin; another might be ableto route a given GPIO to any one of several pins. (Yes, those examples allcome from systems that run Linux today.)Related to multiplexing is configuration and enabling of the pullups orpulldowns integrated on some platforms. Not all platforms support them,or support them in the same way; and any given board might use externalpullups (or pulldowns) so that the on-chip ones should not be used.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 usuallyconfiguration dependent: for GPIOs sharing the same bank. (GPIOs arecommonly grouped in banks of 16 or 32, with a given SOC having several suchbanks.) Some systems can trigger IRQs from output GPIOs. Code relying onsuch mechanisms will necessarily be nonportable.Dynamic definition of GPIOs is not currently supported; for example, asa 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 builton top of it.
