code:
================================
Devres - Managed Device Resource
================================

Tejun Heo	<teheo@suse.de>

First draft	10 January 2007

.. contents

   1. Intro			: Huh? Devres?
   2. Devres			: Devres in a nutshell
   3. Devres Group		: Group devres'es and release them together
   4. Details			: Life time rules, calling context, ...
   5. Overhead			: How much do we have to pay for this?
   6. List of managed interfaces: Currently implemented managed interfaces

1. Intro
--------

devres came up while trying to convert libata to use iomap.  Each
iomapped address should be kept and unmapped on driver detach.  For
example, a plain SFF ATA controller (that is, good old PCI IDE) in
native mode makes use of 5 PCI BARs and all of them should be
maintained.

As with many other device drivers, libata low level drivers have
sufficient bugs in ->remove and ->probe failure path.  Well, yes,
that's probably because libata low level driver developers are lazy
bunch, but aren't all low level driver developers?  After spending a
day fiddling with braindamaged hardware with no document or
braindamaged document, if it's finally working, well, it's working.

For one reason or another, low level drivers don't receive as much
attention or testing as core code, and bugs on driver detach or
initialization failure don't happen often enough to be noticeable.
Init failure path is worse because it's much less travelled while
needs to handle multiple entry points.

So, many low level drivers end up leaking resources on driver detach
and having half broken failure path implementation in ->probe() which
would leak resources or even cause oops when failure occurs.  iomap
adds more to this mix.  So do msi and msix.

2. Devres
---------

devres is basically linked list of arbitrarily sized memory areas
associated with a struct device.  Each devres entry is associated with
a release function.  A devres can be released in several ways.  No
matter what, all devres entries are released on driver detach.  On
release, the associated release function is invoked and then the
devres entry is freed.

Managed interface is created for resources commonly used by device
drivers using devres.  For example, coherent DMA memory is acquired
using dma_alloc_coherent().  The managed version is called
dmam_alloc_coherent().  It is identical to dma_alloc_coherent() except
for the DMA memory allocated using it is managed and will be
automatically released on driver detach.  Implementation looks like
the following::

  struct dma_devres {
	size_t		size;
	void		*vaddr;
	dma_addr_t	dma_handle;
  };

  static void dmam_coherent_release(struct device *dev, void *res)
  {
	struct dma_devres *this = res;

	dma_free_coherent(dev, this->size, this->vaddr, this->dma_handle);
  }

  dmam_alloc_coherent(dev, size, dma_handle, gfp)
  {
	struct dma_devres *dr;
	void *vaddr;

	dr = devres_alloc(dmam_coherent_release, sizeof(*dr), gfp);
	...

	/* alloc DMA memory as usual */
	vaddr = dma_alloc_coherent(...);
	...

	/* record size, vaddr, dma_handle in dr */
	dr->vaddr = vaddr;
	...

	devres_add(dev, dr);

	return vaddr;
  }

If a driver uses dmam_alloc_coherent(), the area is guaranteed to be
freed whether initialization fails half-way or the device gets
detached.  If most resources are acquired using managed interface, a
driver can have much simpler init and exit code.  Init path basically
looks like the following::

  my_init_one()
  {
	struct mydev *d;

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

	d->ring = dmam_alloc_coherent(...);
	if (!d->ring)
		return -ENOMEM;

	if (check something)
		return -EINVAL;
	...

	return register_to_upper_layer(d);
  }

And exit path::

  my_remove_one()
  {
	unregister_from_upper_layer(d);
	shutdown_my_hardware();
  }

As shown above, low level drivers can be simplified a lot by using
devres.  Complexity is shifted from less maintained low level drivers
to better maintained higher layer.  Also, as init failure path is
shared with exit path, both can get more testing.

Note though that when converting current calls or assignments to
managed devm_* versions it is up to you to check if internal operations
like allocating memory, have failed. Managed resources pertains to the
freeing of these resources *only* - all other checks needed are still
on you. In some cases this may mean introducing checks that were not
necessary before moving to the managed devm_* calls.

3. Devres group
---------------

Devres entries can be grouped using devres group.  When a group is
released, all contained normal devres entries and properly nested
groups are released.  One usage is to rollback series of acquired
resources on failure.  For example::

  if (!devres_open_group(dev, NULL, GFP_KERNEL))
	return -ENOMEM;

  acquire A;
  if (failed)
	goto err;

  acquire B;
  if (failed)
	goto err;
  ...

  devres_remove_group(dev, NULL);
  return 0;

 err:
  devres_release_group(dev, NULL);
  return err_code;

As resource acquisition failure usually means probe failure, constructs
like above are usually useful in midlayer driver (e.g. libata core
layer) where interface function shouldn't have side effect on failure.
For LLDs, just returning error code suffices in most cases.

Each group is identified by `void *id`.  It can either be explicitly
specified by @id argument to devres_open_group() or automatically
created by passing NULL as @id as in the above example.  In both
cases, devres_open_group() returns the group's id.  The returned id
can be passed to other devres functions to select the target group.
If NULL is given to those functions, the latest open group is
selected.

For example, you can do something like the following::

  int my_midlayer_create_something()
  {
	if (!devres_open_group(dev, my_midlayer_create_something, GFP_KERNEL))
		return -ENOMEM;

	...

	devres_close_group(dev, my_midlayer_create_something);
	return 0;
  }

  void my_midlayer_destroy_something()
  {
	devres_release_group(dev, my_midlayer_create_something);
  }

4. Details
----------

Lifetime of a devres entry begins on devres allocation and finishes
when it is released or destroyed (removed and freed) - no reference
counting.

devres core guarantees atomicity to all basic devres operations and
has support for single-instance devres types (atomic
lookup-and-add-if-not-found).  Other than that, synchronizing
concurrent accesses to allocated devres data is caller's
responsibility.  This is usually non-issue because bus ops and
resource allocations already do the job.

For an example of single-instance devres type, read pcim_iomap_table()
in lib/devres.c.

All devres interface functions can be called without context if the
right gfp mask is given.

5. Overhead
-----------

Each devres bookkeeping info is allocated together with requested data
area.  With debug option turned off, bookkeeping info occupies 16
bytes on 32bit machines and 24 bytes on 64bit (three pointers rounded
up to ull alignment).  If singly linked list is used, it can be
reduced to two pointers (8 bytes on 32bit, 16 bytes on 64bit).

Each devres group occupies 8 pointers.  It can be reduced to 6 if
singly linked list is used.

Memory space overhead on ahci controller with two ports is between 300
and 400 bytes on 32bit machine after naive conversion (we can
certainly invest a bit more effort into libata core layer).

6. List of managed interfaces
-----------------------------

CLOCK
  devm_clk_get()
  devm_clk_get_optional()
  devm_clk_put()
  devm_clk_bulk_get()
  devm_clk_bulk_get_all()
  devm_clk_bulk_get_optional()
  devm_get_clk_from_child()
  devm_clk_hw_register()
  devm_of_clk_add_hw_provider()
  devm_clk_hw_register_clkdev()

DMA
  dmaenginem_async_device_register()
  dmam_alloc_coherent()
  dmam_alloc_attrs()
  dmam_free_coherent()
  dmam_pool_create()
  dmam_pool_destroy()

DRM
  devm_drm_dev_alloc()

GPIO
  devm_gpiod_get()
  devm_gpiod_get_array()
  devm_gpiod_get_array_optional()
  devm_gpiod_get_index()
  devm_gpiod_get_index_optional()
  devm_gpiod_get_optional()
  devm_gpiod_put()
  devm_gpiod_unhinge()
  devm_gpiochip_add_data()
  devm_gpio_request()
  devm_gpio_request_one()

I2C
  devm_i2c_add_adapter()
  devm_i2c_new_dummy_device()

IIO
  devm_iio_device_alloc()
  devm_iio_device_register()
  devm_iio_dmaengine_buffer_setup()
  devm_iio_kfifo_buffer_setup()
  devm_iio_kfifo_buffer_setup_ext()
  devm_iio_map_array_register()
  devm_iio_triggered_buffer_setup()
  devm_iio_triggered_buffer_setup_ext()
  devm_iio_trigger_alloc()
  devm_iio_trigger_register()
  devm_iio_channel_get()
  devm_iio_channel_get_all()
  devm_iio_hw_consumer_alloc()
  devm_fwnode_iio_channel_get_by_name()

INPUT
  devm_input_allocate_device()

IO region
  devm_release_mem_region()
  devm_release_region()
  devm_release_resource()
  devm_request_mem_region()
  devm_request_free_mem_region()
  devm_request_region()
  devm_request_resource()

IOMAP
  devm_ioport_map()
  devm_ioport_unmap()
  devm_ioremap()
  devm_ioremap_uc()
  devm_ioremap_wc()
  devm_ioremap_resource() : checks resource, requests memory region, ioremaps
  devm_ioremap_resource_wc()
  devm_platform_ioremap_resource() : calls devm_ioremap_resource() for platform device
  devm_platform_ioremap_resource_byname()
  devm_platform_get_and_ioremap_resource()
  devm_iounmap()
  pcim_iomap()
  pcim_iomap_regions()	: do request_region() and iomap() on multiple BARs
  pcim_iomap_table()	: array of mapped addresses indexed by BAR
  pcim_iounmap()

IRQ
  devm_free_irq()
  devm_request_any_context_irq()
  devm_request_irq()
  devm_request_threaded_irq()
  devm_irq_alloc_descs()
  devm_irq_alloc_desc()
  devm_irq_alloc_desc_at()
  devm_irq_alloc_desc_from()
  devm_irq_alloc_descs_from()
  devm_irq_alloc_generic_chip()
  devm_irq_setup_generic_chip()
  devm_irq_domain_create_sim()

LED
  devm_led_classdev_register()
  devm_led_classdev_register_ext()
  devm_led_classdev_unregister()
  devm_led_trigger_register()
  devm_of_led_get()

MDIO
  devm_mdiobus_alloc()
  devm_mdiobus_alloc_size()
  devm_mdiobus_register()
  devm_of_mdiobus_register()

MEM
  devm_free_pages()
  devm_get_free_pages()
  devm_kasprintf()
  devm_kcalloc()
  devm_kfree()
  devm_kmalloc()
  devm_kmalloc_array()
  devm_kmemdup()
  devm_krealloc()
  devm_kstrdup()
  devm_kstrdup_const()
  devm_kvasprintf()
  devm_kzalloc()

MFD
  devm_mfd_add_devices()

MUX
  devm_mux_chip_alloc()
  devm_mux_chip_register()
  devm_mux_control_get()
  devm_mux_state_get()

NET
  devm_alloc_etherdev()
  devm_alloc_etherdev_mqs()
  devm_register_netdev()

PER-CPU MEM
  devm_alloc_percpu()
  devm_free_percpu()

