Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
Peios Kernel

GPIO

Single-page view · as markdown

General Purpose Input/Output (GPIO)

Peios Kernel / Hardware and drivers / Driver development / GPIO

Contents:

  • Introduction
  • Using GPIO Lines in Linux
  • GPIO Driver Interface
  • GPIO Descriptor Consumer Interface
  • GPIO Mappings
  • Supporting Legacy Boards
  • Subsystem drivers using GPIO
  • A driver for a selfmade cheap BT8xx based PCI GPIO-card (bt8xxgpio)
  • PCA953x I²C GPIO expander compatibility list

Core #

struct gpio_irq_chip #

GPIO interrupt controller

Definition

struct gpio_irq_chip {
        struct irq_chip *chip;
        struct irq_domain *domain;
    #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY;
        struct fwnode_handle *fwnode;
        struct irq_domain *parent_domain;
        int (*child_to_parent_hwirq)(struct gpio_chip *gc, unsigned int child_hwirq, unsigned int child_type, unsigned int *parent_hwirq, unsigned int *parent_type);
        int (*populate_parent_alloc_arg)(struct gpio_chip *gc, union gpio_irq_fwspec *fwspec, unsigned int parent_hwirq, unsigned int parent_type);
        unsigned int (*child_offset_to_irq)(struct gpio_chip *gc, unsigned int pin);
        struct irq_domain_ops child_irq_domain_ops;
    #endif;
        irq_flow_handler_t handler;
        unsigned int default_type;
        struct lock_class_key *lock_key;
        struct lock_class_key *request_key;
        irq_flow_handler_t parent_handler;
        union {
            void *parent_handler_data;
            void **parent_handler_data_array;
        };
        unsigned int num_parents;
        unsigned int *parents;
        unsigned int *map;
        bool threaded;
        bool per_parent_data;
        bool initialized;
        bool domain_is_allocated_externally;
        int (*init_hw)(struct gpio_chip *gc);
        void (*init_valid_mask)(struct gpio_chip *gc, unsigned long *valid_mask, unsigned int ngpios);
        unsigned long *valid_mask;
        unsigned int first;
        void (*irq_enable)(struct irq_data *data);
        void (*irq_disable)(struct irq_data *data);
        void (*irq_unmask)(struct irq_data *data);
        void (*irq_mask)(struct irq_data *data);
};

Members

  • chip: GPIO IRQ chip implementation, provided by GPIO driver.

  • domain: Interrupt translation domain; responsible for mapping between GPIO hwirq number and Linux IRQ number.

  • fwnode: Firmware node corresponding to this gpiochip/irqchip, necessary for hierarchical irqdomain support.

  • parent_domain: If non-NULL, will be set as the parent of this GPIO interrupt controller's IRQ domain to establish a hierarchical interrupt domain. The presence of this will activate the hierarchical interrupt support.

  • child_to_parent_hwirq: This callback translates a child hardware IRQ offset to a parent hardware IRQ offset on a hierarchical interrupt chip. The child hardware IRQs correspond to the GPIO index 0..ngpio-1 (see the ngpio field of struct gpio_chip) and the corresponding parent hardware IRQ and type (such as IRQ_TYPE_*) shall be returned by the driver. The driver can calculate this from an offset or using a lookup table or whatever method is best for this chip. Return 0 on successful translation in the driver.

    If some ranges of hardware IRQs do not have a corresponding parent HWIRQ, return -EINVAL, but also make sure to fill in valid_mask and need_valid_mask to make these GPIO lines unavailable for translation.

  • populate_parent_alloc_arg: This optional callback allocates and populates the specific struct for the parent's IRQ domain. If this is not specified, then gpiochip_populate_parent_fwspec_twocell will be used. A four-cell variant named gpiochip_populate_parent_fwspec_fourcell is also available.

  • child_offset_to_irq: This optional callback is used to translate the child's GPIO line offset on the GPIO chip to an IRQ number for the GPIO to_irq() callback. If this is not specified, then a default callback will be provided that returns the line offset.

  • child_irq_domain_ops: The IRQ domain operations that will be used for this GPIO IRQ chip. If no operations are provided, then default callbacks will be populated to setup the IRQ hierarchy. Some drivers need to supply their own translate function.

  • handler: The IRQ handler to use (often a predefined IRQ core function) for GPIO IRQs, provided by GPIO driver.

  • default_type: Default IRQ triggering type applied during GPIO driver initialization, provided by GPIO driver.

  • lock_key: Per GPIO IRQ chip lockdep class for IRQ lock.

  • request_key: Per GPIO IRQ chip lockdep class for IRQ request.

  • parent_handler: The interrupt handler for the GPIO chip's parent interrupts, may be NULL if the parent interrupts are nested rather than cascaded.

  • {unnamed_union}: anonymous

  • parent_handler_data: If per_parent_data is false, parent_handler_data is a single pointer used as the data associated with every parent interrupt.

  • parent_handler_data_array: If per_parent_data is true, parent_handler_data_array is an array of num_parents pointers, and is used to associate different data for each parent. This cannot be NULL if per_parent_data is true.

  • num_parents: The number of interrupt parents of a GPIO chip.

  • parents: A list of interrupt parents of a GPIO chip. This is owned by the driver, so the core will only reference this list, not modify it.

  • map: A list of interrupt parents for each line of a GPIO chip.

  • threaded: True if set the interrupt handling uses nested threads.

  • per_parent_data: True if parent_handler_data_array describes a num_parents sized array to be used as parent data.

  • initialized: Flag to track GPIO chip irq member's initialization. This flag will make sure GPIO chip irq members are not used before they are initialized.

  • domain_is_allocated_externally: True it the irq_domain was allocated outside of gpiolib, in which case gpiolib won't free the irq_domain itself.

  • init_hw: optional routine to initialize hardware before an IRQ chip will be added. This is quite useful when a particular driver wants to clear IRQ related registers in order to avoid undesired events.

  • init_valid_mask: optional routine to initialize valid_mask, to be used if not all GPIO lines are valid interrupts. Sometimes some lines just cannot fire interrupts, and this routine, when defined, is passed a bitmap in "valid_mask" and it will have ngpios bits from 0..(ngpios-1) set to "1" as in valid. The callback can then directly set some bits to "0" if they cannot be used for interrupts.

  • valid_mask: If not NULL, holds bitmask of GPIOs which are valid to be included in IRQ domain of the chip.

  • first: Required for static IRQ allocation. If set, irq_domain_create_simple() will allocate and map all IRQs during initialization.

  • irq_enable: Store old irq_chip irq_enable callback

  • irq_disable: Store old irq_chip irq_disable callback

  • irq_unmask: Store old irq_chip irq_unmask callback

  • irq_mask: Store old irq_chip irq_mask callback

struct gpio_chip #

abstract a GPIO controller

Definition

struct gpio_chip {
        const char              *label;
        struct gpio_device      *gpiodev;
        struct device           *parent;
        struct fwnode_handle    *fwnode;
        struct module           *owner;
        int (*request)(struct gpio_chip *gc, unsigned int offset);
        void (*free)(struct gpio_chip *gc, unsigned int offset);
        int (*get_direction)(struct gpio_chip *gc, unsigned int offset);
        int (*direction_input)(struct gpio_chip *gc, unsigned int offset);
        int (*direction_output)(struct gpio_chip *gc, unsigned int offset, int value);
        int (*get)(struct gpio_chip *gc, unsigned int offset);
        int (*get_multiple)(struct gpio_chip *gc, unsigned long *mask, unsigned long *bits);
        int (*set)(struct gpio_chip *gc, unsigned int offset, int value);
        int (*set_multiple)(struct gpio_chip *gc, unsigned long *mask, unsigned long *bits);
        int (*set_config)(struct gpio_chip *gc, unsigned int offset, unsigned long config);
        int (*to_irq)(struct gpio_chip *gc, unsigned int offset);
        void (*dbg_show)(struct seq_file *s, struct gpio_chip *gc);
        int (*init_valid_mask)(struct gpio_chip *gc, unsigned long *valid_mask, unsigned int ngpios);
        int (*add_pin_ranges)(struct gpio_chip *gc);
        int (*en_hw_timestamp)(struct gpio_chip *gc, u32 offset, unsigned long flags);
        int (*dis_hw_timestamp)(struct gpio_chip *gc, u32 offset, unsigned long flags);
        int base;
        u16 ngpio;
        u16 offset;
        const char              *const *names;
        bool can_sleep;
    #ifdef CONFIG_GPIOLIB_IRQCHIP;
        struct gpio_irq_chip irq;
    #endif;
    #if defined(CONFIG_OF_GPIO);
        unsigned int of_gpio_n_cells;
        bool (*of_node_instance_match)(struct gpio_chip *gc, unsigned int i);
        int (*of_xlate)(struct gpio_chip *gc, const struct of_phandle_args *gpiospec, u32 *flags);
    #endif;
};

Members

  • label: a functional name for the GPIO device, such as a part number or the name of the SoC IP-block implementing it.

  • gpiodev: the internal state holder, opaque struct

  • parent: optional parent device providing the GPIOs

  • fwnode: optional fwnode providing this controller's properties

  • owner: helps prevent removal of modules exporting active GPIOs

  • request: optional hook for chip-specific activation, such as enabling module power and clock; may sleep; must return 0 on success or negative error number on failure

  • free: optional hook for chip-specific deactivation, such as disabling module power and clock; may sleep

  • get_direction: returns direction for signal "offset", 0=out, 1=in, (same as GPIO_LINE_DIRECTION_OUT / GPIO_LINE_DIRECTION_IN), or negative error. It is recommended to always implement this function, even on input-only or output-only gpio chips.

  • direction_input: configures signal "offset" as input, returns 0 on success or a negative error number. This can be omitted on input-only or output-only gpio chips.

  • direction_output: configures signal "offset" as output, returns 0 on success or a negative error number. This can be omitted on input-only or output-only gpio chips.

  • get: returns value for signal "offset", 0=low, 1=high, or negative error

  • get_multiple: reads values for multiple signals defined by "mask" and stores them in "bits", returns 0 on success or negative error

  • set: assigns output value for signal "offset", returns 0 on success or negative error value

  • set_multiple: assigns output values for multiple signals defined by "mask", returns 0 on success or negative error value

  • set_config: optional hook for all kinds of settings. Uses the same packed config format as generic pinconf. Must return 0 on success and a negative error number on failure.

  • to_irq: optional hook supporting non-static gpiod_to_irq() mappings; implementation may not sleep

  • dbg_show: optional routine to show contents in debugfs; default code will be used when this is omitted, but custom code can show extra state (such as pullup/pulldown configuration).

  • init_valid_mask: optional routine to initialize valid_mask, to be used if not all GPIOs are valid.

  • add_pin_ranges: optional routine to initialize pin ranges, to be used when requires special mapping of the pins that provides GPIO functionality. It is called after adding GPIO chip and before adding IRQ chip.

  • en_hw_timestamp: Dependent on GPIO chip, an optional routine to enable hardware timestamp.

  • dis_hw_timestamp: Dependent on GPIO chip, an optional routine to disable hardware timestamp.

  • base: identifies the first GPIO number handled by this chip; or, if negative during registration, requests dynamic ID allocation. DEPRECATION: providing anything non-negative and nailing the base offset of GPIO chips is deprecated. Please pass -1 as base to let gpiolib select the chip base in all possible cases. We want to get rid of the static GPIO number space in the long run.

  • ngpio: the number of GPIOs handled by this controller; the last GPIO handled is (base + ngpio - 1).

  • offset: when multiple gpio chips belong to the same device this can be used as offset within the device so friendly names can be properly assigned.

  • names: if set, must be an array of strings to use as alternative names for the GPIOs in this chip. Any entry in the array may be NULL if there is no alias for the GPIO, however the array must be ngpio entries long.

  • can_sleep: flag must be set iff get()/set() methods sleep, as they must while accessing GPIO expander chips over I2C or SPI. This implies that if the chip supports IRQs, these IRQs need to be threaded as the chip access may sleep when e.g. reading out the IRQ status registers.

  • irq: Integrates interrupt chip functionality with the GPIO chip. Can be used to handle IRQs for most practical cases.

  • of_gpio_n_cells: Number of cells used to form the GPIO specifier. The standard is 2 cells:

    gpios = <gpio offset flags>;

    some complex GPIO controllers instantiate more than one chip per device tree node and have 3 cells:

    gpios = <gpio instance offset flags>;

    Legacy GPIO controllers may even have 1 cell:

    gpios = <gpio offset>;

  • of_node_instance_match: Determine if a chip is the right instance. Must be implemented by any driver using more than one gpio_chip per device tree node. Returns true if gc is the instance indicated by i (which is the first cell in the phandles for GPIO lines and gpio-ranges).

  • of_xlate: Callback to translate a device tree GPIO specifier into a chip- relative GPIO number and flags.

Description

A gpio_chip can help platforms abstract various sources of GPIOs so they can all be accessed through a common programming interface. Example sources would be SOC controllers, FPGAs, multifunction chips, dedicated GPIO expanders, and so on.

Each chip controls a number of signals, identified in method calls by "offset" values in the range 0..(ngpio - 1). When those signals are referenced through calls like gpio_get_value(gpio), the offset is calculated by subtracting base from the gpio number.

for_each_hwgpio_in_range() #

for_each_hwgpio_in_range(_chip, _i, _base, _size, _label)

Iterates over all GPIOs in a given range

Parameters

  • _chip: Chip to iterate over.
  • _i: Loop counter.
  • _base: First GPIO in the ranger.
  • _size: Amount of GPIOs to check starting from base.
  • _label: Place to store the address of the label if the GPIO is requested. Set to NULL for unused GPIOs.

for_each_hwgpio() #

for_each_hwgpio(_chip, _i, _label)

Iterates over all GPIOs for given chip.

Parameters

  • _chip: Chip to iterate over.
  • _i: Loop counter.
  • _label: Place to store the address of the label if the GPIO is requested. Set to NULL for unused GPIOs.

for_each_requested_gpio_in_range() #

for_each_requested_gpio_in_range(_chip, _i, _base, _size, _label)

iterates over requested GPIOs in a given range

Parameters

  • _chip: the chip to query
  • _i: loop variable
  • _base: first GPIO in the range
  • _size: amount of GPIOs to check starting from base
  • _label: label of current GPIO

gpiochip_add_data() #

gpiochip_add_data(gc, data)

register a gpio_chip

Parameters

  • gc: the chip to register, with gc->base initialized
  • data: driver-private data associated with this chip

Context

potentially before irqs will work

Description

When gpiochip_add_data() is called very early during boot, so that GPIOs can be freely used, the gc->parent device must be registered before the gpio framework's arch_initcall(). Otherwise sysfs initialization for GPIOs will fail rudely.

gpiochip_add_data() must only be called after gpiolib initialization, i.e. after core_initcall().

If gc->base is negative, this requests dynamic assignment of a range of valid GPIOs.

Return

A negative errno if the chip can't be registered, such as because the gc->base is invalid or already associated with a different chip. Otherwise it returns zero as a success code.

struct gpio_pin_range #

pin range controlled by a gpio chip

Definition

struct gpio_pin_range {
    struct list_head node;
    struct pinctrl_dev *pctldev;
    struct pinctrl_gpio_range range;
};

Members

  • node: list for maintaining set of pin ranges, used internally
  • pctldev: pinctrl device which handles corresponding pins
  • range: actual range of pins controlled by a gpio controller

gpio_to_desc() #

struct gpio_desc * gpio_to_desc(unsigned gpio)

Convert a GPIO number to its descriptor

Parameters

  • unsigned gpio: global GPIO number

Return

The GPIO descriptor associated with the given GPIO, or NULL if no GPIO with the given number exists in the system.

gpio_device_get_desc() #

struct gpio_desc * gpio_device_get_desc(struct gpio_device *gdev, unsigned int hwnum)

get the GPIO descriptor corresponding to the given hardware number for this GPIO device

Parameters

  • struct gpio_device *gdev: GPIO device to get the descriptor from
  • unsigned int hwnum: hardware number of the GPIO for this chip

Return

A pointer to the GPIO descriptor or EINVAL if no GPIO exists in the given chip for the specified hardware number or ENODEV if the underlying chip already vanished.

Description

The reference count of struct gpio_device is NOT increased like when the GPIO is being requested for exclusive usage. It's up to the caller to make sure the GPIO device will stay alive together with the descriptor returned by this function.

desc_to_gpio() #

int desc_to_gpio(const struct gpio_desc *desc)

convert a GPIO descriptor to the integer namespace

Parameters

  • const struct gpio_desc *desc: GPIO descriptor

Description

This should disappear in the future but is needed since we still use GPIO numbers for error messages and sysfs nodes.

Return

The global GPIO number for the GPIO specified by its descriptor.

gpiod_hwgpio() #

int gpiod_hwgpio(const struct gpio_desc *desc)

Return the GPIO number of the passed descriptor relative to its chip.

Parameters

  • const struct gpio_desc *desc: GPIO descriptor

Return

Hardware offset of the GPIO represented by the descriptor.

gpiod_to_chip() #

struct gpio_chip * gpiod_to_chip(const struct gpio_desc *desc)

Return the GPIO chip to which a GPIO descriptor belongs

Parameters

  • const struct gpio_desc *desc: descriptor to return the chip of

Description

DEPRECATED This function is unsafe and should not be used. Using the chip address without taking the SRCU read lock may result in dereferencing a dangling pointer.

Return

Address of the GPIO chip backing this device.

gpiod_to_gpio_device() #

struct gpio_device * gpiod_to_gpio_device(struct gpio_desc *desc)

Return the GPIO device to which this descriptor belongs.

Parameters

  • struct gpio_desc *desc: Descriptor for which to return the GPIO device.

Description

This DOES NOT increase the reference count of the GPIO device as it's expected that the descriptor is requested and the users already holds a reference to the device.

Return

Address of the GPIO device owning this descriptor.

gpio_device_get_base() #

int gpio_device_get_base(struct gpio_device *gdev)

Get the base GPIO number allocated by this device

Parameters

  • struct gpio_device *gdev: GPIO device

Return

First GPIO number in the global GPIO numberspace for this device.

gpio_device_get_label() #

const char * gpio_device_get_label(struct gpio_device *gdev)

Get the label of this GPIO device

Parameters

  • struct gpio_device *gdev: GPIO device

Return

Pointer to the string containing the GPIO device label. The string's lifetime is tied to that of the underlying GPIO device.

gpio_device_get_chip() #

struct gpio_chip * gpio_device_get_chip(struct gpio_device *gdev)

Get the gpio_chip implementation of this GPIO device

Parameters

  • struct gpio_device *gdev: GPIO device

Return

Address of the GPIO chip backing this device.

Description

DEPRECATED Until we can get rid of all non-driver users of struct gpio_chip, we must provide a way of retrieving the pointer to it from struct gpio_device. This is NOT safe as the GPIO API is considered to be hot-unpluggable and the chip can dissapear at any moment (unlike reference-counted struct gpio_device).

Use at your own risk.

gpiod_is_equal() #

bool gpiod_is_equal(const struct gpio_desc *desc, const struct gpio_desc *other)

Check if two GPIO descriptors refer to the same pin.

Parameters

  • const struct gpio_desc *desc: Descriptor to compare.
  • const struct gpio_desc *other: The second descriptor to compare against.

