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

============
I3C protocol
============

Disclaimer
==========

This chapter will focus on aspects that matter to software developers. For
everything hardware related (like how things are transmitted on the bus, how
collisions are prevented, ...) please have a look at the I3C specification.

This document is just a brief introduction to the I3C protocol and the concepts
it brings to the table. If you need more information, please refer to the MIPI
I3C specification (can be downloaded here
https://resources.mipi.org/mipi-i3c-v1-download).

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

The I3C (pronounced 'eye-three-see') is a MIPI standardized protocol designed
to overcome I2C limitations (limited speed, external signals needed for
interrupts, no automatic detection of the devices connected to the bus, ...)
while remaining power-efficient.

I3C Bus
=======

An I3C bus is made of several I3C devices and possibly some I2C devices as
well, but let's focus on I3C devices for now.

An I3C device on the I3C bus can have one of the following roles:

* Master: the device is driving the bus. It's the one in charge of initiating
  transactions or deciding who is allowed to talk on the bus (slave generated
  events are possible in I3C, see below).
* Slave: the device acts as a slave, and is not able to send frames to another
  slave on the bus. The device can still send events to the master on
  its own initiative if the master allowed it.

I3C is a multi-master protocol, so there might be several masters on a bus,
though only one device can act as a master at a given time. In order to gain
bus ownership, a master has to follow a specific procedure.

Each device on the I3C bus has to be assigned a dynamic address to be able to
communicate. Until this is done, the device should only respond to a limited
set of commands. If it has a static address (also called legacy I2C address),
the device can reply to I2C transfers.

In addition to these per-device addresses, the protocol defines a broadcast
address in order to address all devices on the bus.

Once a dynamic address has been assigned to a device, this address will be used
for any direct communication with the device. Note that even after being
assigned a dynamic address, the device should still process broadcast messages.

I3C Device discovery
====================

The I3C protocol defines a mechanism to automatically discover devices present
on the bus, their capabilities and the functionalities they provide. In this
regard I3C is closer to a discoverable bus like USB than it is to I2C or SPI.

The discovery mechanism is called DAA (Dynamic Address Assignment), because it
not only discovers devices but also assigns them a dynamic address.

During DAA, each I3C device reports 3 important things:

* BCR: Bus Characteristic Register. This 8-bit register describes the device bus
  related capabilities
* DCR: Device Characteristic Register. This 8-bit register describes the
  functionalities provided by the device
* Provisional ID: A 48-bit unique identifier. On a given bus there should be no
  Provisional ID collision, otherwise the discovery mechanism may fail.

I3C slave events
================

The I3C protocol allows slaves to generate events on their own, and thus allows
them to take temporary control of the bus.

This mechanism is called IBI for In Band Interrupts, and as stated in the name,
it allows devices to generate interrupts without requiring an external signal.

During DAA, each device on the bus has been assigned an address, and this
address will serve as a priority identifier to determine who wins if 2 different
devices are generating an interrupt at the same moment on the bus (the lower the
dynamic address the higher the priority).

Masters are allowed to inhibit interrupts if they want to. This inhibition
request can be broadcast (applies to all devices) or sent to a specific
device.

I3C Hot-Join
============

The Hot-Join mechanism is similar to USB hotplug. This mechanism allows
slaves to join the bus after it has been initialized by the master.

This covers the following use cases:

* the device is not powered when the bus is probed
* the device is hotplugged on the bus through an extension board

This mechanism is relying on slave events to inform the master that a new
device joined the bus and is waiting for a dynamic address.

The master is then free to address the request as it wishes: ignore it or
assign a dynamic address to the slave.

I3C transfer types
==================

If you omit SMBus (which is just a standardization on how to access registers
exposed by I2C devices), I2C has only one transfer type.

I3C defines 3 different classes of transfer in addition to I2C transfers which
are here for backward compatibility with I2C devices.

I3C CCC commands
----------------

CCC (Common Command Code) commands are meant to be used for anything that is
related to bus management and all features that are common to a set of devices.

CCC commands contain an 8-bit CCC ID describing the command that is executed.
The MSB of this ID specifies whether this is a broadcast command (bit7 = 0) or a
unicast one (bit7 = 1).

The command ID can be followed by a payload. Depending on the command, this
payload is either sent by the master sending the command (write CCC command),
or sent by the slave receiving the command (read CCC command). Of course, read
accesses only apply to unicast commands.
Note that, when sending a CCC command to a specific device, the device address
is passed in the first byte of the payload.

The payload length is not explicitly passed on the bus, and should be extracted
from the CCC ID.

Note that vendors can use a dedicated range of CCC IDs for their own commands
(0x61-0x7f and 0xe0-0xef).

I3C Private SDR transfers
-------------------------

Private SDR (Single Data Rate) transfers should be used for anything that is
device specific and does not require high transfer speed.

It is the equivalent of I2C transfers but in the I3C world. Each transfer is
passed the device address (dynamic address assigned during DAA), a payload
and a direction.

The only difference with I2C is that the transfer is much faster (typical clock
frequency is 12.5MHz).

I3C HDR commands
----------------

HDR commands should be used for anything that is device specific and requires
high transfer speed.

The first thing attached to an HDR command is the HDR mode. There are currently
3 different modes defined by the I3C specification (refer to the specification
for more details):

* HDR-DDR: Double Data Rate mode
* HDR-TSP: Ternary Symbol Pure. Only usable on busses with no I2C devices
* HDR-TSL: Ternary Symbol Legacy. Usable on busses with I2C devices

When sending an HDR command, the whole bus has to enter HDR mode, which is done
using a broadcast CCC command.
Once the bus has entered a specific HDR mode, the master sends the HDR command.
An HDR command is made of:

* one 16-bits command word in big endian
* N 16-bits data words in big endian

Those words may be wrapped with specific preambles/post-ambles which depend on
the chosen HDR mode and are detailed here (see the specification for more
details).

The 16-bits command word is made of:

* bit[15]: direction bit, read is 1, write is 0
* bit[14:8]: command code. Identifies the command being executed, the amount of
  data words and their meaning
* bit[7:1]: I3C address of the device this command is addressed to
* bit[0]: reserved/parity-bit

Backward compatibility with I2C devices
=======================================

The I3C protocol has been designed to be backward compatible with I2C devices.
This backward compatibility allows one to connect a mix of I2C and I3C devices
on the same bus, though, in order to be really efficient, I2C devices should
be equipped with 50 ns spike filters.

I2C devices can't be discovered like I3C ones and have to be statically
declared. In order to let the master know what these devices are capable of
(both in terms of bus related limitations and functionalities), the software
has to provide some information, which is done through the LVR (Legacy I2C
Virtual Register).


code:
=======
Buffers
=======

* struct iio_buffer — general buffer structure
* :c:func:`iio_validate_scan_mask_onehot` — Validates that exactly one channel
  is selected
* :c:func:`iio_buffer_get` — Grab a reference to the buffer
* :c:func:`iio_buffer_put` — Release the reference to the buffer

The Industrial I/O core offers a way for continuous data capture based on a
trigger source. Multiple data channels can be read at once from
:file:`/dev/iio:device{X}` character device node, thus reducing the CPU load.

IIO buffer sysfs interface
==========================
An IIO buffer has an associated attributes directory under
:file:`/sys/bus/iio/iio:device{X}/buffer/*`. Here are some of the existing
attributes:

* :file:`length`, the total number of data samples (capacity) that can be
  stored by the buffer.
* :file:`enable`, activate buffer capture.

IIO buffer setup
================

The meta information associated with a channel reading placed in a buffer is
called a scan element. The important bits configuring scan elements are
exposed to userspace applications via the
:file:`/sys/bus/iio/iio:device{X}/scan_elements/` directory. This directory contains
attributes of the following form:

* :file:`enable`, used for enabling a channel. If and only if its attribute
  is non *zero*, then a triggered capture will contain data samples for this
  channel.
* :file:`index`, the scan_index of the channel.
* :file:`type`, description of the scan element data storage within the buffer
  and hence the form in which it is read from user space.
  Format is [be|le]:[s|u]bits/storagebits[Xrepeat][>>shift] .

  * *be* or *le*, specifies big or little endian.
  * *s* or *u*, specifies if signed (2's complement) or unsigned.
  * *bits*, is the number of valid data bits.
  * *storagebits*, is the number of bits (after padding) that it occupies in the
    buffer.
  * *repeat*, specifies the number of bits/storagebits repetitions. When the
    repeat element is 0 or 1, then the repeat value is omitted.
  * *shift*, if specified, is the shift that needs to be applied prior to
    masking out unused bits.

For example, a driver for a 3-axis accelerometer with 12 bit resolution where
data is stored in two 8-bits registers as follows::

        7   6   5   4   3   2   1   0
      +---+---+---+---+---+---+---+---+
      |D3 |D2 |D1 |D0 | X | X | X | X | (LOW byte, address 0x06)
      +---+---+---+---+---+---+---+---+

        7   6   5   4   3   2   1   0
      +---+---+---+---+---+---+---+---+
      |D11|D10|D9 |D8 |D7 |D6 |D5 |D4 | (HIGH byte, address 0x07)
      +---+---+---+---+---+---+---+---+

will have the following scan element type for each axis::

      $ cat /sys/bus/iio/devices/iio:device0/scan_elements/in_accel_y_type
      le:s12/16>>4

A user space application will interpret data samples read from the buffer as
two byte little endian signed data, that needs a 4 bits right shift before
masking out the 12 valid bits of data.

For implementing buffer support a driver should initialize the following
fields in iio_chan_spec definition::

   struct iio_chan_spec {
   /* other members */
           int scan_index
           struct {
                   char sign;
                   u8 realbits;
                   u8 storagebits;
                   u8 shift;
                   u8 repeat;
                   enum iio_endian endianness;
                  } scan_type;
          };

The driver implementing the accelerometer described above will have the
following channel definition::

   struct iio_chan_spec accel_channels[] = {
           {
                   .type = IIO_ACCEL,
		   .modified = 1,
		   .channel2 = IIO_MOD_X,
		   /* other stuff here */
		   .scan_index = 0,
		   .scan_type = {
		           .sign = 's',
			   .realbits = 12,
			   .storagebits = 16,
			   .shift = 4,
			   .endianness = IIO_LE,
		   },
           }
           /* similar for Y (with channel2 = IIO_MOD_Y, scan_index = 1)
            * and Z (with channel2 = IIO_MOD_Z, scan_index = 2) axis
            */
    }

Here **scan_index** defines the order in which the enabled channels are placed
inside the buffer. Channels with a lower **scan_index** will be placed before
channels with a higher index. Each channel needs to have a unique
**scan_index**.

Setting **scan_index** to -1 can be used to indicate that the specific channel
does not support buffered capture. In this case no entries will be created for
the channel in the scan_elements directory.

More details
============
.. kernel-doc:: include/linux/iio/buffer.h
.. kernel-doc:: drivers/iio/industrialio-buffer.c
   :export:

repo_name: angery/linux


code:
=============
Core elements
=============

The Industrial I/O core offers both a unified framework for writing drivers for
many different types of embedded sensors and a standard interface to user space
applications manipulating sensors. The implementation can be found under
:file:`drivers/iio/industrialio-*`

Industrial I/O Devices
----------------------

* struct iio_dev - industrial I/O device
* iio_device_alloc() - allocate an :c:type:`iio_dev` from a driver
* iio_device_free() - free an :c:type:`iio_dev` from a driver
* iio_device_register() - register a device with the IIO subsystem
* iio_device_unregister() - unregister a device from the IIO
  subsystem

An IIO device usually corresponds to a single hardware sensor and it
provides all the information needed by a driver handling a device.
Let's first have a look at the functionality embedded in an IIO device
then we will show how a device driver makes use of an IIO device.

There are two ways for a user space application to interact with an IIO driver.

1. :file:`/sys/bus/iio/iio:device{X}/`, this represents a hardware sensor
   and groups together the data channels of the same chip.
2. :file:`/dev/iio:device{X}`, character device node interface used for
   buffered data transfer and for events information retrieval.

A typical IIO driver will register itself as an :doc:`I2C <../i2c>` or
:doc:`SPI <../spi>` driver and will create two routines, probe and remove.

At probe:

1. Call iio_device_alloc(), which allocates memory for an IIO device.
2. Initialize IIO device fields with driver specific information (e.g.
   device name, device channels).
3. Call iio_device_register(), this registers the device with the
   IIO core. After this call the device is ready to accept requests from user
   space applications.

At remove, we free the resources allocated in probe in reverse order:

1. iio_device_unregister(), unregister the device from the IIO core.
2. iio_device_free(), free the memory allocated for the IIO device.

IIO device sysfs interface
==========================

Attributes are sysfs files used to expose chip info and also allowing
applications to set various configuration parameters. For device with
index X, attributes can be found under /sys/bus/iio/iio:deviceX/ directory.
Common attributes are:

* :file:`name`, description of the physical chip.
* :file:`dev`, shows the major:minor pair associated with
  :file:`/dev/iio:deviceX` node.
* :file:`sampling_frequency_available`, available discrete set of sampling
  frequency values for device.
* Available standard attributes for IIO devices are described in the
  :file:`Documentation/ABI/testing/sysfs-bus-iio` file in the Linux kernel
  sources.

IIO device channels
===================

struct iio_chan_spec - specification of a single channel

An IIO device channel is a representation of a data channel. An IIO device can
have one or multiple channels. For example:

* a thermometer sensor has one channel representing the temperature measurement.
* a light sensor with two channels indicating the measurements in the visible
  and infrared spectrum.
* an accelerometer can have up to 3 channels representing acceleration on X, Y
  and Z axes.

An IIO channel is described by the struct iio_chan_spec.
A thermometer driver for the temperature sensor in the example above would
have to describe its channel as follows::

   static const struct iio_chan_spec temp_channel[] = {
        {
            .type = IIO_TEMP,
            .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),
        },
   };

Channel sysfs attributes exposed to userspace are specified in the form of
bitmasks. Depending on their shared info, attributes can be set in one of the
following masks:

* **info_mask_separate**, attributes will be specific to
  this channel
* **info_mask_shared_by_type**, attributes are shared by all channels of the
  same type
* **info_mask_shared_by_dir**, attributes are shared by all channels of the same
  direction
* **info_mask_shared_by_all**, attributes are shared by all channels

When there are multiple data channels per channel type we have two ways to
distinguish between them:

* set **.modified** field of :c:type:`iio_chan_spec` to 1. Modifiers are
  specified using **.channel2** field of the same :c:type:`iio_chan_spec`
  structure and are used to indicate a physically unique characteristic of the
  channel such as its direction or spectral response. For example, a light
  sensor can have two channels, one for infrared light and one for both
  infrared and visible light.
* set **.indexed** field of :c:type:`iio_chan_spec` to 1. In this case the
  channel is simply another instance with an index specified by the **.channel**
  field.

Here is how we can make use of the channel's modifiers::

   static const struct iio_chan_spec light_channels[] = {
           {
                   .type = IIO_INTENSITY,
                   .modified = 1,
                   .channel2 = IIO_MOD_LIGHT_IR,
                   .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
                   .info_mask_shared = BIT(IIO_CHAN_INFO_SAMP_FREQ),
           },
           {
                   .type = IIO_INTENSITY,
                   .modified = 1,
                   .channel2 = IIO_MOD_LIGHT_BOTH,
                   .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
                   .info_mask_shared = BIT(IIO_CHAN_INFO_SAMP_FREQ),
           },
           {
                   .type = IIO_LIGHT,
                   .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),
                   .info_mask_shared = BIT(IIO_CHAN_INFO_SAMP_FREQ),
           },
      }