PCI
  devm_pci_alloc_host_bridge()  : managed PCI host bridge allocation
  devm_pci_remap_cfgspace()	: ioremap PCI configuration space
  devm_pci_remap_cfg_resource()	: ioremap PCI configuration space resource
  pcim_enable_device()		: after success, all PCI ops become managed
  pcim_pin_device()		: keep PCI device enabled after release

PHY
  devm_usb_get_phy()
  devm_usb_get_phy_by_node()
  devm_usb_get_phy_by_phandle()
  devm_usb_put_phy()

PINCTRL
  devm_pinctrl_get()
  devm_pinctrl_put()
  devm_pinctrl_get_select()
  devm_pinctrl_register()
  devm_pinctrl_register_and_init()
  devm_pinctrl_unregister()

POWER
  devm_reboot_mode_register()
  devm_reboot_mode_unregister()

PWM
  devm_pwmchip_add()
  devm_pwm_get()
  devm_fwnode_pwm_get()

REGULATOR
  devm_regulator_bulk_register_supply_alias()
  devm_regulator_bulk_get()
  devm_regulator_bulk_get_const()
  devm_regulator_bulk_get_enable()
  devm_regulator_bulk_put()
  devm_regulator_get()
  devm_regulator_get_enable()
  devm_regulator_get_enable_optional()
  devm_regulator_get_exclusive()
  devm_regulator_get_optional()
  devm_regulator_irq_helper()
  devm_regulator_put()
  devm_regulator_register()
  devm_regulator_register_notifier()
  devm_regulator_register_supply_alias()
  devm_regulator_unregister_notifier()

RESET
  devm_reset_control_get()
  devm_reset_controller_register()

RTC
  devm_rtc_device_register()
  devm_rtc_allocate_device()
  devm_rtc_register_device()
  devm_rtc_nvmem_register()

SERDEV
  devm_serdev_device_open()

SLAVE DMA ENGINE
  devm_acpi_dma_controller_register()

SPI
  devm_spi_alloc_master()
  devm_spi_alloc_slave()
  devm_spi_register_master()

WATCHDOG
  devm_watchdog_register_device()


code:
==============
Device Drivers
==============

See the kerneldoc for the struct device_driver.

Allocation
~~~~~~~~~~

Device drivers are statically allocated structures. Though there may
be multiple devices in a system that a driver supports, struct
device_driver represents the driver as a whole (not a particular
device instance).

Initialization
~~~~~~~~~~~~~~

The driver must initialize at least the name and bus fields. It should
also initialize the devclass field (when it arrives), so it may obtain
the proper linkage internally. It should also initialize as many of
the callbacks as possible, though each is optional.

Declaration
~~~~~~~~~~~

As stated above, struct device_driver objects are statically
allocated. Below is an example declaration of the eepro100
driver. This declaration is hypothetical only; it relies on the driver
being converted completely to the new model::

  static struct device_driver eepro100_driver = {
         .name		= "eepro100",
         .bus		= &pci_bus_type,

         .probe		= eepro100_probe,
         .remove		= eepro100_remove,
         .suspend		= eepro100_suspend,
         .resume		= eepro100_resume,
  };

Most drivers will not be able to be converted completely to the new
model because the bus they belong to has a bus-specific structure with
bus-specific fields that cannot be generalized.

The most common example of this are device ID structures. A driver
typically defines an array of device IDs that it supports. The format
of these structures and the semantics for comparing device IDs are
completely bus-specific. Defining them as bus-specific entities would
sacrifice type-safety, so we keep bus-specific structures around.

Bus-specific drivers should include a generic struct device_driver in
the definition of the bus-specific driver. Like this::

  struct pci_driver {
         const struct pci_device_id *id_table;
         struct device_driver	  driver;
  };

A definition that included bus-specific fields would look like
(using the eepro100 driver again)::

  static struct pci_driver eepro100_driver = {
         .id_table       = eepro100_pci_tbl,
         .driver	       = {
		.name		= "eepro100",
		.bus		= &pci_bus_type,
		.probe		= eepro100_probe,
		.remove		= eepro100_remove,
		.suspend	= eepro100_suspend,
		.resume		= eepro100_resume,
         },
  };

Some may find the syntax of embedded struct initialization awkward or
even a bit ugly. So far, it's the best way we've found to do what we want...

Registration
~~~~~~~~~~~~

::

  int driver_register(struct device_driver *drv);

The driver registers the structure on startup. For drivers that have
no bus-specific fields (i.e. don't have a bus-specific driver
structure), they would use driver_register and pass a pointer to their
struct device_driver object.

Most drivers, however, will have a bus-specific structure and will
need to register with the bus using something like pci_driver_register.

It is important that drivers register their driver structure as early as
possible. Registration with the core initializes several fields in the
struct device_driver object, including the reference count and the
lock. These fields are assumed to be valid at all times and may be
used by the device model core or the bus driver.

Transition Bus Drivers
~~~~~~~~~~~~~~~~~~~~~~

By defining wrapper functions, the transition to the new model can be
made easier. Drivers can ignore the generic structure altogether and
let the bus wrapper fill in the fields. For the callbacks, the bus can
define generic callbacks that forward the call to the bus-specific
callbacks of the drivers.

This solution is intended to be only temporary. In order to get class
information in the driver, the drivers must be modified anyway. Since
converting drivers to the new model should reduce some infrastructural
complexity and code size, it is recommended that they are converted as
class information is added.

Access
~~~~~~

Once the object has been registered, it may access the common fields of
the object, like the lock and the list of devices::

  int driver_for_each_dev(struct device_driver *drv, void *data,
			  int (*callback)(struct device *dev, void *data));

The devices field is a list of all the devices that have been bound to
the driver. The LDM core provides a helper function to operate on all
the devices a driver controls. This helper locks the driver on each
node access, and does proper reference counting on each device as it
accesses it.

sysfs
~~~~~

When a driver is registered, a sysfs directory is created in its
bus's directory. In this directory, the driver can export an interface
to userspace to control operation of the driver on a global basis;
e.g. toggling debugging output in the driver.

A future feature of this directory will be a 'devices' directory. This
directory will contain symlinks to the directories of devices it
supports.

Callbacks
~~~~~~~~~

::

	int	(*probe)	(struct device *dev);

The probe() entry is called in task context, with the bus's rwsem locked
and the driver partially bound to the device.  Drivers commonly use
container_of() to convert "dev" to a bus-specific type, both in probe()
and other routines.  That type often provides device resource data, such
as pci_dev.resource[] or platform_device.resources, which is used in
addition to dev->platform_data to initialize the driver.

This callback holds the driver-specific logic to bind the driver to a
given device.  That includes verifying that the device is present, that
it's a version the driver can handle, that driver data structures can
be allocated and initialized, and that any hardware can be initialized.
Drivers often store a pointer to their state with dev_set_drvdata().
When the driver has successfully bound itself to that device, then probe()
returns zero and the driver model code will finish its part of binding
the driver to that device.

A driver's probe() may return a negative errno value to indicate that
the driver did not bind to this device, in which case it should have
released all resources it allocated.

