code:
===================
Firmware Guidelines
===================

Users switching to a newer kernel should *not* have to install newer
firmware files to keep their hardware working. At the same time updated
firmware files must not cause any regressions for users of older kernel
releases.

Drivers that use firmware from linux-firmware should follow the rules in
this guide. (Where there is limited control of the firmware,
i.e. company doesn't support Linux, firmwares sourced from misc places,
then of course these rules will not apply strictly.)

* Firmware files shall be designed in a way that it allows checking for
  firmware ABI version changes. It is recommended that firmware files be
  versioned with at least a major/minor version. It is suggested that
  the firmware files in linux-firmware be named with some device
  specific name, and just the major version. The firmware version should
  be stored in the firmware header, or as an exception, as part of the
  firmware file name, in order to let the driver detact any non-ABI
  fixes/changes. The firmware files in linux-firmware should be
  overwritten with the newest compatible major version. Newer major
  version firmware shall remain compatible with all kernels that load
  that major number.

* If the kernel support for the hardware is normally inactive, or the
  hardware isn't available for public consumption, this can
  be ignored, until the first kernel release that enables that hardware.
  This means no major version bumps without the kernel retaining
  backwards compatibility for the older major versions.  Minor version
  bumps should not introduce new features that newer kernels depend on
  non-optionally.

* If a security fix needs lockstep firmware and kernel fixes in order to
  be successful, then all supported major versions in the linux-firmware
  repo that are required by currently supported stable/LTS kernels,
  should be updated with the security fix. The kernel patches should
  detect if the firmware is new enough to declare if the security issue
  is fixed.  All communications around security fixes should point at
  both the firmware and kernel fixes. If a security fix requires
  deprecating old major versions, then this should only be done as a
  last option, and be stated clearly in all communications.


code:
==============
Firmware cache
==============

When Linux resumes from suspend some device drivers require firmware lookups to
re-initialize devices. During resume there may be a period of time during which
firmware lookups are not possible, during this short period of time firmware
requests will fail. Time is of essence though, and delaying drivers to wait for
the root filesystem for firmware delays user experience with device
functionality. In order to support these requirements the firmware
infrastructure implements a firmware cache for device drivers for most API
calls, automatically behind the scenes.

The firmware cache makes using certain firmware API calls safe during a device
driver's suspend and resume callback.  Users of these API calls needn't cache
the firmware by themselves for dealing with firmware loss during system resume.

The firmware cache works by requesting for firmware prior to suspend and
caching it in memory. Upon resume device drivers using the firmware API will
have access to the firmware immediately, without having to wait for the root
filesystem to mount or dealing with possible race issues with lookups as the
root filesystem mounts.

Some implementation details about the firmware cache setup:

* The firmware cache is setup by adding a devres entry for each device that
  uses all synchronous call except :c:func:`request_firmware_into_buf`.

* If an asynchronous call is used the firmware cache is only set up for a
  device if the second argument (uevent) to request_firmware_nowait() is
  true. When uevent is true it requests that a kobject uevent be sent to
  userspace for the firmware request through the sysfs fallback mechanism
  if the firmware file is not found.

* If the firmware cache is determined to be needed as per the above two
  criteria the firmware cache is setup by adding a devres entry for the
  device making the firmware request.

* The firmware devres entry is maintained throughout the lifetime of the
  device. This means that even if you release_firmware() the firmware cache
  will still be used on resume from suspend.

* The timeout for the fallback mechanism is temporarily reduced to 10 seconds
  as the firmware cache is set up during suspend, the timeout is set back to
  the old value you had configured after the cache is set up.

* Upon suspend any pending non-uevent firmware requests are killed to avoid
  stalling the kernel, this is done with kill_requests_without_uevent(). Kernel
  calls requiring the non-uevent therefore need to implement their own firmware
  cache mechanism but must not use the firmware API on suspend.

repo_name: angery/linux


code:
=====================
Firmware search paths
=====================

The following search paths are used to look for firmware on your
root filesystem.

* fw_path_para - module parameter - default is empty so this is ignored
* /lib/firmware/updates/UTS_RELEASE/
* /lib/firmware/updates/
* /lib/firmware/UTS_RELEASE/
* /lib/firmware/

The module parameter ''path'' can be passed to the firmware_class module
to activate the first optional custom fw_path_para. The custom path can
only be up to 256 characters long. The kernel parameter passed would be:

* 'firmware_class.path=$CUSTOMIZED_PATH'

There is an alternative to customize the path at run time after bootup, you
can use the file:

* /sys/module/firmware_class/parameters/path

You would echo into it your custom path and firmware requested will be
searched for there first.


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

===================
Firmware Upload API
===================

A device driver that registers with the firmware loader will expose
persistent sysfs nodes to enable users to initiate firmware updates for
that device.  It is the responsibility of the device driver and/or the
device itself to perform any validation on the data received. Firmware
upload uses the same *loading* and *data* sysfs files described in the
documentation for firmware fallback. It also adds additional sysfs files
to provide status on the transfer of the firmware image to the device.

Register for firmware upload
============================

A device driver registers for firmware upload by calling
firmware_upload_register(). Among the parameter list is a name to
identify the device under /sys/class/firmware. A user may initiate a
firmware upload by echoing a 1 to the *loading* sysfs file for the target
device. Next, the user writes the firmware image to the *data* sysfs
file. After writing the firmware data, the user echos 0 to the *loading*
sysfs file to signal completion. Echoing 0 to *loading* also triggers the
transfer of the firmware to the lower-lever device driver in the context
of a kernel worker thread.

To use the firmware upload API, write a driver that implements a set of
ops.  The probe function calls firmware_upload_register() and the remove
function calls firmware_upload_unregister() such as::

	static const struct fw_upload_ops m10bmc_ops = {
		.prepare = m10bmc_sec_prepare,
		.write = m10bmc_sec_write,
		.poll_complete = m10bmc_sec_poll_complete,
		.cancel = m10bmc_sec_cancel,
		.cleanup = m10bmc_sec_cleanup,
	};

	static int m10bmc_sec_probe(struct platform_device *pdev)
	{
		const char *fw_name, *truncate;
		struct m10bmc_sec *sec;
		struct fw_upload *fwl;
		unsigned int len;

		sec = devm_kzalloc(&pdev->dev, sizeof(*sec), GFP_KERNEL);
		if (!sec)
			return -ENOMEM;

		sec->dev = &pdev->dev;
		sec->m10bmc = dev_get_drvdata(pdev->dev.parent);
		dev_set_drvdata(&pdev->dev, sec);

		fw_name = dev_name(sec->dev);
		truncate = strstr(fw_name, ".auto");
		len = (truncate) ? truncate - fw_name : strlen(fw_name);
		sec->fw_name = kmemdup_nul(fw_name, len, GFP_KERNEL);

		fwl = firmware_upload_register(sec->dev, sec->fw_name, &m10bmc_ops, sec);
		if (IS_ERR(fwl)) {
			dev_err(sec->dev, "Firmware Upload driver failed to start\n");
			kfree(sec->fw_name);
			return PTR_ERR(fwl);
		}

		sec->fwl = fwl;
		return 0;
	}

	static int m10bmc_sec_remove(struct platform_device *pdev)
	{
		struct m10bmc_sec *sec = dev_get_drvdata(&pdev->dev);

		firmware_upload_unregister(sec->fwl);
		kfree(sec->fw_name);
		return 0;
	}

