code:
==========================================================================
RapidIO subsystem Channelized Messaging character device driver (rio_cm.c)
==========================================================================

1. Overview
===========

This device driver is the result of collaboration within the RapidIO.org
Software Task Group (STG) between Texas Instruments, Prodrive Technologies,
Nokia Networks, BAE and IDT.  Additional input was received from other members
of RapidIO.org.

The objective was to create a character mode driver interface which exposes
messaging capabilities of RapidIO endpoint devices (mports) directly
to applications, in a manner that allows the numerous and varied RapidIO
implementations to interoperate.

This driver (RIO_CM) provides to user-space applications shared access to
RapidIO mailbox messaging resources.

RapidIO specification (Part 2) defines that endpoint devices may have up to four
messaging mailboxes in case of multi-packet message (up to 4KB) and
up to 64 mailboxes if single-packet messages (up to 256 B) are used. In addition
to protocol definition limitations, a particular hardware implementation can
have reduced number of messaging mailboxes.  RapidIO aware applications must
therefore share the messaging resources of a RapidIO endpoint.

Main purpose of this device driver is to provide RapidIO mailbox messaging
capability to large number of user-space processes by introducing socket-like
operations using a single messaging mailbox.  This allows applications to
use the limited RapidIO messaging hardware resources efficiently.

Most of device driver's operations are supported through 'ioctl' system calls.

When loaded this device driver creates a single file system node named rio_cm
in /dev directory common for all registered RapidIO mport devices.

Following ioctl commands are available to user-space applications:

- RIO_CM_MPORT_GET_LIST:
    Returns to caller list of local mport devices that
    support messaging operations (number of entries up to RIO_MAX_MPORTS).
    Each list entry is combination of mport's index in the system and RapidIO
    destination ID assigned to the port.
- RIO_CM_EP_GET_LIST_SIZE:
    Returns number of messaging capable remote endpoints
    in a RapidIO network associated with the specified mport device.
- RIO_CM_EP_GET_LIST:
    Returns list of RapidIO destination IDs for messaging
    capable remote endpoints (peers) available in a RapidIO network associated
    with the specified mport device.
- RIO_CM_CHAN_CREATE:
    Creates RapidIO message exchange channel data structure
    with channel ID assigned automatically or as requested by a caller.
- RIO_CM_CHAN_BIND:
    Binds the specified channel data structure to the specified
    mport device.
- RIO_CM_CHAN_LISTEN:
    Enables listening for connection requests on the specified
    channel.
- RIO_CM_CHAN_ACCEPT:
    Accepts a connection request from peer on the specified
    channel. If wait timeout for this request is specified by a caller it is
    a blocking call. If timeout set to 0 this is non-blocking call - ioctl
    handler checks for a pending connection request and if one is not available
    exits with -EGAIN error status immediately.
- RIO_CM_CHAN_CONNECT:
    Sends a connection request to a remote peer/channel.
- RIO_CM_CHAN_SEND:
    Sends a data message through the specified channel.
    The handler for this request assumes that message buffer specified by
    a caller includes the reserved space for a packet header required by
    this driver.
- RIO_CM_CHAN_RECEIVE:
    Receives a data message through a connected channel.
    If the channel does not have an incoming message ready to return this ioctl
    handler will wait for new message until timeout specified by a caller
    expires. If timeout value is set to 0, ioctl handler uses a default value
    defined by MAX_SCHEDULE_TIMEOUT.
- RIO_CM_CHAN_CLOSE:
    Closes a specified channel and frees associated buffers.
    If the specified channel is in the CONNECTED state, sends close notification
    to the remote peer.

The ioctl command codes and corresponding data structures intended for use by
user-space applications are defined in 'include/uapi/linux/rio_cm_cdev.h'.

2. Hardware Compatibility
=========================

This device driver uses standard interfaces defined by kernel RapidIO subsystem
and therefore it can be used with any mport device driver registered by RapidIO
subsystem with limitations set by available mport HW implementation of messaging
mailboxes.

3. Module parameters
====================

- 'dbg_level'
      - This parameter allows to control amount of debug information
        generated by this device driver. This parameter is formed by set of
        bit masks that correspond to the specific functional block.
        For mask definitions see 'drivers/rapidio/devices/rio_cm.c'
        This parameter can be changed dynamically.
        Use CONFIG_RAPIDIO_DEBUG=y to enable debug output at the top level.

- 'cmbox'
      - Number of RapidIO mailbox to use (default value is 1).
        This parameter allows to set messaging mailbox number that will be used
        within entire RapidIO network. It can be used when default mailbox is
        used by other device drivers or is not supported by some nodes in the
        RapidIO network.

- 'chstart'
      - Start channel number for dynamic assignment. Default value - 256.
        Allows to exclude channel numbers below this parameter from dynamic
        allocation to avoid conflicts with software components that use
        reserved predefined channel numbers.

4. Known problems
=================

  None.

5. User-space Applications and API Library
==========================================

Messaging API library and applications that use this device driver are available
from RapidIO.org.

6. TODO List
============

- Add support for system notification messages (reserved channel 0).


code:
=============
Sysfs entries
=============

The RapidIO sysfs files have moved to:
Documentation/ABI/testing/sysfs-bus-rapidio and
Documentation/ABI/testing/sysfs-class-rapidio

repo_name: angery/linux


code:
=========================================================================
RapidIO subsystem mport driver for IDT Tsi721 PCI Express-to-SRIO bridge.
=========================================================================

1. Overview
===========

This driver implements all currently defined RapidIO mport callback functions.
It supports maintenance read and write operations, inbound and outbound RapidIO
doorbells, inbound maintenance port-writes and RapidIO messaging.

To generate SRIO maintenance transactions this driver uses one of Tsi721 DMA
channels. This mechanism provides access to larger range of hop counts and
destination IDs without need for changes in outbound window translation.

RapidIO messaging support uses dedicated messaging channels for each mailbox.
For inbound messages this driver uses destination ID matching to forward messages
into the corresponding message queue. Messaging callbacks are implemented to be
fully compatible with RIONET driver (Ethernet over RapidIO messaging services).

1. Module parameters:

- 'dbg_level'
      - This parameter allows to control amount of debug information
        generated by this device driver. This parameter is formed by set of
        This parameter can be changed bit masks that correspond to the specific
        functional block.
        For mask definitions see 'drivers/rapidio/devices/tsi721.h'
        This parameter can be changed dynamically.
        Use CONFIG_RAPIDIO_DEBUG=y to enable debug output at the top level.

- 'dma_desc_per_channel'
      - This parameter defines number of hardware buffer
        descriptors allocated for each registered Tsi721 DMA channel.
        Its default value is 128.

- 'dma_txqueue_sz'
      - DMA transactions queue size. Defines number of pending
        transaction requests that can be accepted by each DMA channel.
        Default value is 16.

- 'dma_sel'
      - DMA channel selection mask. Bitmask that defines which hardware
        DMA channels (0 ... 6) will be registered with DmaEngine core.
        If bit is set to 1, the corresponding DMA channel will be registered.
        DMA channels not selected by this mask will not be used by this device
        driver. Default value is 0x7f (use all channels).

- 'pcie_mrrs'
      - override value for PCIe Maximum Read Request Size (MRRS).
        This parameter gives an ability to override MRRS value set during PCIe
        configuration process. Tsi721 supports read request sizes up to 4096B.
        Value for this parameter must be set as defined by PCIe specification:
        0 = 128B, 1 = 256B, 2 = 512B, 3 = 1024B, 4 = 2048B and 5 = 4096B.
        Default value is '-1' (= keep platform setting).

- 'mbox_sel'
      - RIO messaging MBOX selection mask. This is a bitmask that defines
        messaging MBOXes are managed by this device driver. Mask bits 0 - 3
        correspond to MBOX0 - MBOX3. MBOX is under driver's control if the
        corresponding bit is set to '1'. Default value is 0x0f (= all).

2. Known problems
=================

  None.

3. DMA Engine Support
=====================

Tsi721 mport driver supports DMA data transfers between local system memory and
remote RapidIO devices. This functionality is implemented according to SLAVE
mode API defined by common Linux kernel DMA Engine framework.

Depending on system requirements RapidIO DMA operations can be included/excluded
by setting CONFIG_RAPIDIO_DMA_ENGINE option. Tsi721 miniport driver uses seven
out of eight available BDMA channels to support DMA data transfers.
One BDMA channel is reserved for generation of maintenance read/write requests.

If Tsi721 mport driver have been built with RAPIDIO_DMA_ENGINE support included,
this driver will accept DMA-specific module parameter:

  "dma_desc_per_channel"
			 - defines number of hardware buffer descriptors used by
                           each BDMA channel of Tsi721 (by default - 128).

4. Version History

  =====   ====================================================================
  1.1.0   DMA operations re-worked to support data scatter/gather lists larger
          than hardware buffer descriptors ring.
  1.0.0   Initial driver release.
  =====   ====================================================================

5.  License
===========

  Copyright(c) 2011 Integrated Device Technology, Inc. All rights reserved.

  This program is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by the Free
  Software Foundation; either version 2 of the License, or (at your option)
  any later version.

  This program is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
  more details.

  You should have received a copy of the GNU General Public License along with
  this program; if not, write to the Free Software Foundation, Inc.,
  59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


code:
.. Copyright 2007-2008 Wolfson Microelectronics

..   This documentation is free software; you can redistribute
..   it and/or modify it under the terms of the GNU General Public
..   License version 2 as published by the Free Software Foundation.

=================================
Voltage and current regulator API
=================================

:Author: Liam Girdwood
:Author: Mark Brown

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

This framework is designed to provide a standard kernel interface to
control voltage and current regulators.

The intention is to allow systems to dynamically control regulator power
output in order to save power and prolong battery life. This applies to
both voltage regulators (where voltage output is controllable) and
current sinks (where current limit is controllable).

Note that additional (and currently more complete) documentation is
available in the Linux kernel source under
``Documentation/power/regulator``.

Glossary
--------

The regulator API uses a number of terms which may not be familiar:

Regulator

    Electronic device that supplies power to other devices. Most regulators
    can enable and disable their output and some can also control their
    output voltage or current.