This channel's definition will generate two separate sysfs files for raw data
retrieval:

* :file:`/sys/bus/iio/iio:device{X}/in_intensity_ir_raw`
* :file:`/sys/bus/iio/iio:device{X}/in_intensity_both_raw`

one file for processed data:

* :file:`/sys/bus/iio/iio:device{X}/in_illuminance_input`

and one shared sysfs file for sampling frequency:

* :file:`/sys/bus/iio/iio:device{X}/sampling_frequency`.

Here is how we can make use of the channel's indexing::

   static const struct iio_chan_spec light_channels[] = {
           {
                   .type = IIO_VOLTAGE,
		   .indexed = 1,
		   .channel = 0,
		   .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
	   },
           {
	           .type = IIO_VOLTAGE,
                   .indexed = 1,
                   .channel = 1,
                   .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
           },
   }

This will generate two separate attributes files for raw data retrieval:

* :file:`/sys/bus/iio/devices/iio:device{X}/in_voltage0_raw`, representing
  voltage measurement for channel 0.
* :file:`/sys/bus/iio/devices/iio:device{X}/in_voltage1_raw`, representing
  voltage measurement for channel 1.

More details
============
.. kernel-doc:: include/linux/iio/iio.h
.. kernel-doc:: drivers/iio/industrialio-core.c
   :export:


code:
===========
HW consumer
===========
An IIO device can be directly connected to another device in hardware. In this
case the buffers between IIO provider and IIO consumer are handled by hardware.
The Industrial I/O HW consumer offers a way to bond these IIO devices without
software buffer for data. The implementation can be found under
:file:`drivers/iio/buffer/hw-consumer.c`

* struct iio_hw_consumer — Hardware consumer structure
* :c:func:`iio_hw_consumer_alloc` — Allocate IIO hardware consumer
* :c:func:`iio_hw_consumer_free` — Free IIO hardware consumer
* :c:func:`iio_hw_consumer_enable` — Enable IIO hardware consumer
* :c:func:`iio_hw_consumer_disable` — Disable IIO hardware consumer

HW consumer setup
=================

As standard IIO device the implementation is based on IIO provider/consumer.
A typical IIO HW consumer setup looks like this::

	static struct iio_hw_consumer *hwc;

	static const struct iio_info adc_info = {
		.read_raw = adc_read_raw,
	};

	static int adc_read_raw(struct iio_dev *indio_dev,
				struct iio_chan_spec const *chan, int *val,
				int *val2, long mask)
	{
		ret = iio_hw_consumer_enable(hwc);

		/* Acquire data */

		ret = iio_hw_consumer_disable(hwc);
	}

	static int adc_probe(struct platform_device *pdev)
	{
		hwc = devm_iio_hw_consumer_alloc(&iio->dev);
	}

More details
============
.. kernel-doc:: drivers/iio/buffer/industrialio-hw-consumer.c
   :export:


code:
.. include:: <isonum.txt>

Industrial I/O
==============

**Copyright** |copy| 2015 Intel Corporation

Contents:

.. toctree::
   :maxdepth: 2

   intro
   core
   buffers
   triggers
   triggered-buffers
   hw-consumer


code:
.. include:: <isonum.txt>

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

The main purpose of the Industrial I/O subsystem (IIO) is to provide support
for devices that in some sense perform either
analog-to-digital conversion (ADC) or digital-to-analog conversion (DAC)
or both. The aim is to fill the gap between the somewhat similar hwmon and
:doc:`input <../input>` subsystems. Hwmon is directed at low sample rate
sensors used to monitor and control the system itself, like fan speed control
or temperature measurement. :doc:`Input <../input>` is, as its name suggests,
focused on human interaction input devices (keyboard, mouse, touchscreen).
In some cases there is considerable overlap between these and IIO.

Devices that fall into this category include:

* analog to digital converters (ADCs)
* accelerometers
* capacitance to digital converters (CDCs)
* digital to analog converters (DACs)
* gyroscopes
* inertial measurement units (IMUs)
* color and light sensors
* magnetometers
* pressure sensors
* proximity sensors
* temperature sensors

Usually these sensors are connected via :doc:`SPI <../spi>` or
:doc:`I2C <../i2c>`. A common use case of the sensors devices is to have
combined functionality (e.g. light plus proximity sensor).


code:
=================
Triggered Buffers
=================

Now that we know what buffers and triggers are let's see how they work together.

IIO triggered buffer setup
==========================

* :c:func:`iio_triggered_buffer_setup` — Setup triggered buffer and pollfunc
* :c:func:`iio_triggered_buffer_cleanup` — Free resources allocated by
  :c:func:`iio_triggered_buffer_setup`
* struct iio_buffer_setup_ops — buffer setup related callbacks

A typical triggered buffer setup looks like this::

    const struct iio_buffer_setup_ops sensor_buffer_setup_ops = {
      .preenable    = sensor_buffer_preenable,
      .postenable   = sensor_buffer_postenable,
      .postdisable  = sensor_buffer_postdisable,
      .predisable   = sensor_buffer_predisable,
    };

    irqreturn_t sensor_iio_pollfunc(int irq, void *p)
    {
        pf->timestamp = iio_get_time_ns((struct indio_dev *)p);
        return IRQ_WAKE_THREAD;
    }

    irqreturn_t sensor_trigger_handler(int irq, void *p)
    {
        u16 buf[8];
        int i = 0;

        /* read data for each active channel */
        for_each_set_bit(bit, active_scan_mask, masklength)
            buf[i++] = sensor_get_data(bit)

        iio_push_to_buffers_with_timestamp(indio_dev, buf, timestamp);

        iio_trigger_notify_done(trigger);
        return IRQ_HANDLED;
    }

    /* setup triggered buffer, usually in probe function */
    iio_triggered_buffer_setup(indio_dev, sensor_iio_polfunc,
                               sensor_trigger_handler,
                               sensor_buffer_setup_ops);

The important things to notice here are:

* :c:type:`iio_buffer_setup_ops`, the buffer setup functions to be called at
  predefined points in the buffer configuration sequence (e.g. before enable,
  after disable). If not specified, the IIO core uses the default
  iio_triggered_buffer_setup_ops.
* **sensor_iio_pollfunc**, the function that will be used as top half of poll
  function. It should do as little processing as possible, because it runs in
  interrupt context. The most common operation is recording of the current
  timestamp and for this reason one can use the IIO core defined
  :c:func:`iio_pollfunc_store_time` function.
