Watch
1
Fork
You've already forked kernel_a52xq
0
mirror of https://github.com/a52xq-dev/kernel.git synced 2026-10-18 21:58:11 +07:00

A reasonably busy cycle for documentation this time around. There is a new

guide for user-space API documents, rather sparsely populated at the
 moment, but it's a start.  Markus improved the infrastructure for
 converting diagrams.  Mauro has converted much of the USB documentation
 over to RST.  Plus the usual set of fixes, improvements, and tweaks.
 
 There's a bit more than the usual amount of reaching out of Documentation/
 to fix comments elsewhere in the tree; I have acks for those where I could
 get them.
 -----BEGIN PGP SIGNATURE-----
 
 iQIcBAABAgAGBQJZB1elAAoJEI3ONVYwIuV6wUIQAJSM/4rNdj6z+GXeWhRfbsOo
 vqqVYluvXQIJaaqdsy9dgcfThhOXWYsPyVF6Xd+bDJpwF3BMZYbX1CI1Mo3kRD+7
 9+Pf68cYSHRoU3l/sFI8q0zfKbHtmFteIvnRQoFtRaExqgTR8glUfxNDyN9XuNAZ
 3naS4qMZivM4gjMcSpIB/wFOQpV+6qVIs6VTFLdCC8wodT3W/Wmb+bqrCVJ0twbB
 t8jJeYHt2wsiTdqrKU+VilAUAZ1Lby+DNfeWrO18rC1ohktPyUzOGg8JmTKUBpVO
 qj1OJwD6abuaNh/J9bXsh8u0OrVrBKWjVrhq9IFYDlm92fu3Bgr6YeoaVPEpcklt
 jdlgZnWs9/oXa6d32aMc9F7mP9a0Q1qikFTYINhaHQZCb4VDRuQ9hCSuqWm5jlVy
 lmVAoxLa0zSdOoXaYuO3HC99ku1cIn814CXMDz/IwKXkqUCV+zl+H3AGkvxGyQ5M
 eblw2TnQnc6e1LRcxt5bgpFR1JYMbCJhu0U5XrNFueQV8ReB15dvL7h4y21dWJKF
 2Sr83rwfG1rpZQiSqCjOXxIzuXbEGH3+a+zCDV5IHhQRt/VNDOt2hgmcyucSSJ5h
 5GRFYgTlGvoT/6LdIT39QooHB+4tSDRtEQ6lh0q2ZtVV2rfG/I6/PR5sUbWM65SN
 vAfctRm2afHLhdonSX5O
 =41m+
 -----END PGP SIGNATURE-----

Merge tag 'docs-4.12' of git://git.lwn.net/linux

Pull documentation update from Jonathan Corbet:
 "A reasonably busy cycle for documentation this time around. There is a
  new guide for user-space API documents, rather sparsely populated at
  the moment, but it's a start. Markus improved the infrastructure for
  converting diagrams. Mauro has converted much of the USB documentation
  over to RST. Plus the usual set of fixes, improvements, and tweaks.

  There's a bit more than the usual amount of reaching out of
  Documentation/ to fix comments elsewhere in the tree; I have acks for
  those where I could get them"

* tag 'docs-4.12' of git://git.lwn.net/linux: (74 commits)
  docs: Fix a couple typos
  docs: Fix a spelling error in vfio-mediated-device.txt
  docs: Fix a spelling error in ioctl-number.txt
  MAINTAINERS: update file entry for HSI subsystem
  Documentation: allow installing man pages to a user defined directory
  Doc/PM: Sync with intel_powerclamp code behavior
  zr364xx.rst: usb/devices is now at /sys/kernel/debug/
  usb.rst: move documentation from proc_usb_info.txt to USB ReST book
  convert philips.txt to ReST and add to media docs
  docs-rst: usb: update old usbfs-related documentation
  arm: Documentation: update a path name
  docs: process/4.Coding.rst: Fix a couple of document refs
  docs-rst: fix usb cross-references
  usb: gadget.h: be consistent at kernel doc macros
  usb: composite.h: fix two warnings when building docs
  usb: get rid of some ReST doc build errors
  usb.rst: get rid of some Sphinx errors
  usb/URB.txt: convert to ReST and update it
  usb/persist.txt: convert to ReST and add to driver-api book
  usb/hotplug.txt: convert to ReST and add to driver-api book
  ...
This commit is contained in:
Linus Torvalds 2017-05-02 10:21:17 -07:00
commit c58d4055c0
132 changed files with 6111 additions and 5417 deletions

View file

@ -9,7 +9,7 @@ Description:
hubs this facility is always enabled and their device
directories will not contain this file.
For more information, see Documentation/usb/persist.txt.
For more information, see Documentation/driver-api/usb/persist.rst.
What: /sys/bus/usb/devices/.../power/autosuspend
Date: March 2007

View file

@ -16,7 +16,8 @@ The vDSO uses symbol versioning; whenever you request a symbol from the
vDSO, specify the version you are expecting.
Programs that dynamically link to glibc will use the vDSO automatically.
Otherwise, you can use the reference parser in Documentation/vDSO/parse_vdso.c.
Otherwise, you can use the reference parser in
tools/testing/selftests/vDSO/parse_vdso.c.
Unless otherwise noted, the set of symbols with any given version and the
ABI of those symbols is considered stable. It may vary across architectures,

View file

@ -299,5 +299,5 @@ What: /sys/bus/pci/devices/.../revision
Date: November 2016
Contact: Emil Velikov <emil.l.velikov@gmail.com>
Description:
This file contains the revision field of the the PCI device.
This file contains the revision field of the PCI device.
The value comes from device config space. The file is read only.

View file

@ -8,12 +8,11 @@
DOCBOOKS := z8530book.xml \
kernel-hacking.xml kernel-locking.xml \
writing_usb_driver.xml networking.xml \
kernel-api.xml filesystems.xml lsm.xml kgdb.xml \
gadget.xml libata.xml mtdnand.xml librs.xml rapidio.xml \
genericirq.xml s390-drivers.xml scsi.xml \
sh.xml w1.xml \
writing_musb_glue_layer.xml
networking.xml \
filesystems.xml lsm.xml kgdb.xml \
libata.xml mtdnand.xml librs.xml rapidio.xml \
s390-drivers.xml scsi.xml \
sh.xml w1.xml
ifeq ($(DOCBOOKS),)
@ -62,11 +61,14 @@ MAN := $(patsubst %.xml, %.9, $(BOOKS))
mandocs: $(MAN)
find $(obj)/man -name '*.9' | xargs gzip -nf
# Default location for installed man pages
export INSTALL_MAN_PATH = $(objtree)/usr
installmandocs: mandocs
mkdir -p /usr/local/man/man9/
mkdir -p $(INSTALL_MAN_PATH)/man/man9/
find $(obj)/man -name '*.9.gz' -printf '%h %f\n' | \
sort -k 2 -k 1 | uniq -f 1 | sed -e 's: :/:' | \
xargs install -m 644 -t /usr/local/man/man9/
xargs install -m 644 -t $(INSTALL_MAN_PATH)/man/man9/
# no-op for the DocBook toolchain
epubdocs:
@ -238,7 +240,9 @@ dochelp:
@echo ' psdocs - Postscript'
@echo ' xmldocs - XML DocBook'
@echo ' mandocs - man pages'
@echo ' installmandocs - install man pages generated by mandocs'
@echo ' installmandocs - install man pages generated by mandocs to INSTALL_MAN_PATH'; \
echo ' (default: $(INSTALL_MAN_PATH))'; \
echo ''
@echo ' cleandocs - clean all generated DocBook files'
@echo
@echo ' make DOCBOOKS="s1.xml s2.xml" [target] Generate only docs s1.xml s2.xml'

View file

