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

V4L2 sub-devices
----------------

Many drivers need to communicate with sub-devices. These devices can do all
sort of tasks, but most commonly they handle audio and/or video muxing,
encoding or decoding. For webcams common sub-devices are sensors and camera
controllers.

Usually these are I2C devices, but not necessarily. In order to provide the
driver with a consistent interface to these sub-devices the
:c:type:`v4l2_subdev` struct (v4l2-subdev.h) was created.

Each sub-device driver must have a :c:type:`v4l2_subdev` struct. This struct
can be stand-alone for simple sub-devices or it might be embedded in a larger
struct if more state information needs to be stored. Usually there is a
low-level device struct (e.g. ``i2c_client``) that contains the device data as
setup by the kernel. It is recommended to store that pointer in the private
data of :c:type:`v4l2_subdev` using :c:func:`v4l2_set_subdevdata`. That makes
it easy to go from a :c:type:`v4l2_subdev` to the actual low-level bus-specific
device data.

You also need a way to go from the low-level struct to :c:type:`v4l2_subdev`.
For the common i2c_client struct the i2c_set_clientdata() call is used to store
a :c:type:`v4l2_subdev` pointer, for other buses you may have to use other
methods.

Bridges might also need to store per-subdev private data, such as a pointer to
bridge-specific per-subdev private data. The :c:type:`v4l2_subdev` structure
provides host private data for that purpose that can be accessed with
:c:func:`v4l2_get_subdev_hostdata` and :c:func:`v4l2_set_subdev_hostdata`.

From the bridge driver perspective, you load the sub-device module and somehow
obtain the :c:type:`v4l2_subdev` pointer. For i2c devices this is easy: you call
``i2c_get_clientdata()``. For other buses something similar needs to be done.
Helper functions exist for sub-devices on an I2C bus that do most of this
tricky work for you.

Each :c:type:`v4l2_subdev` contains function pointers that sub-device drivers
can implement (or leave ``NULL`` if it is not applicable). Since sub-devices can
do so many different things and you do not want to end up with a huge ops struct
of which only a handful of ops are commonly implemented, the function pointers
are sorted according to category and each category has its own ops struct.

The top-level ops struct contains pointers to the category ops structs, which
may be NULL if the subdev driver does not support anything from that category.

It looks like this:

.. code-block:: c

	struct v4l2_subdev_core_ops {
		int (*log_status)(struct v4l2_subdev *sd);
		int (*init)(struct v4l2_subdev *sd, u32 val);
		...
	};

	struct v4l2_subdev_tuner_ops {
		...
	};

	struct v4l2_subdev_audio_ops {
		...
	};

	struct v4l2_subdev_video_ops {
		...
	};

	struct v4l2_subdev_pad_ops {
		...
	};

	struct v4l2_subdev_ops {
		const struct v4l2_subdev_core_ops  *core;
		const struct v4l2_subdev_tuner_ops *tuner;
		const struct v4l2_subdev_audio_ops *audio;
		const struct v4l2_subdev_video_ops *video;
		const struct v4l2_subdev_pad_ops *video;
	};

The core ops are common to all subdevs, the other categories are implemented
depending on the sub-device. E.g. a video device is unlikely to support the
audio ops and vice versa.

This setup limits the number of function pointers while still making it easy
to add new ops and categories.

A sub-device driver initializes the :c:type:`v4l2_subdev` struct using:

	:c:func:`v4l2_subdev_init <v4l2_subdev_init>`
	(:c:type:`sd <v4l2_subdev>`, &\ :c:type:`ops <v4l2_subdev_ops>`).

Afterwards you need to initialize :c:type:`sd <v4l2_subdev>`->name with a
unique name and set the module owner. This is done for you if you use the
i2c helper functions.

If integration with the media framework is needed, you must initialize the
:c:type:`media_entity` struct embedded in the :c:type:`v4l2_subdev` struct
(entity field) by calling :c:func:`media_entity_pads_init`, if the entity has
pads:

.. code-block:: c

	struct media_pad *pads = &my_sd->pads;
	int err;

	err = media_entity_pads_init(&sd->entity, npads, pads);

The pads array must have been previously initialized. There is no need to
manually set the struct media_entity function and name fields, but the
revision field must be initialized if needed.

A reference to the entity will be automatically acquired/released when the
subdev device node (if any) is opened/closed.

Don't forget to cleanup the media entity before the sub-device is destroyed:

.. code-block:: c

	media_entity_cleanup(&sd->entity);

If a sub-device driver implements sink pads, the subdev driver may set the
link_validate field in :c:type:`v4l2_subdev_pad_ops` to provide its own link
validation function. For every link in the pipeline, the link_validate pad
operation of the sink end of the link is called. In both cases the driver is
still responsible for validating the correctness of the format configuration
between sub-devices and video nodes.

If link_validate op is not set, the default function
:c:func:`v4l2_subdev_link_validate_default` is used instead. This function
ensures that width, height and the media bus pixel code are equal on both source
and sink of the link. Subdev drivers are also free to use this function to
perform the checks mentioned above in addition to their own checks.

Subdev registration
~~~~~~~~~~~~~~~~~~~

There are currently two ways to register subdevices with the V4L2 core. The
first (traditional) possibility is to have subdevices registered by bridge
drivers. This can be done when the bridge driver has the complete information
about subdevices connected to it and knows exactly when to register them. This
is typically the case for internal subdevices, like video data processing units
within SoCs or complex PCI(e) boards, camera sensors in USB cameras or connected
to SoCs, which pass information about them to bridge drivers, usually in their
platform data.

There are however also situations where subdevices have to be registered
asynchronously to bridge devices. An example of such a configuration is a Device
Tree based system where information about subdevices is made available to the
system independently from the bridge devices, e.g. when subdevices are defined
in DT as I2C device nodes. The API used in this second case is described further
below.

Using one or the other registration method only affects the probing process, the
run-time bridge-subdevice interaction is in both cases the same.

In the **synchronous** case a device (bridge) driver needs to register the
:c:type:`v4l2_subdev` with the v4l2_device:

	:c:func:`v4l2_device_register_subdev <v4l2_device_register_subdev>`
	(:c:type:`v4l2_dev <v4l2_device>`, :c:type:`sd <v4l2_subdev>`).

This can fail if the subdev module disappeared before it could be registered.
After this function was called successfully the subdev->dev field points to
the :c:type:`v4l2_device`.

If the v4l2_device parent device has a non-NULL mdev field, the sub-device
entity will be automatically registered with the media device.

You can unregister a sub-device using:

	:c:func:`v4l2_device_unregister_subdev <v4l2_device_unregister_subdev>`
	(:c:type:`sd <v4l2_subdev>`).

Afterwards the subdev module can be unloaded and
:c:type:`sd <v4l2_subdev>`->dev == ``NULL``.

In the **asynchronous** case subdevice probing can be invoked independently of
the bridge driver availability. The subdevice driver then has to verify whether
all the requirements for a successful probing are satisfied. This can include a
check for a master clock availability. If any of the conditions aren't satisfied
the driver might decide to return ``-EPROBE_DEFER`` to request further reprobing
attempts. Once all conditions are met the subdevice shall be registered using
the :c:func:`v4l2_async_register_subdev` function. Unregistration is
performed using the :c:func:`v4l2_async_unregister_subdev` call. Subdevices
registered this way are stored in a global list of subdevices, ready to be
picked up by bridge drivers.

Bridge drivers in turn have to register a notifier object. This is
performed using the :c:func:`v4l2_async_nf_register` call. To
unregister the notifier the driver has to call
:c:func:`v4l2_async_nf_unregister`. The former of the two functions
takes two arguments: a pointer to struct :c:type:`v4l2_device` and a
pointer to struct :c:type:`v4l2_async_notifier`.

Before registering the notifier, bridge drivers must do two things: first, the
notifier must be initialized using the :c:func:`v4l2_async_nf_init`.
Second, bridge drivers can then begin to form a list of subdevice descriptors
that the bridge device needs for its operation. Several functions are available
to add subdevice descriptors to a notifier, depending on the type of device and
the needs of the driver.

:c:func:`v4l2_async_nf_add_fwnode_remote` and
:c:func:`v4l2_async_nf_add_i2c` are for bridge and ISP drivers for
registering their async sub-devices with the notifier.

:c:func:`v4l2_async_register_subdev_sensor` is a helper function for
sensor drivers registering their own async sub-device, but it also registers a
notifier and further registers async sub-devices for lens and flash devices
found in firmware. The notifier for the sub-device is unregistered with the
async sub-device.

These functions allocate an async sub-device descriptor which is of type struct
:c:type:`v4l2_async_subdev` embedded in a driver-specific struct. The &struct
:c:type:`v4l2_async_subdev` shall be the first member of this struct:

.. code-block:: c

	struct my_async_subdev {
		struct v4l2_async_subdev asd;
		...
	};

	struct my_async_subdev *my_asd;
	struct fwnode_handle *ep;

	...

	my_asd = v4l2_async_nf_add_fwnode_remote(&notifier, ep,
						 struct my_async_subdev);
	fwnode_handle_put(ep);

	if (IS_ERR(asd))
		return PTR_ERR(asd);

The V4L2 core will then use these descriptors to match asynchronously
registered subdevices to them. If a match is detected the ``.bound()``
notifier callback is called. After all subdevices have been located the
.complete() callback is called. When a subdevice is removed from the
system the .unbind() method is called. All three callbacks are optional.

Drivers can store any type of custom data in their driver-specific
:c:type:`v4l2_async_subdev` wrapper. If any of that data requires special
handling when the structure is freed, drivers must implement the ``.destroy()``
notifier callback. The framework will call it right before freeing the
:c:type:`v4l2_async_subdev`.

Calling subdev operations
~~~~~~~~~~~~~~~~~~~~~~~~~