* **sensor_trigger_handler**, the function that will be used as bottom half of
  the poll function. This runs in the context of a kernel thread and all the
  processing takes place here. It usually reads data from the device and
  stores it in the internal buffer together with the timestamp recorded in the
  top half.

More details
============
.. kernel-doc:: drivers/iio/buffer/industrialio-triggered-buffer.c


code:
========
Triggers
========

* struct iio_trigger — industrial I/O trigger device
* :c:func:`devm_iio_trigger_alloc` — Resource-managed iio_trigger_alloc
* :c:func:`devm_iio_trigger_register` — Resource-managed iio_trigger_register
  iio_trigger_unregister
* :c:func:`iio_trigger_validate_own_device` — Check if a trigger and IIO
  device belong to the same device

In many situations it is useful for a driver to be able to capture data based
on some external event (trigger) as opposed to periodically polling for data.
An IIO trigger can be provided by a device driver that also has an IIO device
based on hardware generated events (e.g. data ready or threshold exceeded) or
provided by a separate driver from an independent interrupt source (e.g. GPIO
line connected to some external system, timer interrupt or user space writing
a specific file in sysfs). A trigger may initiate data capture for a number of
sensors and also it may be completely unrelated to the sensor itself.

IIO trigger sysfs interface
===========================

There are two locations in sysfs related to triggers:

* :file:`/sys/bus/iio/devices/trigger{Y}/*`, this file is created once an
  IIO trigger is registered with the IIO core and corresponds to trigger
  with index Y.
  Because triggers can be very different depending on type there are few
  standard attributes that we can describe here:

  * :file:`name`, trigger name that can be later used for association with a
    device.
  * :file:`sampling_frequency`, some timer based triggers use this attribute to
    specify the frequency for trigger calls.

* :file:`/sys/bus/iio/devices/iio:device{X}/trigger/*`, this directory is
  created once the device supports a triggered buffer. We can associate a
  trigger with our device by writing the trigger's name in the
  :file:`current_trigger` file.

IIO trigger setup
=================

Let's see a simple example of how to setup a trigger to be used by a driver::

      struct iio_trigger_ops trigger_ops = {
          .set_trigger_state = sample_trigger_state,
          .validate_device = sample_validate_device,
      }

      struct iio_trigger *trig;

      /* first, allocate memory for our trigger */
      trig = iio_trigger_alloc(dev, "trig-%s-%d", name, idx);

      /* setup trigger operations field */
      trig->ops = &trigger_ops;

      /* now register the trigger with the IIO core */
      iio_trigger_register(trig);

IIO trigger ops
===============

* struct iio_trigger_ops — operations structure for an iio_trigger.

Notice that a trigger has a set of operations attached:

* :file:`set_trigger_state`, switch the trigger on/off on demand.
* :file:`validate_device`, function to validate the device when the current
  trigger gets changed.

More details
============
.. kernel-doc:: include/linux/iio/trigger.h
.. kernel-doc:: drivers/iio/industrialio-trigger.c
   :export:


code:
========================================
The Linux driver implementer's API guide
========================================

The kernel offers a wide variety of interfaces to support the development
of device drivers.  This document is an only somewhat organized collection
of some of those interfaces — it will hopefully get better over time!  The
available subsections can be seen below.

.. class:: toc-title

	   Table of contents

.. toctree::
   :maxdepth: 2

   driver-model/index
   basics
   infrastructure
   ioctl
   early-userspace/index
   pm/index
   clk
   device-io
   dma-buf
   device_link
   component
   message-based
   infiniband
   aperture
   frame-buffer
   regulator
   reset
   iio/index
   input
   usb/index
   firewire
   pci/index
   cxl/index
   spi
   i2c
   ipmb
   ipmi
   i3c/index
   interconnect
   devfreq
   hsi
   edac
   scsi
   libata
   target
   mailbox
   mtdnand
   miscellaneous
   mei/index
   mtd/index
   mmc/index
   nvdimm/index
   w1
   rapidio/index
   s390-drivers
   vme
   80211/index
   uio-howto
   firmware/index
   pin-control
   gpio/index
   md/index
   media/index
   misc_devices
   nfc/index
   dmaengine/index
   slimbus
   soundwire/index
   thermal/index
   fpga/index
   acpi/index
   auxiliary_bus
   backlight/lp855x-driver.rst
   connector
   console
   dcdbas
   eisa
   isa
   isapnp
   io-mapping
   io_ordering
   generic-counter
   memory-devices/index
   men-chameleon-bus
   ntb
   nvmem
   parport-lowlevel
   pps
   ptp
   phy/index
   pwm
   pldmfw/index
   rfkill
   serial/index
   sm501
   surface_aggregator/index
   switchtec
   sync_file
   tty/index
   vfio-mediated-device
   vfio
   vfio-pci-device-specific-driver-acceptance
   xilinx/index
   xillybus
   zorro
   hte/index

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


code:
===========================================
InfiniBand and Remote DMA (RDMA) Interfaces
===========================================

Introduction and Overview
=========================

TBD

InfiniBand core interfaces
==========================

.. kernel-doc:: drivers/infiniband/core/iwpm_util.h
    :internal:

.. kernel-doc:: drivers/infiniband/core/cq.c
    :export:

.. kernel-doc:: drivers/infiniband/core/cm.c
    :export:

.. kernel-doc:: drivers/infiniband/core/rw.c
    :export:

.. kernel-doc:: drivers/infiniband/core/device.c
    :export:

.. kernel-doc:: drivers/infiniband/core/verbs.c
    :export:

.. kernel-doc:: drivers/infiniband/core/packer.c
    :export:

.. kernel-doc:: drivers/infiniband/core/sa_query.c
    :export:

.. kernel-doc:: drivers/infiniband/core/ud_header.c
    :export:

.. kernel-doc:: drivers/infiniband/core/umem.c
    :export:

.. kernel-doc:: drivers/infiniband/core/umem_odp.c
    :export:

RDMA Verbs transport library
============================

.. kernel-doc:: drivers/infiniband/sw/rdmavt/mr.c
    :export:

.. kernel-doc:: drivers/infiniband/sw/rdmavt/rc.c
    :export:

.. kernel-doc:: drivers/infiniband/sw/rdmavt/ah.c
    :export:

.. kernel-doc:: drivers/infiniband/sw/rdmavt/vt.c
    :export:

.. kernel-doc:: drivers/infiniband/sw/rdmavt/cq.c
    :export:

.. kernel-doc:: drivers/infiniband/sw/rdmavt/qp.c
    :export:

.. kernel-doc:: drivers/infiniband/sw/rdmavt/mcast.c
    :export:

Upper Layer Protocols
=====================

iSCSI Extensions for RDMA (iSER)
--------------------------------

.. kernel-doc:: drivers/infiniband/ulp/iser/iscsi_iser.h
   :internal:

.. kernel-doc:: drivers/infiniband/ulp/iser/iscsi_iser.c
   :functions: iscsi_iser_pdu_alloc iser_initialize_task_headers \
	iscsi_iser_task_init iscsi_iser_mtask_xmit iscsi_iser_task_xmit \
	iscsi_iser_cleanup_task iscsi_iser_check_protection \
	iscsi_iser_conn_create iscsi_iser_conn_bind \
	iscsi_iser_conn_start iscsi_iser_conn_stop \
	iscsi_iser_session_destroy iscsi_iser_session_create \
	iscsi_iser_set_param iscsi_iser_ep_connect iscsi_iser_ep_poll \
	iscsi_iser_ep_disconnect

.. kernel-doc:: drivers/infiniband/ulp/iser/iser_initiator.c
   :internal:

.. kernel-doc:: drivers/infiniband/ulp/iser/iser_verbs.c
   :internal:

Omni-Path (OPA) Virtual NIC support
-----------------------------------

.. kernel-doc:: drivers/infiniband/ulp/opa_vnic/opa_vnic_internal.h
   :internal:

.. kernel-doc:: drivers/infiniband/ulp/opa_vnic/opa_vnic_encap.h
   :internal:

.. kernel-doc:: drivers/infiniband/ulp/opa_vnic/opa_vnic_vema_iface.c
   :internal:

.. kernel-doc:: drivers/infiniband/ulp/opa_vnic/opa_vnic_vema.c
   :internal:

InfiniBand SCSI RDMA protocol target support
--------------------------------------------

.. kernel-doc:: drivers/infiniband/ulp/srpt/ib_srpt.h
   :internal:

.. kernel-doc:: drivers/infiniband/ulp/srpt/ib_srpt.c
   :internal:

iSCSI Extensions for RDMA (iSER) target support
-----------------------------------------------

.. kernel-doc:: drivers/infiniband/ulp/isert/ib_isert.c
   :internal:


code:
Device drivers infrastructure
=============================

The Basic Device Driver-Model Structures
----------------------------------------

.. kernel-doc:: include/linux/device.h
   :internal:
   :no-identifiers: device_link_state

Device Drivers Base
-------------------

.. kernel-doc:: drivers/base/init.c
   :internal:

.. kernel-doc:: drivers/base/driver.c
   :export:

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

.. kernel-doc:: drivers/base/syscore.c
   :export:

.. kernel-doc:: drivers/base/class.c
   :export:

.. kernel-doc:: drivers/base/node.c
   :internal:

.. kernel-doc:: drivers/base/transport_class.c
   :export:

.. kernel-doc:: drivers/base/dd.c
   :export:

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

.. kernel-doc:: drivers/base/platform.c
   :export:

.. kernel-doc:: drivers/base/bus.c
   :export:

Device Drivers DMA Management
-----------------------------

.. kernel-doc:: kernel/dma/mapping.c
   :export:

Device drivers PnP support
--------------------------

.. kernel-doc:: drivers/pnp/core.c
   :internal:

.. kernel-doc:: drivers/pnp/card.c
   :export:

.. kernel-doc:: drivers/pnp/driver.c
   :internal:

.. kernel-doc:: drivers/pnp/manager.c
   :export:

.. kernel-doc:: drivers/pnp/support.c
   :export:

Userspace IO devices
--------------------

.. kernel-doc:: drivers/uio/uio.c
   :export:

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


code:
Input Subsystem
===============

Input core
----------

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

.. kernel-doc:: drivers/input/input.c
   :export:

.. kernel-doc:: drivers/input/ff-core.c
   :export:

.. kernel-doc:: drivers/input/ff-memless.c
   :export:

Multitouch Library
------------------

.. kernel-doc:: include/linux/input/mt.h
   :internal:

.. kernel-doc:: drivers/input/input-mt.c
   :export:

Matrix keyboards/keypads
------------------------

.. kernel-doc:: include/linux/input/matrix_keypad.h
   :internal:

Sparse keymap support
---------------------

.. kernel-doc:: include/linux/input/sparse-keymap.h
   :internal:

.. kernel-doc:: drivers/input/sparse-keymap.c
   :export:


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

=====================================
Generic System Interconnect Subsystem
=====================================

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

This framework is designed to provide a standard kernel interface to control
the settings of the interconnects on an SoC. These settings can be throughput,
latency and priority between multiple interconnected devices or functional
blocks. This can be controlled dynamically in order to save power or provide
maximum performance.