@ -1,793 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
"http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" []>
<book id="USB-Gadget-API">
<bookinfo>
<title>USB Gadget API for Linux</title>
<date>20 August 2004</date>
<edition>20 August 2004</edition>
<legalnotice>
<para>
This documentation is free software; you can redistribute
it and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later
version.
</para>
<para>
This program is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
</para>
<para>
You should have received a copy of the GNU General Public
License along with this program; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
</para>
<para>
For more details see the file COPYING in the source
distribution of Linux.
</para>
</legalnotice>
<copyright>
<year>2003-2004</year>
<holder>David Brownell</holder>
</copyright>
<author>
<firstname>David</firstname>
<surname>Brownell</surname>
<affiliation>
<address><email>dbrownell@users.sourceforge.net</email></address>
</affiliation>
</author>
</bookinfo>
<toc></toc>
<chapter id="intro"><title>Introduction</title>
<para>This document presents a Linux-USB "Gadget"
kernel mode
API, for use within peripherals and other USB devices
that embed Linux.
It provides an overview of the API structure,
and shows how that fits into a system development project.
This is the first such API released on Linux to address
a number of important problems, including: </para>
<itemizedlist>
<listitem><para>Supports USB 2.0, for high speed devices which
can stream data at several dozen megabytes per second.
</para></listitem>
<listitem><para>Handles devices with dozens of endpoints just as
well as ones with just two fixed-function ones. Gadget drivers
can be written so they're easy to port to new hardware.
</para></listitem>
<listitem><para>Flexible enough to expose more complex USB device
capabilities such as multiple configurations, multiple interfaces,
composite devices,
and alternate interface settings.
</para></listitem>
<listitem><para>USB "On-The-Go" (OTG) support, in conjunction
with updates to the Linux-USB host side.
</para></listitem>
<listitem><para>Sharing data structures and API models with the
Linux-USB host side API. This helps the OTG support, and
looks forward to more-symmetric frameworks (where the same
I/O model is used by both host and device side drivers).
</para></listitem>
<listitem><para>Minimalist, so it's easier to support new device
controller hardware. I/O processing doesn't imply large
demands for memory or CPU resources.
</para></listitem>
</itemizedlist>
<para>Most Linux developers will not be able to use this API, since they
have USB "host" hardware in a PC, workstation, or server.
Linux users with embedded systems are more likely to
have USB peripheral hardware.
To distinguish drivers running inside such hardware from the
more familiar Linux "USB device drivers",
which are host side proxies for the real USB devices,
a different term is used:
the drivers inside the peripherals are "USB gadget drivers".
In USB protocol interactions, the device driver is the master
(or "client driver")
and the gadget driver is the slave (or "function driver").
</para>
<para>The gadget API resembles the host side Linux-USB API in that both
use queues of request objects to package I/O buffers, and those requests
may be submitted or canceled.
They share common definitions for the standard USB
<emphasis>Chapter 9</emphasis> messages, structures, and constants.
Also, both APIs bind and unbind drivers to devices.
The APIs differ in detail, since the host side's current
URB framework exposes a number of implementation details
and assumptions that are inappropriate for a gadget API.
While the model for control transfers and configuration
management is necessarily different (one side is a hardware-neutral master,
the other is a hardware-aware slave), the endpoint I/0 API used here
should also be usable for an overhead-reduced host side API.
</para>
</chapter>
<chapter id="structure"><title>Structure of Gadget Drivers</title>
<para>A system running inside a USB peripheral
normally has at least three layers inside the kernel to handle
USB protocol processing, and may have additional layers in
user space code.
The "gadget" API is used by the middle layer to interact
with the lowest level (which directly handles hardware).
</para>
<para>In Linux, from the bottom up, these layers are:
</para>
<variablelist>
<varlistentry>
<term><emphasis>USB Controller Driver</emphasis></term>
<listitem>
<para>This is the lowest software level.
It is the only layer that talks to hardware,
through registers, fifos, dma, irqs, and the like.
The <filename>&lt;linux/usb/gadget.h&gt;</filename> API abstracts
the peripheral controller endpoint hardware.
That hardware is exposed through endpoint objects, which accept
streams of IN/OUT buffers, and through callbacks that interact
with gadget drivers.
Since normal USB devices only have one upstream
port, they only have one of these drivers.
The controller driver can support any number of different
gadget drivers, but only one of them can be used at a time.
</para>
<para>Examples of such controller hardware include
the PCI-based NetChip 2280 USB 2.0 high speed controller,
the SA-11x0 or PXA-25x UDC (found within many PDAs),
and a variety of other products.
</para>
</listitem></varlistentry>
<varlistentry>
<term><emphasis>Gadget Driver</emphasis></term>
<listitem>
<para>The lower boundary of this driver implements hardware-neutral
USB functions, using calls to the controller driver.
Because such hardware varies widely in capabilities and restrictions,
and is used in embedded environments where space is at a premium,
the gadget driver is often configured at compile time
to work with endpoints supported by one particular controller.
Gadget drivers may be portable to several different controllers,
using conditional compilation.
(Recent kernels substantially simplify the work involved in
supporting new hardware, by <emphasis>autoconfiguring</emphasis>
endpoints automatically for many bulk-oriented drivers.)
Gadget driver responsibilities include:
</para>
<itemizedlist>
<listitem><para>handling setup requests (ep0 protocol responses)
possibly including class-specific functionality
</para></listitem>
<listitem><para>returning configuration and string descriptors
</para></listitem>
<listitem><para>(re)setting configurations and interface
altsettings, including enabling and configuring endpoints
</para></listitem>
<listitem><para>handling life cycle events, such as managing
bindings to hardware,
USB suspend/resume, remote wakeup,
and disconnection from the USB host.
</para></listitem>
<listitem><para>managing IN and OUT transfers on all currently
enabled endpoints
</para></listitem>
</itemizedlist>
<para>
Such drivers may be modules of proprietary code, although
that approach is discouraged in the Linux community.
</para>
</listitem></varlistentry>
<varlistentry>
<term><emphasis>Upper Level</emphasis></term>
<listitem>
<para>Most gadget drivers have an upper boundary that connects
to some Linux driver or framework in Linux.
Through that boundary flows the data which the gadget driver
produces and/or consumes through protocol transfers over USB.
Examples include:
</para>
<itemizedlist>
<listitem><para>user mode code, using generic (gadgetfs)
or application specific files in
<filename>/dev</filename>
</para></listitem>
<listitem><para>networking subsystem (for network gadgets,
like the CDC Ethernet Model gadget driver)
</para></listitem>
<listitem><para>data capture drivers, perhaps video4Linux or
a scanner driver; or test and measurement hardware.
</para></listitem>
<listitem><para>input subsystem (for HID gadgets)
</para></listitem>
<listitem><para>sound subsystem (for audio gadgets)
</para></listitem>
<listitem><para>file system (for PTP gadgets)
</para></listitem>
<listitem><para>block i/o subsystem (for usb-storage gadgets)
</para></listitem>
<listitem><para>... and more </para></listitem>
</itemizedlist>
</listitem></varlistentry>
<varlistentry>
<term><emphasis>Additional Layers</emphasis></term>
<listitem>
<para>Other layers may exist.
These could include kernel layers, such as network protocol stacks,
as well as user mode applications building on standard POSIX
system call APIs such as
<emphasis>open()</emphasis>, <emphasis>close()</emphasis>,
<emphasis>read()</emphasis> and <emphasis>write()</emphasis>.
On newer systems, POSIX Async I/O calls may be an option.
Such user mode code will not necessarily be subject to
the GNU General Public License (GPL).
</para>
</listitem></varlistentry>
</variablelist>
<para>OTG-capable systems will also need to include a standard Linux-USB
host side stack,
with <emphasis>usbcore</emphasis>,
one or more <emphasis>Host Controller Drivers</emphasis> (HCDs),
<emphasis>USB Device Drivers</emphasis> to support
the OTG "Targeted Peripheral List",
and so forth.
There will also be an <emphasis>OTG Controller Driver</emphasis>,
which is visible to gadget and device driver developers only indirectly.
That helps the host and device side USB controllers implement the
two new OTG protocols (HNP and SRP).
Roles switch (host to peripheral, or vice versa) using HNP
during USB suspend processing, and SRP can be viewed as a
more battery-friendly kind of device wakeup protocol.
</para>
<para>Over time, reusable utilities are evolving to help make some
gadget driver tasks simpler.
For example, building configuration descriptors from vectors of
descriptors for the configurations interfaces and endpoints is
now automated, and many drivers now use autoconfiguration to
choose hardware endpoints and initialize their descriptors.
A potential example of particular interest
is code implementing standard USB-IF protocols for
HID, networking, storage, or audio classes.
Some developers are interested in KDB or KGDB hooks, to let
target hardware be remotely debugged.
Most such USB protocol code doesn't need to be hardware-specific,
any more than network protocols like X11, HTTP, or NFS are.
Such gadget-side interface drivers should eventually be combined,
to implement composite devices.
</para>
</chapter>
<chapter id="api"><title>Kernel Mode Gadget API</title>
<para>Gadget drivers declare themselves through a
<emphasis>struct usb_gadget_driver</emphasis>, which is responsible for
most parts of enumeration for a <emphasis>struct usb_gadget</emphasis>.
The response to a set_configuration usually involves
enabling one or more of the <emphasis>struct usb_ep</emphasis> objects
exposed by the gadget, and submitting one or more
<emphasis>struct usb_request</emphasis> buffers to transfer data.
Understand those four data types, and their operations, and
you will understand how this API works.
</para>
<note><title>Incomplete Data Type Descriptions</title>
<para>This documentation was prepared using the standard Linux
kernel <filename>docproc</filename> tool, which turns text
and in-code comments into SGML DocBook and then into usable
formats such as HTML or PDF.
Other than the "Chapter 9" data types, most of the significant
data types and functions are described here.
</para>
<para>However, docproc does not understand all the C constructs
that are used, so some relevant information is likely omitted from
what you are reading.
One example of such information is endpoint autoconfiguration.
You'll have to read the header file, and use example source
code (such as that for "Gadget Zero"), to fully understand the API.
</para>
<para>The part of the API implementing some basic
driver capabilities is specific to the version of the
Linux kernel that's in use.
The 2.6 kernel includes a <emphasis>driver model</emphasis>
framework that has no analogue on earlier kernels;
so those parts of the gadget API are not fully portable.
(They are implemented on 2.4 kernels, but in a different way.)
The driver model state is another part of this API that is
ignored by the kerneldoc tools.
</para>
</note>
<para>The core API does not expose
every possible hardware feature, only the most widely available ones.
There are significant hardware features, such as device-to-device DMA
(without temporary storage in a memory buffer)
that would be added using hardware-specific APIs.
</para>
<para>This API allows drivers to use conditional compilation to handle
endpoint capabilities of different hardware, but doesn't require that.
Hardware tends to have arbitrary restrictions, relating to
transfer types, addressing, packet sizes, buffering, and availability.
As a rule, such differences only matter for "endpoint zero" logic
that handles device configuration and management.
The API supports limited run-time
detection of capabilities, through naming conventions for endpoints.
Many drivers will be able to at least partially autoconfigure
themselves.
In particular, driver init sections will often have endpoint
autoconfiguration logic that scans the hardware's list of endpoints
to find ones matching the driver requirements
(relying on those conventions), to eliminate some of the most
common reasons for conditional compilation.
</para>
<para>Like the Linux-USB host side API, this API exposes
the "chunky" nature of USB messages: I/O requests are in terms
of one or more "packets", and packet boundaries are visible to drivers.
Compared to RS-232 serial protocols, USB resembles
synchronous protocols like HDLC
(N bytes per frame, multipoint addressing, host as the primary
station and devices as secondary stations)
more than asynchronous ones
(tty style: 8 data bits per frame, no parity, one stop bit).
So for example the controller drivers won't buffer
two single byte writes into a single two-byte USB IN packet,
although gadget drivers may do so when they implement
protocols where packet boundaries (and "short packets")
are not significant.
</para>
<sect1 id="lifecycle"><title>Driver Life Cycle</title>
<para>Gadget drivers make endpoint I/O requests to hardware without
needing to know many details of the hardware, but driver
setup/configuration code needs to handle some differences.
Use the API like this:
</para>
<orderedlist numeration='arabic'>
<listitem><para>Register a driver for the particular device side
usb controller hardware,
such as the net2280 on PCI (USB 2.0),
sa11x0 or pxa25x as found in Linux PDAs,
and so on.
At this point the device is logically in the USB ch9 initial state
("attached"), drawing no power and not usable
(since it does not yet support enumeration).
Any host should not see the device, since it's not
activated the data line pullup used by the host to
detect a device, even if VBUS power is available.
</para></listitem>
<listitem><para>Register a gadget driver that implements some higher level
device function. That will then bind() to a usb_gadget, which
activates the data line pullup sometime after detecting VBUS.
</para></listitem>
<listitem><para>The hardware driver can now start enumerating.
The steps it handles are to accept USB power and set_address requests.
Other steps are handled by the gadget driver.
If the gadget driver module is unloaded before the host starts to
enumerate, steps before step 7 are skipped.
</para></listitem>
<listitem><para>The gadget driver's setup() call returns usb descriptors,
based both on what the bus interface hardware provides and on the
functionality being implemented.
That can involve alternate settings or configurations,
unless the hardware prevents such operation.
For OTG devices, each configuration descriptor includes
an OTG descriptor.
</para></listitem>
<listitem><para>The gadget driver handles the last step of enumeration,
when the USB host issues a set_configuration call.
It enables all endpoints used in that configuration,
with all interfaces in their default settings.
That involves using a list of the hardware's endpoints, enabling each
endpoint according to its descriptor.
It may also involve using <function>usb_gadget_vbus_draw</function>
to let more power be drawn from VBUS, as allowed by that configuration.
For OTG devices, setting a configuration may also involve reporting
HNP capabilities through a user interface.
</para></listitem>
<listitem><para>Do real work and perform data transfers, possibly involving
changes to interface settings or switching to new configurations, until the
device is disconnect()ed from the host.
Queue any number of transfer requests to each endpoint.
It may be suspended and resumed several times before being disconnected.
On disconnect, the drivers go back to step 3 (above).
</para></listitem>
<listitem><para>When the gadget driver module is being unloaded,
the driver unbind() callback is issued. That lets the controller
driver be unloaded.
</para></listitem>
</orderedlist>
<para>Drivers will normally be arranged so that just loading the
gadget driver module (or statically linking it into a Linux kernel)
allows the peripheral device to be enumerated, but some drivers
will defer enumeration until some higher level component (like
a user mode daemon) enables it.
Note that at this lowest level there are no policies about how
ep0 configuration logic is implemented,
except that it should obey USB specifications.
Such issues are in the domain of gadget drivers,
including knowing about implementation constraints
imposed by some USB controllers
or understanding that composite devices might happen to
be built by integrating reusable components.
</para>
<para>Note that the lifecycle above can be slightly different
for OTG devices.
Other than providing an additional OTG descriptor in each
configuration, only the HNP-related differences are particularly
visible to driver code.
They involve reporting requirements during the SET_CONFIGURATION
request, and the option to invoke HNP during some suspend callbacks.
Also, SRP changes the semantics of
<function>usb_gadget_wakeup</function>
slightly.
</para>
</sect1>
<sect1 id="ch9"><title>USB 2.0 Chapter 9 Types and Constants</title>
<para>Gadget drivers
rely on common USB structures and constants
defined in the
<filename>&lt;linux/usb/ch9.h&gt;</filename>
header file, which is standard in Linux 2.6 kernels.
These are the same types and constants used by host
side drivers (and usbcore).
</para>
!Iinclude/linux/usb/ch9.h
</sect1>
<sect1 id="core"><title>Core Objects and Methods</title>
<para>These are declared in
<filename>&lt;linux/usb/gadget.h&gt;</filename>,
and are used by gadget drivers to interact with
USB peripheral controller drivers.
</para>
<!-- yeech, this is ugly in nsgmls PDF output.
the PDF bookmark and refentry output nesting is wrong,
and the member/argument documentation indents ugly.
plus something (docproc?) adds whitespace before the
descriptive paragraph text, so it can't line up right
unless the explanations are trivial.
-->
!Iinclude/linux/usb/gadget.h
</sect1>
<sect1 id="utils"><title>Optional Utilities</title>
<para>The core API is sufficient for writing a USB Gadget Driver,
but some optional utilities are provided to simplify common tasks.
These utilities include endpoint autoconfiguration.
</para>
!Edrivers/usb/gadget/usbstring.c
!Edrivers/usb/gadget/config.c
<!-- !Edrivers/usb/gadget/epautoconf.c -->
</sect1>
<sect1 id="composite"><title>Composite Device Framework</title>
<para>The core API is sufficient for writing drivers for composite
USB devices (with more than one function in a given configuration),
and also multi-configuration devices (also more than one function,
but not necessarily sharing a given configuration).
There is however an optional framework which makes it easier to
reuse and combine functions.
</para>
<para>Devices using this framework provide a <emphasis>struct
usb_composite_driver</emphasis>, which in turn provides one or
more <emphasis>struct usb_configuration</emphasis> instances.
Each such configuration includes at least one
<emphasis>struct usb_function</emphasis>, which packages a user
visible role such as "network link" or "mass storage device".
Management functions may also exist, such as "Device Firmware
Upgrade".
</para>
!Iinclude/linux/usb/composite.h
!Edrivers/usb/gadget/composite.c
</sect1>
<sect1 id="functions"><title>Composite Device Functions</title>
<para>At this writing, a few of the current gadget drivers have
been converted to this framework.
Near-term plans include converting all of them, except for "gadgetfs".
</para>
!Edrivers/usb/gadget/function/f_acm.c
!Edrivers/usb/gadget/function/f_ecm.c
!Edrivers/usb/gadget/function/f_subset.c
!Edrivers/usb/gadget/function/f_obex.c
!Edrivers/usb/gadget/function/f_serial.c
</sect1>
</chapter>
<chapter id="controllers"><title>Peripheral Controller Drivers</title>
<para>The first hardware supporting this API was the NetChip 2280
controller, which supports USB 2.0 high speed and is based on PCI.
This is the <filename>net2280</filename> driver module.
The driver supports Linux kernel versions 2.4 and 2.6;
contact NetChip Technologies for development boards and product
information.
</para>
<para>Other hardware working in the "gadget" framework includes:
Intel's PXA 25x and IXP42x series processors
(<filename>pxa2xx_udc</filename>),
Toshiba TC86c001 "Goku-S" (<filename>goku_udc</filename>),
Renesas SH7705/7727 (<filename>sh_udc</filename>),
MediaQ 11xx (<filename>mq11xx_udc</filename>),
Hynix HMS30C7202 (<filename>h7202_udc</filename>),
National 9303/4 (<filename>n9604_udc</filename>),
Texas Instruments OMAP (<filename>omap_udc</filename>),
Sharp LH7A40x (<filename>lh7a40x_udc</filename>),
and more.
Most of those are full speed controllers.
</para>
<para>At this writing, there are people at work on drivers in
this framework for several other USB device controllers,
with plans to make many of them be widely available.
</para>
<!-- !Edrivers/usb/gadget/net2280.c -->
<para>A partial USB simulator,
the <filename>dummy_hcd</filename> driver, is available.
It can act like a net2280, a pxa25x, or an sa11x0 in terms
of available endpoints and device speeds; and it simulates
control, bulk, and to some extent interrupt transfers.
That lets you develop some parts of a gadget driver on a normal PC,
without any special hardware, and perhaps with the assistance
of tools such as GDB running with User Mode Linux.
At least one person has expressed interest in adapting that
approach, hooking it up to a simulator for a microcontroller.
Such simulators can help debug subsystems where the runtime hardware
is unfriendly to software development, or is not yet available.
</para>
<para>Support for other controllers is expected to be developed
and contributed
over time, as this driver framework evolves.
</para>
</chapter>
<chapter id="gadget"><title>Gadget Drivers</title>
<para>In addition to <emphasis>Gadget Zero</emphasis>
(used primarily for testing and development with drivers
for usb controller hardware), other gadget drivers exist.
</para>
<para>There's an <emphasis>ethernet</emphasis> gadget
driver, which implements one of the most useful
<emphasis>Communications Device Class</emphasis> (CDC) models.
One of the standards for cable modem interoperability even
specifies the use of this ethernet model as one of two
mandatory options.
Gadgets using this code look to a USB host as if they're
an Ethernet adapter.
It provides access to a network where the gadget's CPU is one host,
which could easily be bridging, routing, or firewalling
access to other networks.
Since some hardware can't fully implement the CDC Ethernet
requirements, this driver also implements a "good parts only"
subset of CDC Ethernet.
(That subset doesn't advertise itself as CDC Ethernet,
to avoid creating problems.)
</para>
<para>Support for Microsoft's <emphasis>RNDIS</emphasis>
protocol has been contributed by Pengutronix and Auerswald GmbH.
This is like CDC Ethernet, but it runs on more slightly USB hardware
(but less than the CDC subset).
However, its main claim to fame is being able to connect directly to
recent versions of Windows, using drivers that Microsoft bundles
and supports, making it much simpler to network with Windows.
</para>
<para>There is also support for user mode gadget drivers,
using <emphasis>gadgetfs</emphasis>.
This provides a <emphasis>User Mode API</emphasis> that presents
each endpoint as a single file descriptor. I/O is done using
normal <emphasis>read()</emphasis> and <emphasis>read()</emphasis> calls.
Familiar tools like GDB and pthreads can be used to
develop and debug user mode drivers, so that once a robust
controller driver is available many applications for it
won't require new kernel mode software.
Linux 2.6 <emphasis>Async I/O (AIO)</emphasis>
support is available, so that user mode software
can stream data with only slightly more overhead
than a kernel driver.
</para>
<para>There's a USB Mass Storage class driver, which provides
a different solution for interoperability with systems such
as MS-Windows and MacOS.
That <emphasis>Mass Storage</emphasis> driver uses a
file or block device as backing store for a drive,
like the <filename>loop</filename> driver.
The USB host uses the BBB, CB, or CBI versions of the mass
storage class specification, using transparent SCSI commands
to access the data from the backing store.
</para>
<para>There's a "serial line" driver, useful for TTY style
operation over USB.
The latest version of that driver supports CDC ACM style
operation, like a USB modem, and so on most hardware it can
interoperate easily with MS-Windows.
One interesting use of that driver is in boot firmware (like a BIOS),
which can sometimes use that model with very small systems without
real serial lines.
</para>
<para>Support for other kinds of gadget is expected to
be developed and contributed
over time, as this driver framework evolves.
</para>
</chapter>
<chapter id="otg"><title>USB On-The-GO (OTG)</title>
<para>USB OTG support on Linux 2.6 was initially developed
by Texas Instruments for
<ulink url="http://www.omap.com">OMAP</ulink> 16xx and 17xx
series processors.
Other OTG systems should work in similar ways, but the
hardware level details could be very different.
</para>
<para>Systems need specialized hardware support to implement OTG,
notably including a special <emphasis>Mini-AB</emphasis> jack
and associated transceiver to support <emphasis>Dual-Role</emphasis>
operation:
they can act either as a host, using the standard
Linux-USB host side driver stack,
or as a peripheral, using this "gadget" framework.
To do that, the system software relies on small additions
to those programming interfaces,
and on a new internal component (here called an "OTG Controller")
affecting which driver stack connects to the OTG port.
In each role, the system can re-use the existing pool of
hardware-neutral drivers, layered on top of the controller
driver interfaces (<emphasis>usb_bus</emphasis> or
<emphasis>usb_gadget</emphasis>).
Such drivers need at most minor changes, and most of the calls
added to support OTG can also benefit non-OTG products.
</para>
<itemizedlist>
<listitem><para>Gadget drivers test the <emphasis>is_otg</emphasis>
flag, and use it to determine whether or not to include
an OTG descriptor in each of their configurations.
</para></listitem>
<listitem><para>Gadget drivers may need changes to support the
two new OTG protocols, exposed in new gadget attributes
such as <emphasis>b_hnp_enable</emphasis> flag.
HNP support should be reported through a user interface
(two LEDs could suffice), and is triggered in some cases
when the host suspends the peripheral.
SRP support can be user-initiated just like remote wakeup,
probably by pressing the same button.
</para></listitem>
<listitem><para>On the host side, USB device drivers need
to be taught to trigger HNP at appropriate moments, using
<function>usb_suspend_device()</function>.
That also conserves battery power, which is useful even
for non-OTG configurations.
</para></listitem>
<listitem><para>Also on the host side, a driver must support the
OTG "Targeted Peripheral List". That's just a whitelist,
used to reject peripherals not supported with a given
Linux OTG host.
<emphasis>This whitelist is product-specific;
each product must modify <filename>otg_whitelist.h</filename>
to match its interoperability specification.
</emphasis>
</para>
<para>Non-OTG Linux hosts, like PCs and workstations,
normally have some solution for adding drivers, so that
peripherals that aren't recognized can eventually be supported.
That approach is unreasonable for consumer products that may
never have their firmware upgraded, and where it's usually
unrealistic to expect traditional PC/workstation/server kinds
of support model to work.
For example, it's often impractical to change device firmware
once the product has been distributed, so driver bugs can't
normally be fixed if they're found after shipment.
</para></listitem>
</itemizedlist>
<para>
Additional changes are needed below those hardware-neutral
<emphasis>usb_bus</emphasis> and <emphasis>usb_gadget</emphasis>
driver interfaces; those aren't discussed here in any detail.
Those affect the hardware-specific code for each USB Host or Peripheral
controller, and how the HCD initializes (since OTG can be active only
on a single port).
They also involve what may be called an <emphasis>OTG Controller
Driver</emphasis>, managing the OTG transceiver and the OTG state
machine logic as well as much of the root hub behavior for the
OTG port.
The OTG controller driver needs to activate and deactivate USB
controllers depending on the relevant device role.
Some related changes were needed inside usbcore, so that it
can identify OTG-capable devices and respond appropriately
to HNP or SRP protocols.
</para>
</chapter>
</book>
<!--
vim:syntax=sgml:sw=4
-->

View file