firmware_upload_register
------------------------
.. kernel-doc:: drivers/base/firmware_loader/sysfs_upload.c
   :identifiers: firmware_upload_register

firmware_upload_unregister
--------------------------
.. kernel-doc:: drivers/base/firmware_loader/sysfs_upload.c
   :identifiers: firmware_upload_unregister

Firmware Upload Ops
-------------------
.. kernel-doc:: include/linux/firmware.h
   :identifiers: fw_upload_ops

Firmware Upload Progress Codes
------------------------------
The following progress codes are used internally by the firmware loader.
Corresponding strings are reported through the status sysfs node that
is described below and are documented in the ABI documentation.

.. kernel-doc:: drivers/base/firmware_loader/sysfs_upload.h
   :identifiers: fw_upload_prog

Firmware Upload Error Codes
---------------------------
The following error codes may be returned by the driver ops in case of
failure:

.. kernel-doc:: include/linux/firmware.h
   :identifiers: fw_upload_err

Sysfs Attributes
================

In addition to the *loading* and *data* sysfs files, there are additional
sysfs files to monitor the status of the data transfer to the target
device and to determine the final pass/fail status of the transfer.
Depending on the device and the size of the firmware image, a firmware
update could take milliseconds or minutes.

The additional sysfs files are:

* status - provides an indication of the progress of a firmware update
* error - provides error information for a failed firmware update
* remaining_size - tracks the data transfer portion of an update
* cancel - echo 1 to this file to cancel the update


code:
==================
Linux Firmware API
==================

.. toctree::

   introduction
   core
   efi/index
   request_firmware
   fw_upload
   other_interfaces

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


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

The firmware API enables kernel code to request files required
for functionality from userspace, the uses vary:

* Microcode for CPU errata
* Device driver firmware, required to be loaded onto device
  microcontrollers
* Device driver information data (calibration data, EEPROM overrides),
  some of which can be completely optional.

Types of firmware requests
==========================

There are two types of calls:

* Synchronous
* Asynchronous

Which one you use vary depending on your requirements, the rule of thumb
however is you should strive to use the asynchronous APIs unless you also
are already using asynchronous initialization mechanisms which will not
stall or delay boot. Even if loading firmware does not take a lot of time
processing firmware might, and this can still delay boot or initialization,
as such mechanisms such as asynchronous probe can help supplement drivers.


code:
=====================
Firmware lookup order
=====================

Different functionality is available to enable firmware to be found.
Below is chronological order of how firmware will be looked for once
a driver issues a firmware API call.

* The ''Built-in firmware'' is checked first, if the firmware is present we
  return it immediately
* The ''Firmware cache'' is looked at next. If the firmware is found we
  return it immediately
* The ''Direct filesystem lookup'' is performed next, if found we
  return it immediately
* The ''Platform firmware fallback'' is performed next, but only when
  firmware_request_platform() is used, if found we return it immediately
* If no firmware has been found and the fallback mechanism was enabled
  the sysfs interface is created. After this either a kobject uevent
  is issued or the custom firmware loading is relied upon for firmware
  loading up to the timeout value.


code:
Other Firmware Interfaces
=========================

DMI Interfaces
--------------

.. kernel-doc:: drivers/firmware/dmi_scan.c
   :export:

EDD Interfaces
--------------

.. kernel-doc:: drivers/firmware/edd.c
   :internal:

Generic System Framebuffers Interface
-------------------------------------

.. kernel-doc:: drivers/firmware/sysfb.c
   :export:

Intel Stratix10 SoC Service Layer
---------------------------------
Some features of the Intel Stratix10 SoC require a level of privilege
higher than the kernel is granted. Such secure features include
FPGA programming. In terms of the ARMv8 architecture, the kernel runs
at Exception Level 1 (EL1), access to the features requires
Exception Level 3 (EL3).

The Intel Stratix10 SoC service layer provides an in kernel API for
drivers to request access to the secure features. The requests are queued
and processed one by one. ARM’s SMCCC is used to pass the execution
of the requests on to a secure monitor (EL3).

.. kernel-doc:: include/linux/firmware/intel/stratix10-svc-client.h
   :functions: stratix10_svc_command_code

.. kernel-doc:: include/linux/firmware/intel/stratix10-svc-client.h
   :functions: stratix10_svc_client_msg

.. kernel-doc:: include/linux/firmware/intel/stratix10-svc-client.h
   :functions: stratix10_svc_command_config_type

.. kernel-doc:: include/linux/firmware/intel/stratix10-svc-client.h
   :functions: stratix10_svc_cb_data

.. kernel-doc:: include/linux/firmware/intel/stratix10-svc-client.h
   :functions: stratix10_svc_client

.. kernel-doc:: drivers/firmware/stratix10-svc.c
   :export:


code:
====================
request_firmware API
====================

You would typically load firmware and then load it into your device somehow.
The typical firmware work flow is reflected below::

	 if(request_firmware(&fw_entry, $FIRMWARE, device) == 0)
                copy_fw_to_device(fw_entry->data, fw_entry->size);
	 release_firmware(fw_entry);

Synchronous firmware requests
=============================

Synchronous firmware requests will wait until the firmware is found or until
an error is returned.

request_firmware
----------------
.. kernel-doc:: drivers/base/firmware_loader/main.c
   :functions: request_firmware

firmware_request_nowarn
-----------------------
.. kernel-doc:: drivers/base/firmware_loader/main.c
   :functions: firmware_request_nowarn

firmware_request_platform
-------------------------
.. kernel-doc:: drivers/base/firmware_loader/main.c
   :functions: firmware_request_platform

request_firmware_direct
-----------------------
.. kernel-doc:: drivers/base/firmware_loader/main.c
   :functions: request_firmware_direct

request_firmware_into_buf
-------------------------
.. kernel-doc:: drivers/base/firmware_loader/main.c
   :functions: request_firmware_into_buf

Asynchronous firmware requests
==============================

Asynchronous firmware requests allow driver code to not have to wait
until the firmware or an error is returned. Function callbacks are
provided so that when the firmware or an error is found the driver is
informed through the callback. request_firmware_nowait() cannot be called
in atomic contexts.

request_firmware_nowait
-----------------------
.. kernel-doc:: drivers/base/firmware_loader/main.c
   :functions: request_firmware_nowait

Special optimizations on reboot
===============================

Some devices have an optimization in place to enable the firmware to be
retained during system reboot. When such optimizations are used the driver
author must ensure the firmware is still available on resume from suspend,
this can be done with firmware_request_cache() instead of requesting for the
firmware to be loaded.