The interconnect bus is hardware with configurable parameters, which can be
set on a data path according to the requests received from various drivers.
An example of interconnect buses are the interconnects between various
components or functional blocks in chipsets. There can be multiple interconnects
on an SoC that can be multi-tiered.

Below is a simplified diagram of a real-world SoC interconnect bus topology.

::

 +----------------+    +----------------+
 | HW Accelerator |--->|      M NoC     |<---------------+
 +----------------+    +----------------+                |
                         |      |                    +------------+
  +-----+  +-------------+      V       +------+     |            |
  | DDR |  |                +--------+  | PCIe |     |            |
  +-----+  |                | Slaves |  +------+     |            |
    ^ ^    |                +--------+     |         |   C NoC    |
    | |    V                               V         |            |
 +------------------+   +------------------------+   |            |   +-----+
 |                  |-->|                        |-->|            |-->| CPU |
 |                  |-->|                        |<--|            |   +-----+
 |     Mem NoC      |   |         S NoC          |   +------------+
 |                  |<--|                        |---------+    |
 |                  |<--|                        |<------+ |    |   +--------+
 +------------------+   +------------------------+       | |    +-->| Slaves |
   ^  ^    ^    ^          ^                             | |        +--------+
   |  |    |    |          |                             | V
 +------+  |  +-----+   +-----+  +---------+   +----------------+   +--------+
 | CPUs |  |  | GPU |   | DSP |  | Masters |-->|       P NoC    |-->| Slaves |
 +------+  |  +-----+   +-----+  +---------+   +----------------+   +--------+
           |
       +-------+
       | Modem |
       +-------+

Terminology
-----------

Interconnect provider is the software definition of the interconnect hardware.
The interconnect providers on the above diagram are M NoC, S NoC, C NoC, P NoC
and Mem NoC.

Interconnect node is the software definition of the interconnect hardware
port. Each interconnect provider consists of multiple interconnect nodes,
which are connected to other SoC components including other interconnect
providers. The point on the diagram where the CPUs connect to the memory is
called an interconnect node, which belongs to the Mem NoC interconnect provider.

Interconnect endpoints are the first or the last element of the path. Every
endpoint is a node, but not every node is an endpoint.

Interconnect path is everything between two endpoints including all the nodes
that have to be traversed to reach from a source to destination node. It may
include multiple master-slave pairs across several interconnect providers.

Interconnect consumers are the entities which make use of the data paths exposed
by the providers. The consumers send requests to providers requesting various
throughput, latency and priority. Usually the consumers are device drivers, that
send request based on their needs. An example for a consumer is a video decoder
that supports various formats and image sizes.

Interconnect providers
----------------------

Interconnect provider is an entity that implements methods to initialize and
configure interconnect bus hardware. The interconnect provider drivers should
be registered with the interconnect provider core.

.. kernel-doc:: include/linux/interconnect-provider.h

Interconnect consumers
----------------------

Interconnect consumers are the clients which use the interconnect APIs to
get paths between endpoints and set their bandwidth/latency/QoS requirements
for these interconnect paths.  These interfaces are not currently
documented.

Interconnect debugfs interfaces
-------------------------------

Like several other subsystems interconnect will create some files for debugging
and introspection. Files in debugfs are not considered ABI so application
software shouldn't rely on format details change between kernel versions.

``/sys/kernel/debug/interconnect/interconnect_summary``:

Show all interconnect nodes in the system with their aggregated bandwidth
request. Indented under each node show bandwidth requests from each device.

``/sys/kernel/debug/interconnect/interconnect_graph``:

Show the interconnect graph in the graphviz dot format. It shows all
interconnect nodes and links in the system and groups together nodes from the
same provider as subgraphs. The format is human-readable and can also be piped
through dot to generate diagrams in many graphical formats::

        $ cat /sys/kernel/debug/interconnect/interconnect_graph | \
                dot -Tsvg > interconnect_graph.svg


code:
========================
The io_mapping functions
========================

API
===

The io_mapping functions in linux/io-mapping.h provide an abstraction for
efficiently mapping small regions of an I/O device to the CPU. The initial
usage is to support the large graphics aperture on 32-bit processors where
ioremap_wc cannot be used to statically map the entire aperture to the CPU
as it would consume too much of the kernel address space.

A mapping object is created during driver initialization using::

	struct io_mapping *io_mapping_create_wc(unsigned long base,
						unsigned long size)

'base' is the bus address of the region to be made
mappable, while 'size' indicates how large a mapping region to
enable. Both are in bytes.

This _wc variant provides a mapping which may only be used with
io_mapping_map_atomic_wc(), io_mapping_map_local_wc() or
io_mapping_map_wc().

With this mapping object, individual pages can be mapped either temporarily
or long term, depending on the requirements. Of course, temporary maps are
more efficient. They come in two flavours::

	void *io_mapping_map_local_wc(struct io_mapping *mapping,
				      unsigned long offset)

	void *io_mapping_map_atomic_wc(struct io_mapping *mapping,
				       unsigned long offset)

'offset' is the offset within the defined mapping region.  Accessing
addresses beyond the region specified in the creation function yields
undefined results. Using an offset which is not page aligned yields an
undefined result. The return value points to a single page in CPU address
space.

This _wc variant returns a write-combining map to the page and may only be
used with mappings created by io_mapping_create_wc()

Temporary mappings are only valid in the context of the caller. The mapping
is not guaranteed to be globaly visible.

io_mapping_map_local_wc() has a side effect on X86 32bit as it disables
migration to make the mapping code work. No caller can rely on this side
effect.

io_mapping_map_atomic_wc() has the side effect of disabling preemption and
pagefaults. Don't use in new code. Use io_mapping_map_local_wc() instead.

Nested mappings need to be undone in reverse order because the mapping
code uses a stack for keeping track of them::

 addr1 = io_mapping_map_local_wc(map1, offset1);
 addr2 = io_mapping_map_local_wc(map2, offset2);
 ...
 io_mapping_unmap_local(addr2);
 io_mapping_unmap_local(addr1);

The mappings are released with::

	void io_mapping_unmap_local(void *vaddr)
	void io_mapping_unmap_atomic(void *vaddr)

'vaddr' must be the value returned by the last io_mapping_map_local_wc() or
io_mapping_map_atomic_wc() call. This unmaps the specified mapping and
undoes the side effects of the mapping functions.

If you need to sleep while holding a mapping, you can use the regular
variant, although this may be significantly slower::

	void *io_mapping_map_wc(struct io_mapping *mapping,
				unsigned long offset)

This works like io_mapping_map_atomic/local_wc() except it has no side
effects and the pointer is globaly visible.

The mappings are released with::

	void io_mapping_unmap(void *vaddr)

Use for pages mapped with io_mapping_map_wc().

At driver close time, the io_mapping object must be freed::

	void io_mapping_free(struct io_mapping *mapping)


code:
==============================================
Ordering I/O writes to memory-mapped addresses
==============================================

On some platforms, so-called memory-mapped I/O is weakly ordered.  On such
platforms, driver writers are responsible for ensuring that I/O writes to
memory-mapped addresses on their device arrive in the order intended.  This is
typically done by reading a 'safe' device or bridge register, causing the I/O
chipset to flush pending writes to the device before any reads are posted.  A
driver would usually use this technique immediately prior to the exit of a
critical section of code protected by spinlocks.  This would ensure that
subsequent writes to I/O space arrived only after all prior writes (much like a
memory barrier op, mb(), only with respect to I/O).

A more concrete example from a hypothetical device driver::

		...
	CPU A:  spin_lock_irqsave(&dev_lock, flags)
	CPU A:  val = readl(my_status);
	CPU A:  ...
	CPU A:  writel(newval, ring_ptr);
	CPU A:  spin_unlock_irqrestore(&dev_lock, flags)
		...
	CPU B:  spin_lock_irqsave(&dev_lock, flags)
	CPU B:  val = readl(my_status);
	CPU B:  ...
	CPU B:  writel(newval2, ring_ptr);
	CPU B:  spin_unlock_irqrestore(&dev_lock, flags)
		...

In the case above, the device may receive newval2 before it receives newval,
which could cause problems.  Fixing it is easy enough though::

		...
	CPU A:  spin_lock_irqsave(&dev_lock, flags)
	CPU A:  val = readl(my_status);
	CPU A:  ...
	CPU A:  writel(newval, ring_ptr);
	CPU A:  (void)readl(safe_register); /* maybe a config register? */
	CPU A:  spin_unlock_irqrestore(&dev_lock, flags)
		...
	CPU B:  spin_lock_irqsave(&dev_lock, flags)
	CPU B:  val = readl(my_status);
	CPU B:  ...
	CPU B:  writel(newval2, ring_ptr);
	CPU B:  (void)readl(safe_register); /* maybe a config register? */
	CPU B:  spin_unlock_irqrestore(&dev_lock, flags)

Here, the reads from safe_register will cause the I/O chipset to flush any
pending writes before actually posting the read to the chipset, preventing
possible data corruption.


code:
======================
ioctl based interfaces
======================

ioctl() is the most common way for applications to interface
with device drivers. It is flexible and easily extended by adding new
commands and can be passed through character devices, block devices as
well as sockets and other special file descriptors.

However, it is also very easy to get ioctl command definitions wrong,
and hard to fix them later without breaking existing applications,
so this documentation tries to help developers get it right.

Command number definitions
==========================

The command number, or request number, is the second argument passed to
the ioctl system call. While this can be any 32-bit number that uniquely
identifies an action for a particular driver, there are a number of
conventions around defining them.

``include/uapi/asm-generic/ioctl.h`` provides four macros for defining
ioctl commands that follow modern conventions: ``_IO``, ``_IOR``,
``_IOW``, and ``_IOWR``. These should be used for all new commands,
with the correct parameters:

_IO/_IOR/_IOW/_IOWR
   The macro name specifies how the argument will be used.  It may be a
   pointer to data to be passed into the kernel (_IOW), out of the kernel
   (_IOR), or both (_IOWR).  _IO can indicate either commands with no
   argument or those passing an integer value instead of a pointer.
   It is recommended to only use _IO for commands without arguments,
   and use pointers for passing data.

type
   An 8-bit number, often a character literal, specific to a subsystem
   or driver, and listed in Documentation/userspace-api/ioctl/ioctl-number.rst

nr
  An 8-bit number identifying the specific command, unique for a give
  value of 'type'

data_type
  The name of the data type pointed to by the argument, the command number
  encodes the ``sizeof(data_type)`` value in a 13-bit or 14-bit integer,
  leading to a limit of 8191 bytes for the maximum size of the argument.
  Note: do not pass sizeof(data_type) type into _IOR/_IOW/IOWR, as that
  will lead to encoding sizeof(sizeof(data_type)), i.e. sizeof(size_t).
  _IO does not have a data_type parameter.

Interface versions
==================

Some subsystems use version numbers in data structures to overload
commands with different interpretations of the argument.

This is generally a bad idea, since changes to existing commands tend
to break existing applications.

A better approach is to add a new ioctl command with a new number. The
old command still needs to be implemented in the kernel for compatibility,
but this can be a wrapper around the new implementation.