The advantage of using :c:type:`v4l2_subdev` is that it is a generic struct and
does not contain any knowledge about the underlying hardware. So a driver might
contain several subdevs that use an I2C bus, but also a subdev that is
controlled through GPIO pins. This distinction is only relevant when setting
up the device, but once the subdev is registered it is completely transparent.

Once the subdev has been registered you can call an ops function either
directly:

.. code-block:: c

	err = sd->ops->core->g_std(sd, &norm);

but it is better and easier to use this macro:

.. code-block:: c

	err = v4l2_subdev_call(sd, core, g_std, &norm);

The macro will do the right ``NULL`` pointer checks and returns ``-ENODEV``
if :c:type:`sd <v4l2_subdev>` is ``NULL``, ``-ENOIOCTLCMD`` if either
:c:type:`sd <v4l2_subdev>`->core or :c:type:`sd <v4l2_subdev>`->core->g_std is ``NULL``, or the actual result of the
:c:type:`sd <v4l2_subdev>`->ops->core->g_std ops.

It is also possible to call all or a subset of the sub-devices:

.. code-block:: c

	v4l2_device_call_all(v4l2_dev, 0, core, g_std, &norm);

Any subdev that does not support this ops is skipped and error results are
ignored. If you want to check for errors use this:

.. code-block:: c

	err = v4l2_device_call_until_err(v4l2_dev, 0, core, g_std, &norm);

Any error except ``-ENOIOCTLCMD`` will exit the loop with that error. If no
errors (except ``-ENOIOCTLCMD``) occurred, then 0 is returned.

The second argument to both calls is a group ID. If 0, then all subdevs are
called. If non-zero, then only those whose group ID match that value will
be called. Before a bridge driver registers a subdev it can set
:c:type:`sd <v4l2_subdev>`->grp_id to whatever value it wants (it's 0 by
default). This value is owned by the bridge driver and the sub-device driver
will never modify or use it.

The group ID gives the bridge driver more control how callbacks are called.
For example, there may be multiple audio chips on a board, each capable of
changing the volume. But usually only one will actually be used when the
user want to change the volume. You can set the group ID for that subdev to
e.g. AUDIO_CONTROLLER and specify that as the group ID value when calling
``v4l2_device_call_all()``. That ensures that it will only go to the subdev
that needs it.

If the sub-device needs to notify its v4l2_device parent of an event, then
it can call ``v4l2_subdev_notify(sd, notification, arg)``. This macro checks
whether there is a ``notify()`` callback defined and returns ``-ENODEV`` if not.
Otherwise the result of the ``notify()`` call is returned.

V4L2 sub-device userspace API
-----------------------------

Bridge drivers traditionally expose one or multiple video nodes to userspace,
and control subdevices through the :c:type:`v4l2_subdev_ops` operations in
response to video node operations. This hides the complexity of the underlying
hardware from applications. For complex devices, finer-grained control of the
device than what the video nodes offer may be required. In those cases, bridge
drivers that implement :ref:`the media controller API <media_controller>` may
opt for making the subdevice operations directly accessible from userpace.

Device nodes named ``v4l-subdev``\ *X* can be created in ``/dev`` to access
sub-devices directly. If a sub-device supports direct userspace configuration
it must set the ``V4L2_SUBDEV_FL_HAS_DEVNODE`` flag before being registered.

After registering sub-devices, the :c:type:`v4l2_device` driver can create
device nodes for all registered sub-devices marked with
``V4L2_SUBDEV_FL_HAS_DEVNODE`` by calling
:c:func:`v4l2_device_register_subdev_nodes`. Those device nodes will be
automatically removed when sub-devices are unregistered.

The device node handles a subset of the V4L2 API.

``VIDIOC_QUERYCTRL``,
``VIDIOC_QUERYMENU``,
``VIDIOC_G_CTRL``,
``VIDIOC_S_CTRL``,
``VIDIOC_G_EXT_CTRLS``,
``VIDIOC_S_EXT_CTRLS`` and
``VIDIOC_TRY_EXT_CTRLS``:

	The controls ioctls are identical to the ones defined in V4L2. They
	behave identically, with the only exception that they deal only with
	controls implemented in the sub-device. Depending on the driver, those
	controls can be also be accessed through one (or several) V4L2 device
	nodes.

``VIDIOC_DQEVENT``,
``VIDIOC_SUBSCRIBE_EVENT`` and
``VIDIOC_UNSUBSCRIBE_EVENT``

	The events ioctls are identical to the ones defined in V4L2. They
	behave identically, with the only exception that they deal only with
	events generated by the sub-device. Depending on the driver, those
	events can also be reported by one (or several) V4L2 device nodes.

	Sub-device drivers that want to use events need to set the
	``V4L2_SUBDEV_FL_HAS_EVENTS`` :c:type:`v4l2_subdev`.flags before registering
	the sub-device. After registration events can be queued as usual on the
	:c:type:`v4l2_subdev`.devnode device node.

	To properly support events, the ``poll()`` file operation is also
	implemented.

Private ioctls

	All ioctls not in the above list are passed directly to the sub-device
	driver through the core::ioctl operation.

Read-only sub-device userspace API
----------------------------------

Bridge drivers that control their connected subdevices through direct calls to
the kernel API realized by :c:type:`v4l2_subdev_ops` structure do not usually
want userspace to be able to change the same parameters through the subdevice
device node and thus do not usually register any.

It is sometimes useful to report to userspace the current subdevice
configuration through a read-only API, that does not permit applications to
change to the device parameters but allows interfacing to the subdevice device
node to inspect them.

For instance, to implement cameras based on computational photography, userspace
needs to know the detailed camera sensor configuration (in terms of skipping,
binning, cropping and scaling) for each supported output resolution. To support
such use cases, bridge drivers may expose the subdevice operations to userspace
through a read-only API.

To create a read-only device node for all the subdevices registered with the
``V4L2_SUBDEV_FL_HAS_DEVNODE`` set, the :c:type:`v4l2_device` driver should call
:c:func:`v4l2_device_register_ro_subdev_nodes`.

Access to the following ioctls for userspace applications is restricted on
sub-device device nodes registered with
:c:func:`v4l2_device_register_ro_subdev_nodes`.

``VIDIOC_SUBDEV_S_FMT``,
``VIDIOC_SUBDEV_S_CROP``,
``VIDIOC_SUBDEV_S_SELECTION``:

	These ioctls are only allowed on a read-only subdevice device node
	for the :ref:`V4L2_SUBDEV_FORMAT_TRY <v4l2-subdev-format-whence>`
	formats and selection rectangles.

``VIDIOC_SUBDEV_S_FRAME_INTERVAL``,
``VIDIOC_SUBDEV_S_DV_TIMINGS``,
``VIDIOC_SUBDEV_S_STD``:

	These ioctls are not allowed on a read-only subdevice node.

In case the ioctl is not allowed, or the format to modify is set to
``V4L2_SUBDEV_FORMAT_ACTIVE``, the core returns a negative error code and
the errno variable is set to ``-EPERM``.

I2C sub-device drivers
----------------------

Since these drivers are so common, special helper functions are available to
ease the use of these drivers (``v4l2-common.h``).

The recommended method of adding :c:type:`v4l2_subdev` support to an I2C driver
is to embed the :c:type:`v4l2_subdev` struct into the state struct that is
created for each I2C device instance. Very simple devices have no state
struct and in that case you can just create a :c:type:`v4l2_subdev` directly.

A typical state struct would look like this (where 'chipname' is replaced by
the name of the chip):

.. code-block:: c

	struct chipname_state {
		struct v4l2_subdev sd;
		...  /* additional state fields */
	};

Initialize the :c:type:`v4l2_subdev` struct as follows:

.. code-block:: c

	v4l2_i2c_subdev_init(&state->sd, client, subdev_ops);

This function will fill in all the fields of :c:type:`v4l2_subdev` ensure that
the :c:type:`v4l2_subdev` and i2c_client both point to one another.

You should also add a helper inline function to go from a :c:type:`v4l2_subdev`
pointer to a chipname_state struct:

.. code-block:: c

	static inline struct chipname_state *to_state(struct v4l2_subdev *sd)
	{
		return container_of(sd, struct chipname_state, sd);
	}

Use this to go from the :c:type:`v4l2_subdev` struct to the ``i2c_client``
struct:

.. code-block:: c

	struct i2c_client *client = v4l2_get_subdevdata(sd);

And this to go from an ``i2c_client`` to a :c:type:`v4l2_subdev` struct:

.. code-block:: c

	struct v4l2_subdev *sd = i2c_get_clientdata(client);

Make sure to call
:c:func:`v4l2_device_unregister_subdev`\ (:c:type:`sd <v4l2_subdev>`)
when the ``remove()`` callback is called. This will unregister the sub-device
from the bridge driver. It is safe to call this even if the sub-device was
never registered.

You need to do this because when the bridge driver destroys the i2c adapter
the ``remove()`` callbacks are called of the i2c devices on that adapter.
After that the corresponding v4l2_subdev structures are invalid, so they
have to be unregistered first. Calling
:c:func:`v4l2_device_unregister_subdev`\ (:c:type:`sd <v4l2_subdev>`)
from the ``remove()`` callback ensures that this is always done correctly.

The bridge driver also has some helper functions it can use:

.. code-block:: c

	struct v4l2_subdev *sd = v4l2_i2c_new_subdev(v4l2_dev, adapter,
					"module_foo", "chipid", 0x36, NULL);

This loads the given module (can be ``NULL`` if no module needs to be loaded)
and calls :c:func:`i2c_new_client_device` with the given ``i2c_adapter`` and
chip/address arguments. If all goes well, then it registers the subdev with
the v4l2_device.

You can also use the last argument of :c:func:`v4l2_i2c_new_subdev` to pass
an array of possible I2C addresses that it should probe. These probe addresses
are only used if the previous argument is 0. A non-zero argument means that you
know the exact i2c address so in that case no probing will take place.