firmware_request_cache()
------------------------
.. kernel-doc:: drivers/base/firmware_loader/main.c
   :functions: firmware_request_cache

request firmware API expected driver use
========================================

Once an API call returns you process the firmware and then release the
firmware. For example if you used request_firmware() and it returns,
the driver has the firmware image accessible in fw_entry->{data,size}.
If something went wrong request_firmware() returns non-zero and fw_entry
is set to NULL. Once your driver is done with processing the firmware it
can call release_firmware(fw_entry) to release the firmware image
and any related resource.


code:
FPGA Bridge
===========

API to implement a new FPGA bridge
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

* struct fpga_bridge - The FPGA Bridge structure
* struct fpga_bridge_ops - Low level Bridge driver ops
* fpga_bridge_register() - Create and register a bridge
* fpga_bridge_unregister() - Unregister a bridge

.. kernel-doc:: include/linux/fpga/fpga-bridge.h
   :functions: fpga_bridge

.. kernel-doc:: include/linux/fpga/fpga-bridge.h
   :functions: fpga_bridge_ops

.. kernel-doc:: drivers/fpga/fpga-bridge.c
   :functions: fpga_bridge_register

.. kernel-doc:: drivers/fpga/fpga-bridge.c
   :functions: fpga_bridge_unregister


code:
FPGA Manager
============

Overview
--------

The FPGA manager core exports a set of functions for programming an FPGA with
an image.  The API is manufacturer agnostic.  All manufacturer specifics are
hidden away in a low level driver which registers a set of ops with the core.
The FPGA image data itself is very manufacturer specific, but for our purposes
it's just binary data.  The FPGA manager core won't parse it.

The FPGA image to be programmed can be in a scatter gather list, a single
contiguous buffer, or a firmware file.  Because allocating contiguous kernel
memory for the buffer should be avoided, users are encouraged to use a scatter
gather list instead if possible.

The particulars for programming the image are presented in a structure (struct
fpga_image_info).  This struct contains parameters such as pointers to the
FPGA image as well as image-specific particulars such as whether the image was
built for full or partial reconfiguration.

How to support a new FPGA device
--------------------------------

To add another FPGA manager, write a driver that implements a set of ops.  The
probe function calls fpga_mgr_register() or fpga_mgr_register_full(), such as::

	static const struct fpga_manager_ops socfpga_fpga_ops = {
		.write_init = socfpga_fpga_ops_configure_init,
		.write = socfpga_fpga_ops_configure_write,
		.write_complete = socfpga_fpga_ops_configure_complete,
		.state = socfpga_fpga_ops_state,
	};

	static int socfpga_fpga_probe(struct platform_device *pdev)
	{
		struct device *dev = &pdev->dev;
		struct socfpga_fpga_priv *priv;
		struct fpga_manager *mgr;
		int ret;

		priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
		if (!priv)
			return -ENOMEM;

		/*
		 * do ioremaps, get interrupts, etc. and save
		 * them in priv
		 */

		mgr = fpga_mgr_register(dev, "Altera SOCFPGA FPGA Manager",
					&socfpga_fpga_ops, priv);
		if (IS_ERR(mgr))
			return PTR_ERR(mgr);

		platform_set_drvdata(pdev, mgr);

		return 0;
	}

	static int socfpga_fpga_remove(struct platform_device *pdev)
	{
		struct fpga_manager *mgr = platform_get_drvdata(pdev);

		fpga_mgr_unregister(mgr);

		return 0;
	}

Alternatively, the probe function could call one of the resource managed
register functions, devm_fpga_mgr_register() or devm_fpga_mgr_register_full().
When these functions are used, the parameter syntax is the same, but the call
to fpga_mgr_unregister() should be removed. In the above example, the
socfpga_fpga_remove() function would not be required.

The ops will implement whatever device specific register writes are needed to
do the programming sequence for this particular FPGA.  These ops return 0 for
success or negative error codes otherwise.

The programming sequence is::
 1. .parse_header (optional, may be called once or multiple times)
 2. .write_init
 3. .write or .write_sg (may be called once or multiple times)
 4. .write_complete

The .parse_header function will set header_size and data_size to
struct fpga_image_info. Before parse_header call, header_size is initialized
with initial_header_size. If flag skip_header of fpga_manager_ops is true,
.write function will get image buffer starting at header_size offset from the
beginning. If data_size is set, .write function will get data_size bytes of
the image buffer, otherwise .write will get data up to the end of image buffer.
This will not affect .write_sg, .write_sg will still get whole image in
sg_table form. If FPGA image is already mapped as a single contiguous buffer,
whole buffer will be passed into .parse_header. If image is in scatter-gather
form, core code will buffer up at least .initial_header_size before the first
call of .parse_header, if it is not enough, .parse_header should set desired
size into info->header_size and return -EAGAIN, then it will be called again
with greater part of image buffer on the input.

The .write_init function will prepare the FPGA to receive the image data. The
buffer passed into .write_init will be at least info->header_size bytes long;
if the whole bitstream is not immediately available then the core code will
buffer up at least this much before starting.

The .write function writes a buffer to the FPGA. The buffer may be contain the
whole FPGA image or may be a smaller chunk of an FPGA image.  In the latter
case, this function is called multiple times for successive chunks. This interface
is suitable for drivers which use PIO.

The .write_sg version behaves the same as .write except the input is a sg_table
scatter list. This interface is suitable for drivers which use DMA.

The .write_complete function is called after all the image has been written
to put the FPGA into operating mode.

The ops include a .state function which will determine the state the FPGA is in
and return a code of type enum fpga_mgr_states.  It doesn't result in a change
in state.

API for implementing a new FPGA Manager driver
----------------------------------------------

* ``fpga_mgr_states`` -  Values for :c:expr:`fpga_manager->state`.
* struct fpga_manager -  the FPGA manager struct
* struct fpga_manager_ops -  Low level FPGA manager driver ops
* struct fpga_manager_info -  Parameter structure for fpga_mgr_register_full()
* fpga_mgr_register_full() -  Create and register an FPGA manager using the
  fpga_mgr_info structure to provide the full flexibility of options
* fpga_mgr_register() -  Create and register an FPGA manager using standard
  arguments
* devm_fpga_mgr_register_full() -  Resource managed version of
  fpga_mgr_register_full()
* devm_fpga_mgr_register() -  Resource managed version of fpga_mgr_register()
* fpga_mgr_unregister() -  Unregister an FPGA manager

.. kernel-doc:: include/linux/fpga/fpga-mgr.h
   :functions: fpga_mgr_states

.. kernel-doc:: include/linux/fpga/fpga-mgr.h
   :functions: fpga_manager

.. kernel-doc:: include/linux/fpga/fpga-mgr.h
   :functions: fpga_manager_ops

.. kernel-doc:: include/linux/fpga/fpga-mgr.h
   :functions: fpga_manager_info