Consumer

    Electronic device which consumes power provided by a regulator. These
    may either be static, requiring only a fixed supply, or dynamic,
    requiring active management of the regulator at runtime.

Power Domain

    The electronic circuit supplied by a given regulator, including the
    regulator and all consumer devices. The configuration of the regulator
    is shared between all the components in the circuit.

Power Management Integrated Circuit (PMIC)

    An IC which contains numerous regulators and often also other
    subsystems. In an embedded system the primary PMIC is often equivalent
    to a combination of the PSU and southbridge in a desktop system.

Consumer driver interface
=========================

This offers a similar API to the kernel clock framework. Consumer
drivers use `get <#API-regulator-get>`__ and
`put <#API-regulator-put>`__ operations to acquire and release
regulators. Functions are provided to `enable <#API-regulator-enable>`__
and `disable <#API-regulator-disable>`__ the regulator and to get and
set the runtime parameters of the regulator.

When requesting regulators consumers use symbolic names for their
supplies, such as "Vcc", which are mapped into actual regulator devices
by the machine interface.

A stub version of this API is provided when the regulator framework is
not in use in order to minimise the need to use ifdefs.

Enabling and disabling
----------------------

The regulator API provides reference counted enabling and disabling of
regulators. Consumer devices use the :c:func:`regulator_enable()` and
:c:func:`regulator_disable()` functions to enable and disable
regulators. Calls to the two functions must be balanced.

Note that since multiple consumers may be using a regulator and machine
constraints may not allow the regulator to be disabled there is no
guarantee that calling :c:func:`regulator_disable()` will actually
cause the supply provided by the regulator to be disabled. Consumer
drivers should assume that the regulator may be enabled at all times.

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

Some consumer devices may need to be able to dynamically configure their
supplies. For example, MMC drivers may need to select the correct
operating voltage for their cards. This may be done while the regulator
is enabled or disabled.

The :c:func:`regulator_set_voltage()` and
:c:func:`regulator_set_current_limit()` functions provide the primary
interface for this. Both take ranges of voltages and currents, supporting
drivers that do not require a specific value (eg, CPU frequency scaling
normally permits the CPU to use a wider range of supply voltages at lower
frequencies but does not require that the supply voltage be lowered). Where
an exact value is required both minimum and maximum values should be
identical.

Callbacks
---------

Callbacks may also be registered for events such as regulation failures.

Regulator driver interface
==========================

Drivers for regulator chips register the regulators with the regulator
core, providing operations structures to the core. A notifier interface
allows error conditions to be reported to the core.

Registration should be triggered by explicit setup done by the platform,
supplying a struct regulator_init_data for the regulator
containing constraint and supply information.

Machine interface
=================

This interface provides a way to define how regulators are connected to
consumers on a given system and what the valid operating parameters are
for the system.

Supplies
--------

Regulator supplies are specified using struct
:c:type:`regulator_consumer_supply`. This is done at driver registration
time as part of the machine constraints.

Constraints
-----------

As well as defining the connections the machine interface also provides
constraints defining the operations that clients are allowed to perform
and the parameters that may be set. This is required since generally
regulator devices will offer more flexibility than it is safe to use on
a given system, for example supporting higher supply voltages than the
consumers are rated for.

This is done at driver registration time` by providing a
struct regulation_constraints.

The constraints may also specify an initial configuration for the
regulator in the constraints, which is particularly useful for use with
static consumers.

API reference
=============

Due to limitations of the kernel documentation framework and the
existing layout of the source code the entire regulator API is
documented here.

.. kernel-doc:: include/linux/regulator/consumer.h
   :internal:

.. kernel-doc:: include/linux/regulator/machine.h
   :internal:

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

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


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

====================
Reset controller API
====================

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

Reset controllers are central units that control the reset signals to multiple
peripherals.
The reset controller API is split into two parts:
the `consumer driver interface <#consumer-driver-interface>`__ (`API reference
<#reset-consumer-api>`__), which allows peripheral drivers to request control
over their reset input signals, and the `reset controller driver interface
<#reset-controller-driver-interface>`__ (`API reference
<#reset-controller-driver-api>`__), which is used by drivers for reset
controller devices to register their reset controls to provide them to the
consumers.

While some reset controller hardware units also implement system restart
functionality, restart handlers are out of scope for the reset controller API.

Glossary
--------

The reset controller API uses these terms with a specific meaning:

Reset line

    Physical reset line carrying a reset signal from a reset controller
    hardware unit to a peripheral module.

Reset control

    Control method that determines the state of one or multiple reset lines.
    Most commonly this is a single bit in reset controller register space that
    either allows direct control over the physical state of the reset line, or
    is self-clearing and can be used to trigger a predetermined pulse on the
    reset line.
    In more complicated reset controls, a single trigger action can launch a
    carefully timed sequence of pulses on multiple reset lines.

Reset controller

    A hardware module that provides a number of reset controls to control a
    number of reset lines.

Reset consumer

    Peripheral module or external IC that is put into reset by the signal on a
    reset line.

Consumer driver interface
=========================

This interface provides an API that is similar to the kernel clock framework.
Consumer drivers use get and put operations to acquire and release reset
controls.
Functions are provided to assert and deassert the controlled reset lines,
trigger reset pulses, or to query reset line status.

When requesting reset controls, consumers can use symbolic names for their
reset inputs, which are mapped to an actual reset control on an existing reset
controller device by the core.

A stub version of this API is provided when the reset controller framework is
not in use in order to minimize the need to use ifdefs.

Shared and exclusive resets
---------------------------

The reset controller API provides either reference counted deassertion and
assertion or direct, exclusive control.
The distinction between shared and exclusive reset controls is made at the time
the reset control is requested, either via devm_reset_control_get_shared() or
via devm_reset_control_get_exclusive().
This choice determines the behavior of the API calls made with the reset
control.

Shared resets behave similarly to clocks in the kernel clock framework.
They provide reference counted deassertion, where only the first deassert,
which increments the deassertion reference count to one, and the last assert
which decrements the deassertion reference count back to zero, have a physical
effect on the reset line.

Exclusive resets on the other hand guarantee direct control.
That is, an assert causes the reset line to be asserted immediately, and a
deassert causes the reset line to be deasserted immediately.

Assertion and deassertion
-------------------------

Consumer drivers use the reset_control_assert() and reset_control_deassert()
functions to assert and deassert reset lines.
For shared reset controls, calls to the two functions must be balanced.

Note that since multiple consumers may be using a shared reset control, there
is no guarantee that calling reset_control_assert() on a shared reset control
will actually cause the reset line to be asserted.
Consumer drivers using shared reset controls should assume that the reset line
may be kept deasserted at all times.
The API only guarantees that the reset line can not be asserted as long as any
consumer has requested it to be deasserted.

Triggering
----------

Consumer drivers use reset_control_reset() to trigger a reset pulse on a
self-deasserting reset control.
In general, these resets can not be shared between multiple consumers, since
requesting a pulse from any consumer driver will reset all connected
peripherals.

The reset controller API allows requesting self-deasserting reset controls as
shared, but for those only the first trigger request causes an actual pulse to
be issued on the reset line.
All further calls to this function have no effect until all consumers have
called reset_control_rearm().
For shared reset controls, calls to the two functions must be balanced.
This allows devices that only require an initial reset at any point before the
driver is probed or resumed to share a pulsed reset line.

Querying
--------

Only some reset controllers support querying the current status of a reset
line, via reset_control_status().
If supported, this function returns a positive non-zero value if the given
reset line is asserted.
The reset_control_status() function does not accept a
`reset control array <#reset-control-arrays>`__ handle as its input parameter.

Optional resets
---------------

Often peripherals require a reset line on some platforms but not on others.
For this, reset controls can be requested as optional using
devm_reset_control_get_optional_exclusive() or
devm_reset_control_get_optional_shared().
These functions return a NULL pointer instead of an error when the requested
reset control is not specified in the device tree.
Passing a NULL pointer to the reset_control functions causes them to return
quietly without an error.

Reset control arrays
--------------------

Some drivers need to assert a bunch of reset lines in no particular order.
devm_reset_control_array_get() returns an opaque reset control handle that can
be used to assert, deassert, or trigger all specified reset controls at once.
The reset control API does not guarantee the order in which the individual
controls therein are handled.

Reset controller driver interface
=================================

Drivers for reset controller modules provide the functionality necessary to
assert or deassert reset signals, to trigger a reset pulse on a reset line, or
to query its current state.
All functions are optional.

Initialization
--------------

Drivers fill a struct :c:type:`reset_controller_dev` and register it with
reset_controller_register() in their probe function.
The actual functionality is implemented in callback functions via a struct
:c:type:`reset_control_ops`.

API reference
=============

The reset controller API is documented here in two parts:
the `reset consumer API <#reset-consumer-api>`__ and the `reset controller
driver API <#reset-controller-driver-api>`__.

Reset consumer API
------------------

Reset consumers can control a reset line using an opaque reset control handle,
which can be obtained from devm_reset_control_get_exclusive() or
devm_reset_control_get_shared().
Given the reset control, consumers can call reset_control_assert() and
reset_control_deassert(), trigger a reset pulse using reset_control_reset(), or
query the reset line status using reset_control_status().

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

.. kernel-doc:: drivers/reset/core.c
   :functions: reset_control_reset
               reset_control_assert
               reset_control_deassert
               reset_control_status
               reset_control_acquire
               reset_control_release
               reset_control_rearm
               reset_control_put
               of_reset_control_get_count
               of_reset_control_array_get
               devm_reset_control_array_get
               reset_control_get_count

Reset controller driver API
---------------------------

Reset controller drivers are supposed to implement the necessary functions in
a static constant structure :c:type:`reset_control_ops`, allocate and fill out
a struct :c:type:`reset_controller_dev`, and register it using
devm_reset_controller_register().

.. kernel-doc:: include/linux/reset-controller.h
   :internal:

.. kernel-doc:: drivers/reset/core.c
   :functions: of_reset_simple_xlate
               reset_controller_register
               reset_controller_unregister
               devm_reset_controller_register
               reset_controller_add_lookup


code:
===============================
rfkill - RF kill switch support
===============================

.. contents::
   :depth: 2

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