Both functions return ``NULL`` if something went wrong.

Note that the chipid you pass to :c:func:`v4l2_i2c_new_subdev` is usually
the same as the module name. It allows you to specify a chip variant, e.g.
"saa7114" or "saa7115". In general though the i2c driver autodetects this.
The use of chipid is something that needs to be looked at more closely at a
later date. It differs between i2c drivers and as such can be confusing.
To see which chip variants are supported you can look in the i2c driver code
for the i2c_device_id table. This lists all the possibilities.

There are one more helper function:

:c:func:`v4l2_i2c_new_subdev_board` uses an :c:type:`i2c_board_info` struct
which is passed to the i2c driver and replaces the irq, platform_data and addr
arguments.

If the subdev supports the s_config core ops, then that op is called with
the irq and platform_data arguments after the subdev was setup.

The :c:func:`v4l2_i2c_new_subdev` function will call
:c:func:`v4l2_i2c_new_subdev_board`, internally filling a
:c:type:`i2c_board_info` structure using the ``client_type`` and the
``addr`` to fill it.

Centrally managed subdev active state
-------------------------------------

Traditionally V4L2 subdev drivers maintained internal state for the active
device configuration. This is often implemented as e.g. an array of struct
v4l2_mbus_framefmt, one entry for each pad, and similarly for crop and compose
rectangles.

In addition to the active configuration, each subdev file handle has an array of
struct v4l2_subdev_pad_config, managed by the V4L2 core, which contains the try
configuration.

To simplify the subdev drivers the V4L2 subdev API now optionally supports a
centrally managed active configuration represented by
:c:type:`v4l2_subdev_state`. One instance of state, which contains the active
device configuration, is stored in the sub-device itself as part of
the :c:type:`v4l2_subdev` structure, while the core associates a try state to
each open file handle, to store the try configuration related to that file
handle.

Sub-device drivers can opt-in and use state to manage their active configuration
by initializing the subdevice state with a call to v4l2_subdev_init_finalize()
before registering the sub-device. They must also call v4l2_subdev_cleanup()
to release all the allocated resources before unregistering the sub-device.
The core automatically allocates and initializes a state for each open file
handle to store the try configurations and frees it when closing the file
handle.

V4L2 sub-device operations that use both the :ref:`ACTIVE and TRY formats
<v4l2-subdev-format-whence>` receive the correct state to operate on through
the 'state' parameter. The state must be locked and unlocked by the
caller by calling :c:func:`v4l2_subdev_lock_state()` and
:c:func:`v4l2_subdev_unlock_state()`. The caller can do so by calling the subdev
operation through the :c:func:`v4l2_subdev_call_state_active()` macro.

Operations that do not receive a state parameter implicitly operate on the
subdevice active state, which drivers can exclusively access by
calling :c:func:`v4l2_subdev_lock_and_get_active_state()`. The sub-device active
state must equally be released by calling :c:func:`v4l2_subdev_unlock_state()`.

Drivers must never manually access the state stored in the :c:type:`v4l2_subdev`
or in the file handle without going through the designated helpers.

While the V4L2 core passes the correct try or active state to the subdevice
operations, many existing device drivers pass a NULL state when calling
operations with :c:func:`v4l2_subdev_call()`. This legacy construct causes
issues with subdevice drivers that let the V4L2 core manage the active state,
as they expect to receive the appropriate state as a parameter. To help the
conversion of subdevice drivers to a managed active state without having to
convert all callers at the same time, an additional wrapper layer has been
added to v4l2_subdev_call(), which handles the NULL case by geting and locking
the callee's active state with :c:func:`v4l2_subdev_lock_and_get_active_state()`,
and unlocking the state after the call.

The whole subdev state is in reality split into three parts: the
v4l2_subdev_state, subdev controls and subdev driver's internal state. In the
future these parts should be combined into a single state. For the time being
we need a way to handle the locking for these parts. This can be accomplished
by sharing a lock. The v4l2_ctrl_handler already supports this via its 'lock'
pointer and the same model is used with states. The driver can do the following
before calling v4l2_subdev_init_finalize():

.. code-block:: c

	sd->ctrl_handler->lock = &priv->mutex;
	sd->state_lock = &priv->mutex;

This shares the driver's private mutex between the controls and the states.

V4L2 sub-device functions and data structures
---------------------------------------------

.. kernel-doc:: include/media/v4l2-subdev.h


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

Tuner functions and data structures
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. kernel-doc:: include/media/tuner.h

.. kernel-doc:: include/media/tuner-types.h

repo_name: angery/linux


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

Hauppauge TV EEPROM functions and data structures
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. kernel-doc:: include/media/tveeprom.h


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

.. _vb_framework:

Videobuf Framework
==================

Author: Jonathan Corbet <corbet@lwn.net>

Current as of 2.6.33

.. note::

   The videobuf framework was deprecated in favor of videobuf2. Shouldn't
   be used on new drivers.

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

The videobuf layer functions as a sort of glue layer between a V4L2 driver
and user space.  It handles the allocation and management of buffers for
the storage of video frames.  There is a set of functions which can be used
to implement many of the standard POSIX I/O system calls, including read(),
poll(), and, happily, mmap().  Another set of functions can be used to
implement the bulk of the V4L2 ioctl() calls related to streaming I/O,
including buffer allocation, queueing and dequeueing, and streaming
control.  Using videobuf imposes a few design decisions on the driver
author, but the payback comes in the form of reduced code in the driver and
a consistent implementation of the V4L2 user-space API.

Buffer types
------------

Not all video devices use the same kind of buffers.  In fact, there are (at
least) three common variations:

 - Buffers which are scattered in both the physical and (kernel) virtual
   address spaces.  (Almost) all user-space buffers are like this, but it
   makes great sense to allocate kernel-space buffers this way as well when
   it is possible.  Unfortunately, it is not always possible; working with
   this kind of buffer normally requires hardware which can do
   scatter/gather DMA operations.

 - Buffers which are physically scattered, but which are virtually
   contiguous; buffers allocated with vmalloc(), in other words.  These
   buffers are just as hard to use for DMA operations, but they can be
   useful in situations where DMA is not available but virtually-contiguous
   buffers are convenient.

 - Buffers which are physically contiguous.  Allocation of this kind of
   buffer can be unreliable on fragmented systems, but simpler DMA
   controllers cannot deal with anything else.

Videobuf can work with all three types of buffers, but the driver author
must pick one at the outset and design the driver around that decision.

[It's worth noting that there's a fourth kind of buffer: "overlay" buffers
which are located within the system's video memory.  The overlay
functionality is considered to be deprecated for most use, but it still
shows up occasionally in system-on-chip drivers where the performance
benefits merit the use of this technique.  Overlay buffers can be handled
as a form of scattered buffer, but there are very few implementations in
the kernel and a description of this technique is currently beyond the
scope of this document.]

Data structures, callbacks, and initialization
----------------------------------------------

Depending on which type of buffers are being used, the driver should
include one of the following files:

.. code-block:: none

    <media/videobuf-dma-sg.h>		/* Physically scattered */
    <media/videobuf-vmalloc.h>		/* vmalloc() buffers	*/
    <media/videobuf-dma-contig.h>	/* Physically contiguous */

The driver's data structure describing a V4L2 device should include a
struct videobuf_queue instance for the management of the buffer queue,
along with a list_head for the queue of available buffers.  There will also
need to be an interrupt-safe spinlock which is used to protect (at least)
the queue.

The next step is to write four simple callbacks to help videobuf deal with
the management of buffers:

.. code-block:: none

    struct videobuf_queue_ops {
	int (*buf_setup)(struct videobuf_queue *q,
			 unsigned int *count, unsigned int *size);
	int (*buf_prepare)(struct videobuf_queue *q,
			   struct videobuf_buffer *vb,
			   enum v4l2_field field);
	void (*buf_queue)(struct videobuf_queue *q,
			  struct videobuf_buffer *vb);
	void (*buf_release)(struct videobuf_queue *q,
			    struct videobuf_buffer *vb);
    };

buf_setup() is called early in the I/O process, when streaming is being
initiated; its purpose is to tell videobuf about the I/O stream.  The count
parameter will be a suggested number of buffers to use; the driver should
check it for rationality and adjust it if need be.  As a practical rule, a
minimum of two buffers are needed for proper streaming, and there is
usually a maximum (which cannot exceed 32) which makes sense for each
device.  The size parameter should be set to the expected (maximum) size
for each frame of data.

Each buffer (in the form of a struct videobuf_buffer pointer) will be
passed to buf_prepare(), which should set the buffer's size, width, height,
and field fields properly.  If the buffer's state field is
VIDEOBUF_NEEDS_INIT, the driver should pass it to:

.. code-block:: none

    int videobuf_iolock(struct videobuf_queue* q, struct videobuf_buffer *vb,
			struct v4l2_framebuffer *fbuf);

Among other things, this call will usually allocate memory for the buffer.
Finally, the buf_prepare() function should set the buffer's state to
VIDEOBUF_PREPARED.

When a buffer is queued for I/O, it is passed to buf_queue(), which should
put it onto the driver's list of available buffers and set its state to
VIDEOBUF_QUEUED.  Note that this function is called with the queue spinlock
held; if it tries to acquire it as well things will come to a screeching
halt.  Yes, this is the voice of experience.  Note also that videobuf may
wait on the first buffer in the queue; placing other buffers in front of it
could again gum up the works.  So use list_add_tail() to enqueue buffers.

Finally, buf_release() is called when a buffer is no longer intended to be
used.  The driver should ensure that there is no I/O active on the buffer,
then pass it to the appropriate free routine(s):