.. kernel-doc:: drivers/fpga/fpga-mgr.c
   :functions: fpga_mgr_register_full

.. kernel-doc:: drivers/fpga/fpga-mgr.c
   :functions: fpga_mgr_register

.. kernel-doc:: drivers/fpga/fpga-mgr.c
   :functions: devm_fpga_mgr_register_full

.. kernel-doc:: drivers/fpga/fpga-mgr.c
   :functions: devm_fpga_mgr_register

.. kernel-doc:: drivers/fpga/fpga-mgr.c
   :functions: fpga_mgr_unregister


code:
In-kernel API for FPGA Programming
==================================

Overview
--------

The in-kernel API for FPGA programming is a combination of APIs from
FPGA manager, bridge, and regions.  The actual function used to
trigger FPGA programming is fpga_region_program_fpga().

fpga_region_program_fpga() uses functionality supplied by
the FPGA manager and bridges.  It will:

 * lock the region's mutex
 * lock the mutex of the region's FPGA manager
 * build a list of FPGA bridges if a method has been specified to do so
 * disable the bridges
 * program the FPGA using info passed in :c:expr:`fpga_region->info`.
 * re-enable the bridges
 * release the locks

The struct fpga_image_info specifies what FPGA image to program.  It is
allocated/freed by fpga_image_info_alloc() and freed with
fpga_image_info_free()

How to program an FPGA using a region
-------------------------------------

When the FPGA region driver probed, it was given a pointer to an FPGA manager
driver so it knows which manager to use.  The region also either has a list of
bridges to control during programming or it has a pointer to a function that
will generate that list.  Here's some sample code of what to do next::

	#include <linux/fpga/fpga-mgr.h>
	#include <linux/fpga/fpga-region.h>

	struct fpga_image_info *info;
	int ret;

	/*
	 * First, alloc the struct with information about the FPGA image to
	 * program.
	 */
	info = fpga_image_info_alloc(dev);
	if (!info)
		return -ENOMEM;

	/* Set flags as needed, such as: */
	info->flags = FPGA_MGR_PARTIAL_RECONFIG;

	/*
	 * Indicate where the FPGA image is. This is pseudo-code; you're
	 * going to use one of these three.
	 */
	if (image is in a scatter gather table) {

		info->sgt = [your scatter gather table]

	} else if (image is in a buffer) {

		info->buf = [your image buffer]
		info->count = [image buffer size]

	} else if (image is in a firmware file) {

		info->firmware_name = devm_kstrdup(dev, firmware_name,
						   GFP_KERNEL);

	}

	/* Add info to region and do the programming */
	region->info = info;
	ret = fpga_region_program_fpga(region);

	/* Deallocate the image info if you're done with it */
	region->info = NULL;
	fpga_image_info_free(info);

	if (ret)
		return ret;

	/* Now enumerate whatever hardware has appeared in the FPGA. */

API for programming an FPGA
---------------------------

* fpga_region_program_fpga() -  Program an FPGA
* fpga_image_info() -  Specifies what FPGA image to program
* fpga_image_info_alloc() -  Allocate an FPGA image info struct
* fpga_image_info_free() -  Free an FPGA image info struct

.. kernel-doc:: drivers/fpga/fpga-region.c
   :functions: fpga_region_program_fpga

FPGA Manager flags

.. kernel-doc:: include/linux/fpga/fpga-mgr.h
   :doc: FPGA Manager flags

.. kernel-doc:: include/linux/fpga/fpga-mgr.h
   :functions: fpga_image_info

.. kernel-doc:: drivers/fpga/fpga-mgr.c
   :functions: fpga_image_info_alloc

.. kernel-doc:: drivers/fpga/fpga-mgr.c
   :functions: fpga_image_info_free


code:
FPGA Region
===========

Overview
--------