@ -1,520 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
"http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" []>
<book id="Generic-IRQ-Guide">
<bookinfo>
<title>Linux generic IRQ handling</title>
<authorgroup>
<author>
<firstname>Thomas</firstname>
<surname>Gleixner</surname>
<affiliation>
<address>
<email>tglx@linutronix.de</email>
</address>
</affiliation>
</author>
<author>
<firstname>Ingo</firstname>
<surname>Molnar</surname>
<affiliation>
<address>
<email>mingo@elte.hu</email>
</address>
</affiliation>
</author>
</authorgroup>
<copyright>
<year>2005-2010</year>
<holder>Thomas Gleixner</holder>
</copyright>
<copyright>
<year>2005-2006</year>
<holder>Ingo Molnar</holder>
</copyright>
<legalnotice>
<para>
This documentation is free software; you can redistribute
it and/or modify it under the terms of the GNU General Public
License version 2 as published by the Free Software Foundation.
</para>
<para>
This program is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
</para>
<para>
You should have received a copy of the GNU General Public
License along with this program; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
</para>
<para>
For more details see the file COPYING in the source
distribution of Linux.
</para>
</legalnotice>
</bookinfo>
<toc></toc>
<chapter id="intro">
<title>Introduction</title>
<para>
The generic interrupt handling layer is designed to provide a
complete abstraction of interrupt handling for device drivers.
It is able to handle all the different types of interrupt controller
hardware. Device drivers use generic API functions to request, enable,
disable and free interrupts. The drivers do not have to know anything
about interrupt hardware details, so they can be used on different
platforms without code changes.
</para>
<para>
This documentation is provided to developers who want to implement
an interrupt subsystem based for their architecture, with the help
of the generic IRQ handling layer.
</para>
</chapter>
<chapter id="rationale">
<title>Rationale</title>
<para>
The original implementation of interrupt handling in Linux uses
the __do_IRQ() super-handler, which is able to deal with every
type of interrupt logic.
</para>
<para>
Originally, Russell King identified different types of handlers to
build a quite universal set for the ARM interrupt handler
implementation in Linux 2.5/2.6. He distinguished between:
<itemizedlist>
<listitem><para>Level type</para></listitem>
<listitem><para>Edge type</para></listitem>
<listitem><para>Simple type</para></listitem>
</itemizedlist>
During the implementation we identified another type:
<itemizedlist>
<listitem><para>Fast EOI type</para></listitem>
</itemizedlist>
In the SMP world of the __do_IRQ() super-handler another type
was identified:
<itemizedlist>
<listitem><para>Per CPU type</para></listitem>
</itemizedlist>
</para>
<para>
This split implementation of high-level IRQ handlers allows us to
optimize the flow of the interrupt handling for each specific
interrupt type. This reduces complexity in that particular code path
and allows the optimized handling of a given type.
</para>
<para>
The original general IRQ implementation used hw_interrupt_type
structures and their ->ack(), ->end() [etc.] callbacks to
differentiate the flow control in the super-handler. This leads to
a mix of flow logic and low-level hardware logic, and it also leads
to unnecessary code duplication: for example in i386, there is an
ioapic_level_irq and an ioapic_edge_irq IRQ-type which share many
of the low-level details but have different flow handling.
</para>
<para>
A more natural abstraction is the clean separation of the
'irq flow' and the 'chip details'.
</para>
<para>
Analysing a couple of architecture's IRQ subsystem implementations
reveals that most of them can use a generic set of 'irq flow'
methods and only need to add the chip-level specific code.
The separation is also valuable for (sub)architectures
which need specific quirks in the IRQ flow itself but not in the
chip details - and thus provides a more transparent IRQ subsystem
design.
</para>
<para>
Each interrupt descriptor is assigned its own high-level flow
handler, which is normally one of the generic
implementations. (This high-level flow handler implementation also
makes it simple to provide demultiplexing handlers which can be
found in embedded platforms on various architectures.)
</para>
<para>
The separation makes the generic interrupt handling layer more
flexible and extensible. For example, an (sub)architecture can
use a generic IRQ-flow implementation for 'level type' interrupts
and add a (sub)architecture specific 'edge type' implementation.
</para>
<para>
To make the transition to the new model easier and prevent the
breakage of existing implementations, the __do_IRQ() super-handler
is still available. This leads to a kind of duality for the time
being. Over time the new model should be used in more and more
architectures, as it enables smaller and cleaner IRQ subsystems.
It's deprecated for three years now and about to be removed.
</para>
</chapter>
<chapter id="bugs">
<title>Known Bugs And Assumptions</title>
<para>
None (knock on wood).
</para>
</chapter>
<chapter id="Abstraction">
<title>Abstraction layers</title>
<para>
There are three main levels of abstraction in the interrupt code:
<orderedlist>
<listitem><para>High-level driver API</para></listitem>
<listitem><para>High-level IRQ flow handlers</para></listitem>
<listitem><para>Chip-level hardware encapsulation</para></listitem>
</orderedlist>
</para>
<sect1 id="Interrupt_control_flow">
<title>Interrupt control flow</title>
<para>
Each interrupt is described by an interrupt descriptor structure
irq_desc. The interrupt is referenced by an 'unsigned int' numeric
value which selects the corresponding interrupt description structure
in the descriptor structures array.
The descriptor structure contains status information and pointers
to the interrupt flow method and the interrupt chip structure
which are assigned to this interrupt.
</para>
<para>
Whenever an interrupt triggers, the low-level architecture code calls
into the generic interrupt code by calling desc->handle_irq().
This high-level IRQ handling function only uses desc->irq_data.chip
primitives referenced by the assigned chip descriptor structure.
</para>
</sect1>
<sect1 id="Highlevel_Driver_API">
<title>High-level Driver API</title>
<para>
The high-level Driver API consists of following functions:
<itemizedlist>
<listitem><para>request_irq()</para></listitem>
<listitem><para>free_irq()</para></listitem>
<listitem><para>disable_irq()</para></listitem>
<listitem><para>enable_irq()</para></listitem>
<listitem><para>disable_irq_nosync() (SMP only)</para></listitem>
<listitem><para>synchronize_irq() (SMP only)</para></listitem>
<listitem><para>irq_set_irq_type()</para></listitem>
<listitem><para>irq_set_irq_wake()</para></listitem>
<listitem><para>irq_set_handler_data()</para></listitem>
<listitem><para>irq_set_chip()</para></listitem>
<listitem><para>irq_set_chip_data()</para></listitem>
</itemizedlist>
See the autogenerated function documentation for details.
</para>
</sect1>
<sect1 id="Highlevel_IRQ_flow_handlers">
<title>High-level IRQ flow handlers</title>
<para>
The generic layer provides a set of pre-defined irq-flow methods:
<itemizedlist>
<listitem><para>handle_level_irq</para></listitem>
<listitem><para>handle_edge_irq</para></listitem>
<listitem><para>handle_fasteoi_irq</para></listitem>
<listitem><para>handle_simple_irq</para></listitem>
<listitem><para>handle_percpu_irq</para></listitem>
<listitem><para>handle_edge_eoi_irq</para></listitem>
<listitem><para>handle_bad_irq</para></listitem>
</itemizedlist>
The interrupt flow handlers (either pre-defined or architecture
specific) are assigned to specific interrupts by the architecture
either during bootup or during device initialization.
</para>
<sect2 id="Default_flow_implementations">
<title>Default flow implementations</title>
<sect3 id="Helper_functions">
<title>Helper functions</title>
<para>
The helper functions call the chip primitives and
are used by the default flow implementations.
The following helper functions are implemented (simplified excerpt):
<programlisting>
default_enable(struct irq_data *data)
{
desc->irq_data.chip->irq_unmask(data);
}
default_disable(struct irq_data *data)
{
if (!delay_disable(data))
desc->irq_data.chip->irq_mask(data);
}
default_ack(struct irq_data *data)
{
chip->irq_ack(data);
}
default_mask_ack(struct irq_data *data)
{
if (chip->irq_mask_ack) {
chip->irq_mask_ack(data);
} else {
chip->irq_mask(data);
chip->irq_ack(data);
}
}
noop(struct irq_data *data))
{
}
</programlisting>
</para>
</sect3>
</sect2>
<sect2 id="Default_flow_handler_implementations">
<title>Default flow handler implementations</title>
<sect3 id="Default_Level_IRQ_flow_handler">
<title>Default Level IRQ flow handler</title>
<para>
handle_level_irq provides a generic implementation
for level-triggered interrupts.
</para>
<para>
The following control flow is implemented (simplified excerpt):
<programlisting>
desc->irq_data.chip->irq_mask_ack();
handle_irq_event(desc->action);
desc->irq_data.chip->irq_unmask();
</programlisting>
</para>
</sect3>
<sect3 id="Default_FASTEOI_IRQ_flow_handler">
<title>Default Fast EOI IRQ flow handler</title>
<para>
handle_fasteoi_irq provides a generic implementation
for interrupts, which only need an EOI at the end of
the handler.
</para>
<para>
The following control flow is implemented (simplified excerpt):
<programlisting>
handle_irq_event(desc->action);
desc->irq_data.chip->irq_eoi();
</programlisting>
</para>
</sect3>
<sect3 id="Default_Edge_IRQ_flow_handler">
<title>Default Edge IRQ flow handler</title>
<para>
handle_edge_irq provides a generic implementation
for edge-triggered interrupts.
</para>
<para>
The following control flow is implemented (simplified excerpt):
<programlisting>
if (desc->status &amp; running) {
desc->irq_data.chip->irq_mask_ack();
desc->status |= pending | masked;
return;
}
desc->irq_data.chip->irq_ack();
desc->status |= running;
do {
if (desc->status &amp; masked)
desc->irq_data.chip->irq_unmask();
desc->status &amp;= ~pending;
handle_irq_event(desc->action);
} while (status &amp; pending);
desc->status &amp;= ~running;
</programlisting>
</para>
</sect3>
<sect3 id="Default_simple_IRQ_flow_handler">
<title>Default simple IRQ flow handler</title>
<para>
handle_simple_irq provides a generic implementation
for simple interrupts.
</para>
<para>
Note: The simple flow handler does not call any
handler/chip primitives.
</para>
<para>
The following control flow is implemented (simplified excerpt):
<programlisting>
handle_irq_event(desc->action);
</programlisting>
</para>
</sect3>
<sect3 id="Default_per_CPU_flow_handler">
<title>Default per CPU flow handler</title>
<para>
handle_percpu_irq provides a generic implementation
for per CPU interrupts.
</para>
<para>
Per CPU interrupts are only available on SMP and
the handler provides a simplified version without
locking.
</para>
<para>
The following control flow is implemented (simplified excerpt):
<programlisting>
if (desc->irq_data.chip->irq_ack)
desc->irq_data.chip->irq_ack();
handle_irq_event(desc->action);
if (desc->irq_data.chip->irq_eoi)
desc->irq_data.chip->irq_eoi();
</programlisting>
</para>
</sect3>
<sect3 id="EOI_Edge_IRQ_flow_handler">
<title>EOI Edge IRQ flow handler</title>
<para>
handle_edge_eoi_irq provides an abnomination of the edge
handler which is solely used to tame a badly wreckaged
irq controller on powerpc/cell.
</para>
</sect3>
<sect3 id="BAD_IRQ_flow_handler">
<title>Bad IRQ flow handler</title>
<para>
handle_bad_irq is used for spurious interrupts which
have no real handler assigned..
</para>
</sect3>
</sect2>
<sect2 id="Quirks_and_optimizations">
<title>Quirks and optimizations</title>
<para>
The generic functions are intended for 'clean' architectures and chips,
which have no platform-specific IRQ handling quirks. If an architecture
needs to implement quirks on the 'flow' level then it can do so by
overriding the high-level irq-flow handler.
</para>
</sect2>
<sect2 id="Delayed_interrupt_disable">
<title>Delayed interrupt disable</title>
<para>
This per interrupt selectable feature, which was introduced by Russell
King in the ARM interrupt implementation, does not mask an interrupt
at the hardware level when disable_irq() is called. The interrupt is
kept enabled and is masked in the flow handler when an interrupt event
happens. This prevents losing edge interrupts on hardware which does
not store an edge interrupt event while the interrupt is disabled at
the hardware level. When an interrupt arrives while the IRQ_DISABLED
flag is set, then the interrupt is masked at the hardware level and
the IRQ_PENDING bit is set. When the interrupt is re-enabled by
enable_irq() the pending bit is checked and if it is set, the
interrupt is resent either via hardware or by a software resend
mechanism. (It's necessary to enable CONFIG_HARDIRQS_SW_RESEND when
you want to use the delayed interrupt disable feature and your
hardware is not capable of retriggering an interrupt.)
The delayed interrupt disable is not configurable.
</para>
</sect2>
</sect1>
<sect1 id="Chiplevel_hardware_encapsulation">
<title>Chip-level hardware encapsulation</title>
<para>
The chip-level hardware descriptor structure irq_chip
contains all the direct chip relevant functions, which
can be utilized by the irq flow implementations.
<itemizedlist>
<listitem><para>irq_ack()</para></listitem>
<listitem><para>irq_mask_ack() - Optional, recommended for performance</para></listitem>
<listitem><para>irq_mask()</para></listitem>
<listitem><para>irq_unmask()</para></listitem>
<listitem><para>irq_eoi() - Optional, required for EOI flow handlers</para></listitem>
<listitem><para>irq_retrigger() - Optional</para></listitem>
<listitem><para>irq_set_type() - Optional</para></listitem>
<listitem><para>irq_set_wake() - Optional</para></listitem>
</itemizedlist>
These primitives are strictly intended to mean what they say: ack means
ACK, masking means masking of an IRQ line, etc. It is up to the flow
handler(s) to use these basic units of low-level functionality.
</para>
</sect1>
</chapter>
<chapter id="doirq">
<title>__do_IRQ entry point</title>
<para>
The original implementation __do_IRQ() was an alternative entry
point for all types of interrupts. It no longer exists.
</para>
<para>
This handler turned out to be not suitable for all
interrupt hardware and was therefore reimplemented with split
functionality for edge/level/simple/percpu interrupts. This is not
only a functional optimization. It also shortens code paths for
interrupts.
</para>
</chapter>
<chapter id="locking">
<title>Locking on SMP</title>
<para>
The locking of chip registers is up to the architecture that
defines the chip primitives. The per-irq structure is
protected via desc->lock, by the generic layer.
</para>
</chapter>
<chapter id="genericchip">
<title>Generic interrupt chip</title>
<para>
To avoid copies of identical implementations of IRQ chips the
core provides a configurable generic interrupt chip
implementation. Developers should check carefully whether the
generic chip fits their needs before implementing the same
functionality slightly differently themselves.
</para>
!Ekernel/irq/generic-chip.c
</chapter>
<chapter id="structs">
<title>Structures</title>
<para>
This chapter contains the autogenerated documentation of the structures which are
used in the generic IRQ layer.
</para>
!Iinclude/linux/irq.h
!Iinclude/linux/interrupt.h
</chapter>
<chapter id="pubfunctions">
<title>Public Functions Provided</title>
<para>
This chapter contains the autogenerated documentation of the kernel API functions
which are exported.
</para>
!Ekernel/irq/manage.c
!Ekernel/irq/chip.c
</chapter>
<chapter id="intfunctions">
<title>Internal Functions Provided</title>
<para>
This chapter contains the autogenerated documentation of the internal functions.
</para>
!Ikernel/irq/irqdesc.c
!Ikernel/irq/handle.c
!Ikernel/irq/chip.c
</chapter>
<chapter id="credits">
<title>Credits</title>
<para>
The following people have contributed to this document:
<orderedlist>
<listitem><para>Thomas Gleixner<email>tglx@linutronix.de</email></para></listitem>
<listitem><para>Ingo Molnar<email>mingo@elte.hu</email></para></listitem>
</orderedlist>
</para>
</chapter>
</book>

View file