.. code-block:: none

    /* Scatter/gather drivers */
    int videobuf_dma_unmap(struct videobuf_queue *q,
			   struct videobuf_dmabuf *dma);
    int videobuf_dma_free(struct videobuf_dmabuf *dma);

    /* vmalloc drivers */
    void videobuf_vmalloc_free (struct videobuf_buffer *buf);

    /* Contiguous drivers */
    void videobuf_dma_contig_free(struct videobuf_queue *q,
				  struct videobuf_buffer *buf);

One way to ensure that a buffer is no longer under I/O is to pass it to:

.. code-block:: none

    int videobuf_waiton(struct videobuf_buffer *vb, int non_blocking, int intr);

Here, vb is the buffer, non_blocking indicates whether non-blocking I/O
should be used (it should be zero in the buf_release() case), and intr
controls whether an interruptible wait is used.

File operations
---------------

At this point, much of the work is done; much of the rest is slipping
videobuf calls into the implementation of the other driver callbacks.  The
first step is in the open() function, which must initialize the
videobuf queue.  The function to use depends on the type of buffer used:

.. code-block:: none

    void videobuf_queue_sg_init(struct videobuf_queue *q,
				struct videobuf_queue_ops *ops,
				struct device *dev,
				spinlock_t *irqlock,
				enum v4l2_buf_type type,
				enum v4l2_field field,
				unsigned int msize,
				void *priv);

    void videobuf_queue_vmalloc_init(struct videobuf_queue *q,
				struct videobuf_queue_ops *ops,
				struct device *dev,
				spinlock_t *irqlock,
				enum v4l2_buf_type type,
				enum v4l2_field field,
				unsigned int msize,
				void *priv);

    void videobuf_queue_dma_contig_init(struct videobuf_queue *q,
				       struct videobuf_queue_ops *ops,
				       struct device *dev,
				       spinlock_t *irqlock,
				       enum v4l2_buf_type type,
				       enum v4l2_field field,
				       unsigned int msize,
				       void *priv);

In each case, the parameters are the same: q is the queue structure for the
device, ops is the set of callbacks as described above, dev is the device
structure for this video device, irqlock is an interrupt-safe spinlock to
protect access to the data structures, type is the buffer type used by the
device (cameras will use V4L2_BUF_TYPE_VIDEO_CAPTURE, for example), field
describes which field is being captured (often V4L2_FIELD_NONE for
progressive devices), msize is the size of any containing structure used
around struct videobuf_buffer, and priv is a private data pointer which
shows up in the priv_data field of struct videobuf_queue.  Note that these
are void functions which, evidently, are immune to failure.

V4L2 capture drivers can be written to support either of two APIs: the
read() system call and the rather more complicated streaming mechanism.  As
a general rule, it is necessary to support both to ensure that all
applications have a chance of working with the device.  Videobuf makes it
easy to do that with the same code.  To implement read(), the driver need
only make a call to one of:

.. code-block:: none

    ssize_t videobuf_read_one(struct videobuf_queue *q,
			      char __user *data, size_t count,
			      loff_t *ppos, int nonblocking);

    ssize_t videobuf_read_stream(struct videobuf_queue *q,
				 char __user *data, size_t count,
				 loff_t *ppos, int vbihack, int nonblocking);

Either one of these functions will read frame data into data, returning the
amount actually read; the difference is that videobuf_read_one() will only
read a single frame, while videobuf_read_stream() will read multiple frames
if they are needed to satisfy the count requested by the application.  A
typical driver read() implementation will start the capture engine, call
one of the above functions, then stop the engine before returning (though a
smarter implementation might leave the engine running for a little while in
anticipation of another read() call happening in the near future).

The poll() function can usually be implemented with a direct call to:

.. code-block:: none

    unsigned int videobuf_poll_stream(struct file *file,
				      struct videobuf_queue *q,
				      poll_table *wait);

Note that the actual wait queue eventually used will be the one associated
with the first available buffer.

When streaming I/O is done to kernel-space buffers, the driver must support
the mmap() system call to enable user space to access the data.  In many
V4L2 drivers, the often-complex mmap() implementation simplifies to a
single call to:

.. code-block:: none

    int videobuf_mmap_mapper(struct videobuf_queue *q,
			     struct vm_area_struct *vma);

Everything else is handled by the videobuf code.

The release() function requires two separate videobuf calls:

.. code-block:: none

    void videobuf_stop(struct videobuf_queue *q);
    int videobuf_mmap_free(struct videobuf_queue *q);

The call to videobuf_stop() terminates any I/O in progress - though it is
still up to the driver to stop the capture engine.  The call to
videobuf_mmap_free() will ensure that all buffers have been unmapped; if
so, they will all be passed to the buf_release() callback.  If buffers
remain mapped, videobuf_mmap_free() returns an error code instead.  The
purpose is clearly to cause the closing of the file descriptor to fail if
buffers are still mapped, but every driver in the 2.6.32 kernel cheerfully
ignores its return value.

ioctl() operations
------------------

The V4L2 API includes a very long list of driver callbacks to respond to
the many ioctl() commands made available to user space.  A number of these
- those associated with streaming I/O - turn almost directly into videobuf
calls.  The relevant helper functions are:

.. code-block:: none

    int videobuf_reqbufs(struct videobuf_queue *q,
			 struct v4l2_requestbuffers *req);
    int videobuf_querybuf(struct videobuf_queue *q, struct v4l2_buffer *b);
    int videobuf_qbuf(struct videobuf_queue *q, struct v4l2_buffer *b);
    int videobuf_dqbuf(struct videobuf_queue *q, struct v4l2_buffer *b,
		       int nonblocking);
    int videobuf_streamon(struct videobuf_queue *q);
    int videobuf_streamoff(struct videobuf_queue *q);

So, for example, a VIDIOC_REQBUFS call turns into a call to the driver's
vidioc_reqbufs() callback which, in turn, usually only needs to locate the
proper struct videobuf_queue pointer and pass it to videobuf_reqbufs().
These support functions can replace a great deal of buffer management
boilerplate in a lot of V4L2 drivers.

The vidioc_streamon() and vidioc_streamoff() functions will be a bit more
complex, of course, since they will also need to deal with starting and
stopping the capture engine.

Buffer allocation
-----------------

Thus far, we have talked about buffers, but have not looked at how they are
allocated.  The scatter/gather case is the most complex on this front.  For
allocation, the driver can leave buffer allocation entirely up to the
videobuf layer; in this case, buffers will be allocated as anonymous
user-space pages and will be very scattered indeed.  If the application is
using user-space buffers, no allocation is needed; the videobuf layer will
take care of calling get_user_pages() and filling in the scatterlist array.

If the driver needs to do its own memory allocation, it should be done in
the vidioc_reqbufs() function, *after* calling videobuf_reqbufs().  The
first step is a call to:

.. code-block:: none

    struct videobuf_dmabuf *videobuf_to_dma(struct videobuf_buffer *buf);

The returned videobuf_dmabuf structure (defined in
<media/videobuf-dma-sg.h>) includes a couple of relevant fields:

.. code-block:: none

    struct scatterlist  *sglist;
    int                 sglen;

The driver must allocate an appropriately-sized scatterlist array and
populate it with pointers to the pieces of the allocated buffer; sglen
should be set to the length of the array.

Drivers using the vmalloc() method need not (and cannot) concern themselves
with buffer allocation at all; videobuf will handle those details.  The
same is normally true of contiguous-DMA drivers as well; videobuf will
allocate the buffers (with dma_alloc_coherent()) when it sees fit.  That
means that these drivers may be trying to do high-order allocations at any
time, an operation which is not always guaranteed to work.  Some drivers
play tricks by allocating DMA space at system boot time; videobuf does not
currently play well with those drivers.

As of 2.6.31, contiguous-DMA drivers can work with a user-supplied buffer,
as long as that buffer is physically contiguous.  Normal user-space
allocations will not meet that criterion, but buffers obtained from other
kernel drivers, or those contained within huge pages, will work with these
drivers.

Filling the buffers
-------------------

The final part of a videobuf implementation has no direct callback - it's
the portion of the code which actually puts frame data into the buffers,
usually in response to interrupts from the device.  For all types of
drivers, this process works approximately as follows:

 - Obtain the next available buffer and make sure that somebody is actually
   waiting for it.

 - Get a pointer to the memory and put video data there.

 - Mark the buffer as done and wake up the process waiting for it.

Step (1) above is done by looking at the driver-managed list_head structure
- the one which is filled in the buf_queue() callback.  Because starting
the engine and enqueueing buffers are done in separate steps, it's possible
for the engine to be running without any buffers available - in the
vmalloc() case especially.  So the driver should be prepared for the list
to be empty.  It is equally possible that nobody is yet interested in the
buffer; the driver should not remove it from the list or fill it until a
process is waiting on it.  That test can be done by examining the buffer's
done field (a wait_queue_head_t structure) with waitqueue_active().

A buffer's state should be set to VIDEOBUF_ACTIVE before being mapped for
DMA; that ensures that the videobuf layer will not try to do anything with
it while the device is transferring data.

For scatter/gather drivers, the needed memory pointers will be found in the
scatterlist structure described above.  Drivers using the vmalloc() method
can get a memory pointer with:

.. code-block:: none

    void *videobuf_to_vmalloc(struct videobuf_buffer *buf);

For contiguous DMA drivers, the function to use is:

.. code-block:: none

    dma_addr_t videobuf_to_dma_contig(struct videobuf_buffer *buf);

The contiguous DMA API goes out of its way to hide the kernel-space address
of the DMA buffer from drivers.

The final step is to set the size field of the relevant videobuf_buffer
structure to the actual size of the captured image, set state to
VIDEOBUF_DONE, then call wake_up() on the done queue.  At this point, the
buffer is owned by the videobuf layer and the driver should not touch it
again.

Developers who are interested in more information can go into the relevant
header files; there are a few low-level functions declared there which have
not been talked about here.  Note also that all of these calls are exported
GPL-only, so they will not be available to non-GPL kernel modules.


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

.. _vb2_framework:

V4L2 videobuf2 functions and data structures
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. kernel-doc:: include/media/videobuf2-core.h

.. kernel-doc:: include/media/videobuf2-v4l2.h

.. kernel-doc:: include/media/videobuf2-memops.h


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

HDCP:
=====

ME FW as a security engine provides the capability for setting up
HDCP2.2 protocol negotiation between the Intel graphics device and
an HDC2.2 sink.

ME FW prepares HDCP2.2 negotiation parameters, signs and encrypts them
according the HDCP 2.2 spec. The Intel graphics sends the created blob
to the HDCP2.2 sink.

Similarly, the HDCP2.2 sink's response is transferred to ME FW
for decryption and verification.

Once all the steps of HDCP2.2 negotiation are completed,
upon request ME FW will configure the port as authenticated and supply
the HDCP encryption keys to Intel graphics hardware.

mei_hdcp driver
---------------
.. kernel-doc:: drivers/misc/mei/hdcp/mei_hdcp.c
    :doc: MEI_HDCP Client Driver

mei_hdcp api
------------

.. kernel-doc:: drivers/misc/mei/hdcp/mei_hdcp.c
    :functions:


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

Intel(R) Active Management Technology (Intel AMT)
=================================================

Prominent usage of the Intel ME Interface is to communicate with Intel(R)
Active Management Technology (Intel AMT) implemented in firmware running on
the Intel ME.

Intel AMT provides the ability to manage a host remotely out-of-band (OOB)
even when the operating system running on the host processor has crashed or
is in a sleep state.

Some examples of Intel AMT usage are:
   - Monitoring hardware state and platform components
   - Remote power off/on (useful for green computing or overnight IT
     maintenance)
   - OS updates
   - Storage of useful platform information such as software assets
   - Built-in hardware KVM
   - Selective network isolation of Ethernet and IP protocol flows based
     on policies set by a remote management console
   - IDE device redirection from remote management console

Intel AMT (OOB) communication is based on SOAP (deprecated
starting with Release 6.0) over HTTP/S or WS-Management protocol over
HTTP/S that are received from a remote management console application.

For more information about Intel AMT:
https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm

Intel AMT Applications
----------------------

    1) Intel Local Management Service (Intel LMS)

       Applications running locally on the platform communicate with Intel AMT Release
       2.0 and later releases in the same way that network applications do via SOAP
       over HTTP (deprecated starting with Release 6.0) or with WS-Management over
       SOAP over HTTP. This means that some Intel AMT features can be accessed from a
       local application using the same network interface as a remote application
       communicating with Intel AMT over the network.

       When a local application sends a message addressed to the local Intel AMT host
       name, the Intel LMS, which listens for traffic directed to the host name,
       intercepts the message and routes it to the Intel MEI.
       For more information:
       https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm
       Under "About Intel AMT" => "Local Access"

       For downloading Intel LMS:
       https://github.com/intel/lms

       The Intel LMS opens a connection using the Intel MEI driver to the Intel LMS
       firmware feature using a defined GUID and then communicates with the feature
       using a protocol called Intel AMT Port Forwarding Protocol (Intel APF protocol).
       The protocol is used to maintain multiple sessions with Intel AMT from a
       single application.

       See the protocol specification in the Intel AMT Software Development Kit (SDK)
       https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm
       Under "SDK Resources" => "Intel(R) vPro(TM) Gateway (MPS)"
       => "Information for Intel(R) vPro(TM) Gateway Developers"
       => "Description of the Intel AMT Port Forwarding (APF) Protocol"

    2) Intel AMT Remote configuration using a Local Agent

       A Local Agent enables IT personnel to configure Intel AMT out-of-the-box
       without requiring installing additional data to enable setup. The remote
       configuration process may involve an ISV-developed remote configuration
       agent that runs on the host.
       For more information:
       https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm
       Under "Setup and Configuration of Intel AMT" =>
       "SDK Tools Supporting Setup and Configuration" =>
       "Using the Local Agent Sample"

Intel AMT OS Health Watchdog
----------------------------

The Intel AMT Watchdog is an OS Health (Hang/Crash) watchdog.
Whenever the OS hangs or crashes, Intel AMT will send an event
to any subscriber to this event. This mechanism means that
IT knows when a platform crashes even when there is a hard failure on the host.

The Intel AMT Watchdog is composed of two parts:
    1) Firmware feature - receives the heartbeats
       and sends an event when the heartbeats stop.
    2) Intel MEI iAMT watchdog driver - connects to the watchdog feature,
       configures the watchdog and sends the heartbeats.

The Intel iAMT watchdog MEI driver uses the kernel watchdog API to configure
the Intel AMT Watchdog and to send heartbeats to it. The default timeout of the
watchdog is 120 seconds.

If the Intel AMT is not enabled in the firmware then the watchdog client won't enumerate
on the me client bus and watchdog devices won't be exposed.

---
linux-mei@linux.intel.com


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

.. include:: <isonum.txt>

===================================================
Intel(R) Management Engine Interface (Intel(R) MEI)
===================================================

**Copyright** |copy| 2019 Intel Corporation

.. only:: html

   .. class:: toc-title

        Table of Contents

.. toctree::
   :maxdepth: 3

   mei
   mei-client-bus
   iamt


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

==============================================
Intel(R) Management Engine (ME) Client bus API
==============================================

Rationale
=========

The MEI character device is useful for dedicated applications to send and receive
data to the many FW appliance found in Intel's ME from the user space.
However, for some of the ME functionalities it makes sense to leverage existing software
stack and expose them through existing kernel subsystems.

In order to plug seamlessly into the kernel device driver model we add kernel virtual
bus abstraction on top of the MEI driver. This allows implementing Linux kernel drivers
for the various MEI features as a stand alone entities found in their respective subsystem.
Existing device drivers can even potentially be re-used by adding an MEI CL bus layer to
the existing code.

MEI CL bus API
==============

A driver implementation for an MEI Client is very similar to any other existing bus
based device drivers. The driver registers itself as an MEI CL bus driver through
the ``struct mei_cl_driver`` structure defined in :file:`include/linux/mei_cl_bus.c`

.. code-block:: C

        struct mei_cl_driver {
                struct device_driver driver;
                const char *name;

                const struct mei_cl_device_id *id_table;

                int (*probe)(struct mei_cl_device *dev, const struct mei_cl_id *id);
                int (*remove)(struct mei_cl_device *dev);
        };

The mei_cl_device_id structure defined in :file:`include/linux/mod_devicetable.h` allows a
driver to bind itself against a device name.

.. code-block:: C

        struct mei_cl_device_id {
                char name[MEI_CL_NAME_SIZE];
                uuid_le uuid;
                __u8    version;
                kernel_ulong_t driver_info;
        };

To actually register a driver on the ME Client bus one must call the :c:func:`mei_cl_add_driver`
API. This is typically called at module initialization time.

Once the driver is registered and bound to the device, a driver will typically
try to do some I/O on this bus and this should be done through the :c:func:`mei_cl_send`
and :c:func:`mei_cl_recv` functions. More detailed information is in :ref:`api` section.

In order for a driver to be notified about pending traffic or event, the driver
should register a callback via :c:func:`mei_cl_devev_register_rx_cb` and
:c:func:`mei_cldev_register_notify_cb` function respectively.

.. _api:

API:
----
.. kernel-doc:: drivers/misc/mei/bus.c
    :export: drivers/misc/mei/bus.c

Example
=======

As a theoretical example let's pretend the ME comes with a "contact" NFC IP.
The driver init and exit routines for this device would look like:

.. code-block:: C

        #define CONTACT_DRIVER_NAME "contact"

        static struct mei_cl_device_id contact_mei_cl_tbl[] = {
                { CONTACT_DRIVER_NAME, },

                /* required last entry */
                { }
        };
        MODULE_DEVICE_TABLE(mei_cl, contact_mei_cl_tbl);

        static struct mei_cl_driver contact_driver = {
                .id_table = contact_mei_tbl,
                .name = CONTACT_DRIVER_NAME,

                .probe = contact_probe,
                .remove = contact_remove,
        };

        static int contact_init(void)
        {
                int r;

                r = mei_cl_driver_register(&contact_driver);
                if (r) {
                        pr_err(CONTACT_DRIVER_NAME ": driver registration failed\n");
                        return r;
                }

                return 0;
        }

        static void __exit contact_exit(void)
        {
                mei_cl_driver_unregister(&contact_driver);
        }

        module_init(contact_init);
        module_exit(contact_exit);

And the driver's simplified probe routine would look like that:

.. code-block:: C

        int contact_probe(struct mei_cl_device *dev, struct mei_cl_device_id *id)
        {
                [...]
                mei_cldev_enable(dev);

                mei_cldev_register_rx_cb(dev, contact_rx_cb);

                return 0;
        }

In the probe routine the driver first enable the MEI device and then registers
an rx handler which is as close as it can get to registering a threaded IRQ handler.
The handler implementation will typically call :c:func:`mei_cldev_recv` and then
process received data.

.. code-block:: C

        #define MAX_PAYLOAD 128
        #define HDR_SIZE 4
        static void conntact_rx_cb(struct mei_cl_device *cldev)
        {
                struct contact *c = mei_cldev_get_drvdata(cldev);
                unsigned char payload[MAX_PAYLOAD];
                ssize_t payload_sz;

                payload_sz = mei_cldev_recv(cldev, payload,  MAX_PAYLOAD)
                if (reply_size < HDR_SIZE) {
                        return;
                }

                c->process_rx(payload);

        }

MEI Client Bus Drivers
======================

.. toctree::
   :maxdepth: 2

   hdcp
   nfc


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

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

The Intel Management Engine (Intel ME) is an isolated and protected computing
resource (Co-processor) residing inside certain Intel chipsets. The Intel ME
provides support for computer/IT management and security features.
The actual feature set depends on the Intel chipset SKU.