Return

True if the descriptors refer to the same physical pin. False otherwise.

gpiod_get_direction() #

int gpiod_get_direction(struct gpio_desc *desc)

return the current direction of a GPIO

Parameters

  • struct gpio_desc *desc: GPIO to get the direction of

Return

0 for output, 1 for input, or an error code in case of error.

Description

This function may sleep if gpiod_cansleep() is true.

gpiochip_query_valid_mask() #

const unsigned long * gpiochip_query_valid_mask(const struct gpio_chip *gc)

return the GPIO validity information

Parameters

  • const struct gpio_chip *gc: gpio chip which validity information is queried

Return

bitmap representing valid GPIOs or NULL if all GPIOs are valid

Description

Some GPIO chips may support configurations where some of the pins aren't available. These chips can have valid_mask set to represent the valid GPIOs. This function can be used to retrieve this information.

gpiochip_get_data() #

void * gpiochip_get_data(struct gpio_chip *gc)

get per-subdriver data for the chip

Parameters

  • struct gpio_chip *gc: GPIO chip

Return

The per-subdriver data for the chip.

gpiochip_remove() #

void gpiochip_remove(struct gpio_chip *gc)

unregister a gpio_chip

Parameters

  • struct gpio_chip *gc: the chip to unregister

Description

A gpio_chip with any GPIOs still requested may not be removed.

gpio_device_find() #

struct gpio_device * gpio_device_find(const void *data, int (*match)(struct gpio_chip *gc, const void *data))

find a specific GPIO device

Parameters

  • const void *data: data to pass to match function
  • int (*match)(struct gpio_chip *gc, const void *data): Callback function to check gpio_chip

Return

New reference to struct gpio_device.

Description

Similar to bus_find_device(). It returns a reference to a gpio_device as determined by a user supplied match callback. The callback should return 0 if the device doesn't match and non-zero if it does. If the callback returns non-zero, this function will return to the caller and not iterate over any more gpio_devices.

The callback takes the GPIO chip structure as argument. During the execution of the callback function the chip is protected from being freed. TODO: This actually has yet to be implemented.

If the function returns non-NULL, the returned reference must be freed by the caller using gpio_device_put().

gpio_device_find_by_label() #

struct gpio_device * gpio_device_find_by_label(const char *label)

wrapper around gpio_device_find() finding the GPIO device by its backing chip's label

Parameters

  • const char *label: Label to lookup

Return

Reference to the GPIO device or NULL. Reference must be released with gpio_device_put().

gpio_device_find_by_fwnode() #

struct gpio_device * gpio_device_find_by_fwnode(const struct fwnode_handle *fwnode)

wrapper around gpio_device_find() finding the GPIO device by its fwnode

Parameters

  • const struct fwnode_handle *fwnode: Firmware node to lookup

Return

Reference to the GPIO device or NULL. Reference must be released with gpio_device_put().

gpio_device_get() #

struct gpio_device * gpio_device_get(struct gpio_device *gdev)

Increase the reference count of this GPIO device

Parameters

  • struct gpio_device *gdev: GPIO device to increase the refcount for

Return

Pointer to gdev.

gpio_device_put() #

void gpio_device_put(struct gpio_device *gdev)

Decrease the reference count of this GPIO device and possibly free all resources associated with it.

Parameters

  • struct gpio_device *gdev: GPIO device to decrease the reference count for

gpio_device_to_device() #

struct device * gpio_device_to_device(struct gpio_device *gdev)

Retrieve the address of the underlying struct device.

Parameters

  • struct gpio_device *gdev: GPIO device for which to return the address.

Description

This does not increase the reference count of the GPIO device nor the underlying struct device.

Return

Address of struct device backing this GPIO device.

gpiochip_irqchip_add_domain() #

int gpiochip_irqchip_add_domain(struct gpio_chip *gc, struct irq_domain *domain)

adds an irqdomain to a gpiochip

Parameters

  • struct gpio_chip *gc: the gpiochip to add the irqchip to
  • struct irq_domain *domain: the irqdomain to add to the gpiochip

Description

This function adds an IRQ domain to the gpiochip.

Return

0 on success, or negative errno on failure.

gpiochip_generic_request() #

int gpiochip_generic_request(struct gpio_chip *gc, unsigned int offset)

request the gpio function for a pin

Parameters

  • struct gpio_chip *gc: the gpiochip owning the GPIO
  • unsigned int offset: the offset of the GPIO to request for GPIO function

Return

0 on success, or negative errno on failure.

gpiochip_generic_free() #

void gpiochip_generic_free(struct gpio_chip *gc, unsigned int offset)

free the gpio function from a pin

Parameters

  • struct gpio_chip *gc: the gpiochip to request the gpio function for
  • unsigned int offset: the offset of the GPIO to free from GPIO function

gpiochip_generic_config() #

int gpiochip_generic_config(struct gpio_chip *gc, unsigned int offset, unsigned long config)

apply configuration for a pin

Parameters

  • struct gpio_chip *gc: the gpiochip owning the GPIO
  • unsigned int offset: the offset of the GPIO to apply the configuration
  • unsigned long config: the configuration to be applied

Return

0 on success, or negative errno on failure.

gpiochip_add_pingroup_range() #

int gpiochip_add_pingroup_range(struct gpio_chip *gc, struct pinctrl_dev *pctldev, unsigned int gpio_offset, const char *pin_group)

add a range for GPIO <-> pin mapping

Parameters

  • struct gpio_chip *gc: the gpiochip to add the range for
  • struct pinctrl_dev *pctldev: the pin controller to map to
  • unsigned int gpio_offset: the start offset in the current gpio_chip number space
  • const char *pin_group: name of the pin group inside the pin controller

Description

Calling this function directly from a DeviceTree-supported pinctrl driver is DEPRECATED. Please see Section 2.1 of Documentation/devicetree/bindings/gpio/gpio.txt on how to bind pinctrl and gpio drivers via the "gpio-ranges" property.

Return

0 on success, or negative errno on failure.

gpiochip_add_pin_range_with_pins() #

int gpiochip_add_pin_range_with_pins(struct gpio_chip *gc, const char *pinctl_name, unsigned int gpio_offset, unsigned int pin_offset, unsigned int const *pins, unsigned int npins)

add a range for GPIO <-> pin mapping

Parameters

  • struct gpio_chip *gc: the gpiochip to add the range for
  • const char *pinctl_name: the dev_name() of the pin controller to map to
  • unsigned int gpio_offset: the start offset in the current gpio_chip number space
  • unsigned int pin_offset: the start offset in the pin controller number space
  • unsigned int const *pins: the list of non consecutive pins to accumulate in this range (if not NULL, pin_offset is ignored by pinctrl core)
  • unsigned int npins: the number of pins from the offset of each pin space (GPIO and pin controller) to accumulate in this range

Description

Calling this function directly from a DeviceTree-supported pinctrl driver is DEPRECATED. Please see Section 2.1 of Documentation/devicetree/bindings/gpio/gpio.txt on how to bind pinctrl and gpio drivers via the "gpio-ranges" property.

Return

0 on success, or a negative errno on failure.

gpiochip_remove_pin_ranges() #

void gpiochip_remove_pin_ranges(struct gpio_chip *gc)

remove all the GPIO <-> pin mappings

Parameters

  • struct gpio_chip *gc: the chip to remove all the mappings for

gpiochip_dup_line_label() #

char * gpiochip_dup_line_label(struct gpio_chip *gc, unsigned int offset)

Get a copy of the consumer label.

Parameters

  • struct gpio_chip *gc: GPIO chip controlling this line.
  • unsigned int offset: Hardware offset of the line.

Return

Pointer to a copy of the consumer label if the line is requested or NULL if it's not. If a valid pointer was returned, it must be freed using kfree(). In case of a memory allocation error, the function returns ENOMEM.

Description

Must not be called from atomic context.

gpiochip_request_own_desc() #

struct gpio_desc * gpiochip_request_own_desc(struct gpio_chip *gc, unsigned int hwnum, const char *label, enum gpio_lookup_flags lflags, enum gpiod_flags dflags)

Allow GPIO chip to request its own descriptor

Parameters

  • struct gpio_chip *gc: GPIO chip
  • unsigned int hwnum: hardware number of the GPIO for which to request the descriptor
  • const char *label: label for the GPIO
  • enum gpio_lookup_flags lflags: lookup flags for this GPIO or 0 if default, this can be used to specify things like line inversion semantics with the machine flags such as GPIO_OUT_LOW
  • enum gpiod_flags dflags: descriptor request flags for this GPIO or 0 if default, this can be used to specify consumer semantics such as open drain

Description

Function allows GPIO chip drivers to request and use their own GPIO descriptors via gpiolib API. Difference to gpiod_request() is that this function will not increase reference count of the GPIO chip module. This allows the GPIO chip module to be unloaded as needed (we assume that the GPIO chip driver handles freeing the GPIOs it has requested).

Return

A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error code on failure.

gpiochip_free_own_desc() #

void gpiochip_free_own_desc(struct gpio_desc *desc)

Free GPIO requested by the chip driver

Parameters

  • struct gpio_desc *desc: GPIO descriptor to free

Description

Function frees the given GPIO requested previously with gpiochip_request_own_desc().

gpiod_direction_input() #

int gpiod_direction_input(struct gpio_desc *desc)

set the GPIO direction to input

Parameters

  • struct gpio_desc *desc: GPIO to set to input

Description

Set the direction of the passed GPIO to input, such as gpiod_get_value() can be called safely on it.

Return

0 on success, or negative errno on failure.

gpiod_direction_output_raw() #

int gpiod_direction_output_raw(struct gpio_desc *desc, int value)

set the GPIO direction to output

Parameters

  • struct gpio_desc *desc: GPIO to set to output
  • int value: initial output value of the GPIO

Description

Set the direction of the passed GPIO to output, such as gpiod_set_value() can be called safely on it. The initial value of the output must be specified as raw value on the physical line without regard for the ACTIVE_LOW status.

Return

0 on success, or negative errno on failure.

gpiod_direction_output() #

int gpiod_direction_output(struct gpio_desc *desc, int value)

set the GPIO direction to output

Parameters

  • struct gpio_desc *desc: GPIO to set to output
  • int value: initial output value of the GPIO

Description

Set the direction of the passed GPIO to output, such as gpiod_set_value() can be called safely on it. The initial value of the output must be specified as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into account.

Return

0 on success, or negative errno on failure.

gpiod_enable_hw_timestamp_ns() #

int gpiod_enable_hw_timestamp_ns(struct gpio_desc *desc, unsigned long flags)

Enable hardware timestamp in nanoseconds.

Parameters

  • struct gpio_desc *desc: GPIO to enable.
  • unsigned long flags: Flags related to GPIO edge.

Return

0 on success, or negative errno on failure.

gpiod_disable_hw_timestamp_ns() #

int gpiod_disable_hw_timestamp_ns(struct gpio_desc *desc, unsigned long flags)

Disable hardware timestamp.

Parameters

  • struct gpio_desc *desc: GPIO to disable.
  • unsigned long flags: Flags related to GPIO edge, same value as used during enable call.

Return

0 on success, or negative errno on failure.

gpiod_set_config() #

int gpiod_set_config(struct gpio_desc *desc, unsigned long config)

sets config for a GPIO

Parameters

  • struct gpio_desc *desc: descriptor of the GPIO for which to set the configuration
  • unsigned long config: Same packed config format as generic pinconf

Return

0 on success, -ENOTSUPP if the controller doesn't support setting the configuration.

gpiod_set_debounce() #

int gpiod_set_debounce(struct gpio_desc *desc, unsigned int debounce)

sets debounce time for a GPIO

Parameters

  • struct gpio_desc *desc: descriptor of the GPIO for which to set debounce time
  • unsigned int debounce: debounce time in microseconds

Return

0 on success, -ENOTSUPP if the controller doesn't support setting the debounce time.

gpiod_is_active_low() #

int gpiod_is_active_low(const struct gpio_desc *desc)

test whether a GPIO is active-low or not

Parameters

  • const struct gpio_desc *desc: the gpio descriptor to test

Return

1 if the GPIO is active-low, 0 otherwise.

gpiod_toggle_active_low() #

void gpiod_toggle_active_low(struct gpio_desc *desc)

toggle whether a GPIO is active-low or not

Parameters

  • struct gpio_desc *desc: the gpio descriptor to change

gpiod_get_raw_value() #

int gpiod_get_raw_value(const struct gpio_desc *desc)

return a gpio's raw value

Parameters

  • const struct gpio_desc *desc: gpio whose value will be returned

Return

The GPIO's raw value, i.e. the value of the physical line disregarding its ACTIVE_LOW status, or negative errno on failure.

Description

This function can be called from contexts where we cannot sleep, and will complain if the GPIO chip functions potentially sleep.

gpiod_get_value() #

int gpiod_get_value(const struct gpio_desc *desc)

return a gpio's value

Parameters

  • const struct gpio_desc *desc: gpio whose value will be returned

Return

The GPIO's logical value, i.e. taking the ACTIVE_LOW status into account, or negative errno on failure.

Description

This function can be called from contexts where we cannot sleep, and will complain if the GPIO chip functions potentially sleep.

gpiod_get_raw_array_value() #

int gpiod_get_raw_array_value(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)

read raw values from an array of GPIOs

Parameters

  • unsigned int array_size: number of elements in the descriptor array / value bitmap
  • struct gpio_desc **desc_array: array of GPIO descriptors whose values will be read
  • struct gpio_array *array_info: information on applicability of fast bitmap processing path
  • unsigned long *value_bitmap: bitmap to store the read values

Description

Read the raw values of the GPIOs, i.e. the values of the physical lines without regard for their ACTIVE_LOW status.

This function can be called from contexts where we cannot sleep, and it will complain if the GPIO chip functions potentially sleep.

Return

0 on success, or negative errno on failure.

gpiod_get_array_value() #

int gpiod_get_array_value(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)

read values from an array of GPIOs

Parameters

  • unsigned int array_size: number of elements in the descriptor array / value bitmap
  • struct gpio_desc **desc_array: array of GPIO descriptors whose values will be read
  • struct gpio_array *array_info: information on applicability of fast bitmap processing path
  • unsigned long *value_bitmap: bitmap to store the read values

Description

Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status into account.

This function can be called from contexts where we cannot sleep, and it will complain if the GPIO chip functions potentially sleep.

Return

0 on success, or negative errno on failure.

gpiod_set_raw_value() #

int gpiod_set_raw_value(struct gpio_desc *desc, int value)

assign a gpio's raw value

Parameters

  • struct gpio_desc *desc: gpio whose value will be assigned
  • int value: value to assign

Description

Set the raw value of the GPIO, i.e. the value of its physical line without regard for its ACTIVE_LOW status.

This function can be called from contexts where we cannot sleep, and will complain if the GPIO chip functions potentially sleep.

Return

0 on success, negative error number on failure.

gpiod_set_value() #

int gpiod_set_value(struct gpio_desc *desc, int value)

assign a gpio's value

Parameters

  • struct gpio_desc *desc: gpio whose value will be assigned
  • int value: value to assign

Description

Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW, OPEN_DRAIN and OPEN_SOURCE flags into account.

This function can be called from contexts where we cannot sleep, and will complain if the GPIO chip functions potentially sleep.

Return

0 on success, negative error number on failure.

gpiod_set_raw_array_value() #

int gpiod_set_raw_array_value(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)

assign values to an array of GPIOs

Parameters

  • unsigned int array_size: number of elements in the descriptor array / value bitmap
  • struct gpio_desc **desc_array: array of GPIO descriptors whose values will be assigned
  • struct gpio_array *array_info: information on applicability of fast bitmap processing path
  • unsigned long *value_bitmap: bitmap of values to assign

Description

Set the raw values of the GPIOs, i.e. the values of the physical lines without regard for their ACTIVE_LOW status.

This function can be called from contexts where we cannot sleep, and will complain if the GPIO chip functions potentially sleep.

Return

0 on success, or negative errno on failure.

gpiod_set_array_value() #

int gpiod_set_array_value(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)

assign values to an array of GPIOs

Parameters

  • unsigned int array_size: number of elements in the descriptor array / value bitmap
  • struct gpio_desc **desc_array: array of GPIO descriptors whose values will be assigned
  • struct gpio_array *array_info: information on applicability of fast bitmap processing path
  • unsigned long *value_bitmap: bitmap of values to assign

Description

Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status into account.

This function can be called from contexts where we cannot sleep, and will complain if the GPIO chip functions potentially sleep.

Return

0 on success, or negative errno on failure.

gpiod_cansleep() #

int gpiod_cansleep(const struct gpio_desc *desc)

report whether gpio value access may sleep

Parameters

  • const struct gpio_desc *desc: gpio to check

Return

0 for non-sleepable, 1 for sleepable, or an error code in case of error.

gpiod_set_consumer_name() #

int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)

set the consumer name for the descriptor

Parameters

  • struct gpio_desc *desc: gpio to set the consumer name on
  • const char *name: the new consumer name

Return

0 on success, or negative errno on failure.

gpiod_is_shared() #

bool gpiod_is_shared(const struct gpio_desc *desc)

check if this GPIO can be shared by multiple consumers

Parameters

  • const struct gpio_desc *desc: GPIO to inspect

Return

True if this GPIO can be shared by multiple consumers at once. False if it's a regular, exclusive GPIO.

Note

This function returning true does not mean that this GPIO is currently being shared. It means the GPIO core has registered the fact that the firmware configuration indicates that it can be shared by multiple consumers and is in charge of arbitrating the access.

gpiod_to_irq() #

int gpiod_to_irq(const struct gpio_desc *desc)

return the IRQ corresponding to a GPIO

Parameters

  • const struct gpio_desc *desc: gpio whose IRQ will be returned (already requested)

Return

The IRQ corresponding to the passed GPIO, or an error code in case of error.

gpiochip_lock_as_irq() #

int gpiochip_lock_as_irq(struct gpio_chip *gc, unsigned int offset)

lock a GPIO to be used as IRQ

Parameters

  • struct gpio_chip *gc: the chip the GPIO to lock belongs to
  • unsigned int offset: the offset of the GPIO to lock as IRQ

Description

This is used directly by GPIO drivers that want to lock down a certain GPIO line to be used for IRQs.

Return

0 on success, or negative errno on failure.

gpiochip_unlock_as_irq() #

void gpiochip_unlock_as_irq(struct gpio_chip *gc, unsigned int offset)

unlock a GPIO used as IRQ

Parameters

  • struct gpio_chip *gc: the chip the GPIO to lock belongs to
  • unsigned int offset: the offset of the GPIO to lock as IRQ

Description

This is used directly by GPIO drivers that want to indicate that a certain GPIO is no longer used exclusively for IRQ.

gpiod_get_raw_value_cansleep() #

int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)

return a gpio's raw value

Parameters

  • const struct gpio_desc *desc: gpio whose value will be returned

Return

The GPIO's raw value, i.e. the value of the physical line disregarding its ACTIVE_LOW status, or negative errno on failure.

Description

This function is to be called from contexts that can sleep.

gpiod_get_value_cansleep() #

int gpiod_get_value_cansleep(const struct gpio_desc *desc)

return a gpio's value

Parameters

  • const struct gpio_desc *desc: gpio whose value will be returned

Return