This document is meant to be a brief overview of the FPGA region API usage.  A
more conceptual look at regions can be found in the Device Tree binding
document [#f1]_.

For the purposes of this API document, let's just say that a region associates
an FPGA Manager and a bridge (or bridges) with a reprogrammable region of an
FPGA or the whole FPGA.  The API provides a way to register a region and to
program a region.

Currently the only layer above fpga-region.c in the kernel is the Device Tree
support (of-fpga-region.c) described in [#f1]_.  The DT support layer uses regions
to program the FPGA and then DT to handle enumeration.  The common region code
is intended to be used by other schemes that have other ways of accomplishing
enumeration after programming.

An fpga-region can be set up to know the following things:

 * which FPGA manager to use to do the programming

 * which bridges to disable before programming and enable afterwards.

Additional info needed to program the FPGA image is passed in the struct
fpga_image_info including:

 * pointers to the image as either a scatter-gather buffer, a contiguous
   buffer, or the name of firmware file

 * flags indicating specifics such as whether the image is for partial
   reconfiguration.

How to add a new FPGA region
----------------------------

An example of usage can be seen in the probe function of [#f2]_.

.. [#f1] ../devicetree/bindings/fpga/fpga-region.txt
.. [#f2] ../../drivers/fpga/of-fpga-region.c

API to add a new FPGA region
----------------------------

* struct fpga_region - The FPGA region struct
* struct fpga_region_info - Parameter structure for fpga_region_register_full()
* fpga_region_register_full() -  Create and register an FPGA region using the
  fpga_region_info structure to provide the full flexibility of options
* fpga_region_register() -  Create and register an FPGA region using standard
  arguments
* fpga_region_unregister() -  Unregister an FPGA region

The FPGA region's probe function will need to get a reference to the FPGA
Manager it will be using to do the programming.  This usually would happen
during the region's probe function.

* fpga_mgr_get() - Get a reference to an FPGA manager, raise ref count
* of_fpga_mgr_get() -  Get a reference to an FPGA manager, raise ref count,
  given a device node.
* fpga_mgr_put() - Put an FPGA manager

The FPGA region will need to specify which bridges to control while programming
the FPGA.  The region driver can build a list of bridges during probe time
(:c:expr:`fpga_region->bridge_list`) or it can have a function that creates
the list of bridges to program just before programming
(:c:expr:`fpga_region->get_bridges`).  The FPGA bridge framework supplies the
following APIs to handle building or tearing down that list.

* fpga_bridge_get_to_list() - Get a ref of an FPGA bridge, add it to a
  list
* of_fpga_bridge_get_to_list() - Get a ref of an FPGA bridge, add it to a
  list, given a device node
* fpga_bridges_put() - Given a list of bridges, put them

.. kernel-doc:: include/linux/fpga/fpga-region.h
   :functions: fpga_region

.. kernel-doc:: include/linux/fpga/fpga-region.h
   :functions: fpga_region_info

.. kernel-doc:: drivers/fpga/fpga-region.c
   :functions: fpga_region_register_full

.. kernel-doc:: drivers/fpga/fpga-region.c
   :functions: fpga_region_register

.. kernel-doc:: drivers/fpga/fpga-region.c
   :functions: fpga_region_unregister

.. kernel-doc:: drivers/fpga/fpga-mgr.c
   :functions: fpga_mgr_get

.. kernel-doc:: drivers/fpga/fpga-mgr.c
   :functions: of_fpga_mgr_get

.. kernel-doc:: drivers/fpga/fpga-mgr.c
   :functions: fpga_mgr_put

.. kernel-doc:: drivers/fpga/fpga-bridge.c
   :functions: fpga_bridge_get_to_list

.. kernel-doc:: drivers/fpga/fpga-bridge.c
   :functions: of_fpga_bridge_get_to_list

.. kernel-doc:: drivers/fpga/fpga-bridge.c
   :functions: fpga_bridges_put


code:
==============
FPGA Subsystem
==============

:Author: Alan Tull

.. toctree::
   :maxdepth: 2

   intro
   fpga-mgr
   fpga-bridge
   fpga-region
   fpga-programming


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

The FPGA subsystem supports reprogramming FPGAs dynamically under
Linux.  Some of the core intentions of the FPGA subsystems are:

* The FPGA subsystem is vendor agnostic.

* The FPGA subsystem separates upper layers (userspace interfaces and
  enumeration) from lower layers that know how to program a specific
  FPGA.

* Code should not be shared between upper and lower layers.  This
  should go without saying.  If that seems necessary, there's probably
  framework functionality that can be added that will benefit
  other users.  Write the linux-fpga mailing list and maintainers and
  seek out a solution that expands the framework for broad reuse.

* Generally, when adding code, think of the future.  Plan for reuse.

The framework in the kernel is divided into:

FPGA Manager
------------

If you are adding a new FPGA or a new method of programming an FPGA,
this is the subsystem for you.  Low level FPGA manager drivers contain
the knowledge of how to program a specific device.  This subsystem
includes the framework in fpga-mgr.c and the low level drivers that
are registered with it.

FPGA Bridge
-----------

FPGA Bridges prevent spurious signals from going out of an FPGA or a
region of an FPGA during programming.  They are disabled before
programming begins and re-enabled afterwards.  An FPGA bridge may be
actual hard hardware that gates a bus to a CPU or a soft ("freeze")
bridge in FPGA fabric that surrounds a partial reconfiguration region
of an FPGA.  This subsystem includes fpga-bridge.c and the low level
drivers that are registered with it.

FPGA Region
-----------

If you are adding a new interface to the FPGA framework, add it on top
of an FPGA region.

The FPGA Region framework (fpga-region.c) associates managers and
bridges as reconfigurable regions.  A region may refer to the whole
FPGA in full reconfiguration or to a partial reconfiguration region.

The Device Tree FPGA Region support (of-fpga-region.c) handles
reprogramming FPGAs when device tree overlays are applied.


code:
Frame Buffer Library
====================

The frame buffer drivers depend heavily on four data structures. These
structures are declared in include/linux/fb.h. They are fb_info,
fb_var_screeninfo, fb_fix_screeninfo and fb_monospecs. The last
three can be made available to and from userland.

fb_info defines the current state of a particular video card. Inside
fb_info, there exists a fb_ops structure which is a collection of
needed functions to make fbdev and fbcon work. fb_info is only visible
to the kernel.

fb_var_screeninfo is used to describe the features of a video card
that are user defined. With fb_var_screeninfo, things such as depth
and the resolution may be defined.

The next structure is fb_fix_screeninfo. This defines the properties
of a card that are created when a mode is set and can't be changed
otherwise. A good example of this is the start of the frame buffer
memory. This "locks" the address of the frame buffer memory, so that it
cannot be changed or moved.

The last structure is fb_monospecs. In the old API, there was little
importance for fb_monospecs. This allowed for forbidden things such as
setting a mode of 800x600 on a fix frequency monitor. With the new API,
fb_monospecs prevents such things, and if used correctly, can prevent a
monitor from being cooked. fb_monospecs will not be useful until
kernels 2.5.x.

Frame Buffer Memory
-------------------

.. kernel-doc:: drivers/video/fbdev/core/fbmem.c
   :export:

Frame Buffer Colormap
---------------------

.. kernel-doc:: drivers/video/fbdev/core/fbcmap.c
   :export:

Frame Buffer Video Mode Database
--------------------------------

.. kernel-doc:: drivers/video/fbdev/core/modedb.c
   :internal:

.. kernel-doc:: drivers/video/fbdev/core/modedb.c
   :export:

Frame Buffer Macintosh Video Mode Database
------------------------------------------

.. kernel-doc:: drivers/video/fbdev/macmodes.c
   :export:

Frame Buffer Fonts
------------------

Refer to the file lib/fonts/fonts.c for more information.


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

=========================
Generic Counter Interface
=========================

Introduction
============

Counter devices are prevalent among a diverse spectrum of industries.
The ubiquitous presence of these devices necessitates a common interface
and standard of interaction and exposure. This driver API attempts to
resolve the issue of duplicate code found among existing counter device
drivers by introducing a generic counter interface for consumption. The
Generic Counter interface enables drivers to support and expose a common
set of components and functionality present in counter devices.

Theory
======

Counter devices can vary greatly in design, but regardless of whether
some devices are quadrature encoder counters or tally counters, all
counter devices consist of a core set of components. This core set of
components, shared by all counter devices, is what forms the essence of
the Generic Counter interface.

There are three core components to a counter:

* Signal:
  Stream of data to be evaluated by the counter.

* Synapse:
  Association of a Signal, and evaluation trigger, with a Count.

* Count:
  Accumulation of the effects of connected Synapses.

SIGNAL
------
A Signal represents a stream of data. This is the input data that is
evaluated by the counter to determine the count data; e.g. a quadrature
signal output line of a rotary encoder. Not all counter devices provide
user access to the Signal data, so exposure is optional for drivers.

When the Signal data is available for user access, the Generic Counter
interface provides the following available signal values:

* SIGNAL_LOW:
  Signal line is in a low state.

* SIGNAL_HIGH:
  Signal line is in a high state.

A Signal may be associated with one or more Counts.

SYNAPSE
-------
A Synapse represents the association of a Signal with a Count. Signal
data affects respective Count data, and the Synapse represents this
relationship.

The Synapse action mode specifies the Signal data condition that
triggers the respective Count's count function evaluation to update the
count data. The Generic Counter interface provides the following
available action modes:

* None:
  Signal does not trigger the count function. In Pulse-Direction count
  function mode, this Signal is evaluated as Direction.

* Rising Edge:
  Low state transitions to high state.

* Falling Edge:
  High state transitions to low state.

* Both Edges:
  Any state transition.

A counter is defined as a set of input signals associated with count
data that are generated by the evaluation of the state of the associated
input signals as defined by the respective count functions. Within the
context of the Generic Counter interface, a counter consists of Counts
each associated with a set of Signals, whose respective Synapse
instances represent the count function update conditions for the
associated Counts.

A Synapse associates one Signal with one Count.

COUNT
-----
A Count represents the accumulation of the effects of connected
Synapses; i.e. the count data for a set of Signals. The Generic
Counter interface represents the count data as a natural number.

A Count has a count function mode which represents the update behavior
for the count data. The Generic Counter interface provides the following
available count function modes:

* Increase:
  Accumulated count is incremented.

* Decrease:
  Accumulated count is decremented.

* Pulse-Direction:
  Rising edges on signal A updates the respective count. The input level
  of signal B determines direction.

* Quadrature:
  A pair of quadrature encoding signals are evaluated to determine
  position and direction. The following Quadrature modes are available:

  - x1 A:
    If direction is forward, rising edges on quadrature pair signal A
    updates the respective count; if the direction is backward, falling
    edges on quadrature pair signal A updates the respective count.
    Quadrature encoding determines the direction.

  - x1 B:
    If direction is forward, rising edges on quadrature pair signal B
    updates the respective count; if the direction is backward, falling
    edges on quadrature pair signal B updates the respective count.
    Quadrature encoding determines the direction.

  - x2 A:
    Any state transition on quadrature pair signal A updates the
    respective count. Quadrature encoding determines the direction.

  - x2 B:
    Any state transition on quadrature pair signal B updates the
    respective count. Quadrature encoding determines the direction.

  - x4:
    Any state transition on either quadrature pair signals updates the
    respective count. Quadrature encoding determines the direction.

A Count has a set of one or more associated Synapses.

Paradigm
========

The most basic counter device may be expressed as a single Count
associated with a single Signal via a single Synapse. Take for example
a counter device which simply accumulates a count of rising edges on a
source input line::

                Count                Synapse        Signal
                -----                -------        ------
        +---------------------+
        | Data: Count         |    Rising Edge     ________
        | Function: Increase  |  <-------------   / Source \
        |                     |                  ____________
        +---------------------+

In this example, the Signal is a source input line with a pulsing
voltage, while the Count is a persistent count value which is repeatedly
incremented. The Signal is associated with the respective Count via a
Synapse. The increase function is triggered by the Signal data condition
specified by the Synapse -- in this case a rising edge condition on the
voltage input line. In summary, the counter device existence and
behavior is aptly represented by respective Count, Signal, and Synapse
components: a rising edge condition triggers an increase function on an
accumulating count datum.

A counter device is not limited to a single Signal; in fact, in theory
many Signals may be associated with even a single Count. For example, a
quadrature encoder counter device can keep track of position based on
the states of two input lines::

                   Count                 Synapse     Signal
                   -----                 -------     ------
        +-------------------------+
        | Data: Position          |    Both Edges     ___
        | Function: Quadrature x4 |  <------------   / A \
        |                         |                 _______
        |                         |
        |                         |    Both Edges     ___
        |                         |  <------------   / B \
        |                         |                 _______
        +-------------------------+

In this example, two Signals (quadrature encoder lines A and B) are
associated with a single Count: a rising or falling edge on either A or
B triggers the "Quadrature x4" function which determines the direction
of movement and updates the respective position data. The "Quadrature
x4" function is likely implemented in the hardware of the quadrature
encoder counter device; the Count, Signals, and Synapses simply
represent this hardware behavior and functionality.

Signals associated with the same Count can have differing Synapse action
mode conditions. For example, a quadrature encoder counter device
operating in a non-quadrature Pulse-Direction mode could have one input
line dedicated for movement and a second input line dedicated for
direction::

                   Count                   Synapse      Signal
                   -----                   -------      ------
        +---------------------------+
        | Data: Position            |    Rising Edge     ___
        | Function: Pulse-Direction |  <-------------   / A \ (Movement)
        |                           |                  _______
        |                           |
        |                           |       None         ___
        |                           |  <-------------   / B \ (Direction)
        |                           |                  _______
        +---------------------------+

Only Signal A triggers the "Pulse-Direction" update function, but the
instantaneous state of Signal B is still required in order to know the
direction so that the position data may be properly updated. Ultimately,
both Signals are associated with the same Count via two respective
Synapses, but only one Synapse has an active action mode condition which
triggers the respective count function while the other is left with a
"None" condition action mode to indicate its respective Signal's
availability for state evaluation despite its non-triggering mode.

Keep in mind that the Signal, Synapse, and Count are abstract
representations which do not need to be closely married to their
respective physical sources. This allows the user of a counter to
divorce themselves from the nuances of physical components (such as
whether an input line is differential or single-ended) and instead focus
on the core idea of what the data and process represent (e.g. position
as interpreted from quadrature encoding data).

Driver API
==========

Driver authors may utilize the Generic Counter interface in their code
by including the include/linux/counter.h header file. This header file
provides several core data structures, function prototypes, and macros
for defining a counter device.

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

.. kernel-doc:: drivers/counter/counter-core.c
   :export:

.. kernel-doc:: drivers/counter/counter-chrdev.c
   :export:

Driver Implementation
=====================

To support a counter device, a driver must first allocate the available
Counter Signals via counter_signal structures. These Signals should
be stored as an array and set to the signals array member of an
allocated counter_device structure before the Counter is registered to
the system.

Counter Counts may be allocated via counter_count structures, and
respective Counter Signal associations (Synapses) made via
counter_synapse structures. Associated counter_synapse structures are
stored as an array and set to the synapses array member of the
respective counter_count structure. These counter_count structures are
set to the counts array member of an allocated counter_device structure
before the Counter is registered to the system.

Driver callbacks must be provided to the counter_device structure in
order to communicate with the device: to read and write various Signals
and Counts, and to set and get the "action mode" and "function mode" for
various Synapses and Counts respectively.

A counter_device structure is allocated using counter_alloc() and then
registered to the system by passing it to the counter_add() function, and
unregistered by passing it to the counter_unregister function. There are
device managed variants of these functions: devm_counter_alloc() and
devm_counter_add().

The struct counter_comp structure is used to define counter extensions
for Signals, Synapses, and Counts.

The "type" member specifies the type of high-level data (e.g. BOOL,
COUNT_DIRECTION, etc.) handled by this extension. The "``*_read``" and
"``*_write``" members can then be set by the counter device driver with
callbacks to handle that data using native C data types (i.e. u8, u64,
etc.).

Convenience macros such as ``COUNTER_COMP_COUNT_U64`` are provided for
use by driver authors. In particular, driver authors are expected to use
the provided macros for standard Counter subsystem attributes in order
to maintain a consistent interface for userspace. For example, a counter
device driver may define several standard attributes like so::

        struct counter_comp count_ext[] = {
                COUNTER_COMP_DIRECTION(count_direction_read),
                COUNTER_COMP_ENABLE(count_enable_read, count_enable_write),
                COUNTER_COMP_CEILING(count_ceiling_read, count_ceiling_write),
        };

This makes it simple to see, add, and modify the attributes that are
supported by this driver ("direction", "enable", and "ceiling") and to
maintain this code without getting lost in a web of struct braces.

Callbacks must match the function type expected for the respective
component or extension. These function types are defined in the struct
counter_comp structure as the "``*_read``" and "``*_write``" union
members.

The corresponding callback prototypes for the extensions mentioned in
the previous example above would be::

        int count_direction_read(struct counter_device *counter,
                                 struct counter_count *count,
                                 enum counter_count_direction *direction);
        int count_enable_read(struct counter_device *counter,
                              struct counter_count *count, u8 *enable);
        int count_enable_write(struct counter_device *counter,
                               struct counter_count *count, u8 enable);
        int count_ceiling_read(struct counter_device *counter,
                               struct counter_count *count, u64 *ceiling);
        int count_ceiling_write(struct counter_device *counter,
                                struct counter_count *count, u64 ceiling);

Determining the type of extension to create is a matter of scope.

* Signal extensions are attributes that expose information/control
  specific to a Signal. These types of attributes will exist under a
  Signal's directory in sysfs.

  For example, if you have an invert feature for a Signal, you can have
  a Signal extension called "invert" that toggles that feature:
  /sys/bus/counter/devices/counterX/signalY/invert

* Count extensions are attributes that expose information/control
  specific to a Count. These type of attributes will exist under a
  Count's directory in sysfs.

  For example, if you want to pause/unpause a Count from updating, you
  can have a Count extension called "enable" that toggles such:
  /sys/bus/counter/devices/counterX/countY/enable

* Device extensions are attributes that expose information/control
  non-specific to a particular Count or Signal. This is where you would
  put your global features or other miscellaneous functionality.

  For example, if your device has an overtemp sensor, you can report the
  chip overheated via a device extension called "error_overtemp":
  /sys/bus/counter/devices/counterX/error_overtemp

Subsystem Architecture
======================

Counter drivers pass and take data natively (i.e. ``u8``, ``u64``, etc.)
and the shared counter module handles the translation between the sysfs
interface. This guarantees a standard userspace interface for all
counter drivers, and enables a Generic Counter chrdev interface via a
generalized device driver ABI.

A high-level view of how a count value is passed down from a counter
driver is exemplified by the following. The driver callbacks are first
registered to the Counter core component for use by the Counter
userspace interface components::

        Driver callbacks registration:
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                        +----------------------------+
                        | Counter device driver      |
                        +----------------------------+
                        | Processes data from device |
                        +----------------------------+
                                |
                         -------------------
                        / driver callbacks /
                        -------------------
                                |
                                V
                        +----------------------+
                        | Counter core         |
                        +----------------------+
                        | Routes device driver |
                        | callbacks to the     |
                        | userspace interfaces |
                        +----------------------+
                                |
                         -------------------
                        / driver callbacks /
                        -------------------
                                |
                +---------------+---------------+
                |                               |
                V                               V
        +--------------------+          +---------------------+
        | Counter sysfs      |          | Counter chrdev      |
        +--------------------+          +---------------------+
        | Translates to the  |          | Translates to the   |
        | standard Counter   |          | standard Counter    |
        | sysfs output       |          | character device    |
        +--------------------+          +---------------------+

Thereafter, data can be transferred directly between the Counter device
driver and Counter userspace interface::

        Count data request:
        ~~~~~~~~~~~~~~~~~~~
                         ----------------------
                        / Counter device       \
                        +----------------------+
                        | Count register: 0x28 |
                        +----------------------+
                                |
                         -----------------
                        / raw count data /
                        -----------------
                                |
                                V
                        +----------------------------+
                        | Counter device driver      |
                        +----------------------------+
                        | Processes data from device |
                        |----------------------------|
                        | Type: u64                  |
                        | Value: 42                  |
                        +----------------------------+
                                |
                         ----------
                        / u64     /
                        ----------
                                |
                +---------------+---------------+
                |                               |
                V                               V
        +--------------------+          +---------------------+
        | Counter sysfs      |          | Counter chrdev      |
        +--------------------+          +---------------------+
        | Translates to the  |          | Translates to the   |
        | standard Counter   |          | standard Counter    |
        | sysfs output       |          | character device    |
        |--------------------|          |---------------------|
        | Type: const char * |          | Type: u64           |
        | Value: "42"        |          | Value: 42           |
        +--------------------+          +---------------------+
                |                               |
         ---------------                 -----------------------
        / const char * /                / struct counter_event /
        ---------------                 -----------------------
                |                               |
                |                               V
                |                       +-----------+
                |                       | read      |
                |                       +-----------+
                |                       \ Count: 42 /
                |                        -----------
                |
                V
        +--------------------------------------------------+
        | `/sys/bus/counter/devices/counterX/countY/count` |
        +--------------------------------------------------+
        \ Count: "42"                                      /
         --------------------------------------------------

There are four primary components involved:

Counter device driver
---------------------
Communicates with the hardware device to read/write data; e.g. counter
drivers for quadrature encoders, timers, etc.

Counter core
------------
Registers the counter device driver to the system so that the respective
callbacks are called during userspace interaction.

Counter sysfs
-------------
Translates counter data to the standard Counter sysfs interface format
and vice versa.

Please refer to the ``Documentation/ABI/testing/sysfs-bus-counter`` file
for a detailed breakdown of the available Generic Counter interface
sysfs attributes.

Counter chrdev
--------------
Translates Counter events to the standard Counter character device; data
is transferred via standard character device read calls, while Counter
events are configured via ioctl calls.

Sysfs Interface
===============

Several sysfs attributes are generated by the Generic Counter interface,
and reside under the ``/sys/bus/counter/devices/counterX`` directory,
where ``X`` is to the respective counter device id. Please see
``Documentation/ABI/testing/sysfs-bus-counter`` for detailed information
on each Generic Counter interface sysfs attribute.

Through these sysfs attributes, programs and scripts may interact with
the Generic Counter paradigm Counts, Signals, and Synapses of respective
counter devices.

Counter Character Device
========================

Counter character device nodes are created under the ``/dev`` directory
as ``counterX``, where ``X`` is the respective counter device id.
Defines for the standard Counter data types are exposed via the
userspace ``include/uapi/linux/counter.h`` file.

Counter events
--------------
Counter device drivers can support Counter events by utilizing the
``counter_push_event`` function::

        void counter_push_event(struct counter_device *const counter, const u8 event,
                                const u8 channel);

The event id is specified by the ``event`` parameter; the event channel
id is specified by the ``channel`` parameter. When this function is
called, the Counter data associated with the respective event is
gathered, and a ``struct counter_event`` is generated for each datum and
pushed to userspace.

Counter events can be configured by users to report various Counter
data of interest. This can be conceptualized as a list of Counter
component read calls to perform. For example:

        +------------------------+------------------------+
        | COUNTER_EVENT_OVERFLOW | COUNTER_EVENT_INDEX    |
        +========================+========================+
        | Channel 0              | Channel 0              |
        +------------------------+------------------------+
        | * Count 0              | * Signal 0             |
        | * Count 1              | * Signal 0 Extension 0 |
        | * Signal 3             | * Extension 4          |
        | * Count 4 Extension 2  +------------------------+
        | * Signal 5 Extension 0 | Channel 1              |
        |                        +------------------------+
        |                        | * Signal 4             |
        |                        | * Signal 4 Extension 0 |
        |                        | * Count 7              |
        +------------------------+------------------------+

When ``counter_push_event(counter, COUNTER_EVENT_INDEX, 1)`` is called
for example, it will go down the list for the ``COUNTER_EVENT_INDEX``
event channel 1 and execute the read callbacks for Signal 4, Signal 4
Extension 0, and Count 7 -- the data returned for each is pushed to a
kfifo as a ``struct counter_event``, which userspace can retrieve via a
standard read operation on the respective character device node.

Userspace
---------
Userspace applications can configure Counter events via ioctl operations
on the Counter character device node. There following ioctl codes are
supported and provided by the ``linux/counter.h`` userspace header file:

* :c:macro:`COUNTER_ADD_WATCH_IOCTL`

* :c:macro:`COUNTER_ENABLE_EVENTS_IOCTL`

* :c:macro:`COUNTER_DISABLE_EVENTS_IOCTL`

To configure events to gather Counter data, users first populate a
``struct counter_watch`` with the relevant event id, event channel id,
and the information for the desired Counter component from which to
read, and then pass it via the ``COUNTER_ADD_WATCH_IOCTL`` ioctl
command.

Note that an event can be watched without gathering Counter data by
setting the ``component.type`` member equal to
``COUNTER_COMPONENT_NONE``. With this configuration the Counter
character device will simply populate the event timestamps for those
respective ``struct counter_event`` elements and ignore the component
value.

The ``COUNTER_ADD_WATCH_IOCTL`` command will buffer these Counter
watches. When ready, the ``COUNTER_ENABLE_EVENTS_IOCTL`` ioctl command
may be used to activate these Counter watches.

Userspace applications can then execute a ``read`` operation (optionally
calling ``poll`` first) on the Counter character device node to retrieve
``struct counter_event`` elements with the desired data.


code:
=============
GPIO Mappings
=============

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

Note that it only applies to the new descriptor-based interface. For a
description of the deprecated integer-based GPIO interface please refer to
legacy.rst (actually, there is no real mapping possible with the old
interface; you just fetch an integer from somewhere and request the
corresponding GPIO).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	#include <linux/gpio/machine.h>

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

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

where

  - key is either the label of the gpiod_chip instance providing the GPIO, or
    the GPIO line name
  - chip_hwnum is the hardware number of the GPIO within the chip, or U16_MAX
    to indicate that key is a GPIO line name
  - con_id is the name of the GPIO function from the device point of view. It
	can be NULL, in which case it will match any function.
  - idx is the index of the GPIO within the function.
  - flags is defined to specify the following properties:
	* GPIO_ACTIVE_HIGH	- GPIO line is active high
	* GPIO_ACTIVE_LOW	- GPIO line is active low
	* GPIO_OPEN_DRAIN	- GPIO line is set up as open drain
	* GPIO_OPEN_SOURCE	- GPIO line is set up as open source
	* GPIO_PERSISTENT	- GPIO line is persistent during
				  suspend/resume and maintains its value
	* GPIO_TRANSITORY	- GPIO line is transitory and may loose its
				  electrical state during suspend/resume

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

Note that:
  1. GPIO line names are not guaranteed to be globally unique, so the first
     match found will be used.
  2. GPIO_LOOKUP() is just a shortcut to GPIO_LOOKUP_IDX() where idx = 0.

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

.. code-block:: c

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

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

	gpiod_add_lookup_table(&gpios_table);

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

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

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

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

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

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

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

.. code-block:: c

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

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

        gpiod_add_hogs(gpio_hog_table);

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

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

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

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

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

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


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

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

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

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

How to physically access the GPIO pins
======================================

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

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

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


code:
==================================
GPIO Descriptor Consumer Interface
==================================

This document describes the consumer interface of the GPIO framework. Note that
it describes the new descriptor-based interface. For a description of the
deprecated integer-based GPIO interface please refer to legacy.rst.

Guidelines for GPIOs consumers
==============================

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

	#include <linux/gpio/consumer.h>

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

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

- Truly optional GPIOLIB support - where the driver does not really make use
  of the GPIOs on certain compile-time configurations for certain systems, but
  will use it under other compile-time configurations. In this case the
  consumer must make sure not to call into these functions, or the user will
  be met with console warnings that may be perceived as intimidating.

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

Obtaining and Disposing GPIOs
=============================

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

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

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

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

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

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

* GPIOD_ASIS or 0 to not initialize the GPIO at all. The direction must be set
  later with one of the dedicated functions.
* GPIOD_IN to initialize the GPIO as input.
* GPIOD_OUT_LOW to initialize the GPIO as output with a value of 0.
* GPIOD_OUT_HIGH to initialize the GPIO as output with a value of 1.
* GPIOD_OUT_LOW_OPEN_DRAIN same as GPIOD_OUT_LOW but also enforce the line
  to be electrically used with open drain.
* GPIOD_OUT_HIGH_OPEN_DRAIN same as GPIOD_OUT_HIGH but also enforce the line
  to be electrically used with open drain.

Note that the initial value is *logical* and the physical line level depends on
whether the line is configured active high or active low (see
:ref:`active_low_semantics`).

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

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

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

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

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

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

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

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

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

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

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

Device-managed variants of these functions are also defined::

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

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

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

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

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

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

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

	void gpiod_put(struct gpio_desc *desc)

For an array of GPIOs this function can be used::

	void gpiod_put_array(struct gpio_descs *descs)

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

The device-managed variants are, unsurprisingly::

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

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

Using GPIOs
===========

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

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

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

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

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

	int gpiod_get_direction(const struct gpio_desc *desc)

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

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

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

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

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

The values are boolean, zero for 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 do not return errors because "invalid GPIO" should have been
reported earlier from gpiod_direction_*(). However, note that not all platforms
can read the value of output pins; those that can't should always return zero.
Also, using these calls for GPIOs that can't safely be accessed without sleeping
(see below) is an error.

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

Platforms that support this type of GPIO distinguish them from other GPIOs by
returning nonzero from this call::

	int gpiod_cansleep(const struct gpio_desc *desc)

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

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

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

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

.. _active_low_semantics:

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

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

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

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

To summarize::

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

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

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

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

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

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

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

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

Access multiple GPIOs with a single function call
-------------------------------------------------
The following functions get or set the values of an array of GPIOs::

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

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

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

The functions take four arguments:

	* array_size	- the number of array elements
	* desc_array	- an array of GPIO descriptors
	* array_info	- optional information obtained from gpiod_get_array()
	* value_bitmap	- a bitmap to store the GPIOs' values (get) or
          a bitmap of values to assign to the GPIOs (set)

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

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

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

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

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

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

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

	int gpiod_to_irq(const struct gpio_desc *desc)

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

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

GPIOs and ACPI
==============

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

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

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

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

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

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

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