Return code
===========

ioctl commands can return negative error codes as documented in errno(3);
these get turned into errno values in user space. On success, the return
code should be zero. It is also possible but not recommended to return
a positive 'long' value.

When the ioctl callback is called with an unknown command number, the
handler returns either -ENOTTY or -ENOIOCTLCMD, which also results in
-ENOTTY being returned from the system call. Some subsystems return
-ENOSYS or -EINVAL here for historic reasons, but this is wrong.

Prior to Linux 5.5, compat_ioctl handlers were required to return
-ENOIOCTLCMD in order to use the fallback conversion into native
commands. As all subsystems are now responsible for handling compat
mode themselves, this is no longer needed, but it may be important to
consider when backporting bug fixes to older kernels.

Timestamps
==========

Traditionally, timestamps and timeout values are passed as ``struct
timespec`` or ``struct timeval``, but these are problematic because of
incompatible definitions of these structures in user space after the
move to 64-bit time_t.

The ``struct __kernel_timespec`` type can be used instead to be embedded
in other data structures when separate second/nanosecond values are
desired, or passed to user space directly. This is still not ideal though,
as the structure matches neither the kernel's timespec64 nor the user
space timespec exactly. The get_timespec64() and put_timespec64() helper
functions can be used to ensure that the layout remains compatible with
user space and the padding is treated correctly.

As it is cheap to convert seconds to nanoseconds, but the opposite
requires an expensive 64-bit division, a simple __u64 nanosecond value
can be simpler and more efficient.

Timeout values and timestamps should ideally use CLOCK_MONOTONIC time,
as returned by ktime_get_ns() or ktime_get_ts64().  Unlike
CLOCK_REALTIME, this makes the timestamps immune from jumping backwards
or forwards due to leap second adjustments and clock_settime() calls.

ktime_get_real_ns() can be used for CLOCK_REALTIME timestamps that
need to be persistent across a reboot or between multiple machines.

32-bit compat mode
==================

In order to support 32-bit user space running on a 64-bit machine, each
subsystem or driver that implements an ioctl callback handler must also
implement the corresponding compat_ioctl handler.

As long as all the rules for data structures are followed, this is as
easy as setting the .compat_ioctl pointer to a helper function such as
compat_ptr_ioctl() or blkdev_compat_ptr_ioctl().

compat_ptr()
------------

On the s390 architecture, 31-bit user space has ambiguous representations
for data pointers, with the upper bit being ignored. When running such
a process in compat mode, the compat_ptr() helper must be used to
clear the upper bit of a compat_uptr_t and turn it into a valid 64-bit
pointer.  On other architectures, this macro only performs a cast to a
``void __user *`` pointer.

In an compat_ioctl() callback, the last argument is an unsigned long,
which can be interpreted as either a pointer or a scalar depending on
the command. If it is a scalar, then compat_ptr() must not be used, to
ensure that the 64-bit kernel behaves the same way as a 32-bit kernel
for arguments with the upper bit set.

The compat_ptr_ioctl() helper can be used in place of a custom
compat_ioctl file operation for drivers that only take arguments that
are pointers to compatible data structures.

Structure layout
----------------

Compatible data structures have the same layout on all architectures,
avoiding all problematic members:

* ``long`` and ``unsigned long`` are the size of a register, so
  they can be either 32-bit or 64-bit wide and cannot be used in portable
  data structures. Fixed-length replacements are ``__s32``, ``__u32``,
  ``__s64`` and ``__u64``.

* Pointers have the same problem, in addition to requiring the
  use of compat_ptr(). The best workaround is to use ``__u64``
  in place of pointers, which requires a cast to ``uintptr_t`` in user
  space, and the use of u64_to_user_ptr() in the kernel to convert
  it back into a user pointer.

* On the x86-32 (i386) architecture, the alignment of 64-bit variables
  is only 32-bit, but they are naturally aligned on most other
  architectures including x86-64. This means a structure like::

    struct foo {
        __u32 a;
        __u64 b;
        __u32 c;
    };

  has four bytes of padding between a and b on x86-64, plus another four
  bytes of padding at the end, but no padding on i386, and it needs a
  compat_ioctl conversion handler to translate between the two formats.

  To avoid this problem, all structures should have their members
  naturally aligned, or explicit reserved fields added in place of the
  implicit padding. The ``pahole`` tool can be used for checking the
  alignment.

* On ARM OABI user space, structures are padded to multiples of 32-bit,
  making some structs incompatible with modern EABI kernels if they
  do not end on a 32-bit boundary.

* On the m68k architecture, struct members are not guaranteed to have an
  alignment greater than 16-bit, which is a problem when relying on
  implicit padding.

* Bitfields and enums generally work as one would expect them to,
  but some properties of them are implementation-defined, so it is better
  to avoid them completely in ioctl interfaces.

* ``char`` members can be either signed or unsigned, depending on
  the architecture, so the __u8 and __s8 types should be used for 8-bit
  integer values, though char arrays are clearer for fixed-length strings.

Information leaks
=================

Uninitialized data must not be copied back to user space, as this can
cause an information leak, which can be used to defeat kernel address
space layout randomization (KASLR), helping in an attack.

For this reason (and for compat support) it is best to avoid any
implicit padding in data structures.  Where there is implicit padding
in an existing structure, kernel drivers must be careful to fully
initialize an instance of the structure before copying it to user
space.  This is usually done by calling memset() before assigning to
individual members.

Subsystem abstractions
======================

While some device drivers implement their own ioctl function, most
subsystems implement the same command for multiple drivers.  Ideally the
subsystem has an .ioctl() handler that copies the arguments from and
to user space, passing them into subsystem specific callback functions
through normal kernel pointers.

This helps in various ways:

* Applications written for one driver are more likely to work for
  another one in the same subsystem if there are no subtle differences
  in the user space ABI.

* The complexity of user space access and data structure layout is done
  in one place, reducing the potential for implementation bugs.

* It is more likely to be reviewed by experienced developers
  that can spot problems in the interface when the ioctl is shared
  between multiple drivers than when it is only used in a single driver.

Alternatives to ioctl
=====================

There are many cases in which ioctl is not the best solution for a
problem. Alternatives include:

* System calls are a better choice for a system-wide feature that
  is not tied to a physical device or constrained by the file system
  permissions of a character device node

* netlink is the preferred way of configuring any network related
  objects through sockets.

* debugfs is used for ad-hoc interfaces for debugging functionality
  that does not need to be exposed as a stable interface to applications.

* sysfs is a good way to expose the state of an in-kernel object
  that is not tied to a file descriptor.

* configfs can be used for more complex configuration than sysfs

* A custom file system can provide extra flexibility with a simple
  user interface but adds a lot of complexity to the implementation.


code:
==============================
IPMB Driver for a Satellite MC
==============================

The Intelligent Platform Management Bus or IPMB, is an
I2C bus that provides a standardized interconnection between
different boards within a chassis. This interconnection is
between the baseboard management (BMC) and chassis electronics.
IPMB is also associated with the messaging protocol through the
IPMB bus.

The devices using the IPMB are usually management
controllers that perform management functions such as servicing
the front panel interface, monitoring the baseboard,
hot-swapping disk drivers in the system chassis, etc...

When an IPMB is implemented in the system, the BMC serves as
a controller to give system software access to the IPMB. The BMC
sends IPMI requests to a device (usually a Satellite Management
Controller or Satellite MC) via IPMB and the device
sends a response back to the BMC.

For more information on IPMB and the format of an IPMB message,
refer to the IPMB and IPMI specifications.

IPMB driver for Satellite MC
----------------------------

ipmb-dev-int - This is the driver needed on a Satellite MC to
receive IPMB messages from a BMC and send a response back.
This driver works with the I2C driver and a userspace
program such as OpenIPMI:

1) It is an I2C slave backend driver. So, it defines a callback
   function to set the Satellite MC as an I2C slave.
   This callback function handles the received IPMI requests.

2) It defines the read and write functions to enable a user
   space program (such as OpenIPMI) to communicate with the kernel.

Load the IPMB driver
--------------------

The driver needs to be loaded at boot time or manually first.
First, make sure you have the following in your config file:
CONFIG_IPMB_DEVICE_INTERFACE=y

1) If you want the driver to be loaded at boot time:

a) Add this entry to your ACPI table, under the appropriate SMBus::

     Device (SMB0) // Example SMBus host controller
     {
     Name (_HID, "<Vendor-Specific HID>") // Vendor-Specific HID
     Name (_UID, 0) // Unique ID of particular host controller
     :
     :
       Device (IPMB)
       {
         Name (_HID, "IPMB0001") // IPMB device interface
         Name (_UID, 0) // Unique device identifier
       }
     }

b) Example for device tree::

     &i2c2 {
            status = "okay";

            ipmb@10 {
                    compatible = "ipmb-dev";
                    reg = <0x10>;
                    i2c-protocol;
            };
     };

If xmit of data to be done using raw i2c block vs smbus
then "i2c-protocol" needs to be defined as above.

2) Manually from Linux::

     modprobe ipmb-dev-int

Instantiate the device
----------------------

After loading the driver, you can instantiate the device as
described in 'Documentation/i2c/instantiating-devices.rst'.
If you have multiple BMCs, each connected to your Satellite MC via
a different I2C bus, you can instantiate a device for each of
those BMCs.

The name of the instantiated device contains the I2C bus number
associated with it as follows::

  BMC1 ------ IPMB/I2C bus 1 ---------|   /dev/ipmb-1
				Satellite MC
  BMC1 ------ IPMB/I2C bus 2 ---------|   /dev/ipmb-2

For instance, you can instantiate the ipmb-dev-int device from
user space at the 7 bit address 0x10 on bus 2::

  # echo ipmb-dev 0x1010 > /sys/bus/i2c/devices/i2c-2/new_device

This will create the device file /dev/ipmb-2, which can be accessed
by the user space program. The device needs to be instantiated
before running the user space program.


code:
=====================
The Linux IPMI Driver
=====================

:Author: Corey Minyard <minyard@mvista.com> / <minyard@acm.org>

The Intelligent Platform Management Interface, or IPMI, is a
standard for controlling intelligent devices that monitor a system.
It provides for dynamic discovery of sensors in the system and the
ability to monitor the sensors and be informed when the sensor's
values change or go outside certain boundaries.  It also has a
standardized database for field-replaceable units (FRUs) and a watchdog
timer.

To use this, you need an interface to an IPMI controller in your
system (called a Baseboard Management Controller, or BMC) and
management software that can use the IPMI system.

This document describes how to use the IPMI driver for Linux.  If you
are not familiar with IPMI itself, see the web site at
https://www.intel.com/design/servers/ipmi/index.htm.  IPMI is a big
subject and I can't cover it all here!

Configuration
-------------

The Linux IPMI driver is modular, which means you have to pick several
things to have it work right depending on your hardware.  Most of
these are available in the 'Character Devices' menu then the IPMI
menu.

No matter what, you must pick 'IPMI top-level message handler' to use
IPMI.  What you do beyond that depends on your needs and hardware.