The GPIO's logical value, i.e. taking the ACTIVE_LOW status into account, or negative errno on failure.

Description

This function is to be called from contexts that can sleep.

gpiod_get_raw_array_value_cansleep() #

int gpiod_get_raw_array_value_cansleep(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)

read raw values from an array of GPIOs

Parameters

  • unsigned int array_size: number of elements in the descriptor array / value bitmap
  • struct gpio_desc **desc_array: array of GPIO descriptors whose values will be read
  • struct gpio_array *array_info: information on applicability of fast bitmap processing path
  • unsigned long *value_bitmap: bitmap to store the read values

Description

Read the raw values of the GPIOs, i.e. the values of the physical lines without regard for their ACTIVE_LOW status.

This function is to be called from contexts that can sleep.

Return

0 on success, or negative errno on failure.

gpiod_get_array_value_cansleep() #

int gpiod_get_array_value_cansleep(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)

read values from an array of GPIOs

Parameters

  • unsigned int array_size: number of elements in the descriptor array / value bitmap
  • struct gpio_desc **desc_array: array of GPIO descriptors whose values will be read
  • struct gpio_array *array_info: information on applicability of fast bitmap processing path
  • unsigned long *value_bitmap: bitmap to store the read values

Description

Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status into account.

This function is to be called from contexts that can sleep.

Return

0 on success, or negative errno on failure.

gpiod_set_raw_value_cansleep() #

int gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)

assign a gpio's raw value

Parameters

  • struct gpio_desc *desc: gpio whose value will be assigned
  • int value: value to assign

Description

Set the raw value of the GPIO, i.e. the value of its physical line without regard for its ACTIVE_LOW status.

This function is to be called from contexts that can sleep.

Return

0 on success, negative error number on failure.

gpiod_set_value_cansleep() #

int gpiod_set_value_cansleep(struct gpio_desc *desc, int value)

assign a gpio's value

Parameters

  • struct gpio_desc *desc: gpio whose value will be assigned
  • int value: value to assign

Description

Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into account

This function is to be called from contexts that can sleep.

Return

0 on success, negative error number on failure.

gpiod_set_raw_array_value_cansleep() #

int gpiod_set_raw_array_value_cansleep(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)

assign values to an array of GPIOs

Parameters

  • unsigned int array_size: number of elements in the descriptor array / value bitmap
  • struct gpio_desc **desc_array: array of GPIO descriptors whose values will be assigned
  • struct gpio_array *array_info: information on applicability of fast bitmap processing path
  • unsigned long *value_bitmap: bitmap of values to assign

Description

Set the raw values of the GPIOs, i.e. the values of the physical lines without regard for their ACTIVE_LOW status.

This function is to be called from contexts that can sleep.

Return

0 on success, or negative errno on failure.

gpiod_set_array_value_cansleep() #

int gpiod_set_array_value_cansleep(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)

assign values to an array of GPIOs

Parameters

  • unsigned int array_size: number of elements in the descriptor array / value bitmap
  • struct gpio_desc **desc_array: array of GPIO descriptors whose values will be assigned
  • struct gpio_array *array_info: information on applicability of fast bitmap processing path
  • unsigned long *value_bitmap: bitmap of values to assign

Description

Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status into account.

This function is to be called from contexts that can sleep.

Return

0 on success, or negative errno on failure.

gpiod_add_lookup_table() #

void gpiod_add_lookup_table(struct gpiod_lookup_table *table)

register GPIO device consumers

Parameters

  • struct gpiod_lookup_table *table: table of consumers to register

gpiod_remove_lookup_table() #

void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)

unregister GPIO device consumers

Parameters

  • struct gpiod_lookup_table *table: table of consumers to unregister

gpiod_add_hogs() #

void gpiod_add_hogs(struct gpiod_hog *hogs)

register a set of GPIO hogs from machine code

Parameters

  • struct gpiod_hog *hogs: table of gpio hog entries with a zeroed sentinel at the end

fwnode_gpiod_get_index() #

struct gpio_desc * fwnode_gpiod_get_index(struct fwnode_handle *fwnode, const char *con_id, int index, enum gpiod_flags flags, const char *label)

obtain a GPIO from firmware node

Parameters

  • struct fwnode_handle *fwnode: handle of the firmware node
  • const char *con_id: function within the GPIO consumer
  • int index: index of the GPIO to obtain for the consumer
  • enum gpiod_flags flags: GPIO initialization flags
  • const char *label: label to attach to the requested GPIO

Description

This function can be used for drivers that get their configuration from opaque firmware.

The function properly finds the corresponding GPIO using whatever is the underlying firmware interface and then makes sure that the GPIO descriptor is requested before it is returned to the caller.

In case of error an ERR_PTR() is returned.

Return

On successful request the GPIO pin is configured in accordance with provided flags.

gpiod_count() #

int gpiod_count(struct device *dev, const char *con_id)

return the number of GPIOs associated with a device / function

Parameters

  • struct device *dev: GPIO consumer, can be NULL for system-global GPIOs
  • const char *con_id: function within the GPIO consumer

Return

The number of GPIOs associated with a device / function or -ENOENT if no GPIO has been assigned to the requested function.

gpiod_get() #

struct gpio_desc * gpiod_get(struct device *dev, const char *con_id, enum gpiod_flags flags)

obtain a GPIO for a given GPIO function

Parameters

  • struct device *dev: GPIO consumer, can be NULL for system-global GPIOs
  • const char *con_id: function within the GPIO consumer
  • enum gpiod_flags flags: optional GPIO initialization flags

Return

The GPIO descriptor corresponding to the function con_id of device dev, -ENOENT if no GPIO has been assigned to the requested function, or another IS_ERR() code if an error occurred while trying to acquire the GPIO.

gpiod_get_optional() #

struct gpio_desc * gpiod_get_optional(struct device *dev, const char *con_id, enum gpiod_flags flags)

obtain an optional GPIO for a given GPIO function

Parameters

  • struct device *dev: GPIO consumer, can be NULL for system-global GPIOs
  • const char *con_id: function within the GPIO consumer
  • enum gpiod_flags flags: optional GPIO initialization flags

Description

This is equivalent to gpiod_get(), except that when no GPIO was assigned to the requested function it will return NULL. This is convenient for drivers that need to handle optional GPIOs.

Return

The GPIO descriptor corresponding to the function con_id of device dev, NULL if no GPIO has been assigned to the requested function, or another IS_ERR() code if an error occurred while trying to acquire the GPIO.

gpiod_get_index() #

struct gpio_desc * gpiod_get_index(struct device *dev, const char *con_id, unsigned int idx, enum gpiod_flags flags)

obtain a GPIO from a multi-index GPIO function

Parameters

  • struct device *dev: GPIO consumer, can be NULL for system-global GPIOs
  • const char *con_id: function within the GPIO consumer
  • unsigned int idx: index of the GPIO to obtain in the consumer
  • enum gpiod_flags flags: optional GPIO initialization flags

Description

This variant of gpiod_get() allows to access GPIOs other than the first defined one for functions that define several GPIOs.

Return

A valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the requested function and/or index, or another IS_ERR() code if an error occurred while trying to acquire the GPIO.

gpiod_get_index_optional() #

struct gpio_desc * gpiod_get_index_optional(struct device *dev, const char *con_id, unsigned int index, enum gpiod_flags flags)

obtain an optional GPIO from a multi-index GPIO function

Parameters

  • struct device *dev: GPIO consumer, can be NULL for system-global GPIOs
  • const char *con_id: function within the GPIO consumer
  • unsigned int index: index of the GPIO to obtain in the consumer
  • enum gpiod_flags flags: optional GPIO initialization flags

Description

This is equivalent to gpiod_get_index(), except that when no GPIO with the specified index was assigned to the requested function it will return NULL. This is convenient for drivers that need to handle optional GPIOs.

Return

A valid GPIO descriptor, NULL if no GPIO has been assigned to the requested function and/or index, or another IS_ERR() code if an error occurred while trying to acquire the GPIO.

gpiod_get_array() #

struct gpio_descs * gpiod_get_array(struct device *dev, const char *con_id, enum gpiod_flags flags)

obtain multiple GPIOs from a multi-index GPIO function

Parameters

  • struct device *dev: GPIO consumer, can be NULL for system-global GPIOs
  • const char *con_id: function within the GPIO consumer
  • enum gpiod_flags flags: optional GPIO initialization flags

Description

This function acquires all the GPIOs defined under a given function.

Return

The GPIO descriptors corresponding to the function con_id of device dev, -ENOENT if no GPIO has been assigned to the requested function, or another IS_ERR() code if an error occurred while trying to acquire the GPIOs.

gpiod_get_array_optional() #

struct gpio_descs * gpiod_get_array_optional(struct device *dev, const char *con_id, enum gpiod_flags flags)

obtain multiple GPIOs from a multi-index GPIO function

Parameters

  • struct device *dev: GPIO consumer, can be NULL for system-global GPIOs
  • const char *con_id: function within the GPIO consumer
  • enum gpiod_flags flags: optional GPIO initialization flags

Description

This is equivalent to gpiod_get_array(), except that when no GPIO was assigned to the requested function it will return NULL.

Return

The GPIO descriptors corresponding to the function con_id of device dev, NULL if no GPIO has been assigned to the requested function, or another IS_ERR() code if an error occurred while trying to acquire the GPIOs.

gpiod_put() #

void gpiod_put(struct gpio_desc *desc)

dispose of a GPIO descriptor

Parameters

  • struct gpio_desc *desc: GPIO descriptor to dispose of

Description

No descriptor can be used after gpiod_put() has been called on it.

gpiod_put_array() #

void gpiod_put_array(struct gpio_descs *descs)

dispose of multiple GPIO descriptors

Parameters

  • struct gpio_descs *descs: struct gpio_descs containing an array of descriptors

ACPI support #

acpi_gpio_get_io_resource() #

bool acpi_gpio_get_io_resource(struct acpi_resource *ares, struct acpi_resource_gpio **agpio)

Fetch details of an ACPI resource if it is a GPIO I/O resource or return False if not.

Parameters

  • struct acpi_resource *ares: Pointer to the ACPI resource to fetch
  • struct acpi_resource_gpio **agpio: Pointer to a struct acpi_resource_gpio to store the output pointer

Return

true if GpioIo resource is found, false otherwise.

acpi_gpiochip_request_interrupts() #

void acpi_gpiochip_request_interrupts(struct gpio_chip *chip)

Register isr for gpio chip ACPI events

Parameters

  • struct gpio_chip *chip: GPIO chip

Description

ACPI5 platforms can use GPIO signaled ACPI events. These GPIO interrupts are handled by ACPI event methods which need to be called from the GPIO chip's interrupt handler. acpi_gpiochip_request_interrupts() finds out which GPIO pins have ACPI event methods and assigns interrupt handlers that calls the ACPI event methods for those pins.

acpi_gpiochip_free_interrupts() #

void acpi_gpiochip_free_interrupts(struct gpio_chip *chip)

Free GPIO ACPI event interrupts.

Parameters

  • struct gpio_chip *chip: GPIO chip

Description

Free interrupts associated with GPIO ACPI event method for the given GPIO chip.

acpi_dev_gpio_irq_wake_get_by() #

int acpi_dev_gpio_irq_wake_get_by(struct acpi_device *adev, const char *con_id, int index, bool *wake_capable)

Find GpioInt and translate it to Linux IRQ number

Parameters

  • struct acpi_device *adev: pointer to a ACPI device to get IRQ from
  • const char *con_id: optional name of GpioInt resource
  • int index: index of GpioInt resource (starting from 0)
  • bool *wake_capable: Set to true if the IRQ is wake capable

Description

If the device has one or more GpioInt resources, this function can be used to translate from the GPIO offset in the resource to the Linux IRQ number.

The function is idempotent, though each time it runs it will configure GPIO pin direction according to the flags in GpioInt resource.

The function takes optional con_id parameter. If the resource has a con_id in a property, then only those will be taken into account.

The GPIO is considered wake capable if the GpioInt resource specifies SharedAndWake or ExclusiveAndWake.

Return

Linux IRQ number (> 0) on success, negative errno on failure.

Device tree support #

of_get_named_gpio() #

int of_get_named_gpio(const struct device_node *np, const char *propname, int index)

Get a GPIO number to use with GPIO API

Parameters

  • const struct device_node *np: device node to get GPIO from
  • const char *propname: Name of property containing gpio specifier(s)
  • int index: index of the GPIO

Description

DEPRECATED This function is deprecated and must not be used in new code.

Return

GPIO number to use with Linux generic GPIO API, or one of the errno value on the error condition.

Device-managed API #

devm_gpiod_get() #

struct gpio_desc * devm_gpiod_get(struct device *dev, const char *con_id, enum gpiod_flags flags)

Resource-managed gpiod_get()

Parameters

  • struct device *dev: GPIO consumer
  • const char *con_id: function within the GPIO consumer
  • enum gpiod_flags flags: optional GPIO initialization flags

Description

Managed gpiod_get(). GPIO descriptors returned from this function are automatically disposed on driver detach. See gpiod_get() for detailed information about behavior and return values.

Return

The GPIO descriptor corresponding to the function con_id of device dev, -ENOENT if no GPIO has been assigned to the requested function, or another IS_ERR() code if an error occurred while trying to acquire the GPIO.

devm_gpiod_get_optional() #

struct gpio_desc * devm_gpiod_get_optional(struct device *dev, const char *con_id, enum gpiod_flags flags)

Resource-managed gpiod_get_optional()

Parameters

  • struct device *dev: GPIO consumer
  • const char *con_id: function within the GPIO consumer
  • enum gpiod_flags flags: optional GPIO initialization flags

Description

Managed gpiod_get_optional(). GPIO descriptors returned from this function are automatically disposed on driver detach. See gpiod_get_optional() for detailed information about behavior and return values.

Return

The GPIO descriptor corresponding to the function con_id of device dev, NULL if no GPIO has been assigned to the requested function, or another IS_ERR() code if an error occurred while trying to acquire the GPIO.

devm_gpiod_get_index() #

struct gpio_desc * devm_gpiod_get_index(struct device *dev, const char *con_id, unsigned int idx, enum gpiod_flags flags)

Resource-managed gpiod_get_index()

Parameters

  • struct device *dev: GPIO consumer
  • const char *con_id: function within the GPIO consumer
  • unsigned int idx: index of the GPIO to obtain in the consumer
  • enum gpiod_flags flags: optional GPIO initialization flags

Description

Managed gpiod_get_index(). GPIO descriptors returned from this function are automatically disposed on driver detach. See gpiod_get_index() for detailed information about behavior and return values.

Return

The GPIO descriptor corresponding to the function con_id of device dev, -ENOENT if no GPIO has been assigned to the requested function, or another IS_ERR() code if an error occurred while trying to acquire the GPIO.

devm_fwnode_gpiod_get_index() #

struct gpio_desc * devm_fwnode_gpiod_get_index(struct device *dev, struct fwnode_handle *fwnode, const char *con_id, int index, enum gpiod_flags flags, const char *label)

get a GPIO descriptor from a given node

Parameters

  • struct device *dev: GPIO consumer
  • struct fwnode_handle *fwnode: firmware node containing GPIO reference
  • const char *con_id: function within the GPIO consumer
  • int index: index of the GPIO to obtain in the consumer
  • enum gpiod_flags flags: GPIO initialization flags
  • const char *label: label to attach to the requested GPIO

Description

GPIO descriptors returned from this function are automatically disposed on driver detach.

Return

The GPIO descriptor corresponding to the function con_id of device dev, -ENOENT if no GPIO has been assigned to the requested function, or another IS_ERR() code if an error occurred while trying to acquire the GPIO.

devm_gpiod_get_index_optional() #

struct gpio_desc * devm_gpiod_get_index_optional(struct device *dev, const char *con_id, unsigned int index, enum gpiod_flags flags)

Resource-managed gpiod_get_index_optional()

Parameters

  • struct device *dev: GPIO consumer
  • const char *con_id: function within the GPIO consumer
  • unsigned int index: index of the GPIO to obtain in the consumer
  • enum gpiod_flags flags: optional GPIO initialization flags

Description

Managed gpiod_get_index_optional(). GPIO descriptors returned from this function are automatically disposed on driver detach. See gpiod_get_index_optional() for detailed information about behavior and return values.

Return

The GPIO descriptor corresponding to the function con_id of device dev, NULL if no GPIO has been assigned to the requested function, or another IS_ERR() code if an error occurred while trying to acquire the GPIO.

devm_gpiod_get_array() #

struct gpio_descs * devm_gpiod_get_array(struct device *dev, const char *con_id, enum gpiod_flags flags)

Resource-managed gpiod_get_array()

Parameters

  • struct device *dev: GPIO consumer
  • const char *con_id: function within the GPIO consumer
  • enum gpiod_flags flags: optional GPIO initialization flags

Description

Managed gpiod_get_array(). GPIO descriptors returned from this function are automatically disposed on driver detach. See gpiod_get_array() for detailed information about behavior and return values.

Return

The GPIO descriptors corresponding to the function con_id of device dev, -ENOENT if no GPIO has been assigned to the requested function, or another IS_ERR() code if an error occurred while trying to acquire the GPIOs.

devm_gpiod_get_array_optional() #

struct gpio_descs * devm_gpiod_get_array_optional(struct device *dev, const char *con_id, enum gpiod_flags flags)

Resource-managed gpiod_get_array_optional()

Parameters

  • struct device *dev: GPIO consumer
  • const char *con_id: function within the GPIO consumer
  • enum gpiod_flags flags: optional GPIO initialization flags

Description

Managed gpiod_get_array_optional(). GPIO descriptors returned from this function are automatically disposed on driver detach. See gpiod_get_array_optional() for detailed information about behavior and return values.

Return

The GPIO descriptors corresponding to the function con_id of device dev, NULL if no GPIO has been assigned to the requested function, or another IS_ERR() code if an error occurred while trying to acquire the GPIOs.

devm_gpiod_put() #

void devm_gpiod_put(struct device *dev, struct gpio_desc *desc)

Resource-managed gpiod_put()

Parameters

  • struct device *dev: GPIO consumer
  • struct gpio_desc *desc: GPIO descriptor to dispose of

Description

Dispose of a GPIO descriptor obtained with devm_gpiod_get() or devm_gpiod_get_index(). Normally this function will not be called as the GPIO will be disposed of by the resource management code.

devm_gpiod_unhinge() #

void devm_gpiod_unhinge(struct device *dev, struct gpio_desc *desc)

Remove resource management from a gpio descriptor

Parameters

  • struct device *dev: GPIO consumer
  • struct gpio_desc *desc: GPIO descriptor to remove resource management from

Description

DEPRECATED This function should not be used. It's been provided as a workaround for resource ownership issues in the regulator framework and should be replaced with a better solution.

Remove resource management from a GPIO descriptor. This is needed when you want to hand over lifecycle management of a descriptor to another mechanism.

devm_gpiod_put_array() #

void devm_gpiod_put_array(struct device *dev, struct gpio_descs *descs)

Resource-managed gpiod_put_array()

Parameters

  • struct device *dev: GPIO consumer
  • struct gpio_descs *descs: GPIO descriptor array to dispose of

Description

Dispose of an array of GPIO descriptors obtained with devm_gpiod_get_array(). Normally this function will not be called as the GPIOs will be disposed of by the resource management code.