The Intel Management Engine Interface (Intel MEI, previously known as HECI)
is the interface between the Host and Intel ME. This interface is exposed
to the host as a PCI device, actually multiple PCI devices might be exposed.
The Intel MEI Driver is in charge of the communication channel between
a host application and the Intel ME features.

Each Intel ME feature, or Intel ME Client is addressed by a unique GUID and
each client has its own protocol. The protocol is message-based with a
header and payload up to maximal number of bytes advertised by the client,
upon connection.

Intel MEI Driver
================

The driver exposes a character device with device nodes /dev/meiX.

An application maintains communication with an Intel ME feature while
/dev/meiX is open. The binding to a specific feature is performed by calling
:c:macro:`MEI_CONNECT_CLIENT_IOCTL`, which passes the desired GUID.
The number of instances of an Intel ME feature that can be opened
at the same time depends on the Intel ME feature, but most of the
features allow only a single instance.

The driver is transparent to data that are passed between firmware feature
and host application.

Because some of the Intel ME features can change the system
configuration, the driver by default allows only a privileged
user to access it.

The session is terminated calling :c:expr:`close(fd)`.

A code snippet for an application communicating with Intel AMTHI client:

In order to support virtualization or sandboxing a trusted supervisor
can use :c:macro:`MEI_CONNECT_CLIENT_IOCTL_VTAG` to create
virtual channels with an Intel ME feature. Not all features support
virtual channels such client with answer EOPNOTSUPP.

.. code-block:: C

	struct mei_connect_client_data data;
	fd = open(MEI_DEVICE);

	data.d.in_client_uuid = AMTHI_GUID;

	ioctl(fd, IOCTL_MEI_CONNECT_CLIENT, &data);

	printf("Ver=%d, MaxLen=%ld\n",
	       data.d.in_client_uuid.protocol_version,
	       data.d.in_client_uuid.max_msg_length);

	[...]

	write(fd, amthi_req_data, amthi_req_data_len);

	[...]

	read(fd, &amthi_res_data, amthi_res_data_len);

	[...]
	close(fd);

User space API

IOCTLs:
=======

The Intel MEI Driver supports the following IOCTL commands:

IOCTL_MEI_CONNECT_CLIENT
-------------------------
Connect to firmware Feature/Client.

.. code-block:: none

	Usage:

        struct mei_connect_client_data client_data;

        ioctl(fd, IOCTL_MEI_CONNECT_CLIENT, &client_data);

	Inputs:

        struct mei_connect_client_data - contain the following
	Input field:

		in_client_uuid -	GUID of the FW Feature that needs
					to connect to.
         Outputs:
		out_client_properties - Client Properties: MTU and Protocol Version.

         Error returns:

                ENOTTY  No such client (i.e. wrong GUID) or connection is not allowed.
		EINVAL	Wrong IOCTL Number
		ENODEV	Device or Connection is not initialized or ready.
		ENOMEM	Unable to allocate memory to client internal data.
		EFAULT	Fatal Error (e.g. Unable to access user input data)
		EBUSY	Connection Already Open

:Note:
        max_msg_length (MTU) in client properties describes the maximum
        data that can be sent or received. (e.g. if MTU=2K, can send
        requests up to bytes 2k and received responses up to 2k bytes).

IOCTL_MEI_CONNECT_CLIENT_VTAG:
------------------------------

.. code-block:: none

        Usage:

        struct mei_connect_client_data_vtag client_data_vtag;

        ioctl(fd, IOCTL_MEI_CONNECT_CLIENT_VTAG, &client_data_vtag);

        Inputs:

        struct mei_connect_client_data_vtag - contain the following
        Input field:

                in_client_uuid -  GUID of the FW Feature that needs
                                  to connect to.
                vtag - virtual tag [1, 255]

         Outputs:
                out_client_properties - Client Properties: MTU and Protocol Version.

         Error returns:

                ENOTTY No such client (i.e. wrong GUID) or connection is not allowed.
                EINVAL Wrong IOCTL Number or tag == 0
                ENODEV Device or Connection is not initialized or ready.
                ENOMEM Unable to allocate memory to client internal data.
                EFAULT Fatal Error (e.g. Unable to access user input data)
                EBUSY  Connection Already Open
                EOPNOTSUPP Vtag is not supported

IOCTL_MEI_NOTIFY_SET
---------------------
Enable or disable event notifications.

.. code-block:: none

	Usage:

		uint32_t enable;

		ioctl(fd, IOCTL_MEI_NOTIFY_SET, &enable);

		uint32_t enable = 1;
		or
		uint32_t enable[disable] = 0;

	Error returns:

		EINVAL	Wrong IOCTL Number
		ENODEV	Device  is not initialized or the client not connected
		ENOMEM	Unable to allocate memory to client internal data.
		EFAULT	Fatal Error (e.g. Unable to access user input data)
		EOPNOTSUPP if the device doesn't support the feature

:Note:
	The client must be connected in order to enable notification events

IOCTL_MEI_NOTIFY_GET
--------------------
Retrieve event

.. code-block:: none

	Usage:
		uint32_t event;
		ioctl(fd, IOCTL_MEI_NOTIFY_GET, &event);

	Outputs:
		1 - if an event is pending
		0 - if there is no even pending

	Error returns:
		EINVAL	Wrong IOCTL Number
		ENODEV	Device is not initialized or the client not connected
		ENOMEM	Unable to allocate memory to client internal data.
		EFAULT	Fatal Error (e.g. Unable to access user input data)
		EOPNOTSUPP if the device doesn't support the feature

:Note:
	The client must be connected and event notification has to be enabled
	in order to receive an event

Supported Chipsets
==================
82X38/X48 Express and newer

linux-mei@linux.intel.com


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

MEI NFC
-------

Some Intel 8 and 9 Serieses chipsets supports NFC devices connected behind
the Intel Management Engine controller.
MEI client bus exposes the NFC chips as NFC phy devices and enables
binding with Microread and NXP PN544 NFC device driver from the Linux NFC
subsystem.

.. kernel-render:: DOT
   :alt: MEI NFC digraph
   :caption: **MEI NFC** Stack

   digraph NFC {
    cl_nfc -> me_cl_nfc;
    "drivers/nfc/mei_phy" -> cl_nfc [lhead=bus];
    "drivers/nfc/microread/mei" -> cl_nfc;
    "drivers/nfc/microread/mei" -> "drivers/nfc/mei_phy";
    "drivers/nfc/pn544/mei" -> cl_nfc;
    "drivers/nfc/pn544/mei" -> "drivers/nfc/mei_phy";
    "net/nfc" -> "drivers/nfc/microread/mei";
    "net/nfc" -> "drivers/nfc/pn544/mei";
    "neard" -> "net/nfc";
    cl_nfc [label="mei/bus(nfc)"];
    me_cl_nfc [label="me fw (nfc)"];
   }


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

=========================
Memory Controller drivers
=========================

.. toctree::
    :maxdepth: 1

    ti-emif
    ti-gpmc

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


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

===============================
TI EMIF SDRAM Controller Driver
===============================

Author
======
Aneesh V <aneesh@ti.com>

Location
========
driver/memory/emif.c

Supported SoCs:
===============
TI OMAP44xx
TI OMAP54xx

Menuconfig option:
==================
Device Drivers
	Memory devices
		Texas Instruments EMIF driver

Description
===========
This driver is for the EMIF module available in Texas Instruments
SoCs. EMIF is an SDRAM controller that, based on its revision,
supports one or more of DDR2, DDR3, and LPDDR2 SDRAM protocols.
This driver takes care of only LPDDR2 memories presently. The
functions of the driver includes re-configuring AC timing
parameters and other settings during frequency, voltage and
temperature changes

Platform Data (see include/linux/platform_data/emif_plat.h)
===========================================================
DDR device details and other board dependent and SoC dependent
information can be passed through platform data (struct emif_platform_data)

- DDR device details: 'struct ddr_device_info'
- Device AC timings: 'struct lpddr2_timings' and 'struct lpddr2_min_tck'
- Custom configurations: customizable policy options through
  'struct emif_custom_configs'
- IP revision
- PHY type

Interface to the external world
===============================
EMIF driver registers notifiers for voltage and frequency changes
affecting EMIF and takes appropriate actions when these are invoked.

- freq_pre_notify_handling()
- freq_post_notify_handling()
- volt_notify_handling()

Debugfs
=======
The driver creates two debugfs entries per device.

- regcache_dump : dump of register values calculated and saved for all
  frequencies used so far.
- mr4 : last polled value of MR4 register in the LPDDR2 device. MR4
  indicates the current temperature level of the device.


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

========================================
GPMC (General Purpose Memory Controller)
========================================

GPMC is an unified memory controller dedicated to interfacing external
memory devices like

 * Asynchronous SRAM like memories and application specific integrated
   circuit devices.
 * Asynchronous, synchronous, and page mode burst NOR flash devices
   NAND flash
 * Pseudo-SRAM devices

GPMC is found on Texas Instruments SoC's (OMAP based)
IP details: https://www.ti.com/lit/pdf/spruh73 section 7.1

GPMC generic timing calculation:
================================

GPMC has certain timings that has to be programmed for proper
functioning of the peripheral, while peripheral has another set of
timings. To have peripheral work with gpmc, peripheral timings has to
be translated to the form gpmc can understand. The way it has to be
translated depends on the connected peripheral. Also there is a
dependency for certain gpmc timings on gpmc clock frequency. Hence a
generic timing routine was developed to achieve above requirements.

Generic routine provides a generic method to calculate gpmc timings
from gpmc peripheral timings. struct gpmc_device_timings fields has to
be updated with timings from the datasheet of the peripheral that is
connected to gpmc. A few of the peripheral timings can be fed either
in time or in cycles, provision to handle this scenario has been
provided (refer struct gpmc_device_timings definition). It may so
happen that timing as specified by peripheral datasheet is not present
in timing structure, in this scenario, try to correlate peripheral
timing to the one available. If that doesn't work, try to add a new
field as required by peripheral, educate generic timing routine to
handle it, make sure that it does not break any of the existing.
Then there may be cases where peripheral datasheet doesn't mention
certain fields of struct gpmc_device_timings, zero those entries.