The message handler does not provide any user-level interfaces.
Kernel code (like the watchdog) can still use it.  If you need access
from userland, you need to select 'Device interface for IPMI' if you
want access through a device driver.

The driver interface depends on your hardware.  If your system
properly provides the SMBIOS info for IPMI, the driver will detect it
and just work.  If you have a board with a standard interface (These
will generally be either "KCS", "SMIC", or "BT", consult your hardware
manual), choose the 'IPMI SI handler' option.  A driver also exists
for direct I2C access to the IPMI management controller.  Some boards
support this, but it is unknown if it will work on every board.  For
this, choose 'IPMI SMBus handler', but be ready to try to do some
figuring to see if it will work on your system if the SMBIOS/APCI
information is wrong or not present.  It is fairly safe to have both
these enabled and let the drivers auto-detect what is present.

You should generally enable ACPI on your system, as systems with IPMI
can have ACPI tables describing them.

If you have a standard interface and the board manufacturer has done
their job correctly, the IPMI controller should be automatically
detected (via ACPI or SMBIOS tables) and should just work.  Sadly,
many boards do not have this information.  The driver attempts
standard defaults, but they may not work.  If you fall into this
situation, you need to read the section below named 'The SI Driver' or
"The SMBus Driver" on how to hand-configure your system.

IPMI defines a standard watchdog timer.  You can enable this with the
'IPMI Watchdog Timer' config option.  If you compile the driver into
the kernel, then via a kernel command-line option you can have the
watchdog timer start as soon as it initializes.  It also have a lot
of other options, see the 'Watchdog' section below for more details.
Note that you can also have the watchdog continue to run if it is
closed (by default it is disabled on close).  Go into the 'Watchdog
Cards' menu, enable 'Watchdog Timer Support', and enable the option
'Disable watchdog shutdown on close'.

IPMI systems can often be powered off using IPMI commands.  Select
'IPMI Poweroff' to do this.  The driver will auto-detect if the system
can be powered off by IPMI.  It is safe to enable this even if your
system doesn't support this option.  This works on ATCA systems, the
Radisys CPI1 card, and any IPMI system that supports standard chassis
management commands.

If you want the driver to put an event into the event log on a panic,
enable the 'Generate a panic event to all BMCs on a panic' option.  If
you want the whole panic string put into the event log using OEM
events, enable the 'Generate OEM events containing the panic string'
option.  You can also enable these dynamically by setting the module
parameter named "panic_op" in the ipmi_msghandler module to "event"
or "string".  Setting that parameter to "none" disables this function.

Basic Design
------------

The Linux IPMI driver is designed to be very modular and flexible, you
only need to take the pieces you need and you can use it in many
different ways.  Because of that, it's broken into many chunks of
code.  These chunks (by module name) are:

ipmi_msghandler - This is the central piece of software for the IPMI
system.  It handles all messages, message timing, and responses.  The
IPMI users tie into this, and the IPMI physical interfaces (called
System Management Interfaces, or SMIs) also tie in here.  This
provides the kernelland interface for IPMI, but does not provide an
interface for use by application processes.

ipmi_devintf - This provides a userland IOCTL interface for the IPMI
driver, each open file for this device ties in to the message handler
as an IPMI user.

ipmi_si - A driver for various system interfaces.  This supports KCS,
SMIC, and BT interfaces.  Unless you have an SMBus interface or your
own custom interface, you probably need to use this.

ipmi_ssif - A driver for accessing BMCs on the SMBus. It uses the
I2C kernel driver's SMBus interfaces to send and receive IPMI messages
over the SMBus.

ipmi_powernv - A driver for access BMCs on POWERNV systems.

ipmi_watchdog - IPMI requires systems to have a very capable watchdog
timer.  This driver implements the standard Linux watchdog timer
interface on top of the IPMI message handler.

ipmi_poweroff - Some systems support the ability to be turned off via
IPMI commands.

bt-bmc - This is not part of the main driver, but instead a driver for
accessing a BMC-side interface of a BT interface.  It is used on BMCs
running Linux to provide an interface to the host.

These are all individually selectable via configuration options.

Much documentation for the interface is in the include files.  The
IPMI include files are:

linux/ipmi.h - Contains the user interface and IOCTL interface for IPMI.

linux/ipmi_smi.h - Contains the interface for system management interfaces
(things that interface to IPMI controllers) to use.

linux/ipmi_msgdefs.h - General definitions for base IPMI messaging.

Addressing
----------

The IPMI addressing works much like IP addresses, you have an overlay
to handle the different address types.  The overlay is::

  struct ipmi_addr
  {
	int   addr_type;
	short channel;
	char  data[IPMI_MAX_ADDR_SIZE];
  };

The addr_type determines what the address really is.  The driver
currently understands two different types of addresses.

"System Interface" addresses are defined as::

  struct ipmi_system_interface_addr
  {
	int   addr_type;
	short channel;
  };

and the type is IPMI_SYSTEM_INTERFACE_ADDR_TYPE.  This is used for talking
straight to the BMC on the current card.  The channel must be
IPMI_BMC_CHANNEL.

Messages that are destined to go out on the IPMB bus going through the
BMC use the IPMI_IPMB_ADDR_TYPE address type.  The format is::

  struct ipmi_ipmb_addr
  {
	int           addr_type;
	short         channel;
	unsigned char slave_addr;
	unsigned char lun;
  };

The "channel" here is generally zero, but some devices support more
than one channel, it corresponds to the channel as defined in the IPMI
spec.

There is also an IPMB direct address for a situation where the sender
is directly on an IPMB bus and doesn't have to go through the BMC.
You can send messages to a specific management controller (MC) on the
IPMB using the IPMI_IPMB_DIRECT_ADDR_TYPE with the following format::

  struct ipmi_ipmb_direct_addr
  {
	int           addr_type;
	short         channel;
	unsigned char slave_addr;
	unsigned char rq_lun;
	unsigned char rs_lun;
  };

The channel is always zero.  You can also receive commands from other
MCs that you have registered to handle and respond to them, so you can
use this to implement a management controller on a bus..

Messages
--------

Messages are defined as::

  struct ipmi_msg
  {
	unsigned char netfn;
	unsigned char lun;
	unsigned char cmd;
	unsigned char *data;
	int           data_len;
  };

The driver takes care of adding/stripping the header information.  The
data portion is just the data to be send (do NOT put addressing info
here) or the response.  Note that the completion code of a response is
the first item in "data", it is not stripped out because that is how
all the messages are defined in the spec (and thus makes counting the
offsets a little easier :-).

When using the IOCTL interface from userland, you must provide a block
of data for "data", fill it, and set data_len to the length of the
block of data, even when receiving messages.  Otherwise the driver
will have no place to put the message.

Messages coming up from the message handler in kernelland will come in
as::

  struct ipmi_recv_msg
  {
	struct list_head link;

	/* The type of message as defined in the "Receive Types"
           defines above. */
	int         recv_type;

	ipmi_user_t      *user;
	struct ipmi_addr addr;
	long             msgid;
	struct ipmi_msg  msg;

	/* Call this when done with the message.  It will presumably free
	   the message and do any other necessary cleanup. */
	void (*done)(struct ipmi_recv_msg *msg);

	/* Place-holder for the data, don't make any assumptions about
	   the size or existence of this, since it may change. */
	unsigned char   msg_data[IPMI_MAX_MSG_LENGTH];
  };

You should look at the receive type and handle the message
appropriately.

The Upper Layer Interface (Message Handler)
-------------------------------------------

The upper layer of the interface provides the users with a consistent
view of the IPMI interfaces.  It allows multiple SMI interfaces to be
addressed (because some boards actually have multiple BMCs on them)
and the user should not have to care what type of SMI is below them.

Watching For Interfaces
^^^^^^^^^^^^^^^^^^^^^^^

When your code comes up, the IPMI driver may or may not have detected
if IPMI devices exist.  So you might have to defer your setup until
the device is detected, or you might be able to do it immediately.
To handle this, and to allow for discovery, you register an SMI
watcher with ipmi_smi_watcher_register() to iterate over interfaces
and tell you when they come and go.

Creating the User
^^^^^^^^^^^^^^^^^

To use the message handler, you must first create a user using
ipmi_create_user.  The interface number specifies which SMI you want
to connect to, and you must supply callback functions to be called
when data comes in.  The callback function can run at interrupt level,
so be careful using the callbacks.  This also allows to you pass in a
piece of data, the handler_data, that will be passed back to you on
all calls.

Once you are done, call ipmi_destroy_user() to get rid of the user.

From userland, opening the device automatically creates a user, and
closing the device automatically destroys the user.

Messaging
^^^^^^^^^

To send a message from kernel-land, the ipmi_request_settime() call does
pretty much all message handling.  Most of the parameter are
self-explanatory.  However, it takes a "msgid" parameter.  This is NOT
the sequence number of messages.  It is simply a long value that is
passed back when the response for the message is returned.  You may
use it for anything you like.

Responses come back in the function pointed to by the ipmi_recv_hndl
field of the "handler" that you passed in to ipmi_create_user().
Remember again, these may be running at interrupt level.  Remember to
look at the receive type, too.

From userland, you fill out an ipmi_req_t structure and use the
IPMICTL_SEND_COMMAND ioctl.  For incoming stuff, you can use select()
or poll() to wait for messages to come in.  However, you cannot use
read() to get them, you must call the IPMICTL_RECEIVE_MSG with the
ipmi_recv_t structure to actually get the message.  Remember that you
must supply a pointer to a block of data in the msg.data field, and
you must fill in the msg.data_len field with the size of the data.
This gives the receiver a place to actually put the message.

If the message cannot fit into the data you provide, you will get an
EMSGSIZE error and the driver will leave the data in the receive
queue.  If you want to get it and have it truncate the message, us
the IPMICTL_RECEIVE_MSG_TRUNC ioctl.

When you send a command (which is defined by the lowest-order bit of
the netfn per the IPMI spec) on the IPMB bus, the driver will
automatically assign the sequence number to the command and save the
command.  If the response is not receive in the IPMI-specified 5
seconds, it will generate a response automatically saying the command
timed out.  If an unsolicited response comes in (if it was after 5
seconds, for instance), that response will be ignored.

In kernelland, after you receive a message and are done with it, you
MUST call ipmi_free_recv_msg() on it, or you will leak messages.  Note
that you should NEVER mess with the "done" field of a message, that is
required to properly clean up the message.

Note that when sending, there is an ipmi_request_supply_msgs() call
that lets you supply the smi and receive message.  This is useful for
pieces of code that need to work even if the system is out of buffers
(the watchdog timer uses this, for instance).  You supply your own
buffer and own free routines.  This is not recommended for normal use,
though, since it is tricky to manage your own buffers.

Events and Incoming Commands
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The driver takes care of polling for IPMI events and receiving
commands (commands are messages that are not responses, they are
commands that other things on the IPMB bus have sent you).  To receive
these, you must register for them, they will not automatically be sent
to you.

To receive events, you must call ipmi_set_gets_events() and set the
"val" to non-zero.  Any events that have been received by the driver
since startup will immediately be delivered to the first user that
registers for events.  After that, if multiple users are registered
for events, they will all receive all events that come in.