@ -1,331 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
"http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" []>
<book id="LinuxKernelAPI">
<bookinfo>
<title>The Linux Kernel API</title>
<legalnotice>
<para>
This documentation is free software; you can redistribute
it and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later
version.
</para>
<para>
This program is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
</para>
<para>
You should have received a copy of the GNU General Public
License along with this program; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
</para>
<para>
For more details see the file COPYING in the source
distribution of Linux.
</para>
</legalnotice>
</bookinfo>
<toc></toc>
<chapter id="adt">
<title>Data Types</title>
<sect1><title>Doubly Linked Lists</title>
!Iinclude/linux/list.h
</sect1>
</chapter>
<chapter id="libc">
<title>Basic C Library Functions</title>
<para>
When writing drivers, you cannot in general use routines which are
from the C Library. Some of the functions have been found generally
useful and they are listed below. The behaviour of these functions
may vary slightly from those defined by ANSI, and these deviations
are noted in the text.
</para>
<sect1><title>String Conversions</title>
!Elib/vsprintf.c
!Finclude/linux/kernel.h kstrtol
!Finclude/linux/kernel.h kstrtoul
!Elib/kstrtox.c
</sect1>
<sect1><title>String Manipulation</title>
<!-- All functions are exported at now
X!Ilib/string.c
-->
!Elib/string.c
</sect1>
<sect1><title>Bit Operations</title>
!Iarch/x86/include/asm/bitops.h
</sect1>
</chapter>
<chapter id="kernel-lib">
<title>Basic Kernel Library Functions</title>
<para>
The Linux kernel provides more basic utility functions.
</para>
<sect1><title>Bitmap Operations</title>
!Elib/bitmap.c
!Ilib/bitmap.c
</sect1>
<sect1><title>Command-line Parsing</title>
!Elib/cmdline.c
</sect1>
<sect1 id="crc"><title>CRC Functions</title>
!Elib/crc7.c
!Elib/crc16.c
!Elib/crc-itu-t.c
!Elib/crc32.c
!Elib/crc-ccitt.c
</sect1>
<sect1 id="idr"><title>idr/ida Functions</title>
!Pinclude/linux/idr.h idr sync
!Plib/idr.c IDA description
!Elib/idr.c
</sect1>
</chapter>
<chapter id="mm">
<title>Memory Management in Linux</title>
<sect1><title>The Slab Cache</title>
!Iinclude/linux/slab.h
!Emm/slab.c
!Emm/util.c
</sect1>
<sect1><title>User Space Memory Access</title>
!Iarch/x86/include/asm/uaccess_32.h
!Earch/x86/lib/usercopy_32.c
</sect1>
<sect1><title>More Memory Management Functions</title>
!Emm/readahead.c
!Emm/filemap.c
!Emm/memory.c
!Emm/vmalloc.c
!Imm/page_alloc.c
!Emm/mempool.c
!Emm/dmapool.c
!Emm/page-writeback.c
!Emm/truncate.c
</sect1>
</chapter>
<chapter id="ipc">
<title>Kernel IPC facilities</title>
<sect1><title>IPC utilities</title>
!Iipc/util.c
</sect1>
</chapter>
<chapter id="kfifo">
<title>FIFO Buffer</title>
<sect1><title>kfifo interface</title>
!Iinclude/linux/kfifo.h
</sect1>
</chapter>
<chapter id="relayfs">
<title>relay interface support</title>
<para>
Relay interface support
is designed to provide an efficient mechanism for tools and
facilities to relay large amounts of data from kernel space to
user space.
</para>
<sect1><title>relay interface</title>
!Ekernel/relay.c
!Ikernel/relay.c
</sect1>
</chapter>
<chapter id="modload">
<title>Module Support</title>
<sect1><title>Module Loading</title>
!Ekernel/kmod.c
</sect1>
<sect1><title>Inter Module support</title>
<para>
Refer to the file kernel/module.c for more information.
</para>
<!-- FIXME: Removed for now since no structured comments in source
X!Ekernel/module.c
-->
</sect1>
</chapter>
<chapter id="hardware">
<title>Hardware Interfaces</title>
<sect1><title>Interrupt Handling</title>
!Ekernel/irq/manage.c
</sect1>
<sect1><title>DMA Channels</title>
!Ekernel/dma.c
</sect1>
<sect1><title>Resources Management</title>
!Ikernel/resource.c
!Ekernel/resource.c
</sect1>
<sect1><title>MTRR Handling</title>
!Earch/x86/kernel/cpu/mtrr/main.c
</sect1>
<sect1><title>PCI Support Library</title>
!Edrivers/pci/pci.c
!Edrivers/pci/pci-driver.c
!Edrivers/pci/remove.c
!Edrivers/pci/search.c
!Edrivers/pci/msi.c
!Edrivers/pci/bus.c
!Edrivers/pci/access.c
!Edrivers/pci/irq.c
!Edrivers/pci/htirq.c
<!-- FIXME: Removed for now since no structured comments in source
X!Edrivers/pci/hotplug.c
-->
!Edrivers/pci/probe.c
!Edrivers/pci/slot.c
!Edrivers/pci/rom.c
!Edrivers/pci/iov.c
!Idrivers/pci/pci-sysfs.c
</sect1>
<sect1><title>PCI Hotplug Support Library</title>
!Edrivers/pci/hotplug/pci_hotplug_core.c
</sect1>
</chapter>
<chapter id="firmware">
<title>Firmware Interfaces</title>
<sect1><title>DMI Interfaces</title>
!Edrivers/firmware/dmi_scan.c
</sect1>
<sect1><title>EDD Interfaces</title>
!Idrivers/firmware/edd.c
</sect1>
</chapter>
<chapter id="security">
<title>Security Framework</title>
!Isecurity/security.c
!Esecurity/inode.c
</chapter>
<chapter id="audit">
<title>Audit Interfaces</title>
!Ekernel/audit.c
!Ikernel/auditsc.c
!Ikernel/auditfilter.c
</chapter>
<chapter id="accounting">
<title>Accounting Framework</title>
!Ikernel/acct.c
</chapter>
<chapter id="blkdev">
<title>Block Devices</title>
!Eblock/blk-core.c
!Iblock/blk-core.c
!Eblock/blk-map.c
!Iblock/blk-sysfs.c
!Eblock/blk-settings.c
!Eblock/blk-exec.c
!Eblock/blk-flush.c
!Eblock/blk-lib.c
!Eblock/blk-tag.c
!Iblock/blk-tag.c
!Eblock/blk-integrity.c
!Ikernel/trace/blktrace.c
!Iblock/genhd.c
!Eblock/genhd.c
</chapter>
<chapter id="chrdev">
<title>Char devices</title>
!Efs/char_dev.c
</chapter>
<chapter id="miscdev">
<title>Miscellaneous Devices</title>
!Edrivers/char/misc.c
</chapter>
<chapter id="clk">
<title>Clock Framework</title>
<para>
The clock framework defines programming interfaces to support
software management of the system clock tree.
This framework is widely used with System-On-Chip (SOC) platforms
to support power management and various devices which may need
custom clock rates.
Note that these "clocks" don't relate to timekeeping or real
time clocks (RTCs), each of which have separate frameworks.
These <structname>struct clk</structname> instances may be used
to manage for example a 96 MHz signal that is used to shift bits
into and out of peripherals or busses, or otherwise trigger
synchronous state machine transitions in system hardware.
</para>
<para>
Power management is supported by explicit software clock gating:
unused clocks are disabled, so the system doesn't waste power
changing the state of transistors that aren't in active use.
On some systems this may be backed by hardware clock gating,
where clocks are gated without being disabled in software.
Sections of chips that are powered but not clocked may be able
to retain their last state.
This low power state is often called a <emphasis>retention
mode</emphasis>.
This mode still incurs leakage currents, especially with finer
circuit geometries, but for CMOS circuits power is mostly used
by clocked state changes.
</para>
<para>
Power-aware drivers only enable their clocks when the device
they manage is in active use. Also, system sleep states often
differ according to which clock domains are active: while a
"standby" state may allow wakeup from several active domains, a
"mem" (suspend-to-RAM) state may require a more wholesale shutdown
of clocks derived from higher speed PLLs and oscillators, limiting
the number of possible wakeup event sources. A driver's suspend
method may need to be aware of system-specific clock constraints
on the target sleep state.
</para>
<para>
Some platforms support programmable clock generators. These
can be used by external chips of various kinds, such as other
CPUs, multimedia codecs, and devices with strict requirements
for interface clocking.
</para>
!Iinclude/linux/clk.h
</chapter>
</book>

View file