Generic timing routine has been verified to work properly on
multiple onenand's and tusb6010 peripherals.

A word of caution: generic timing routine has been developed based
on understanding of gpmc timings, peripheral timings, available
custom timing routines, a kind of reverse engineering without
most of the datasheets & hardware (to be exact none of those supported
in mainline having custom timing routine) and by simulation.

gpmc timing dependency on peripheral timings:

[<gpmc_timing>: <peripheral timing1>, <peripheral timing2> ...]

1. common

cs_on:
	t_ceasu
adv_on:
	t_avdasu, t_ceavd

2. sync common

sync_clk:
	clk
page_burst_access:
	t_bacc
clk_activation:
	t_ces, t_avds

3. read async muxed

adv_rd_off:
	t_avdp_r
oe_on:
	t_oeasu, t_aavdh
access:
	t_iaa, t_oe, t_ce, t_aa
rd_cycle:
	t_rd_cycle, t_cez_r, t_oez

4. read async non-muxed

adv_rd_off:
	t_avdp_r
oe_on:
	t_oeasu
access:
	t_iaa, t_oe, t_ce, t_aa
rd_cycle:
	t_rd_cycle, t_cez_r, t_oez

5. read sync muxed

adv_rd_off:
	t_avdp_r, t_avdh
oe_on:
	t_oeasu, t_ach, cyc_aavdh_oe
access:
	t_iaa, cyc_iaa, cyc_oe
rd_cycle:
	t_cez_r, t_oez, t_ce_rdyz

6. read sync non-muxed

adv_rd_off:
	t_avdp_r
oe_on:
	t_oeasu
access:
	t_iaa, cyc_iaa, cyc_oe
rd_cycle:
	t_cez_r, t_oez, t_ce_rdyz

7. write async muxed

adv_wr_off:
	t_avdp_w
we_on, wr_data_mux_bus:
	t_weasu, t_aavdh, cyc_aavhd_we
we_off:
	t_wpl
cs_wr_off:
	t_wph
wr_cycle:
	t_cez_w, t_wr_cycle

8. write async non-muxed

adv_wr_off:
	t_avdp_w
we_on, wr_data_mux_bus:
	t_weasu
we_off:
	t_wpl
cs_wr_off:
	t_wph
wr_cycle:
	t_cez_w, t_wr_cycle

9. write sync muxed

adv_wr_off:
	t_avdp_w, t_avdh
we_on, wr_data_mux_bus:
	t_weasu, t_rdyo, t_aavdh, cyc_aavhd_we
we_off:
	t_wpl, cyc_wpl
cs_wr_off:
	t_wph
wr_cycle:
	t_cez_w, t_ce_rdyz

10. write sync non-muxed

adv_wr_off:
	t_avdp_w
we_on, wr_data_mux_bus:
	t_weasu, t_rdyo
we_off:
	t_wpl, cyc_wpl
cs_wr_off:
	t_wph
wr_cycle:
	t_cez_w, t_ce_rdyz

Note:
  Many of gpmc timings are dependent on other gpmc timings (a few
  gpmc timings purely dependent on other gpmc timings, a reason that
  some of the gpmc timings are missing above), and it will result in
  indirect dependency of peripheral timings to gpmc timings other than
  mentioned above, refer timing routine for more details. To know what
  these peripheral timings correspond to, please see explanations in
  struct gpmc_device_timings definition. And for gpmc timings refer
  IP details (link above).


code:
=================
MEN Chameleon Bus
=================

.. Table of Contents
   =================
   1 Introduction
       1.1 Scope of this Document
       1.2 Limitations of the current implementation
   2 Architecture
       2.1 MEN Chameleon Bus
       2.2 Carrier Devices
       2.3 Parser
   3 Resource handling
       3.1 Memory Resources
       3.2 IRQs
   4 Writing an MCB driver
       4.1 The driver structure
       4.2 Probing and attaching
       4.3 Initializing the driver
       4.4 Using DMA

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

This document describes the architecture and implementation of the MEN
Chameleon Bus (called MCB throughout this document).

Scope of this Document
----------------------

This document is intended to be a short overview of the current
implementation and does by no means describe the complete possibilities of MCB
based devices.

Limitations of the current implementation
-----------------------------------------

The current implementation is limited to PCI and PCIe based carrier devices
that only use a single memory resource and share the PCI legacy IRQ.  Not
implemented are:

- Multi-resource MCB devices like the VME Controller or M-Module carrier.
- MCB devices that need another MCB device, like SRAM for a DMA Controller's
  buffer descriptors or a video controller's video memory.
- A per-carrier IRQ domain for carrier devices that have one (or more) IRQs
  per MCB device like PCIe based carriers with MSI or MSI-X support.

Architecture
============

MCB is divided into 3 functional blocks:

- The MEN Chameleon Bus itself,
- drivers for MCB Carrier Devices and
- the parser for the Chameleon table.

MEN Chameleon Bus
-----------------

The MEN Chameleon Bus is an artificial bus system that attaches to a so
called Chameleon FPGA device found on some hardware produced my MEN Mikro
Elektronik GmbH. These devices are multi-function devices implemented in a
single FPGA and usually attached via some sort of PCI or PCIe link. Each
FPGA contains a header section describing the content of the FPGA. The
header lists the device id, PCI BAR, offset from the beginning of the PCI
BAR, size in the FPGA, interrupt number and some other properties currently
not handled by the MCB implementation.

Carrier Devices
---------------

A carrier device is just an abstraction for the real world physical bus the
Chameleon FPGA is attached to. Some IP Core drivers may need to interact with
properties of the carrier device (like querying the IRQ number of a PCI
device). To provide abstraction from the real hardware bus, an MCB carrier
device provides callback methods to translate the driver's MCB function calls
to hardware related function calls. For example a carrier device may
implement the get_irq() method which can be translated into a hardware bus
query for the IRQ number the device should use.

Parser
------

The parser reads the first 512 bytes of a Chameleon device and parses the
Chameleon table. Currently the parser only supports the Chameleon v2 variant
of the Chameleon table but can easily be adopted to support an older or
possible future variant. While parsing the table's entries new MCB devices
are allocated and their resources are assigned according to the resource
assignment in the Chameleon table. After resource assignment is finished, the
MCB devices are registered at the MCB and thus at the driver core of the
Linux kernel.

Resource handling
=================

The current implementation assigns exactly one memory and one IRQ resource
per MCB device. But this is likely going to change in the future.

Memory Resources
----------------

Each MCB device has exactly one memory resource, which can be requested from
the MCB bus. This memory resource is the physical address of the MCB device
inside the carrier and is intended to be passed to ioremap() and friends. It
is already requested from the kernel by calling request_mem_region().

IRQs
----

Each MCB device has exactly one IRQ resource, which can be requested from the
MCB bus. If a carrier device driver implements the ->get_irq() callback
method, the IRQ number assigned by the carrier device will be returned,
otherwise the IRQ number inside the Chameleon table will be returned. This
number is suitable to be passed to request_irq().

Writing an MCB driver
=====================

The driver structure
--------------------

Each MCB driver has a structure to identify the device driver as well as
device ids which identify the IP Core inside the FPGA. The driver structure
also contains callback methods which get executed on driver probe and
removal from the system::

	static const struct mcb_device_id foo_ids[] = {
		{ .device = 0x123 },
		{ }
	};
	MODULE_DEVICE_TABLE(mcb, foo_ids);

	static struct mcb_driver foo_driver = {
	driver = {
		.name = "foo-bar",
		.owner = THIS_MODULE,
	},
		.probe = foo_probe,
		.remove = foo_remove,
		.id_table = foo_ids,
	};

Probing and attaching
---------------------

When a driver is loaded and the MCB devices it services are found, the MCB
core will call the driver's probe callback method. When the driver is removed
from the system, the MCB core will call the driver's remove callback method::

	static init foo_probe(struct mcb_device *mdev, const struct mcb_device_id *id);
	static void foo_remove(struct mcb_device *mdev);

Initializing the driver
-----------------------

When the kernel is booted or your foo driver module is inserted, you have to
perform driver initialization. Usually it is enough to register your driver
module at the MCB core::

	static int __init foo_init(void)
	{
		return mcb_register_driver(&foo_driver);
	}
	module_init(foo_init);

	static void __exit foo_exit(void)
	{
		mcb_unregister_driver(&foo_driver);
	}
	module_exit(foo_exit);

The module_mcb_driver() macro can be used to reduce the above code::

	module_mcb_driver(foo_driver);

Using DMA
---------

To make use of the kernel's DMA-API's function, you will need to use the
carrier device's 'struct device'. Fortunately 'struct mcb_device' embeds a
pointer (->dma_dev) to the carrier's device for DMA purposes::

        ret = dma_set_mask_and_coherent(&mdev->dma_dev, DMA_BIT_MASK(dma_bits));
        if (rc)
                /* Handle errors */


code:
Message-based devices
=====================

Fusion message devices
----------------------

.. kernel-doc:: drivers/message/fusion/mptbase.c
   :export:

.. kernel-doc:: drivers/message/fusion/mptscsih.c
   :export:


code:
Miscellaneous Devices
=====================

.. kernel-doc:: drivers/char/misc.c
   :export:


code:
Parallel Port Devices
=====================

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

.. kernel-doc:: drivers/parport/ieee1284.c
   :export:

.. kernel-doc:: drivers/parport/share.c
   :export:

.. kernel-doc:: drivers/parport/daisy.c
   :internal:

16x50 UART Driver
=================

.. kernel-doc:: drivers/tty/serial/8250/8250_core.c
   :export:

See serial/driver.rst for related APIs.

Pulse-Width Modulation (PWM)
============================

Pulse-width modulation is a modulation technique primarily used to
control power supplied to electrical devices.

The PWM framework provides an abstraction for providers and consumers of
PWM signals. A controller that provides one or more PWM signals is
registered as :c:type:`struct pwm_chip <pwm_chip>`. Providers
are expected to embed this structure in a driver-specific structure.
This structure contains fields that describe a particular chip.

A chip exposes one or more PWM signal sources, each of which exposed as
a :c:type:`struct pwm_device <pwm_device>`. Operations can be
performed on PWM devices to control the period, duty cycle, polarity and
active state of the signal.

Note that PWM devices are exclusive resources: they can always only be
used by one consumer at a time.

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

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


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

========================
MMC/SD/SDIO card support
========================

.. toctree::
   :maxdepth: 1

   mmc-dev-attrs
   mmc-dev-parts
   mmc-async-req
   mmc-tools


code:
========================
MMC Asynchronous Request
========================

Rationale
=========

How significant is the cache maintenance overhead?

It depends. Fast eMMC and multiple cache levels with speculative cache
pre-fetch makes the cache overhead relatively significant. If the DMA
preparations for the next request are done in parallel with the current
transfer, the DMA preparation overhead would not affect the MMC performance.

The intention of non-blocking (asynchronous) MMC requests is to minimize the
time between when an MMC request ends and another MMC request begins.

Using mmc_wait_for_req(), the MMC controller is idle while dma_map_sg and
dma_unmap_sg are processing. Using non-blocking MMC requests makes it
possible to prepare the caches for next job in parallel with an active
MMC request.

MMC block driver
================

The mmc_blk_issue_rw_rq() in the MMC block driver is made non-blocking.

The increase in throughput is proportional to the time it takes to
prepare (major part of preparations are dma_map_sg() and dma_unmap_sg())
a request and how fast the memory is. The faster the MMC/SD is the
more significant the prepare request time becomes. Roughly the expected
performance gain is 5% for large writes and 10% on large reads on a L2 cache
platform. In power save mode, when clocks run on a lower frequency, the DMA
preparation may cost even more. As long as these slower preparations are run
in parallel with the transfer performance won't be affected.

Details on measurements from IOZone and mmc_test
================================================

https://wiki.linaro.org/WorkingGroups/Kernel/Specs/StoragePerfMMC-async-req

MMC core API extension
======================

There is one new public function mmc_start_req().

It starts a new MMC command request for a host. The function isn't
truly non-blocking. If there is an ongoing async request it waits
for completion of that request and starts the new one and returns. It
doesn't wait for the new request to complete. If there is no ongoing
request it starts the new request and returns immediately.

MMC host extensions
===================

There are two optional members in the mmc_host_ops -- pre_req() and
post_req() -- that the host driver may implement in order to move work
to before and after the actual mmc_host_ops.request() function is called.

In the DMA case pre_req() may do dma_map_sg() and prepare the DMA
descriptor, and post_req() runs the dma_unmap_sg().

Optimize for the first request
==============================

The first request in a series of requests can't be prepared in parallel
with the previous transfer, since there is no previous request.

The argument is_first_req in pre_req() indicates that there is no previous
request. The host driver may optimize for this scenario to minimize
the performance loss. A way to optimize for this is to split the current
request in two chunks, prepare the first chunk and start the request,
and finally prepare the second chunk and start the transfer.

Pseudocode to handle is_first_req scenario with minimal prepare overhead::

  if (is_first_req && req->size > threshold)
     /* start MMC transfer for the complete transfer size */
     mmc_start_command(MMC_CMD_TRANSFER_FULL_SIZE);

     /*
      * Begin to prepare DMA while cmd is being processed by MMC.
      * The first chunk of the request should take the same time
      * to prepare as the "MMC process command time".
      * If prepare time exceeds MMC cmd time
      * the transfer is delayed, guesstimate max 4k as first chunk size.
      */
      prepare_1st_chunk_for_dma(req);
      /* flush pending desc to the DMAC (dmaengine.h) */
      dma_issue_pending(req->dma_desc);

      prepare_2nd_chunk_for_dma(req);
      /*
       * The second issue_pending should be called before MMC runs out
       * of the first chunk. If the MMC runs out of the first data chunk
       * before this call, the transfer is delayed.
       */
      dma_issue_pending(req->dma_desc);


code:
==================================
SD and MMC Block Device Attributes
==================================

These attributes are defined for the block devices associated with the
SD or MMC device.

The following attributes are read/write.

	========		===============================================
	force_ro		Enforce read-only access even if write protect 					switch is off.
	========		===============================================

SD and MMC Device Attributes
============================

All attributes are read-only.

	======================	===============================================
	cid			Card Identification Register
	csd			Card Specific Data Register
	scr			SD Card Configuration Register (SD only)
	date			Manufacturing Date (from CID Register)
	fwrev			Firmware/Product Revision (from CID Register)
				(SD and MMCv1 only)
	hwrev			Hardware/Product Revision (from CID Register)
				(SD and MMCv1 only)
	manfid			Manufacturer ID (from CID Register)
	name			Product Name (from CID Register)
	oemid			OEM/Application ID (from CID Register)
	prv			Product Revision (from CID Register)
				(SD and MMCv4 only)
	serial			Product Serial Number (from CID Register)
	erase_size		Erase group size
	preferred_erase_size	Preferred erase size
	raw_rpmb_size_mult	RPMB partition size
	rel_sectors		Reliable write sector count
	ocr 			Operation Conditions Register
	dsr			Driver Stage Register
	cmdq_en			Command Queue enabled:

					1 => enabled, 0 => not enabled
	======================	===============================================

Note on Erase Size and Preferred Erase Size:

	"erase_size" is the  minimum size, in bytes, of an erase
	operation.  For MMC, "erase_size" is the erase group size
	reported by the card.  Note that "erase_size" does not apply
	to trim or secure trim operations where the minimum size is
	always one 512 byte sector.  For SD, "erase_size" is 512
	if the card is block-addressed, 0 otherwise.

	SD/MMC cards can erase an arbitrarily large area up to and
	including the whole card.  When erasing a large area it may
	be desirable to do it in smaller chunks for three reasons:

	     1. A single erase command will make all other I/O on
		the card wait.  This is not a problem if the whole card
		is being erased, but erasing one partition will make
		I/O for another partition on the same card wait for the
		duration of the erase - which could be a several
		minutes.
	     2. To be able to inform the user of erase progress.
	     3. The erase timeout becomes too large to be very
		useful.  Because the erase timeout contains a margin
		which is multiplied by the size of the erase area,
		the value can end up being several minutes for large
		areas.

	"erase_size" is not the most efficient unit to erase
	(especially for SD where it is just one sector),
	hence "preferred_erase_size" provides a good chunk
	size for erasing large areas.

	For MMC, "preferred_erase_size" is the high-capacity
	erase size if a card specifies one, otherwise it is
	based on the capacity of the card.

	For SD, "preferred_erase_size" is the allocation unit
	size specified by the card.

	"preferred_erase_size" is in bytes.

Note on raw_rpmb_size_mult:

	"raw_rpmb_size_mult" is a multiple of 128kB block.

	RPMB size in byte is calculated by using the following equation:

		RPMB partition size = 128kB x raw_rpmb_size_mult


code:
============================
SD and MMC Device Partitions
============================

Device partitions are additional logical block devices present on the
SD/MMC device.

As of this writing, MMC boot partitions as supported and exposed as
/dev/mmcblkXboot0 and /dev/mmcblkXboot1, where X is the index of the
parent /dev/mmcblkX.

MMC Boot Partitions
===================

Read and write access is provided to the two MMC boot partitions. Due to
the sensitive nature of the boot partition contents, which often store
a bootloader or bootloader configuration tables crucial to booting the
platform, write access is disabled by default to reduce the chance of
accidental bricking.

To enable write access to /dev/mmcblkXbootY, disable the forced read-only
access with::

	echo 0 > /sys/block/mmcblkXbootY/force_ro

To re-enable read-only access::

	echo 1 > /sys/block/mmcblkXbootY/force_ro

The boot partitions can also be locked read only until the next power on,
with::

	echo 1 > /sys/block/mmcblkXbootY/ro_lock_until_next_power_on

This is a feature of the card and not of the kernel. If the card does
not support boot partition locking, the file will not exist. If the
feature has been disabled on the card, the file will be read-only.

The boot partitions can also be locked permanently, but this feature is
not accessible through sysfs in order to avoid accidental or malicious
bricking.


code:
======================
MMC tools introduction
======================

There is one MMC test tools called mmc-utils, which is maintained by Ulf Hansson,
you can find it at the below public git repository:

	https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git

Functions
=========

The mmc-utils tools can do the following:

 - Print and parse extcsd data.
 - Determine the eMMC writeprotect status.
 - Set the eMMC writeprotect status.
 - Set the eMMC data sector size to 4KB by disabling emulation.
 - Create general purpose partition.
 - Enable the enhanced user area.
 - Enable write reliability per partition.
 - Print the response to STATUS_SEND (CMD13).
 - Enable the boot partition.
 - Set Boot Bus Conditions.
 - Enable the eMMC BKOPS feature.
 - Permanently enable the eMMC H/W Reset feature.
 - Permanently disable the eMMC H/W Reset feature.
 - Send Sanitize command.
 - Program authentication key for the device.
 - Counter value for the rpmb device will be read to stdout.
 - Read from rpmb device to output.
 - Write to rpmb device from data file.
 - Enable the eMMC cache feature.
 - Disable the eMMC cache feature.
 - Print and parse CID data.
 - Print and parse CSD data.
 - Print and parse SCR data.


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

==============================
Memory Technology Device (MTD)
==============================

.. toctree::
   :maxdepth: 1

   spi-intel
   nand_ecc
   spi-nor