For receiving commands, you have to individually register commands you
want to receive.  Call ipmi_register_for_cmd() and supply the netfn
and command name for each command you want to receive.  You also
specify a bitmask of the channels you want to receive the command from
(or use IPMI_CHAN_ALL for all channels if you don't care).  Only one
user may be registered for each netfn/cmd/channel, but different users
may register for different commands, or the same command if the
channel bitmasks do not overlap.

To respond to a received command, set the response bit in the returned
netfn, use the address from the received message, and use the same
msgid that you got in the receive message.

From userland, equivalent IOCTLs are provided to do these functions.

The Lower Layer (SMI) Interface
-------------------------------

As mentioned before, multiple SMI interfaces may be registered to the
message handler, each of these is assigned an interface number when
they register with the message handler.  They are generally assigned
in the order they register, although if an SMI unregisters and then
another one registers, all bets are off.

The ipmi_smi.h defines the interface for management interfaces, see
that for more details.

The SI Driver
-------------

The SI driver allows KCS, BT, and SMIC interfaces to be configured
in the system.  It discovers interfaces through a host of different
methods, depending on the system.

You can specify up to four interfaces on the module load line and
control some module parameters::

  modprobe ipmi_si.o type=<type1>,<type2>....
       ports=<port1>,<port2>... addrs=<addr1>,<addr2>...
       irqs=<irq1>,<irq2>...
       regspacings=<sp1>,<sp2>,... regsizes=<size1>,<size2>,...
       regshifts=<shift1>,<shift2>,...
       slave_addrs=<addr1>,<addr2>,...
       force_kipmid=<enable1>,<enable2>,...
       kipmid_max_busy_us=<ustime1>,<ustime2>,...
       unload_when_empty=[0|1]
       trydmi=[0|1] tryacpi=[0|1]
       tryplatform=[0|1] trypci=[0|1]

Each of these except try... items is a list, the first item for the
first interface, second item for the second interface, etc.

The si_type may be either "kcs", "smic", or "bt".  If you leave it blank, it
defaults to "kcs".

If you specify addrs as non-zero for an interface, the driver will
use the memory address given as the address of the device.  This
overrides si_ports.

If you specify ports as non-zero for an interface, the driver will
use the I/O port given as the device address.

If you specify irqs as non-zero for an interface, the driver will
attempt to use the given interrupt for the device.

The other try... items disable discovery by their corresponding
names.  These are all enabled by default, set them to zero to disable
them.  The tryplatform disables openfirmware.

The next three parameters have to do with register layout.  The
registers used by the interfaces may not appear at successive
locations and they may not be in 8-bit registers.  These parameters
allow the layout of the data in the registers to be more precisely
specified.

The regspacings parameter give the number of bytes between successive
register start addresses.  For instance, if the regspacing is set to 4
and the start address is 0xca2, then the address for the second
register would be 0xca6.  This defaults to 1.

The regsizes parameter gives the size of a register, in bytes.  The
data used by IPMI is 8-bits wide, but it may be inside a larger
register.  This parameter allows the read and write type to specified.
It may be 1, 2, 4, or 8.  The default is 1.

Since the register size may be larger than 32 bits, the IPMI data may not
be in the lower 8 bits.  The regshifts parameter give the amount to shift
the data to get to the actual IPMI data.

The slave_addrs specifies the IPMI address of the local BMC.  This is
usually 0x20 and the driver defaults to that, but in case it's not, it
can be specified when the driver starts up.

The force_ipmid parameter forcefully enables (if set to 1) or disables
(if set to 0) the kernel IPMI daemon.  Normally this is auto-detected
by the driver, but systems with broken interrupts might need an enable,
or users that don't want the daemon (don't need the performance, don't
want the CPU hit) can disable it.

If unload_when_empty is set to 1, the driver will be unloaded if it
doesn't find any interfaces or all the interfaces fail to work.  The
default is one.  Setting to 0 is useful with the hotmod, but is
obviously only useful for modules.

When compiled into the kernel, the parameters can be specified on the
kernel command line as::

  ipmi_si.type=<type1>,<type2>...
       ipmi_si.ports=<port1>,<port2>... ipmi_si.addrs=<addr1>,<addr2>...
       ipmi_si.irqs=<irq1>,<irq2>...
       ipmi_si.regspacings=<sp1>,<sp2>,...
       ipmi_si.regsizes=<size1>,<size2>,...
       ipmi_si.regshifts=<shift1>,<shift2>,...
       ipmi_si.slave_addrs=<addr1>,<addr2>,...
       ipmi_si.force_kipmid=<enable1>,<enable2>,...
       ipmi_si.kipmid_max_busy_us=<ustime1>,<ustime2>,...

It works the same as the module parameters of the same names.

If your IPMI interface does not support interrupts and is a KCS or
SMIC interface, the IPMI driver will start a kernel thread for the
interface to help speed things up.  This is a low-priority kernel
thread that constantly polls the IPMI driver while an IPMI operation
is in progress.  The force_kipmid module parameter will all the user to
force this thread on or off.  If you force it off and don't have
interrupts, the driver will run VERY slowly.  Don't blame me,
these interfaces suck.

Unfortunately, this thread can use a lot of CPU depending on the
interface's performance.  This can waste a lot of CPU and cause
various issues with detecting idle CPU and using extra power.  To
avoid this, the kipmid_max_busy_us sets the maximum amount of time, in
microseconds, that kipmid will spin before sleeping for a tick.  This
value sets a balance between performance and CPU waste and needs to be
tuned to your needs.  Maybe, someday, auto-tuning will be added, but
that's not a simple thing and even the auto-tuning would need to be
tuned to the user's desired performance.

The driver supports a hot add and remove of interfaces.  This way,
interfaces can be added or removed after the kernel is up and running.
This is done using /sys/modules/ipmi_si/parameters/hotmod, which is a
write-only parameter.  You write a string to this interface.  The string
has the format::

   <op1>[:op2[:op3...]]

The "op"s are::

   add|remove,kcs|bt|smic,mem|i/o,<address>[,<opt1>[,<opt2>[,...]]]

You can specify more than one interface on the line.  The "opt"s are::

   rsp=<regspacing>
   rsi=<regsize>
   rsh=<regshift>
   irq=<irq>
   ipmb=<ipmb slave addr>

and these have the same meanings as discussed above.  Note that you
can also use this on the kernel command line for a more compact format
for specifying an interface.  Note that when removing an interface,
only the first three parameters (si type, address type, and address)
are used for the comparison.  Any options are ignored for removing.

The SMBus Driver (SSIF)
-----------------------

The SMBus driver allows up to 4 SMBus devices to be configured in the
system.  By default, the driver will only register with something it
finds in DMI or ACPI tables.  You can change this
at module load time (for a module) with::

  modprobe ipmi_ssif.o
	addr=<i2caddr1>[,<i2caddr2>[,...]]
	adapter=<adapter1>[,<adapter2>[...]]
	dbg=<flags1>,<flags2>...
	slave_addrs=<addr1>,<addr2>,...
	tryacpi=[0|1] trydmi=[0|1]
	[dbg_probe=1]
	alerts_broken

The addresses are normal I2C addresses.  The adapter is the string
name of the adapter, as shown in /sys/class/i2c-adapter/i2c-<n>/name.
It is *NOT* i2c-<n> itself.  Also, the comparison is done ignoring
spaces, so if the name is "This is an I2C chip" you can say
adapter_name=ThisisanI2cchip.  This is because it's hard to pass in
spaces in kernel parameters.

The debug flags are bit flags for each BMC found, they are:
IPMI messages: 1, driver state: 2, timing: 4, I2C probe: 8

The tryxxx parameters can be used to disable detecting interfaces
from various sources.

Setting dbg_probe to 1 will enable debugging of the probing and
detection process for BMCs on the SMBusses.

The slave_addrs specifies the IPMI address of the local BMC.  This is
usually 0x20 and the driver defaults to that, but in case it's not, it
can be specified when the driver starts up.

alerts_broken does not enable SMBus alert for SSIF. Otherwise SMBus
alert will be enabled on supported hardware.

Discovering the IPMI compliant BMC on the SMBus can cause devices on
the I2C bus to fail. The SMBus driver writes a "Get Device ID" IPMI
message as a block write to the I2C bus and waits for a response.
This action can be detrimental to some I2C devices. It is highly
recommended that the known I2C address be given to the SMBus driver in
the smb_addr parameter unless you have DMI or ACPI data to tell the
driver what to use.

When compiled into the kernel, the addresses can be specified on the
kernel command line as::

  ipmb_ssif.addr=<i2caddr1>[,<i2caddr2>[...]]
	ipmi_ssif.adapter=<adapter1>[,<adapter2>[...]]
	ipmi_ssif.dbg=<flags1>[,<flags2>[...]]
	ipmi_ssif.dbg_probe=1
	ipmi_ssif.slave_addrs=<addr1>[,<addr2>[...]]
	ipmi_ssif.tryacpi=[0|1] ipmi_ssif.trydmi=[0|1]

These are the same options as on the module command line.

The I2C driver does not support non-blocking access or polling, so
this driver cannod to IPMI panic events, extend the watchdog at panic
time, or other panic-related IPMI functions without special kernel
patches and driver modifications.  You can get those at the openipmi
web page.

The driver supports a hot add and remove of interfaces through the I2C
sysfs interface.

The IPMI IPMB Driver
--------------------

This driver is for supporting a system that sits on an IPMB bus; it
allows the interface to look like a normal IPMI interface.  Sending
system interface addressed messages to it will cause the message to go
to the registered BMC on the system (default at IPMI address 0x20).

It also allows you to directly address other MCs on the bus using the
ipmb direct addressing.  You can receive commands from other MCs on
the bus and they will be handled through the normal received command
mechanism described above.

Parameters are::

  ipmi_ipmb.bmcaddr=<address to use for system interface addresses messages>
	ipmi_ipmb.retry_time_ms=<Time between retries on IPMB>
	ipmi_ipmb.max_retries=<Number of times to retry a message>

Loading the module will not result in the driver automatcially
starting unless there is device tree information setting it up.  If
you want to instantiate one of these by hand, do::

  echo ipmi-ipmb <addr> > /sys/class/i2c-dev/i2c-<n>/device/new_device

Note that the address you give here is the I2C address, not the IPMI
address.  So if you want your MC address to be 0x60, you put 0x30
here.  See the I2C driver info for more details.

Command bridging to other IPMB busses through this interface does not
work.  The receive message queue is not implemented, by design.  There
is only one receive message queue on a BMC, and that is meant for the
host drivers, not something on the IPMB bus.

A BMC may have multiple IPMB busses, which bus your device sits on
depends on how the system is wired.  You can fetch the channels with
"ipmitool channel info <n>" where <n> is the channel, with the
channels being 0-7 and try the IPMB channels.

Other Pieces
------------

Get the detailed info related with the IPMI device
--------------------------------------------------