The rfkill subsystem provides a generic interface for disabling any radio
transmitter in the system. When a transmitter is blocked, it shall not
radiate any power.

The subsystem also provides the ability to react on button presses and
disable all transmitters of a certain type (or all). This is intended for
situations where transmitters need to be turned off, for example on
aircraft.

The rfkill subsystem has a concept of "hard" and "soft" block, which
differ little in their meaning (block == transmitters off) but rather in
whether they can be changed or not:

 - hard block
	read-only radio block that cannot be overridden by software

 - soft block
	writable radio block (need not be readable) that is set by
        the system software.

The rfkill subsystem has two parameters, rfkill.default_state and
rfkill.master_switch_mode, which are documented in
admin-guide/kernel-parameters.rst.

Implementation details
======================

The rfkill subsystem is composed of three main components:

 * the rfkill core,
 * the deprecated rfkill-input module (an input layer handler, being
   replaced by userspace policy code) and
 * the rfkill drivers.

The rfkill core provides API for kernel drivers to register their radio
transmitter with the kernel, methods for turning it on and off, and letting
the system know about hardware-disabled states that may be implemented on
the device.

The rfkill core code also notifies userspace of state changes, and provides
ways for userspace to query the current states. See the "Userspace support"
section below.

When the device is hard-blocked (either by a call to rfkill_set_hw_state()
or from query_hw_block), set_block() will be invoked for additional software
block, but drivers can ignore the method call since they can use the return
value of the function rfkill_set_hw_state() to sync the software state
instead of keeping track of calls to set_block(). In fact, drivers should
use the return value of rfkill_set_hw_state() unless the hardware actually
keeps track of soft and hard block separately.

Kernel API
==========

Drivers for radio transmitters normally implement an rfkill driver.

Platform drivers might implement input devices if the rfkill button is just
that, a button. If that button influences the hardware then you need to
implement an rfkill driver instead. This also applies if the platform provides
a way to turn on/off the transmitter(s).

For some platforms, it is possible that the hardware state changes during
suspend/hibernation, in which case it will be necessary to update the rfkill
core with the current state at resume time.

To create an rfkill driver, driver's Kconfig needs to have::

	depends on RFKILL || !RFKILL

to ensure the driver cannot be built-in when rfkill is modular. The !RFKILL
case allows the driver to be built when rfkill is not configured, in which
case all rfkill API can still be used but will be provided by static inlines
which compile to almost nothing.

Calling rfkill_set_hw_state() when a state change happens is required from
rfkill drivers that control devices that can be hard-blocked unless they also
assign the poll_hw_block() callback (then the rfkill core will poll the
device). Don't do this unless you cannot get the event in any other way.

rfkill provides per-switch LED triggers, which can be used to drive LEDs
according to the switch state (LED_FULL when blocked, LED_OFF otherwise).

Userspace support
=================

The recommended userspace interface to use is /dev/rfkill, which is a misc
character device that allows userspace to obtain and set the state of rfkill
devices and sets of devices. It also notifies userspace about device addition
and removal. The API is a simple read/write API that is defined in
linux/rfkill.h, with one ioctl that allows turning off the deprecated input
handler in the kernel for the transition period.

Except for the one ioctl, communication with the kernel is done via read()
and write() of instances of 'struct rfkill_event'. In this structure, the
soft and hard block are properly separated (unlike sysfs, see below) and
userspace is able to get a consistent snapshot of all rfkill devices in the
system. Also, it is possible to switch all rfkill drivers (or all drivers of
a specified type) into a state which also updates the default state for
hotplugged devices.

After an application opens /dev/rfkill, it can read the current state of all
devices. Changes can be obtained by either polling the descriptor for
hotplug or state change events or by listening for uevents emitted by the
rfkill core framework.

Additionally, each rfkill device is registered in sysfs and emits uevents.

rfkill devices issue uevents (with an action of "change"), with the following
environment variables set::

	RFKILL_NAME
	RFKILL_STATE
	RFKILL_TYPE

The content of these variables corresponds to the "name", "state" and
"type" sysfs files explained above.

For further details consult Documentation/ABI/stable/sysfs-class-rfkill.


code:
===================================
Writing s390 channel device drivers
===================================

:Author: Cornelia Huck

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

This document describes the interfaces available for device drivers that
drive s390 based channel attached I/O devices. This includes interfaces
for interaction with the hardware and interfaces for interacting with
the common driver core. Those interfaces are provided by the s390 common
I/O layer.

The document assumes a familarity with the technical terms associated
with the s390 channel I/O architecture. For a description of this
architecture, please refer to the "z/Architecture: Principles of
Operation", IBM publication no. SA22-7832.

While most I/O devices on a s390 system are typically driven through the
channel I/O mechanism described here, there are various other methods
(like the diag interface). These are out of the scope of this document.

The s390 common I/O layer also provides access to some devices that are
not strictly considered I/O devices. They are considered here as well,
although they are not the focus of this document.

Some additional information can also be found in the kernel source under
Documentation/s390/driver-model.rst.

The css bus
===========

The css bus contains the subchannels available on the system. They fall
into several categories:

* Standard I/O subchannels, for use by the system. They have a child
  device on the ccw bus and are described below.
* I/O subchannels bound to the vfio-ccw driver. See
  Documentation/s390/vfio-ccw.rst.
* Message subchannels. No Linux driver currently exists.
* CHSC subchannels (at most one). The chsc subchannel driver can be used
  to send asynchronous chsc commands.
* eADM subchannels. Used for talking to storage class memory.

The ccw bus
===========

The ccw bus typically contains the majority of devices available to a
s390 system. Named after the channel command word (ccw), the basic
command structure used to address its devices, the ccw bus contains
so-called channel attached devices. They are addressed via I/O
subchannels, visible on the css bus. A device driver for
channel-attached devices, however, will never interact with the
subchannel directly, but only via the I/O device on the ccw bus, the ccw
device.

I/O functions for channel-attached devices
------------------------------------------

Some hardware structures have been translated into C structures for use
by the common I/O layer and device drivers. For more information on the
hardware structures represented here, please consult the Principles of
Operation.

.. kernel-doc:: arch/s390/include/asm/cio.h
   :internal:

ccw devices
-----------

Devices that want to initiate channel I/O need to attach to the ccw bus.
Interaction with the driver core is done via the common I/O layer, which
provides the abstractions of ccw devices and ccw device drivers.

The functions that initiate or terminate channel I/O all act upon a ccw
device structure. Device drivers must not bypass those functions or
strange side effects may happen.

.. kernel-doc:: arch/s390/include/asm/ccwdev.h
   :internal:

.. kernel-doc:: drivers/s390/cio/device.c
   :export:

.. kernel-doc:: drivers/s390/cio/device_ops.c
   :export:

The channel-measurement facility
--------------------------------

The channel-measurement facility provides a means to collect measurement
data which is made available by the channel subsystem for each channel
attached device.

.. kernel-doc:: arch/s390/include/uapi/asm/cmb.h
   :internal:

.. kernel-doc:: drivers/s390/cio/cmf.c
   :export:

The ccwgroup bus
================

The ccwgroup bus only contains artificial devices, created by the user.
Many networking devices (e.g. qeth) are in fact composed of several ccw
devices (like read, write and data channel for qeth). The ccwgroup bus
provides a mechanism to create a meta-device which contains those ccw
devices as slave devices and can be associated with the netdevice.

ccw group devices
-----------------

.. kernel-doc:: arch/s390/include/asm/ccwgroup.h
   :internal:

.. kernel-doc:: drivers/s390/cio/ccwgroup.c
   :export:

Generic interfaces
==================

The following section contains interfaces in use not only by drivers
dealing with ccw devices, but drivers for various other s390 hardware
as well.

Adapter interrupts
------------------

The common I/O layer provides helper functions for dealing with adapter
interrupts and interrupt vectors.

.. kernel-doc:: drivers/s390/cio/airq.c
   :export:


code:
=====================
SCSI Interfaces Guide
=====================

:Author: James Bottomley
:Author: Rob Landley

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

Protocol vs bus
---------------

Once upon a time, the Small Computer Systems Interface defined both a
parallel I/O bus and a data protocol to connect a wide variety of
peripherals (disk drives, tape drives, modems, printers, scanners,
optical drives, test equipment, and medical devices) to a host computer.

Although the old parallel (fast/wide/ultra) SCSI bus has largely fallen
out of use, the SCSI command set is more widely used than ever to
communicate with devices over a number of different busses.

The `SCSI protocol <http://www.t10.org/scsi-3.htm>`__ is a big-endian
peer-to-peer packet based protocol. SCSI commands are 6, 10, 12, or 16
bytes long, often followed by an associated data payload.

SCSI commands can be transported over just about any kind of bus, and
are the default protocol for storage devices attached to USB, SATA, SAS,
Fibre Channel, FireWire, and ATAPI devices. SCSI packets are also
commonly exchanged over Infiniband,
`I2O <http://i2o.shadowconnect.com/faq.php>`__, TCP/IP
(`iSCSI <https://en.wikipedia.org/wiki/ISCSI>`__), even `Parallel
ports <http://cyberelk.net/tim/parport/parscsi.html>`__.

Design of the Linux SCSI subsystem
----------------------------------

The SCSI subsystem uses a three layer design, with upper, mid, and low
layers. Every operation involving the SCSI subsystem (such as reading a
sector from a disk) uses one driver at each of the 3 levels: one upper
layer driver, one lower layer driver, and the SCSI midlayer.

The SCSI upper layer provides the interface between userspace and the
kernel, in the form of block and char device nodes for I/O and ioctl().
The SCSI lower layer contains drivers for specific hardware devices.

In between is the SCSI mid-layer, analogous to a network routing layer
such as the IPv4 stack. The SCSI mid-layer routes a packet based data
protocol between the upper layer's /dev nodes and the corresponding
devices in the lower layer. It manages command queues, provides error
handling and power management functions, and responds to ioctl()
requests.

SCSI upper layer
================

The upper layer supports the user-kernel interface by providing device
nodes.

sd (SCSI Disk)
--------------

sd (sd_mod.o)

sr (SCSI CD-ROM)
----------------

sr (sr_mod.o)

