code:
=====================
GPIO Driver Interface
=====================

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(), 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 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:

.. csv-table::
    :header: 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:

.. code-block:: c

  /* 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:

.. code-block:: c

  /* 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:

.. code-block:: c

  /* 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] http://www.spinics.net/lists/linux-omap/msg120425.html
* [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.


code:
============================
Subsystem drivers using 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.

- 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.

repo_name: angery/linux


code:
===================================
General Purpose Input/Output (GPIO)
===================================

Contents:

.. toctree::
   :maxdepth: 2

   intro
   using-gpio
   driver
   consumer
   board
   drivers-on-gpio
   legacy
   bt8xxgpio

Core
====

.. kernel-doc:: include/linux/gpio/driver.h
   :internal:

.. kernel-doc:: drivers/gpio/gpiolib.c
   :export:

ACPI support
============

.. kernel-doc:: drivers/gpio/gpiolib-acpi.c
   :export:

Device tree support
===================

.. kernel-doc:: drivers/gpio/gpiolib-of.c
   :export:

Device-managed API
==================

.. kernel-doc:: drivers/gpio/gpiolib-devres.c
   :export:

sysfs helpers
=============

.. kernel-doc:: drivers/gpio/gpiolib-sysfs.c
   :export:


code:
============
Introduction
============

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.

Due to the history of GPIO interfaces in the kernel, there are two different
ways to obtain and use GPIOs:

  - The descriptor-based interface is the preferred way to manipulate GPIOs,
    and is described by all the files in this directory excepted legacy.rst.
  - The legacy integer-based interface which is considered deprecated (but still
    usable for compatibility reasons) is documented in legacy.rst.

The remainder of this document applies to the new descriptor-based interface.
legacy.rst contains the same information applied to the legacy
integer-based interface.

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.


code:
======================
Legacy GPIO Interfaces
======================

This provides an overview of GPIO access conventions on Linux.

These calls use the gpio_* naming prefix.  No other calls should use that
prefix, or the related __gpio_* prefix.

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

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

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

  - Output values are writable (high=1, low=0).  Some chips also have
    options about how that value is driven, so that for example only one
    value might be driven ... supporting "wire-OR" and similar schemes
    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 writeprotect status, driving
a LED, configuring a transceiver, bitbanging a serial bus, poking a hardware
watchdog, sensing a switch, and so on.

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

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

That said, if the convention is supported on their platform, drivers should
use it when possible.  Platforms must select GPIOLIB if GPIO functionality
is strictly required.  Drivers that can't work without
standard GPIO calls should have Kconfig entries which depend on GPIOLIB.  The
GPIO calls are available, either as "real code" or as optimized-away stubs,
when drivers use the include file:

	#include <linux/gpio.h>

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

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

Identifying GPIOs
-----------------
GPIOs are identified by unsigned integers in the range 0..MAX_INT.  That
reserves "negative" numbers for other purposes like marking signals as
"not available on this board", or indicating faults.  Code that doesn't
touch the underlying hardware treats these integers as opaque cookies.

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

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

If you want to initialize a structure with an invalid GPIO number, use
some negative number (perhaps "-EINVAL"); that will never be valid.  To
test if such number from such a structure could reference a GPIO, you
may use this predicate:

	int gpio_is_valid(int number);

A number that's not valid will be rejected by calls which may request
or free GPIOs (see below).  Other numbers may also be rejected; for
example, a number might be valid but temporarily unused on a given board.

Whether a platform supports multiple GPIO controllers is a platform-specific
implementation issue, as are whether that support can leave "holes" in the space
of GPIO numbers, and whether new controllers can be added at runtime.  Such issues
can affect things including whether adjacent GPIO numbers are both valid.

Using GPIOs
-----------
The first thing a system should do with a GPIO is allocate it, using
the gpio_request() call; see later.

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

	/* set as input or output, returning 0 or negative errno */
	int gpio_direction_input(unsigned gpio);
	int gpio_direction_output(unsigned gpio, int value);

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

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

For compatibility with legacy interfaces to GPIOs, setting the direction
of a GPIO implicitly requests that GPIO (see below) if it has not been
requested already.  That compatibility is being removed from the optional
gpiolib framework.

Setting the direction can fail if the GPIO number is invalid, or when
that particular GPIO can't be used in that mode.  It's generally a bad
idea to rely on boot firmware to have set the direction correctly, since
it probably wasn't validated to do more than boot Linux.  (Similarly,
that board setup code probably needs to multiplex that pin as a GPIO,
and configure pullups/pulldowns appropriately.)

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