@ -1,873 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
"http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" []>
<book id="Writing-MUSB-Glue-Layer">
<bookinfo>
<title>Writing an MUSB Glue Layer</title>
<authorgroup>
<author>
<firstname>Apelete</firstname>
<surname>Seketeli</surname>
<affiliation>
<address>
<email>apelete at seketeli.net</email>
</address>
</affiliation>
</author>
</authorgroup>
<copyright>
<year>2014</year>
<holder>Apelete Seketeli</holder>
</copyright>
<legalnotice>
<para>
This documentation is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
</para>
<para>
This documentation is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
</para>
<para>
You should have received a copy of the GNU General Public License
along with this documentation; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
</para>
<para>
For more details see the file COPYING in the Linux kernel source
tree.
</para>
</legalnotice>
</bookinfo>
<toc></toc>
<chapter id="introduction">
<title>Introduction</title>
<para>
The Linux MUSB subsystem is part of the larger Linux USB
subsystem. It provides support for embedded USB Device Controllers
(UDC) that do not use Universal Host Controller Interface (UHCI)
or Open Host Controller Interface (OHCI).
</para>
<para>
Instead, these embedded UDC rely on the USB On-the-Go (OTG)
specification which they implement at least partially. The silicon
reference design used in most cases is the Multipoint USB
Highspeed Dual-Role Controller (MUSB HDRC) found in the Mentor
Graphics Inventra™ design.
</para>
<para>
As a self-taught exercise I have written an MUSB glue layer for
the Ingenic JZ4740 SoC, modelled after the many MUSB glue layers
in the kernel source tree. This layer can be found at
drivers/usb/musb/jz4740.c. In this documentation I will walk
through the basics of the jz4740.c glue layer, explaining the
different pieces and what needs to be done in order to write your
own device glue layer.
</para>
</chapter>
<chapter id="linux-musb-basics">
<title>Linux MUSB Basics</title>
<para>
To get started on the topic, please read USB On-the-Go Basics (see
Resources) which provides an introduction of USB OTG operation at
the hardware level. A couple of wiki pages by Texas Instruments
and Analog Devices also provide an overview of the Linux kernel
MUSB configuration, albeit focused on some specific devices
provided by these companies. Finally, getting acquainted with the
USB specification at USB home page may come in handy, with
practical instance provided through the Writing USB Device Drivers
documentation (again, see Resources).
</para>
<para>
Linux USB stack is a layered architecture in which the MUSB
controller hardware sits at the lowest. The MUSB controller driver
abstract the MUSB controller hardware to the Linux USB stack.
</para>
<programlisting>
------------------------
| | &lt;------- drivers/usb/gadget
| Linux USB Core Stack | &lt;------- drivers/usb/host
| | &lt;------- drivers/usb/core
------------------------
⬍
--------------------------
| | &lt;------ drivers/usb/musb/musb_gadget.c
| MUSB Controller driver | &lt;------ drivers/usb/musb/musb_host.c
| | &lt;------ drivers/usb/musb/musb_core.c
--------------------------
⬍
---------------------------------
| MUSB Platform Specific Driver |
| | &lt;-- drivers/usb/musb/jz4740.c
| aka &quot;Glue Layer&quot; |
---------------------------------
⬍
---------------------------------
| MUSB Controller Hardware |
---------------------------------
</programlisting>
<para>
As outlined above, the glue layer is actually the platform
specific code sitting in between the controller driver and the
controller hardware.
</para>
<para>
Just like a Linux USB driver needs to register itself with the
Linux USB subsystem, the MUSB glue layer needs first to register
itself with the MUSB controller driver. This will allow the
controller driver to know about which device the glue layer
supports and which functions to call when a supported device is
detected or released; remember we are talking about an embedded
controller chip here, so no insertion or removal at run-time.
</para>
<para>
All of this information is passed to the MUSB controller driver
through a platform_driver structure defined in the glue layer as:
</para>
<programlisting linenumbering="numbered">
static struct platform_driver jz4740_driver = {
.probe = jz4740_probe,
.remove = jz4740_remove,
.driver = {
.name = "musb-jz4740",
},
};
</programlisting>
<para>
The probe and remove function pointers are called when a matching
device is detected and, respectively, released. The name string
describes the device supported by this glue layer. In the current
case it matches a platform_device structure declared in
arch/mips/jz4740/platform.c. Note that we are not using device
tree bindings here.
</para>
<para>
In order to register itself to the controller driver, the glue
layer goes through a few steps, basically allocating the
controller hardware resources and initialising a couple of
circuits. To do so, it needs to keep track of the information used
throughout these steps. This is done by defining a private
jz4740_glue structure:
</para>
<programlisting linenumbering="numbered">
struct jz4740_glue {
struct device *dev;
struct platform_device *musb;
struct clk *clk;
};
</programlisting>
<para>
The dev and musb members are both device structure variables. The
first one holds generic information about the device, since it's
the basic device structure, and the latter holds information more
closely related to the subsystem the device is registered to. The
clk variable keeps information related to the device clock
operation.
</para>
<para>
Let's go through the steps of the probe function that leads the
glue layer to register itself to the controller driver.
</para>
<para>
N.B.: For the sake of readability each function will be split in
logical parts, each part being shown as if it was independent from
the others.
</para>
<programlisting linenumbering="numbered">
static int jz4740_probe(struct platform_device *pdev)
{
struct platform_device *musb;
struct jz4740_glue *glue;
struct clk *clk;
int ret;
glue = devm_kzalloc(&amp;pdev->dev, sizeof(*glue), GFP_KERNEL);
if (!glue)
return -ENOMEM;
musb = platform_device_alloc("musb-hdrc", PLATFORM_DEVID_AUTO);
if (!musb) {
dev_err(&amp;pdev->dev, "failed to allocate musb device\n");
return -ENOMEM;
}
clk = devm_clk_get(&amp;pdev->dev, "udc");
if (IS_ERR(clk)) {
dev_err(&amp;pdev->dev, "failed to get clock\n");
ret = PTR_ERR(clk);
goto err_platform_device_put;
}
ret = clk_prepare_enable(clk);
if (ret) {
dev_err(&amp;pdev->dev, "failed to enable clock\n");
goto err_platform_device_put;
}
musb->dev.parent = &amp;pdev->dev;
glue->dev = &amp;pdev->dev;
glue->musb = musb;
glue->clk = clk;
return 0;
err_platform_device_put:
platform_device_put(musb);
return ret;
}
</programlisting>
<para>
The first few lines of the probe function allocate and assign the
glue, musb and clk variables. The GFP_KERNEL flag (line 8) allows
the allocation process to sleep and wait for memory, thus being
usable in a blocking situation. The PLATFORM_DEVID_AUTO flag (line
12) allows automatic allocation and management of device IDs in
order to avoid device namespace collisions with explicit IDs. With
devm_clk_get() (line 18) the glue layer allocates the clock -- the
<literal>devm_</literal> prefix indicates that clk_get() is
managed: it automatically frees the allocated clock resource data
when the device is released -- and enable it.
</para>
<para>
Then comes the registration steps:
</para>
<programlisting linenumbering="numbered">
static int jz4740_probe(struct platform_device *pdev)
{
struct musb_hdrc_platform_data *pdata = &amp;jz4740_musb_platform_data;
pdata->platform_ops = &amp;jz4740_musb_ops;
platform_set_drvdata(pdev, glue);
ret = platform_device_add_resources(musb, pdev->resource,
pdev->num_resources);
if (ret) {
dev_err(&amp;pdev->dev, "failed to add resources\n");
goto err_clk_disable;
}
ret = platform_device_add_data(musb, pdata, sizeof(*pdata));
if (ret) {
dev_err(&amp;pdev->dev, "failed to add platform_data\n");
goto err_clk_disable;
}
return 0;
err_clk_disable:
clk_disable_unprepare(clk);
err_platform_device_put:
platform_device_put(musb);
return ret;
}
</programlisting>
<para>
The first step is to pass the device data privately held by the
glue layer on to the controller driver through
platform_set_drvdata() (line 7). Next is passing on the device
resources information, also privately held at that point, through
platform_device_add_resources() (line 9).
</para>
<para>
Finally comes passing on the platform specific data to the
controller driver (line 16). Platform data will be discussed in
<link linkend="device-platform-data">Chapter 4</link>, but here
we are looking at the platform_ops function pointer (line 5) in
musb_hdrc_platform_data structure (line 3). This function
pointer allows the MUSB controller driver to know which function
to call for device operation:
</para>
<programlisting linenumbering="numbered">
static const struct musb_platform_ops jz4740_musb_ops = {
.init = jz4740_musb_init,
.exit = jz4740_musb_exit,
};
</programlisting>
<para>
Here we have the minimal case where only init and exit functions
are called by the controller driver when needed. Fact is the
JZ4740 MUSB controller is a basic controller, lacking some
features found in other controllers, otherwise we may also have
pointers to a few other functions like a power management function
or a function to switch between OTG and non-OTG modes, for
instance.
</para>
<para>
At that point of the registration process, the controller driver
actually calls the init function:
</para>
<programlisting linenumbering="numbered">
static int jz4740_musb_init(struct musb *musb)
{
musb->xceiv = usb_get_phy(USB_PHY_TYPE_USB2);
if (!musb->xceiv) {
pr_err("HS UDC: no transceiver configured\n");
return -ENODEV;
}
/* Silicon does not implement ConfigData register.
* Set dyn_fifo to avoid reading EP config from hardware.
*/
musb->dyn_fifo = true;
musb->isr = jz4740_musb_interrupt;
return 0;
}
</programlisting>
<para>
The goal of jz4740_musb_init() is to get hold of the transceiver
driver data of the MUSB controller hardware and pass it on to the
MUSB controller driver, as usual. The transceiver is the circuitry
inside the controller hardware responsible for sending/receiving
the USB data. Since it is an implementation of the physical layer
of the OSI model, the transceiver is also referred to as PHY.
</para>
<para>
Getting hold of the MUSB PHY driver data is done with
usb_get_phy() which returns a pointer to the structure
containing the driver instance data. The next couple of
instructions (line 12 and 14) are used as a quirk and to setup
IRQ handling respectively. Quirks and IRQ handling will be
discussed later in <link linkend="device-quirks">Chapter
5</link> and <link linkend="handling-irqs">Chapter 3</link>.
</para>
<programlisting linenumbering="numbered">
static int jz4740_musb_exit(struct musb *musb)
{
usb_put_phy(musb->xceiv);
return 0;
}
</programlisting>
<para>
Acting as the counterpart of init, the exit function releases the
MUSB PHY driver when the controller hardware itself is about to be
released.
</para>
<para>
Again, note that init and exit are fairly simple in this case due
to the basic set of features of the JZ4740 controller hardware.
When writing an musb glue layer for a more complex controller
hardware, you might need to take care of more processing in those
two functions.
</para>
<para>
Returning from the init function, the MUSB controller driver jumps
back into the probe function:
</para>
<programlisting linenumbering="numbered">
static int jz4740_probe(struct platform_device *pdev)
{
ret = platform_device_add(musb);
if (ret) {
dev_err(&amp;pdev->dev, "failed to register musb device\n");
goto err_clk_disable;
}
return 0;
err_clk_disable:
clk_disable_unprepare(clk);
err_platform_device_put:
platform_device_put(musb);
return ret;
}
</programlisting>
<para>
This is the last part of the device registration process where the
glue layer adds the controller hardware device to Linux kernel
device hierarchy: at this stage, all known information about the
device is passed on to the Linux USB core stack.
</para>
<programlisting linenumbering="numbered">
static int jz4740_remove(struct platform_device *pdev)
{
struct jz4740_glue *glue = platform_get_drvdata(pdev);
platform_device_unregister(glue->musb);
clk_disable_unprepare(glue->clk);
return 0;
}
</programlisting>
<para>
Acting as the counterpart of probe, the remove function unregister
the MUSB controller hardware (line 5) and disable the clock (line
6), allowing it to be gated.
</para>
</chapter>
<chapter id="handling-irqs">
<title>Handling IRQs</title>
<para>
Additionally to the MUSB controller hardware basic setup and
registration, the glue layer is also responsible for handling the
IRQs:
</para>
<programlisting linenumbering="numbered">
static irqreturn_t jz4740_musb_interrupt(int irq, void *__hci)
{
unsigned long flags;
irqreturn_t retval = IRQ_NONE;
struct musb *musb = __hci;
spin_lock_irqsave(&amp;musb->lock, flags);
musb->int_usb = musb_readb(musb->mregs, MUSB_INTRUSB);
musb->int_tx = musb_readw(musb->mregs, MUSB_INTRTX);
musb->int_rx = musb_readw(musb->mregs, MUSB_INTRRX);
/*
* The controller is gadget only, the state of the host mode IRQ bits is
* undefined. Mask them to make sure that the musb driver core will
* never see them set
*/
musb->int_usb &amp;= MUSB_INTR_SUSPEND | MUSB_INTR_RESUME |
MUSB_INTR_RESET | MUSB_INTR_SOF;
if (musb->int_usb || musb->int_tx || musb->int_rx)
retval = musb_interrupt(musb);
spin_unlock_irqrestore(&amp;musb->lock, flags);
return retval;
}
</programlisting>
<para>
Here the glue layer mostly has to read the relevant hardware
registers and pass their values on to the controller driver which
will handle the actual event that triggered the IRQ.
</para>
<para>
The interrupt handler critical section is protected by the
spin_lock_irqsave() and counterpart spin_unlock_irqrestore()
functions (line 7 and 24 respectively), which prevent the
interrupt handler code to be run by two different threads at the
same time.
</para>
<para>
Then the relevant interrupt registers are read (line 9 to 11):
</para>
<itemizedlist>
<listitem>
<para>
MUSB_INTRUSB: indicates which USB interrupts are currently
active,
</para>
</listitem>
<listitem>
<para>
MUSB_INTRTX: indicates which of the interrupts for TX
endpoints are currently active,
</para>
</listitem>
<listitem>
<para>
MUSB_INTRRX: indicates which of the interrupts for TX
endpoints are currently active.
</para>
</listitem>
</itemizedlist>
<para>
Note that musb_readb() is used to read 8-bit registers at most,
while musb_readw() allows us to read at most 16-bit registers.
There are other functions that can be used depending on the size
of your device registers. See musb_io.h for more information.
</para>
<para>
Instruction on line 18 is another quirk specific to the JZ4740
USB device controller, which will be discussed later in <link
linkend="device-quirks">Chapter 5</link>.
</para>
<para>
The glue layer still needs to register the IRQ handler though.
Remember the instruction on line 14 of the init function:
</para>
<programlisting linenumbering="numbered">
static int jz4740_musb_init(struct musb *musb)
{
musb->isr = jz4740_musb_interrupt;
return 0;
}
</programlisting>
<para>
This instruction sets a pointer to the glue layer IRQ handler
function, in order for the controller hardware to call the handler
back when an IRQ comes from the controller hardware. The interrupt
handler is now implemented and registered.
</para>
</chapter>
<chapter id="device-platform-data">
<title>Device Platform Data</title>
<para>
In order to write an MUSB glue layer, you need to have some data
describing the hardware capabilities of your controller hardware,
which is called the platform data.
</para>
<para>
Platform data is specific to your hardware, though it may cover a
broad range of devices, and is generally found somewhere in the
arch/ directory, depending on your device architecture.
</para>
<para>
For instance, platform data for the JZ4740 SoC is found in
arch/mips/jz4740/platform.c. In the platform.c file each device of
the JZ4740 SoC is described through a set of structures.
</para>
<para>
Here is the part of arch/mips/jz4740/platform.c that covers the
USB Device Controller (UDC):
</para>
<programlisting linenumbering="numbered">
/* USB Device Controller */
struct platform_device jz4740_udc_xceiv_device = {
.name = "usb_phy_gen_xceiv",
.id = 0,
};
static struct resource jz4740_udc_resources[] = {
[0] = {
.start = JZ4740_UDC_BASE_ADDR,
.end = JZ4740_UDC_BASE_ADDR + 0x10000 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = JZ4740_IRQ_UDC,
.end = JZ4740_IRQ_UDC,
.flags = IORESOURCE_IRQ,
.name = "mc",
},
};
struct platform_device jz4740_udc_device = {
.name = "musb-jz4740",
.id = -1,
.dev = {
.dma_mask = &amp;jz4740_udc_device.dev.coherent_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.num_resources = ARRAY_SIZE(jz4740_udc_resources),
.resource = jz4740_udc_resources,
};
</programlisting>
<para>
The jz4740_udc_xceiv_device platform device structure (line 2)
describes the UDC transceiver with a name and id number.
</para>
<para>
At the time of this writing, note that
&quot;usb_phy_gen_xceiv&quot; is the specific name to be used for
all transceivers that are either built-in with reference USB IP or
autonomous and doesn't require any PHY programming. You will need
to set CONFIG_NOP_USB_XCEIV=y in the kernel configuration to make
use of the corresponding transceiver driver. The id field could be
set to -1 (equivalent to PLATFORM_DEVID_NONE), -2 (equivalent to
PLATFORM_DEVID_AUTO) or start with 0 for the first device of this
kind if we want a specific id number.
</para>
<para>
The jz4740_udc_resources resource structure (line 7) defines the
UDC registers base addresses.
</para>
<para>
The first array (line 9 to 11) defines the UDC registers base
memory addresses: start points to the first register memory
address, end points to the last register memory address and the
flags member defines the type of resource we are dealing with. So
IORESOURCE_MEM is used to define the registers memory addresses.
The second array (line 14 to 17) defines the UDC IRQ registers
addresses. Since there is only one IRQ register available for the
JZ4740 UDC, start and end point at the same address. The
IORESOURCE_IRQ flag tells that we are dealing with IRQ resources,
and the name &quot;mc&quot; is in fact hard-coded in the MUSB core
in order for the controller driver to retrieve this IRQ resource
by querying it by its name.
</para>
<para>
Finally, the jz4740_udc_device platform device structure (line 21)
describes the UDC itself.
</para>
<para>
The &quot;musb-jz4740&quot; name (line 22) defines the MUSB
driver that is used for this device; remember this is in fact
the name that we used in the jz4740_driver platform driver
structure in <link linkend="linux-musb-basics">Chapter
2</link>. The id field (line 23) is set to -1 (equivalent to
PLATFORM_DEVID_NONE) since we do not need an id for the device:
the MUSB controller driver was already set to allocate an
automatic id in <link linkend="linux-musb-basics">Chapter
2</link>. In the dev field we care for DMA related information
here. The dma_mask field (line 25) defines the width of the DMA
mask that is going to be used, and coherent_dma_mask (line 26)
has the same purpose but for the alloc_coherent DMA mappings: in
both cases we are using a 32 bits mask. Then the resource field
(line 29) is simply a pointer to the resource structure defined
before, while the num_resources field (line 28) keeps track of
the number of arrays defined in the resource structure (in this
case there were two resource arrays defined before).
</para>
<para>
With this quick overview of the UDC platform data at the arch/
level now done, let's get back to the MUSB glue layer specific
platform data in drivers/usb/musb/jz4740.c:
</para>
<programlisting linenumbering="numbered">
static struct musb_hdrc_config jz4740_musb_config = {
/* Silicon does not implement USB OTG. */
.multipoint = 0,
/* Max EPs scanned, driver will decide which EP can be used. */
.num_eps = 4,
/* RAMbits needed to configure EPs from table */
.ram_bits = 9,
.fifo_cfg = jz4740_musb_fifo_cfg,
.fifo_cfg_size = ARRAY_SIZE(jz4740_musb_fifo_cfg),
};
static struct musb_hdrc_platform_data jz4740_musb_platform_data = {
.mode = MUSB_PERIPHERAL,
.config = &amp;jz4740_musb_config,
};
</programlisting>
<para>
First the glue layer configures some aspects of the controller
driver operation related to the controller hardware specifics.
This is done through the jz4740_musb_config musb_hdrc_config
structure.
</para>
<para>
Defining the OTG capability of the controller hardware, the
multipoint member (line 3) is set to 0 (equivalent to false)
since the JZ4740 UDC is not OTG compatible. Then num_eps (line
5) defines the number of USB endpoints of the controller
hardware, including endpoint 0: here we have 3 endpoints +
endpoint 0. Next is ram_bits (line 7) which is the width of the
RAM address bus for the MUSB controller hardware. This
information is needed when the controller driver cannot
automatically configure endpoints by reading the relevant
controller hardware registers. This issue will be discussed when
we get to device quirks in <link linkend="device-quirks">Chapter
5</link>. Last two fields (line 8 and 9) are also about device
quirks: fifo_cfg points to the USB endpoints configuration table
and fifo_cfg_size keeps track of the size of the number of
entries in that configuration table. More on that later in <link
linkend="device-quirks">Chapter 5</link>.
</para>
<para>
Then this configuration is embedded inside
jz4740_musb_platform_data musb_hdrc_platform_data structure (line
11): config is a pointer to the configuration structure itself,
and mode tells the controller driver if the controller hardware
may be used as MUSB_HOST only, MUSB_PERIPHERAL only or MUSB_OTG
which is a dual mode.
</para>
<para>
Remember that jz4740_musb_platform_data is then used to convey
platform data information as we have seen in the probe function
in <link linkend="linux-musb-basics">Chapter 2</link>
</para>
</chapter>
<chapter id="device-quirks">
<title>Device Quirks</title>
<para>
Completing the platform data specific to your device, you may also
need to write some code in the glue layer to work around some
device specific limitations. These quirks may be due to some
hardware bugs, or simply be the result of an incomplete
implementation of the USB On-the-Go specification.
</para>
<para>
The JZ4740 UDC exhibits such quirks, some of which we will discuss
here for the sake of insight even though these might not be found
in the controller hardware you are working on.
</para>
<para>
Let's get back to the init function first:
</para>
<programlisting linenumbering="numbered">
static int jz4740_musb_init(struct musb *musb)
{
musb->xceiv = usb_get_phy(USB_PHY_TYPE_USB2);
if (!musb->xceiv) {
pr_err("HS UDC: no transceiver configured\n");
return -ENODEV;
}
/* Silicon does not implement ConfigData register.
* Set dyn_fifo to avoid reading EP config from hardware.
*/
musb->dyn_fifo = true;
musb->isr = jz4740_musb_interrupt;
return 0;
}
</programlisting>
<para>
Instruction on line 12 helps the MUSB controller driver to work
around the fact that the controller hardware is missing registers
that are used for USB endpoints configuration.
</para>
<para>
Without these registers, the controller driver is unable to read
the endpoints configuration from the hardware, so we use line 12
instruction to bypass reading the configuration from silicon, and
rely on a hard-coded table that describes the endpoints
configuration instead:
</para>
<programlisting linenumbering="numbered">
static struct musb_fifo_cfg jz4740_musb_fifo_cfg[] = {
{ .hw_ep_num = 1, .style = FIFO_TX, .maxpacket = 512, },
{ .hw_ep_num = 1, .style = FIFO_RX, .maxpacket = 512, },
{ .hw_ep_num = 2, .style = FIFO_TX, .maxpacket = 64, },
};
</programlisting>
<para>
Looking at the configuration table above, we see that each
endpoints is described by three fields: hw_ep_num is the endpoint
number, style is its direction (either FIFO_TX for the controller
driver to send packets in the controller hardware, or FIFO_RX to
receive packets from hardware), and maxpacket defines the maximum
size of each data packet that can be transmitted over that
endpoint. Reading from the table, the controller driver knows that
endpoint 1 can be used to send and receive USB data packets of 512
bytes at once (this is in fact a bulk in/out endpoint), and
endpoint 2 can be used to send data packets of 64 bytes at once
(this is in fact an interrupt endpoint).
</para>
<para>
Note that there is no information about endpoint 0 here: that one
is implemented by default in every silicon design, with a
predefined configuration according to the USB specification. For
more examples of endpoint configuration tables, see musb_core.c.
</para>
<para>
Let's now get back to the interrupt handler function:
</para>
<programlisting linenumbering="numbered">
static irqreturn_t jz4740_musb_interrupt(int irq, void *__hci)
{
unsigned long flags;
irqreturn_t retval = IRQ_NONE;
struct musb *musb = __hci;
spin_lock_irqsave(&amp;musb->lock, flags);
musb->int_usb = musb_readb(musb->mregs, MUSB_INTRUSB);
musb->int_tx = musb_readw(musb->mregs, MUSB_INTRTX);
musb->int_rx = musb_readw(musb->mregs, MUSB_INTRRX);
/*
* The controller is gadget only, the state of the host mode IRQ bits is
* undefined. Mask them to make sure that the musb driver core will
* never see them set
*/
musb->int_usb &amp;= MUSB_INTR_SUSPEND | MUSB_INTR_RESUME |
MUSB_INTR_RESET | MUSB_INTR_SOF;
if (musb->int_usb || musb->int_tx || musb->int_rx)
retval = musb_interrupt(musb);
spin_unlock_irqrestore(&amp;musb->lock, flags);
return retval;
}
</programlisting>
<para>
Instruction on line 18 above is a way for the controller driver to
work around the fact that some interrupt bits used for USB host
mode operation are missing in the MUSB_INTRUSB register, thus left
in an undefined hardware state, since this MUSB controller
hardware is used in peripheral mode only. As a consequence, the
glue layer masks these missing bits out to avoid parasite
interrupts by doing a logical AND operation between the value read
from MUSB_INTRUSB and the bits that are actually implemented in
the register.
</para>
<para>
These are only a couple of the quirks found in the JZ4740 USB
device controller. Some others were directly addressed in the MUSB
core since the fixes were generic enough to provide a better
handling of the issues for others controller hardware eventually.
</para>
</chapter>
<chapter id="conclusion">
<title>Conclusion</title>
<para>
Writing a Linux MUSB glue layer should be a more accessible task,
as this documentation tries to show the ins and outs of this
exercise.
</para>
<para>
The JZ4740 USB device controller being fairly simple, I hope its
glue layer serves as a good example for the curious mind. Used
with the current MUSB glue layers, this documentation should
provide enough guidance to get started; should anything gets out
of hand, the linux-usb mailing list archive is another helpful
resource to browse through.
</para>
</chapter>
<chapter id="acknowledgements">
<title>Acknowledgements</title>
<para>
Many thanks to Lars-Peter Clausen and Maarten ter Huurne for
answering my questions while I was writing the JZ4740 glue layer
and for helping me out getting the code in good shape.
</para>
<para>
I would also like to thank the Qi-Hardware community at large for
its cheerful guidance and support.
</para>
</chapter>
<chapter id="resources">
<title>Resources</title>
<para>
USB Home Page:
<ulink url="http://www.usb.org">http://www.usb.org</ulink>
</para>
<para>
linux-usb Mailing List Archives:
<ulink url="http://marc.info/?l=linux-usb">http://marc.info/?l=linux-usb</ulink>
</para>
<para>
USB On-the-Go Basics:
<ulink url="http://www.maximintegrated.com/app-notes/index.mvp/id/1822">http://www.maximintegrated.com/app-notes/index.mvp/id/1822</ulink>
</para>
<para>
Writing USB Device Drivers:
<ulink url="https://www.kernel.org/doc/htmldocs/writing_usb_driver/index.html">https://www.kernel.org/doc/htmldocs/writing_usb_driver/index.html</ulink>
</para>
<para>
Texas Instruments USB Configuration Wiki Page:
<ulink url="http://processors.wiki.ti.com/index.php/Usbgeneralpage">http://processors.wiki.ti.com/index.php/Usbgeneralpage</ulink>
</para>
<para>
Analog Devices Blackfin MUSB Configuration:
<ulink url="http://docs.blackfin.uclinux.org/doku.php?id=linux-kernel:drivers:musb">http://docs.blackfin.uclinux.org/doku.php?id=linux-kernel:drivers:musb</ulink>
</para>
</chapter>
</book>

View file

@ -1,412 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
"http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" []>
<book id="USBDeviceDriver">
<bookinfo>
<title>Writing USB Device Drivers</title>
<authorgroup>
<author>
<firstname>Greg</firstname>
<surname>Kroah-Hartman</surname>
<affiliation>
<address>
<email>greg@kroah.com</email>
</address>
</affiliation>
</author>
</authorgroup>
<copyright>
<year>2001-2002</year>
<holder>Greg Kroah-Hartman</holder>
</copyright>
<legalnotice>
<para>
This documentation is free software; you can redistribute
it and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later
version.
</para>
<para>
This program is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
</para>
<para>
You should have received a copy of the GNU General Public
License along with this program; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
</para>
<para>
For more details see the file COPYING in the source
distribution of Linux.
</para>
<para>
This documentation is based on an article published in
Linux Journal Magazine, October 2001, Issue 90.
</para>
</legalnotice>
</bookinfo>
<toc></toc>
<chapter id="intro">
<title>Introduction</title>
<para>
The Linux USB subsystem has grown from supporting only two different
types of devices in the 2.2.7 kernel (mice and keyboards), to over 20
different types of devices in the 2.4 kernel. Linux currently supports
almost all USB class devices (standard types of devices like keyboards,
mice, modems, printers and speakers) and an ever-growing number of
vendor-specific devices (such as USB to serial converters, digital
cameras, Ethernet devices and MP3 players). For a full list of the
different USB devices currently supported, see Resources.
</para>
<para>
The remaining kinds of USB devices that do not have support on Linux are
almost all vendor-specific devices. Each vendor decides to implement a
custom protocol to talk to their device, so a custom driver usually needs
to be created. Some vendors are open with their USB protocols and help
with the creation of Linux drivers, while others do not publish them, and
developers are forced to reverse-engineer. See Resources for some links
to handy reverse-engineering tools.
</para>
<para>
Because each different protocol causes a new driver to be created, I have
written a generic USB driver skeleton, modelled after the pci-skeleton.c
file in the kernel source tree upon which many PCI network drivers have
been based. This USB skeleton can be found at drivers/usb/usb-skeleton.c
in the kernel source tree. In this article I will walk through the basics
of the skeleton driver, explaining the different pieces and what needs to
be done to customize it to your specific device.
</para>
</chapter>
<chapter id="basics">
<title>Linux USB Basics</title>
<para>
If you are going to write a Linux USB driver, please become familiar with
the USB protocol specification. It can be found, along with many other
useful documents, at the USB home page (see Resources). An excellent
introduction to the Linux USB subsystem can be found at the USB Working
Devices List (see Resources). It explains how the Linux USB subsystem is
structured and introduces the reader to the concept of USB urbs
(USB Request Blocks), which are essential to USB drivers.
</para>
<para>
The first thing a Linux USB driver needs to do is register itself with
the Linux USB subsystem, giving it some information about which devices
the driver supports and which functions to call when a device supported
by the driver is inserted or removed from the system. All of this
information is passed to the USB subsystem in the usb_driver structure.
The skeleton driver declares a usb_driver as:
</para>
<programlisting>
static struct usb_driver skel_driver = {
.name = "skeleton",
.probe = skel_probe,
.disconnect = skel_disconnect,
.fops = &amp;skel_fops,
.minor = USB_SKEL_MINOR_BASE,
.id_table = skel_table,
};
</programlisting>
<para>
The variable name is a string that describes the driver. It is used in
informational messages printed to the system log. The probe and
disconnect function pointers are called when a device that matches the
information provided in the id_table variable is either seen or removed.
</para>
<para>
The fops and minor variables are optional. Most USB drivers hook into
another kernel subsystem, such as the SCSI, network or TTY subsystem.
These types of drivers register themselves with the other kernel
subsystem, and any user-space interactions are provided through that
interface. But for drivers that do not have a matching kernel subsystem,
such as MP3 players or scanners, a method of interacting with user space
is needed. The USB subsystem provides a way to register a minor device
number and a set of file_operations function pointers that enable this
user-space interaction. The skeleton driver needs this kind of interface,
so it provides a minor starting number and a pointer to its
file_operations functions.
</para>
<para>
The USB driver is then registered with a call to usb_register, usually in
the driver's init function, as shown here:
</para>
<programlisting>
static int __init usb_skel_init(void)
{
int result;
/* register this driver with the USB subsystem */
result = usb_register(&amp;skel_driver);
if (result &lt; 0) {
err(&quot;usb_register failed for the &quot;__FILE__ &quot;driver.&quot;
&quot;Error number %d&quot;, result);
return -1;
}
return 0;
}
module_init(usb_skel_init);
</programlisting>
<para>
When the driver is unloaded from the system, it needs to deregister
itself with the USB subsystem. This is done with the usb_deregister
function:
</para>
<programlisting>
static void __exit usb_skel_exit(void)
{
/* deregister this driver with the USB subsystem */
usb_deregister(&amp;skel_driver);
}
module_exit(usb_skel_exit);
</programlisting>
<para>
To enable the linux-hotplug system to load the driver automatically when
the device is plugged in, you need to create a MODULE_DEVICE_TABLE. The
following code tells the hotplug scripts that this module supports a
single device with a specific vendor and product ID:
</para>
<programlisting>
/* table of devices that work with this driver */
static struct usb_device_id skel_table [] = {
{ USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, skel_table);
</programlisting>
<para>
There are other macros that can be used in describing a usb_device_id for
drivers that support a whole class of USB drivers. See usb.h for more
information on this.
</para>
</chapter>
<chapter id="device">
<title>Device operation</title>
<para>
When a device is plugged into the USB bus that matches the device ID
pattern that your driver registered with the USB core, the probe function
is called. The usb_device structure, interface number and the interface ID
are passed to the function:
</para>
<programlisting>
static int skel_probe(struct usb_interface *interface,
const struct usb_device_id *id)
</programlisting>
<para>
The driver now needs to verify that this device is actually one that it
can accept. If so, it returns 0.
If not, or if any error occurs during initialization, an errorcode
(such as <literal>-ENOMEM</literal> or <literal>-ENODEV</literal>)
is returned from the probe function.
</para>
<para>
In the skeleton driver, we determine what end points are marked as bulk-in
and bulk-out. We create buffers to hold the data that will be sent and
received from the device, and a USB urb to write data to the device is
initialized.
</para>
<para>
Conversely, when the device is removed from the USB bus, the disconnect
function is called with the device pointer. The driver needs to clean any
private data that has been allocated at this time and to shut down any
pending urbs that are in the USB system.
</para>
<para>
Now that the device is plugged into the system and the driver is bound to
the device, any of the functions in the file_operations structure that
were passed to the USB subsystem will be called from a user program trying
to talk to the device. The first function called will be open, as the
program tries to open the device for I/O. We increment our private usage
count and save a pointer to our internal structure in the file
structure. This is done so that future calls to file operations will
enable the driver to determine which device the user is addressing. All
of this is done with the following code:
</para>
<programlisting>
/* increment our usage count for the module */
++skel->open_count;
/* save our object in the file's private structure */
file->private_data = dev;
</programlisting>
<para>
After the open function is called, the read and write functions are called
to receive and send data to the device. In the skel_write function, we
receive a pointer to some data that the user wants to send to the device
and the size of the data. The function determines how much data it can
send to the device based on the size of the write urb it has created (this
size depends on the size of the bulk out end point that the device has).
Then it copies the data from user space to kernel space, points the urb to
the data and submits the urb to the USB subsystem. This can be seen in
the following code:
</para>
<programlisting>
/* we can only write as much as 1 urb will hold */
bytes_written = (count > skel->bulk_out_size) ? skel->bulk_out_size : count;
/* copy the data from user space into our urb */
copy_from_user(skel->write_urb->transfer_buffer, buffer, bytes_written);
/* set up our urb */
usb_fill_bulk_urb(skel->write_urb,
skel->dev,
usb_sndbulkpipe(skel->dev, skel->bulk_out_endpointAddr),
skel->write_urb->transfer_buffer,
bytes_written,
skel_write_bulk_callback,
skel);
/* send the data out the bulk port */
result = usb_submit_urb(skel->write_urb);
if (result) {
err(&quot;Failed submitting write urb, error %d&quot;, result);
}
</programlisting>
<para>
When the write urb is filled up with the proper information using the
usb_fill_bulk_urb function, we point the urb's completion callback to call our
own skel_write_bulk_callback function. This function is called when the
urb is finished by the USB subsystem. The callback function is called in
interrupt context, so caution must be taken not to do very much processing
at that time. Our implementation of skel_write_bulk_callback merely
reports if the urb was completed successfully or not and then returns.
</para>
<para>
The read function works a bit differently from the write function in that
we do not use an urb to transfer data from the device to the driver.
Instead we call the usb_bulk_msg function, which can be used to send or
receive data from a device without having to create urbs and handle
urb completion callback functions. We call the usb_bulk_msg function,
giving it a buffer into which to place any data received from the device
and a timeout value. If the timeout period expires without receiving any
data from the device, the function will fail and return an error message.
This can be shown with the following code:
</para>
<programlisting>
/* do an immediate bulk read to get data from the device */
retval = usb_bulk_msg (skel->dev,
usb_rcvbulkpipe (skel->dev,
skel->bulk_in_endpointAddr),
skel->bulk_in_buffer,
skel->bulk_in_size,
&amp;count, HZ*10);
/* if the read was successful, copy the data to user space */
if (!retval) {
if (copy_to_user (buffer, skel->bulk_in_buffer, count))
retval = -EFAULT;
else
retval = count;
}
</programlisting>
<para>
The usb_bulk_msg function can be very useful for doing single reads or
writes to a device; however, if you need to read or write constantly to a
device, it is recommended to set up your own urbs and submit them to the
USB subsystem.
</para>
<para>
When the user program releases the file handle that it has been using to
talk to the device, the release function in the driver is called. In this
function we decrement our private usage count and wait for possible
pending writes:
</para>
<programlisting>
/* decrement our usage count for the device */
--skel->open_count;
</programlisting>
<para>
One of the more difficult problems that USB drivers must be able to handle
smoothly is the fact that the USB device may be removed from the system at
any point in time, even if a program is currently talking to it. It needs
to be able to shut down any current reads and writes and notify the
user-space programs that the device is no longer there. The following
code (function <function>skel_delete</function>)
is an example of how to do this: </para>
<programlisting>
static inline void skel_delete (struct usb_skel *dev)
{
kfree (dev->bulk_in_buffer);
if (dev->bulk_out_buffer != NULL)
usb_free_coherent (dev->udev, dev->bulk_out_size,
dev->bulk_out_buffer,
dev->write_urb->transfer_dma);
usb_free_urb (dev->write_urb);
kfree (dev);
}
</programlisting>
<para>
If a program currently has an open handle to the device, we reset the flag
<literal>device_present</literal>. For
every read, write, release and other functions that expect a device to be
present, the driver first checks this flag to see if the device is
still present. If not, it releases that the device has disappeared, and a
-ENODEV error is returned to the user-space program. When the release
function is eventually called, it determines if there is no device
and if not, it does the cleanup that the skel_disconnect
function normally does if there are no open files on the device (see
Listing 5).
</para>
</chapter>
<chapter id="iso">
<title>Isochronous Data</title>
<para>
This usb-skeleton driver does not have any examples of interrupt or
isochronous data being sent to or from the device. Interrupt data is sent
almost exactly as bulk data is, with a few minor exceptions. Isochronous
data works differently with continuous streams of data being sent to or
from the device. The audio and video camera drivers are very good examples
of drivers that handle isochronous data and will be useful if you also
need to do this.
</para>
</chapter>
<chapter id="Conclusion">
<title>Conclusion</title>
<para>
Writing Linux USB device drivers is not a difficult task as the
usb-skeleton driver shows. This driver, combined with the other current
USB drivers, should provide enough examples to help a beginning author
create a working driver in a minimal amount of time. The linux-usb-devel
mailing list archives also contain a lot of helpful information.
</para>
</chapter>
<chapter id="resources">
<title>Resources</title>
<para>
The Linux USB Project: <ulink url="http://www.linux-usb.org">http://www.linux-usb.org/</ulink>
</para>
<para>
Linux Hotplug Project: <ulink url="http://linux-hotplug.sourceforge.net">http://linux-hotplug.sourceforge.net/</ulink>
</para>
<para>
Linux USB Working Devices List: <ulink url="http://www.qbik.ch/usb/devices">http://www.qbik.ch/usb/devices/</ulink>
</para>
<para>
linux-usb-devel Mailing List Archives: <ulink url="http://marc.theaimsgroup.com/?l=linux-usb-devel">http://marc.theaimsgroup.com/?l=linux-usb-devel</ulink>
</para>
<para>
Programming Guide for Linux USB Device Drivers: <ulink url="http://usb.cs.tum.edu/usbdoc">http://usb.cs.tum.edu/usbdoc</ulink>
</para>
<para>
USB Home Page: <ulink url="http://www.usb.org">http://www.usb.org</ulink>
</para>
</chapter>
</book>

View file

@ -11,7 +11,7 @@
Many PCI bus controllers are able to detect a variety of hardware
PCI errors on the bus, such as parity errors on the data and address
busses, as well as SERR and PERR errors. Some of the more advanced
buses, as well as SERR and PERR errors. Some of the more advanced
chipsets are able to deal with these errors; these include PCI-E chipsets,
and the PCI-host bridges found on IBM Power4, Power5 and Power6-based
pSeries boxes. A typical action taken is to disconnect the affected device,
@ -173,7 +173,7 @@ is STEP 6 (Permanent Failure).
>>> a value of 0xff on read, and writes will be dropped. If more than
>>> EEH_MAX_FAILS I/O's are attempted to a frozen adapter, EEH
>>> assumes that the device driver has gone into an infinite loop
>>> and prints an error to syslog. A reboot is then required to
>>> and prints an error to syslog. A reboot is then required to
>>> get the device working again.
STEP 2: MMIO Enabled
@ -231,14 +231,14 @@ proceeds to STEP 4 (Slot Reset)
STEP 3: Link Reset
------------------
The platform resets the link. This is a PCI-Express specific step
and is done whenever a non-fatal error has been detected that can be
and is done whenever a fatal error has been detected that can be
"solved" by resetting the link.
STEP 4: Slot Reset
------------------
In response to a return value of PCI_ERS_RESULT_NEED_RESET, the
the platform will perform a slot reset on the requesting PCI device(s).
the platform will perform a slot reset on the requesting PCI device(s).
The actual steps taken by a platform to perform a slot reset
will be platform-dependent. Upon completion of slot reset, the
platform will call the device slot_reset() callback.
@ -258,7 +258,7 @@ configuration registers to initialize to their default conditions.
For most PCI devices, a soft reset will be sufficient for recovery.
Optional fundamental reset is provided to support a limited number
of PCI Express PCI devices for which a soft reset is not sufficient
of PCI Express devices for which a soft reset is not sufficient
for recovery.
If the platform supports PCI hotplug, then the reset might be
@ -303,7 +303,7 @@ driver performs device init only from PCI function 0:
Same as above.
Drivers for PCI Express cards that require a fundamental reset must
set the needs_freset bit in the pci_dev structure in their probe function.
set the needs_freset bit in the pci_dev structure in their probe function.
For example, the QLogic qla2xxx driver sets the needs_freset bit for certain
PCI card types:

View file

@ -15,7 +15,7 @@ kernel.
CONFIG_ACPI_DEBUGGER=y
CONFIG_ACPI_DEBUGGER_USER=m
The userspace utlities can be built from the kernel source tree using
The userspace utilities can be built from the kernel source tree using
the following commands:
$ cd tools

View file

@ -367,10 +367,10 @@ resulting child platform device.
Device Tree namespace link device ID
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Device Tree protocol uses device indentification based on the "compatible"
The Device Tree protocol uses device identification based on the "compatible"
property whose value is a string or an array of strings recognized as device
identifiers by drivers and the driver core. The set of all those strings may be
regarded as a device indentification namespace analogous to the ACPI/PNP device
regarded as a device identification namespace analogous to the ACPI/PNP device
ID namespace. Consequently, in principle it should not be necessary to allocate
a new (and arguably redundant) ACPI/PNP device ID for a devices with an existing
identification string in the Device Tree (DT) namespace, especially if that ID
@ -381,7 +381,7 @@ In ACPI, the device identification object called _CID (Compatible ID) is used to
list the IDs of devices the given one is compatible with, but those IDs must
belong to one of the namespaces prescribed by the ACPI specification (see
Section 6.1.2 of ACPI 6.0 for details) and the DT namespace is not one of them.
Moreover, the specification mandates that either a _HID or an _ADR identificaion
Moreover, the specification mandates that either a _HID or an _ADR identification
object be present for all ACPI objects representing devices (Section 6.1 of ACPI
6.0). For non-enumerable bus types that object must be _HID and its value must
be a device ID from one of the namespaces prescribed by the specification too.

View file

@ -60,6 +60,7 @@ configure specific aspects of kernel behavior to your liking.
mono
java
ras
pm/index
.. only:: subproject and html

View file

@ -1,3 +1,5 @@
.. _kernelparameters:
The kernel's command-line parameters
====================================
@ -196,7 +198,7 @@ and is between 256 and 4096 characters. It is defined in the file
Finally, the [KMG] suffix is commonly described after a number of kernel
parameter values. These 'K', 'M', and 'G' letters represent the _binary_
multipliers 'Kilo', 'Mega', and 'Giga', equalling 2^10, 2^20, and 2^30
multipliers 'Kilo', 'Mega', and 'Giga', equaling 2^10, 2^20, and 2^30
bytes respectively. Such letter suffixes can also be entirely omitted:
.. include:: kernel-parameters.txt

View file

@ -0,0 +1,700 @@
.. |struct cpufreq_policy| replace:: :c:type:`struct cpufreq_policy <cpufreq_policy>`
=======================
CPU Performance Scaling
=======================
::
Copyright (c) 2017 Intel Corp., Rafael J. Wysocki <rafael.j.wysocki@intel.com>
The Concept of CPU Performance Scaling
======================================
The majority of modern processors are capable of operating in a number of
different clock frequency and voltage configurations, often referred to as
Operating Performance Points or P-states (in ACPI terminology). As a rule,
the higher the clock frequency and the higher the voltage, the more instructions
can be retired by the CPU over a unit of time, but also the higher the clock
frequency and the higher the voltage, the more energy is consumed over a unit of
time (or the more power is drawn) by the CPU in the given P-state. Therefore
there is a natural tradeoff between the CPU capacity (the number of instructions
that can be executed over a unit of time) and the power drawn by the CPU.
In some situations it is desirable or even necessary to run the program as fast
as possible and then there is no reason to use any P-states different from the
highest one (i.e. the highest-performance frequency/voltage configuration
available). In some other cases, however, it may not be necessary to execute
instructions so quickly and maintaining the highest available CPU capacity for a
relatively long time without utilizing it entirely may be regarded as wasteful.
It also may not be physically possible to maintain maximum CPU capacity for too
long for thermal or power supply capacity reasons or similar. To cover those
cases, there are hardware interfaces allowing CPUs to be switched between
different frequency/voltage configurations or (in the ACPI terminology) to be
put into different P-states.
Typically, they are used along with algorithms to estimate the required CPU
capacity, so as to decide which P-states to put the CPUs into. Of course, since
the utilization of the system generally changes over time, that has to be done
repeatedly on a regular basis. The activity by which this happens is referred
to as CPU performance scaling or CPU frequency scaling (because it involves
adjusting the CPU clock frequency).
CPU Performance Scaling in Linux
================================
The Linux kernel supports CPU performance scaling by means of the ``CPUFreq``
(CPU Frequency scaling) subsystem that consists of three layers of code: the
core, scaling governors and scaling drivers.
The ``CPUFreq`` core provides the common code infrastructure and user space
interfaces for all platforms that support CPU performance scaling. It defines
the basic framework in which the other components operate.
Scaling governors implement algorithms to estimate the required CPU capacity.
As a rule, each governor implements one, possibly parametrized, scaling
algorithm.
Scaling drivers talk to the hardware. They provide scaling governors with
information on the available P-states (or P-state ranges in some cases) and
access platform-specific hardware interfaces to change CPU P-states as requested
by scaling governors.
In principle, all available scaling governors can be used with every scaling
driver. That design is based on the observation that the information used by
performance scaling algorithms for P-state selection can be represented in a
platform-independent form in the majority of cases, so it should be possible
to use the same performance scaling algorithm implemented in exactly the same
way regardless of which scaling driver is used. Consequently, the same set of
scaling governors should be suitable for every supported platform.
However, that observation may not hold for performance scaling algorithms
based on information provided by the hardware itself, for example through
feedback registers, as that information is typically specific to the hardware
interface it comes from and may not be easily represented in an abstract,
platform-independent way. For this reason, ``CPUFreq`` allows scaling drivers
to bypass the governor layer and implement their own performance scaling
algorithms. That is done by the ``intel_pstate`` scaling driver.
``CPUFreq`` Policy Objects
==========================
In some cases the hardware interface for P-state control is shared by multiple
CPUs. That is, for example, the same register (or set of registers) is used to
control the P-state of multiple CPUs at the same time and writing to it affects
all of those CPUs simultaneously.
Sets of CPUs sharing hardware P-state control interfaces are represented by
``CPUFreq`` as |struct cpufreq_policy| objects. For consistency,
|struct cpufreq_policy| is also used when there is only one CPU in the given
set.
The ``CPUFreq`` core maintains a pointer to a |struct cpufreq_policy| object for
every CPU in the system, including CPUs that are currently offline. If multiple
CPUs share the same hardware P-state control interface, all of the pointers
corresponding to them point to the same |struct cpufreq_policy| object.
``CPUFreq`` uses |struct cpufreq_policy| as its basic data type and the design
of its user space interface is based on the policy concept.
CPU Initialization
==================
First of all, a scaling driver has to be registered for ``CPUFreq`` to work.
It is only possible to register one scaling driver at a time, so the scaling
driver is expected to be able to handle all CPUs in the system.
The scaling driver may be registered before or after CPU registration. If
CPUs are registered earlier, the driver core invokes the ``CPUFreq`` core to
take a note of all of the already registered CPUs during the registration of the
scaling driver. In turn, if any CPUs are registered after the registration of
the scaling driver, the ``CPUFreq`` core will be invoked to take note of them
at their registration time.
In any case, the ``CPUFreq`` core is invoked to take note of any logical CPU it
has not seen so far as soon as it is ready to handle that CPU. [Note that the
logical CPU may be a physical single-core processor, or a single core in a
multicore processor, or a hardware thread in a physical processor or processor
core. In what follows "CPU" always means "logical CPU" unless explicitly stated
otherwise and the word "processor" is used to refer to the physical part
possibly including multiple logical CPUs.]
Once invoked, the ``CPUFreq`` core checks if the policy pointer is already set
for the given CPU and if so, it skips the policy object creation. Otherwise,
a new policy object is created and initialized, which involves the creation of
a new policy directory in ``sysfs``, and the policy pointer corresponding to
the given CPU is set to the new policy object's address in memory.
Next, the scaling driver's ``->init()`` callback is invoked with the policy
pointer of the new CPU passed to it as the argument. That callback is expected
to initialize the performance scaling hardware interface for the given CPU (or,
more precisely, for the set of CPUs sharing the hardware interface it belongs
to, represented by its policy object) and, if the policy object it has been
called for is new, to set parameters of the policy, like the minimum and maximum
frequencies supported by the hardware, the table of available frequencies (if
the set of supported P-states is not a continuous range), and the mask of CPUs
that belong to the same policy (including both online and offline CPUs). That
mask is then used by the core to populate the policy pointers for all of the
CPUs in it.
The next major initialization step for a new policy object is to attach a
scaling governor to it (to begin with, that is the default scaling governor
determined by the kernel configuration, but it may be changed later
via ``sysfs``). First, a pointer to the new policy object is passed to the
governor's ``->init()`` callback which is expected to initialize all of the
data structures necessary to handle the given policy and, possibly, to add
a governor ``sysfs`` interface to it. Next, the governor is started by
invoking its ``->start()`` callback.
That callback it expected to register per-CPU utilization update callbacks for
all of the online CPUs belonging to the given policy with the CPU scheduler.
The utilization update callbacks will be invoked by the CPU scheduler on
important events, like task enqueue and dequeue, on every iteration of the
scheduler tick or generally whenever the CPU utilization may change (from the
scheduler's perspective). They are expected to carry out computations needed
to determine the P-state to use for the given policy going forward and to
invoke the scaling driver to make changes to the hardware in accordance with
the P-state selection. The scaling driver may be invoked directly from
scheduler context or asynchronously, via a kernel thread or workqueue, depending
on the configuration and capabilities of the scaling driver and the governor.
Similar steps are taken for policy objects that are not new, but were "inactive"
previously, meaning that all of the CPUs belonging to them were offline. The
only practical difference in that case is that the ``CPUFreq`` core will attempt
to use the scaling governor previously used with the policy that became
"inactive" (and is re-initialized now) instead of the default governor.
In turn, if a previously offline CPU is being brought back online, but some
other CPUs sharing the policy object with it are online already, there is no
need to re-initialize the policy object at all. In that case, it only is
necessary to restart the scaling governor so that it can take the new online CPU
into account. That is achieved by invoking the governor's ``->stop`` and
``->start()`` callbacks, in this order, for the entire policy.
As mentioned before, the ``intel_pstate`` scaling driver bypasses the scaling
governor layer of ``CPUFreq`` and provides its own P-state selection algorithms.
Consequently, if ``intel_pstate`` is used, scaling governors are not attached to
new policy objects. Instead, the driver's ``->setpolicy()`` callback is invoked
to register per-CPU utilization update callbacks for each policy. These
callbacks are invoked by the CPU scheduler in the same way as for scaling
governors, but in the ``intel_pstate`` case they both determine the P-state to
use and change the hardware configuration accordingly in one go from scheduler
context.
The policy objects created during CPU initialization and other data structures
associated with them are torn down when the scaling driver is unregistered
(which happens when the kernel module containing it is unloaded, for example) or
when the last CPU belonging to the given policy in unregistered.
Policy Interface in ``sysfs``
=============================
During the initialization of the kernel, the ``CPUFreq`` core creates a
``sysfs`` directory (kobject) called ``cpufreq`` under
:file:`/sys/devices/system/cpu/`.
That directory contains a ``policyX`` subdirectory (where ``X`` represents an
integer number) for every policy object maintained by the ``CPUFreq`` core.
Each ``policyX`` directory is pointed to by ``cpufreq`` symbolic links
under :file:`/sys/devices/system/cpu/cpuY/` (where ``Y`` represents an integer
that may be different from the one represented by ``X``) for all of the CPUs
associated with (or belonging to) the given policy. The ``policyX`` directories
in :file:`/sys/devices/system/cpu/cpufreq` each contain policy-specific
attributes (files) to control ``CPUFreq`` behavior for the corresponding policy
objects (that is, for all of the CPUs associated with them).
Some of those attributes are generic. They are created by the ``CPUFreq`` core
and their behavior generally does not depend on what scaling driver is in use
and what scaling governor is attached to the given policy. Some scaling drivers
also add driver-specific attributes to the policy directories in ``sysfs`` to
control policy-specific aspects of driver behavior.
The generic attributes under :file:`/sys/devices/system/cpu/cpufreq/policyX/`
are the following:
``affected_cpus``
List of online CPUs belonging to this policy (i.e. sharing the hardware
performance scaling interface represented by the ``policyX`` policy
object).
``bios_limit``
If the platform firmware (BIOS) tells the OS to apply an upper limit to
CPU frequencies, that limit will be reported through this attribute (if
present).
The existence of the limit may be a result of some (often unintentional)
BIOS settings, restrictions coming from a service processor or another
BIOS/HW-based mechanisms.
This does not cover ACPI thermal limitations which can be discovered
through a generic thermal driver.
This attribute is not present if the scaling driver in use does not
support it.
``cpuinfo_max_freq``
Maximum possible operating frequency the CPUs belonging to this policy
can run at (in kHz).
``cpuinfo_min_freq``
Minimum possible operating frequency the CPUs belonging to this policy
can run at (in kHz).
``cpuinfo_transition_latency``
The time it takes to switch the CPUs belonging to this policy from one
P-state to another, in nanoseconds.
If unknown or if known to be so high that the scaling driver does not
work with the `ondemand`_ governor, -1 (:c:macro:`CPUFREQ_ETERNAL`)
will be returned by reads from this attribute.
``related_cpus``
List of all (online and offline) CPUs belonging to this policy.
``scaling_available_governors``
List of ``CPUFreq`` scaling governors present in the kernel that can
be attached to this policy or (if the ``intel_pstate`` scaling driver is
in use) list of scaling algorithms provided by the driver that can be
applied to this policy.
[Note that some governors are modular and it may be necessary to load a
kernel module for the governor held by it to become available and be
listed by this attribute.]
``scaling_cur_freq``
Current frequency of all of the CPUs belonging to this policy (in kHz).
For the majority of scaling drivers, this is the frequency of the last
P-state requested by the driver from the hardware using the scaling
interface provided by it, which may or may not reflect the frequency
the CPU is actually running at (due to hardware design and other
limitations).
Some scaling drivers (e.g. ``intel_pstate``) attempt to provide
information more precisely reflecting the current CPU frequency through
this attribute, but that still may not be the exact current CPU
frequency as seen by the hardware at the moment.
``scaling_driver``
The scaling driver currently in use.
``scaling_governor``
The scaling governor currently attached to this policy or (if the
``intel_pstate`` scaling driver is in use) the scaling algorithm
provided by the driver that is currently applied to this policy.
This attribute is read-write and writing to it will cause a new scaling
governor to be attached to this policy or a new scaling algorithm
provided by the scaling driver to be applied to it (in the
``intel_pstate`` case), as indicated by the string written to this
attribute (which must be one of the names listed by the
``scaling_available_governors`` attribute described above).
``scaling_max_freq``
Maximum frequency the CPUs belonging to this policy are allowed to be
running at (in kHz).
This attribute is read-write and writing a string representing an
integer to it will cause a new limit to be set (it must not be lower
than the value of the ``scaling_min_freq`` attribute).
``scaling_min_freq``
Minimum frequency the CPUs belonging to this policy are allowed to be
running at (in kHz).
This attribute is read-write and writing a string representing a
non-negative integer to it will cause a new limit to be set (it must not
be higher than the value of the ``scaling_max_freq`` attribute).
``scaling_setspeed``
This attribute is functional only if the `userspace`_ scaling governor
is attached to the given policy.
It returns the last frequency requested by the governor (in kHz) or can
be written to in order to set a new frequency for the policy.
Generic Scaling Governors
=========================
``CPUFreq`` provides generic scaling governors that can be used with all
scaling drivers. As stated before, each of them implements a single, possibly
parametrized, performance scaling algorithm.
Scaling governors are attached to policy objects and different policy objects
can be handled by different scaling governors at the same time (although that
may lead to suboptimal results in some cases).
The scaling governor for a given policy object can be changed at any time with
the help of the ``scaling_governor`` policy attribute in ``sysfs``.
Some governors expose ``sysfs`` attributes to control or fine-tune the scaling
algorithms implemented by them. Those attributes, referred to as governor
tunables, can be either global (system-wide) or per-policy, depending on the
scaling driver in use. If the driver requires governor tunables to be
per-policy, they are located in a subdirectory of each policy directory.
Otherwise, they are located in a subdirectory under
:file:`/sys/devices/system/cpu/cpufreq/`. In either case the name of the
subdirectory containing the governor tunables is the name of the governor
providing them.
``performance``
---------------
When attached to a policy object, this governor causes the highest frequency,
within the ``scaling_max_freq`` policy limit, to be requested for that policy.
The request is made once at that time the governor for the policy is set to
``performance`` and whenever the ``scaling_max_freq`` or ``scaling_min_freq``
policy limits change after that.
``powersave``
-------------
When attached to a policy object, this governor causes the lowest frequency,
within the ``scaling_min_freq`` policy limit, to be requested for that policy.
The request is made once at that time the governor for the policy is set to
``powersave`` and whenever the ``scaling_max_freq`` or ``scaling_min_freq``
policy limits change after that.
``userspace``
-------------
This governor does not do anything by itself. Instead, it allows user space
to set the CPU frequency for the policy it is attached to by writing to the
``scaling_setspeed`` attribute of that policy.
``schedutil``
-------------
This governor uses CPU utilization data available from the CPU scheduler. It
generally is regarded as a part of the CPU scheduler, so it can access the
scheduler's internal data structures directly.
It runs entirely in scheduler context, although in some cases it may need to
invoke the scaling driver asynchronously when it decides that the CPU frequency
should be changed for a given policy (that depends on whether or not the driver
is capable of changing the CPU frequency from scheduler context).
The actions of this governor for a particular CPU depend on the scheduling class
invoking its utilization update callback for that CPU. If it is invoked by the
RT or deadline scheduling classes, the governor will increase the frequency to
the allowed maximum (that is, the ``scaling_max_freq`` policy limit). In turn,
if it is invoked by the CFS scheduling class, the governor will use the
Per-Entity Load Tracking (PELT) metric for the root control group of the
given CPU as the CPU utilization estimate (see the `Per-entity load tracking`_
LWN.net article for a description of the PELT mechanism). Then, the new
CPU frequency to apply is computed in accordance with the formula
f = 1.25 * ``f_0`` * ``util`` / ``max``
where ``util`` is the PELT number, ``max`` is the theoretical maximum of
``util``, and ``f_0`` is either the maximum possible CPU frequency for the given
policy (if the PELT number is frequency-invariant), or the current CPU frequency
(otherwise).
This governor also employs a mechanism allowing it to temporarily bump up the
CPU frequency for tasks that have been waiting on I/O most recently, called
"IO-wait boosting". That happens when the :c:macro:`SCHED_CPUFREQ_IOWAIT` flag
is passed by the scheduler to the governor callback which causes the frequency
to go up to the allowed maximum immediately and then draw back to the value
returned by the above formula over time.
This governor exposes only one tunable:
``rate_limit_us``
Minimum time (in microseconds) that has to pass between two consecutive
runs of governor computations (default: 1000 times the scaling driver's
transition latency).
The purpose of this tunable is to reduce the scheduler context overhead
of the governor which might be excessive without it.
This governor generally is regarded as a replacement for the older `ondemand`_
and `conservative`_ governors (described below), as it is simpler and more
tightly integrated with the CPU scheduler, its overhead in terms of CPU context
switches and similar is less significant, and it uses the scheduler's own CPU
utilization metric, so in principle its decisions should not contradict the
decisions made by the other parts of the scheduler.
``ondemand``
------------
This governor uses CPU load as a CPU frequency selection metric.
In order to estimate the current CPU load, it measures the time elapsed between
consecutive invocations of its worker routine and computes the fraction of that
time in which the given CPU was not idle. The ratio of the non-idle (active)
time to the total CPU time is taken as an estimate of the load.
If this governor is attached to a policy shared by multiple CPUs, the load is
estimated for all of them and the greatest result is taken as the load estimate
for the entire policy.
The worker routine of this governor has to run in process context, so it is
invoked asynchronously (via a workqueue) and CPU P-states are updated from
there if necessary. As a result, the scheduler context overhead from this
governor is minimum, but it causes additional CPU context switches to happen
relatively often and the CPU P-state updates triggered by it can be relatively
irregular. Also, it affects its own CPU load metric by running code that
reduces the CPU idle time (even though the CPU idle time is only reduced very
slightly by it).
It generally selects CPU frequencies proportional to the estimated load, so that
the value of the ``cpuinfo_max_freq`` policy attribute corresponds to the load of
1 (or 100%), and the value of the ``cpuinfo_min_freq`` policy attribute
corresponds to the load of 0, unless when the load exceeds a (configurable)
speedup threshold, in which case it will go straight for the highest frequency
it is allowed to use (the ``scaling_max_freq`` policy limit).
This governor exposes the following tunables:
``sampling_rate``
This is how often the governor's worker routine should run, in
microseconds.
Typically, it is set to values of the order of 10000 (10 ms). Its
default value is equal to the value of ``cpuinfo_transition_latency``
for each policy this governor is attached to (but since the unit here
is greater by 1000, this means that the time represented by
``sampling_rate`` is 1000 times greater than the transition latency by
default).
If this tunable is per-policy, the following shell command sets the time
represented by it to be 750 times as high as the transition latency::
# echo `$(($(cat cpuinfo_transition_latency) * 750 / 1000)) > ondemand/sampling_rate
``min_sampling_rate``
The minimum value of ``sampling_rate``.
Equal to 10000 (10 ms) if :c:macro:`CONFIG_NO_HZ_COMMON` and
:c:data:`tick_nohz_active` are both set or to 20 times the value of
:c:data:`jiffies` in microseconds otherwise.
``up_threshold``
If the estimated CPU load is above this value (in percent), the governor
will set the frequency to the maximum value allowed for the policy.
Otherwise, the selected frequency will be proportional to the estimated
CPU load.
``ignore_nice_load``
If set to 1 (default 0), it will cause the CPU load estimation code to
treat the CPU time spent on executing tasks with "nice" levels greater
than 0 as CPU idle time.
This may be useful if there are tasks in the system that should not be
taken into account when deciding what frequency to run the CPUs at.
Then, to make that happen it is sufficient to increase the "nice" level
of those tasks above 0 and set this attribute to 1.
``sampling_down_factor``
Temporary multiplier, between 1 (default) and 100 inclusive, to apply to
the ``sampling_rate`` value if the CPU load goes above ``up_threshold``.
This causes the next execution of the governor's worker routine (after
setting the frequency to the allowed maximum) to be delayed, so the
frequency stays at the maximum level for a longer time.
Frequency fluctuations in some bursty workloads may be avoided this way
at the cost of additional energy spent on maintaining the maximum CPU
capacity.
``powersave_bias``
Reduction factor to apply to the original frequency target of the
governor (including the maximum value used when the ``up_threshold``
value is exceeded by the estimated CPU load) or sensitivity threshold
for the AMD frequency sensitivity powersave bias driver
(:file:`drivers/cpufreq/amd_freq_sensitivity.c`), between 0 and 1000
inclusive.
If the AMD frequency sensitivity powersave bias driver is not loaded,
the effective frequency to apply is given by
f * (1 - ``powersave_bias`` / 1000)
where f is the governor's original frequency target. The default value
of this attribute is 0 in that case.
If the AMD frequency sensitivity powersave bias driver is loaded, the
value of this attribute is 400 by default and it is used in a different
way.
On Family 16h (and later) AMD processors there is a mechanism to get a
measured workload sensitivity, between 0 and 100% inclusive, from the
hardware. That value can be used to estimate how the performance of the
workload running on a CPU will change in response to frequency changes.
The performance of a workload with the sensitivity of 0 (memory-bound or
IO-bound) is not expected to increase at all as a result of increasing
the CPU frequency, whereas workloads with the sensitivity of 100%
(CPU-bound) are expected to perform much better if the CPU frequency is
increased.
If the workload sensitivity is less than the threshold represented by
the ``powersave_bias`` value, the sensitivity powersave bias driver
will cause the governor to select a frequency lower than its original
target, so as to avoid over-provisioning workloads that will not benefit
from running at higher CPU frequencies.
``conservative``
----------------
This governor uses CPU load as a CPU frequency selection metric.
It estimates the CPU load in the same way as the `ondemand`_ governor described
above, but the CPU frequency selection algorithm implemented by it is different.
Namely, it avoids changing the frequency significantly over short time intervals
which may not be suitable for systems with limited power supply capacity (e.g.
battery-powered). To achieve that, it changes the frequency in relatively
small steps, one step at a time, up or down - depending on whether or not a
(configurable) threshold has been exceeded by the estimated CPU load.
This governor exposes the following tunables:
``freq_step``
Frequency step in percent of the maximum frequency the governor is
allowed to set (the ``scaling_max_freq`` policy limit), between 0 and
100 (5 by default).
This is how much the frequency is allowed to change in one go. Setting
it to 0 will cause the default frequency step (5 percent) to be used
and setting it to 100 effectively causes the governor to periodically
switch the frequency between the ``scaling_min_freq`` and
``scaling_max_freq`` policy limits.
``down_threshold``
Threshold value (in percent, 20 by default) used to determine the
frequency change direction.
If the estimated CPU load is greater than this value, the frequency will
go up (by ``freq_step``). If the load is less than this value (and the
``sampling_down_factor`` mechanism is not in effect), the frequency will
go down. Otherwise, the frequency will not be changed.
``sampling_down_factor``
Frequency decrease deferral factor, between 1 (default) and 10
inclusive.
It effectively causes the frequency to go down ``sampling_down_factor``
times slower than it ramps up.
Frequency Boost Support
=======================
Background
----------
Some processors support a mechanism to raise the operating frequency of some
cores in a multicore package temporarily (and above the sustainable frequency
threshold for the whole package) under certain conditions, for example if the
whole chip is not fully utilized and below its intended thermal or power budget.
Different names are used by different vendors to refer to this functionality.
For Intel processors it is referred to as "Turbo Boost", AMD calls it
"Turbo-Core" or (in technical documentation) "Core Performance Boost" and so on.
As a rule, it also is implemented differently by different vendors. The simple
term "frequency boost" is used here for brevity to refer to all of those
implementations.
The frequency boost mechanism may be either hardware-based or software-based.
If it is hardware-based (e.g. on x86), the decision to trigger the boosting is
made by the hardware (although in general it requires the hardware to be put
into a special state in which it can control the CPU frequency within certain
limits). If it is software-based (e.g. on ARM), the scaling driver decides
whether or not to trigger boosting and when to do that.
The ``boost`` File in ``sysfs``
-------------------------------
This file is located under :file:`/sys/devices/system/cpu/cpufreq/` and controls
the "boost" setting for the whole system. It is not present if the underlying
scaling driver does not support the frequency boost mechanism (or supports it,
but provides a driver-specific interface for controlling it, like
``intel_pstate``).
If the value in this file is 1, the frequency boost mechanism is enabled. This
means that either the hardware can be put into states in which it is able to
trigger boosting (in the hardware-based case), or the software is allowed to
trigger boosting (in the software-based case). It does not mean that boosting
is actually in use at the moment on any CPUs in the system. It only means a
permission to use the frequency boost mechanism (which still may never be used
for other reasons).
If the value in this file is 0, the frequency boost mechanism is disabled and
cannot be used at all.
The only values that can be written to this file are 0 and 1.
Rationale for Boost Control Knob
--------------------------------
The frequency boost mechanism is generally intended to help to achieve optimum
CPU performance on time scales below software resolution (e.g. below the
scheduler tick interval) and it is demonstrably suitable for many workloads, but
it may lead to problems in certain situations.
For this reason, many systems make it possible to disable the frequency boost
mechanism in the platform firmware (BIOS) setup, but that requires the system to
be restarted for the setting to be adjusted as desired, which may not be
practical at least in some cases. For example:
1. Boosting means overclocking the processor, although under controlled
conditions. Generally, the processor's energy consumption increases
as a result of increasing its frequency and voltage, even temporarily.
That may not be desirable on systems that switch to power sources of
limited capacity, such as batteries, so the ability to disable the boost
mechanism while the system is running may help there (but that depends on
the workload too).
2. In some situations deterministic behavior is more important than
performance or energy consumption (or both) and the ability to disable
boosting while the system is running may be useful then.
3. To examine the impact of the frequency boost mechanism itself, it is useful
to be able to run tests with and without boosting, preferably without
restarting the system in the meantime.
4. Reproducible results are important when running benchmarks. Since
the boosting functionality depends on the load of the whole package,
single-thread performance may vary because of it which may lead to
unreproducible results sometimes. That can be avoided by disabling the
frequency boost mechanism before running benchmarks sensitive to that
issue.
Legacy AMD ``cpb`` Knob
-----------------------
The AMD powernow-k8 scaling driver supports a ``sysfs`` knob very similar to
the global ``boost`` one. It is used for disabling/enabling the "Core
Performance Boost" feature of some AMD processors.
If present, that knob is located in every ``CPUFreq`` policy directory in
``sysfs`` (:file:`/sys/devices/system/cpu/cpufreq/policyX/`) and is called
``cpb``, which indicates a more fine grained control interface. The actual
implementation, however, works on the system-wide basis and setting that knob
for one policy causes the same value of it to be set for all of the other
policies at the same time.
That knob is still supported on AMD processors that support its underlying
hardware feature, but it may be configured out of the kernel (via the
:c:macro:`CONFIG_X86_ACPI_CPUFREQ_CPB` configuration option) and the global
``boost`` knob is present regardless. Thus it is always possible use the
``boost`` knob instead of the ``cpb`` one which is highly recommended, as that
is more consistent with what all of the other systems do (and the ``cpb`` knob
may not be supported any more in the future).
The ``cpb`` knob is never present for any processors without the underlying
hardware feature (e.g. all Intel ones), even if the
:c:macro:`CONFIG_X86_ACPI_CPUFREQ_CPB` configuration option is set.
.. _Per-entity load tracking: https://lwn.net/Articles/531853/

View file

@ -0,0 +1,15 @@
================
Power Management
================
.. toctree::
:maxdepth: 2
cpufreq
.. only:: subproject and html
Indices
=======
* :ref:`genindex`

View file

@ -8,7 +8,7 @@ RAS concepts
************
Reliability, Availability and Serviceability (RAS) is a concept used on
servers meant to measure their robusteness.
servers meant to measure their robustness.
Reliability
is the probability that a system will produce correct outputs.
@ -42,13 +42,13 @@ Among the monitoring measures, the most usual ones include:
* CPU – detect errors at instruction execution and at L1/L2/L3 caches;
* Memory – add error correction logic (ECC) to detect and correct errors;
* I/O – add CRC checksums for tranfered data;
* I/O – add CRC checksums for transferred data;
* Storage – RAID, journal file systems, checksums,
Self-Monitoring, Analysis and Reporting Technology (SMART).
By monitoring the number of occurrences of error detections, it is possible
to identify if the probability of hardware errors is increasing, and, on such
case, do a preventive maintainance to replace a degrated component while
case, do a preventive maintenance to replace a degraded component while
those errors are correctable.
Types of errors
@ -121,7 +121,7 @@ using the ``dmidecode`` tool. For example, on a desktop machine, it shows::
On the above example, a DDR4 SO-DIMM memory module is located at the
system's memory labeled as "BANK 0", as given by the *bank locator* field.
Please notice that, on such system, the *total width* is equal to the
*data witdh*. It means that such memory module doesn't have error
*data width*. It means that such memory module doesn't have error
detection/correction mechanisms.
Unfortunately, not all systems use the same field to specify the memory
@ -145,7 +145,7 @@ bank. On this example, from an older server, ``dmidecode`` shows::
There, the DDR3 RDIMM memory module is located at the system's memory labeled
as "DIMM_A1", as given by the *locator* field. Please notice that this
memory module has 64 bits of *data witdh* and 72 bits of *total width*. So,
memory module has 64 bits of *data width* and 72 bits of *total width*. So,
it has 8 extra bits to be used by error detection and correction mechanisms.
Such kind of memory is called Error-correcting code memory (ECC memory).
@ -186,7 +186,7 @@ Architecture (MCA)\ [#f3]_.
.. [#f1] Please notice that several memory controllers allow operation on a
mode called "Lock-Step", where it groups two memory modules together,
doing 128-bit reads/writes. That gives 16 bits for error correction, with
significatively improves the error correction mechanism, at the expense
significantly improves the error correction mechanism, at the expense
that, when an error happens, there's no way to know what memory module is
to blame. So, it has to blame both memory modules.

View file

@ -14,14 +14,17 @@ Contact
The Linux kernel security team can be contacted by email at
<security@kernel.org>. This is a private list of security officers
who will help verify the bug report and develop and release a fix.
It is possible that the security team will bring in extra help from
area maintainers to understand and fix the security vulnerability.
If you already have a fix, please include it with your report, as
that can speed up the process considerably. It is possible that the
security team will bring in extra help from area maintainers to
understand and fix the security vulnerability.
As it is with any bug, the more information provided the easier it
will be to diagnose and fix. Please review the procedure outlined in
admin-guide/reporting-bugs.rst if you are unclear about what information is helpful.
Any exploit code is very helpful and will not be released without
consent from the reporter unless it has already been made public.
admin-guide/reporting-bugs.rst if you are unclear about what
information is helpful. Any exploit code is very helpful and will not
be released without consent from the reporter unless it has already been
made public.
Disclosure
----------
@ -39,6 +42,32 @@ disclosure is from immediate (esp. if it's already publicly known)
to a few weeks. As a basic default policy, we expect report date to
disclosure date to be on the order of 7 days.
Coordination
------------
Fixes for sensitive bugs, such as those that might lead to privilege
escalations, may need to be coordinated with the private
<linux-distros@vs.openwall.org> mailing list so that distribution vendors
are well prepared to issue a fixed kernel upon public disclosure of the
upstream fix. Distros will need some time to test the proposed patch and
will generally request at least a few days of embargo, and vendor update
publication prefers to happen Tuesday through Thursday. When appropriate,
the security team can assist with this coordination, or the reporter can
include linux-distros from the start. In this case, remember to prefix
the email Subject line with "[vs]" as described in the linux-distros wiki:
<http://oss-security.openwall.org/wiki/mailing-lists/distros#how-to-use-the-lists>
CVE assignment
--------------
The security team does not normally assign CVEs, nor do we require them
for reports or fixes, as this can needlessly complicate the process and
may delay the bug handling. If a reporter wishes to have a CVE identifier
assigned ahead of public disclosure, they will need to contact the private
linux-distros list, described above. When such a CVE identifier is known
before a patch is provided, it is desirable to mention it in the commit
message, though.
Non-disclosure agreements
-------------------------

View file

@ -212,7 +212,8 @@ I hit SysRq, but nothing seems to happen, what's wrong?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are some keyboards that produce a different keycode for SysRq than the
pre-defined value of 99 (see ``KEY_SYSRQ`` in ``include/linux/input.h``), or
pre-defined value of 99
(see ``KEY_SYSRQ`` in ``include/uapi/linux/input-event-codes.h``), or
which don't have a SysRq key at all. In these cases, run ``showkey -s`` to find
an appropriate scancode sequence, and use ``setkeycodes <sequence> 99`` to map
this sequence to the usual SysRq code (e.g., ``setkeycodes e05b 99``). It's

View file

@ -48,7 +48,7 @@ Note that not all combinations are supported - only values 0 through 5.
For example, the following will turn on the warnings, but without
fixing up or sending SIGBUS signals:
echo 1 > /proc/sys/debug/alignment
echo 1 > /proc/cpu/alignment
You can also read the content of the same file to get statistical
information on unaligned access occurrences plus the current mode of

Some files were not shown because too many files have changed in this diff Show more