st (SCSI Tape)
--------------

st (st.o)

sg (SCSI Generic)
-----------------

sg (sg.o)

ch (SCSI Media Changer)
-----------------------

ch (ch.c)

SCSI mid layer
==============

SCSI midlayer implementation
----------------------------

include/scsi/scsi_device.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. kernel-doc:: include/scsi/scsi_device.h
   :internal:

drivers/scsi/scsi.c
~~~~~~~~~~~~~~~~~~~

Main file for the SCSI midlayer.

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

drivers/scsi/scsicam.c
~~~~~~~~~~~~~~~~~~~~~~

`SCSI Common Access
Method <http://www.t10.org/ftp/t10/drafts/cam/cam-r12b.pdf>`__ support
functions, for use with HDIO_GETGEO, etc.

.. kernel-doc:: drivers/scsi/scsicam.c
   :export:

drivers/scsi/scsi_error.c
~~~~~~~~~~~~~~~~~~~~~~~~~~

Common SCSI error/timeout handling routines.

.. kernel-doc:: drivers/scsi/scsi_error.c
   :export:

drivers/scsi/scsi_devinfo.c
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Manage scsi_dev_info_list, which tracks blacklisted and whitelisted
devices.

.. kernel-doc:: drivers/scsi/scsi_devinfo.c
   :internal:

drivers/scsi/scsi_ioctl.c
~~~~~~~~~~~~~~~~~~~~~~~~~~

Handle ioctl() calls for SCSI devices.

.. kernel-doc:: drivers/scsi/scsi_ioctl.c
   :export:

drivers/scsi/scsi_lib.c
~~~~~~~~~~~~~~~~~~~~~~~~

SCSI queuing library.

.. kernel-doc:: drivers/scsi/scsi_lib.c
   :export:

drivers/scsi/scsi_lib_dma.c
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

SCSI library functions depending on DMA (map and unmap scatter-gather
lists).

.. kernel-doc:: drivers/scsi/scsi_lib_dma.c
   :export:

drivers/scsi/scsi_proc.c
~~~~~~~~~~~~~~~~~~~~~~~~~

The functions in this file provide an interface between the PROC file
system and the SCSI device drivers It is mainly used for debugging,
statistics and to pass information directly to the lowlevel driver. I.E.
plumbing to manage /proc/scsi/\*

.. kernel-doc:: drivers/scsi/scsi_proc.c
   :internal:

drivers/scsi/scsi_netlink.c
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Infrastructure to provide async events from transports to userspace via
netlink, using a single NETLINK_SCSITRANSPORT protocol for all
transports. See `the original patch
submission <http://marc.info/?l=linux-scsi&m=115507374832500&w=2>`__ for
more details.

.. kernel-doc:: drivers/scsi/scsi_netlink.c
   :internal:

drivers/scsi/scsi_scan.c
~~~~~~~~~~~~~~~~~~~~~~~~~

Scan a host to determine which (if any) devices are attached. The
general scanning/probing algorithm is as follows, exceptions are made to
it depending on device specific flags, compilation options, and global
variable (boot or module load time) settings. A specific LUN is scanned
via an INQUIRY command; if the LUN has a device attached, a scsi_device
is allocated and setup for it. For every id of every channel on the
given host, start by scanning LUN 0. Skip hosts that don't respond at
all to a scan of LUN 0. Otherwise, if LUN 0 has a device attached,
allocate and setup a scsi_device for it. If target is SCSI-3 or up,
issue a REPORT LUN, and scan all of the LUNs returned by the REPORT LUN;
else, sequentially scan LUNs up until some maximum is reached, or a LUN
is seen that cannot have a device attached to it.

.. kernel-doc:: drivers/scsi/scsi_scan.c
   :internal:

drivers/scsi/scsi_sysctl.c
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Set up the sysctl entry: "/dev/scsi/logging_level"
(DEV_SCSI_LOGGING_LEVEL) which sets/returns scsi_logging_level.

drivers/scsi/scsi_sysfs.c
~~~~~~~~~~~~~~~~~~~~~~~~~~

SCSI sysfs interface routines.

.. kernel-doc:: drivers/scsi/scsi_sysfs.c
   :export:

drivers/scsi/hosts.c
~~~~~~~~~~~~~~~~~~~~

mid to lowlevel SCSI driver interface

.. kernel-doc:: drivers/scsi/hosts.c
   :export:

drivers/scsi/scsi_common.c
~~~~~~~~~~~~~~~~~~~~~~~~~~

general support functions

.. kernel-doc:: drivers/scsi/scsi_common.c
   :export:

Transport classes
-----------------

Transport classes are service libraries for drivers in the SCSI lower
layer, which expose transport attributes in sysfs.

Fibre Channel transport
~~~~~~~~~~~~~~~~~~~~~~~

The file drivers/scsi/scsi_transport_fc.c defines transport attributes
for Fibre Channel.

.. kernel-doc:: drivers/scsi/scsi_transport_fc.c
   :export:

iSCSI transport class
~~~~~~~~~~~~~~~~~~~~~

The file drivers/scsi/scsi_transport_iscsi.c defines transport
attributes for the iSCSI class, which sends SCSI packets over TCP/IP
connections.

.. kernel-doc:: drivers/scsi/scsi_transport_iscsi.c
   :export:

Serial Attached SCSI (SAS) transport class
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The file drivers/scsi/scsi_transport_sas.c defines transport
attributes for Serial Attached SCSI, a variant of SATA aimed at large
high-end systems.

The SAS transport class contains common code to deal with SAS HBAs, an
aproximated representation of SAS topologies in the driver model, and
various sysfs attributes to expose these topologies and management
interfaces to userspace.

In addition to the basic SCSI core objects this transport class
introduces two additional intermediate objects: The SAS PHY as
represented by struct sas_phy defines an "outgoing" PHY on a SAS HBA or
Expander, and the SAS remote PHY represented by struct sas_rphy defines
an "incoming" PHY on a SAS Expander or end device. Note that this is
purely a software concept, the underlying hardware for a PHY and a
remote PHY is the exactly the same.

There is no concept of a SAS port in this code, users can see what PHYs
form a wide port based on the port_identifier attribute, which is the
same for all PHYs in a port.

.. kernel-doc:: drivers/scsi/scsi_transport_sas.c
   :export:

SATA transport class
~~~~~~~~~~~~~~~~~~~~

The SATA transport is handled by libata, which has its own book of
documentation in this directory.

Parallel SCSI (SPI) transport class
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The file drivers/scsi/scsi_transport_spi.c defines transport
attributes for traditional (fast/wide/ultra) SCSI busses.

.. kernel-doc:: drivers/scsi/scsi_transport_spi.c
   :export:

SCSI RDMA (SRP) transport class
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The file drivers/scsi/scsi_transport_srp.c defines transport
attributes for SCSI over Remote Direct Memory Access.

.. kernel-doc:: drivers/scsi/scsi_transport_srp.c
   :export:

SCSI lower layer
================

Host Bus Adapter transport types
--------------------------------

Many modern device controllers use the SCSI command set as a protocol to
communicate with their devices through many different types of physical
connections.

In SCSI language a bus capable of carrying SCSI commands is called a
"transport", and a controller connecting to such a bus is called a "host
bus adapter" (HBA).

Debug transport
~~~~~~~~~~~~~~~

The file drivers/scsi/scsi_debug.c simulates a host adapter with a
variable number of disks (or disk like devices) attached, sharing a
common amount of RAM. Does a lot of checking to make sure that we are
not getting blocks mixed up, and panics the kernel if anything out of
the ordinary is seen.

To be more realistic, the simulated devices have the transport
attributes of SAS disks.

For documentation see http://sg.danny.cz/sg/sdebug26.html

todo
~~~~

Parallel (fast/wide/ultra) SCSI, USB, SATA, SAS, Fibre Channel,
FireWire, ATAPI devices, Infiniband, I2O, Parallel ports,
netlink...


code:
====================
Low Level Serial API
====================

This document is meant as a brief overview of some aspects of the new serial
driver.  It is not complete, any questions you have should be directed to
<rmk@arm.linux.org.uk>

The reference implementation is contained within amba-pl011.c.

Low Level Serial Hardware Driver
--------------------------------

The low level serial hardware driver is responsible for supplying port
information (defined by uart_port) and a set of control methods (defined
by uart_ops) to the core serial driver.  The low level driver is also
responsible for handling interrupts for the port, and providing any
console support.

Console Support
---------------

The serial core provides a few helper functions.  This includes identifing
the correct port structure (via uart_get_console()) and decoding command line
arguments (uart_parse_options()).

There is also a helper function (uart_console_write()) which performs a
character by character write, translating newlines to CRLF sequences.
Driver writers are recommended to use this function rather than implementing
their own version.

Locking
-------

It is the responsibility of the low level hardware driver to perform the
necessary locking using port->lock.  There are some exceptions (which
are described in the struct uart_ops listing below.)

There are two locks.  A per-port spinlock, and an overall semaphore.

From the core driver perspective, the port->lock locks the following
data::

	port->mctrl
	port->icount
	port->state->xmit.head (circ_buf->head)
	port->state->xmit.tail (circ_buf->tail)

The low level driver is free to use this lock to provide any additional
locking.

The port_sem semaphore is used to protect against ports being added/
removed or reconfigured at inappropriate times. Since v2.6.27, this
semaphore has been the 'mutex' member of the tty_port struct, and
commonly referred to as the port mutex.

uart_ops
--------

.. kernel-doc:: include/linux/serial_core.h
   :identifiers: uart_ops

Other functions
---------------

.. kernel-doc:: drivers/tty/serial/serial_core.c
   :identifiers: uart_update_timeout uart_get_baud_rate uart_get_divisor
           uart_match_port uart_write_wakeup uart_register_driver
           uart_unregister_driver uart_suspend_port uart_resume_port
           uart_add_one_port uart_remove_one_port uart_console_write
           uart_parse_earlycon uart_parse_options uart_set_options
           uart_get_lsr_info uart_handle_dcd_change uart_handle_cts_change
           uart_try_toggle_sysrq uart_get_console

.. kernel-doc:: include/linux/serial_core.h
   :identifiers: uart_port_tx_limited uart_port_tx