Some users need more detailed information about a device, like where
the address came from or the raw base device for the IPMI interface.
You can use the IPMI smi_watcher to catch the IPMI interfaces as they
come or go, and to grab the information, you can use the function
ipmi_get_smi_info(), which returns the following structure::

  struct ipmi_smi_info {
	enum ipmi_addr_src addr_src;
	struct device *dev;
	union {
		struct {
			void *acpi_handle;
		} acpi_info;
	} addr_info;
  };

Currently special info for only for SI_ACPI address sources is
returned.  Others may be added as necessary.

Note that the dev pointer is included in the above structure, and
assuming ipmi_smi_get_info returns success, you must call put_device
on the dev pointer.

Watchdog
--------

A watchdog timer is provided that implements the Linux-standard
watchdog timer interface.  It has three module parameters that can be
used to control it::

  modprobe ipmi_watchdog timeout=<t> pretimeout=<t> action=<action type>
      preaction=<preaction type> preop=<preop type> start_now=x
      nowayout=x ifnum_to_use=n panic_wdt_timeout=<t>

ifnum_to_use specifies which interface the watchdog timer should use.
The default is -1, which means to pick the first one registered.

The timeout is the number of seconds to the action, and the pretimeout
is the amount of seconds before the reset that the pre-timeout panic will
occur (if pretimeout is zero, then pretimeout will not be enabled).  Note
that the pretimeout is the time before the final timeout.  So if the
timeout is 50 seconds and the pretimeout is 10 seconds, then the pretimeout
will occur in 40 second (10 seconds before the timeout). The panic_wdt_timeout
is the value of timeout which is set on kernel panic, in order to let actions
such as kdump to occur during panic.

The action may be "reset", "power_cycle", or "power_off", and
specifies what to do when the timer times out, and defaults to
"reset".

The preaction may be "pre_smi" for an indication through the SMI
interface, "pre_int" for an indication through the SMI with an
interrupts, and "pre_nmi" for a NMI on a preaction.  This is how
the driver is informed of the pretimeout.

The preop may be set to "preop_none" for no operation on a pretimeout,
"preop_panic" to set the preoperation to panic, or "preop_give_data"
to provide data to read from the watchdog device when the pretimeout
occurs.  A "pre_nmi" setting CANNOT be used with "preop_give_data"
because you can't do data operations from an NMI.

When preop is set to "preop_give_data", one byte comes ready to read
on the device when the pretimeout occurs.  Select and fasync work on
the device, as well.

If start_now is set to 1, the watchdog timer will start running as
soon as the driver is loaded.

If nowayout is set to 1, the watchdog timer will not stop when the
watchdog device is closed.  The default value of nowayout is true
if the CONFIG_WATCHDOG_NOWAYOUT option is enabled, or false if not.

When compiled into the kernel, the kernel command line is available
for configuring the watchdog::

  ipmi_watchdog.timeout=<t> ipmi_watchdog.pretimeout=<t>
	ipmi_watchdog.action=<action type>
	ipmi_watchdog.preaction=<preaction type>
	ipmi_watchdog.preop=<preop type>
	ipmi_watchdog.start_now=x
	ipmi_watchdog.nowayout=x
	ipmi_watchdog.panic_wdt_timeout=<t>

The options are the same as the module parameter options.

The watchdog will panic and start a 120 second reset timeout if it
gets a pre-action.  During a panic or a reboot, the watchdog will
start a 120 timer if it is running to make sure the reboot occurs.

Note that if you use the NMI preaction for the watchdog, you MUST NOT
use the nmi watchdog.  There is no reasonable way to tell if an NMI
comes from the IPMI controller, so it must assume that if it gets an
otherwise unhandled NMI, it must be from IPMI and it will panic
immediately.

Once you open the watchdog timer, you must write a 'V' character to the
device to close it, or the timer will not stop.  This is a new semantic
for the driver, but makes it consistent with the rest of the watchdog
drivers in Linux.

Panic Timeouts
--------------

The OpenIPMI driver supports the ability to put semi-custom and custom
events in the system event log if a panic occurs.  if you enable the
'Generate a panic event to all BMCs on a panic' option, you will get
one event on a panic in a standard IPMI event format.  If you enable
the 'Generate OEM events containing the panic string' option, you will
also get a bunch of OEM events holding the panic string.

The field settings of the events are:

* Generator ID: 0x21 (kernel)
* EvM Rev: 0x03 (this event is formatting in IPMI 1.0 format)
* Sensor Type: 0x20 (OS critical stop sensor)
* Sensor #: The first byte of the panic string (0 if no panic string)
* Event Dir | Event Type: 0x6f (Assertion, sensor-specific event info)
* Event Data 1: 0xa1 (Runtime stop in OEM bytes 2 and 3)
* Event data 2: second byte of panic string
* Event data 3: third byte of panic string

See the IPMI spec for the details of the event layout.  This event is
always sent to the local management controller.  It will handle routing
the message to the right place

Other OEM events have the following format:

* Record ID (bytes 0-1): Set by the SEL.
* Record type (byte 2): 0xf0 (OEM non-timestamped)
* byte 3: The slave address of the card saving the panic
* byte 4: A sequence number (starting at zero)
  The rest of the bytes (11 bytes) are the panic string.  If the panic string
  is longer than 11 bytes, multiple messages will be sent with increasing
  sequence numbers.

Because you cannot send OEM events using the standard interface, this
function will attempt to find an SEL and add the events there.  It
will first query the capabilities of the local management controller.
If it has an SEL, then they will be stored in the SEL of the local
management controller.  If not, and the local management controller is
an event generator, the event receiver from the local management
controller will be queried and the events sent to the SEL on that
device.  Otherwise, the events go nowhere since there is nowhere to
send them.

Poweroff
--------

If the poweroff capability is selected, the IPMI driver will install
a shutdown function into the standard poweroff function pointer.  This
is in the ipmi_poweroff module.  When the system requests a powerdown,
it will send the proper IPMI commands to do this.  This is supported on
several platforms.

There is a module parameter named "poweroff_powercycle" that may
either be zero (do a power down) or non-zero (do a power cycle, power
the system off, then power it on in a few seconds).  Setting
ipmi_poweroff.poweroff_control=x will do the same thing on the kernel
command line.  The parameter is also available via the proc filesystem
in /proc/sys/dev/ipmi/poweroff_powercycle.  Note that if the system
does not support power cycling, it will always do the power off.

The "ifnum_to_use" parameter specifies which interface the poweroff
code should use.  The default is -1, which means to pick the first one
registered.

Note that if you have ACPI enabled, the system will prefer using ACPI to
power off.


code:
===========
ISA Drivers
===========

The following text is adapted from the commit message of the initial
commit of the ISA bus driver authored by Rene Herman.

During the recent "isa drivers using platform devices" discussion it was
pointed out that (ALSA) ISA drivers ran into the problem of not having
the option to fail driver load (device registration rather) upon not
finding their hardware due to a probe() error not being passed up
through the driver model. In the course of that, I suggested a separate
ISA bus might be best; Russell King agreed and suggested this bus could
use the .match() method for the actual device discovery.

The attached does this. For this old non (generically) discoverable ISA
hardware only the driver itself can do discovery so as a difference with
the platform_bus, this isa_bus also distributes match() up to the
driver.

As another difference: these devices only exist in the driver model due
to the driver creating them because it might want to drive them, meaning
that all device creation has been made internal as well.

The usage model this provides is nice, and has been acked from the ALSA
side by Takashi Iwai and Jaroslav Kysela. The ALSA driver module_init's
now (for oldisa-only drivers) become::

	static int __init alsa_card_foo_init(void)
	{
		return isa_register_driver(&snd_foo_isa_driver, SNDRV_CARDS);
	}

	static void __exit alsa_card_foo_exit(void)
	{
		isa_unregister_driver(&snd_foo_isa_driver);
	}

Quite like the other bus models therefore. This removes a lot of
duplicated init code from the ALSA ISA drivers.

The passed in isa_driver struct is the regular driver struct embedding a
struct device_driver, the normal probe/remove/shutdown/suspend/resume
callbacks, and as indicated that .match callback.

The "SNDRV_CARDS" you see being passed in is a "unsigned int ndev"
parameter, indicating how many devices to create and call our methods
with.

The platform_driver callbacks are called with a platform_device param;
the isa_driver callbacks are being called with a ``struct device *dev,
unsigned int id`` pair directly -- with the device creation completely
internal to the bus it's much cleaner to not leak isa_dev's by passing
them in at all. The id is the only thing we ever want other then the
struct device anyways, and it makes for nicer code in the callbacks as
well.

With this additional .match() callback ISA drivers have all options. If
ALSA would want to keep the old non-load behaviour, it could stick all
of the old .probe in .match, which would only keep them registered after
everything was found to be present and accounted for. If it wanted the
behaviour of always loading as it inadvertently did for a bit after the
changeover to platform devices, it could just not provide a .match() and
do everything in .probe() as before.

If it, as Takashi Iwai already suggested earlier as a way of following
the model from saner buses more closely, wants to load when a later bind
could conceivably succeed, it could use .match() for the prerequisites
(such as checking the user wants the card enabled and that port/irq/dma
values have been passed in) and .probe() for everything else. This is
the nicest model.

To the code...

This exports only two functions; isa_{,un}register_driver().

isa_register_driver() register's the struct device_driver, and then
loops over the passed in ndev creating devices and registering them.
This causes the bus match method to be called for them, which is::

	int isa_bus_match(struct device *dev, struct device_driver *driver)
	{
		struct isa_driver *isa_driver = to_isa_driver(driver);

		if (dev->platform_data == isa_driver) {
			if (!isa_driver->match ||
				isa_driver->match(dev, to_isa_dev(dev)->id))
				return 1;
			dev->platform_data = NULL;
		}
		return 0;
	}

The first thing this does is check if this device is in fact one of this
driver's devices by seeing if the device's platform_data pointer is set
to this driver. Platform devices compare strings, but we don't need to
do that with everything being internal, so isa_register_driver() abuses
dev->platform_data as a isa_driver pointer which we can then check here.
I believe platform_data is available for this, but if rather not, moving
the isa_driver pointer to the private struct isa_dev is ofcourse fine as
well.

Then, if the driver did not provide a .match, it matches. If it did,
the driver match() method is called to determine a match.

If it did **not** match, dev->platform_data is reset to indicate this to
isa_register_driver which can then unregister the device again.

If during all this, there's any error, or no devices matched at all
everything is backed out again and the error, or -ENODEV, is returned.

isa_unregister_driver() just unregisters the matched devices and the
driver itself.

module_isa_driver is a helper macro for ISA drivers which do not do
anything special in module init/exit. This eliminates a lot of
boilerplate code. Each module may only use this macro once, and calling
it replaces module_init and module_exit.

max_num_isa_dev is a macro to determine the maximum possible number of
ISA devices which may be registered in the I/O port address space given
the address extent of the ISA devices.


code:
==========================================================
ISA Plug & Play support by Jaroslav Kysela <perex@suse.cz>
==========================================================

Interface /proc/isapnp
======================

The interface has been removed. See pnp.txt for more details.

Interface /proc/bus/isapnp
==========================

This directory allows access to ISA PnP cards and logical devices.
The regular files contain the contents of ISA PnP registers for
a logical device.