Use the following calls to access such GPIOs,
for which gpio_cansleep() will always return false (see below)::

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

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

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

The get/set calls have no error returns because "invalid GPIO" should have
been reported earlier from gpio_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.

Platform-specific implementations are encouraged to optimize the two
calls to access the GPIO value in cases where the GPIO number (and for
output, value) are constant.  It's normal for them to need only a couple
of instructions in such cases (reading or writing a hardware register),
and not to need spinlocks.  Such optimized calls can make bitbanging
applications a lot more efficient (in both space and time) than spending
dozens of instructions on subroutine calls.

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

Platforms that support this type of GPIO distinguish them from other GPIOs
by returning nonzero from this call (which requires a valid GPIO number,
which should have been previously allocated with gpio_request)::

	int gpio_cansleep(unsigned gpio);

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

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

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

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.

**IN ADDITION** calls to setup and configure such GPIOs must be made
from contexts which may sleep, since they may need to access the GPIO
controller chip too  (These setup calls are usually made from board
setup or driver probe/teardown code, so this is an easy constraint.)::

                gpio_direction_input()
                gpio_direction_output()
                gpio_request()

        ## 	gpio_request_one()
        ##	gpio_request_array()
        ## 	gpio_free_array()

                gpio_free()
                gpio_set_debounce()

Claiming and Releasing GPIOs
----------------------------
To help catch system configuration errors, two calls are defined::

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

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

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

These calls serve two basic purposes.  One is marking the signals which
are actually in use as GPIOs, for better diagnostics; systems may have
several hundred potential GPIOs, but often only a dozen are used on any
given board.  Another is to catch conflicts, identifying errors when
(a) two or more drivers wrongly think they have exclusive use of that
signal, or (b) something wrongly believes it's safe to remove drivers
needed to manage a signal that's in active use.  That is, requesting a
GPIO can serve as a kind of lock.

Some platforms may also use knowledge about what GPIOs are active for
power management, such as by powering down unused chip sectors and, more
easily, gating off unused clocks.

For GPIOs that use pins known to the pinctrl subsystem, that subsystem should
be informed of their use; a gpiolib driver's .request() operation may call
pinctrl_gpio_request(), and a gpiolib driver's .free() operation may call
pinctrl_gpio_free(). The pinctrl subsystem allows a pinctrl_gpio_request()
to succeed concurrently with a pin or pingroup being "owned" by a device for
pin multiplexing.

Any programming of pin multiplexing hardware that is needed to route the
GPIO signal to the appropriate pin should occur within a GPIO driver's
.direction_input() or .direction_output() operations, and occur after any
setup of an output GPIO's value. This allows a glitch-free migration from a
pin's special function to GPIO. This is sometimes required when using a GPIO
to implement a workaround on signals typically driven by a non-GPIO HW block.

Some platforms allow some or all GPIO signals to be routed to different pins.
Similarly, other aspects of the GPIO or pin may need to be configured, such as
pullup/pulldown. Platform software should arrange that any such details are
configured prior to gpio_request() being called for those GPIOs, e.g. using
the pinctrl subsystem's mapping table, so that GPIO users need not be aware
of these details.

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

Considering in most cases GPIOs are actually configured right after they
are claimed, three additional calls are defined::

	/* request a single GPIO, with initial configuration specified by
	 * 'flags', identical to gpio_request() wrt other arguments and
	 * return value
	 */
	int gpio_request_one(unsigned gpio, unsigned long flags, const char *label);

	/* request multiple GPIOs in a single call
	 */
	int gpio_request_array(struct gpio *array, size_t num);

	/* release multiple GPIOs in a single call
	 */
	void gpio_free_array(struct gpio *array, size_t num);

where 'flags' is currently defined to specify the following properties:

	* GPIOF_DIR_IN		- to configure direction as input
	* GPIOF_DIR_OUT		- to configure direction as output

	* GPIOF_INIT_LOW	- as output, set initial level to LOW
	* GPIOF_INIT_HIGH	- as output, set initial level to HIGH
	* GPIOF_OPEN_DRAIN	- gpio pin is open drain type.
	* GPIOF_OPEN_SOURCE	- gpio pin is open source type.

	* GPIOF_EXPORT_DIR_FIXED	- export gpio to sysfs, keep direction
	* GPIOF_EXPORT_DIR_CHANGEABLE	- also export, allow changing direction