devm_gpiochip_add_data_with_key() #

int devm_gpiochip_add_data_with_key(struct device *dev, struct gpio_chip *gc, void *data, struct lock_class_key *lock_key, struct lock_class_key *request_key)

Resource managed gpiochip_add_data_with_key()

Parameters

  • struct device *dev: pointer to the device that gpio_chip belongs to.
  • struct gpio_chip *gc: the GPIO chip to register
  • void *data: driver-private data associated with this chip
  • struct lock_class_key *lock_key: lockdep class for IRQ lock
  • struct lock_class_key *request_key: lockdep class for IRQ request

Context

potentially before irqs will work

Description

The gpio chip automatically be released when the device is unbound.

Return

A negative errno if the chip can't be registered, such as because the gc->base is invalid or already associated with a different chip. Otherwise it returns zero as a success code.

sysfs helpers #

gpiod_export() #

int gpiod_export(struct gpio_desc *desc, bool direction_may_change)

export a GPIO through sysfs

Parameters

  • struct gpio_desc *desc: GPIO to make available, already requested
  • bool direction_may_change: true if userspace may change GPIO direction

Context

arch_initcall or later

Description

When drivers want to make a GPIO accessible to userspace after they have requested it -- perhaps while debugging, or as part of their public interface -- they may use this routine. If the GPIO can change direction (some can't) and the caller allows it, userspace will see "direction" sysfs attribute which may be used to change the gpio's direction. A "value" attribute will always be provided.

Return

0 on success, or negative errno on failure.

gpiod_export_link() #

int gpiod_export_link(struct device *dev, const char *name, struct gpio_desc *desc)

create a sysfs link to an exported GPIO node

Parameters

  • struct device *dev: device under which to create symlink
  • const char *name: name of the symlink
  • struct gpio_desc *desc: GPIO to create symlink to, already exported

Description

Set up a symlink from /sys/.../dev/name to /sys/class/gpio/gpioN node. Caller is responsible for unlinking.

Return

0 on success, or negative errno on failure.

gpiod_unexport() #

void gpiod_unexport(struct gpio_desc *desc)

reverse effect of gpiod_export()

Parameters

  • struct gpio_desc *desc: GPIO to make unavailable

Description

This is implicit on gpiod_free().

GPIO Mappings

Peios Kernel / Hardware and drivers / Driver development / GPIO

This document explains how GPIOs can be assigned to given devices and functions.

All platforms can enable the GPIO library, but if the platform strictly requires GPIO functionality to be present, it needs to select GPIOLIB from its Kconfig. Then, how GPIOs are mapped depends on what the platform uses to describe its hardware layout. Currently, mappings can be defined through device tree, ACPI, and platform data.

Device Tree #

GPIOs can easily be mapped to devices and functions in the device tree. The exact way to do it depends on the GPIO controller providing the GPIOs, see the device tree bindings for your controller.

GPIOs mappings are defined in the consumer device's node, in a property named <function>-gpios, where <function> is the function the driver will request through gpiod_get(). For example:

foo_device {
        compatible = "acme,foo";
        ...
        led-gpios = <&gpio 15 GPIO_ACTIVE_HIGH>, /* red */
                    <&gpio 16 GPIO_ACTIVE_HIGH>, /* green */
                    <&gpio 17 GPIO_ACTIVE_HIGH>; /* blue */

        power-gpios = <&gpio 1 GPIO_ACTIVE_LOW>;
};

Properties named <function>-gpio are also considered valid and old bindings use it but are only supported for compatibility reasons and should not be used for newer bindings since it has been deprecated.

This property will make GPIOs 15, 16 and 17 available to the driver under the "led" function, and GPIO 1 as the "power" GPIO:

struct gpio_desc *red, *green, *blue, *power;

red = gpiod_get_index(dev, "led", 0, GPIOD_OUT_HIGH);
green = gpiod_get_index(dev, "led", 1, GPIOD_OUT_HIGH);
blue = gpiod_get_index(dev, "led", 2, GPIOD_OUT_HIGH);

power = gpiod_get(dev, "power", GPIOD_OUT_HIGH);

The led GPIOs will be active high, while the power GPIO will be active low (i.e. gpiod_is_active_low(power) will be true).

The second parameter of the gpiod_get() functions, the con_id string, has to be the <function>-prefix of the GPIO suffixes ("gpios" or "gpio", automatically looked up by the gpiod functions internally) used in the device tree. With above "led-gpios" example, use the prefix without the "-" as con_id parameter: "led".

Internally, the GPIO subsystem prefixes the GPIO suffix ("gpios" or "gpio") with the string passed in con_id to get the resulting string (snprintf(... "%s-%s", con_id, gpio_suffixes[]).

ACPI #

ACPI also supports function names for GPIOs in a similar fashion to DT. The above DT example can be converted to an equivalent ACPI description with the help of _DSD (Device Specific Data), introduced in ACPI 5.1:

Device (FOO) {
        Name (_CRS, ResourceTemplate () {
                GpioIo (Exclusive, PullUp, 0, 0, IoRestrictionOutputOnly,
                        "\\_SB.GPI0", 0, ResourceConsumer) { 15 } // red
                GpioIo (Exclusive, PullUp, 0, 0, IoRestrictionOutputOnly,
                        "\\_SB.GPI0", 0, ResourceConsumer) { 16 } // green
                GpioIo (Exclusive, PullUp, 0, 0, IoRestrictionOutputOnly,
                        "\\_SB.GPI0", 0, ResourceConsumer) { 17 } // blue
                GpioIo (Exclusive, PullNone, 0, 0, IoRestrictionOutputOnly,
                        "\\_SB.GPI0", 0, ResourceConsumer) { 1 } // power
        })

        Name (_DSD, Package () {
                ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
                Package () {
                        Package () {
                                "led-gpios",
                                Package () {
                                        ^FOO, 0, 0, 1,
                                        ^FOO, 1, 0, 1,
                                        ^FOO, 2, 0, 1,
                                }
                        },
                        Package () { "power-gpios", Package () { ^FOO, 3, 0, 0 } },
                }
        })
}

For more information about the ACPI GPIO bindings see Documentation/firmware-guide/acpi/gpio-properties.rst.

Software Nodes #

Software nodes allow board-specific code to construct an in-memory, device-tree-like structure using struct software_node and struct property_entry. This structure can then be associated with a platform device, allowing drivers to use the standard device properties API to query configuration, just as they would on an ACPI or device tree system.

Software-node-backed GPIOs are described using the PROPERTY_ENTRY_GPIO() macro, which ties a software node representing the GPIO controller with consumer device. It allows consumers to use regular gpiolib APIs, such as gpiod_get(), gpiod_get_optional().

The software node representing a GPIO controller need not be attached to the GPIO controller device. The only requirement is that the node must be registered and its name must match the GPIO controller's label.

For example, here is how to describe a single GPIO-connected LED. This is an alternative to using platform_data on legacy systems.

#include <linux/property.h>
#include <linux/gpio/machine.h>
#include <linux/gpio/property.h>

/*
 * 1. Define a node for the GPIO controller. Its .name must match the
 *    controller's label.
 */
static const struct software_node gpio_controller_node = {
        .name = "gpio-foo",
};

/* 2. Define the properties for the LED device. */
static const struct property_entry led_device_props[] = {
        PROPERTY_ENTRY_STRING("label", "myboard:green:status"),
        PROPERTY_ENTRY_STRING("linux,default-trigger", "heartbeat"),
        PROPERTY_ENTRY_GPIO("gpios", &gpio_controller_node, 42, GPIO_ACTIVE_HIGH),
        { }
};

/* 3. Define the software node for the LED device. */
static const struct software_node led_device_swnode = {
        .name = "status-led",
        .properties = led_device_props,
};

/*
 * 4. Register the software nodes and the platform device.
 */
const struct software_node *swnodes[] = {
        &gpio_controller_node,
        &led_device_swnode,
        NULL
};
software_node_register_node_group(swnodes);

// Then register a platform_device for "leds-gpio" and associate
// it with &led_device_swnode via .fwnode.

For a complete guide on converting board files to use software nodes, see Documentation/driver-api/gpio/legacy-boards.rst.

Platform Data #

Finally, GPIOs can be bound to devices and functions using platform data. Board files that desire to do so need to include the following header:

#include <linux/gpio/machine.h>

GPIOs are mapped by the means of tables of lookups, containing instances of the gpiod_lookup structure. Two macros are defined to help declaring such mappings:

GPIO_LOOKUP(key, chip_hwnum, con_id, flags)
GPIO_LOOKUP_IDX(key, chip_hwnum, con_id, idx, flags)

where

  • key is either the label of the gpiod_chip instance providing the GPIO, or the GPIO line name

  • chip_hwnum is the hardware number of the GPIO within the chip, or U16_MAX to indicate that key is a GPIO line name

    • con_id is the name of the GPIO function from the device point of view. It

      can be NULL, in which case it will match any function.

  • idx is the index of the GPIO within the function.

    • flags is defined to specify the following properties:

      • GPIO_ACTIVE_HIGH - GPIO line is active high

      • GPIO_ACTIVE_LOW - GPIO line is active low

      • GPIO_OPEN_DRAIN - GPIO line is set up as open drain

      • GPIO_OPEN_SOURCE - GPIO line is set up as open source

        • GPIO_PERSISTENT - GPIO line is persistent during

          suspend/resume and maintains its value

        • GPIO_TRANSITORY - GPIO line is transitory and may loose its

          electrical state during suspend/resume

In the future, these flags might be extended to support more properties.

  • Note that:

    1. GPIO line names are not guaranteed to be globally unique, so the first match found will be used.

    2. GPIO_LOOKUP() is just a shortcut to GPIO_LOOKUP_IDX() where idx = 0.

A lookup table can then be defined as follows, with an empty entry defining its end. The 'dev_id' field of the table is the identifier of the device that will make use of these GPIOs. It can be NULL, in which case it will be matched for calls to gpiod_get() with a NULL device.

struct gpiod_lookup_table gpios_table = {
        .dev_id = "foo.0",
        .table = {
                GPIO_LOOKUP_IDX("gpio.0", 15, "led", 0, GPIO_ACTIVE_HIGH),
                GPIO_LOOKUP_IDX("gpio.0", 16, "led", 1, GPIO_ACTIVE_HIGH),
                GPIO_LOOKUP_IDX("gpio.0", 17, "led", 2, GPIO_ACTIVE_HIGH),
                GPIO_LOOKUP("gpio.0", 1, "power", GPIO_ACTIVE_LOW),
                { },
        },
};

And the table can be added by the board code as follows:

gpiod_add_lookup_table(&gpios_table);

The driver controlling "foo.0" will then be able to obtain its GPIOs as follows:

struct gpio_desc *red, *green, *blue, *power;

red = gpiod_get_index(dev, "led", 0, GPIOD_OUT_HIGH);
green = gpiod_get_index(dev, "led", 1, GPIOD_OUT_HIGH);
blue = gpiod_get_index(dev, "led", 2, GPIOD_OUT_HIGH);

power = gpiod_get(dev, "power", GPIOD_OUT_HIGH);

Since the "led" GPIOs are mapped as active-high, this example will switch their signals to 1, i.e. enabling the LEDs. And for the "power" GPIO, which is mapped as active-low, its actual signal will be 0 after this code. Contrary to the legacy integer GPIO interface, the active-low property is handled during mapping and is thus transparent to GPIO consumers.

A set of functions such as gpiod_set_value() is available to work with the new descriptor-oriented interface.

Boards using platform data can also hog GPIO lines by defining GPIO hog tables.

struct gpiod_hog gpio_hog_table[] = {
        GPIO_HOG("gpio.0", 10, "foo", GPIO_ACTIVE_LOW, GPIOD_OUT_HIGH),
        { }
};

And the table can be added to the board code as follows:

gpiod_add_hogs(gpio_hog_table);

The line will be hogged as soon as the gpiochip is created or - in case the chip was created earlier - when the hog table is registered.

Arrays of pins #

In addition to requesting pins belonging to a function one by one, a device may also request an array of pins assigned to the function. The way those pins are mapped to the device determines if the array qualifies for fast bitmap processing. If yes, a bitmap is passed over get/set array functions directly between a caller and a respective .get/set_multiple() callback of a GPIO chip.

In order to qualify for fast bitmap processing, the array must meet the following requirements:

  • pin hardware number of array member 0 must also be 0,

  • pin hardware numbers of consecutive array members which belong to the same chip as member 0 does must also match their array indexes.

Otherwise fast bitmap processing path is not used in order to avoid consecutive pins which belong to the same chip but are not in hardware order being processed separately.

If the array applies for fast bitmap processing path, pins which belong to different chips than member 0 does, as well as those with indexes different from their hardware pin numbers, are excluded from the fast path, both input and output. Moreover, open drain and open source pins are excluded from fast bitmap output processing.

A driver for a selfmade cheap BT8xx based PCI GPIO-card (bt8xxgpio)

Peios Kernel / Hardware and drivers / Driver development / GPIO

For advanced documentation, see https://bues.ch/cms/unmaintained/btgpio.html

A generic digital 24-port PCI GPIO card can be built out of an ordinary Brooktree bt848, bt849, bt878 or bt879 based analog TV tuner card. The Brooktree chip is used in old analog Hauppauge WinTV PCI cards. You can easily find them used for low prices on the net.

The bt8xx chip does have 24 digital GPIO ports. These ports are accessible via 24 pins on the SMD chip package.

How to physically access the GPIO pins #

The are several ways to access these pins. One might unsolder the whole chip and put it on a custom PCI board, or one might only unsolder each individual GPIO pin and solder that to some tiny wire. As the chip package really is tiny there are some advanced soldering skills needed in any case.

The physical pinouts are drawn in the following ASCII art. The GPIO pins are marked with G00-G23:

                                  G G G G G G G G G G G G     G G G G G G
                                  0 0 0 0 0 0 0 0 0 0 1 1     1 1 1 1 1 1
                                  0 1 2 3 4 5 6 7 8 9 0 1     2 3 4 5 6 7
  | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
  ---------------------------------------------------------------------------
--|                               ^                                     ^   |--
--|                               pin 86                           pin 67   |--
--|                                                                         |--
--|                                                               pin 61 >  |-- G18
--|                                                                         |-- G19
--|                                                                         |-- G20
--|                                                                         |-- G21
--|                                                                         |-- G22
--|                                                               pin 56 >  |-- G23
--|                                                                         |--
--|                           Brooktree 878/879                             |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|   O                                                                     |--
--|                                                                         |--
  ---------------------------------------------------------------------------
  | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
  ^
  This is pin 1

GPIO Descriptor Consumer Interface

Peios Kernel / Hardware and drivers / Driver development / GPIO

This document describes the consumer interface of the GPIO framework.

Guidelines for GPIOs consumers #

Drivers that can't work without standard GPIO calls should have Kconfig entries that depend on GPIOLIB or select GPIOLIB. The functions that allow a driver to obtain and use GPIOs are available by including the following file:

#include <linux/gpio/consumer.h>

There are static inline stubs for all functions in the header file in the case where GPIOLIB is disabled. When these stubs are called they will emit warnings. These stubs are used for two use cases:

  • Simple compile coverage with e.g. COMPILE_TEST - it does not matter that the current platform does not enable or select GPIOLIB because we are not going to execute the system anyway.

  • Truly optional GPIOLIB support - where the driver does not really make use of the GPIOs on certain compile-time configurations for certain systems, but will use it under other compile-time configurations. In this case the consumer must make sure not to call into these functions, or the user will be met with console warnings that may be perceived as intimidating. Combining truly optional GPIOLIB usage with calls to [devm_]gpiod_get_optional() is a bad idea, and will result in weird error messages. Use the ordinary getter functions with optional GPIOLIB: some open coding of error handling should be expected when you do this.

All the functions that work with the descriptor-based GPIO interface are prefixed with gpiod_. The gpio_ prefix is used for the legacy interface. No other function in the kernel should use these prefixes. The use of the legacy functions is strongly discouraged, new code should use <linux/gpio/consumer.h> and descriptors exclusively.

Obtaining and Disposing GPIOs #

With the descriptor-based interface, GPIOs are identified with an opaque, non-forgeable handler that must be obtained through a call to one of the gpiod_get() functions. Like many other kernel subsystems, gpiod_get() takes the device that will use the GPIO and the function the requested GPIO is supposed to fulfill:

struct gpio_desc *gpiod_get(struct device *dev, const char *con_id,
                            enum gpiod_flags flags)

If a function is implemented by using several GPIOs together (e.g. a simple LED device that displays digits), an additional index argument can be specified:

struct gpio_desc *gpiod_get_index(struct device *dev,
                                  const char *con_id, unsigned int idx,
                                  enum gpiod_flags flags)

For a more detailed description of the con_id parameter in the DeviceTree case see Documentation/driver-api/gpio/board.rst

The flags parameter is used to optionally specify a direction and initial value for the GPIO. Values can be:

  • GPIOD_ASIS or 0 to not initialize the GPIO at all. The direction must be set later with one of the dedicated functions.

  • GPIOD_IN to initialize the GPIO as input.

  • GPIOD_OUT_LOW to initialize the GPIO as output with a value of 0.

  • GPIOD_OUT_HIGH to initialize the GPIO as output with a value of 1.

  • GPIOD_OUT_LOW_OPEN_DRAIN same as GPIOD_OUT_LOW but also enforce the line to be electrically used with open drain.

  • GPIOD_OUT_HIGH_OPEN_DRAIN same as GPIOD_OUT_HIGH but also enforce the line to be electrically used with open drain.

Note that the initial value is logical and the physical line level depends on whether the line is configured active high or active low (see The active low and open drain semantics).

The two last flags are used for use cases where open drain is mandatory, such as I2C: if the line is not already configured as open drain in the mappings (see board.rst), then open drain will be enforced anyway and a warning will be printed that the board configuration needs to be updated to match the use case.

Both functions return either a valid GPIO descriptor, or an error code checkable with IS_ERR() (they will never return a NULL pointer). -ENOENT will be returned if and only if no GPIO has been assigned to the device/function/index triplet, other error codes are used for cases where a GPIO has been assigned but an error occurred while trying to acquire it. This is useful to discriminate between mere errors and an absence of GPIO for optional GPIO parameters. For the common pattern where a GPIO is optional, the gpiod_get_optional() and gpiod_get_index_optional() functions can be used. These functions return NULL instead of -ENOENT if no GPIO has been assigned to the requested function:

struct gpio_desc *gpiod_get_optional(struct device *dev,
                                     const char *con_id,
                                     enum gpiod_flags flags)

struct gpio_desc *gpiod_get_index_optional(struct device *dev,
                                           const char *con_id,
                                           unsigned int index,
                                           enum gpiod_flags flags)

Note that gpio_get*_optional() functions (and their managed variants), unlike the rest of gpiolib API, also return NULL when gpiolib support is disabled. This is helpful to driver authors, since they do not need to special case -ENOSYS return codes. System integrators should however be careful to enable gpiolib on systems that need it.

For a function using multiple GPIOs all of those can be obtained with one call:

struct gpio_descs *gpiod_get_array(struct device *dev,
                                   const char *con_id,
                                   enum gpiod_flags flags)

This function returns a struct gpio_descs which contains an array of descriptors. It also contains a pointer to a gpiolib private structure which, if passed back to get/set array functions, may speed up I/O processing:

struct gpio_descs {
        struct gpio_array *info;
        unsigned int ndescs;
        struct gpio_desc *desc[];
}

The following function returns NULL instead of -ENOENT if no GPIOs have been assigned to the requested function:

struct gpio_descs *gpiod_get_array_optional(struct device *dev,
                                            const char *con_id,
                                            enum gpiod_flags flags)

Device-managed variants of these functions are also defined:

struct gpio_desc *devm_gpiod_get(struct device *dev, const char *con_id,
                                 enum gpiod_flags flags)

struct gpio_desc *devm_gpiod_get_index(struct device *dev,
                                       const char *con_id,
                                       unsigned int idx,
                                       enum gpiod_flags flags)

struct gpio_desc *devm_gpiod_get_optional(struct device *dev,
                                          const char *con_id,
                                          enum gpiod_flags flags)

struct gpio_desc *devm_gpiod_get_index_optional(struct device *dev,
                                                const char *con_id,
                                                unsigned int index,
                                                enum gpiod_flags flags)

struct gpio_descs *devm_gpiod_get_array(struct device *dev,
                                        const char *con_id,
                                        enum gpiod_flags flags)

struct gpio_descs *devm_gpiod_get_array_optional(struct device *dev,
                                                 const char *con_id,
                                                 enum gpiod_flags flags)

A GPIO descriptor can be disposed of using the gpiod_put() function:

void gpiod_put(struct gpio_desc *desc)

For an array of GPIOs this function can be used:

void gpiod_put_array(struct gpio_descs *descs)

It is strictly forbidden to use a descriptor after calling these functions. It is also not allowed to individually release descriptors (using gpiod_put()) from an array acquired with gpiod_get_array().

The device-managed variants are, unsurprisingly:

void devm_gpiod_put(struct device *dev, struct gpio_desc *desc)

void devm_gpiod_put_array(struct device *dev, struct gpio_descs *descs)

Using GPIOs #

Setting Direction #

The first thing a driver must do with a GPIO is setting its direction. If no direction-setting flags have been given to gpiod_get*(), this is done by invoking one of the gpiod_direction_*() functions:

int gpiod_direction_input(struct gpio_desc *desc)
int gpiod_direction_output(struct gpio_desc *desc, int value)

The return value is zero for success, else a negative errno. It should be checked, since the get/set calls don't return errors and since misconfiguration is possible. You should normally issue these calls from a task context. However, for spinlock-safe GPIOs it is OK to use them before 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.

A driver can also query the current direction of a GPIO:

int gpiod_get_direction(const struct gpio_desc *desc)

This function returns 0 for output, 1 for input, or an error code in case of error.

Be aware that there is no default direction for GPIOs. Therefore, using a GPIO without setting its direction first is illegal and will result in undefined behavior!

Spinlock-Safe GPIO Access #

Most GPIO controllers can be accessed with memory read/write instructions. Those don't need to sleep, and can safely be done from inside hard (non-threaded) IRQ handlers and similar contexts.

Use the following calls to access GPIOs from an atomic context:

int gpiod_get_value(const struct gpio_desc *desc);
void gpiod_set_value(struct gpio_desc *desc, int value);

The values are boolean, zero for inactive, nonzero for active. 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 issues including open-drain signaling and output latencies.

The get/set calls do not return errors because "invalid GPIO" should have been reported earlier from gpiod_direction_*(). However, note that not all platforms can read the value of output pins; those that can't should always return zero. Also, using these calls for GPIOs that can't safely be accessed without sleeping (see below) is an error.

GPIO Access That May Sleep #

Some GPIO controllers must be accessed using message based buses 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 by returning nonzero from this call:

int gpiod_cansleep(const struct gpio_desc *desc)

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

int gpiod_get_value_cansleep(const struct gpio_desc *desc)
void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)

Accessing such GPIOs requires a context which may sleep, for example a threaded IRQ handler, and those accessors must be used instead of spinlock-safe accessors without the cansleep() name suffix.

Other than the fact that these accessors might sleep, and will work on GPIOs that can't be accessed from hardIRQ handlers, these calls act the same as the spinlock-safe calls.

The active low and open drain semantics #

As a consumer should not have to care about the physical line level, all of the gpiod_set_value_xxx() or gpiod_set_array_value_xxx() functions operate with the logical value. With this they take the active low property into account. This means that they check whether the GPIO is configured to be active low, and if so, they manipulate the passed value before the physical line level is driven.

The same is applicable for open drain or open source output lines: those do not actively drive their output high (open drain) or low (open source), they just switch their output to a high impedance value. The consumer should not need to care. (For details read about open drain in driver.rst.)

With this, all the gpiod_set_(array)_value_xxx() functions interpret the parameter "value" as "active" ("1") or "inactive" ("0"). The physical line level will be driven accordingly.

As an example, if the active low property for a dedicated GPIO is set, and the gpiod_set_(array)_value_xxx() passes "active" ("1"), the physical line level will be driven low.

To summarize:

Function (example)                 line property          physical line
gpiod_set_raw_value(desc, 0);      don't care             low
gpiod_set_raw_value(desc, 1);      don't care             high
gpiod_set_value(desc, 0);          default (active high)  low
gpiod_set_value(desc, 1);          default (active high)  high
gpiod_set_value(desc, 0);          active low             high
gpiod_set_value(desc, 1);          active low             low
gpiod_set_value(desc, 0);          open drain             low
gpiod_set_value(desc, 1);          open drain             high impedance
gpiod_set_value(desc, 0);          open source            high impedance
gpiod_set_value(desc, 1);          open source            high

It is possible to override these semantics using the set_raw/get_raw functions but it should be avoided as much as possible, especially by system-agnostic drivers which should not need to care about the actual physical line level and worry about the logical value instead.

Accessing raw GPIO values #

Consumers exist that need to manage the logical state of a GPIO line, i.e. the value their device will actually receive, no matter what lies between it and the GPIO line.

The following set of calls ignore the active-low or open drain property of a GPIO and work on the raw line value:

int gpiod_get_raw_value(const struct gpio_desc *desc)
void gpiod_set_raw_value(struct gpio_desc *desc, int value)
int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
int gpiod_direction_output_raw(struct gpio_desc *desc, int value)

The active low state of a GPIO can also be queried and toggled using the following calls:

int gpiod_is_active_low(const struct gpio_desc *desc)
void gpiod_toggle_active_low(struct gpio_desc *desc)

Note that these functions should only be used with great moderation; a driver should not have to care about the physical line level or open drain semantics.

Access multiple GPIOs with a single function call #

The following functions get or set the values of an array of GPIOs:

int gpiod_get_array_value(unsigned int array_size,
                          struct gpio_desc **desc_array,
                          struct gpio_array *array_info,
                          unsigned long *value_bitmap);
int gpiod_get_raw_array_value(unsigned int array_size,
                              struct gpio_desc **desc_array,
                              struct gpio_array *array_info,
                              unsigned long *value_bitmap);
int gpiod_get_array_value_cansleep(unsigned int array_size,
                                   struct gpio_desc **desc_array,
                                   struct gpio_array *array_info,
                                   unsigned long *value_bitmap);
int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
                                   struct gpio_desc **desc_array,
                                   struct gpio_array *array_info,
                                   unsigned long *value_bitmap);