Other notes
-----------

It is intended some day to drop the 'unused' entries from uart_port, and
allow low level drivers to register their own individual uart_port's with
the core.  This will allow drivers to use uart_port as a pointer to a
structure containing both the uart_port entry with their own extensions,
thus::

	struct my_port {
		struct uart_port	port;
		int			my_stuff;
	};

Modem control lines via GPIO
----------------------------

Some helpers are provided in order to set/get modem control lines via GPIO.

.. kernel-doc:: drivers/tty/serial/serial_mctrl_gpio.c
   :identifiers: mctrl_gpio_init mctrl_gpio_free mctrl_gpio_to_gpiod
           mctrl_gpio_set mctrl_gpio_get mctrl_gpio_enable_ms
           mctrl_gpio_disable_ms


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

==========================
Support for Serial devices
==========================

.. toctree::
    :maxdepth: 1

    driver

Serial drivers
==============

.. toctree::
    :maxdepth: 1

    serial-iso7816
    serial-rs485

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


code:
=============================
ISO7816 Serial Communications
=============================

1. Introduction
===============

  ISO/IEC7816 is a series of standards specifying integrated circuit cards (ICC)
  also known as smart cards.

2. Hardware-related considerations
==================================

  Some CPUs/UARTs (e.g., Microchip AT91) contain a built-in mode capable of
  handling communication with a smart card.

  For these microcontrollers, the Linux driver should be made capable of
  working in both modes, and proper ioctls (see later) should be made
  available at user-level to allow switching from one mode to the other, and
  vice versa.

3. Data Structures Already Available in the Kernel
==================================================

  The Linux kernel provides the serial_iso7816 structure (see [1]) to handle
  ISO7816 communications. This data structure is used to set and configure
  ISO7816 parameters in ioctls.

  Any driver for devices capable of working both as RS232 and ISO7816 should
  implement the iso7816_config callback in the uart_port structure. The
  serial_core calls iso7816_config to do the device specific part in response
  to TIOCGISO7816 and TIOCSISO7816 ioctls (see below). The iso7816_config
  callback receives a pointer to struct serial_iso7816.

4. Usage from user-level
========================

  From user-level, ISO7816 configuration can be get/set using the previous
  ioctls. For instance, to set ISO7816 you can use the following code::

	#include <linux/serial.h>

	/* Include definition for ISO7816 ioctls: TIOCSISO7816 and TIOCGISO7816 */
	#include <sys/ioctl.h>

	/* Open your specific device (e.g., /dev/mydevice): */
	int fd = open ("/dev/mydevice", O_RDWR);
	if (fd < 0) {
		/* Error handling. See errno. */
	}

	struct serial_iso7816 iso7816conf;

	/* Reserved fields as to be zeroed */
	memset(&iso7816conf, 0, sizeof(iso7816conf));

	/* Enable ISO7816 mode: */
	iso7816conf.flags |= SER_ISO7816_ENABLED;

	/* Select the protocol: */
	/* T=0 */
	iso7816conf.flags |= SER_ISO7816_T(0);
	/* or T=1 */
	iso7816conf.flags |= SER_ISO7816_T(1);

	/* Set the guard time: */
	iso7816conf.tg = 2;

	/* Set the clock frequency*/
	iso7816conf.clk = 3571200;

	/* Set transmission factors: */
	iso7816conf.sc_fi = 372;
	iso7816conf.sc_di = 1;

	if (ioctl(fd_usart, TIOCSISO7816, &iso7816conf) < 0) {
		/* Error handling. See errno. */
	}

	/* Use read() and write() syscalls here... */

	/* Close the device when finished: */
	if (close (fd) < 0) {
		/* Error handling. See errno. */
	}

5. References
=============

 [1]    include/uapi/linux/serial.h


code:
===========================
RS485 Serial Communications
===========================

1. Introduction
===============

   EIA-485, also known as TIA/EIA-485 or RS-485, is a standard defining the
   electrical characteristics of drivers and receivers for use in balanced
   digital multipoint systems.
   This standard is widely used for communications in industrial automation
   because it can be used effectively over long distances and in electrically
   noisy environments.

2. Hardware-related Considerations
==================================

   Some CPUs/UARTs (e.g., Atmel AT91 or 16C950 UART) contain a built-in
   half-duplex mode capable of automatically controlling line direction by
   toggling RTS or DTR signals. That can be used to control external
   half-duplex hardware like an RS485 transceiver or any RS232-connected
   half-duplex devices like some modems.

   For these microcontrollers, the Linux driver should be made capable of
   working in both modes, and proper ioctls (see later) should be made
   available at user-level to allow switching from one mode to the other, and
   vice versa.