Optionally, probe() may return -EPROBE_DEFER if the driver depends on
resources that are not yet available (e.g., supplied by a driver that
hasn't initialized yet).  The driver core will put the device onto the
deferred probe list and will try to call it again later. If a driver
must defer, it should return -EPROBE_DEFER as early as possible to
reduce the amount of time spent on setup work that will need to be
unwound and reexecuted at a later time.

.. warning::
      -EPROBE_DEFER must not be returned if probe() has already created
      child devices, even if those child devices are removed again
      in a cleanup path. If -EPROBE_DEFER is returned after a child
      device has been registered, it may result in an infinite loop of
      .probe() calls to the same driver.

::

	void	(*sync_state)	(struct device *dev);

sync_state is called only once for a device. It's called when all the consumer
devices of the device have successfully probed. The list of consumers of the
device is obtained by looking at the device links connecting that device to its
consumer devices.

The first attempt to call sync_state() is made during late_initcall_sync() to
give firmware and drivers time to link devices to each other. During the first
attempt at calling sync_state(), if all the consumers of the device at that
point in time have already probed successfully, sync_state() is called right
away. If there are no consumers of the device during the first attempt, that
too is considered as "all consumers of the device have probed" and sync_state()
is called right away.

If during the first attempt at calling sync_state() for a device, there are
still consumers that haven't probed successfully, the sync_state() call is
postponed and reattempted in the future only when one or more consumers of the
device probe successfully. If during the reattempt, the driver core finds that
there are one or more consumers of the device that haven't probed yet, then
sync_state() call is postponed again.

A typical use case for sync_state() is to have the kernel cleanly take over
management of devices from the bootloader. For example, if a device is left on
and at a particular hardware configuration by the bootloader, the device's
driver might need to keep the device in the boot configuration until all the
consumers of the device have probed. Once all the consumers of the device have
probed, the device's driver can synchronize the hardware state of the device to
match the aggregated software state requested by all the consumers. Hence the
name sync_state().

While obvious examples of resources that can benefit from sync_state() include
resources such as regulator, sync_state() can also be useful for complex
resources like IOMMUs. For example, IOMMUs with multiple consumers (devices
whose addresses are remapped by the IOMMU) might need to keep their mappings
fixed at (or additive to) the boot configuration until all its consumers have
probed.

While the typical use case for sync_state() is to have the kernel cleanly take
over management of devices from the bootloader, the usage of sync_state() is
not restricted to that. Use it whenever it makes sense to take an action after
all the consumers of a device have probed::

	int 	(*remove)	(struct device *dev);

remove is called to unbind a driver from a device. This may be
called if a device is physically removed from the system, if the
driver module is being unloaded, during a reboot sequence, or
in other cases.

It is up to the driver to determine if the device is present or
not. It should free any resources allocated specifically for the
device; i.e. anything in the device's driver_data field.

If the device is still present, it should quiesce the device and place
it into a supported low-power state.

::

	int	(*suspend)	(struct device *dev, pm_message_t state);

suspend is called to put the device in a low power state.

::

	int	(*resume)	(struct device *dev);

Resume is used to bring a device back from a low power state.

Attributes
~~~~~~~~~~

::

  struct driver_attribute {
          struct attribute        attr;
          ssize_t (*show)(struct device_driver *driver, char *buf);
          ssize_t (*store)(struct device_driver *, const char *buf, size_t count);
  };

Device drivers can export attributes via their sysfs directories.
Drivers can declare attributes using a DRIVER_ATTR_RW and DRIVER_ATTR_RO
macro that works identically to the DEVICE_ATTR_RW and DEVICE_ATTR_RO
macros.

Example::

	DRIVER_ATTR_RW(debug);

This is equivalent to declaring::

	struct driver_attribute driver_attr_debug;

This can then be used to add and remove the attribute from the
driver's directory using::

  int driver_create_file(struct device_driver *, const struct driver_attribute *);
  void driver_remove_file(struct device_driver *, const struct driver_attribute *);

repo_name: angery/linux


code:
============
Driver Model
============

.. toctree::
   :maxdepth: 1

   binding
   bus
   design-patterns
   device
   devres
   driver
   overview
   platform
   porting

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


code:
=============================
The Linux Kernel Device Model
=============================

Patrick Mochel	<mochel@digitalimplant.org>

Drafted 26 August 2002
Updated 31 January 2006

Overview
~~~~~~~~

The Linux Kernel Driver Model is a unification of all the disparate driver
models that were previously used in the kernel. It is intended to augment the
bus-specific drivers for bridges and devices by consolidating a set of data
and operations into globally accessible data structures.

Traditional driver models implemented some sort of tree-like structure
(sometimes just a list) for the devices they control. There wasn't any
uniformity across the different bus types.

The current driver model provides a common, uniform data model for describing
a bus and the devices that can appear under the bus. The unified bus
model includes a set of common attributes which all busses carry, and a set
of common callbacks, such as device discovery during bus probing, bus
shutdown, bus power management, etc.

The common device and bridge interface reflects the goals of the modern
computer: namely the ability to do seamless device "plug and play", power
management, and hot plug. In particular, the model dictated by Intel and
Microsoft (namely ACPI) ensures that almost every device on almost any bus
on an x86-compatible system can work within this paradigm.  Of course,
not every bus is able to support all such operations, although most
buses support most of those operations.

Downstream Access
~~~~~~~~~~~~~~~~~

Common data fields have been moved out of individual bus layers into a common
data structure. These fields must still be accessed by the bus layers,
and sometimes by the device-specific drivers.

Other bus layers are encouraged to do what has been done for the PCI layer.
struct pci_dev now looks like this::

  struct pci_dev {
	...

	struct device dev;     /* Generic device interface */
	...
  };

Note first that the struct device dev within the struct pci_dev is
statically allocated. This means only one allocation on device discovery.

Note also that that struct device dev is not necessarily defined at the
front of the pci_dev structure.  This is to make people think about what
they're doing when switching between the bus driver and the global driver,
and to discourage meaningless and incorrect casts between the two.

The PCI bus layer freely accesses the fields of struct device. It knows about
the structure of struct pci_dev, and it should know the structure of struct
device. Individual PCI device drivers that have been converted to the current
driver model generally do not and should not touch the fields of struct device,
unless there is a compelling reason to do so.

The above abstraction prevents unnecessary pain during transitional phases.
If it were not done this way, then when a field was renamed or removed, every
downstream driver would break.  On the other hand, if only the bus layer
(and not the device layer) accesses the struct device, it is only the bus
layer that needs to change.

User Interface
~~~~~~~~~~~~~~

By virtue of having a complete hierarchical view of all the devices in the
system, exporting a complete hierarchical view to userspace becomes relatively
easy. This has been accomplished by implementing a special purpose virtual
file system named sysfs.

Almost all mainstream Linux distros mount this filesystem automatically; you
can see some variation of the following in the output of the "mount" command::

  $ mount
  ...
  none on /sys type sysfs (rw,noexec,nosuid,nodev)
  ...
  $

The auto-mounting of sysfs is typically accomplished by an entry similar to
the following in the /etc/fstab file::

  none     	/sys	sysfs    defaults	  	0 0

or something similar in the /lib/init/fstab file on Debian-based systems::

  none            /sys    sysfs    nodev,noexec,nosuid    0 0

If sysfs is not automatically mounted, you can always do it manually with::

	# mount -t sysfs sysfs /sys

Whenever a device is inserted into the tree, a directory is created for it.
This directory may be populated at each layer of discovery - the global layer,
the bus layer, or the device layer.

The global layer currently creates two files - 'name' and 'power'. The
former only reports the name of the device. The latter reports the
current power state of the device. It will also be used to set the current
power state.

The bus layer may also create files for the devices it finds while probing the
bus. For example, the PCI layer currently creates 'irq' and 'resource' files
for each PCI device.

A device-specific driver may also export files in its directory to expose
device-specific data or tunable interfaces.

More information about the sysfs directory layout can be found in
the other documents in this directory and in the file
Documentation/filesystems/sysfs.rst.


code:
============================
Platform Devices and Drivers
============================

See <linux/platform_device.h> for the driver model interface to the
platform bus:  platform_device, and platform_driver.  This pseudo-bus
is used to connect devices on busses with minimal infrastructure,
like those used to integrate peripherals on many system-on-chip
processors, or some "legacy" PC interconnects; as opposed to large
formally specified ones like PCI or USB.

Platform devices
~~~~~~~~~~~~~~~~
Platform devices are devices that typically appear as autonomous
entities in the system. This includes legacy port-based devices and
host bridges to peripheral buses, and most controllers integrated
into system-on-chip platforms.  What they usually have in common
is direct addressing from a CPU bus.  Rarely, a platform_device will
be connected through a segment of some other kind of bus; but its
registers will still be directly addressable.

Platform devices are given a name, used in driver binding, and a
list of resources such as addresses and IRQs::

  struct platform_device {
	const char	*name;
	u32		id;
	struct device	dev;
	u32		num_resources;
	struct resource	*resource;
  };

Platform drivers
~~~~~~~~~~~~~~~~
Platform drivers follow the standard driver model convention, where
discovery/enumeration is handled outside the drivers, and drivers
provide probe() and remove() methods.  They support power management
and shutdown notifications using the standard conventions::

  struct platform_driver {
	int (*probe)(struct platform_device *);
	int (*remove)(struct platform_device *);
	void (*shutdown)(struct platform_device *);
	int (*suspend)(struct platform_device *, pm_message_t state);
	int (*suspend_late)(struct platform_device *, pm_message_t state);
	int (*resume_early)(struct platform_device *);
	int (*resume)(struct platform_device *);
	struct device_driver driver;
  };

Note that probe() should in general verify that the specified device hardware
actually exists; sometimes platform setup code can't be sure.  The probing
can use device resources, including clocks, and device platform_data.

Platform drivers register themselves the normal way::

	int platform_driver_register(struct platform_driver *drv);

Or, in common situations where the device is known not to be hot-pluggable,
the probe() routine can live in an init section to reduce the driver's
runtime memory footprint::

	int platform_driver_probe(struct platform_driver *drv,
			  int (*probe)(struct platform_device *))

Kernel modules can be composed of several platform drivers. The platform core
provides helpers to register and unregister an array of drivers::

	int __platform_register_drivers(struct platform_driver * const *drivers,
				      unsigned int count, struct module *owner);
	void platform_unregister_drivers(struct platform_driver * const *drivers,
					 unsigned int count);

If one of the drivers fails to register, all drivers registered up to that
point will be unregistered in reverse order. Note that there is a convenience
macro that passes THIS_MODULE as owner parameter::

	#define platform_register_drivers(drivers, count)

Device Enumeration
~~~~~~~~~~~~~~~~~~
As a rule, platform specific (and often board-specific) setup code will
register platform devices::

	int platform_device_register(struct platform_device *pdev);

	int platform_add_devices(struct platform_device **pdevs, int ndev);

The general rule is to register only those devices that actually exist,
but in some cases extra devices might be registered.  For example, a kernel
might be configured to work with an external network adapter that might not
be populated on all boards, or likewise to work with an integrated controller
that some boards might not hook up to any peripherals.

In some cases, boot firmware will export tables describing the devices
that are populated on a given board.   Without such tables, often the
only way for system setup code to set up the correct devices is to build
a kernel for a specific target board.  Such board-specific kernels are
common with embedded and custom systems development.

In many cases, the memory and IRQ resources associated with the platform
device are not enough to let the device's driver work.  Board setup code
will often provide additional information using the device's platform_data
field to hold additional information.

Embedded systems frequently need one or more clocks for platform devices,
which are normally kept off until they're actively needed (to save power).
System setup also associates those clocks with the device, so that
calls to clk_get(&pdev->dev, clock_name) return them as needed.

Legacy Drivers:  Device Probing
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some drivers are not fully converted to the driver model, because they take
on a non-driver role:  the driver registers its platform device, rather than
leaving that for system infrastructure.  Such drivers can't be hotplugged
or coldplugged, since those mechanisms require device creation to be in a
different system component than the driver.

The only "good" reason for this is to handle older system designs which, like
original IBM PCs, rely on error-prone "probe-the-hardware" models for hardware
configuration.  Newer systems have largely abandoned that model, in favor of
bus-level support for dynamic configuration (PCI, USB), or device tables
provided by the boot firmware (e.g. PNPACPI on x86).  There are too many
conflicting options about what might be where, and even educated guesses by
an operating system will be wrong often enough to make trouble.

This style of driver is discouraged.  If you're updating such a driver,
please try to move the device enumeration to a more appropriate location,
outside the driver.  This will usually be cleanup, since such drivers
tend to already have "normal" modes, such as ones using device nodes that
were created by PNP or by platform device setup.

None the less, there are some APIs to support such legacy drivers.  Avoid
using these calls except with such hotplug-deficient drivers::

	struct platform_device *platform_device_alloc(
			const char *name, int id);

You can use platform_device_alloc() to dynamically allocate a device, which
you will then initialize with resources and platform_device_register().
A better solution is usually::

	struct platform_device *platform_device_register_simple(
			const char *name, int id,
			struct resource *res, unsigned int nres);

You can use platform_device_register_simple() as a one-step call to allocate
and register a device.

Device Naming and Driver Binding
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The platform_device.dev.bus_id is the canonical name for the devices.
It's built from two components:

    * platform_device.name ... which is also used to for driver matching.

    * platform_device.id ... the device instance number, or else "-1"
      to indicate there's only one.

These are concatenated, so name/id "serial"/0 indicates bus_id "serial.0", and
"serial/3" indicates bus_id "serial.3"; both would use the platform_driver
named "serial".  While "my_rtc"/-1 would be bus_id "my_rtc" (no instance id)
and use the platform_driver called "my_rtc".

Driver binding is performed automatically by the driver core, invoking
driver probe() after finding a match between device and driver.  If the
probe() succeeds, the driver and device are bound as usual.  There are
three different ways to find such a match:

    - Whenever a device is registered, the drivers for that bus are
      checked for matches.  Platform devices should be registered very
      early during system boot.

    - When a driver is registered using platform_driver_register(), all
      unbound devices on that bus are checked for matches.  Drivers
      usually register later during booting, or by module loading.

    - Registering a driver using platform_driver_probe() works just like
      using platform_driver_register(), except that the driver won't
      be probed later if another device registers.  (Which is OK, since
      this interface is only for use with non-hotpluggable devices.)

Early Platform Devices and Drivers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The early platform interfaces provide platform data to platform device
drivers early on during the system boot. The code is built on top of the
early_param() command line parsing and can be executed very early on.

Example: "earlyprintk" class early serial console in 6 steps

1. Registering early platform device data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The architecture code registers platform device data using the function
early_platform_add_devices(). In the case of early serial console this
should be hardware configuration for the serial port. Devices registered
at this point will later on be matched against early platform drivers.

2. Parsing kernel command line
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The architecture code calls parse_early_param() to parse the kernel
command line. This will execute all matching early_param() callbacks.
User specified early platform devices will be registered at this point.
For the early serial console case the user can specify port on the
kernel command line as "earlyprintk=serial.0" where "earlyprintk" is
the class string, "serial" is the name of the platform driver and
0 is the platform device id. If the id is -1 then the dot and the
id can be omitted.

3. Installing early platform drivers belonging to a certain class
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The architecture code may optionally force registration of all early
platform drivers belonging to a certain class using the function
early_platform_driver_register_all(). User specified devices from
step 2 have priority over these. This step is omitted by the serial
driver example since the early serial driver code should be disabled
unless the user has specified port on the kernel command line.

4. Early platform driver registration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Compiled-in platform drivers making use of early_platform_init() are
automatically registered during step 2 or 3. The serial driver example
should use early_platform_init("earlyprintk", &platform_driver).

5. Probing of early platform drivers belonging to a certain class
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The architecture code calls early_platform_driver_probe() to match
registered early platform devices associated with a certain class with
registered early platform drivers. Matched devices will get probed().
This step can be executed at any point during the early boot. As soon
as possible may be good for the serial port case.

6. Inside the early platform driver probe()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The driver code needs to take special care during early boot, especially
when it comes to memory allocation and interrupt registration. The code
in the probe() function can use is_early_platform_device() to check if
it is called at early platform device or at the regular platform device
time. The early serial driver performs register_console() at this point.

For further information, see <linux/platform_device.h>.


code:
=======================================
Porting Drivers to the New Driver Model
=======================================

Patrick Mochel

7 January 2003

Overview

Please refer to `Documentation/driver-api/driver-model/*.rst` for definitions of
various driver types and concepts.

Most of the work of porting devices drivers to the new model happens
at the bus driver layer. This was intentional, to minimize the
negative effect on kernel drivers, and to allow a gradual transition
of bus drivers.

In a nutshell, the driver model consists of a set of objects that can
be embedded in larger, bus-specific objects. Fields in these generic
objects can replace fields in the bus-specific objects.

The generic objects must be registered with the driver model core. By
doing so, they will exported via the sysfs filesystem. sysfs can be
mounted by doing::

	# mount -t sysfs sysfs /sys

The Process

Step 0: Read include/linux/device.h for object and function definitions.

Step 1: Registering the bus driver.

- Define a struct bus_type for the bus driver::

    struct bus_type pci_bus_type = {
          .name           = "pci",
    };

- Register the bus type.

  This should be done in the initialization function for the bus type,
  which is usually the module_init(), or equivalent, function::

    static int __init pci_driver_init(void)
    {
            return bus_register(&pci_bus_type);
    }

    subsys_initcall(pci_driver_init);

  The bus type may be unregistered (if the bus driver may be compiled
  as a module) by doing::

     bus_unregister(&pci_bus_type);

- Export the bus type for others to use.

  Other code may wish to reference the bus type, so declare it in a
  shared header file and export the symbol.

From include/linux/pci.h::

  extern struct bus_type pci_bus_type;

From file the above code appears in::

  EXPORT_SYMBOL(pci_bus_type);

- This will cause the bus to show up in /sys/bus/pci/ with two
  subdirectories: 'devices' and 'drivers'::

    # tree -d /sys/bus/pci/
    /sys/bus/pci/
    |-- devices
    `-- drivers

Step 2: Registering Devices.

struct device represents a single device. It mainly contains metadata
describing the relationship the device has to other entities.

- Embed a struct device in the bus-specific device type::

    struct pci_dev {
           ...
           struct  device  dev;            /* Generic device interface */
           ...
    };

  It is recommended that the generic device not be the first item in
  the struct to discourage programmers from doing mindless casts
  between the object types. Instead macros, or inline functions,
  should be created to convert from the generic object type::

    #define to_pci_dev(n) container_of(n, struct pci_dev, dev)

    or

    static inline struct pci_dev * to_pci_dev(struct kobject * kobj)
    {
	return container_of(n, struct pci_dev, dev);
    }

  This allows the compiler to verify type-safety of the operations
  that are performed (which is Good).

- Initialize the device on registration.

  When devices are discovered or registered with the bus type, the
  bus driver should initialize the generic device. The most important
  things to initialize are the bus_id, parent, and bus fields.

  The bus_id is an ASCII string that contains the device's address on
  the bus. The format of this string is bus-specific. This is
  necessary for representing devices in sysfs.

  parent is the physical parent of the device. It is important that
  the bus driver sets this field correctly.

  The driver model maintains an ordered list of devices that it uses
  for power management. This list must be in order to guarantee that
  devices are shutdown before their physical parents, and vice versa.
  The order of this list is determined by the parent of registered
  devices.

  Also, the location of the device's sysfs directory depends on a
  device's parent. sysfs exports a directory structure that mirrors
  the device hierarchy. Accurately setting the parent guarantees that
  sysfs will accurately represent the hierarchy.

  The device's bus field is a pointer to the bus type the device
  belongs to. This should be set to the bus_type that was declared
  and initialized before.

  Optionally, the bus driver may set the device's name and release
  fields.

  The name field is an ASCII string describing the device, like

     "ATI Technologies Inc Radeon QD"

  The release field is a callback that the driver model core calls
  when the device has been removed, and all references to it have
  been released. More on this in a moment.

- Register the device.

  Once the generic device has been initialized, it can be registered
  with the driver model core by doing::

       device_register(&dev->dev);

  It can later be unregistered by doing::

       device_unregister(&dev->dev);

  This should happen on buses that support hotpluggable devices.
  If a bus driver unregisters a device, it should not immediately free
  it. It should instead wait for the driver model core to call the
  device's release method, then free the bus-specific object.
  (There may be other code that is currently referencing the device
  structure, and it would be rude to free the device while that is
  happening).

  When the device is registered, a directory in sysfs is created.
  The PCI tree in sysfs looks like::

    /sys/devices/pci0/
    |-- 00:00.0
    |-- 00:01.0
    |   `-- 01:00.0
    |-- 00:02.0
    |   `-- 02:1f.0
    |       `-- 03:00.0
    |-- 00:1e.0
    |   `-- 04:04.0
    |-- 00:1f.0
    |-- 00:1f.1
    |   |-- ide0
    |   |   |-- 0.0
    |   |   `-- 0.1
    |   `-- ide1
    |       `-- 1.0
    |-- 00:1f.2
    |-- 00:1f.3
    `-- 00:1f.5

  Also, symlinks are created in the bus's 'devices' directory
  that point to the device's directory in the physical hierarchy::

    /sys/bus/pci/devices/
    |-- 00:00.0 -> ../../../devices/pci0/00:00.0
    |-- 00:01.0 -> ../../../devices/pci0/00:01.0
    |-- 00:02.0 -> ../../../devices/pci0/00:02.0
    |-- 00:1e.0 -> ../../../devices/pci0/00:1e.0
    |-- 00:1f.0 -> ../../../devices/pci0/00:1f.0
    |-- 00:1f.1 -> ../../../devices/pci0/00:1f.1
    |-- 00:1f.2 -> ../../../devices/pci0/00:1f.2
    |-- 00:1f.3 -> ../../../devices/pci0/00:1f.3
    |-- 00:1f.5 -> ../../../devices/pci0/00:1f.5
    |-- 01:00.0 -> ../../../devices/pci0/00:01.0/01:00.0
    |-- 02:1f.0 -> ../../../devices/pci0/00:02.0/02:1f.0
    |-- 03:00.0 -> ../../../devices/pci0/00:02.0/02:1f.0/03:00.0
    `-- 04:04.0 -> ../../../devices/pci0/00:1e.0/04:04.0

Step 3: Registering Drivers.

struct device_driver is a simple driver structure that contains a set
of operations that the driver model core may call.

- Embed a struct device_driver in the bus-specific driver.

  Just like with devices, do something like::

    struct pci_driver {
           ...
           struct device_driver    driver;
    };

- Initialize the generic driver structure.

  When the driver registers with the bus (e.g. doing pci_register_driver()),
  initialize the necessary fields of the driver: the name and bus
  fields.

- Register the driver.

  After the generic driver has been initialized, call::

	driver_register(&drv->driver);

  to register the driver with the core.

  When the driver is unregistered from the bus, unregister it from the
  core by doing::

        driver_unregister(&drv->driver);

  Note that this will block until all references to the driver have
  gone away. Normally, there will not be any.

- Sysfs representation.

  Drivers are exported via sysfs in their bus's 'driver's directory.
  For example::

    /sys/bus/pci/drivers/
    |-- 3c59x
    |-- Ensoniq AudioPCI
    |-- agpgart-amdk7
    |-- e100
    `-- serial

Step 4: Define Generic Methods for Drivers.

struct device_driver defines a set of operations that the driver model
core calls. Most of these operations are probably similar to
operations the bus already defines for drivers, but taking different
parameters.

It would be difficult and tedious to force every driver on a bus to
simultaneously convert their drivers to generic format. Instead, the
bus driver should define single instances of the generic methods that
forward call to the bus-specific drivers. For instance::

  static int pci_device_remove(struct device * dev)
  {
          struct pci_dev * pci_dev = to_pci_dev(dev);
          struct pci_driver * drv = pci_dev->driver;

          if (drv) {
                  if (drv->remove)
                          drv->remove(pci_dev);
                  pci_dev->driver = NULL;
          }
          return 0;
  }

The generic driver should be initialized with these methods before it
is registered::

        /* initialize common driver fields */
        drv->driver.name = drv->name;
        drv->driver.bus = &pci_bus_type;
        drv->driver.probe = pci_device_probe;
        drv->driver.resume = pci_device_resume;
        drv->driver.suspend = pci_device_suspend;
        drv->driver.remove = pci_device_remove;

        /* register with core */
        driver_register(&drv->driver);

Ideally, the bus should only initialize the fields if they are not
already set. This allows the drivers to implement their own generic
methods.

Step 5: Support generic driver binding.

The model assumes that a device or driver can be dynamically
registered with the bus at any time. When registration happens,
devices must be bound to a driver, or drivers must be bound to all
devices that it supports.

A driver typically contains a list of device IDs that it supports. The
bus driver compares these IDs to the IDs of devices registered with it.
The format of the device IDs, and the semantics for comparing them are
bus-specific, so the generic model does attempt to generalize them.

Instead, a bus may supply a method in struct bus_type that does the
comparison::

  int (*match)(struct device * dev, struct device_driver * drv);

match should return positive value if the driver supports the device,
and zero otherwise. It may also return error code (for example
-EPROBE_DEFER) if determining that given driver supports the device is
not possible.

When a device is registered, the bus's list of drivers is iterated
over. bus->match() is called for each one until a match is found.

When a driver is registered, the bus's list of devices is iterated
over. bus->match() is called for each device that is not already
claimed by a driver.

When a device is successfully bound to a driver, device->driver is
set, the device is added to a per-driver list of devices, and a
symlink is created in the driver's sysfs directory that points to the
device's physical directory::

  /sys/bus/pci/drivers/
  |-- 3c59x
  |   `-- 00:0b.0 -> ../../../../devices/pci0/00:0b.0
  |-- Ensoniq AudioPCI
  |-- agpgart-amdk7
  |   `-- 00:00.0 -> ../../../../devices/pci0/00:00.0
  |-- e100
  |   `-- 00:0c.0 -> ../../../../devices/pci0/00:0c.0
  `-- serial

This driver binding should replace the existing driver binding
mechanism the bus currently uses.

Step 6: Supply a hotplug callback.

Whenever a device is registered with the driver model core, the
userspace program /sbin/hotplug is called to notify userspace.
Users can define actions to perform when a device is inserted or
removed.

The driver model core passes several arguments to userspace via
environment variables, including

- ACTION: set to 'add' or 'remove'
- DEVPATH: set to the device's physical path in sysfs.

A bus driver may also supply additional parameters for userspace to
consume. To do this, a bus must implement the 'hotplug' method in
struct bus_type::

     int (*hotplug) (struct device *dev, char **envp,
                     int num_envp, char *buffer, int buffer_size);

This is called immediately before /sbin/hotplug is executed.

Step 7: Cleaning up the bus driver.

The generic bus, device, and driver structures provide several fields
that can replace those defined privately to the bus driver.

- Device list.

struct bus_type contains a list of all devices registered with the bus
type. This includes all devices on all instances of that bus type.
An internal list that the bus uses may be removed, in favor of using
this one.

The core provides an iterator to access these devices::

  int bus_for_each_dev(struct bus_type * bus, struct device * start,
                       void * data, int (*fn)(struct device *, void *));

- Driver list.

struct bus_type also contains a list of all drivers registered with
it. An internal list of drivers that the bus driver maintains may
be removed in favor of using the generic one.

The drivers may be iterated over, like devices::

  int bus_for_each_drv(struct bus_type * bus, struct device_driver * start,
                       void * data, int (*fn)(struct device_driver *, void *));

Please see drivers/base/bus.c for more information.

- rwsem

struct bus_type contains an rwsem that protects all core accesses to
the device and driver lists. This can be used by the bus driver
internally, and should be used when accessing the device or driver
lists the bus maintains.

- Device and driver fields.

Some of the fields in struct device and struct device_driver duplicate
fields in the bus-specific representations of these objects. Feel free
to remove the bus-specific ones and favor the generic ones. Note
though, that this will likely mean fixing up all the drivers that
reference the bus-specific fields (though those should all be 1-line
changes).


code:
=======================
initramfs buffer format
=======================

Al Viro, H. Peter Anvin

Last revision: 2002-01-13

Starting with kernel 2.5.x, the old "initial ramdisk" protocol is
getting {replaced/complemented} with the new "initial ramfs"
(initramfs) protocol.  The initramfs contents is passed using the same
memory buffer protocol used by the initrd protocol, but the contents
is different.  The initramfs buffer contains an archive which is
expanded into a ramfs filesystem; this document details the format of
the initramfs buffer format.

The initramfs buffer format is based around the "newc" or "crc" CPIO
formats, and can be created with the cpio(1) utility.  The cpio
archive can be compressed using gzip(1).  One valid version of an
initramfs buffer is thus a single .cpio.gz file.

The full format of the initramfs buffer is defined by the following
grammar, where::

	*	is used to indicate "0 or more occurrences of"
	(|)	indicates alternatives
	+	indicates concatenation
	GZIP()	indicates the gzip(1) of the operand
	ALGN(n)	means padding with null bytes to an n-byte boundary

	initramfs  := ("\0" | cpio_archive | cpio_gzip_archive)*

	cpio_gzip_archive := GZIP(cpio_archive)

	cpio_archive := cpio_file* + (<nothing> | cpio_trailer)

	cpio_file := ALGN(4) + cpio_header + filename + "\0" + ALGN(4) + data

	cpio_trailer := ALGN(4) + cpio_header + "TRAILER!!!\0" + ALGN(4)

In human terms, the initramfs buffer contains a collection of
compressed and/or uncompressed cpio archives (in the "newc" or "crc"
formats); arbitrary amounts zero bytes (for padding) can be added
between members.

The cpio "TRAILER!!!" entry (cpio end-of-archive) is optional, but is
not ignored; see "handling of hard links" below.

The structure of the cpio_header is as follows (all fields contain
hexadecimal ASCII numbers fully padded with '0' on the left to the
full width of the field, for example, the integer 4780 is represented
by the ASCII string "000012ac"):

============= ================== ==============================================
Field name    Field size	 Meaning
============= ================== ==============================================
c_magic	      6 bytes		 The string "070701" or "070702"
c_ino	      8 bytes		 File inode number
c_mode	      8 bytes		 File mode and permissions
c_uid	      8 bytes		 File uid
c_gid	      8 bytes		 File gid
c_nlink	      8 bytes		 Number of links
c_mtime	      8 bytes		 Modification time
c_filesize    8 bytes		 Size of data field
c_maj	      8 bytes		 Major part of file device number
c_min	      8 bytes		 Minor part of file device number
c_rmaj	      8 bytes		 Major part of device node reference
c_rmin	      8 bytes		 Minor part of device node reference
c_namesize    8 bytes		 Length of filename, including final \0
c_chksum      8 bytes		 Checksum of data field if c_magic is 070702;
				 otherwise zero
============= ================== ==============================================

The c_mode field matches the contents of st_mode returned by stat(2)
on Linux, and encodes the file type and file permissions.

The c_filesize should be zero for any file which is not a regular file
or symlink.

The c_chksum field contains a simple 32-bit unsigned sum of all the
bytes in the data field.  cpio(1) refers to this as "crc", which is
clearly incorrect (a cyclic redundancy check is a different and
significantly stronger integrity check), however, this is the
algorithm used.

If the filename is "TRAILER!!!" this is actually an end-of-archive
marker; the c_filesize for an end-of-archive marker must be zero.

Handling of hard links
======================

When a nondirectory with c_nlink > 1 is seen, the (c_maj,c_min,c_ino)
tuple is looked up in a tuple buffer.  If not found, it is entered in
the tuple buffer and the entry is created as usual; if found, a hard
link rather than a second copy of the file is created.  It is not
necessary (but permitted) to include a second copy of the file
contents; if the file contents is not included, the c_filesize field
should be set to zero to indicate no data section follows.  If data is
present, the previous instance of the file is overwritten; this allows
the data-carrying instance of a file to occur anywhere in the sequence
(GNU cpio is reported to attach the data to the last instance of a
file only.)

c_filesize must not be zero for a symlink.

When a "TRAILER!!!" end-of-archive marker is seen, the tuple buffer is
reset.  This permits archives which are generated independently to be
concatenated.

To combine file data from different sources (without having to
regenerate the (c_maj,c_min,c_ino) fields), therefore, either one of
the following techniques can be used:

a) Separate the different file data sources with a "TRAILER!!!"
   end-of-archive marker, or

b) Make sure c_nlink == 1 for all nondirectory entries.


code:
=======================
Early userspace support
=======================

Last update: 2004-12-20 tlh

"Early userspace" is a set of libraries and programs that provide
various pieces of functionality that are important enough to be
available while a Linux kernel is coming up, but that don't need to be
run inside the kernel itself.

It consists of several major infrastructure components:

- gen_init_cpio, a program that builds a cpio-format archive
  containing a root filesystem image.  This archive is compressed, and
  the compressed image is linked into the kernel image.
- initramfs, a chunk of code that unpacks the compressed cpio image
  midway through the kernel boot process.
- klibc, a userspace C library, currently packaged separately, that is
  optimized for correctness and small size.

The cpio file format used by initramfs is the "newc" (aka "cpio -H newc")
format, and is documented in the file "buffer-format.txt".  There are
two ways to add an early userspace image: specify an existing cpio
archive to be used as the image or have the kernel build process build
the image from specifications.

CPIO ARCHIVE method
-------------------

You can create a cpio archive that contains the early userspace image.
Your cpio archive should be specified in CONFIG_INITRAMFS_SOURCE and it
will be used directly.  Only a single cpio file may be specified in
CONFIG_INITRAMFS_SOURCE and directory and file names are not allowed in
combination with a cpio archive.

IMAGE BUILDING method
---------------------

The kernel build process can also build an early userspace image from
source parts rather than supplying a cpio archive.  This method provides
a way to create images with root-owned files even though the image was
built by an unprivileged user.

The image is specified as one or more sources in
CONFIG_INITRAMFS_SOURCE.  Sources can be either directories or files -
cpio archives are *not* allowed when building from sources.

A source directory will have it and all of its contents packaged.  The
specified directory name will be mapped to '/'.  When packaging a
directory, limited user and group ID translation can be performed.
INITRAMFS_ROOT_UID can be set to a user ID that needs to be mapped to
user root (0).  INITRAMFS_ROOT_GID can be set to a group ID that needs
to be mapped to group root (0).

A source file must be directives in the format required by the
usr/gen_init_cpio utility (run 'usr/gen_init_cpio -h' to get the
file format).  The directives in the file will be passed directly to
usr/gen_init_cpio.

When a combination of directories and files are specified then the
initramfs image will be an aggregate of all of them.  In this way a user
can create a 'root-image' directory and install all files into it.
Because device-special files cannot be created by a unprivileged user,
special files can be listed in a 'root-files' file.  Both 'root-image'
and 'root-files' can be listed in CONFIG_INITRAMFS_SOURCE and a complete
early userspace image can be built by an unprivileged user.

As a technical note, when directories and files are specified, the
entire CONFIG_INITRAMFS_SOURCE is passed to
usr/gen_initramfs.sh.  This means that CONFIG_INITRAMFS_SOURCE
can really be interpreted as any legal argument to
gen_initramfs.sh.  If a directory is specified as an argument then
the contents are scanned, uid/gid translation is performed, and
usr/gen_init_cpio file directives are output.  If a directory is
specified as an argument to usr/gen_initramfs.sh then the
contents of the file are simply copied to the output.  All of the output
directives from directory scanning and file contents copying are
processed by usr/gen_init_cpio.

See also 'usr/gen_initramfs.sh -h'.

Where's this all leading?
=========================

The klibc distribution contains some of the necessary software to make
early userspace useful.  The klibc distribution is currently
maintained separately from the kernel.

You can obtain somewhat infrequent snapshots of klibc from
https://www.kernel.org/pub/linux/libs/klibc/

For active users, you are better off using the klibc git
repository, at https://git.kernel.org/?p=libs/klibc/klibc.git

The standalone klibc distribution currently provides three components,
in addition to the klibc library:

- ipconfig, a program that configures network interfaces.  It can
  configure them statically, or use DHCP to obtain information
  dynamically (aka "IP autoconfiguration").
- nfsmount, a program that can mount an NFS filesystem.
- kinit, the "glue" that uses ipconfig and nfsmount to replace the old
  support for IP autoconfig, mount a filesystem over NFS, and continue
  system boot using that filesystem as root.

kinit is built as a single statically linked binary to save space.

Eventually, several more chunks of kernel functionality will hopefully
move to early userspace:

- Almost all of init/do_mounts* (the beginning of this is already in
  place)
- ACPI table parsing
- Insert unwieldy subsystem that doesn't really need to be in kernel
  space here

If kinit doesn't meet your current needs and you've got bytes to burn,
the klibc distribution includes a small Bourne-compatible shell (ash)
and a number of other utilities, so you can replace kinit and build
custom initramfs images that meet your needs exactly.

For questions and help, you can sign up for the early userspace
mailing list at https://www.zytor.com/mailman/listinfo/klibc

How does it work?
=================

The kernel has currently 3 ways to mount the root filesystem:

a) all required device and filesystem drivers compiled into the kernel, no
   initrd.  init/main.c:init() will call prepare_namespace() to mount the
   final root filesystem, based on the root= option and optional init= to run
   some other init binary than listed at the end of init/main.c:init().

b) some device and filesystem drivers built as modules and stored in an
   initrd.  The initrd must contain a binary '/linuxrc' which is supposed to
   load these driver modules.  It is also possible to mount the final root
   filesystem via linuxrc and use the pivot_root syscall.  The initrd is
   mounted and executed via prepare_namespace().

c) using initramfs.  The call to prepare_namespace() must be skipped.
   This means that a binary must do all the work.  Said binary can be stored
   into initramfs either via modifying usr/gen_init_cpio.c or via the new
   initrd format, an cpio archive.  It must be called "/init".  This binary
   is responsible to do all the things prepare_namespace() would do.

   To maintain backwards compatibility, the /init binary will only run if it
   comes via an initramfs cpio archive.  If this is not the case,
   init/main.c:init() will run prepare_namespace() to mount the final root
   and exec one of the predefined init binaries.

Bryan O'Sullivan <bos@serpentine.com>


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

===============
Early Userspace
===============

.. toctree::
    :maxdepth: 1

    early_userspace_support
    buffer-format

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


code:
Error Detection And Correction (EDAC) Devices
=============================================

Main Concepts used at the EDAC subsystem
----------------------------------------

There are several things to be aware of that aren't at all obvious, like
*sockets, *socket sets*, *banks*, *rows*, *chip-select rows*, *channels*,
etc...

These are some of the many terms that are thrown about that don't always
mean what people think they mean (Inconceivable!).  In the interest of
creating a common ground for discussion, terms and their definitions
will be established.

* Memory devices

The individual DRAM chips on a memory stick.  These devices commonly
output 4 and 8 bits each (x4, x8). Grouping several of these in parallel
provides the number of bits that the memory controller expects:
typically 72 bits, in order to provide 64 bits + 8 bits of ECC data.

* Memory Stick

A printed circuit board that aggregates multiple memory devices in
parallel.  In general, this is the Field Replaceable Unit (FRU) which
gets replaced, in the case of excessive errors. Most often it is also
called DIMM (Dual Inline Memory Module).

* Memory Socket

A physical connector on the motherboard that accepts a single memory
stick. Also called as "slot" on several datasheets.

* Channel

A memory controller channel, responsible to communicate with a group of
DIMMs. Each channel has its own independent control (command) and data
bus, and can be used independently or grouped with other channels.

* Branch

It is typically the highest hierarchy on a Fully-Buffered DIMM memory
controller. Typically, it contains two channels. Two channels at the
same branch can be used in single mode or in lockstep mode. When
lockstep is enabled, the cacheline is doubled, but it generally brings
some performance penalty. Also, it is generally not possible to point to
just one memory stick when an error occurs, as the error correction code
is calculated using two DIMMs instead of one. Due to that, it is capable
of correcting more errors than on single mode.

* Single-channel

The data accessed by the memory controller is contained into one dimm
only. E. g. if the data is 64 bits-wide, the data flows to the CPU using
one 64 bits parallel access. Typically used with SDR, DDR, DDR2 and DDR3
memories. FB-DIMM and RAMBUS use a different concept for channel, so
this concept doesn't apply there.

* Double-channel

The data size accessed by the memory controller is interlaced into two
dimms, accessed at the same time. E. g. if the DIMM is 64 bits-wide (72
bits with ECC), the data flows to the CPU using a 128 bits parallel
access.

* Chip-select row

This is the name of the DRAM signal used to select the DRAM ranks to be
accessed. Common chip-select rows for single channel are 64 bits, for
dual channel 128 bits. It may not be visible by the memory controller,
as some DIMM types have a memory buffer that can hide direct access to
it from the Memory Controller.

* Single-Ranked stick

A Single-ranked stick has 1 chip-select row of memory. Motherboards
commonly drive two chip-select pins to a memory stick. A single-ranked
stick, will occupy only one of those rows. The other will be unused.

.. _doubleranked:

* Double-Ranked stick

A double-ranked stick has two chip-select rows which access different
sets of memory devices.  The two rows cannot be accessed concurrently.

* Double-sided stick

**DEPRECATED TERM**, see :ref:`Double-Ranked stick <doubleranked>`.

A double-sided stick has two chip-select rows which access different sets
of memory devices. The two rows cannot be accessed concurrently.
"Double-sided" is irrespective of the memory devices being mounted on
both sides of the memory stick.

* Socket set

All of the memory sticks that are required for a single memory access or
all of the memory sticks spanned by a chip-select row.  A single socket
set has two chip-select rows and if double-sided sticks are used these
will occupy those chip-select rows.

* Bank

This term is avoided because it is unclear when needing to distinguish
between chip-select rows and socket sets.

Memory Controllers
------------------

Most of the EDAC core is focused on doing Memory Controller error detection.
The :c:func:`edac_mc_alloc`. It uses internally the struct ``mem_ctl_info``
to describe the memory controllers, with is an opaque struct for the EDAC
drivers. Only the EDAC core is allowed to touch it.

.. kernel-doc:: include/linux/edac.h

.. kernel-doc:: drivers/edac/edac_mc.h

PCI Controllers
---------------

The EDAC subsystem provides a mechanism to handle PCI controllers by calling
the :c:func:`edac_pci_alloc_ctl_info`. It will use the struct
:c:type:`edac_pci_ctl_info` to describe the PCI controllers.

.. kernel-doc:: drivers/edac/edac_pci.h

EDAC Blocks
-----------

The EDAC subsystem also provides a generic mechanism to report errors on
other parts of the hardware via :c:func:`edac_device_alloc_ctl_info` function.

The structures :c:type:`edac_dev_sysfs_block_attribute`,
:c:type:`edac_device_block`, :c:type:`edac_device_instance` and
:c:type:`edac_device_ctl_info` provide a generic or abstract 'edac_device'
representation at sysfs.

This set of structures and the code that implements the APIs for the same, provide for registering EDAC type devices which are NOT standard memory or
PCI, like:

- CPU caches (L1 and L2)
- DMA engines
- Core CPU switches
- Fabric switch units
- PCIe interface controllers
- other EDAC/ECC type devices that can be monitored for
  errors, etc.

It allows for a 2 level set of hierarchy.

For example, a cache could be composed of L1, L2 and L3 levels of cache.
Each CPU core would have its own L1 cache, while sharing L2 and maybe L3
caches. On such case, those can be represented via the following sysfs
nodes::

	/sys/devices/system/edac/..

	pci/		<existing pci directory (if available)>
	mc/		<existing memory device directory>
	cpu/cpu0/..	<L1 and L2 block directory>
		/L1-cache/ce_count
			 /ue_count
		/L2-cache/ce_count
			 /ue_count
	cpu/cpu1/..	<L1 and L2 block directory>
		/L1-cache/ce_count
			 /ue_count
		/L2-cache/ce_count
			 /ue_count
	...

	the L1 and L2 directories would be "edac_device_block's"

.. kernel-doc:: drivers/edac/edac_device.h


code:
================
EISA bus support
================

:Author: Marc Zyngier <maz@wild-wind.fr.eu.org>

This document groups random notes about porting EISA drivers to the
new EISA/sysfs API.

Starting from version 2.5.59, the EISA bus is almost given the same
status as other much more mainstream busses such as PCI or USB. This
has been possible through sysfs, which defines a nice enough set of
abstractions to manage busses, devices and drivers.

Although the new API is quite simple to use, converting existing
drivers to the new infrastructure is not an easy task (mostly because
detection code is generally also used to probe ISA cards). Moreover,
most EISA drivers are among the oldest Linux drivers so, as you can
imagine, some dust has settled here over the years.

The EISA infrastructure is made up of three parts:

    - The bus code implements most of the generic code. It is shared
      among all the architectures that the EISA code runs on. It
      implements bus probing (detecting EISA cards available on the bus),
      allocates I/O resources, allows fancy naming through sysfs, and
      offers interfaces for driver to register.

    - The bus root driver implements the glue between the bus hardware
      and the generic bus code. It is responsible for discovering the
      device implementing the bus, and setting it up to be latter probed
      by the bus code. This can go from something as simple as reserving
      an I/O region on x86, to the rather more complex, like the hppa
      EISA code. This is the part to implement in order to have EISA
      running on an "new" platform.

    - The driver offers the bus a list of devices that it manages, and
      implements the necessary callbacks to probe and release devices
      whenever told to.

Every function/structure below lives in <linux/eisa.h>, which depends
heavily on <linux/device.h>.

Bus root driver
===============

::

	int eisa_root_register (struct eisa_root_device *root);

The eisa_root_register function is used to declare a device as the
root of an EISA bus. The eisa_root_device structure holds a reference
to this device, as well as some parameters for probing purposes::

	struct eisa_root_device {
		struct device   *dev;	 /* Pointer to bridge device */
		struct resource *res;
		unsigned long    bus_base_addr;
		int		 slots;  /* Max slot number */
		int		 force_probe; /* Probe even when no slot 0 */
		u64		 dma_mask; /* from bridge device */
		int              bus_nr; /* Set by eisa_root_register */
		struct resource  eisa_root_res;	/* ditto */
	};

============= ======================================================
node          used for eisa_root_register internal purpose
dev           pointer to the root device
res           root device I/O resource
bus_base_addr slot 0 address on this bus
slots	      max slot number to probe
force_probe   Probe even when slot 0 is empty (no EISA mainboard)
dma_mask      Default DMA mask. Usually the bridge device dma_mask.
bus_nr	      unique bus id, set by eisa_root_register
============= ======================================================

Driver
======

::

	int eisa_driver_register (struct eisa_driver *edrv);
	void eisa_driver_unregister (struct eisa_driver *edrv);

Clear enough ?

::

	struct eisa_device_id {
		char sig[EISA_SIG_LEN];
		unsigned long driver_data;
	};

	struct eisa_driver {
		const struct eisa_device_id *id_table;
		struct device_driver         driver;
	};

=============== ====================================================
id_table	an array of NULL terminated EISA id strings,
		followed by an empty string. Each string can
		optionally be paired with a driver-dependent value
		(driver_data).

driver		a generic driver, such as described in
		Documentation/driver-api/driver-model/driver.rst. Only .name,
		.probe and .remove members are mandatory.
=============== ====================================================

An example is the 3c59x driver::

	static struct eisa_device_id vortex_eisa_ids[] = {
		{ "TCM5920", EISA_3C592_OFFSET },
		{ "TCM5970", EISA_3C597_OFFSET },
		{ "" }
	};

	static struct eisa_driver vortex_eisa_driver = {
		.id_table = vortex_eisa_ids,
		.driver   = {
			.name    = "3c59x",
			.probe   = vortex_eisa_probe,
			.remove  = vortex_eisa_remove
		}
	};

Device
======

The sysfs framework calls .probe and .remove functions upon device
discovery and removal (note that the .remove function is only called
when driver is built as a module).

Both functions are passed a pointer to a 'struct device', which is
encapsulated in a 'struct eisa_device' described as follows::

	struct eisa_device {
		struct eisa_device_id id;
		int                   slot;
		int                   state;
		unsigned long         base_addr;
		struct resource       res[EISA_MAX_RESOURCES];
		u64                   dma_mask;
		struct device         dev; /* generic device */
	};

======== ============================================================
id	 EISA id, as read from device. id.driver_data is set from the
	 matching driver EISA id.
slot	 slot number which the device was detected on
state    set of flags indicating the state of the device. Current
	 flags are EISA_CONFIG_ENABLED and EISA_CONFIG_FORCED.
res	 set of four 256 bytes I/O regions allocated to this device
dma_mask DMA mask set from the parent device.
dev	 generic device (see Documentation/driver-api/driver-model/device.rst)
======== ============================================================

You can get the 'struct eisa_device' from 'struct device' using the
'to_eisa_device' macro.

Misc stuff
==========

::

	void eisa_set_drvdata (struct eisa_device *edev, void *data);

Stores data into the device's driver_data area.

::

	void *eisa_get_drvdata (struct eisa_device *edev):

Gets the pointer previously stored into the device's driver_data area.

::

	int eisa_get_region_index (void *addr);

Returns the region number (0 <= x < EISA_MAX_RESOURCES) of a given
address.

Kernel parameters
=================

eisa_bus.enable_dev
	A comma-separated list of slots to be enabled, even if the firmware
	set the card as disabled. The driver must be able to properly
	initialize the device in such conditions.

eisa_bus.disable_dev
	A comma-separated list of slots to be disabled, even if the firmware
	set the card as enabled. The driver won't be called to handle this
	device.

virtual_root.force_probe
	Force the probing code to probe EISA slots even when it cannot find an
	EISA compliant mainboard (nothing appears on slot 0). Defaults to 0
	(don't force), and set to 1 (force probing) when either
	CONFIG_ALPHA_JENSEN or CONFIG_EISA_VLB_PRIMING are set.

Random notes
============

Converting an EISA driver to the new API mostly involves *deleting*
code (since probing is now in the core EISA code). Unfortunately, most
drivers share their probing routine between ISA, and EISA. Special
care must be taken when ripping out the EISA code, so other busses
won't suffer from these surgical strikes...

You *must not* expect any EISA device to be detected when returning
from eisa_driver_register, since the chances are that the bus has not
yet been probed. In fact, that's what happens most of the time (the
bus root driver usually kicks in rather late in the boot process).
Unfortunately, most drivers are doing the probing by themselves, and
expect to have explored the whole machine when they exit their probe
routine.

For example, switching your favorite EISA SCSI card to the "hotplug"
model is "the right thing"(tm).

Thanks
======

I'd like to thank the following people for their help:

- Xavier Benigni for lending me a wonderful Alpha Jensen,
- James Bottomley, Jeff Garzik for getting this stuff into the kernel,
- Andries Brouwer for contributing numerous EISA ids,
- Catrin Jones for coping with far too many machines at home.


code:
===========================================
Firewire (IEEE 1394) driver Interface Guide
===========================================

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

The Linux FireWire subsystem adds some interfaces into the Linux system to
 use/maintain+any resource on IEEE 1394 bus.

The main purpose of these interfaces is to access address space on each node
on IEEE 1394 bus by ISO/IEC 13213 (IEEE 1212) procedure, and to control
isochronous resources on the bus by IEEE 1394 procedure.

Two types of interfaces are added, according to consumers of the interface. A
set of userspace interfaces is available via `firewire character devices`. A set
of kernel interfaces is available via exported symbols in `firewire-core` module.

Firewire char device data structures
====================================

.. include:: ../ABI/stable/firewire-cdev
    :literal:

.. kernel-doc:: include/uapi/linux/firewire-cdev.h
    :internal:

Firewire device probing and sysfs interfaces
============================================

.. include:: ../ABI/stable/sysfs-bus-firewire
    :literal:

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

Firewire core transaction interfaces
====================================

.. kernel-doc:: drivers/firewire/core-transaction.c
    :export:

Firewire Isochronous I/O interfaces
===================================

.. kernel-doc:: drivers/firewire/core-iso.c
   :export:


code:
=================
Built-in firmware
=================

Firmware can be built-in to the kernel, this means building the firmware
into vmlinux directly, to enable avoiding having to look for firmware from
the filesystem. Instead, firmware can be looked for inside the kernel
directly. You can enable built-in firmware using the kernel configuration
options:

  * CONFIG_EXTRA_FIRMWARE
  * CONFIG_EXTRA_FIRMWARE_DIR

There are a few reasons why you might want to consider building your firmware
into the kernel with CONFIG_EXTRA_FIRMWARE:

* Speed
* Firmware is needed for accessing the boot device, and the user doesn't
  want to stuff the firmware into the boot initramfs.

Even if you have these needs there are a few reasons why you may not be
able to make use of built-in firmware:

* Legalese - firmware is non-GPL compatible
* Some firmware may be optional
* Firmware upgrades are possible, therefore a new firmware would implicate
  a complete kernel rebuild.
* Some firmware files may be really large in size. The remote-proc subsystem
  is an example subsystem which deals with these sorts of firmware
* The firmware may need to be scraped out from some device specific location
  dynamically, an example is calibration data for some WiFi chipsets. This
  calibration data can be unique per sold device.


code:
==========================
Firmware API core features
==========================

The firmware API has a rich set of core features available. This section
documents these features.

.. toctree::

   fw_search_path
   built-in-fw
   firmware_cache
   direct-fs-lookup
   fallback-mechanisms
   lookup-order
   firmware-usage-guidelines


code:
========================
Direct filesystem lookup
========================

Direct filesystem lookup is the most common form of firmware lookup performed
by the kernel. The kernel looks for the firmware directly on the root
filesystem in the paths documented in the section 'Firmware search paths'.
The filesystem lookup is implemented in fw_get_filesystem_firmware(), it
uses common core kernel file loader facility kernel_read_file_from_path().
The max path allowed is PATH_MAX -- currently this is 4096 characters.

It is recommended you keep /lib/firmware paths on your root filesystem,
avoid having a separate partition for them in order to avoid possible
races with lookups and avoid uses of the custom fallback mechanisms
documented below.

Firmware and initramfs
----------------------

Drivers which are built-in to the kernel should have the firmware integrated
also as part of the initramfs used to boot the kernel given that otherwise
a race is possible with loading the driver and the real rootfs not yet being
available. Stuffing the firmware into initramfs resolves this race issue,
however note that using initrd does not suffice to address the same race.

There are circumstances that justify not wanting to include firmware into
initramfs, such as dealing with large firmware files for the
remote-proc subsystem. For such cases using a userspace fallback mechanism
is currently the only viable solution as only userspace can know for sure
when the real rootfs is ready and mounted.


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

============
UEFI Support
============

UEFI stub library functions
===========================

.. kernel-doc:: drivers/firmware/efi/libstub/mem.c
   :internal:


code:
===================
Fallback mechanisms
===================

A fallback mechanism is supported to allow to overcome failures to do a direct
filesystem lookup on the root filesystem or when the firmware simply cannot be
installed for practical reasons on the root filesystem. The kernel
configuration options related to supporting the firmware fallback mechanism are:

  * CONFIG_FW_LOADER_USER_HELPER: enables building the firmware fallback
    mechanism. Most distributions enable this option today. If enabled but
    CONFIG_FW_LOADER_USER_HELPER_FALLBACK is disabled, only the custom fallback
    mechanism is available and for the request_firmware_nowait() call.
  * CONFIG_FW_LOADER_USER_HELPER_FALLBACK: force enables each request to
    enable the kobject uevent fallback mechanism on all firmware API calls
    except request_firmware_direct(). Most distributions disable this option
    today. The call request_firmware_nowait() allows for one alternative
    fallback mechanism: if this kconfig option is enabled and your second
    argument to request_firmware_nowait(), uevent, is set to false you are
    informing the kernel that you have a custom fallback mechanism and it will
    manually load the firmware. Read below for more details.

Note that this means when having this configuration:

CONFIG_FW_LOADER_USER_HELPER=y
CONFIG_FW_LOADER_USER_HELPER_FALLBACK=n

the kobject uevent fallback mechanism will never take effect even
for request_firmware_nowait() when uevent is set to true.

Justifying the firmware fallback mechanism
==========================================

Direct filesystem lookups may fail for a variety of reasons. Known reasons for
this are worth itemizing and documenting as it justifies the need for the
fallback mechanism:

* Race against access with the root filesystem upon bootup.

* Races upon resume from suspend. This is resolved by the firmware cache, but
  the firmware cache is only supported if you use uevents, and its not
  supported for request_firmware_into_buf().

* Firmware is not accessible through typical means:

        * It cannot be installed into the root filesystem
        * The firmware provides very unique device specific data tailored for
          the unit gathered with local information. An example is calibration
          data for WiFi chipsets for mobile devices. This calibration data is
          not common to all units, but tailored per unit.  Such information may
          be installed on a separate flash partition other than where the root
          filesystem is provided.

Types of fallback mechanisms
============================

There are really two fallback mechanisms available using one shared sysfs
interface as a loading facility:

* Kobject uevent fallback mechanism
* Custom fallback mechanism

First lets document the shared sysfs loading facility.

Firmware sysfs loading facility
===============================

In order to help device drivers upload firmware using a fallback mechanism
the firmware infrastructure creates a sysfs interface to enable userspace
to load and indicate when firmware is ready. The sysfs directory is created
via fw_create_instance(). This call creates a new struct device named after
the firmware requested, and establishes it in the device hierarchy by
associating the device used to make the request as the device's parent.
The sysfs directory's file attributes are defined and controlled through
the new device's class (firmware_class) and group (fw_dev_attr_groups).
This is actually where the original firmware_class module name came from,
given that originally the only firmware loading mechanism available was the
mechanism we now use as a fallback mechanism, which registers a struct class
firmware_class. Because the attributes exposed are part of the module name, the
module name firmware_class cannot be renamed in the future, to ensure backward
compatibility with old userspace.

To load firmware using the sysfs interface we expose a loading indicator,
and a file upload firmware into:

  * /sys/$DEVPATH/loading
  * /sys/$DEVPATH/data

To upload firmware you will echo 1 onto the loading file to indicate
you are loading firmware. You then write the firmware into the data file,
and you notify the kernel the firmware is ready by echo'ing 0 onto
the loading file.

The firmware device used to help load firmware using sysfs is only created if
direct firmware loading fails and if the fallback mechanism is enabled for your
firmware request, this is set up with :c:func:`firmware_fallback_sysfs`. It is
important to re-iterate that no device is created if a direct filesystem lookup
succeeded.

Using::

        echo 1 > /sys/$DEVPATH/loading

Will clean any previous partial load at once and make the firmware API
return an error. When loading firmware the firmware_class grows a buffer
for the firmware in PAGE_SIZE increments to hold the image as it comes in.

firmware_data_read() and firmware_loading_show() are just provided for the
test_firmware driver for testing, they are not called in normal use or
expected to be used regularly by userspace.

firmware_fallback_sysfs
-----------------------
.. kernel-doc:: drivers/base/firmware_loader/fallback.c
   :functions: firmware_fallback_sysfs

Firmware kobject uevent fallback mechanism
==========================================

Since a device is created for the sysfs interface to help load firmware as a
fallback mechanism userspace can be informed of the addition of the device by
relying on kobject uevents. The addition of the device into the device
hierarchy means the fallback mechanism for firmware loading has been initiated.
For details of implementation refer to fw_load_sysfs_fallback(), in particular
on the use of dev_set_uevent_suppress() and kobject_uevent().

The kernel's kobject uevent mechanism is implemented in lib/kobject_uevent.c,
it issues uevents to userspace. As a supplement to kobject uevents Linux
distributions could also enable CONFIG_UEVENT_HELPER_PATH, which makes use of
core kernel's usermode helper (UMH) functionality to call out to a userspace
helper for kobject uevents. In practice though no standard distribution has
ever used the CONFIG_UEVENT_HELPER_PATH. If CONFIG_UEVENT_HELPER_PATH is
enabled this binary would be called each time kobject_uevent_env() gets called
in the kernel for each kobject uevent triggered.

Different implementations have been supported in userspace to take advantage of
this fallback mechanism. When firmware loading was only possible using the
sysfs mechanism the userspace component "hotplug" provided the functionality of
monitoring for kobject events. Historically this was superseded be systemd's
udev, however firmware loading support was removed from udev as of systemd
commit be2ea723b1d0 ("udev: remove userspace firmware loading support")
as of v217 on August, 2014. This means most Linux distributions today are
not using or taking advantage of the firmware fallback mechanism provided
by kobject uevents. This is specially exacerbated due to the fact that most
distributions today disable CONFIG_FW_LOADER_USER_HELPER_FALLBACK.

Refer to do_firmware_uevent() for details of the kobject event variables
setup. The variables currently passed to userspace with a "kobject add"
event are:

* FIRMWARE=firmware name
* TIMEOUT=timeout value
* ASYNC=whether or not the API request was asynchronous

By default DEVPATH is set by the internal kernel kobject infrastructure.
Below is an example simple kobject uevent script::

        # Both $DEVPATH and $FIRMWARE are already provided in the environment.
        MY_FW_DIR=/lib/firmware/
        echo 1 > /sys/$DEVPATH/loading
        cat $MY_FW_DIR/$FIRMWARE > /sys/$DEVPATH/data
        echo 0 > /sys/$DEVPATH/loading

Firmware custom fallback mechanism
==================================

Users of the request_firmware_nowait() call have yet another option available
at their disposal: rely on the sysfs fallback mechanism but request that no
kobject uevents be issued to userspace. The original logic behind this
was that utilities other than udev might be required to lookup firmware
in non-traditional paths -- paths outside of the listing documented in the
section 'Direct filesystem lookup'. This option is not available to any of
the other API calls as uevents are always forced for them.

Since uevents are only meaningful if the fallback mechanism is enabled
in your kernel it would seem odd to enable uevents with kernels that do not
have the fallback mechanism enabled in their kernels. Unfortunately we also
rely on the uevent flag which can be disabled by request_firmware_nowait() to
also setup the firmware cache for firmware requests. As documented above,
the firmware cache is only set up if uevent is enabled for an API call.
Although this can disable the firmware cache for request_firmware_nowait()
calls, users of this API should not use it for the purposes of disabling
the cache as that was not the original purpose of the flag. Not setting
the uevent flag means you want to opt-in for the firmware fallback mechanism
but you want to suppress kobject uevents, as you have a custom solution which
will monitor for your device addition into the device hierarchy somehow and
load firmware for you through a custom path.

Firmware fallback timeout
=========================

The firmware fallback mechanism has a timeout. If firmware is not loaded
onto the sysfs interface by the timeout value an error is sent to the
driver. By default the timeout is set to 60 seconds if uevents are
desirable, otherwise MAX_JIFFY_OFFSET is used (max timeout possible).
The logic behind using MAX_JIFFY_OFFSET for non-uevents is that a custom
solution will have as much time as it needs to load firmware.

You can customize the firmware timeout by echo'ing your desired timeout into
the following file:

* /sys/class/firmware/timeout

If you echo 0 into it means MAX_JIFFY_OFFSET will be used. The data type
for the timeout is an int.

EFI embedded firmware fallback mechanism
========================================

On some devices the system's EFI code / ROM may contain an embedded copy
of firmware for some of the system's integrated peripheral devices and
the peripheral's Linux device-driver needs to access this firmware.

Device drivers which need such firmware can use the
firmware_request_platform() function for this, note that this is a
separate fallback mechanism from the other fallback mechanisms and
this does not use the sysfs interface.

A device driver which needs this can describe the firmware it needs
using an efi_embedded_fw_desc struct:

.. kernel-doc:: include/linux/efi_embedded_fw.h
   :functions: efi_embedded_fw_desc

The EFI embedded-fw code works by scanning all EFI_BOOT_SERVICES_CODE memory
segments for an eight byte sequence matching prefix; if the prefix is found it
then does a sha256 over length bytes and if that matches makes a copy of length
bytes and adds that to its list with found firmwares.

To avoid doing this somewhat expensive scan on all systems, dmi matching is
used. Drivers are expected to export a dmi_system_id array, with each entries'
driver_data pointing to an efi_embedded_fw_desc.

To register this array with the efi-embedded-fw code, a driver needs to:

1. Always be builtin to the kernel or store the dmi_system_id array in a
   separate object file which always gets builtin.

2. Add an extern declaration for the dmi_system_id array to
   include/linux/efi_embedded_fw.h.

3. Add the dmi_system_id array to the embedded_fw_table in
   drivers/firmware/efi/embedded-firmware.c wrapped in a #ifdef testing that
   the driver is being builtin.

4. Add "select EFI_EMBEDDED_FIRMWARE if EFI_STUB" to its Kconfig entry.

The firmware_request_platform() function will always first try to load firmware
with the specified name directly from the disk, so the EFI embedded-fw can
always be overridden by placing a file under /lib/firmware.

Note that:

1. The code scanning for EFI embedded-firmware runs near the end
   of start_kernel(), just before calling rest_init(). For normal drivers and
   subsystems using subsys_initcall() to register themselves this does not
   matter. This means that code running earlier cannot use EFI
   embedded-firmware.

2. At the moment the EFI embedded-fw code assumes that firmwares always start at
   an offset which is a multiple of 8 bytes, if this is not true for your case
   send in a patch to fix this.

3. At the moment the EFI embedded-fw code only works on x86 because other archs
   free EFI_BOOT_SERVICES_CODE before the EFI embedded-fw code gets a chance to
   scan it.

4. The current brute-force scanning of EFI_BOOT_SERVICES_CODE is an ad-hoc
   brute-force solution. There has been discussion to use the UEFI Platform
   Initialization (PI) spec's Firmware Volume protocol. This has been rejected
   because the FV Protocol relies on *internal* interfaces of the PI spec, and:
   1. The PI spec does not define peripheral firmware at all
   2. The internal interfaces of the PI spec do not guarantee any backward
   compatibility. Any implementation details in FV may be subject to change,
   and may vary system to system. Supporting the FV Protocol would be
   difficult as it is purposely ambiguous.

Example how to check for and extract embedded firmware
------------------------------------------------------

To check for, for example Silead touchscreen controller embedded firmware,
do the following:

1. Boot the system with efi=debug on the kernel commandline

2. cp /sys/kernel/debug/efi/boot_services_code? to your home dir

3. Open the boot_services_code? files in a hex-editor, search for the
   magic prefix for Silead firmware: F0 00 00 00 02 00 00 00, this gives you
   the beginning address of the firmware inside the boot_services_code? file.

4. The firmware has a specific pattern, it starts with a 8 byte page-address,
   typically F0 00 00 00 02 00 00 00 for the first page followed by 32-bit
   word-address + 32-bit value pairs. With the word-address incrementing 4
   bytes (1 word) for each pair until a page is complete. A complete page is
   followed by a new page-address, followed by more word + value pairs. This
   leads to a very distinct pattern. Scroll down until this pattern stops,
   this gives you the end of the firmware inside the boot_services_code? file.

5. "dd if=boot_services_code? of=firmware bs=1 skip=<begin-addr> count=<len>"
   will extract the firmware for you. Inspect the firmware file in a
   hexeditor to make sure you got the dd parameters correct.

6. Copy it to /lib/firmware under the expected name to test it.

7. If the extracted firmware works, you can use the found info to fill an
   efi_embedded_fw_desc struct to describe it, run "sha256sum firmware"
   to get the sha256sum to put in the sha256 field.