int gpiod_set_array_value(unsigned int array_size,
                          struct gpio_desc **desc_array,
                          struct gpio_array *array_info,
                          unsigned long *value_bitmap)
int gpiod_set_raw_array_value(unsigned int array_size,
                              struct gpio_desc **desc_array,
                              struct gpio_array *array_info,
                              unsigned long *value_bitmap)
int gpiod_set_array_value_cansleep(unsigned int array_size,
                                   struct gpio_desc **desc_array,
                                   struct gpio_array *array_info,
                                   unsigned long *value_bitmap)
int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
                                       struct gpio_desc **desc_array,
                                       struct gpio_array *array_info,
                                       unsigned long *value_bitmap)

The array can be an arbitrary set of GPIOs. The functions will try to access GPIOs belonging to the same bank or chip simultaneously if supported by the corresponding chip driver. In that case a significantly improved performance can be expected. If simultaneous access is not possible the GPIOs will be accessed sequentially.

The functions take four arguments:

  • array_size - the number of array elements

  • desc_array - an array of GPIO descriptors

  • array_info - optional information obtained from gpiod_get_array()

  • value_bitmap - a bitmap to store the GPIOs' values (get) or a bitmap of values to assign to the GPIOs (set)

The descriptor array can be obtained using the gpiod_get_array() function or one of its variants. If the group of descriptors returned by that function matches the desired group of GPIOs, those GPIOs can be accessed by simply using the struct gpio_descs returned by gpiod_get_array():

struct gpio_descs *my_gpio_descs = gpiod_get_array(...);
gpiod_set_array_value(my_gpio_descs->ndescs, my_gpio_descs->desc,
                      my_gpio_descs->info, my_gpio_value_bitmap);

It is also possible to access a completely arbitrary array of descriptors. The descriptors may be obtained using any combination of gpiod_get() and gpiod_get_array(). Afterwards the array of descriptors has to be setup manually before it can be passed to one of the above functions. In that case, array_info should be set to NULL.

Note that for optimal performance GPIOs belonging to the same chip should be contiguous within the array of descriptors.

Still better performance may be achieved if array indexes of the descriptors match hardware pin numbers of a single chip. If an array passed to a get/set array function matches the one obtained from gpiod_get_array() and array_info associated with the array is also passed, the function may take a fast bitmap processing path, passing the value_bitmap argument directly to the respective .get/set_multiple() callback of the chip. That allows for utilization of GPIO banks as data I/O ports without much loss of performance.

The return value of gpiod_get_array_value() and its variants is 0 on success or negative on error. Note the difference to gpiod_get_value(), which returns 0 or 1 on success to convey the GPIO value. With the array functions, the GPIO values are stored in value_array rather than passed back as return value.

GPIOs mapped to IRQs #

GPIO lines can quite often be used as IRQs. You can get the IRQ number corresponding to a given GPIO using the following call:

int gpiod_to_irq(const struct gpio_desc *desc)

It will return an IRQ number, or a negative errno code if the mapping can't be done (most likely because that particular GPIO cannot be used as IRQ). It is an unchecked error to use a GPIO that wasn't set up as an input using gpiod_direction_input(), or to use an IRQ number that didn't originally come from gpiod_to_irq(). gpiod_to_irq() is not allowed to sleep.

Non-error values returned from gpiod_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.

GPIOs and ACPI #

On ACPI systems, GPIOs are described by GpioIo()/GpioInt() resources listed by the _CRS configuration objects of devices. Those resources do not provide connection IDs (names) for GPIOs, so it is necessary to use an additional mechanism for this purpose.

Systems compliant with ACPI 5.1 or newer may provide a _DSD configuration object which, among other things, may be used to provide connection IDs for specific GPIOs described by the GpioIo()/GpioInt() resources in _CRS. If that is the case, it will be handled by the GPIO subsystem automatically. However, if the _DSD is not present, the mappings between GpioIo()/GpioInt() resources and GPIO connection IDs need to be provided by device drivers.

For details refer to Documentation/firmware-guide/acpi/gpio-properties.rst

Interacting With the Legacy GPIO Subsystem #

Many kernel subsystems and drivers still handle GPIOs using the legacy integer-based interface. It is strongly recommended to update these to the new gpiod interface. For cases where both interfaces need to be used, the following two functions allow to convert a GPIO descriptor into the GPIO integer namespace and vice-versa:

int desc_to_gpio(const struct gpio_desc *desc)
struct gpio_desc *gpio_to_desc(unsigned gpio)

The GPIO number returned by desc_to_gpio() can safely be used as a parameter of the gpio_*() functions for as long as the GPIO descriptor desc is not freed. All the same, a GPIO number passed to gpio_to_desc() must first be properly acquired using e.g. gpio_request_one(), and the returned GPIO descriptor is only considered valid until that GPIO number is released using gpio_free().

Freeing a GPIO obtained by one API with the other API is forbidden and an unchecked error.

GPIO Driver Interface

Peios Kernel / Hardware and drivers / Driver development / GPIO

This document serves as a guide for writers of GPIO chip drivers.

Each GPIO controller driver needs to include the following header, which defines the structures used to define a GPIO driver:

#include <linux/gpio/driver.h>

Internal Representation of GPIOs #

A GPIO chip handles one or more GPIO lines. To be considered a GPIO chip, the lines must conform to the definition: General Purpose Input/Output. If the line is not general purpose, it is not GPIO and should not be handled by a GPIO chip. The use case is the indicative: certain lines in a system may be called GPIO but serve a very particular purpose thus not meeting the criteria of a general purpose I/O. On the other hand a LED driver line may be used as a GPIO and should therefore still be handled by a GPIO chip driver.

Inside a GPIO driver, individual GPIO lines are identified by their hardware number, sometime also referred to as offset, which is a unique number between 0 and n-1, n being the number of GPIOs managed by the chip.

The hardware GPIO number should be something intuitive to the hardware, for example if a system uses a memory-mapped set of I/O-registers where 32 GPIO lines are handled by one bit per line in a 32-bit register, it makes sense to use hardware offsets 0..31 for these, corresponding to bits 0..31 in the register.

This number is purely internal: the hardware number of a particular GPIO line is never made visible outside of the driver.

On top of this internal number, each GPIO line also needs to have a global number in the integer GPIO namespace so that it can be used with the legacy GPIO interface. Each chip must thus have a "base" number (which can be automatically assigned), and for each GPIO line the global number will be (base + hardware number). Although the integer representation is considered deprecated, it still has many users and thus needs to be maintained.

So for example one platform could use global numbers 32-159 for GPIOs, with a controller defining 128 GPIOs at a "base" of 32 ; while another platform uses global 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 legacy numbers need not be contiguous; either of those platforms could also use numbers 2000-2063 to identify GPIO lines in a bank of I2C GPIO expanders.

Controller Drivers: gpio_chip #

In the gpiolib framework each GPIO controller is packaged as a "struct gpio_chip" (see <linux/gpio/driver.h> for its complete definition) with members common to each controller of that type, these should be assigned by the driver code:

  • methods to establish GPIO line direction

  • methods used to access GPIO line values

  • method to set electrical configuration for a given GPIO line

  • method to return the IRQ number associated to a given GPIO line

  • flag saying whether calls to its methods may sleep

  • optional line names array to identify lines

  • optional debugfs dump method (showing extra state information)

  • optional base number (will be automatically assigned if omitted)

  • optional label for diagnostics and GPIO chip mapping using platform data

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

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

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

Realtime considerations: the GPIO driver should not use spinlock_t or any sleepable APIs (like PM runtime) in its gpio_chip implementation (.get/.set and direction control callbacks) if it is expected to call GPIO APIs from atomic context on realtime kernels (inside hard IRQ handlers and similar contexts). Normally this should not be required.

GPIO electrical configuration #

GPIO lines can be configured for several electrical modes of operation by using the .set_config() callback. Currently this API supports setting:

  • Debouncing

  • Single-ended modes (open drain/open source)

  • Pull up and pull down resistor enablement

These settings are described below.

The .set_config() callback uses the same enumerators and configuration semantics as the generic pin control drivers. This is not a coincidence: it is possible to assign the .set_config() to the function gpiochip_generic_config() which will result in pinctrl_gpio_set_config() being called and eventually ending up in the pin control back-end "behind" the GPIO controller, usually closer to the actual pins. This way the pin controller can manage the below listed GPIO configurations.

If a pin controller back-end is used, the GPIO controller or hardware description needs to provide "GPIO ranges" mapping the GPIO line offsets to pin numbers on the pin controller so they can properly cross-reference each other.

GPIO lines with debounce support #

Debouncing is a configuration set to a pin indicating that it is connected to a mechanical switch or button, or similar that may bounce. Bouncing means the line is pulled high/low quickly at very short intervals for mechanical reasons. This can result in the value being unstable or irqs firing repeatedly unless the line is debounced.

Debouncing in practice involves setting up a timer when something happens on the line, wait a little while and then sample the line again, so see if it still has the same value (low or high). This could also be repeated by a clever state machine, waiting for a line to become stable. In either case, it sets a certain number of milliseconds for debouncing, or just "on/off" if that time is not configurable.

GPIO lines with open drain/source support #

Open drain (CMOS) or open collector (TTL) means the line is not actively driven high: instead you provide the drain/collector as output, so when the transistor is not open, it will present a high-impedance (tristate) to the external rail:

CMOS CONFIGURATION      TTL CONFIGURATION

         ||--- out              +--- out
  in ----||                   |/
         ||--+         in ----|
             |                |\
            GND                 GND

This configuration is normally used as a way to achieve one of two things:

  • Level-shifting: to reach a logical level higher than that of the silicon where the output resides.

  • Inverse wire-OR on an I/O line, for example a GPIO line, making it possible for any driving stage on the line to drive it low even if any other output to the same line is simultaneously driving it high. A special case of this is driving the SCL and SDA lines of an I2C bus, which is by definition a wire-OR bus.

Both use cases require that the line be equipped with a pull-up resistor. This resistor will make the line tend to high level unless one of the transistors on the rail actively pulls it down.

The level on the line will go as high as the VDD on the pull-up resistor, which may be higher than the level supported by the transistor, achieving a level-shift to the higher VDD.

Integrated electronics often have an output driver stage in the form of a CMOS "totem-pole" with one N-MOS and one P-MOS transistor where one of them drives the line high and one of them drives the line low. This is called a push-pull output. The "totem-pole" looks like so:

                 VDD
                  |
        OD    ||--+
     +--/ ---o||     P-MOS-FET
     |        ||--+
IN --+            +----- out
     |        ||--+
     +--/ ----||     N-MOS-FET
        OS    ||--+
                  |
                 GND

The desired output signal (e.g. coming directly from some GPIO output register) arrives at IN. The switches named "OD" and "OS" are normally closed, creating a push-pull circuit.

Consider the little "switches" named "OD" and "OS" that enable/disable the P-MOS or N-MOS transistor right after the split of the input. As you can see, either transistor will go totally numb if this switch is open. The totem-pole is then halved and give high impedance instead of actively driving the line high or low respectively. That is usually how software-controlled open drain/source works.

Some GPIO hardware come in open drain / open source configuration. Some are hard-wired lines that will only support open drain or open source no matter what: there is only one transistor there. Some are software-configurable: by flipping a bit in a register the output can be configured as open drain or open source, in practice by flicking open the switches labeled "OD" and "OS" in the drawing above.

By disabling the P-MOS transistor, the output can be driven between GND and high impedance (open drain), and by disabling the N-MOS transistor, the output can be driven between VDD and high impedance (open source). In the first case, a pull-up resistor is needed on the outgoing rail to complete the circuit, and in the second case, a pull-down resistor is needed on the rail.

Hardware that supports open drain or open source or both, can implement a special callback in the gpio_chip: .set_config() that takes a generic pinconf packed value telling whether to configure the line as open drain, open source or push-pull. This will happen in response to the GPIO_OPEN_DRAIN or GPIO_OPEN_SOURCE flag set in the machine file, or coming from other hardware descriptions.