3. Data Structures Already Available in the Kernel
==================================================

   The Linux kernel provides the struct serial_rs485 to handle RS485
   communications. This data structure is used to set and configure RS485
   parameters in the platform data and in ioctls.

   The device tree can also provide RS485 boot time parameters
   [#DT-bindings]_. The serial core fills the struct serial_rs485 from the
   values given by the device tree when the driver calls
   uart_get_rs485_mode().

   Any driver for devices capable of working both as RS232 and RS485 should
   implement the ``rs485_config`` callback and provide ``rs485_supported``
   in the ``struct uart_port``. The serial core calls ``rs485_config`` to do
   the device specific part in response to TIOCSRS485 ioctl (see below). The
   ``rs485_config`` callback receives a pointer to a sanitizated struct
   serial_rs485. The struct serial_rs485 userspace provides is sanitized
   before calling ``rs485_config`` using ``rs485_supported`` that indicates
   what RS485 features the driver supports for the ``struct uart_port``.
   TIOCGRS485 ioctl can be used to read back the struct serial_rs485
   matching to the current configuration.

.. kernel-doc:: include/uapi/linux/serial.h
   :identifiers: serial_rs485 uart_get_rs485_mode

4. Usage from user-level
========================

   From user-level, RS485 configuration can be get/set using the previous
   ioctls. For instance, to set RS485 you can use the following code::

	#include <linux/serial.h>

	/* Include definition for RS485 ioctls: TIOCGRS485 and TIOCSRS485 */
	#include <sys/ioctl.h>

	/* Open your specific device (e.g., /dev/mydevice): */
	int fd = open ("/dev/mydevice", O_RDWR);
	if (fd < 0) {
		/* Error handling. See errno. */
	}

	struct serial_rs485 rs485conf;

	/* Enable RS485 mode: */
	rs485conf.flags |= SER_RS485_ENABLED;

	/* Set logical level for RTS pin equal to 1 when sending: */
	rs485conf.flags |= SER_RS485_RTS_ON_SEND;
	/* or, set logical level for RTS pin equal to 0 when sending: */
	rs485conf.flags &= ~(SER_RS485_RTS_ON_SEND);

	/* Set logical level for RTS pin equal to 1 after sending: */
	rs485conf.flags |= SER_RS485_RTS_AFTER_SEND;
	/* or, set logical level for RTS pin equal to 0 after sending: */
	rs485conf.flags &= ~(SER_RS485_RTS_AFTER_SEND);

	/* Set rts delay before send, if needed: */
	rs485conf.delay_rts_before_send = ...;

	/* Set rts delay after send, if needed: */
	rs485conf.delay_rts_after_send = ...;

	/* Set this flag if you want to receive data even while sending data */
	rs485conf.flags |= SER_RS485_RX_DURING_TX;

	if (ioctl (fd, TIOCSRS485, &rs485conf) < 0) {
		/* Error handling. See errno. */
	}

	/* Use read() and write() syscalls here... */

	/* Close the device when finished: */
	if (close (fd) < 0) {
		/* Error handling. See errno. */
	}

5. Multipoint Addressing
========================

   The Linux kernel provides addressing mode for multipoint RS-485 serial
   communications line. The addressing mode is enabled with
   ``SER_RS485_ADDRB`` flag in struct serial_rs485. The struct serial_rs485
   has two additional flags and fields for enabling receive and destination
   addresses.

   Address mode flags:
	- ``SER_RS485_ADDRB``: Enabled addressing mode (sets also ADDRB in termios).
	- ``SER_RS485_ADDR_RECV``: Receive (filter) address enabled.
	- ``SER_RS485_ADDR_DEST``: Set destination address.

   Address fields (enabled with corresponding ``SER_RS485_ADDR_*`` flag):
	- ``addr_recv``: Receive address.
	- ``addr_dest``: Destination address.

   Once a receive address is set, the communication can occur only with the
   particular device and other peers are filtered out. It is left up to the
   receiver side to enforce the filtering. Receive address will be cleared
   if ``SER_RS485_ADDR_RECV`` is not set.

   Note: not all devices supporting RS485 support multipoint addressing.

6. References
=============

.. [#DT-bindings]	Documentation/devicetree/bindings/serial/rs485.txt


code:
============================
Linux kernel SLIMbus support
============================

Overview
========

What is SLIMbus?
----------------
SLIMbus (Serial Low Power Interchip Media Bus) is a specification developed by
MIPI (Mobile Industry Processor Interface) alliance. The bus uses master/slave
configuration, and is a 2-wire multi-drop implementation (clock, and data).

Currently, SLIMbus is used to interface between application processors of SoCs
(System-on-Chip) and peripheral components (typically codec). SLIMbus uses
Time-Division-Multiplexing to accommodate multiple data channels, and
a control channel.

The control channel is used for various control functions such as bus
management, configuration and status updates. These messages can be unicast (e.g.
reading/writing device specific values), or multicast (e.g. data channel
reconfiguration sequence is a broadcast message announced to all devices)

A data channel is used for data-transfer between 2 SLIMbus devices. Data
channel uses dedicated ports on the device.

Hardware description:
---------------------
SLIMbus specification has different types of device classifications based on
their capabilities.
A manager device is responsible for enumeration, configuration, and dynamic
channel allocation. Every bus has 1 active manager.

A generic device is a device providing application functionality (e.g. codec).

Framer device is responsible for clocking the bus, and transmitting frame-sync
and framing information on the bus.

Each SLIMbus component has an interface device for monitoring physical layer.

Typically each SoC contains SLIMbus component having 1 manager, 1 framer device,
1 generic device (for data channel support), and 1 interface device.
External peripheral SLIMbus component usually has 1 generic device (for
functionality/data channel support), and an associated interface device.
The generic device's registers are mapped as 'value elements' so that they can
be written/read using SLIMbus control channel exchanging control/status type of
information.
In case there are multiple framer devices on the same bus, manager device is
responsible to select the active-framer for clocking the bus.

Per specification, SLIMbus uses "clock gears" to do power management based on
current frequency and bandwidth requirements. There are 10 clock gears and each
gear changes the SLIMbus frequency to be twice its previous gear.

Each device has a 6-byte enumeration-address and the manager assigns every
device with a 1-byte logical address after the devices report presence on the
bus.

Software description:
---------------------
There are 2 types of SLIMbus drivers:

slim_controller represents a 'controller' for SLIMbus. This driver should
implement duties needed by the SoC (manager device, associated
interface device for monitoring the layers and reporting errors, default
framer device).

slim_device represents the 'generic device/component' for SLIMbus, and a
slim_driver should implement driver for that slim_device.

Device notifications to the driver:
-----------------------------------
Since SLIMbus devices have mechanisms for reporting their presence, the
framework allows drivers to bind when corresponding devices report their
presence on the bus.
However, it is possible that the driver needs to be probed
first so that it can enable corresponding SLIMbus device (e.g. power it up and/or
take it out of reset). To support that behavior, the framework allows drivers
to probe first as well  (e.g. using standard DeviceTree compatibility field).
This creates the necessity for the driver to know when the device is functional
(i.e. reported present). device_up callback is used for that reason when the
device reports present and is assigned a logical address by the controller.

Similarly, SLIMbus devices 'report absent' when they go down. A 'device_down'
callback notifies the driver when the device reports absent and its logical
address assignment is invalidated by the controller.

Another notification "boot_device" is used to notify the slim_driver when
controller resets the bus. This notification allows the driver to take necessary
steps to boot the device so that it's functional after the bus has been reset.

Driver and Controller APIs:
---------------------------
.. kernel-doc:: include/linux/slimbus.h
   :internal:

.. kernel-doc:: drivers/slimbus/slimbus.h
   :internal:

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

Clock-pause:
------------
SLIMbus mandates that a reconfiguration sequence (known as clock-pause) be
broadcast to all active devices on the bus before the bus can enter low-power
mode. Controller uses this sequence when it decides to enter low-power mode so
that corresponding clocks and/or power-rails can be turned off to save power.
Clock-pause is exited by waking up framer device (if controller driver initiates
exiting low power mode), or by toggling the data line (if a slave device wants
to initiate it).

Clock-pause APIs:
~~~~~~~~~~~~~~~~~
.. kernel-doc:: drivers/slimbus/sched.c
   :export:

Messaging:
----------
The framework supports regmap and read/write apis to exchange control-information
with a SLIMbus device. APIs can be synchronous or asynchronous.
The header file <linux/slimbus.h> has more documentation about messaging APIs.

Messaging APIs:
~~~~~~~~~~~~~~~
.. kernel-doc:: drivers/slimbus/messaging.c
   :export:

Streaming APIs:
~~~~~~~~~~~~~~~
.. kernel-doc:: drivers/slimbus/stream.c
   :export:


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

============
SM501 Driver
============

:Copyright: |copy| 2006, 2007 Simtec Electronics

The Silicon Motion SM501 multimedia companion chip is a multifunction device
which may provide numerous interfaces including USB host controller USB gadget,
asynchronous serial ports, audio functions, and a dual display video interface.
The device may be connected by PCI or local bus with varying functions enabled.

Core
----

The core driver in drivers/mfd provides common services for the
drivers which manage the specific hardware blocks. These services
include locking for common registers, clock control and resource
management.

The core registers drivers for both PCI and generic bus based
chips via the platform device and driver system.

On detection of a device, the core initialises the chip (which may
be specified by the platform data) and then exports the selected
peripheral set as platform devices for the specific drivers.

The core re-uses the platform device system as the platform device
system provides enough features to support the drivers without the
need to create a new bus-type and the associated code to go with it.

Resources
---------

Each peripheral has a view of the device which is implicitly narrowed to
the specific set of resources that peripheral requires in order to
function correctly.

The centralised memory allocation allows the driver to ensure that the
maximum possible resource allocation can be made to the video subsystem
as this is by-far the most resource-sensitive of the on-chip functions.

The primary issue with memory allocation is that of moving the video
buffers once a display mode is chosen. Indeed when a video mode change
occurs the memory footprint of the video subsystem changes.

Since video memory is difficult to move without changing the display
(unless sufficient contiguous memory can be provided for the old and new
modes simultaneously) the video driver fully utilises the memory area
given to it by aligning fb0 to the start of the area and fb1 to the end
of it. Any memory left over in the middle is used for the acceleration
functions, which are transient and thus their location is less critical
as it can be moved.

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

The platform device driver uses a set of platform data to pass
configurations through to the core and the subsidiary drivers
so that there can be support for more than one system carrying
an SM501 built into a single kernel image.

The PCI driver assumes that the PCI card behaves as per the Silicon
Motion reference design.

There is an errata (AB-5) affecting the selection of the
of the M1XCLK and M1CLK frequencies. These two clocks
must be sourced from the same PLL, although they can then
be divided down individually. If this is not set, then SM501 may
lock and hang the whole system. The driver will refuse to
attach if the PLL selection is different.


code:
========================
SoundWire Error Handling
========================

The SoundWire PHY was designed with care and errors on the bus are going to
be very unlikely, and if they happen it should be limited to single bit
errors. Examples of this design can be found in the synchronization
mechanism (sync loss after two errors) and short CRCs used for the Bulk
Register Access.

The errors can be detected with multiple mechanisms:

1. Bus clash or parity errors: This mechanism relies on low-level detectors
   that are independent of the payload and usages, and they cover both control
   and audio data. The current implementation only logs such errors.
   Improvements could be invalidating an entire programming sequence and
   restarting from a known position. In the case of such errors outside of a
   control/command sequence, there is no concealment or recovery for audio
   data enabled by the SoundWire protocol, the location of the error will also
   impact its audibility (most-significant bits will be more impacted in PCM),
   and after a number of such errors are detected the bus might be reset. Note
   that bus clashes due to programming errors (two streams using the same bit
   slots) or electrical issues during the transmit/receive transition cannot
   be distinguished, although a recurring bus clash when audio is enabled is a
   indication of a bus allocation issue. The interrupt mechanism can also help
   identify Slaves which detected a Bus Clash or a Parity Error, but they may
   not be responsible for the errors so resetting them individually is not a
   viable recovery strategy.

2. Command status: Each command is associated with a status, which only
   covers transmission of the data between devices. The ACK status indicates
   that the command was received and will be executed by the end of the
   current frame. A NAK indicates that the command was in error and will not
   be applied. In case of a bad programming (command sent to non-existent
   Slave or to a non-implemented register) or electrical issue, no response
   signals the command was ignored. Some Master implementations allow for a
   command to be retransmitted several times.  If the retransmission fails,
   backtracking and restarting the entire programming sequence might be a
   solution. Alternatively some implementations might directly issue a bus
   reset and re-enumerate all devices.

3. Timeouts: In a number of cases such as ChannelPrepare or
   ClockStopPrepare, the bus driver is supposed to poll a register field until
   it transitions to a NotFinished value of zero. The MIPI SoundWire spec 1.1
   does not define timeouts but the MIPI SoundWire DisCo document adds
   recommendation on timeouts. If such configurations do not complete, the
   driver will return a -ETIMEOUT. Such timeouts are symptoms of a faulty
   Slave device and are likely impossible to recover from.

Errors during global reconfiguration sequences are extremely difficult to
handle:

1. BankSwitch: An error during the last command issuing a BankSwitch is
   difficult to backtrack from. Retransmitting the Bank Switch command may be
   possible in a single segment setup, but this can lead to synchronization
   problems when enabling multiple bus segments (a command with side effects
   such as frame reconfiguration would be handled at different times). A global
   hard-reset might be the best solution.

Note that SoundWire does not provide a mechanism to detect illegal values
written in valid registers. In a number of cases the standard even mentions
that the Slave might behave in implementation-defined ways. The bus
implementation does not provide a recovery mechanism for such errors, Slave
or Master driver implementers are responsible for writing valid values in
valid registers and implement additional range checking if needed.


code:
=======================
SoundWire Documentation
=======================

.. toctree::
   :maxdepth: 1

   summary
   stream
   error_handling
   locking

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


code:
=================
SoundWire Locking
=================

This document explains locking mechanism of the SoundWire Bus. Bus uses
following locks in order to avoid race conditions in Bus operations on
shared resources.

  - Bus lock

  - Message lock

Bus lock
========

SoundWire Bus lock is a mutex and is part of Bus data structure
(sdw_bus) which is used for every Bus instance. This lock is used to
serialize each of the following operations(s) within SoundWire Bus instance.

  - Addition and removal of Slave(s), changing Slave status.

  - Prepare, Enable, Disable and De-prepare stream operations.

  - Access of Stream data structure.

Message lock
============

SoundWire message transfer lock. This mutex is part of
Bus data structure (sdw_bus). This lock is used to serialize the message
transfers (read/write) within a SoundWire Bus instance.

Below examples show how locks are acquired.

Example 1
---------

Message transfer.

  1. For every message transfer

     a. Acquire Message lock.

     b. Transfer message (Read/Write) to Slave1 or broadcast message on
        Bus in case of bank switch.

     c. Release Message lock

     ::

	+----------+                    +---------+
	|          |                    |         |
	|   Bus    |                    | Master  |
	|          |                    | Driver  |
	|          |                    |         |
	+----+-----+                    +----+----+
	     |                               |
	     |     bus->ops->xfer_msg()      |
	     <-------------------------------+   a. Acquire Message lock
	     |                               |   b. Transfer message
	     |                               |
	     +------------------------------->   c. Release Message lock
	     |    return success/error       |   d. Return success/error
	     |                               |
	     +                               +

Example 2
---------

Prepare operation.

  1. Acquire lock for Bus instance associated with Master 1.

  2. For every message transfer in Prepare operation

     a. Acquire Message lock.

     b. Transfer message (Read/Write) to Slave1 or broadcast message on
        Bus in case of bank switch.

     c. Release Message lock.

  3. Release lock for Bus instance associated with Master 1 ::

	+----------+                    +---------+
	|          |                    |         |
	|   Bus    |                    | Master  |
	|          |                    | Driver  |
	|          |                    |         |
	+----+-----+                    +----+----+
	     |                               |
	     |    sdw_prepare_stream()       |
	     <-------------------------------+   1. Acquire bus lock
	     |                               |   2. Perform stream prepare
	     |                               |
	     |                               |
	     |     bus->ops->xfer_msg()      |
	     <-------------------------------+   a. Acquire Message lock
	     |                               |   b. Transfer message
	     |                               |
	     +------------------------------->   c. Release Message lock
	     |    return success/error       |   d. Return success/error
	     |                               |
	     |                               |
	     |    return success/error       |   3. Release bus lock
	     +------------------------------->   4. Return success/error
	     |                               |
	     +                               +


code:
=========================
Audio Stream in SoundWire
=========================

An audio stream is a logical or virtual connection created between

  (1) System memory buffer(s) and Codec(s)

  (2) DSP memory buffer(s) and Codec(s)

  (3) FIFO(s) and Codec(s)

  (4) Codec(s) and Codec(s)

which is typically driven by a DMA(s) channel through the data link. An
audio stream contains one or more channels of data. All channels within
stream must have same sample rate and same sample size.

Assume a stream with two channels (Left & Right) is opened using SoundWire
interface. Below are some ways a stream can be represented in SoundWire.

Stream Sample in memory (System memory, DSP memory or FIFOs) ::

	-------------------------
	| L | R | L | R | L | R |
	-------------------------

Example 1: Stereo Stream with L and R channels is rendered from Master to
Slave. Both Master and Slave is using single port. ::

	+---------------+                    Clock Signal  +---------------+
	|    Master     +----------------------------------+     Slave     |
	|   Interface   |                                  |   Interface   |
	|               |                                  |       1       |
	|               |                     Data Signal  |               |
	|    L  +  R    +----------------------------------+    L  +  R    |
	|     (Data)    |     Data Direction               |     (Data)    |
	+---------------+  +----------------------->       +---------------+

Example 2: Stereo Stream with L and R channels is captured from Slave to
Master. Both Master and Slave is using single port. ::

	+---------------+                    Clock Signal  +---------------+
	|    Master     +----------------------------------+     Slave     |
	|   Interface   |                                  |   Interface   |
	|               |                                  |       1       |
	|               |                     Data Signal  |               |
	|    L  +  R    +----------------------------------+    L  +  R    |
	|     (Data)    |     Data Direction               |     (Data)    |
	+---------------+  <-----------------------+       +---------------+

Example 3: Stereo Stream with L and R channels is rendered by Master. Each
of the L and R channel is received by two different Slaves. Master and both
Slaves are using single port. ::

	+---------------+                    Clock Signal  +---------------+
	|    Master     +---------+------------------------+     Slave     |
	|   Interface   |         |                        |   Interface   |
	|               |         |                        |       1       |
	|               |         |           Data Signal  |               |
	|    L  +  R    +---+------------------------------+       L       |
	|     (Data)    |   |     |    Data Direction      |     (Data)    |
	+---------------+   |     |   +------------->      +---------------+
	                    |     |
	                    |     |
	                    |     |                        +---------------+
	                    |     +----------------------> |     Slave     |
	                    |                              |   Interface   |
	                    |                              |       2       |
	                    |                              |               |
	                    +----------------------------> |       R       |
	                                                   |     (Data)    |
	                                                   +---------------+

Example 4: Stereo Stream with L and R channels is rendered by
Master. Both of the L and R channels are received by two different
Slaves. Master and both Slaves are using single port handling
L+R. Each Slave device processes the L + R data locally, typically
based on static configuration or dynamic orientation, and may drive
one or more speakers. ::

	+---------------+                    Clock Signal  +---------------+
	|    Master     +---------+------------------------+     Slave     |
	|   Interface   |         |                        |   Interface   |
	|               |         |                        |       1       |
	|               |         |           Data Signal  |               |
	|    L  +  R    +---+------------------------------+     L + R     |
	|     (Data)    |   |     |    Data Direction      |     (Data)    |
	+---------------+   |     |   +------------->      +---------------+
	                    |     |
	                    |     |
	                    |     |                        +---------------+
	                    |     +----------------------> |     Slave     |
	                    |                              |   Interface   |
	                    |                              |       2       |
	                    |                              |               |
	                    +----------------------------> |     L + R     |
	                                                   |     (Data)    |
	                                                   +---------------+

Example 5: Stereo Stream with L and R channel is rendered by two different
Ports of the Master and is received by only single Port of the Slave
interface. ::

	+--------------------+
	|                    |
	|     +--------------+                             +----------------+
	|     |             ||                             |                |
	|     |  Data Port  ||  L Channel                  |                |
	|     |      1      |------------+                 |                |
	|     |  L Channel  ||           |                 +-----+----+     |
	|     |   (Data)    ||           |   L + R Channel ||    Data |     |
	| Master  +----------+           | +---+---------> ||    Port |     |
	| Interface          |           |                 ||     1   |     |
	|     +--------------+           |                 ||         |     |
	|     |             ||           |                 +----------+     |
	|     |  Data Port  |------------+                 |                |
	|     |      2      ||  R Channel                  |     Slave      |
	|     |  R Channel  ||                             |   Interface    |
	|     |   (Data)    ||                             |       1        |
	|     +--------------+         Clock Signal        |     L  +  R    |
	|                    +---------------------------> |      (Data)    |
	+--------------------+                             |                |
							   +----------------+

Example 6: Stereo Stream with L and R channel is rendered by 2 Masters, each
rendering one channel, and is received by two different Slaves, each
receiving one channel. Both Masters and both Slaves are using single port. ::

	+---------------+                    Clock Signal  +---------------+
	|    Master     +----------------------------------+     Slave     |
	|   Interface   |                                  |   Interface   |
	|       1       |                                  |       1       |
	|               |                     Data Signal  |               |
	|       L       +----------------------------------+       L       |
	|     (Data)    |     Data Direction               |     (Data)    |
	+---------------+  +----------------------->       +---------------+

	+---------------+                    Clock Signal  +---------------+
	|    Master     +----------------------------------+     Slave     |
	|   Interface   |                                  |   Interface   |
	|       2       |                                  |       2       |
	|               |                     Data Signal  |               |
	|       R       +----------------------------------+       R       |
	|     (Data)    |     Data Direction               |     (Data)    |
	+---------------+  +----------------------->       +---------------+

Example 7: Stereo Stream with L and R channel is rendered by 2
Masters, each rendering both channels. Each Slave receives L + R. This
is the same application as Example 4 but with Slaves placed on
separate links. ::

	+---------------+                    Clock Signal  +---------------+
	|    Master     +----------------------------------+     Slave     |
	|   Interface   |                                  |   Interface   |
	|       1       |                                  |       1       |
	|               |                     Data Signal  |               |
	|     L + R     +----------------------------------+     L + R     |
	|     (Data)    |     Data Direction               |     (Data)    |
	+---------------+  +----------------------->       +---------------+

	+---------------+                    Clock Signal  +---------------+
	|    Master     +----------------------------------+     Slave     |
	|   Interface   |                                  |   Interface   |
	|       2       |                                  |       2       |
	|               |                     Data Signal  |               |
	|     L + R     +----------------------------------+     L + R     |
	|     (Data)    |     Data Direction               |     (Data)    |
	+---------------+  +----------------------->       +---------------+

Example 8: 4-channel Stream is rendered by 2 Masters, each rendering a
2 channels. Each Slave receives 2 channels. ::

	+---------------+                    Clock Signal  +---------------+
	|    Master     +----------------------------------+     Slave     |
	|   Interface   |                                  |   Interface   |
	|       1       |                                  |       1       |
	|               |                     Data Signal  |               |
	|    L1 + R1    +----------------------------------+    L1 + R1    |
	|     (Data)    |     Data Direction               |     (Data)    |
	+---------------+  +----------------------->       +---------------+

	+---------------+                    Clock Signal  +---------------+
	|    Master     +----------------------------------+     Slave     |
	|   Interface   |                                  |   Interface   |
	|       2       |                                  |       2       |
	|               |                     Data Signal  |               |
	|     L2 + R2   +----------------------------------+    L2 + R2    |
	|     (Data)    |     Data Direction               |     (Data)    |
	+---------------+  +----------------------->       +---------------+

Note1: In multi-link cases like above, to lock, one would acquire a global
lock and then go on locking bus instances. But, in this case the caller
framework(ASoC DPCM) guarantees that stream operations on a card are
always serialized. So, there is no race condition and hence no need for
global lock.

Note2: A Slave device may be configured to receive all channels
transmitted on a link for a given Stream (Example 4) or just a subset
of the data (Example 3). The configuration of the Slave device is not
handled by a SoundWire subsystem API, but instead by the
snd_soc_dai_set_tdm_slot() API. The platform or machine driver will
typically configure which of the slots are used. For Example 4, the
same slots would be used by all Devices, while for Example 3 the Slave
Device1 would use e.g. Slot 0 and Slave device2 slot 1.

Note3: Multiple Sink ports can extract the same information for the
same bitSlots in the SoundWire frame, however multiple Source ports
shall be configured with different bitSlot configurations. This is the
same limitation as with I2S/PCM TDM usages.

SoundWire Stream Management flow
================================

Stream definitions
------------------

  (1) Current stream: This is classified as the stream on which operation has
      to be performed like prepare, enable, disable, de-prepare etc.

  (2) Active stream: This is classified as the stream which is already active
      on Bus other than current stream. There can be multiple active streams
      on the Bus.

SoundWire Bus manages stream operations for each stream getting
rendered/captured on the SoundWire Bus. This section explains Bus operations
done for each of the stream allocated/released on Bus. Following are the
stream states maintained by the Bus for each of the audio stream.

SoundWire stream states
-----------------------

Below shows the SoundWire stream states and state transition diagram. ::

	+-----------+     +------------+     +----------+     +----------+
	| ALLOCATED +---->| CONFIGURED +---->| PREPARED +---->| ENABLED  |
	|   STATE   |     |    STATE   |     |  STATE   |     |  STATE   |
	+-----------+     +------------+     +---+--+---+     +----+-----+
	                                         ^  ^              ^
				                 |  |              |
				               __|  |___________   |
				              |                 |  |
	                                      v                 |  v
	         +----------+           +-----+------+        +-+--+-----+
	         | RELEASED |<----------+ DEPREPARED |<-------+ DISABLED |
	         |  STATE   |           |   STATE    |        |  STATE   |
	         +----------+           +------------+        +----------+

NOTE: State transitions between ``SDW_STREAM_ENABLED`` and
``SDW_STREAM_DISABLED`` are only relevant when then INFO_PAUSE flag is
supported at the ALSA/ASoC level. Likewise the transition between
``SDW_DISABLED_STATE`` and ``SDW_PREPARED_STATE`` depends on the
INFO_RESUME flag.

NOTE2: The framework implements basic state transition checks, but
does not e.g. check if a transition from DISABLED to ENABLED is valid
on a specific platform. Such tests need to be added at the ALSA/ASoC
level.

Stream State Operations
-----------------------

Below section explains the operations done by the Bus on Master(s) and
Slave(s) as part of stream state transitions.

SDW_STREAM_ALLOCATED
~~~~~~~~~~~~~~~~~~~~

Allocation state for stream. This is the entry state
of the stream. Operations performed before entering in this state:

  (1) A stream runtime is allocated for the stream. This stream
      runtime is used as a reference for all the operations performed
      on the stream.

  (2) The resources required for holding stream runtime information are
      allocated and initialized. This holds all stream related information
      such as stream type (PCM/PDM) and parameters, Master and Slave
      interface associated with the stream, stream state etc.

After all above operations are successful, stream state is set to
``SDW_STREAM_ALLOCATED``.

Bus implements below API for allocate a stream which needs to be called once
per stream. From ASoC DPCM framework, this stream state maybe linked to
.startup() operation.

.. code-block:: c

  int sdw_alloc_stream(char * stream_name);

The SoundWire core provides a sdw_startup_stream() helper function,
typically called during a dailink .startup() callback, which performs
stream allocation and sets the stream pointer for all DAIs
connected to a stream.

SDW_STREAM_CONFIGURED
~~~~~~~~~~~~~~~~~~~~~

Configuration state of stream. Operations performed before entering in
this state:

  (1) The resources allocated for stream information in SDW_STREAM_ALLOCATED
      state are updated here. This includes stream parameters, Master(s)
      and Slave(s) runtime information associated with current stream.

  (2) All the Master(s) and Slave(s) associated with current stream provide
      the port information to Bus which includes port numbers allocated by
      Master(s) and Slave(s) for current stream and their channel mask.

After all above operations are successful, stream state is set to
``SDW_STREAM_CONFIGURED``.

Bus implements below APIs for CONFIG state which needs to be called by
the respective Master(s) and Slave(s) associated with stream. These APIs can
only be invoked once by respective Master(s) and Slave(s). From ASoC DPCM
framework, this stream state is linked to .hw_params() operation.

.. code-block:: c

  int sdw_stream_add_master(struct sdw_bus * bus,
		struct sdw_stream_config * stream_config,
		struct sdw_ports_config * ports_config,
		struct sdw_stream_runtime * stream);

  int sdw_stream_add_slave(struct sdw_slave * slave,
		struct sdw_stream_config * stream_config,
		struct sdw_ports_config * ports_config,
		struct sdw_stream_runtime * stream);

SDW_STREAM_PREPARED
~~~~~~~~~~~~~~~~~~~

Prepare state of stream. Operations performed before entering in this state:

  (0) Steps 1 and 2 are omitted in the case of a resume operation,
      where the bus bandwidth is known.

  (1) Bus parameters such as bandwidth, frame shape, clock frequency,
      are computed based on current stream as well as already active
      stream(s) on Bus. Re-computation is required to accommodate current
      stream on the Bus.

  (2) Transport and port parameters of all Master(s) and Slave(s) port(s) are
      computed for the current as well as already active stream based on frame
      shape and clock frequency computed in step 1.

  (3) Computed Bus and transport parameters are programmed in Master(s) and
      Slave(s) registers. The banked registers programming is done on the
      alternate bank (bank currently unused). Port(s) are enabled for the
      already active stream(s) on the alternate bank (bank currently unused).
      This is done in order to not disrupt already active stream(s).

  (4) Once all the values are programmed, Bus initiates switch to alternate
      bank where all new values programmed gets into effect.

  (5) Ports of Master(s) and Slave(s) for current stream are prepared by
      programming PrepareCtrl register.

After all above operations are successful, stream state is set to
``SDW_STREAM_PREPARED``.

Bus implements below API for PREPARE state which needs to be called
once per stream. From ASoC DPCM framework, this stream state is linked
to .prepare() operation. Since the .trigger() operations may not
follow the .prepare(), a direct transition from
``SDW_STREAM_PREPARED`` to ``SDW_STREAM_DEPREPARED`` is allowed.

.. code-block:: c

  int sdw_prepare_stream(struct sdw_stream_runtime * stream);

SDW_STREAM_ENABLED
~~~~~~~~~~~~~~~~~~

Enable state of stream. The data port(s) are enabled upon entering this state.
Operations performed before entering in this state:

  (1) All the values computed in SDW_STREAM_PREPARED state are programmed
      in alternate bank (bank currently unused). It includes programming of
      already active stream(s) as well.

  (2) All the Master(s) and Slave(s) port(s) for the current stream are
      enabled on alternate bank (bank currently unused) by programming
      ChannelEn register.

  (3) Once all the values are programmed, Bus initiates switch to alternate
      bank where all new values programmed gets into effect and port(s)
      associated with current stream are enabled.

After all above operations are successful, stream state is set to
``SDW_STREAM_ENABLED``.

Bus implements below API for ENABLE state which needs to be called once per
stream. From ASoC DPCM framework, this stream state is linked to
.trigger() start operation.

.. code-block:: c

  int sdw_enable_stream(struct sdw_stream_runtime * stream);

SDW_STREAM_DISABLED
~~~~~~~~~~~~~~~~~~~

Disable state of stream. The data port(s) are disabled upon exiting this state.
Operations performed before entering in this state:

  (1) All the Master(s) and Slave(s) port(s) for the current stream are
      disabled on alternate bank (bank currently unused) by programming
      ChannelEn register.

  (2) All the current configuration of Bus and active stream(s) are programmed
      into alternate bank (bank currently unused).

  (3) Once all the values are programmed, Bus initiates switch to alternate
      bank where all new values programmed gets into effect and port(s) associated
      with current stream are disabled.

After all above operations are successful, stream state is set to
``SDW_STREAM_DISABLED``.

Bus implements below API for DISABLED state which needs to be called once
per stream. From ASoC DPCM framework, this stream state is linked to
.trigger() stop operation.

When the INFO_PAUSE flag is supported, a direct transition to
``SDW_STREAM_ENABLED`` is allowed.

For resume operations where ASoC will use the .prepare() callback, the
stream can transition from ``SDW_STREAM_DISABLED`` to
``SDW_STREAM_PREPARED``, with all required settings restored but
without updating the bandwidth and bit allocation.

.. code-block:: c

  int sdw_disable_stream(struct sdw_stream_runtime * stream);

SDW_STREAM_DEPREPARED
~~~~~~~~~~~~~~~~~~~~~

De-prepare state of stream. Operations performed before entering in this
state:

  (1) All the port(s) of Master(s) and Slave(s) for current stream are
      de-prepared by programming PrepareCtrl register.

  (2) The payload bandwidth of current stream is reduced from the total
      bandwidth requirement of bus and new parameters calculated and
      applied by performing bank switch etc.

After all above operations are successful, stream state is set to
``SDW_STREAM_DEPREPARED``.

Bus implements below API for DEPREPARED state which needs to be called
once per stream. ALSA/ASoC do not have a concept of 'deprepare', and
the mapping from this stream state to ALSA/ASoC operation may be
implementation specific.

When the INFO_PAUSE flag is supported, the stream state is linked to
the .hw_free() operation - the stream is not deprepared on a
TRIGGER_STOP.

Other implementations may transition to the ``SDW_STREAM_DEPREPARED``
state on TRIGGER_STOP, should they require a transition through the
``SDW_STREAM_PREPARED`` state.

.. code-block:: c

  int sdw_deprepare_stream(struct sdw_stream_runtime * stream);

SDW_STREAM_RELEASED
~~~~~~~~~~~~~~~~~~~

Release state of stream. Operations performed before entering in this state:

  (1) Release port resources for all Master(s) and Slave(s) port(s)
      associated with current stream.

  (2) Release Master(s) and Slave(s) runtime resources associated with
      current stream.

  (3) Release stream runtime resources associated with current stream.

After all above operations are successful, stream state is set to
``SDW_STREAM_RELEASED``.

Bus implements below APIs for RELEASE state which needs to be called by
all the Master(s) and Slave(s) associated with stream. From ASoC DPCM
framework, this stream state is linked to .hw_free() operation.

.. code-block:: c

  int sdw_stream_remove_master(struct sdw_bus * bus,
		struct sdw_stream_runtime * stream);
  int sdw_stream_remove_slave(struct sdw_slave * slave,
		struct sdw_stream_runtime * stream);

The .shutdown() ASoC DPCM operation calls below Bus API to release
stream assigned as part of ALLOCATED state.

In .shutdown() the data structure maintaining stream state are freed up.

.. code-block:: c

  void sdw_release_stream(struct sdw_stream_runtime * stream);

The SoundWire core provides a sdw_shutdown_stream() helper function,
typically called during a dailink .shutdown() callback, which clears
the stream pointer for all DAIS connected to a stream and releases the
memory allocated for the stream.

Not Supported
=============

1. A single port with multiple channels supported cannot be used between two
   streams or across stream. For example a port with 4 channels cannot be used
   to handle 2 independent stereo streams even though it's possible in theory
   in SoundWire.