since GPIOF_INIT_* are only valid when configured as output, so group valid
combinations as:

	* GPIOF_IN		- configure as input
	* GPIOF_OUT_INIT_LOW	- configured as output, initial level LOW
	* GPIOF_OUT_INIT_HIGH	- configured as output, initial level HIGH

When setting the flag as GPIOF_OPEN_DRAIN then it will assume that pins is
open drain type. Such pins will not be driven to 1 in output mode. It is
require to connect pull-up on such pins. By enabling this flag, gpio lib will
make the direction to input when it is asked to set value of 1 in output mode
to make the pin HIGH. The pin is make to LOW by driving value 0 in output mode.

When setting the flag as GPIOF_OPEN_SOURCE then it will assume that pins is
open source type. Such pins will not be driven to 0 in output mode. It is
require to connect pull-down on such pin. By enabling this flag, gpio lib will
make the direction to input when it is asked to set value of 0 in output mode
to make the pin LOW. The pin is make to HIGH by driving value 1 in output mode.

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

Further more, to ease the claim/release of multiple GPIOs, 'struct gpio' is
introduced to encapsulate all three fields as::

	struct gpio {
		unsigned	gpio;
		unsigned long	flags;
		const char	*label;
	};

A typical example of usage::

	static struct gpio leds_gpios[] = {
		{ 32, GPIOF_OUT_INIT_HIGH, "Power LED" }, /* default to ON */
		{ 33, GPIOF_OUT_INIT_LOW,  "Green LED" }, /* default to OFF */
		{ 34, GPIOF_OUT_INIT_LOW,  "Red LED"   }, /* default to OFF */
		{ 35, GPIOF_OUT_INIT_LOW,  "Blue LED"  }, /* default to OFF */
		{ ... },
	};

	err = gpio_request_one(31, GPIOF_IN, "Reset Button");
	if (err)
		...

	err = gpio_request_array(leds_gpios, ARRAY_SIZE(leds_gpios));
	if (err)
		...

	gpio_free_array(leds_gpios, ARRAY_SIZE(leds_gpios));

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

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

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

Those return either the corresponding number in the other namespace, or
else a negative errno code if the mapping can't be done.  (For example,
some GPIOs can't be used as IRQs.)  It is an unchecked error to use a GPIO
number that wasn't set up as an input using gpio_direction_input(), or
to use an IRQ number that didn't originally come from gpio_to_irq().

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

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

Non-error values returned from irq_to_gpio() would most commonly be used
with gpio_get_value(), for example to initialize or update driver state
when the IRQ is edge-triggered.  Note that some platforms don't support
this reverse mapping, so you should avoid using it.

Emulating Open Drain Signals
----------------------------
Sometimes shared signals need to use "open drain" signaling, where only the
low signal level is actually driven.  (That term applies to CMOS transistors;
"open collector" is used for TTL.)  A pullup resistor causes the high signal
level.  This is sometimes called a "wire-AND"; or more practically, from the
negative logic (low=true) perspective this is a "wire-OR".

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

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

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

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

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

GPIO controllers and the pinctrl subsystem
------------------------------------------

A GPIO controller on a SOC might be tightly coupled with the pinctrl
subsystem, in the sense that the pins can be used by other functions
together with an optional gpio feature. We have already covered the
case where e.g. a GPIO controller need to reserve a pin or set the
direction of a pin by calling any of::

  pinctrl_gpio_request()
  pinctrl_gpio_free()
  pinctrl_gpio_direction_input()
  pinctrl_gpio_direction_output()

But how does the pin control subsystem cross-correlate the GPIO
numbers (which are a global business) to a certain pin on a certain
pin controller?

This is done by registering "ranges" of pins, which are essentially
cross-reference tables. These are described in
Documentation/driver-api/pin-control.rst

While the pin allocation is totally managed by the pinctrl subsystem,
gpio (under gpiolib) is still maintained by gpio drivers. It may happen
that different pin ranges in a SoC is managed by different gpio drivers.

This makes it logical to let gpio drivers announce their pin ranges to
the pin ctrl subsystem before it will call 'pinctrl_gpio_request' in order
to request the corresponding pin to be prepared by the pinctrl subsystem
before any gpio usage.