If this state can not be configured in hardware, i.e. if the GPIO hardware does not support open drain/open source in hardware, the GPIO library will instead use a trick: when a line is set as output, if the line is flagged as open drain, and the IN output value is low, it will be driven low as usual. But if the IN output value is set to high, it will instead NOT be driven high, instead it will be switched to input, as input mode is an equivalent to high impedance, thus achieving an "open drain emulation" of sorts: electrically the behaviour will be identical, with the exception of possible hardware glitches when switching the mode of the line.

For open source configuration the same principle is used, just that instead of actively driving the line low, it is set to input.

GPIO lines with pull up/down resistor support #

A GPIO line can support pull-up/down using the .set_config() callback. This means that a pull up or pull-down resistor is available on the output of the GPIO line, and this resistor is software controlled.

In discrete designs, a pull-up or pull-down resistor is simply soldered on the circuit board. This is not something we deal with or model in software. The most you will think about these lines is that they will very likely be configured as open drain or open source (see the section above).

The .set_config() callback can only turn pull up or down on and off, and will no have any semantic knowledge about the resistance used. It will only say switch a bit in a register enabling or disabling pull-up or pull-down.

If the GPIO line supports shunting in different resistance values for the pull-up or pull-down resistor, the GPIO chip callback .set_config() will not suffice. For these complex use cases, a combined GPIO chip and pin controller need to be implemented, as the pin config interface of a pin controller supports more versatile control over electrical properties and can handle different pull-up or pull-down resistance values.

GPIO drivers providing IRQs #

It is custom that GPIO drivers (GPIO chips) are also providing interrupts, most often cascaded off a parent interrupt controller, and in some special cases the GPIO logic is melded with a SoC's primary interrupt controller.

The IRQ portions of the GPIO block are implemented using an irq_chip, using the header <linux/irq.h>. So this combined driver is utilizing two sub- systems simultaneously: gpio and irq.

It is legal for any IRQ consumer to request an IRQ from any irqchip even if it is a combined GPIO+IRQ driver. The basic premise is that gpio_chip and irq_chip are orthogonal, and offering their services independent of each other.

gpiod_to_irq() is just a convenience function to figure out the IRQ for a certain GPIO line and should not be relied upon to have been called before the IRQ is used.

Always prepare the hardware and make it ready for action in respective callbacks from the GPIO and irq_chip APIs. Do not rely on gpiod_to_irq() having been called first.

We can divide GPIO irqchips in two broad categories:

  • CASCADED INTERRUPT CHIPS: this means that the GPIO chip has one common interrupt output line, which is triggered by any enabled GPIO line on that chip. The interrupt output line will then be routed to an parent interrupt controller one level up, in the most simple case the systems primary interrupt controller. This is modeled by an irqchip that will inspect bits inside the GPIO controller to figure out which line fired it. The irqchip part of the driver needs to inspect registers to figure this out and it will likely also need to acknowledge that it is handling the interrupt by clearing some bit (sometime implicitly, by just reading a status register) and it will often need to set up the configuration such as edge sensitivity (rising or falling edge, or high/low level interrupt for example).

  • HIERARCHICAL INTERRUPT CHIPS: this means that each GPIO line has a dedicated irq line to a parent interrupt controller one level up. There is no need to inquire the GPIO hardware to figure out which line has fired, but it may still be necessary to acknowledge the interrupt and set up configuration such as edge sensitivity.

Realtime considerations: a realtime compliant GPIO driver should not use spinlock_t or any sleepable APIs (like PM runtime) as part of its irqchip implementation.

  • spinlock_t should be replaced with raw_spinlock_t.[1]

  • If sleepable APIs have to be used, these can be done from the .irq_bus_lock() and .irq_bus_unlock() callbacks, as these are the only slowpath callbacks on an irqchip. Create the callbacks if needed.[2]

Cascaded GPIO irqchips #

Cascaded GPIO irqchips usually fall in one of three categories:

  • CHAINED CASCADED GPIO IRQCHIPS: these are usually the type that is embedded on an SoC. This means that there is a fast IRQ flow handler for the GPIOs that gets called in a chain from the parent IRQ handler, most typically the system interrupt controller. This means that the GPIO irqchip handler will be called immediately from the parent irqchip, while holding the IRQs disabled. The GPIO irqchip will then end up calling something like this sequence in its interrupt handler:

    static irqreturn_t foo_gpio_irq(int irq, void *data)
        chained_irq_enter(...);
        generic_handle_irq(...);
        chained_irq_exit(...);
    

    Chained GPIO irqchips typically can NOT set the .can_sleep flag on struct gpio_chip, as everything happens directly in the callbacks: no slow bus traffic like I2C can be used.

    Realtime considerations: Note that chained IRQ handlers will not be forced threaded on -RT. As a result, spinlock_t or any sleepable APIs (like PM runtime) can't be used in a chained IRQ handler.

    If required (and if it can't be converted to the nested threaded GPIO irqchip, see below) a chained IRQ handler can be converted to generic irq handler and this way it will become a threaded IRQ handler on -RT and a hard IRQ handler on non-RT (for example, see [3]).

    The generic_handle_irq() is expected to be called with IRQ disabled, so the IRQ core will complain if it is called from an IRQ handler which is forced to a thread. The "fake?" raw lock can be used to work around this problem:

    raw_spinlock_t wa_lock;
    static irqreturn_t omap_gpio_irq_handler(int irq, void *gpiobank)
        unsigned long wa_lock_flags;
        raw_spin_lock_irqsave(&bank->wa_lock, wa_lock_flags);
        generic_handle_irq(irq_find_mapping(bank->chip.irq.domain, bit));
        raw_spin_unlock_irqrestore(&bank->wa_lock, wa_lock_flags);
    
  • GENERIC CHAINED GPIO IRQCHIPS: these are the same as "CHAINED GPIO irqchips", but chained IRQ handlers are not used. Instead GPIO IRQs dispatching is performed by generic IRQ handler which is configured using request_irq(). The GPIO irqchip will then end up calling something like this sequence in its interrupt handler:

    static irqreturn_t gpio_rcar_irq_handler(int irq, void *dev_id)
        for each detected GPIO IRQ
            generic_handle_irq(...);
    

    Realtime considerations: this kind of handlers will be forced threaded on -RT, and as result the IRQ core will complain that generic_handle_irq() is called with IRQ enabled and the same work-around as for "CHAINED GPIO irqchips" can be applied.

  • NESTED THREADED GPIO IRQCHIPS: these are off-chip GPIO expanders and any other GPIO irqchip residing on the other side of a sleeping bus such as I2C or SPI.

    Of course such drivers that need slow bus traffic to read out IRQ status and similar, traffic which may in turn incur other IRQs to happen, cannot be handled in a quick IRQ handler with IRQs disabled. Instead they need to spawn a thread and then mask the parent IRQ line until the interrupt is handled by the driver. The hallmark of this driver is to call something like this in its interrupt handler:

    static irqreturn_t foo_gpio_irq(int irq, void *data)
        ...
        handle_nested_irq(irq);
    

    The hallmark of threaded GPIO irqchips is that they set the .can_sleep flag on struct gpio_chip to true, indicating that this chip may sleep when accessing the GPIOs.

    These kinds of irqchips are inherently realtime tolerant as they are already set up to handle sleeping contexts.

Infrastructure helpers for GPIO irqchips #

To help out in handling the set-up and management of GPIO irqchips and the associated irqdomain and resource allocation callbacks. These are activated by selecting the Kconfig symbol GPIOLIB_IRQCHIP. If the symbol IRQ_DOMAIN_HIERARCHY is also selected, hierarchical helpers will also be provided. A big portion of overhead code will be managed by gpiolib, under the assumption that your interrupts are 1-to-1-mapped to the GPIO line index:

GPIO line offset

Hardware IRQ

0

0

1

1

2

2

...

...

ngpio-1

ngpio-1

If some GPIO lines do not have corresponding IRQs, the bitmask valid_mask and the flag need_valid_mask in gpio_irq_chip can be used to mask off some lines as invalid for associating with IRQs.

The preferred way to set up the helpers is to fill in the struct gpio_irq_chip inside struct gpio_chip before adding the gpio_chip. If you do this, the additional irq_chip will be set up by gpiolib at the same time as setting up the rest of the GPIO functionality. The following is a typical example of a chained cascaded interrupt handler using the gpio_irq_chip. Note how the mask/unmask (or disable/enable) functions call into the core gpiolib code:

/* Typical state container */
struct my_gpio {
    struct gpio_chip gc;
};

static void my_gpio_mask_irq(struct irq_data *d)
{
    struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
    irq_hw_number_t hwirq = irqd_to_hwirq(d);

    /*
     * Perform any necessary action to mask the interrupt,
     * and then call into the core code to synchronise the
     * state.
     */

    gpiochip_disable_irq(gc, hwirq);
}

static void my_gpio_unmask_irq(struct irq_data *d)
{
    struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
    irq_hw_number_t hwirq = irqd_to_hwirq(d);

    gpiochip_enable_irq(gc, hwirq);

    /*
     * Perform any necessary action to unmask the interrupt,
     * after having called into the core code to synchronise
     * the state.
     */
}

/*
 * Statically populate the irqchip. Note that it is made const
 * (further indicated by the IRQCHIP_IMMUTABLE flag), and that
 * the GPIOCHIP_IRQ_RESOURCE_HELPER macro adds some extra
 * callbacks to the structure.
 */
static const struct irq_chip my_gpio_irq_chip = {
    .name             = "my_gpio_irq",
    .irq_ack          = my_gpio_ack_irq,
    .irq_mask         = my_gpio_mask_irq,
    .irq_unmask       = my_gpio_unmask_irq,
    .irq_set_type     = my_gpio_set_irq_type,
    .flags            = IRQCHIP_IMMUTABLE,
    /* Provide the gpio resource callbacks */
    GPIOCHIP_IRQ_RESOURCE_HELPERS,
};

int irq; /* from platform etc */
struct my_gpio *g;
struct gpio_irq_chip *girq;

/* Get a pointer to the gpio_irq_chip */
girq = &g->gc.irq;
gpio_irq_chip_set_chip(girq, &my_gpio_irq_chip);
girq->parent_handler = ftgpio_gpio_irq_handler;
girq->num_parents = 1;
girq->parents = devm_kcalloc(dev, 1, sizeof(*girq->parents),
                             GFP_KERNEL);
if (!girq->parents)
    return -ENOMEM;
girq->default_type = IRQ_TYPE_NONE;
girq->handler = handle_bad_irq;
girq->parents[0] = irq;

return devm_gpiochip_add_data(dev, &g->gc, g);

The helper supports using threaded interrupts as well. Then you just request the interrupt separately and go with it:

/* Typical state container */
struct my_gpio {
    struct gpio_chip gc;
};

static void my_gpio_mask_irq(struct irq_data *d)
{
    struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
    irq_hw_number_t hwirq = irqd_to_hwirq(d);

    /*
     * Perform any necessary action to mask the interrupt,
     * and then call into the core code to synchronise the
     * state.
     */

    gpiochip_disable_irq(gc, hwirq);
}

static void my_gpio_unmask_irq(struct irq_data *d)
{
    struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
    irq_hw_number_t hwirq = irqd_to_hwirq(d);

    gpiochip_enable_irq(gc, hwirq);

    /*
     * Perform any necessary action to unmask the interrupt,
     * after having called into the core code to synchronise
     * the state.
     */
}

/*
 * Statically populate the irqchip. Note that it is made const
 * (further indicated by the IRQCHIP_IMMUTABLE flag), and that
 * the GPIOCHIP_IRQ_RESOURCE_HELPER macro adds some extra
 * callbacks to the structure.
 */
static const struct irq_chip my_gpio_irq_chip = {
    .name             = "my_gpio_irq",
    .irq_ack          = my_gpio_ack_irq,
    .irq_mask         = my_gpio_mask_irq,
    .irq_unmask       = my_gpio_unmask_irq,
    .irq_set_type     = my_gpio_set_irq_type,
    .flags            = IRQCHIP_IMMUTABLE,
    /* Provide the gpio resource callbacks */
    GPIOCHIP_IRQ_RESOURCE_HELPERS,
};

int irq; /* from platform etc */
struct my_gpio *g;
struct gpio_irq_chip *girq;

ret = devm_request_threaded_irq(dev, irq, NULL, irq_thread_fn,
                                IRQF_ONESHOT, "my-chip", g);
if (ret < 0)
    return ret;

/* Get a pointer to the gpio_irq_chip */
girq = &g->gc.irq;
gpio_irq_chip_set_chip(girq, &my_gpio_irq_chip);
/* This will let us handle the parent IRQ in the driver */
girq->parent_handler = NULL;
girq->num_parents = 0;
girq->parents = NULL;
girq->default_type = IRQ_TYPE_NONE;
girq->handler = handle_bad_irq;

return devm_gpiochip_add_data(dev, &g->gc, g);

The helper supports using hierarchical interrupt controllers as well. In this case the typical set-up will look like this:

/* Typical state container with dynamic irqchip */
struct my_gpio {
    struct gpio_chip gc;
    struct fwnode_handle *fwnode;
};

static void my_gpio_mask_irq(struct irq_data *d)
{
    struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
    irq_hw_number_t hwirq = irqd_to_hwirq(d);

    /*
     * Perform any necessary action to mask the interrupt,
     * and then call into the core code to synchronise the
     * state.
     */

    gpiochip_disable_irq(gc, hwirq);
    irq_mask_mask_parent(d);
}

static void my_gpio_unmask_irq(struct irq_data *d)
{
    struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
    irq_hw_number_t hwirq = irqd_to_hwirq(d);

    gpiochip_enable_irq(gc, hwirq);

    /*
     * Perform any necessary action to unmask the interrupt,
     * after having called into the core code to synchronise
     * the state.
     */

    irq_mask_unmask_parent(d);
}

/*
 * Statically populate the irqchip. Note that it is made const
 * (further indicated by the IRQCHIP_IMMUTABLE flag), and that
 * the GPIOCHIP_IRQ_RESOURCE_HELPER macro adds some extra
 * callbacks to the structure.
 */
static const struct irq_chip my_gpio_irq_chip = {
    .name             = "my_gpio_irq",
    .irq_ack          = my_gpio_ack_irq,
    .irq_mask         = my_gpio_mask_irq,
    .irq_unmask       = my_gpio_unmask_irq,
    .irq_set_type     = my_gpio_set_irq_type,
    .flags            = IRQCHIP_IMMUTABLE,
    /* Provide the gpio resource callbacks */
    GPIOCHIP_IRQ_RESOURCE_HELPERS,
};

struct my_gpio *g;
struct gpio_irq_chip *girq;

/* Get a pointer to the gpio_irq_chip */
girq = &g->gc.irq;
gpio_irq_chip_set_chip(girq, &my_gpio_irq_chip);
girq->default_type = IRQ_TYPE_NONE;
girq->handler = handle_bad_irq;
girq->fwnode = g->fwnode;
girq->parent_domain = parent;
girq->child_to_parent_hwirq = my_gpio_child_to_parent_hwirq;

return devm_gpiochip_add_data(dev, &g->gc, g);

As you can see pretty similar, but you do not supply a parent handler for the IRQ, instead a parent irqdomain, an fwnode for the hardware and a function .child_to_parent_hwirq() that has the purpose of looking up the parent hardware irq from a child (i.e. this gpio chip) hardware irq. As always it is good to look at examples in the kernel tree for advice on how to find the required pieces.

If there is a need to exclude certain GPIO lines from the IRQ domain handled by these helpers, we can set .irq.need_valid_mask of the gpiochip before devm_gpiochip_add_data() or gpiochip_add_data() is called. This allocates an .irq.valid_mask with as many bits set as there are GPIO lines in the chip, each bit representing line 0..n-1. Drivers can exclude GPIO lines by clearing bits from this mask. The mask can be filled in the init_valid_mask() callback that is part of the struct gpio_irq_chip.

To use the helpers please keep the following in mind:

  • Make sure to assign all relevant members of the struct gpio_chip so that the irqchip can initialize. E.g. .dev and .can_sleep shall be set up properly.

  • Nominally set gpio_irq_chip.handler to handle_bad_irq. Then, if your irqchip is cascaded, set the handler to handle_level_irq() and/or handle_edge_irq() in the irqchip .set_type() callback depending on what your controller supports and what is requested by the consumer.

Locking IRQ usage #

Since GPIO and irq_chip are orthogonal, we can get conflicts between different use cases. For example a GPIO line used for IRQs should be an input line, it does not make sense to fire interrupts on an output GPIO.

If there is competition inside the subsystem which side is using the resource (a certain GPIO line and register for example) it needs to deny certain operations and keep track of usage inside of the gpiolib subsystem.

Input GPIOs can be used as IRQ signals. When this happens, a driver is requested to mark the GPIO as being used as an IRQ:

int gpiochip_lock_as_irq(struct gpio_chip *chip, unsigned int offset)

This will prevent the use of non-irq related GPIO APIs until the GPIO IRQ lock is released:

void gpiochip_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)

When implementing an irqchip inside a GPIO driver, these two functions should typically be called in the .startup() and .shutdown() callbacks from the irqchip.

When using the gpiolib irqchip helpers, these callbacks are automatically assigned.

Disabling and enabling IRQs #

In some (fringe) use cases, a driver may be using a GPIO line as input for IRQs, but occasionally switch that line over to drive output and then back to being an input with interrupts again. This happens on things like CEC (Consumer Electronics Control).

When a GPIO is used as an IRQ signal, then gpiolib also needs to know if the IRQ is enabled or disabled. In order to inform gpiolib about this, the irqchip driver should call:

void gpiochip_disable_irq(struct gpio_chip *chip, unsigned int offset)

This allows drivers to drive the GPIO as an output while the IRQ is disabled. When the IRQ is enabled again, a driver should call:

void gpiochip_enable_irq(struct gpio_chip *chip, unsigned int offset)

When implementing an irqchip inside a GPIO driver, these two functions should typically be called in the .irq_disable() and .irq_enable() callbacks from the irqchip.

When IRQCHIP_IMMUTABLE is not advertised by the irqchip, these callbacks are automatically assigned. This behaviour is deprecated and on its way to be removed from the kernel.

Real-Time compliance for GPIO IRQ chips #

Any provider of irqchips needs to be carefully tailored to support Real-Time preemption. It is desirable that all irqchips in the GPIO subsystem keep this in mind and do the proper testing to assure they are real time-enabled.

So, pay attention on above realtime considerations in the documentation.

The following is a checklist to follow when preparing a driver for real-time compliance:

  • ensure spinlock_t is not used as part irq_chip implementation

  • ensure that sleepable APIs are not used as part irq_chip implementation If sleepable APIs have to be used, these can be done from the .irq_bus_lock() and .irq_bus_unlock() callbacks

  • Chained GPIO irqchips: ensure spinlock_t or any sleepable APIs are not used from the chained IRQ handler

  • Generic chained GPIO irqchips: take care about generic_handle_irq() calls and apply corresponding work-around

  • Chained GPIO irqchips: get rid of the chained IRQ handler and use generic irq handler if possible

  • regmap_mmio: it is possible to disable internal locking in regmap by setting .disable_locking and handling the locking in the GPIO driver

  • Test your driver with the appropriate in-kernel real-time test cases for both level and edge IRQs

  • [1] https://lore.kernel.org/r/1437496011-11486-1-git-send-email-bigeasy@linutronix.de/

  • [2] https://lore.kernel.org/r/1443209283-20781-2-git-send-email-grygorii.strashko@ti.com

  • [3] https://lore.kernel.org/r/1443209283-20781-3-git-send-email-grygorii.strashko@ti.com

Requesting self-owned GPIO pins #

Sometimes it is useful to allow a GPIO chip driver to request its own GPIO descriptors through the gpiolib API. A GPIO driver can use the following functions to request and free descriptors:

struct gpio_desc *gpiochip_request_own_desc(struct gpio_desc *desc,
                                            u16 hwnum,
                                            const char *label,
                                            enum gpiod_flags flags)

void gpiochip_free_own_desc(struct gpio_desc *desc)

Descriptors requested with gpiochip_request_own_desc() must be released with gpiochip_free_own_desc().

These functions must be used with care since they do not affect module use count. Do not use the functions to request gpio descriptors not owned by the calling driver.

Subsystem drivers using GPIO

Peios Kernel / Hardware and drivers / Driver development / GPIO

Note that standard kernel drivers exist for common GPIO tasks and will provide the right in-kernel and userspace APIs/ABIs for the job, and that these drivers can quite easily interconnect with other kernel subsystems using hardware descriptions such as device tree or ACPI:

  • leds-gpio: drivers/leds/leds-gpio.c will handle LEDs connected to GPIO lines, giving you the LED sysfs interface

  • ledtrig-gpio: drivers/leds/trigger/ledtrig-gpio.c will provide a LED trigger, i.e. a LED will turn on/off in response to a GPIO line going high or low (and that LED may in turn use the leds-gpio as per above).

  • gpio-keys: drivers/input/keyboard/gpio_keys.c is used when your GPIO line can generate interrupts in response to a key press. Also supports debounce.

  • gpio-keys-polled: drivers/input/keyboard/gpio_keys_polled.c is used when your GPIO line cannot generate interrupts, so it needs to be periodically polled by a timer.

  • gpio_mouse: drivers/input/mouse/gpio_mouse.c is used to provide a mouse with up to three buttons by simply using GPIOs and no mouse port. You can cut the mouse cable and connect the wires to GPIO lines or solder a mouse connector to the lines for a more permanent solution of this type.

  • gpio-beeper: drivers/input/misc/gpio-beeper.c is used to provide a beep from an external speaker connected to a GPIO line. (If the beep is controlled by off/on, for an actual PWM waveform, see pwm-gpio below.)

  • pwm-gpio: drivers/pwm/pwm-gpio.c is used to toggle a GPIO with a high resolution timer producing a PWM waveform on the GPIO line, as well as Linux high resolution timers can do.

  • extcon-gpio: drivers/extcon/extcon-gpio.c is used when you need to read an external connector status, such as a headset line for an audio driver or an HDMI connector. It will provide a better userspace sysfs interface than GPIO.

  • restart-gpio: drivers/power/reset/gpio-restart.c is used to restart/reboot the system by pulling a GPIO line and will register a restart handler so userspace can issue the right system call to restart the system.

  • poweroff-gpio: drivers/power/reset/gpio-poweroff.c is used to power the system down by pulling a GPIO line and will register a pm_power_off() callback so that userspace can issue the right system call to power down the system.

  • gpio-gate-clock: drivers/clk/clk-gpio.c is used to control a gated clock (off/on) that uses a GPIO, and integrated with the clock subsystem.

  • i2c-gpio: drivers/i2c/busses/i2c-gpio.c is used to drive an I2C bus (two wires, SDA and SCL lines) by hammering (bitbang) two GPIO lines. It will appear as any other I2C bus to the system and makes it possible to connect drivers for the I2C devices on the bus like any other I2C bus driver.

  • spi_gpio: drivers/spi/spi-gpio.c is used to drive an SPI bus (variable number of wires, at least SCK and optionally MISO, MOSI and chip select lines) using GPIO hammering (bitbang). It will appear as any other SPI bus on the system and makes it possible to connect drivers for SPI devices on the bus like any other SPI bus driver. For example any MMC/SD card can then be connected to this SPI by using the mmc_spi host from the MMC/SD card subsystem.

  • w1-gpio: drivers/w1/masters/w1-gpio.c is used to drive a one-wire bus using a GPIO line, integrating with the W1 subsystem and handling devices on the bus like any other W1 device.

  • gpio-fan: drivers/hwmon/gpio-fan.c is used to control a fan for cooling the system, connected to a GPIO line (and optionally a GPIO alarm line), presenting all the right in-kernel and sysfs interfaces to make your system not overheat.

  • gpio-regulator: drivers/regulator/gpio-regulator.c is used to control a regulator providing a certain voltage by pulling a GPIO line, integrating with the regulator subsystem and giving you all the right interfaces.

  • gpio-wdt: drivers/watchdog/gpio_wdt.c is used to provide a watchdog timer that will periodically "ping" a hardware connected to a GPIO line by toggling it from 1-to-0-to-1. If that hardware does not receive its "ping" periodically, it will reset the system.

  • gpio-nand: drivers/mtd/nand/raw/gpio.c is used to connect a NAND flash chip to a set of simple GPIO lines: RDY, NCE, ALE, CLE, NWP. It interacts with the NAND flash MTD subsystem and provides chip access and partition parsing like any other NAND driving hardware.

  • ps2-gpio: drivers/input/serio/ps2-gpio.c is used to drive a PS/2 (IBM) serio bus, data and clock line, by bit banging two GPIO lines. It will appear as any other serio bus to the system and makes it possible to connect drivers for e.g. keyboards and other PS/2 protocol based devices.

  • cec-gpio: drivers/media/platform/cec-gpio/ is used to interact with a CEC Consumer Electronics Control bus using only GPIO. It is used to communicate with devices on the HDMI bus.

  • gpio-charger: drivers/power/supply/gpio-charger.c is used if you need to do battery charging and all you have to go by to check the presence of the AC charger or more complex tasks such as indicating charging status using nothing but GPIO lines, this driver provides that and also a clearly defined way to pass the charging parameters from hardware descriptions such as the device tree.

  • gpio-mux: drivers/mux/gpio.c is used for controlling a multiplexer using n GPIO lines such that you can mux in 2^n different devices by activating different GPIO lines. Often the GPIOs are on a SoC and the devices are some SoC-external entities, such as different components on a PCB that can be selectively enabled.

Apart from this there are special GPIO drivers in subsystems like MMC/SD to read card detect and write protect GPIO lines, and in the TTY serial subsystem to emulate MCTRL (modem control) signals CTS/RTS by using two GPIO lines. The MTD NOR flash has add-ons for extra GPIO lines too, though the address bus is usually connected directly to the flash.

Use those instead of talking directly to the GPIOs from userspace; they integrate with kernel frameworks better than your userspace code could. Needless to say, just using the appropriate kernel drivers will simplify and speed up your embedded hacking in particular by providing ready-made components.

Introduction

Peios Kernel / Hardware and drivers / Driver development / GPIO

GPIO Interfaces #

The documents in this directory give detailed instructions on how to access GPIOs in drivers, and how to write a driver for a device that provides GPIOs itself.

What is a GPIO? #

A "General Purpose Input/Output" (GPIO) is a flexible software-controlled digital signal. They are provided from many kinds of chips, 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 buses. 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 for the other value (notably, "open drain" signaling).

  • 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 input de-glitch/debounce logic, sometimes with software controls.

  • 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 write-protect status, driving a LED, configuring a transceiver, bit-banging a serial bus, poking a hardware watchdog, sensing a switch, and so on.

Common GPIO Properties #

These properties are met through all the other documents of the GPIO interface and it is useful to understand them, especially if you need to define GPIO mappings.

Active-High and Active-Low #

It is natural to assume that a GPIO is "active" when its output signal is 1 ("high"), and inactive when it is 0 ("low"). However in practice the signal of a GPIO may be inverted before is reaches its destination, or a device could decide to have different conventions about what "active" means. Such decisions should be transparent to device drivers, therefore it is possible to define a GPIO as being either active-high ("1" means "active", the default) or active-low ("0" means "active") so that drivers only need to worry about the logical signal and not about what happens at the line level.

Open Drain and Open Source #

Sometimes shared signals need to use "open drain" (where only the low signal level is actually driven), or "open source" (where only the high signal level is driven) signaling. That term applies to CMOS transistors; "open collector" is used for TTL. A pullup or pulldown resistor causes the high or low 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 and open source 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: gpiod_direction_output(gpio, 0) ... this drives the signal and overrides the pullup.

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

The same logic can be applied to emulate open source signaling, by driving the high signal and configuring the GPIO as input for low. This open drain/open source emulation can be handled transparently by the GPIO framework.

If you are "driving" the signal high but gpiod_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.

Supporting Legacy Boards

Peios Kernel / Hardware and drivers / Driver development / GPIO

Many drivers in the kernel, such as leds-gpio and gpio-keys, are migrating away from using board-specific platform_data to a unified device properties interface. This interface allows drivers to be simpler and more generic, as they can query properties in a standardized way.

On modern systems, these properties are provided via device tree. However, some older platforms have not been converted to device tree and instead rely on board files to describe their hardware configuration. To bridge this gap and allow these legacy boards to work with modern, generic drivers, the kernel provides a mechanism called software nodes.

This document provides a guide on how to convert a legacy board file from using platform_data and gpiod_lookup_table to the modern software node approach for describing GPIO-connected devices.

The Core Idea: Software Nodes #

Software nodes allow board-specific code to construct an in-memory, device-tree-like structure using struct software_node and struct property_entry. This structure can then be associated with a platform device, allowing drivers to use the standard device properties API (e.g., device_property_read_u32(), device_property_read_string()) to query configuration, just as they would on an ACPI or device tree system.

The gpiolib code has support for handling software nodes, so that if GPIO is described properly, as detailed in the section below, then regular gpiolib APIs, such as gpiod_get(), gpiod_get_optional(), and others will work.

Requirements for GPIO Properties #

When using software nodes to describe GPIO connections, the following requirements must be met for the GPIO core to correctly resolve the reference:

  1. The GPIO controller's software node "name" must match the controller's "label". The gpiolib core uses this name to find the corresponding struct gpio_chip at runtime. This software node has to be registered, but need not be attached to the device representing the GPIO controller that is providing the GPIO in question. It may be left as a "free floating" node.

  2. The GPIO property must be a reference. The PROPERTY_ENTRY_GPIO() macro handles this as it is an alias for PROPERTY_ENTRY_REF().

  3. The reference must have exactly two arguments:

    • The first argument is the GPIO offset within the controller.

    • The second argument is the flags for the GPIO line (e.g., GPIO_ACTIVE_HIGH, GPIO_ACTIVE_LOW).

The PROPERTY_ENTRY_GPIO() macro is the preferred way of defining GPIO properties in software nodes.

Conversion Example #

Let's walk through an example of converting a board file that defines a GPIO- connected LED and a button.

Before: Using Platform Data #

A typical legacy board file might look like this:

#include <linux/platform_device.h>
#include <linux/leds.h>
#include <linux/gpio_keys.h>
#include <linux/gpio/machine.h>

#define MYBOARD_GPIO_CONTROLLER "gpio-foo"

/* LED setup */
static const struct gpio_led myboard_leds[] = {
      {
              .name = "myboard:green:status",
              .default_trigger = "heartbeat",
      },
};

static const struct gpio_led_platform_data myboard_leds_pdata = {
      .num_leds = ARRAY_SIZE(myboard_leds),
      .leds = myboard_leds,
};

static struct gpiod_lookup_table myboard_leds_gpios = {
      .dev_id = "leds-gpio",
      .table = {
              GPIO_LOOKUP_IDX(MYBOARD_GPIO_CONTROLLER, 42, NULL, 0, GPIO_ACTIVE_HIGH),
              { },
      },
};

/* Button setup */
static struct gpio_keys_button myboard_buttons[] = {
      {
              .code = KEY_WPS_BUTTON,
              .desc = "WPS Button",
              .active_low = 1,
      },
};

static const struct gpio_keys_platform_data myboard_buttons_pdata = {
      .buttons = myboard_buttons,
      .nbuttons = ARRAY_SIZE(myboard_buttons),
};

static struct gpiod_lookup_table myboard_buttons_gpios = {
      .dev_id = "gpio-keys",
      .table = {
              GPIO_LOOKUP_IDX(MYBOARD_GPIO_CONTROLLER, 15, NULL, 0, GPIO_ACTIVE_LOW),
              { },
      },
};

/* Device registration */
static int __init myboard_init(void)
{
      gpiod_add_lookup_table(&myboard_leds_gpios);
      gpiod_add_lookup_table(&myboard_buttons_gpios);

      platform_device_register_data(NULL, "leds-gpio", -1,
                                    &myboard_leds_pdata, sizeof(myboard_leds_pdata));
      platform_device_register_data(NULL, "gpio-keys", -1,
                                    &myboard_buttons_pdata, sizeof(myboard_buttons_pdata));

      return 0;
}

After: Using Software Nodes #

Here is how the same configuration can be expressed using software nodes.

Step 1: Define the GPIO Controller Node #

First, define a software node that represents the GPIO controller that the LEDs and buttons are connected to. The name of this node must match the name of the driver for the GPIO controller (e.g., "gpio-foo").

#include <linux/property.h>
#include <linux/gpio/property.h>

#define MYBOARD_GPIO_CONTROLLER "gpio-foo"

static const struct software_node myboard_gpio_controller_node = {
      .name = MYBOARD_GPIO_CONTROLLER,
};

Step 2: Define Consumer Device Nodes and Properties #

Next, define the software nodes for the consumer devices (the LEDs and buttons). This involves creating a parent node for each device type and child nodes for each individual LED or button.

/* LED setup */
static const struct software_node myboard_leds_node = {
      .name = "myboard-leds",
};

static const struct property_entry myboard_status_led_props[] = {
      PROPERTY_ENTRY_STRING("label", "myboard:green:status"),
      PROPERTY_ENTRY_STRING("linux,default-trigger", "heartbeat"),
      PROPERTY_ENTRY_GPIO("gpios", &myboard_gpio_controller_node, 42, GPIO_ACTIVE_HIGH),
      { }
};

static const struct software_node myboard_status_led_swnode = {
      .name = "status-led",
      .parent = &myboard_leds_node,
      .properties = myboard_status_led_props,
};

/* Button setup */
static const struct software_node myboard_keys_node = {
      .name = "myboard-keys",
};

static const struct property_entry myboard_wps_button_props[] = {
      PROPERTY_ENTRY_STRING("label", "WPS Button"),
      PROPERTY_ENTRY_U32("linux,code", KEY_WPS_BUTTON),
      PROPERTY_ENTRY_GPIO("gpios", &myboard_gpio_controller_node, 15, GPIO_ACTIVE_LOW),
      { }
};

static const struct software_node myboard_wps_button_swnode = {
      .name = "wps-button",
      .parent = &myboard_keys_node,
      .properties = myboard_wps_button_props,
};

Step 3: Group and Register the Nodes #

For maintainability, it is often beneficial to group all software nodes into a single array and register them with one call.

static const struct software_node * const myboard_swnodes[] = {
      &myboard_gpio_controller_node,
      &myboard_leds_node,
      &myboard_status_led_swnode,
      &myboard_keys_node,
      &myboard_wps_button_swnode,
      NULL
};

static int __init myboard_init(void)
{
      int error;

      error = software_node_register_node_group(myboard_swnodes);
      if (error) {
              pr_err("Failed to register software nodes: %d\n", error);
              return error;
      }

      // ... platform device registration follows
}

Note

When splitting registration of nodes by devices that they represent, it is essential that the software node representing the GPIO controller itself is registered first, before any of the nodes that reference it.

Step 4: Register Platform Devices with Software Nodes #

Finally, register the platform devices and associate them with their respective software nodes using the fwnode field in struct platform_device_info.

static struct platform_device *leds_pdev;
static struct platform_device *keys_pdev;

static int __init myboard_init(void)
{
      struct platform_device_info pdev_info;
      int error;

      error = software_node_register_node_group(myboard_swnodes);
      if (error)
              return error;

      memset(&pdev_info, 0, sizeof(pdev_info));
      pdev_info.name = "leds-gpio";
      pdev_info.id = PLATFORM_DEVID_NONE;
      pdev_info.fwnode = software_node_fwnode(&myboard_leds_node);
      leds_pdev = platform_device_register_full(&pdev_info);
      if (IS_ERR(leds_pdev)) {
              error = PTR_ERR(leds_pdev);
              goto err_unregister_nodes;
      }

      memset(&pdev_info, 0, sizeof(pdev_info));
      pdev_info.name = "gpio-keys";
      pdev_info.id = PLATFORM_DEVID_NONE;
      pdev_info.fwnode = software_node_fwnode(&myboard_keys_node);
      keys_pdev = platform_device_register_full(&pdev_info);
      if (IS_ERR(keys_pdev)) {
              error = PTR_ERR(keys_pdev);
              platform_device_unregister(leds_pdev);
              goto err_unregister_nodes;
      }

      return 0;

err_unregister_nodes:
      software_node_unregister_node_group(myboard_swnodes);
      return error;
}

static void __exit myboard_exit(void)
{
      platform_device_unregister(keys_pdev);
      platform_device_unregister(leds_pdev);
      software_node_unregister_node_group(myboard_swnodes);
}

With these changes, the generic leds-gpio and gpio-keys drivers will be able to probe successfully and get their configuration from the properties defined in the software nodes, removing the need for board-specific platform data.

PCA953x I²C GPIO expander compatibility list

Peios Kernel / Hardware and drivers / Driver development / GPIO

Author: Levente Révész <levente.revesz@eilabs.com>

I went through all the datasheets and created this note listing chip functions and register layouts.

Overview of chips #

Chips with the basic 4 registers #

These chips have 4 register banks: input, output, invert and direction. Each of these banks contains (lines/8) registers, one for each GPIO port.

Banks offset is always a power of 2:

  • 4 lines -> bank offset is 1

  • 8 lines -> bank offset is 1

  • 16 lines -> bank offset is 2

  • 24 lines -> bank offset is 4

  • 32 lines -> bank offset is 4

  • 40 lines -> bank offset is 8

For example, register layout of GPIO expander with 24 lines:

addr

function

bank

00

input port0

bank 0

01

input port1

02

input port2

03

n/a

04

output port0

bank 1

05

output port1

06

output port2

07

n/a

08

invert port0

bank 2

09

invert port1

0A

invert port2

0B

n/a

0C

direction port0

bank 3

0D

direction port1

0E

direction port2

0F

n/a

Note

This is followed by all supported chips, except by pcal6534.

The table below shows the offsets for each of the compatible chips:

compatible

lines

interrupt

input

output

invert

direction

pca9536

4

no

00

01

02

03

pca9537

4

yes

00

01

02

03

pca6408

8

yes

00

01

02

03

tca6408

8

yes

00

01

02

03

pca9534

8

yes

00

01

02

03

pca9538

8

yes

00

01

02

03

pca9554

8

yes

00

01

02

03

tca9554

8

yes

00

01

02

03

pca9556

8

no

00

01

02

03

pca9557

8

no

00

01

02

03

pca6107

8

yes

00

01

02

03

pca6416

16

yes

00

02

04

06

tca6416

16

yes

00

02

04

06

pca9535

16

yes

00

02

04

06