For this, the gpio controller can register its pin range with pinctrl
subsystem. There are two ways of doing it currently: with or without DT.

For with DT support refer to Documentation/devicetree/bindings/gpio/gpio.txt.

For non-DT support, user can call gpiochip_add_pin_range() with appropriate
parameters to register a range of gpio pins with a pinctrl driver. For this
exact name string of pinctrl device has to be passed as one of the
argument to this routine.

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

Related to multiplexing is configuration and enabling of the pullups or
pulldowns integrated on some platforms.  Not all platforms support them,
or support them in the same way; and any given board might use external
pullups (or pulldowns) so that the on-chip ones should not be used.
(When a circuit needs 5 kOhm, on-chip 100 kOhm resistors won't do.)
Likewise drive strength (2 mA vs 20 mA) and voltage (1.8V vs 3.3V) is a
platform-specific issue, as are models like (not) having a one-to-one
correspondence between configurable pins and GPIOs.

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

Dynamic definition of GPIOs is not currently standard; for example, as
a side effect of configuring an add-on board with some GPIO expanders.

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

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

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

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

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

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

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

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

Platform Support
----------------
To force-enable this framework, a platform's Kconfig will "select" GPIOLIB,
else it is up to the user to configure support for GPIO.

If neither of these options are selected, the platform does not support
GPIOs through GPIO-lib and the code cannot be enabled by the user.

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

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

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

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

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

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

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

Sysfs Interface for Userspace (OPTIONAL)
========================================
Platforms which use the "gpiolib" implementors framework may choose to
configure a sysfs user interface to GPIOs.  This is different from the
debugfs interface, since it provides control over GPIO direction and
value instead of just showing a gpio state summary.  Plus, it could be
present on production systems without debugging support.

Given appropriate hardware documentation for the system, userspace could
know for example that GPIO #23 controls the write protect line used to
protect boot loader segments in flash memory.  System upgrade procedures
may need to temporarily remove that protection, first importing a GPIO,
then changing its output state, then updating the code before re-enabling
the write protection.  In normal use, GPIO #23 would never be touched,
and the kernel would have no need to know about it.

Again depending on appropriate hardware documentation, on some systems
userspace GPIO can be used to determine system configuration data that
standard kernels won't know about.  And for some tasks, simple userspace
GPIO drivers could be all that the system really needs.

Note that standard kernel drivers exist for common "LEDs and Buttons"
GPIO tasks:  "leds-gpio" and "gpio_keys", respectively.  Use those
instead of talking directly to the GPIOs; they integrate with kernel
frameworks better than your userspace code could.

Paths in Sysfs
--------------
There are three kinds of entry in /sys/class/gpio:

   -	Control interfaces used to get userspace control over GPIOs;

   -	GPIOs themselves; and

   -	GPIO controllers ("gpio_chip" instances).

That's in addition to standard files including the "device" symlink.

The control interfaces are write-only:

    /sys/class/gpio/

    	"export" ... Userspace may ask the kernel to export control of
		a GPIO to userspace by writing its number to this file.

		Example:  "echo 19 > export" will create a "gpio19" node
		for GPIO #19, if that's not requested by kernel code.

    	"unexport" ... Reverses the effect of exporting to userspace.

		Example:  "echo 19 > unexport" will remove a "gpio19"
		node exported using the "export" file.

GPIO signals have paths like /sys/class/gpio/gpio42/ (for GPIO #42)
and have the following read/write attributes:

    /sys/class/gpio/gpioN/

	"direction" ... reads as either "in" or "out".  This value may
		normally be written.  Writing as "out" defaults to
		initializing the value as low.  To ensure glitch free
		operation, values "low" and "high" may be written to
		configure the GPIO as an output with that initial value.

		Note that this attribute *will not exist* if the kernel
		doesn't support changing the direction of a GPIO, or
		it was exported by kernel code that didn't explicitly
		allow userspace to reconfigure this GPIO's direction.

	"value" ... reads as either 0 (low) or 1 (high).  If the GPIO
		is configured as an output, this value may be written;
		any nonzero value is treated as high.

		If the pin can be configured as interrupt-generating interrupt
		and if it has been configured to generate interrupts (see the
		description of "edge"), you can poll(2) on that file and
		poll(2) will return whenever the interrupt was triggered. If
		you use poll(2), set the events POLLPRI. If you use select(2),
		set the file descriptor in exceptfds. After poll(2) returns,
		either lseek(2) to the beginning of the sysfs file and read the
		new value or close the file and re-open it to read the value.

	"edge" ... reads as either "none", "rising", "falling", or
		"both". Write these strings to select the signal edge(s)
		that will make poll(2) on the "value" file return.

		This file exists only if the pin can be configured as an
		interrupt generating input pin.

	"active_low" ... reads as either 0 (false) or 1 (true).  Write
		any nonzero value to invert the value attribute both
		for reading and writing.  Existing and subsequent
		poll(2) support configuration via the edge attribute
		for "rising" and "falling" edges will follow this
		setting.

GPIO controllers have paths like /sys/class/gpio/gpiochip42/ (for the
controller implementing GPIOs starting at #42) and have the following
read-only attributes:

    /sys/class/gpio/gpiochipN/

    	"base" ... same as N, the first GPIO managed by this chip

    	"label" ... provided for diagnostics (not always unique)

    	"ngpio" ... how many GPIOs this manges (N to N + ngpio - 1)

Board documentation should in most cases cover what GPIOs are used for
what purposes.  However, those numbers are not always stable; GPIOs on
a daughtercard might be different depending on the base board being used,
or other cards in the stack.  In such cases, you may need to use the
gpiochip nodes (possibly in conjunction with schematics) to determine
the correct GPIO number to use for a given signal.

Exporting from Kernel code
--------------------------
Kernel code can explicitly manage exports of GPIOs which have already been
requested using gpio_request()::

	/* export the GPIO to userspace */
	int gpio_export(unsigned gpio, bool direction_may_change);

	/* reverse gpio_export() */
	void gpio_unexport();

	/* create a sysfs link to an exported GPIO node */
	int gpio_export_link(struct device *dev, const char *name,
		unsigned gpio)

After a kernel driver requests a GPIO, it may only be made available in
the sysfs interface by gpio_export().  The driver can control whether the
signal direction may change.  This helps drivers prevent userspace code
from accidentally clobbering important system state.

This explicit exporting can help with debugging (by making some kinds
of experiments easier), or can provide an always-there interface that's
suitable for documenting as part of a board support package.

After the GPIO has been exported, gpio_export_link() allows creating
symlinks from elsewhere in sysfs to the GPIO sysfs node.  Drivers can
use this to provide the interface under their own device in sysfs with
a descriptive name.

API Reference
=============

The functions listed in this section are deprecated. The GPIO descriptor based
API should be used in new code.

.. kernel-doc:: drivers/gpio/gpiolib-legacy.c
   :export:


code:
=========================
Using GPIO Lines in Linux
=========================

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.

.. _libgpiod: https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/


code:
High Speed Synchronous Serial Interface (HSI)
=============================================

Introduction
---------------

High Speed Syncronous Interface (HSI) is a fullduplex, low latency protocol,
that is optimized for die-level interconnect between an Application Processor
and a Baseband chipset. It has been specified by the MIPI alliance in 2003 and
implemented by multiple vendors since then.

The HSI interface supports full duplex communication over multiple channels
(typically 8) and is capable of reaching speeds up to 200 Mbit/s.

The serial protocol uses two signals, DATA and FLAG as combined data and clock
signals and an additional READY signal for flow control. An additional WAKE
signal can be used to wakeup the chips from standby modes. The signals are
commonly prefixed by AC for signals going from the application die to the
cellular die and CA for signals going the other way around.

::

    +------------+                                 +---------------+
    |  Cellular  |                                 |  Application  |
    |    Die     |                                 |      Die      |
    |            | - - - - - - CAWAKE - - - - - - >|               |
    |           T|------------ CADATA ------------>|R              |
    |           X|------------ CAFLAG ------------>|X              |
    |            |<----------- ACREADY ------------|               |
    |            |                                 |               |
    |            |                                 |               |
    |            |< - - - - -  ACWAKE - - - - - - -|               |
    |           R|<----------- ACDATA -------------|T              |
    |           X|<----------- ACFLAG -------------|X              |
    |            |------------ CAREADY ----------->|               |
    |            |                                 |               |
    |            |                                 |               |
    +------------+                                 +---------------+

HSI Subsystem in Linux
-------------------------

In the Linux kernel the hsi subsystem is supposed to be used for HSI devices.
The hsi subsystem contains drivers for hsi controllers including support for
multi-port controllers and provides a generic API for using the HSI ports.

It also contains HSI client drivers, which make use of the generic API to
implement a protocol used on the HSI interface. These client drivers can
use an arbitrary number of channels.

hsi-char Device
------------------

Each port automatically registers a generic client driver called hsi_char,
which provides a charecter device for userspace representing the HSI port.
It can be used to communicate via HSI from userspace. Userspace may
configure the hsi_char device using the following ioctl commands:

HSC_RESET
 flush the HSI port

HSC_SET_PM
 enable or disable the client.

HSC_SEND_BREAK
 send break

HSC_SET_RX
 set RX configuration

HSC_GET_RX
 get RX configuration

HSC_SET_TX
 set TX configuration

HSC_GET_TX
 get TX configuration

The kernel HSI API
------------------

.. kernel-doc:: include/linux/hsi/hsi.h
   :internal:

.. kernel-doc:: drivers/hsi/hsi_core.c
   :export:


code:
.. SPDX-License-Identifier: GPL-2.0+

============================================
The Linux Hardware Timestamping Engine (HTE)
============================================

:Author: Dipen Patel

Introduction
------------

Certain devices have built in hardware timestamping engines which can
monitor sets of system signals, lines, buses etc... in realtime for state
change; upon detecting the change they can automatically store the timestamp at
the moment of occurrence. Such functionality may help achieve better accuracy
in obtaining timestamps than using software counterparts i.e. ktime and
friends.

This document describes the API that can be used by hardware timestamping
engine provider and consumer drivers that want to use the hardware timestamping
engine (HTE) framework. Both consumers and providers must include
``#include <linux/hte.h>``.

The HTE framework APIs for the providers
----------------------------------------

.. kernel-doc:: drivers/hte/hte.c
   :functions: devm_hte_register_chip hte_push_ts_ns

The HTE framework APIs for the consumers
----------------------------------------

.. kernel-doc:: drivers/hte/hte.c
   :functions: hte_init_line_attr hte_ts_get hte_ts_put devm_hte_request_ts_ns hte_request_ts_ns hte_enable_ts hte_disable_ts of_hte_req_count hte_get_clk_src_info

The HTE framework public structures
-----------------------------------
.. kernel-doc:: include/linux/hte.h

More on the HTE timestamp data
------------------------------
The ``struct hte_ts_data`` is used to pass timestamp details between the
consumers and the providers. It expresses timestamp data in nanoseconds in
u64. An example of the typical timestamp data life cycle, for the GPIO line is
as follows::

 - Monitors GPIO line change.
 - Detects the state change on GPIO line.
 - Converts timestamps in nanoseconds.
 - Stores GPIO raw level in raw_level variable if the provider has that
 hardware capability.
 - Pushes this hte_ts_data object to HTE subsystem.
 - HTE subsystem increments seq counter and invokes consumer provided callback.
 Based on callback return value, the HTE core invokes secondary callback in
 the thread context.

HTE subsystem debugfs attributes
--------------------------------
HTE subsystem creates debugfs attributes at ``/sys/kernel/debug/hte/``.
It also creates line/signal-related debugfs attributes at
``/sys/kernel/debug/hte/<provider>/<label or line id>/``. Note that these
attributes are read-only.

`ts_requested`
		The total number of entities requested from the given provider,
		where entity is specified by the provider and could represent
		lines, GPIO, chip signals, buses etc...
                The attribute will be available at
		``/sys/kernel/debug/hte/<provider>/``.

`total_ts`
		The total number of entities supported by the provider.
                The attribute will be available at
		``/sys/kernel/debug/hte/<provider>/``.

`dropped_timestamps`
		The dropped timestamps for a given line.
                The attribute will be available at
		``/sys/kernel/debug/hte/<provider>/<label or line id>/``.


code:
.. SPDX-License-Identifier: GPL-2.0+

HTE Kernel provider driver
==========================

Description
-----------
The Nvidia tegra194 HTE provider driver implements two GTE
(Generic Timestamping Engine) instances: 1) GPIO GTE and 2) LIC
(Legacy Interrupt Controller) IRQ GTE. Both GTE instances get the
timestamp from the system counter TSC which has 31.25MHz clock rate, and the
driver converts clock tick rate to nanoseconds before storing it as timestamp
value.

GPIO GTE
--------

This GTE instance timestamps GPIO in real time. For that to happen GPIO
needs to be configured as input. The always on (AON) GPIO controller instance
supports timestamping GPIOs in real time and it has 39 GPIO lines. The GPIO GTE
and AON GPIO controller are tightly coupled as it requires very specific bits
to be set in GPIO config register before GPIO GTE can be used, for that GPIOLIB
adds two optional APIs as below. The GPIO GTE code supports both kernel
and userspace consumers. The kernel space consumers can directly talk to HTE
subsystem while userspace consumers timestamp requests go through GPIOLIB CDEV
framework to HTE subsystem.

See gpiod_enable_hw_timestamp_ns() and gpiod_disable_hw_timestamp_ns().

For userspace consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE flag must be
specified during IOCTL calls. Refer to ``tools/gpio/gpio-event-mon.c``, which
returns the timestamp in nanoseconds.

LIC (Legacy Interrupt Controller) IRQ GTE
-----------------------------------------

This GTE instance timestamps LIC IRQ lines in real time. There are 352 IRQ
lines which this instance can add timestamps to in real time. The hte
devicetree binding described at ``Documentation/devicetree/bindings/timestamp``
provides an example of how a consumer can request an IRQ line. Since it is a
one-to-one mapping with IRQ GTE provider, consumers can simply specify the IRQ
number that they are interested in. There is no userspace consumer support for
this GTE instance in the HTE framework.

The provider source code of both IRQ and GPIO GTE instances is located at
``drivers/hte/hte-tegra194.c``. The test driver
``drivers/hte/hte-tegra194-test.c`` demonstrates HTE API usage for both IRQ
and GPIO GTE.


code:
I\ :sup:`2`\ C and SMBus Subsystem
==================================

I\ :sup:`2`\ C (or without fancy typography, "I2C") is an acronym for
the "Inter-IC" bus, a simple bus protocol which is widely used where low
data rate communications suffice. Since it's also a licensed trademark,
some vendors use another name (such as "Two-Wire Interface", TWI) for
the same bus. I2C only needs two signals (SCL for clock, SDA for data),
conserving board real estate and minimizing signal quality issues. Most
I2C devices use seven bit addresses, and bus speeds of up to 400 kHz;
there's a high speed extension (3.4 MHz) that's not yet found wide use.
I2C is a multi-master bus; open drain signaling is used to arbitrate
between masters, as well as to handshake and to synchronize clocks from
slower clients.

The Linux I2C programming interfaces support the master side of bus
interactions and the slave side. The programming interface is
structured around two kinds of driver, and two kinds of device. An I2C
"Adapter Driver" abstracts the controller hardware; it binds to a
physical device (perhaps a PCI device or platform_device) and exposes a
:c:type:`struct i2c_adapter <i2c_adapter>` representing each
I2C bus segment it manages. On each I2C bus segment will be I2C devices
represented by a :c:type:`struct i2c_client <i2c_client>`.
Those devices will be bound to a :c:type:`struct i2c_driver
<i2c_driver>`, which should follow the standard Linux driver model. There
are functions to perform various I2C protocol operations; at this writing
all such functions are usable only from task context.

The System Management Bus (SMBus) is a sibling protocol. Most SMBus
systems are also I2C conformant. The electrical constraints are tighter
for SMBus, and it standardizes particular protocol messages and idioms.
Controllers that support I2C can also support most SMBus operations, but
SMBus controllers don't support all the protocol options that an I2C
controller will. There are functions to perform various SMBus protocol
operations, either using I2C primitives or by issuing SMBus commands to
i2c_adapter devices which don't support those I2C operations.

.. kernel-doc:: include/linux/i2c.h
   :internal:

.. kernel-doc:: drivers/i2c/i2c-boardinfo.c
   :functions: i2c_register_board_info

.. kernel-doc:: drivers/i2c/i2c-core-base.c
   :export:

.. kernel-doc:: drivers/i2c/i2c-core-smbus.c
   :export:


code:
.. SPDX-License-Identifier: GPL-2.0

=====================
I3C device driver API
=====================

.. kernel-doc:: include/linux/i3c/device.h

.. kernel-doc:: drivers/i3c/device.c


code:
.. SPDX-License-Identifier: GPL-2.0

=============
I3C subsystem
=============

.. toctree::

   protocol
   device-driver-api
   master-driver-api


code:
.. SPDX-License-Identifier: GPL-2.0

================================
I3C master controller driver API
================================

.. kernel-doc:: drivers/i3c/master.c

.. kernel-doc:: include/linux/i3c/master.h