pca9539

16

yes

00

02

04

06

tca9539

16

yes

00

02

04

06

pca9555

16

yes

00

02

04

06

max7318

16

yes

00

02

04

06

tca6424

24

yes

00

04

08

0C

Chips with additional timeout_en register #

These Maxim chips have a bus timeout function which can be enabled in the timeout_en register. This is present in only two chips. Defaults to timeout disabled.

compatible

lines

interrupt

input

output

invert

direction

timeout_en

max7310

8

no

00

01

02

03

04

max7312

16

yes

00

02

04

06

08

Chips with additional int_mask register #

These chips have an interrupt mask register in addition to the 4 basic registers. The interrupt masks default to all interrupts disabled. To use interrupts with these chips, the driver has to set the int_mask register.

compatible

lines

interrupt

input

output

invert

direction

int_mask

pca9505

40

yes

00

08

10

18

20

pca9506

40

yes

00

08

10

18

20

Chips with additional int_mask and out_conf registers #

This chip has an interrupt mask register, and an output port configuration register, which can select between push-pull and open-drain modes. Each bit controls two lines. Both of these registers are present in PCAL chips as well, albeit the out_conf works differently.

compatible

lines

interrupt

input

output

invert

direction

int_mask

out_conf

pca9698

40

yes

00

08

10

18

20

28

pca9698 also has a "master output" register for setting all outputs per port to the same value simultaneously, and a chip specific mode register for various additional chip settings.

compatible

master_output

mode

pca9698

29

2A

Chips with LED blink and intensity control #

These Maxim chips have no invert register.

They have two sets of output registers (output0 and output1). An internal timer alternates the effective output between the values set in these registers, if blink mode is enabled in the blink register. The master_intensity register and the intensity registers together define the PWM intensity value for each pair of outputs.

These chips can be used as simple GPIO expanders if the driver handles the input, output0 and direction registers.

compatible

lines

interrupt

input

output0

direction

output1

master_intensity

blink

intensity

max7315

8

yes

00

01

03

09

0E

0F

10

max7313

16

yes

00

02

06

0A

0E

0F

10

Basic PCAL chips #

compatible

lines

interrupt

input

output

invert

direction

pcal6408

8

yes

00

01

02

03

pcal9554b

8

yes

00

01

02

03

pcal6416

16

yes

00

02

04

06

pcal9535

16

yes

00

02

04

06

pcal9555a

16

yes

00

02

04

06

tcal6408

8

yes

00

01

02

03

tcal6416

16

yes

00

02

04

06

These chips have several additional features:

  1. output drive strength setting (out_strength)

  2. input latch (in_latch)

  3. pull-up/pull-down (pull_in, pull_sel)

  4. push-pull/open-drain outputs (out_conf)

  5. interrupt mask and interrupt status (int_mask, int_status)

compatible

out_strength

in_latch

pull_en

pull_sel

int_mask

int_status

out_conf

pcal6408

40

42

43

44

45

46

4F

pcal9554b

40

42

43

44

45

46

4F

pcal6416

40

44

46

48

4A

4C

4F

pcal9535

40

44

46

48

4A

4C

4F

pcal9555a

40

44

46

48

4A

4C

4F

tcal6408

40

42

43

44

45

46

4F

tcal6416

40

44

46

48

4A

4C

4F

Currently the driver has support for the input latch, pull-up/pull-down and uses int_mask and int_status for interrupts.

PCAL chips with extended interrupt and output configuration functions #

compatible

lines

interrupt

input

output

invert

direction

pcal6524

24

yes

00

04

08

0C

pcal6534

34

yes

00

05

0A

0F

These chips have the full PCAL register set, plus the following functions:

  1. interrupt event selection: level, rising, falling, any edge

  2. clear interrupt status per line

  3. read input without clearing interrupt status

  4. individual output config (push-pull/open-drain) per output line

  5. debounce inputs

compatible

out_strength

in_latch

pull_en

pull_sel

int_mask

int_status

out_conf

pcal6524

40

48

4C

50

54

58

5C

pcal6534

30

3A

3F

44

49

4E

53

compatible

int_edge

int_clear

input_status

indiv_out_conf

debounce

debounce_count

pcal6524

60

68

6C

70

74

76

pcal6534

54

5E

63

68

6D

6F

As can be seen in the table above, pcal6534 does not follow the usual bank spacing rule. Its banks are closely packed instead.

PCA957X chips with a completely different register layout #

These chips have the basic 4 registers, but at unusual addresses.

Additionally, they have:

  1. pull-up/pull-down (pull_sel)

  2. a global pull enable, defaults to disabled (config)

  3. interrupt mask, interrupt status (int_mask, int_status)

compatible

lines

interrupt

input

invert

config

pull_sel

direction

output

int_mask

int_status

pca9574

8

yes

00

01

02

03

04

05

06

07

pca9575

16

yes

00

02

04

06

08

0A

0C

0E

Currently the driver supports none of the advanced features.

XRA1202 #

Basic 4 registers, plus advanced features:

  1. interrupt mask, defaults to interrupts disabled

  2. interrupt status

  3. interrupt event selection, level, rising, falling, any edge (int_mask, rising_mask, falling_mask)

  4. pull-up (no pull-down)

  5. tri-state

  6. debounce

compatible

lines

interrupt

input

output

invert

direction

pullup_en

xra1202

8

yes

00

01

02

03

04

compatible

int_mask

tristate

int_status

rising_mask

falling_mask

debounce

xra1202

05

06

07

08

09

0A

Overview of functions #

This section lists chip functions that are supported by the driver already, or are at least common in multiple chips.

Input, Output, Invert, Direction #

The basic 4 GPIO functions are present in all but one chip category, i.e. Chips with LED blink and intensity control are missing the invert register.

3 different layouts are used for these registers:

    • banks 0, 1, 2, 3 with bank offsets of 2^n

      • all other chips
    • banks 0, 1, 2, 3 with closely packed banks

      • pcal6534
    • banks 0, 5, 1, 4 with bank offsets of 2^n

      • pca9574

      • pca9575

Interrupts #

Only an interrupt mask register #

The same layout is used for all of these:

    • bank 5 with bank offsets of 2^n

      • pca9505

      • pca9506

      • pca9698

Interrupt mask and interrupt status registers #

These work the same way in all of the chips: mask and status have one bit per line, 1 in the mask means interrupt enabled.

Layouts:

    • base offset 0x40, bank 5 and bank 6, bank offsets of 2^n

      • pcal6408

      • pcal6416

      • pcal9535

      • pcal9554b

      • pcal9555a

      • pcal6524

      • tcal6408

      • tcal6416

    • base offset 0x30, bank 5 and 6, closely packed banks

      • pcal6534
    • bank 6 and 7, bank offsets of 2^n

      • pca9574

      • pca9575

    • bank 5 and 7, bank offsets of 2^n

      • xra1202

Interrupt on specific edges #

PCAL chips with extended interrupt and output configuration functions have an int_edge register. This contains 2 bits per line, one of 4 events can be selected for each line:

0: level, 1: rising edge, 2: falling edge, 3: any edge

Layouts:

  1. base offset 0x40, bank 7, bank offsets of 2^n

    • pcal6524
  2. base offset 0x30, bank 7 + offset 0x01, closely packed banks (out_conf is 1 byte, not (lines/8) bytes, hence the 0x01 offset)

    • pcal6534

XRA1202 chips have a different mechanism for the same thing: they have a rising mask and a falling mask, with one bit per line.

Layout:

  1. bank 5, bank offsets of 2^n

Input latch #

Only Basic PCAL chips and PCAL chips with extended interrupt and output configuration functions have this function. When the latch is enabled, the interrupt is not cleared until the input port is read. When the latch is disabled, the interrupt is cleared even if the input register is not read, if the input pin returns to the logic value it had before generating the interrupt. Defaults to latch disabled.

Currently the driver enables the latch for each line with interrupt enabled.

An interrupt status register records which pins triggered an interrupt. However, the status register and the input port register must be read separately; there is no atomic mechanism to read both simultaneously, so races are possible. Refer to the chapter Interrupt source detection to understand the implications of this and how the driver still makes use of the latching feature.

    • base offset 0x40, bank 2, bank offsets of 2^n

      • pcal6408

      • pcal6416

      • pcal9535

      • pcal9554b

      • pcal9555a

      • pcal6524

      • tcal6408

      • tcal6416

    • base offset 0x30, bank 2, closely packed banks

      • pcal6534

Pull-up and pull-down #

Basic PCAL chips and PCAL chips with extended interrupt and output configuration functions use the same mechanism: their pull_en register enables the pull-up or pull-down function, and their pull_sel register chooses the direction. They all use one bit per line.

0: pull-down, 1: pull-up

Layouts:

    • base offset 0x40, bank 3 (en) and 4 (sel), bank offsets of 2^n

      • pcal6408

      • pcal6416

      • pcal9535

      • pcal9554b

      • pcal9555a

      • pcal6524

    • base offset 0x30, bank 3 (en) and 4 (sel), closely packed banks

      • pcal6534

PCA957X chips with a completely different register layout have a pull_sel register with one bit per line, and a global pull_en bit in their config register.

Layout:

    • bank 2 (config), bank 3 (sel), bank offsets of 2^n

      • pca9574

      • pca9575

XRA1202 chips can only pull-up. They have a pullup_en register.

Layout:

    • bank 4, bank offsets of 2^n

      • xra1202

Push-pull and open-drain #

Chips with additional int_mask and out_conf registers have this function, but only for select IO ports. Register has 1 bit per 2 lines. In pca9698, only port0 and port1 have this function.

0: open-drain, 1: push-pull

Layout:

    • base offset 5*bankoffset

      • pca9698

Basic PCAL chips have 1 bit per port in one single out_conf register. Only whole ports can be configured.

0: push-pull, 1: open-drain

Layout:

    • base offset 0x4F

      • pcal6408

      • pcal6416

      • pcal9535

      • pcal9554b

      • pcal9555a

      • tcal6408

      • tcal6416

PCAL chips with extended interrupt and output configuration functions can set this for each line individually. They have the same per-port out_conf register as Basic PCAL chips, but they also have an indiv_out_conf register with one bit per line, which inverts the effect of the port-wise setting.

0: push-pull, 1: open-drain

Layouts:

  1. base offset 0x40 + 7*bankoffset (out_conf), base offset 0x60, bank 4 (indiv_out_conf) with bank offset of 2^n

    • pcal6524
  2. base offset 0x30 + 7*banksize (out_conf), base offset 0x54, bank 4 (indiv_out_conf), closely packed banks

    • pcal6534

This function is currently not supported by the driver.

Output drive strength #

Only PCAL chips have this function. 2 bits per line.

bits

drive strength

00

0.25x

01

0.50x

10

0.75x

11

1.00x

    • base offset 0x40, bank 0 and 1, bank offsets of 2^n

      • pcal6408

      • pcal6416

      • pcal9535

      • pcal9554b

      • pcal9555a

      • pcal6524

      • tcal6408

      • tcal6416

    • base offset 0x30, bank 0 and 1, closely packed banks

      • pcal6534

Currently not supported by the driver.

Interrupt source detection #

When triggered by the GPIO expander's interrupt, the driver determines which IRQs are pending by reading the input port register.

To be able to filter on specific interrupt events for all compatible devices, the driver keeps track of the previous input state of the lines, and emits an IRQ only for the correct edge or level. This system works irrespective of the number of enabled interrupts. Events will not be missed even if they occur between the GPIO expander's interrupt and the actual I2C read. Edges could of course be missed if the related signal level changes back to the value previously saved by the driver before the I2C read. PCAL variants offer input latching for that reason.

PCAL input latching #

The PCAL variants have an input latch and the driver enables this for all interrupt-enabled lines. The interrupt is then only cleared when the input port is read out. These variants provide an interrupt status register that records which pins triggered an interrupt, but the status and input registers cannot be read atomically. If another interrupt occurs on a different line after the status register has been read but before the input port register is sampled, that event will not be reflected in the earlier status snapshot, so relying solely on the interrupt status register is insufficient.

Thus, the PCAL variants also have to use the existing level-change logic.

For short pulses, the first edge is captured when the input register is read, but if the signal returns to its previous level before this read, the second edge is not observed. As a result, successive pulses can produce identical input values at read time and no level change is detected, causing interrupts to be missed. Below timing diagram shows this situation where the top signal is the input pin level and the bottom signal indicates the latched value:

─────┐     ┌──*───────────────┐     ┌──*─────────────────┐     ┌──*───
     │     │  .               │     │  .                 │     │  .
     │     │  │               │     │  │                 │     │  │
     └──*──┘  │               └──*──┘  │                 └──*──┘  │
Input   │     │                  │     │                    │     │
        ▼     │                  ▼     │                    ▼     │
       IRQ    │                 IRQ    │                   IRQ    │
              .                        .                          .
─────┐        .┌──────────────┐        .┌────────────────┐        .┌──
     │         │              │         │                │         │
     │         │              │         │                │         │
     └────────*┘              └────────*┘                └────────*┘
Latched       │                        │                          │
              ▼                        ▼                          ▼
            READ 0                   READ 0                     READ 0
                                   NO CHANGE                  NO CHANGE

To deal with this, events indicated by the interrupt status register are merged with events detected through the existing level-change logic. As a result:

  • short pulses, whose second edges are invisible, are detected via the interrupt status register, and

  • interrupts that occur between the status and input reads are still caught by the generic level-change logic.

Note that this is still best-effort: the status and input registers are read separately, and short pulses on other lines may occur in between those reads. Such pulses can still be latched as an interrupt without leaving an observable level change at read time, and may not be attributable to a specific edge. This does not reduce detection compared to the generic path, but reflects inherent atomicity limitations.

Datasheets #

  • MAX7310: https://datasheets.maximintegrated.com/en/ds/MAX7310.pdf

  • MAX7312: https://datasheets.maximintegrated.com/en/ds/MAX7312.pdf

  • MAX7313: https://datasheets.maximintegrated.com/en/ds/MAX7313.pdf

  • MAX7315: https://datasheets.maximintegrated.com/en/ds/MAX7315.pdf

  • MAX7318: https://datasheets.maximintegrated.com/en/ds/MAX7318.pdf

  • PCA6107: https://pdf1.alldatasheet.com/datasheet-pdf/view/161780/TI/PCA6107.html

  • PCA6408A: https://www.nxp.com/docs/en/data-sheet/PCA6408A.pdf

  • PCA6416A: https://www.nxp.com/docs/en/data-sheet/PCA6416A.pdf

  • PCA9505: https://www.nxp.com/docs/en/data-sheet/PCA9505_9506.pdf

  • PCA9505: https://www.nxp.com/docs/en/data-sheet/PCA9505_9506.pdf

  • PCA9534: https://www.nxp.com/docs/en/data-sheet/PCA9534.pdf

  • PCA9535: https://www.nxp.com/docs/en/data-sheet/PCA9535_PCA9535C.pdf

  • PCA9536: https://www.nxp.com/docs/en/data-sheet/PCA9536.pdf

  • PCA9537: https://www.nxp.com/docs/en/data-sheet/PCA9537.pdf

  • PCA9538: https://www.nxp.com/docs/en/data-sheet/PCA9538.pdf

  • PCA9539: https://www.nxp.com/docs/en/data-sheet/PCA9539_PCA9539R.pdf

  • PCA9554: https://www.nxp.com/docs/en/data-sheet/PCA9554_9554A.pdf

  • PCA9555: https://www.nxp.com/docs/en/data-sheet/PCA9555.pdf

  • PCA9556: https://www.nxp.com/docs/en/data-sheet/PCA9556.pdf

  • PCA9557: https://www.nxp.com/docs/en/data-sheet/PCA9557.pdf

  • PCA9574: https://www.nxp.com/docs/en/data-sheet/PCA9574.pdf

  • PCA9575: https://www.nxp.com/docs/en/data-sheet/PCA9575.pdf

  • PCA9698: https://www.nxp.com/docs/en/data-sheet/PCA9698.pdf

  • PCAL6408A: https://www.nxp.com/docs/en/data-sheet/PCAL6408A.pdf

  • PCAL6416A: https://www.nxp.com/docs/en/data-sheet/PCAL6416A.pdf

  • PCAL6524: https://www.nxp.com/docs/en/data-sheet/PCAL6524.pdf

  • PCAL6534: https://www.nxp.com/docs/en/data-sheet/PCAL6534.pdf

  • PCAL9535A: https://www.nxp.com/docs/en/data-sheet/PCAL9535A.pdf

  • PCAL9554B: https://www.nxp.com/docs/en/data-sheet/PCAL9554B_PCAL9554C.pdf

  • PCAL9555A: https://www.nxp.com/docs/en/data-sheet/PCAL9555A.pdf

  • TCA6408A: https://www.ti.com/lit/gpn/tca6408a

  • TCA6416: https://www.ti.com/lit/gpn/tca6416

  • TCA6424: https://www.ti.com/lit/gpn/tca6424

  • TCA9539: https://www.ti.com/lit/gpn/tca9539

  • TCA9554: https://www.ti.com/lit/gpn/tca9554

  • XRA1202: https://assets.maxlinear.com/web/documents/xra1202_1202p_101_042213.pdf

Using GPIO Lines in Linux

Peios Kernel / Hardware and drivers / Driver development / GPIO

The Linux kernel exists to abstract and present hardware to users. GPIO lines as such are normally not user facing abstractions. The most obvious, natural and preferred way to use GPIO lines is to let kernel hardware drivers deal with them.

For examples of already existing generic drivers that will also be good examples for any other kernel drivers you want to author, refer to Documentation/driver-api/gpio/drivers-on-gpio.rst

For any kind of mass produced system you want to support, such as servers, laptops, phones, tablets, routers, and any consumer or office or business goods using appropriate kernel drivers is paramount. Submit your code for inclusion in the upstream Linux kernel when you feel it is mature enough and you will get help to refine it, see Documentation/process/submitting-patches.rst.

In Linux GPIO lines also have a userspace ABI.

The userspace ABI is intended for one-off deployments. Examples are prototypes, factory lines, maker community projects, workshop specimen, production tools, industrial automation, PLC-type use cases, door controllers, in short a piece of specialized equipment that is not produced by the numbers, requiring operators to have a deep knowledge of the equipment and knows about the software-hardware interface to be set up. They should not have a natural fit to any existing kernel subsystem and not be a good fit for an operating system, because of not being reusable or abstract enough, or involving a lot of non computer hardware related policy.

Applications that have a good reason to use the industrial I/O (IIO) subsystem from userspace will likely be a good fit for using GPIO lines from userspace as well.

Do not under any circumstances abuse the GPIO userspace ABI to cut corners in any product development projects. If you use it for prototyping, then do not productify the prototype: rewrite it using proper kernel drivers. Do not under any circumstances deploy any uniform products using GPIO from userspace.

The userspace ABI is a character device for each GPIO hardware unit (GPIO chip). These devices will appear on the system as /dev/gpiochip0 thru /dev/gpiochipN. Examples of how to directly use the userspace ABI can be found in the kernel tree tools/gpio subdirectory.

For structured and managed applications, we recommend that you make use of the libgpiod library. This provides helper abstractions, command line utilities and arbitration for multiple simultaneous consumers on the same GPIO chip.

Peios Learn — documentation for Peios software.

Built with Trail.