code:
================================================
Care and feeding of your Human Interface Devices
================================================

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

In addition to the normal input type HID devices, USB also uses the
human interface device protocols for things that are not really human
interfaces, but have similar sorts of communication needs. The two big
examples for this are power devices (especially uninterruptable power
supplies) and monitor control on higher end monitors.

To support these disparate requirements, the Linux USB system provides
HID events to two separate interfaces:
* the input subsystem, which converts HID events into normal input
device interfaces (such as keyboard, mouse and joystick) and a
normalised event interface - see Documentation/input/input.rst
* the hiddev interface, which provides fairly raw HID events

The data flow for a HID event produced by a device is something like
the following::

 usb.c ---> hid-core.c  ----> hid-input.c ----> [keyboard/mouse/joystick/event]
                         |
                         |
                          --> hiddev.c ----> POWER / MONITOR CONTROL

In addition, other subsystems (apart from USB) can potentially feed
events into the input subsystem, but these have no effect on the HID
device interface.

Using the HID Device Interface
==============================

The hiddev interface is a char interface using the normal USB major,
with the minor numbers starting at 96 and finishing at 111. Therefore,
you need the following commands::

	mknod /dev/usb/hiddev0 c 180 96
	mknod /dev/usb/hiddev1 c 180 97
	mknod /dev/usb/hiddev2 c 180 98
	mknod /dev/usb/hiddev3 c 180 99
	mknod /dev/usb/hiddev4 c 180 100
	mknod /dev/usb/hiddev5 c 180 101
	mknod /dev/usb/hiddev6 c 180 102
	mknod /dev/usb/hiddev7 c 180 103
	mknod /dev/usb/hiddev8 c 180 104
	mknod /dev/usb/hiddev9 c 180 105
	mknod /dev/usb/hiddev10 c 180 106
	mknod /dev/usb/hiddev11 c 180 107
	mknod /dev/usb/hiddev12 c 180 108
	mknod /dev/usb/hiddev13 c 180 109
	mknod /dev/usb/hiddev14 c 180 110
	mknod /dev/usb/hiddev15 c 180 111

So you point your hiddev compliant user-space program at the correct
interface for your device, and it all just works.

Assuming that you have a hiddev compliant user-space program, of
course. If you need to write one, read on.

The HIDDEV API
==============

This description should be read in conjunction with the HID
specification, freely available from https://www.usb.org, and
conveniently linked of http://www.linux-usb.org.

The hiddev API uses a read() interface, and a set of ioctl() calls.

HID devices exchange data with the host computer using data
bundles called "reports".  Each report is divided into "fields",
each of which can have one or more "usages".  In the hid-core,
each one of these usages has a single signed 32-bit value.

read():
-------

This is the event interface.  When the HID device's state changes,
it performs an interrupt transfer containing a report which contains
the changed value.  The hid-core.c module parses the report, and
returns to hiddev.c the individual usages that have changed within
the report.  In its basic mode, the hiddev will make these individual
usage changes available to the reader using a struct hiddev_event::

       struct hiddev_event {
           unsigned hid;
           signed int value;
       };

containing the HID usage identifier for the status that changed, and
the value that it was changed to. Note that the structure is defined
within <linux/hiddev.h>, along with some other useful #defines and
structures.  The HID usage identifier is a composite of the HID usage
page shifted to the 16 high order bits ORed with the usage code.  The
behavior of the read() function can be modified using the HIDIOCSFLAG
ioctl() described below.

ioctl():
--------

This is the control interface. There are a number of controls:

HIDIOCGVERSION
  - int (read)

 Gets the version code out of the hiddev driver.

HIDIOCAPPLICATION
  - (none)

This ioctl call returns the HID application usage associated with the
HID device. The third argument to ioctl() specifies which application
index to get. This is useful when the device has more than one
application collection. If the index is invalid (greater or equal to
the number of application collections this device has) the ioctl
returns -1. You can find out beforehand how many application
collections the device has from the num_applications field from the
hiddev_devinfo structure.

HIDIOCGCOLLECTIONINFO
  - struct hiddev_collection_info (read/write)

This returns a superset of the information above, providing not only
application collections, but all the collections the device has.  It
also returns the level the collection lives in the hierarchy.
The user passes in a hiddev_collection_info struct with the index
field set to the index that should be returned.  The ioctl fills in
the other fields.  If the index is larger than the last collection
index, the ioctl returns -1 and sets errno to -EINVAL.

HIDIOCGDEVINFO
  - struct hiddev_devinfo (read)

Gets a hiddev_devinfo structure which describes the device.

HIDIOCGSTRING
  - struct hiddev_string_descriptor (read/write)

Gets a string descriptor from the device. The caller must fill in the
"index" field to indicate which descriptor should be returned.

HIDIOCINITREPORT
  - (none)

Instructs the kernel to retrieve all input and feature report values
from the device. At this point, all the usage structures will contain
current values for the device, and will maintain it as the device
changes.  Note that the use of this ioctl is unnecessary in general,
since later kernels automatically initialize the reports from the
device at attach time.

HIDIOCGNAME
  - string (variable length)

Gets the device name

HIDIOCGREPORT
  - struct hiddev_report_info (write)

Instructs the kernel to get a feature or input report from the device,
in order to selectively update the usage structures (in contrast to
INITREPORT).

HIDIOCSREPORT
  - struct hiddev_report_info (write)

Instructs the kernel to send a report to the device. This report can
be filled in by the user through HIDIOCSUSAGE calls (below) to fill in
individual usage values in the report before sending the report in full
to the device.

HIDIOCGREPORTINFO
  - struct hiddev_report_info (read/write)

Fills in a hiddev_report_info structure for the user. The report is
looked up by type (input, output or feature) and id, so these fields
must be filled in by the user. The ID can be absolute -- the actual
report id as reported by the device -- or relative --
HID_REPORT_ID_FIRST for the first report, and (HID_REPORT_ID_NEXT |
report_id) for the next report after report_id. Without a priori
information about report ids, the right way to use this ioctl is to
use the relative IDs above to enumerate the valid IDs. The ioctl
returns non-zero when there is no more next ID. The real report ID is
filled into the returned hiddev_report_info structure.

HIDIOCGFIELDINFO
  - struct hiddev_field_info (read/write)

Returns the field information associated with a report in a
hiddev_field_info structure. The user must fill in report_id and
report_type in this structure, as above. The field_index should also
be filled in, which should be a number from 0 and maxfield-1, as
returned from a previous HIDIOCGREPORTINFO call.

HIDIOCGUCODE
  - struct hiddev_usage_ref (read/write)

Returns the usage_code in a hiddev_usage_ref structure, given that
its report type, report id, field index, and index within the
field have already been filled into the structure.

HIDIOCGUSAGE
  - struct hiddev_usage_ref (read/write)

Returns the value of a usage in a hiddev_usage_ref structure. The
usage to be retrieved can be specified as above, or the user can
choose to fill in the report_type field and specify the report_id as
HID_REPORT_ID_UNKNOWN. In this case, the hiddev_usage_ref will be
filled in with the report and field information associated with this
usage if it is found.

HIDIOCSUSAGE
  - struct hiddev_usage_ref (write)

Sets the value of a usage in an output report.  The user fills in
the hiddev_usage_ref structure as above, but additionally fills in
the value field.

HIDIOGCOLLECTIONINDEX
  - struct hiddev_usage_ref (write)

Returns the collection index associated with this usage.  This
indicates where in the collection hierarchy this usage sits.

HIDIOCGFLAG
  - int (read)
HIDIOCSFLAG
  - int (write)

These operations respectively inspect and replace the mode flags
that influence the read() call above.  The flags are as follows:

    HIDDEV_FLAG_UREF
      - read() calls will now return
        struct hiddev_usage_ref instead of struct hiddev_event.
        This is a larger structure, but in situations where the
        device has more than one usage in its reports with the
        same usage code, this mode serves to resolve such
        ambiguity.

    HIDDEV_FLAG_REPORT
      - This flag can only be used in conjunction
        with HIDDEV_FLAG_UREF.  With this flag set, when the device
        sends a report, a struct hiddev_usage_ref will be returned
        to read() filled in with the report_type and report_id, but
        with field_index set to FIELD_INDEX_NONE.  This serves as
        additional notification when the device has sent a report.


code:
================================================================
HIDRAW - Raw Access to USB and Bluetooth Human Interface Devices
================================================================

The hidraw driver provides a raw interface to USB and Bluetooth Human
Interface Devices (HIDs).  It differs from hiddev in that reports sent and
received are not parsed by the HID parser, but are sent to and received from
the device unmodified.

Hidraw should be used if the userspace application knows exactly how to
communicate with the hardware device, and is able to construct the HID
reports manually.  This is often the case when making userspace drivers for
custom HID devices.

Hidraw is also useful for communicating with non-conformant HID devices
which send and receive data in a way that is inconsistent with their report
descriptors.  Because hiddev parses reports which are sent and received
through it, checking them against the device's report descriptor, such
communication with these non-conformant devices is impossible using hiddev.
Hidraw is the only alternative, short of writing a custom kernel driver, for
these non-conformant devices.

A benefit of hidraw is that its use by userspace applications is independent
of the underlying hardware type.  Currently, hidraw is implemented for USB
and Bluetooth.  In the future, as new hardware bus types are developed which
use the HID specification, hidraw will be expanded to add support for these
new bus types.

Hidraw uses a dynamic major number, meaning that udev should be relied on to
create hidraw device nodes.  Udev will typically create the device nodes
directly under /dev (eg: /dev/hidraw0).  As this location is distribution-
and udev rule-dependent, applications should use libudev to locate hidraw
devices attached to the system.  There is a tutorial on libudev with a
working example at::

	http://www.signal11.us/oss/udev/
	https://web.archive.org/web/2019*/www.signal11.us

The HIDRAW API
---------------

read()
-------
read() will read a queued report received from the HID device. On USB
devices, the reports read using read() are the reports sent from the device
on the INTERRUPT IN endpoint.  By default, read() will block until there is
a report available to be read.  read() can be made non-blocking, by passing
the O_NONBLOCK flag to open(), or by setting the O_NONBLOCK flag using
fcntl().

On a device which uses numbered reports, the first byte of the returned data
will be the report number; the report data follows, beginning in the second
byte.  For devices which do not use numbered reports, the report data
will begin at the first byte.

write()
-------
The write() function will write a report to the device. For USB devices, if
the device has an INTERRUPT OUT endpoint, the report will be sent on that
endpoint. If it does not, the report will be sent over the control endpoint,
using a SET_REPORT transfer.

The first byte of the buffer passed to write() should be set to the report
number.  If the device does not use numbered reports, the first byte should
be set to 0. The report data itself should begin at the second byte.

ioctl()
-------
Hidraw supports the following ioctls:

HIDIOCGRDESCSIZE:
	Get Report Descriptor Size

This ioctl will get the size of the device's report descriptor.

HIDIOCGRDESC:
	Get Report Descriptor

This ioctl returns the device's report descriptor using a
hidraw_report_descriptor struct.  Make sure to set the size field of the
hidraw_report_descriptor struct to the size returned from HIDIOCGRDESCSIZE.

HIDIOCGRAWINFO:
	Get Raw Info

This ioctl will return a hidraw_devinfo struct containing the bus type, the
vendor ID (VID), and product ID (PID) of the device. The bus type can be one
of::

	- BUS_USB
	- BUS_HIL
	- BUS_BLUETOOTH
	- BUS_VIRTUAL

which are defined in uapi/linux/input.h.

HIDIOCGRAWNAME(len):
	Get Raw Name

This ioctl returns a string containing the vendor and product strings of
the device.  The returned string is Unicode, UTF-8 encoded.

HIDIOCGRAWPHYS(len):
	Get Physical Address

This ioctl returns a string representing the physical address of the device.
For USB devices, the string contains the physical path to the device (the
USB controller, hubs, ports, etc).  For Bluetooth devices, the string
contains the hardware (MAC) address of the device.

HIDIOCSFEATURE(len):
	Send a Feature Report

This ioctl will send a feature report to the device.  Per the HID
specification, feature reports are always sent using the control endpoint.
Set the first byte of the supplied buffer to the report number.  For devices
which do not use numbered reports, set the first byte to 0. The report data
begins in the second byte. Make sure to set len accordingly, to one more
than the length of the report (to account for the report number).

HIDIOCGFEATURE(len):
	Get a Feature Report

This ioctl will request a feature report from the device using the control
endpoint.  The first byte of the supplied buffer should be set to the report
number of the requested report.  For devices which do not use numbered
reports, set the first byte to 0.  The returned report buffer will contain the
report number in the first byte, followed by the report data read from the
device.  For devices which do not use numbered reports, the report data will
begin at the first byte of the returned buffer.

HIDIOCSINPUT(len):
	Send an Input Report

This ioctl will send an input report to the device, using the control endpoint.
In most cases, setting an input HID report on a device is meaningless and has
no effect, but some devices may choose to use this to set or reset an initial
state of a report.  The format of the buffer issued with this report is identical
to that of HIDIOCSFEATURE.

HIDIOCGINPUT(len):
	Get an Input Report

This ioctl will request an input report from the device using the control
endpoint.  This is slower on most devices where a dedicated In endpoint exists
for regular input reports, but allows the host to request the value of a
specific report number.  Typically, this is used to request the initial states of
an input report of a device, before an application listens for normal reports via
the regular device read() interface.  The format of the buffer issued with this report
is identical to that of HIDIOCGFEATURE.

HIDIOCSOUTPUT(len):
	Send an Output Report

This ioctl will send an output report to the device, using the control endpoint.
This is slower on most devices where a dedicated Out endpoint exists for regular
output reports, but is added for completeness.  Typically, this is used to set
the initial states of an output report of a device, before an application sends
updates via the regular device write() interface. The format of the buffer issued
with this report is identical to that of HIDIOCSFEATURE.

HIDIOCGOUTPUT(len):
	Get an Output Report

This ioctl will request an output report from the device using the control
endpoint.  Typically, this is used to retrive the initial state of
an output report of a device, before an application updates it as necessary either
via a HIDIOCSOUTPUT request, or the regular device write() interface.  The format
of the buffer issued with this report is identical to that of HIDIOCGFEATURE.

Example
-------
In samples/, find hid-example.c, which shows examples of read(), write(),
and all the ioctls for hidraw.  The code may be used by anyone for any
purpose, and can serve as a starting point for developing applications using
hidraw.

Document by:

	Alan Ott <alan@signal11.us>, Signal 11 Software

repo_name: angery/linux


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

=============================
Human Interface Devices (HID)
=============================

.. toctree::
   :maxdepth: 1

   hiddev
   hidraw
   hid-sensor
   hid-transport

   uhid

   hid-alps
   intel-ish-hid
   amd-sfh-hid


code:
=================================
Intel Integrated Sensor Hub (ISH)
=================================

A sensor hub enables the ability to offload sensor polling and algorithm
processing to a dedicated low power co-processor. This allows the core
processor to go into low power modes more often, resulting in increased
battery life.

There are many vendors providing external sensor hubs conforming to HID
Sensor usage tables. These may be found in tablets, 2-in-1 convertible laptops
and embedded products. Linux has had this support since Linux 3.9.

Intel® introduced integrated sensor hubs as a part of the SoC starting from
Cherry Trail and now supported on multiple generations of CPU packages. There
are many commercial devices already shipped with Integrated Sensor Hubs (ISH).
These ISH also comply to HID sensor specification, but the difference is the
transport protocol used for communication. The current external sensor hubs
mainly use HID over I2C or USB. But ISH doesn't use either I2C or USB.

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

Using a analogy with a usbhid implementation, the ISH follows a similar model
for a very high speed communication::

	-----------------		----------------------
	|    USB HID	|	-->	|    ISH HID	     |
	-----------------		----------------------
	-----------------		----------------------
	|  USB protocol	|	-->	|    ISH Transport   |
	-----------------		----------------------
	-----------------		----------------------
	|  EHCI/XHCI	|	-->	|    ISH IPC	     |
	-----------------		----------------------
	      PCI				 PCI
	-----------------		----------------------
	|Host controller|	-->	|    ISH processor   |
	-----------------		----------------------
	     USB Link
	-----------------		----------------------
	| USB End points|	-->	|    ISH Clients     |
	-----------------		----------------------

Like USB protocol provides a method for device enumeration, link management
and user data encapsulation, the ISH also provides similar services. But it is
very light weight tailored to manage and communicate with ISH client
applications implemented in the firmware.

The ISH allows multiple sensor management applications executing in the
firmware. Like USB endpoints the messaging can be to/from a client. As part of
enumeration process, these clients are identified. These clients can be simple
HID sensor applications, sensor calibration applications or sensor firmware
update applications.

The implementation model is similar, like USB bus, ISH transport is also
implemented as a bus. Each client application executing in the ISH processor
is registered as a device on this bus. The driver, which binds each device
(ISH HID driver) identifies the device type and registers with the HID core.

2. ISH Implementation: Block Diagram
====================================

::

	 ---------------------------
	|  User Space Applications  |
	 ---------------------------

  ----------------IIO ABI----------------
	 --------------------------
	|  IIO Sensor Drivers	  |
	 --------------------------
	 --------------------------
	|	 IIO core	  |
	 --------------------------
	 --------------------------
	|   HID Sensor Hub MFD	  |
	 --------------------------
	 --------------------------
	|       HID Core	  |
	 --------------------------
	 --------------------------
	|   HID over ISH Client   |
	 --------------------------
	 --------------------------
	|   ISH Transport (ISHTP) |
	 --------------------------
	 --------------------------
	|      IPC Drivers	  |
	 --------------------------
  OS
  ---------------- PCI -----------------
  Hardware + Firmware
	 ----------------------------
	| ISH Hardware/Firmware(FW) |
	 ----------------------------

3. High level processing in above blocks
========================================

3.1 Hardware Interface
----------------------

The ISH is exposed as "Non-VGA unclassified PCI device" to the host. The PCI
product and vendor IDs are changed from different generations of processors. So
the source code which enumerates drivers needs to update from generation to
generation.

3.2 Inter Processor Communication (IPC) driver
----------------------------------------------

Location: drivers/hid/intel-ish-hid/ipc

The IPC message uses memory mapped I/O. The registers are defined in
hw-ish-regs.h.

3.2.1 IPC/FW message types
^^^^^^^^^^^^^^^^^^^^^^^^^^

There are two types of messages, one for management of link and another for
messages to and from transport layers.

TX and RX of Transport messages
...............................

A set of memory mapped register offers support of multi-byte messages TX and
RX (e.g. IPC_REG_ISH2HOST_MSG, IPC_REG_HOST2ISH_MSG). The IPC layer maintains
internal queues to sequence messages and send them in order to the firmware.
Optionally the caller can register handler to get notification of completion.
A doorbell mechanism is used in messaging to trigger processing in host and
client firmware side. When ISH interrupt handler is called, the ISH2HOST
doorbell register is used by host drivers to determine that the interrupt
is for ISH.

Each side has 32 32-bit message registers and a 32-bit doorbell. Doorbell
register has the following format::

  Bits 0..6: fragment length (7 bits are used)
  Bits 10..13: encapsulated protocol
  Bits 16..19: management command (for IPC management protocol)
  Bit 31: doorbell trigger (signal H/W interrupt to the other side)
  Other bits are reserved, should be 0.

3.2.2 Transport layer interface
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

To abstract HW level IPC communication, a set of callbacks is registered.
The transport layer uses them to send and receive messages.
Refer to struct ishtp_hw_ops for callbacks.

3.3 ISH Transport layer
-----------------------

Location: drivers/hid/intel-ish-hid/ishtp/

3.3.1 A Generic Transport Layer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The transport layer is a bi-directional protocol, which defines:
- Set of commands to start, stop, connect, disconnect and flow control
(see ishtp/hbm.h for details)
- A flow control mechanism to avoid buffer overflows

This protocol resembles bus messages described in the following document:
http://www.intel.com/content/dam/www/public/us/en/documents/technical-\
specifications/dcmi-hi-1-0-spec.pdf "Chapter 7: Bus Message Layer"

3.3.2 Connection and Flow Control Mechanism
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Each FW client and a protocol is identified by a UUID. In order to communicate
to a FW client, a connection must be established using connect request and
response bus messages. If successful, a pair (host_client_id and fw_client_id)
will identify the connection.

Once connection is established, peers send each other flow control bus messages
independently. Every peer may send a message only if it has received a
flow-control credit before. Once it has sent a message, it may not send another one
before receiving the next flow control credit.
Either side can send disconnect request bus message to end communication. Also
the link will be dropped if major FW reset occurs.

3.3.3 Peer to Peer data transfer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Peer to Peer data transfer can happen with or without using DMA. Depending on
the sensor bandwidth requirement DMA can be enabled by using module parameter
ishtp_use_dma under intel_ishtp.

Each side (host and FW) manages its DMA transfer memory independently. When an
ISHTP client from either host or FW side wants to send something, it decides
whether to send over IPC or over DMA; for each transfer the decision is
independent. The sending side sends DMA_XFER message when the message is in
the respective host buffer (TX when host client sends, RX when FW client
sends). The recipient of DMA message responds with DMA_XFER_ACK, indicating
the sender that the memory region for that message may be reused.

DMA initialization is started with host sending DMA_ALLOC_NOTIFY bus message
(that includes RX buffer) and FW responds with DMA_ALLOC_NOTIFY_ACK.
Additionally to DMA address communication, this sequence checks capabilities:
if thw host doesn't support DMA, then it won't send DMA allocation, so FW can't
send DMA; if FW doesn't support DMA then it won't respond with
DMA_ALLOC_NOTIFY_ACK, in which case host will not use DMA transfers.
Here ISH acts as busmaster DMA controller. Hence when host sends DMA_XFER,
it's request to do host->ISH DMA transfer; when FW sends DMA_XFER, it means
that it already did DMA and the message resides at host. Thus, DMA_XFER
and DMA_XFER_ACK act as ownership indicators.

At initial state all outgoing memory belongs to the sender (TX to host, RX to
FW), DMA_XFER transfers ownership on the region that contains ISHTP message to
the receiving side, DMA_XFER_ACK returns ownership to the sender. A sender
need not wait for previous DMA_XFER to be ack'ed, and may send another message
as long as remaining continuous memory in its ownership is enough.
In principle, multiple DMA_XFER and DMA_XFER_ACK messages may be sent at once
(up to IPC MTU), thus allowing for interrupt throttling.
Currently, ISH FW decides to send over DMA if ISHTP message is more than 3 IPC
fragments and via IPC otherwise.

3.3.4 Ring Buffers
^^^^^^^^^^^^^^^^^^

When a client initiates a connection, a ring of RX and TX buffers is allocated.
The size of ring can be specified by the client. HID client sets 16 and 32 for
TX and RX buffers respectively. On send request from client, the data to be
sent is copied to one of the send ring buffer and scheduled to be sent using
bus message protocol. These buffers are required because the FW may have not
have processed the last message and may not have enough flow control credits
to send. Same thing holds true on receive side and flow control is required.

3.3.5 Host Enumeration
^^^^^^^^^^^^^^^^^^^^^^

The host enumeration bus command allows discovery of clients present in the FW.
There can be multiple sensor clients and clients for calibration function.

To ease implementation and allow independent drivers to handle each client,
this transport layer takes advantage of Linux Bus driver model. Each
client is registered as device on the transport bus (ishtp bus).

Enumeration sequence of messages:

- Host sends HOST_START_REQ_CMD, indicating that host ISHTP layer is up.
- FW responds with HOST_START_RES_CMD
- Host sends HOST_ENUM_REQ_CMD (enumerate FW clients)
- FW responds with HOST_ENUM_RES_CMD that includes bitmap of available FW
  client IDs
- For each FW ID found in that bitmap host sends
  HOST_CLIENT_PROPERTIES_REQ_CMD
- FW responds with HOST_CLIENT_PROPERTIES_RES_CMD. Properties include UUID,
  max ISHTP message size, etc.
- Once host received properties for that last discovered client, it considers
  ISHTP device fully functional (and allocates DMA buffers)

3.4 HID over ISH Client
-----------------------

Location: drivers/hid/intel-ish-hid

The ISHTP client driver is responsible for:

- enumerate HID devices under FW ISH client
- Get Report descriptor
- Register with HID core as a LL driver
- Process Get/Set feature request
- Get input reports

3.5 HID Sensor Hub MFD and IIO sensor drivers
---------------------------------------------

The functionality in these drivers is the same as an external sensor hub.
Refer to
Documentation/hid/hid-sensor.rst for HID sensor
Documentation/ABI/testing/sysfs-bus-iio for IIO ABIs to user space.

3.6 End to End HID transport Sequence Diagram
---------------------------------------------

::

  HID-ISH-CLN                    ISHTP                    IPC                             HW
          |                        |                       |                               |
          |                        |                       |-----WAKE UP------------------>|
          |                        |                       |                               |
          |                        |                       |-----HOST READY--------------->|
          |                        |                       |                               |
          |                        |                       |<----MNG_RESET_NOTIFY_ACK----- |
          |                        |                       |                               |
          |                        |<----ISHTP_START------ |                               |
          |                        |                       |                               |
          |                        |<-----------------HOST_START_RES_CMD-------------------|
          |                        |                       |                               |
          |                        |------------------QUERY_SUBSCRIBER-------------------->|
          |                        |                       |                               |
          |                        |------------------HOST_ENUM_REQ_CMD------------------->|
          |                        |                       |                               |
          |                        |<-----------------HOST_ENUM_RES_CMD--------------------|
          |                        |                       |                               |
          |                        |------------------HOST_CLIENT_PROPERTIES_REQ_CMD------>|
          |                        |                       |                               |
          |                        |<-----------------HOST_CLIENT_PROPERTIES_RES_CMD-------|
          |       Create new device on in ishtp bus        |                               |
          |                        |                       |                               |
          |                        |------------------HOST_CLIENT_PROPERTIES_REQ_CMD------>|
          |                        |                       |                               |
          |                        |<-----------------HOST_CLIENT_PROPERTIES_RES_CMD-------|
          |       Create new device on in ishtp bus        |                               |
          |                        |                       |                               |
          |                        |--Repeat HOST_CLIENT_PROPERTIES_REQ_CMD-till last one--|
          |                        |                       |                               |
       probed()
          |----ishtp_cl_connect--->|----------------- CLIENT_CONNECT_REQ_CMD-------------->|
          |                        |                       |                               |
          |                        |<----------------CLIENT_CONNECT_RES_CMD----------------|
          |                        |                       |                               |
          |register event callback |                       |                               |
          |                        |                       |                               |
          |ishtp_cl_send(
          HOSTIF_DM_ENUM_DEVICES)  |----------fill ishtp_msg_hdr struct write to HW-----  >|
          |                        |                       |                               |
          |                        |                       |<-----IRQ(IPC_PROTOCOL_ISHTP---|
          |                        |                       |                               |
          |<--ENUM_DEVICE RSP------|                       |                               |
          |                        |                       |                               |
  for each enumerated device
          |ishtp_cl_send(
          HOSTIF_GET_HID_DESCRIPTOR|----------fill ishtp_msg_hdr struct write to HW-----  >|
          |                        |                       |                               |
          ...Response
          |                        |                       |                               |
  for each enumerated device
          |ishtp_cl_send(
       HOSTIF_GET_REPORT_DESCRIPTOR|--------------fill ishtp_msg_hdr struct write to HW-- >|
          |                        |                       |                               |
          |                        |                       |                               |
   hid_allocate_device
          |                        |                       |                               |
   hid_add_device                  |                       |                               |
          |                        |                       |                               |

3.7 ISH Debugging
-----------------

To debug ISH, event tracing mechanism is used. To enable debug logs::

  echo 1 > /sys/kernel/debug/tracing/events/intel_ish/enable
  cat /sys/kernel/debug/tracing/trace

3.8 ISH IIO sysfs Example on Lenovo thinkpad Yoga 260
-----------------------------------------------------

::

  root@otcpl-ThinkPad-Yoga-260:~# tree -l /sys/bus/iio/devices/
  /sys/bus/iio/devices/
  ├── iio:device0 -> ../../../devices/0044:8086:22D8.0001/HID-SENSOR-200073.9.auto/iio:device0
  │   ├── buffer
  │   │   ├── enable
  │   │   ├── length
  │   │   └── watermark
  ...
  │   ├── in_accel_hysteresis
  │   ├── in_accel_offset
  │   ├── in_accel_sampling_frequency
  │   ├── in_accel_scale
  │   ├── in_accel_x_raw
  │   ├── in_accel_y_raw
  │   ├── in_accel_z_raw
  │   ├── name
  │   ├── scan_elements
  │   │   ├── in_accel_x_en
  │   │   ├── in_accel_x_index
  │   │   ├── in_accel_x_type
  │   │   ├── in_accel_y_en
  │   │   ├── in_accel_y_index
  │   │   ├── in_accel_y_type
  │   │   ├── in_accel_z_en
  │   │   ├── in_accel_z_index
  │   │   └── in_accel_z_type
  ...
  │   │   ├── devices
  │   │   │   │   ├── buffer
  │   │   │   │   │   ├── enable
  │   │   │   │   │   ├── length
  │   │   │   │   │   └── watermark
  │   │   │   │   ├── dev
  │   │   │   │   ├── in_intensity_both_raw
  │   │   │   │   ├── in_intensity_hysteresis
  │   │   │   │   ├── in_intensity_offset
  │   │   │   │   ├── in_intensity_sampling_frequency
  │   │   │   │   ├── in_intensity_scale
  │   │   │   │   ├── name
  │   │   │   │   ├── scan_elements
  │   │   │   │   │   ├── in_intensity_both_en
  │   │   │   │   │   ├── in_intensity_both_index
  │   │   │   │   │   └── in_intensity_both_type
  │   │   │   │   ├── trigger
  │   │   │   │   │   └── current_trigger
  ...
  │   │   │   │   ├── buffer
  │   │   │   │   │   ├── enable
  │   │   │   │   │   ├── length
  │   │   │   │   │   └── watermark
  │   │   │   │   ├── dev
  │   │   │   │   ├── in_magn_hysteresis
  │   │   │   │   ├── in_magn_offset
  │   │   │   │   ├── in_magn_sampling_frequency
  │   │   │   │   ├── in_magn_scale
  │   │   │   │   ├── in_magn_x_raw
  │   │   │   │   ├── in_magn_y_raw
  │   │   │   │   ├── in_magn_z_raw
  │   │   │   │   ├── in_rot_from_north_magnetic_tilt_comp_raw
  │   │   │   │   ├── in_rot_hysteresis
  │   │   │   │   ├── in_rot_offset
  │   │   │   │   ├── in_rot_sampling_frequency
  │   │   │   │   ├── in_rot_scale
  │   │   │   │   ├── name
  ...
  │   │   │   │   ├── scan_elements
  │   │   │   │   │   ├── in_magn_x_en
  │   │   │   │   │   ├── in_magn_x_index
  │   │   │   │   │   ├── in_magn_x_type
  │   │   │   │   │   ├── in_magn_y_en
  │   │   │   │   │   ├── in_magn_y_index
  │   │   │   │   │   ├── in_magn_y_type
  │   │   │   │   │   ├── in_magn_z_en
  │   │   │   │   │   ├── in_magn_z_index
  │   │   │   │   │   ├── in_magn_z_type
  │   │   │   │   │   ├── in_rot_from_north_magnetic_tilt_comp_en
  │   │   │   │   │   ├── in_rot_from_north_magnetic_tilt_comp_index
  │   │   │   │   │   └── in_rot_from_north_magnetic_tilt_comp_type
  │   │   │   │   ├── trigger
  │   │   │   │   │   └── current_trigger
  ...
  │   │   │   │   ├── buffer
  │   │   │   │   │   ├── enable
  │   │   │   │   │   ├── length
  │   │   │   │   │   └── watermark
  │   │   │   │   ├── dev
  │   │   │   │   ├── in_anglvel_hysteresis
  │   │   │   │   ├── in_anglvel_offset
  │   │   │   │   ├── in_anglvel_sampling_frequency
  │   │   │   │   ├── in_anglvel_scale
  │   │   │   │   ├── in_anglvel_x_raw
  │   │   │   │   ├── in_anglvel_y_raw
  │   │   │   │   ├── in_anglvel_z_raw
  │   │   │   │   ├── name
  │   │   │   │   ├── scan_elements
  │   │   │   │   │   ├── in_anglvel_x_en
  │   │   │   │   │   ├── in_anglvel_x_index
  │   │   │   │   │   ├── in_anglvel_x_type
  │   │   │   │   │   ├── in_anglvel_y_en
  │   │   │   │   │   ├── in_anglvel_y_index
  │   │   │   │   │   ├── in_anglvel_y_type
  │   │   │   │   │   ├── in_anglvel_z_en
  │   │   │   │   │   ├── in_anglvel_z_index
  │   │   │   │   │   └── in_anglvel_z_type
  │   │   │   │   ├── trigger
  │   │   │   │   │   └── current_trigger
  ...
  │   │   │   │   ├── buffer
  │   │   │   │   │   ├── enable
  │   │   │   │   │   ├── length
  │   │   │   │   │   └── watermark
  │   │   │   │   ├── dev
  │   │   │   │   ├── in_anglvel_hysteresis
  │   │   │   │   ├── in_anglvel_offset
  │   │   │   │   ├── in_anglvel_sampling_frequency
  │   │   │   │   ├── in_anglvel_scale
  │   │   │   │   ├── in_anglvel_x_raw
  │   │   │   │   ├── in_anglvel_y_raw
  │   │   │   │   ├── in_anglvel_z_raw
  │   │   │   │   ├── name
  │   │   │   │   ├── scan_elements
  │   │   │   │   │   ├── in_anglvel_x_en
  │   │   │   │   │   ├── in_anglvel_x_index
  │   │   │   │   │   ├── in_anglvel_x_type
  │   │   │   │   │   ├── in_anglvel_y_en
  │   │   │   │   │   ├── in_anglvel_y_index
  │   │   │   │   │   ├── in_anglvel_y_type
  │   │   │   │   │   ├── in_anglvel_z_en
  │   │   │   │   │   ├── in_anglvel_z_index
  │   │   │   │   │   └── in_anglvel_z_type
  │   │   │   │   ├── trigger
  │   │   │   │   │   └── current_trigger
  ...


code:
======================================================
UHID - User-space I/O driver support for HID subsystem
======================================================

UHID allows user-space to implement HID transport drivers. Please see
hid-transport.rst for an introduction into HID transport drivers. This document
relies heavily on the definitions declared there.

With UHID, a user-space transport driver can create kernel hid-devices for each
device connected to the user-space controlled bus. The UHID API defines the I/O
events provided from the kernel to user-space and vice versa.

There is an example user-space application in ./samples/uhid/uhid-example.c

The UHID API
------------

UHID is accessed through a character misc-device. The minor number is allocated
dynamically so you need to rely on udev (or similar) to create the device node.
This is /dev/uhid by default.

If a new device is detected by your HID I/O Driver and you want to register this
device with the HID subsystem, then you need to open /dev/uhid once for each
device you want to register. All further communication is done by read()'ing or
write()'ing "struct uhid_event" objects. Non-blocking operations are supported
by setting O_NONBLOCK::

  struct uhid_event {
        __u32 type;
        union {
                struct uhid_create2_req create2;
                struct uhid_output_req output;
                struct uhid_input2_req input2;
                ...
        } u;
  };

The "type" field contains the ID of the event. Depending on the ID different
payloads are sent. You must not split a single event across multiple read()'s or
multiple write()'s. A single event must always be sent as a whole. Furthermore,
only a single event can be sent per read() or write(). Pending data is ignored.
If you want to handle multiple events in a single syscall, then use vectored
I/O with readv()/writev().
The "type" field defines the payload. For each type, there is a
payload-structure available in the union "u" (except for empty payloads). This
payload contains management and/or device data.

The first thing you should do is send a UHID_CREATE2 event. This will
register the device. UHID will respond with a UHID_START event. You can now
start sending data to and reading data from UHID. However, unless UHID sends the
UHID_OPEN event, the internally attached HID Device Driver has no user attached.
That is, you might put your device asleep unless you receive the UHID_OPEN
event. If you receive the UHID_OPEN event, you should start I/O. If the last
user closes the HID device, you will receive a UHID_CLOSE event. This may be
followed by a UHID_OPEN event again and so on. There is no need to perform
reference-counting in user-space. That is, you will never receive multiple
UHID_OPEN events without a UHID_CLOSE event. The HID subsystem performs
ref-counting for you.
You may decide to ignore UHID_OPEN/UHID_CLOSE, though. I/O is allowed even
though the device may have no users.

If you want to send data on the interrupt channel to the HID subsystem, you send
a HID_INPUT2 event with your raw data payload. If the kernel wants to send data
on the interrupt channel to the device, you will read a UHID_OUTPUT event.
Data requests on the control channel are currently limited to GET_REPORT and
SET_REPORT (no other data reports on the control channel are defined so far).
Those requests are always synchronous. That means, the kernel sends
UHID_GET_REPORT and UHID_SET_REPORT events and requires you to forward them to
the device on the control channel. Once the device responds, you must forward
the response via UHID_GET_REPORT_REPLY and UHID_SET_REPORT_REPLY to the kernel.
The kernel blocks internal driver-execution during such round-trips (times out
after a hard-coded period).

If your device disconnects, you should send a UHID_DESTROY event. This will
unregister the device. You can now send UHID_CREATE2 again to register a new
device.
If you close() the fd, the device is automatically unregistered and destroyed
internally.

write()
-------
write() allows you to modify the state of the device and feed input data into
the kernel. The kernel will parse the event immediately and if the event ID is
not supported, it will return -EOPNOTSUPP. If the payload is invalid, then
-EINVAL is returned, otherwise, the amount of data that was read is returned and
the request was handled successfully. O_NONBLOCK does not affect write() as
writes are always handled immediately in a non-blocking fashion. Future requests
might make use of O_NONBLOCK, though.

UHID_CREATE2:
  This creates the internal HID device. No I/O is possible until you send this
  event to the kernel. The payload is of type struct uhid_create2_req and
  contains information about your device. You can start I/O now.

UHID_DESTROY:
  This destroys the internal HID device. No further I/O will be accepted. There
  may still be pending messages that you can receive with read() but no further
  UHID_INPUT events can be sent to the kernel.
  You can create a new device by sending UHID_CREATE2 again. There is no need to
  reopen the character device.

UHID_INPUT2:
  You must send UHID_CREATE2 before sending input to the kernel! This event
  contains a data-payload. This is the raw data that you read from your device
  on the interrupt channel. The kernel will parse the HID reports.

UHID_GET_REPORT_REPLY:
  If you receive a UHID_GET_REPORT request you must answer with this request.
  You  must copy the "id" field from the request into the answer. Set the "err"
  field to 0 if no error occurred or to EIO if an I/O error occurred.
  If "err" is 0 then you should fill the buffer of the answer with the results
  of the GET_REPORT request and set "size" correspondingly.

UHID_SET_REPORT_REPLY:
  This is the SET_REPORT equivalent of UHID_GET_REPORT_REPLY. Unlike GET_REPORT,
  SET_REPORT never returns a data buffer, therefore, it's sufficient to set the
  "id" and "err" fields correctly.

read()
------
read() will return a queued output report. No reaction is required to any of
them but you should handle them according to your needs.

UHID_START:
  This is sent when the HID device is started. Consider this as an answer to
  UHID_CREATE2. This is always the first event that is sent. Note that this
  event might not be available immediately after write(UHID_CREATE2) returns.
  Device drivers might require delayed setups.
  This event contains a payload of type uhid_start_req. The "dev_flags" field
  describes special behaviors of a device. The following flags are defined:

      - UHID_DEV_NUMBERED_FEATURE_REPORTS
      - UHID_DEV_NUMBERED_OUTPUT_REPORTS
      - UHID_DEV_NUMBERED_INPUT_REPORTS

          Each of these flags defines whether a given report-type uses numbered
          reports. If numbered reports are used for a type, all messages from
          the kernel already have the report-number as prefix. Otherwise, no
          prefix is added by the kernel.
          For messages sent by user-space to the kernel, you must adjust the
          prefixes according to these flags.

UHID_STOP:
  This is sent when the HID device is stopped. Consider this as an answer to
  UHID_DESTROY.

  If you didn't destroy your device via UHID_DESTROY, but the kernel sends an
  UHID_STOP event, this should usually be ignored. It means that the kernel
  reloaded/changed the device driver loaded on your HID device (or some other
  maintenance actions happened).

  You can usually ignore any UHID_STOP events safely.

UHID_OPEN:
  This is sent when the HID device is opened. That is, the data that the HID
  device provides is read by some other process. You may ignore this event but
  it is useful for power-management. As long as you haven't received this event
  there is actually no other process that reads your data so there is no need to
  send UHID_INPUT2 events to the kernel.

UHID_CLOSE:
  This is sent when there are no more processes which read the HID data. It is
  the counterpart of UHID_OPEN and you may as well ignore this event.

UHID_OUTPUT:
  This is sent if the HID device driver wants to send raw data to the I/O
  device on the interrupt channel. You should read the payload and forward it to
  the device. The payload is of type "struct uhid_output_req".
  This may be received even though you haven't received UHID_OPEN yet.

UHID_GET_REPORT:
  This event is sent if the kernel driver wants to perform a GET_REPORT request
  on the control channel as described in the HID specs. The report-type and
  report-number are available in the payload.
  The kernel serializes GET_REPORT requests so there will never be two in
  parallel. However, if you fail to respond with a UHID_GET_REPORT_REPLY, the
  request might silently time out.
  Once you read a GET_REPORT request, you shall forward it to the HID device and
  remember the "id" field in the payload. Once your HID device responds to the
  GET_REPORT (or if it fails), you must send a UHID_GET_REPORT_REPLY to the
  kernel with the exact same "id" as in the request. If the request already
  timed out, the kernel will ignore the response silently. The "id" field is
  never re-used, so conflicts cannot happen.

UHID_SET_REPORT:
  This is the SET_REPORT equivalent of UHID_GET_REPORT. On receipt, you shall
  send a SET_REPORT request to your HID device. Once it replies, you must tell
  the kernel about it via UHID_SET_REPORT_REPLY.
  The same restrictions as for UHID_GET_REPORT apply.

----------------------------------------------------

Written 2012, David Herrmann <dh.herrmann@gmail.com>


code:
===============
uGuru datasheet
===============

First of all, what I know about uGuru is no fact based on any help, hints or
datasheet from Abit. The data I have got on uGuru have I assembled through
my weak knowledge in "backwards engineering".
And just for the record, you may have noticed uGuru isn't a chip developed by
Abit, as they claim it to be. It's really just an microprocessor (uC) created by
Winbond (W83L950D). And no, reading the manual for this specific uC or
mailing  Windbond for help won't give any useful data about uGuru, as it is
the program inside the uC that is responding to calls.

Olle Sandberg <ollebull@gmail.com>, 2005-05-25

Original version by Olle Sandberg who did the heavy lifting of the initial
reverse engineering. This version has been almost fully rewritten for clarity
and extended with write support and info on more databanks, the write support
is once again reverse engineered by Olle the additional databanks have been
reverse engineered by me. I would like to express my thanks to Olle, this
document and the Linux driver could not have been written without his efforts.

Note: because of the lack of specs only the sensors part of the uGuru is
described here and not the CPU / RAM / etc voltage & frequency control.

Hans de Goede <j.w.r.degoede@hhs.nl>, 28-01-2006

Detection
=========

As far as known the uGuru is always placed at and using the (ISA) I/O-ports
0xE0 and 0xE4, so we don't have to scan any port-range, just check what the two
ports are holding for detection. We will refer to 0xE0 as CMD (command-port)
and 0xE4 as DATA because Abit refers to them with these names.

If DATA holds 0x00 or 0x08 and CMD holds 0x00 or 0xAC an uGuru could be
present. We have to check for two different values at data-port, because
after a reboot uGuru will hold 0x00 here, but if the driver is removed and
later on attached again data-port will hold 0x08, more about this later.

After wider testing of the Linux kernel driver some variants of the uGuru have
turned up which will hold 0x00 instead of 0xAC at the CMD port, thus we also
have to test CMD for two different values. On these uGuru's DATA will initially
hold 0x09 and will only hold 0x08 after reading CMD first, so CMD must be read
first!

To be really sure an uGuru is present a test read of one or more register
sets should be done.

Reading / Writing
=================

Addressing
----------

The uGuru has a number of different addressing levels. The first addressing
level we will call banks. A bank holds data for one or more sensors. The data
in a bank for a sensor is one or more bytes large.

The number of bytes is fixed for a given bank, you should always read or write
that many bytes, reading / writing more will fail, the results when writing
less then the number of bytes for a given bank are undetermined.

See below for all known bank addresses, numbers of sensors in that bank,
number of bytes data per sensor and contents/meaning of those bytes.

Although both this document and the kernel driver have kept the sensor
terminology for the addressing within a bank this is not 100% correct, in
bank 0x24 for example the addressing within the bank selects a PWM output not
a sensor.

Notice that some banks have both a read and a write address this is how the
uGuru determines if a read from or a write to the bank is taking place, thus
when reading you should always use the read address and when writing the
write address. The write address is always one (1) more than the read address.

uGuru ready
-----------

Before you can read from or write to the uGuru you must first put the uGuru
in "ready" mode.

To put the uGuru in ready mode first write 0x00 to DATA and then wait for DATA
to hold 0x09, DATA should read 0x09 within 250 read cycles.

Next CMD _must_ be read and should hold 0xAC, usually CMD will hold 0xAC the
first read but sometimes it takes a while before CMD holds 0xAC and thus it
has to be read a number of times (max 50).

After reading CMD, DATA should hold 0x08 which means that the uGuru is ready
for input. As above DATA will usually hold 0x08 the first read but not always.
This step can be skipped, but it is undetermined what happens if the uGuru has
not yet reported 0x08 at DATA and you proceed with writing a bank address.

Sending bank and sensor addresses to the uGuru
----------------------------------------------

First the uGuru must be in "ready" mode as described above, DATA should hold
0x08 indicating that the uGuru wants input, in this case the bank address.

Next write the bank address to DATA. After the bank address has been written
wait for to DATA to hold 0x08 again indicating that it wants / is ready for
more input (max 250 reads).

Once DATA holds 0x08 again write the sensor address to CMD.

Reading
-------

First send the bank and sensor addresses as described above.
Then for each byte of data you want to read wait for DATA to hold 0x01
which indicates that the uGuru is ready to be read (max 250 reads) and once
DATA holds 0x01 read the byte from CMD.

Once all bytes have been read data will hold 0x09, but there is no reason to
test for this. Notice that the number of bytes is bank address dependent see
above and below.

After completing a successful read it is advised to put the uGuru back in
ready mode, so that it is ready for the next read / write cycle. This way
if your program / driver is unloaded and later loaded again the detection
algorithm described above will still work.

Writing
-------

First send the bank and sensor addresses as described above.
Then for each byte of data you want to write wait for DATA to hold 0x00
which indicates that the uGuru is ready to be written (max 250 reads) and
once DATA holds 0x00 write the byte to CMD.

Once all bytes have been written wait for DATA to hold 0x01 (max 250 reads)
don't ask why this is the way it is.

Once DATA holds 0x01 read CMD it should hold 0xAC now.

After completing a successful write it is advised to put the uGuru back in
ready mode, so that it is ready for the next read / write cycle. This way
if your program / driver is unloaded and later loaded again the detection
algorithm described above will still work.

Gotchas
-------

After wider testing of the Linux kernel driver some variants of the uGuru have
turned up which do not hold 0x08 at DATA within 250 reads after writing the
bank address. With these versions this happens quite frequent, using larger
timeouts doesn't help, they just go offline for a second or 2, doing some
internal calibration or whatever. Your code should be prepared to handle
this and in case of no response in this specific case just goto sleep for a
while and then retry.

Address Map
===========

Bank 0x20 Alarms (R)
--------------------
This bank contains 0 sensors, iow the sensor address is ignored (but must be
written) just use 0. Bank 0x20 contains 3 bytes:

Byte 0:
  This byte holds the alarm flags for sensor 0-7 of Sensor Bank1, with bit 0
  corresponding to sensor 0, 1 to 1, etc.

Byte 1:
  This byte holds the alarm flags for sensor 8-15 of Sensor Bank1, with bit 0
  corresponding to sensor 8, 1 to 9, etc.

Byte 2:
  This byte holds the alarm flags for sensor 0-5 of Sensor Bank2, with bit 0
  corresponding to sensor 0, 1 to 1, etc.

Bank 0x21 Sensor Bank1 Values / Readings (R)
--------------------------------------------
This bank contains 16 sensors, for each sensor it contains 1 byte.
So far the following sensors are known to be available on all motherboards:

- Sensor  0 CPU temp
- Sensor  1 SYS temp
- Sensor  3 CPU core volt
- Sensor  4 DDR volt
- Sensor 10 DDR Vtt volt
- Sensor 15 PWM temp

Byte 0:
  This byte holds the reading from the sensor. Sensors in Bank1 can be both
  volt and temp sensors, this is motherboard specific. The uGuru however does
  seem to know (be programmed with) what kindoff sensor is attached see Sensor
  Bank1 Settings description.

Volt sensors use a linear scale, a reading 0 corresponds with 0 volt and a
reading of 255 with 3494 mV. The sensors for higher voltages however are
connected through a division circuit. The currently known division circuits
in use result in ranges of: 0-4361mV, 0-6248mV or 0-14510mV. 3.3 volt sources
use the 0-4361mV range, 5 volt the 0-6248mV and 12 volt the 0-14510mV .

Temp sensors also use a linear scale, a reading of 0 corresponds with 0 degree
Celsius and a reading of 255 with a reading of 255 degrees Celsius.

Bank 0x22 Sensor Bank1 Settings (R) and Bank 0x23 Sensor Bank1 Settings (W)
---------------------------------------------------------------------------

Those banks contain 16 sensors, for each sensor it contains 3 bytes. Each
set of 3 bytes contains the settings for the sensor with the same sensor
address in Bank 0x21 .

Byte 0:
  Alarm behaviour for the selected sensor. A 1 enables the described
  behaviour.

Bit 0:
  Give an alarm if measured temp is over the warning threshold		(RW) [1]_

Bit 1:
  Give an alarm if measured volt is over the max threshold		(RW) [2]_

Bit 2:
  Give an alarm if measured volt is under the min threshold		(RW) [2]_

Bit 3:
  Beep if alarm								(RW)

Bit 4:
  1 if alarm cause measured temp is over the warning threshold		(R)

Bit 5:
  1 if alarm cause measured volt is over the max threshold		(R)

Bit 6:
  1 if alarm cause measured volt is under the min threshold		(R)

Bit 7:
  - Volt sensor: Shutdown if alarm persist for more than 4 seconds	(RW)
  - Temp sensor: Shutdown if temp is over the shutdown threshold	(RW)

.. [1] This bit is only honored/used by the uGuru if a temp sensor is connected

.. [2] This bit is only honored/used by the uGuru if a volt sensor is connected
       Note with some trickery this can be used to find out what kinda sensor
       is detected see the Linux kernel driver for an example with many
       comments on how todo this.

Byte 1:
  - Temp sensor: warning threshold  (scale as bank 0x21)
  - Volt sensor: min threshold      (scale as bank 0x21)

Byte 2:
  - Temp sensor: shutdown threshold (scale as bank 0x21)
  - Volt sensor: max threshold      (scale as bank 0x21)

Bank 0x24 PWM outputs for FAN's (R) and Bank 0x25 PWM outputs for FAN's (W)
---------------------------------------------------------------------------

Those banks contain 3 "sensors", for each sensor it contains 5 bytes.
  - Sensor 0 usually controls the CPU fan
  - Sensor 1 usually controls the NB (or chipset for single chip) fan
  - Sensor 2 usually controls the System fan

Byte 0:
  Flag 0x80 to enable control, Fan runs at 100% when disabled.
  low nibble (temp)sensor address at bank 0x21 used for control.

Byte 1:
  0-255 = 0-12v (linear), specify voltage at which fan will rotate when under
  low threshold temp (specified in byte 3)

Byte 2:
  0-255 = 0-12v (linear), specify voltage at which fan will rotate when above
  high threshold temp (specified in byte 4)

Byte 3:
  Low threshold temp  (scale as bank 0x21)

byte 4:
  High threshold temp (scale as bank 0x21)

Bank 0x26 Sensors Bank2 Values / Readings (R)
---------------------------------------------

This bank contains 6 sensors (AFAIK), for each sensor it contains 1 byte.

So far the following sensors are known to be available on all motherboards:
  - Sensor 0: CPU fan speed
  - Sensor 1: NB (or chipset for single chip) fan speed
  - Sensor 2: SYS fan speed

Byte 0:
  This byte holds the reading from the sensor. 0-255 = 0-15300 (linear)

Bank 0x27 Sensors Bank2 Settings (R) and Bank 0x28 Sensors Bank2 Settings (W)
-----------------------------------------------------------------------------

Those banks contain 6 sensors (AFAIK), for each sensor it contains 2 bytes.

Byte 0:
  Alarm behaviour for the selected sensor. A 1 enables the described behaviour.

Bit 0:
  Give an alarm if measured rpm is under the min threshold	(RW)

Bit 3:
  Beep if alarm							(RW)

Bit 7:
  Shutdown if alarm persist for more than 4 seconds		(RW)

Byte 1:
  min threshold (scale as bank 0x26)

Warning for the adventurous
===========================

A word of caution to those who want to experiment and see if they can figure
the voltage / clock programming out, I tried reading and only reading banks
0-0x30 with the reading code used for the sensor banks (0x20-0x28) and this
resulted in a _permanent_ reprogramming of the voltages, luckily I had the
sensors part configured so that it would shutdown my system on any out of spec
voltages which probably safed my computer (after a reboot I managed to
immediately enter the bios and reload the defaults). This probably means that
the read/write cycle for the non sensor part is different from the sensor part.


code:
Kernel driver abituguru
=======================

Supported chips:

  * Abit uGuru revision 1 & 2 (Hardware Monitor part only)

    Prefix: 'abituguru'

    Addresses scanned: ISA 0x0E0

    Datasheet: Not available, this driver is based on reverse engineering.
    A "Datasheet" has been written based on the reverse engineering it
    should be available in the same dir as this file under the name
    abituguru-datasheet.

    Note:
	The uGuru is a microcontroller with onboard firmware which programs
	it to behave as a hwmon IC. There are many different revisions of the
	firmware and thus effectively many different revisions of the uGuru.
	Below is an incomplete list with which revisions are used for which
	Motherboards:

	- uGuru 1.00    ~ 1.24    (AI7, KV8-MAX3, AN7) [1]_
	- uGuru 2.0.0.0 ~ 2.0.4.2 (KV8-PRO)
	- uGuru 2.1.0.0 ~ 2.1.2.8 (AS8, AV8, AA8, AG8, AA8XE, AX8)
	- uGuru 2.2.0.0 ~ 2.2.0.6 (AA8 Fatal1ty)
	- uGuru 2.3.0.0 ~ 2.3.0.9 (AN8)
	- uGuru 3.0.0.0 ~ 3.0.x.x (AW8, AL8, AT8, NI8 SLI, AT8 32X, AN8 32X,
	  AW9D-MAX) [2]_

.. [1]  For revisions 2 and 3 uGuru's the driver can autodetect the
	sensortype (Volt or Temp) for bank1 sensors, for revision 1 uGuru's
	this does not always work. For these uGuru's the autodetection can
	be overridden with the bank1_types module param. For all 3 known
	revision 1 motherboards the correct use of this param is:
	bank1_types=1,1,0,0,0,0,0,2,0,0,0,0,2,0,0,1
	You may also need to specify the fan_sensors option for these boards
	fan_sensors=5

.. [2]  There is a separate abituguru3 driver for these motherboards,
	the abituguru (without the 3 !) driver will not work on these
	motherboards (and visa versa)!

Authors:
	- Hans de Goede <j.w.r.degoede@hhs.nl>,
	- (Initial reverse engineering done by Olle Sandberg
	  <ollebull@gmail.com>)

Module Parameters
-----------------

* force: bool
			Force detection. Note this parameter only causes the
			detection to be skipped, and thus the insmod to
			succeed. If the uGuru can't be read the actual hwmon
			driver will not load and thus no hwmon device will get
			registered.
* bank1_types: int[]
			Bank1 sensortype autodetection override:

			  * -1 autodetect (default)
			  *  0 volt sensor
			  *  1 temp sensor
			  *  2 not connected
* fan_sensors: int
			Tell the driver how many fan speed sensors there are
			on your motherboard. Default: 0 (autodetect).
* pwms: int
			Tell the driver how many fan speed controls (fan
			pwms) your motherboard has. Default: 0 (autodetect).
* verbose: int
			How verbose should the driver be? (0-3):

			   * 0 normal output
			   * 1 + verbose error reporting
			   * 2 + sensors type probing info (default)
			   * 3 + retryable error reporting

			Default: 2 (the driver is still in the testing phase)

Notice: if you need any of the first three options above please insmod the
driver with verbose set to 3 and mail me <j.w.r.degoede@hhs.nl> the output of:
dmesg | grep abituguru

Description
-----------

This driver supports the hardware monitoring features of the first and
second revision of the Abit uGuru chip found on Abit uGuru featuring
motherboards (most modern Abit motherboards).

The first and second revision of the uGuru chip in reality is a Winbond
W83L950D in disguise (despite Abit claiming it is "a new microprocessor
designed by the ABIT Engineers"). Unfortunately this doesn't help since the
W83L950D is a generic microcontroller with a custom Abit application running
on it.

Despite Abit not releasing any information regarding the uGuru, Olle
Sandberg <ollebull@gmail.com> has managed to reverse engineer the sensor part
of the uGuru. Without his work this driver would not have been possible.

Known Issues
------------

The voltage and frequency control parts of the Abit uGuru are not supported.

.. toctree::
   :maxdepth: 1

   abituguru-datasheet.rst


code:
Kernel driver abituguru3
========================

Supported chips:
  * Abit uGuru revision 3 (Hardware Monitor part, reading only)

    Prefix: 'abituguru3'

    Addresses scanned: ISA 0x0E0

    Datasheet: Not available, this driver is based on reverse engineering.

    Note:
	The uGuru is a microcontroller with onboard firmware which programs
	it to behave as a hwmon IC. There are many different revisions of the
	firmware and thus effectively many different revisions of the uGuru.
	Below is an incomplete list with which revisions are used for which
	Motherboards:

	- uGuru 1.00    ~ 1.24    (AI7, KV8-MAX3, AN7)
	- uGuru 2.0.0.0 ~ 2.0.4.2 (KV8-PRO)
	- uGuru 2.1.0.0 ~ 2.1.2.8 (AS8, AV8, AA8, AG8, AA8XE, AX8)
	- uGuru 2.3.0.0 ~ 2.3.0.9 (AN8)
	- uGuru 3.0.0.0 ~ 3.0.x.x (AW8, AL8, AT8, NI8 SLI, AT8 32X, AN8 32X,
	  AW9D-MAX)

	The abituguru3 driver is only for revision 3.0.x.x motherboards,
	this driver will not work on older motherboards. For older
	motherboards use the abituguru (without the 3 !) driver.

Authors:
	- Hans de Goede <j.w.r.degoede@hhs.nl>,
	- (Initial reverse engineering done by Louis Kruger)

Module Parameters
-----------------

* force: bool
			Force detection. Note this parameter only causes the
			detection to be skipped, and thus the insmod to
			succeed. If the uGuru can't be read the actual hwmon
			driver will not load and thus no hwmon device will get
			registered.
* verbose: bool
			Should the driver be verbose?

			* 0/off/false  normal output
			* 1/on/true    + verbose error reporting (default)

			Default: 1 (the driver is still in the testing phase)

Description
-----------

This driver supports the hardware monitoring features of the third revision of
the Abit uGuru chip, found on recent Abit uGuru featuring motherboards.

The 3rd revision of the uGuru chip in reality is a Winbond W83L951G.
Unfortunately this doesn't help since the W83L951G is a generic microcontroller
with a custom Abit application running on it.

Despite Abit not releasing any information regarding the uGuru revision 3,
Louis Kruger has managed to reverse engineer the sensor part of the uGuru.
Without his work this driver would not have been possible.

Known Issues
------------

The voltage and frequency control parts of the Abit uGuru are not supported,
neither is writing any of the sensor settings and writing / reading the
fanspeed control registers (FanEQ)

If you encounter any problems please mail me <j.w.r.degoede@hhs.nl> and
include the output of: `dmesg | grep abituguru`


code:
Kernel driver power_meter
=========================

This driver talks to ACPI 4.0 power meters.

Supported systems:

  * Any recent system with ACPI 4.0.

    Prefix: 'power_meter'

    Datasheet: https://uefi.org/specifications, section 10.4.

Author: Darrick J. Wong

Description
-----------

This driver implements sensor reading support for the power meters exposed in
the ACPI 4.0 spec (Chapter 10.4).  These devices have a simple set of
features--a power meter that returns average power use over a configurable
interval, an optional capping mechanism, and a couple of trip points.  The
sysfs interface conforms with the specification outlined in the "Power" section
of Documentation/hwmon/sysfs-interface.rst.

Special Features
----------------

The `power[1-*]_is_battery` knob indicates if the power supply is a battery.
Both `power[1-*]_average_{min,max}` must be set before the trip points will work.
When both of them are set, an ACPI event will be broadcast on the ACPI netlink
socket and a poll notification will be sent to the appropriate
`power[1-*]_average` sysfs file.

The `power[1-*]_{model_number, serial_number, oem_info}` fields display
arbitrary strings that ACPI provides with the meter.  The measures/ directory
contains symlinks to the devices that this meter measures.

Some computers have the ability to enforce a power cap in hardware.  If this is
the case, the `power[1-*]_cap` and related sysfs files will appear.  When the
average power consumption exceeds the cap, an ACPI event will be broadcast on
the netlink event socket and a poll notification will be sent to the
appropriate `power[1-*]_alarm` file to indicate that capping has begun, and the
hardware has taken action to reduce power consumption.  Most likely this will
result in reduced performance.

There are a few other ACPI notifications that can be sent by the firmware.  In
all cases the ACPI event will be broadcast on the ACPI netlink event socket as
well as sent as a poll notification to a sysfs file.  The events are as
follows:

`power[1-*]_cap` will be notified if the firmware changes the power cap.
`power[1-*]_interval` will be notified if the firmware changes the averaging
interval.


code:
Kernel driver ad7314
====================

Supported chips:

   * Analog Devices AD7314

     Prefix: 'ad7314'

     Datasheet: Publicly available at Analog Devices website.

   * Analog Devices ADT7301

     Prefix: 'adt7301'

     Datasheet: Publicly available at Analog Devices website.

   * Analog Devices ADT7302

     Prefix: 'adt7302'

     Datasheet: Publicly available at Analog Devices website.

Description
-----------

Driver supports the above parts.  The ad7314 has a 10 bit
sensor with 1lsb = 0.25 degrees centigrade. The adt7301 and
adt7302 have 14 bit sensors with 1lsb = 0.03125 degrees centigrade.

Notes
-----

Currently power down mode is not supported.


code:
Kernel driver adc128d818
========================

Supported chips:

  * Texas Instruments ADC818D818

    Prefix: 'adc818d818'

    Addresses scanned: I2C 0x1d, 0x1e, 0x1f, 0x2d, 0x2e, 0x2f

    Datasheet: Publicly available at the TI website https://www.ti.com/

Author: Guenter Roeck

Description
-----------

This driver implements support for the Texas Instruments ADC128D818.
It is described as 'ADC System Monitor with Temperature Sensor'.

The ADC128D818 implements one temperature sensor and seven voltage sensors.

Temperatures are measured in degrees Celsius. There is one set of limits.
When the HOT Temperature Limit is crossed, this will cause an alarm that will
be reasserted until the temperature drops below the HOT Hysteresis.
Measurements are guaranteed between -55 and +125 degrees. The temperature
measurement has a resolution of 0.5 degrees; the limits have a resolution
of 1 degree.

Voltage sensors (also known as IN sensors) report their values in volts.
An alarm is triggered if the voltage has crossed a programmable minimum
or maximum limit. Note that minimum in this case always means 'closest to
zero'; this is important for negative voltage measurements. All voltage
inputs can measure voltages between 0 and 2.55 volts, with a resolution
of 0.625 mV.

If an alarm triggers, it will remain triggered until the hardware register
is read at least once. This means that the cause for the alarm may
already have disappeared by the time the alarm is read. The driver
caches the alarm status for each sensor until it is at least reported
once, to ensure that alarms are reported to user space.

The ADC128D818 only updates its values approximately once per second;
reading it more often will do no harm, but will return 'old' values.

In addition to the scanned address list, the chip can also be configured for
addresses 0x35 to 0x37. Those addresses are not scanned. You have to instantiate
the driver explicitly if the chip is configured for any of those addresses in
your system.


code:
Kernel driver adm1021
=====================

Supported chips:

  * Analog Devices ADM1021

    Prefix: 'adm1021'

    Addresses scanned: I2C 0x18 - 0x1a, 0x29 - 0x2b, 0x4c - 0x4e

    Datasheet: Publicly available at the Analog Devices website

  * Analog Devices ADM1021A/ADM1023

    Prefix: 'adm1023'

    Addresses scanned: I2C 0x18 - 0x1a, 0x29 - 0x2b, 0x4c - 0x4e

    Datasheet: Publicly available at the Analog Devices website

  * Genesys Logic GL523SM

    Prefix: 'gl523sm'

    Addresses scanned: I2C 0x18 - 0x1a, 0x29 - 0x2b, 0x4c - 0x4e

    Datasheet:

  * Maxim MAX1617

    Prefix: 'max1617'

    Addresses scanned: I2C 0x18 - 0x1a, 0x29 - 0x2b, 0x4c - 0x4e

    Datasheet: Publicly available at the Maxim website

  * Maxim MAX1617A

    Prefix: 'max1617a'

    Addresses scanned: I2C 0x18 - 0x1a, 0x29 - 0x2b, 0x4c - 0x4e

    Datasheet: Publicly available at the Maxim website

  * National Semiconductor LM84

    Prefix: 'lm84'

    Addresses scanned: I2C 0x18 - 0x1a, 0x29 - 0x2b, 0x4c - 0x4e

    Datasheet: Publicly available at the National Semiconductor website

  * Philips NE1617

    Prefix: 'max1617' (probably detected as a max1617)

    Addresses scanned: I2C 0x18 - 0x1a, 0x29 - 0x2b, 0x4c - 0x4e

    Datasheet: Publicly available at the Philips website

  * Philips NE1617A

    Prefix: 'max1617' (probably detected as a max1617)

    Addresses scanned: I2C 0x18 - 0x1a, 0x29 - 0x2b, 0x4c - 0x4e

    Datasheet: Publicly available at the Philips website

  * TI THMC10

    Prefix: 'thmc10'

    Addresses scanned: I2C 0x18 - 0x1a, 0x29 - 0x2b, 0x4c - 0x4e

    Datasheet: Publicly available at the TI website

  * Onsemi MC1066

    Prefix: 'mc1066'

    Addresses scanned: I2C 0x18 - 0x1a, 0x29 - 0x2b, 0x4c - 0x4e

    Datasheet: Publicly available at the Onsemi website

Authors:
	- Frodo Looijaard <frodol@dds.nl>,
	- Philip Edelbrock <phil@netroedge.com>

Module Parameters
-----------------

* read_only: int
  Don't set any values, read only mode

Description
-----------

The chips supported by this driver are very similar. The Maxim MAX1617 is
the oldest; it has the problem that it is not very well detectable. The
MAX1617A solves that. The ADM1021 is a straight clone of the MAX1617A.
Ditto for the THMC10. From here on, we will refer to all these chips as
ADM1021-clones.

The ADM1021 and MAX1617A reports a die code, which is a sort of revision
code. This can help us pinpoint problems; it is not very useful
otherwise.

ADM1021-clones implement two temperature sensors. One of them is internal,
and measures the temperature of the chip itself; the other is external and
is realised in the form of a transistor-like device. A special alarm
indicates whether the remote sensor is connected.

Each sensor has its own low and high limits. When they are crossed, the
corresponding alarm is set and remains on as long as the temperature stays
out of range. Temperatures are measured in degrees Celsius. Measurements
are possible between -65 and +127 degrees, with a resolution of one degree.

If an alarm triggers, it will remain triggered until the hardware register
is read at least once. This means that the cause for the alarm may already
have disappeared!

This driver only updates its values each 1.5 seconds; reading it more often
will do no harm, but will return 'old' values. It is possible to make
ADM1021-clones do faster measurements, but there is really no good reason
for that.

Netburst-based Xeon support
---------------------------

Some Xeon processors based on the Netburst (early Pentium 4, from 2001 to
2003) microarchitecture had real MAX1617, ADM1021, or compatible chips
within them, with two temperature sensors. Other Xeon processors of this
era (with 400 MHz FSB) had chips with only one temperature sensor.

If you have such an old Xeon, and you get two valid temperatures when
loading the adm1021 module, then things are good.

If nothing happens when loading the adm1021 module, and you are certain
that your specific Xeon processor model includes compatible sensors, you
will have to explicitly instantiate the sensor chips from user-space. See
method 4 in Documentation/i2c/instantiating-devices.rst. Possible slave
addresses are 0x18, 0x1a, 0x29, 0x2b, 0x4c, or 0x4e. It is likely that
only temp2 will be correct and temp1 will have to be ignored.

Previous generations of the Xeon processor (based on Pentium II/III)
didn't have these sensors. Next generations of Xeon processors (533 MHz
FSB and faster) lost them, until the Core-based generation which
introduced integrated digital thermal sensors. These are supported by
the coretemp driver.


code:
Kernel driver adm1025
=====================

Supported chips:

  * Analog Devices ADM1025, ADM1025A

    Prefix: 'adm1025'

    Addresses scanned: I2C 0x2c - 0x2e

    Datasheet: Publicly available at the Analog Devices website

  * Philips NE1619

    Prefix: 'ne1619'

    Addresses scanned: I2C 0x2c - 0x2d

    Datasheet: Publicly available at the Philips website

The NE1619 presents some differences with the original ADM1025:

  * Only two possible addresses (0x2c - 0x2d).
  * No temperature offset register, but we don't use it anyway.
  * No INT mode for pin 16. We don't play with it anyway.

Authors:
	- Chen-Yuan Wu <gwu@esoft.com>,
	- Jean Delvare <jdelvare@suse.de>

Description
-----------

(This is from Analog Devices.) The ADM1025 is a complete system hardware
monitor for microprocessor-based systems, providing measurement and limit
comparison of various system parameters. Five voltage measurement inputs
are provided, for monitoring +2.5V, +3.3V, +5V and +12V power supplies and
the processor core voltage. The ADM1025 can monitor a sixth power-supply
voltage by measuring its own VCC. One input (two pins) is dedicated to a
remote temperature-sensing diode and an on-chip temperature sensor allows
ambient temperature to be monitored.

One specificity of this chip is that the pin 11 can be hardwired in two
different manners. It can act as the +12V power-supply voltage analog
input, or as the a fifth digital entry for the VID reading (bit 4). It's
kind of strange since both are useful, and the reason for designing the
chip that way is obscure at least to me. The bit 5 of the configuration
register can be used to define how the chip is hardwired. Please note that
it is not a choice you have to make as the user. The choice was already
made by your motherboard's maker. If the configuration bit isn't set
properly, you'll have a wrong +12V reading or a wrong VID reading. The way
the driver handles that is to preserve this bit through the initialization
process, assuming that the BIOS set it up properly beforehand. If it turns
out not to be true in some cases, we'll provide a module parameter to force
modes.

This driver also supports the ADM1025A, which differs from the ADM1025
only in that it has "open-drain VID inputs while the ADM1025 has on-chip
100k pull-ups on the VID inputs". It doesn't make any difference for us.


code:
Kernel driver adm1026
=====================

Supported chips:
  * Analog Devices ADM1026

    Prefix: 'adm1026'

    Addresses scanned: I2C 0x2c, 0x2d, 0x2e

    Datasheet: Publicly available at the Analog Devices website

	       https://www.onsemi.com/PowerSolutions/product.do?id=ADM1026

Authors:
	- Philip Pokorny <ppokorny@penguincomputing.com> for Penguin Computing
	- Justin Thiessen <jthiessen@penguincomputing.com>

Module Parameters
-----------------

* gpio_input: int array (min = 1, max = 17)
    List of GPIO pins (0-16) to program as inputs

* gpio_output: int array (min = 1, max = 17)
    List of GPIO pins (0-16) to program as outputs

* gpio_inverted: int array (min = 1, max = 17)
    List of GPIO pins (0-16) to program as inverted

* gpio_normal: int array (min = 1, max = 17)
    List of GPIO pins (0-16) to program as normal/non-inverted

* gpio_fan: int array (min = 1, max = 8)
    List of GPIO pins (0-7) to program as fan tachs

Description
-----------

This driver implements support for the Analog Devices ADM1026. Analog
Devices calls it a "complete thermal system management controller."

The ADM1026 implements three (3) temperature sensors, 17 voltage sensors,
16 general purpose digital I/O lines, eight (8) fan speed sensors (8-bit),
an analog output and a PWM output along with limit, alarm and mask bits for
all of the above. There is even 8k bytes of EEPROM memory on chip.

Temperatures are measured in degrees Celsius. There are two external
sensor inputs and one internal sensor. Each sensor has a high and low
limit. If the limit is exceeded, an interrupt (#SMBALERT) can be
generated. The interrupts can be masked. In addition, there are over-temp
limits for each sensor. If this limit is exceeded, the #THERM output will
be asserted. The current temperature and limits have a resolution of 1
degree.

Fan rotation speeds are reported in RPM (rotations per minute) but measured
in counts of a 22.5kHz internal clock. Each fan has a high limit which
corresponds to a minimum fan speed. If the limit is exceeded, an interrupt
can be generated. Each fan can be programmed to divide the reference clock
by 1, 2, 4 or 8. Not all RPM values can accurately be represented, so some
rounding is done. With a divider of 8, the slowest measurable speed of a
two pulse per revolution fan is 661 RPM.

There are 17 voltage sensors. An alarm is triggered if the voltage has
crossed a programmable minimum or maximum limit. Note that minimum in this
case always means 'closest to zero'; this is important for negative voltage
measurements. Several inputs have integrated attenuators so they can measure
higher voltages directly. 3.3V, 5V, 12V, -12V and battery voltage all have
dedicated inputs. There are several inputs scaled to 0-3V full-scale range
for SCSI terminator power. The remaining inputs are not scaled and have
a 0-2.5V full-scale range. A 2.5V or 1.82V reference voltage is provided
for negative voltage measurements.

If an alarm triggers, it will remain triggered until the hardware register
is read at least once. This means that the cause for the alarm may already
have disappeared! Note that in the current implementation, all hardware
registers are read whenever any data is read (unless it is less than 2.0
seconds since the last update). This means that you can easily miss
once-only alarms.

The ADM1026 measures continuously. Analog inputs are measured about 4
times a second. Fan speed measurement time depends on fan speed and
divisor. It can take as long as 1.5 seconds to measure all fan speeds.

The ADM1026 has the ability to automatically control fan speed based on the
temperature sensor inputs. Both the PWM output and the DAC output can be
used to control fan speed. Usually only one of these two outputs will be
used. Write the minimum PWM or DAC value to the appropriate control
register. Then set the low temperature limit in the tmin values for each
temperature sensor. The range of control is fixed at 20 °C, and the
largest difference between current and tmin of the temperature sensors sets
the control output. See the datasheet for several example circuits for
controlling fan speed with the PWM and DAC outputs. The fan speed sensors
do not have PWM compensation, so it is probably best to control the fan
voltage from the power lead rather than on the ground lead.

The datasheet shows an example application with VID signals attached to
GPIO lines. Unfortunately, the chip may not be connected to the VID lines
in this way. The driver assumes that the chips *is* connected this way to
get a VID voltage.


code:
Kernel driver adm1031
=====================

Supported chips:
  * Analog Devices ADM1030

    Prefix: 'adm1030'

    Addresses scanned: I2C 0x2c to 0x2e

    Datasheet: Publicly available at the Analog Devices website

	       https://www.analog.com/en/prod/0%2C2877%2CADM1030%2C00.html

  * Analog Devices ADM1031

    Prefix: 'adm1031'

    Addresses scanned: I2C 0x2c to 0x2e

    Datasheet: Publicly available at the Analog Devices website

	       https://www.analog.com/en/prod/0%2C2877%2CADM1031%2C00.html

Authors:
	- Alexandre d'Alton <alex@alexdalton.org>
	- Jean Delvare <jdelvare@suse.de>

Description
-----------

The ADM1030 and ADM1031 are digital temperature sensors and fan controllers.
They sense their own temperature as well as the temperature of up to one
(ADM1030) or two (ADM1031) external diodes.

All temperature values are given in degrees Celsius. Resolution is 0.5
degree for the local temperature, 0.125 degree for the remote temperatures.

Each temperature channel has its own high and low limits, plus a critical
limit.

The ADM1030 monitors a single fan speed, while the ADM1031 monitors up to
two. Each fan channel has its own low speed limit.


code:
Kernel driver adm1177
=====================

Supported chips:
  * Analog Devices ADM1177
    Prefix: 'adm1177'
    Datasheet: https://www.analog.com/media/en/technical-documentation/data-sheets/ADM1177.pdf

Author: Beniamin Bia <beniamin.bia@analog.com>

Description
-----------

This driver supports hardware monitoring for Analog Devices ADM1177
Hot-Swap Controller and Digital Power Monitors with Soft Start Pin.

Usage Notes
-----------

This driver does not auto-detect devices. You will have to instantiate the
devices explicitly. Please see Documentation/i2c/instantiating-devices.rst
for details.

Sysfs entries
-------------

The following attributes are supported. Current maxim attribute
is read-write, all other attributes are read-only.

in0_input		Measured voltage in microvolts.

curr1_input		Measured current in microamperes.
curr1_max_alarm		Overcurrent alarm in microamperes.


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

Kernel driver adm1266
=====================

Supported chips:
  * Analog Devices ADM1266
    Prefix: 'adm1266'
    Datasheet: https://www.analog.com/media/en/technical-documentation/data-sheets/ADM1266.pdf

Author: Alexandru Tachici <alexandru.tachici@analog.com>

Description
-----------

This driver supports hardware monitoring for Analog Devices ADM1266 sequencer.

ADM1266 is a sequencer that features voltage readback from 17 channels via an
integrated 12 bit SAR ADC, accessed using a PMBus interface.

The driver is a client driver to the core PMBus driver. Please see
Documentation/hwmon/pmbus.rst for details on PMBus client drivers.

Sysfs entries
-------------

The following attributes are supported. Limits are read-write, history reset
attributes are write-only, all other attributes are read-only.

inX_label		"voutx"
inX_input		Measured voltage.
inX_min			Minimum Voltage.
inX_max			Maximum voltage.
inX_min_alarm		Voltage low alarm.
inX_max_alarm		Voltage high alarm.


code:
Kernel driver adm1275
=====================

Supported chips:

  * Analog Devices ADM1075

    Prefix: 'adm1075'

    Addresses scanned: -

    Datasheet: www.analog.com/static/imported-files/data_sheets/ADM1075.pdf

  * Analog Devices ADM1272

    Prefix: 'adm1272'

    Addresses scanned: -

    Datasheet: www.analog.com/static/imported-files/data_sheets/ADM1272.pdf

  * Analog Devices ADM1275

    Prefix: 'adm1275'

    Addresses scanned: -

    Datasheet: www.analog.com/static/imported-files/data_sheets/ADM1275.pdf

  * Analog Devices ADM1276

    Prefix: 'adm1276'

    Addresses scanned: -

    Datasheet: www.analog.com/static/imported-files/data_sheets/ADM1276.pdf

  * Analog Devices ADM1278

    Prefix: 'adm1278'

    Addresses scanned: -

    Datasheet: www.analog.com/static/imported-files/data_sheets/ADM1278.pdf

  * Analog Devices ADM1293/ADM1294

    Prefix: 'adm1293', 'adm1294'

    Addresses scanned: -

    Datasheet: https://www.analog.com/media/en/technical-documentation/data-sheets/ADM1293_1294.pdf

Author: Guenter Roeck <linux@roeck-us.net>

Description
-----------

This driver supports hardware monitoring for Analog Devices ADM1075, ADM1272,
ADM1275, ADM1276, ADM1278, ADM1293, and ADM1294 Hot-Swap Controller and
Digital Power Monitors.

ADM1075, ADM1272, ADM1275, ADM1276, ADM1278, ADM1293, and ADM1294 are hot-swap
controllers that allow a circuit board to be removed from or inserted into
a live backplane. They also feature current and voltage readback via an
integrated 12 bit analog-to-digital converter (ADC), accessed using a
PMBus interface.

The driver is a client driver to the core PMBus driver. Please see
Documentation/hwmon/pmbus.rst for details on PMBus client drivers.

Usage Notes
-----------

This driver does not auto-detect devices. You will have to instantiate the
devices explicitly. Please see Documentation/i2c/instantiating-devices.rst for
details.

The ADM1075, unlike many other PMBus devices, does not support internal voltage
or current scaling. Reported voltages, currents, and power are raw measurements,
and will typically have to be scaled.

The shunt value in micro-ohms can be set via device tree at compile-time. Please
refer to the Documentation/devicetree/bindings/hwmon/adi,adm1275.yaml for bindings
if the device tree is used.

Platform data support
---------------------

The driver supports standard PMBus driver platform data. Please see
Documentation/hwmon/pmbus.rst for details.

Sysfs entries
-------------

The following attributes are supported. Limits are read-write, history reset
attributes are write-only, all other attributes are read-only.

======================= =======================================================
inX_label		"vin1" or "vout1" depending on chip variant and
			configuration. On ADM1075, ADM1293, and ADM1294,
			vout1 reports the voltage on the VAUX pin.
inX_input		Measured voltage.
inX_min			Minimum Voltage.
inX_max			Maximum voltage.
inX_min_alarm		Voltage low alarm.
inX_max_alarm		Voltage high alarm.
inX_highest		Historical maximum voltage.
inX_reset_history	Write any value to reset history.

curr1_label		"iout1"
curr1_input		Measured current.
curr1_max		Maximum current.
curr1_max_alarm		Current high alarm.
curr1_lcrit		Critical minimum current. Depending on the chip
			configuration, either curr1_lcrit or curr1_crit is
			supported, but not both.
curr1_lcrit_alarm	Critical current low alarm.
curr1_crit		Critical maximum current. Depending on the chip
			configuration, either curr1_lcrit or curr1_crit is
			supported, but not both.
curr1_crit_alarm	Critical current high alarm.
curr1_highest		Historical maximum current.
curr1_reset_history	Write any value to reset history.

power1_label		"pin1"
power1_input		Input power.
power1_input_lowest	Lowest observed input power. ADM1293 and ADM1294 only.
power1_input_highest	Highest observed input power.
power1_reset_history	Write any value to reset history.

			Power attributes are supported on ADM1075, ADM1272,
			ADM1276, ADM1293, and ADM1294.

temp1_input		Chip temperature.
temp1_max		Maximum chip temperature.
temp1_max_alarm		Temperature alarm.
temp1_crit		Critical chip temperature.
temp1_crit_alarm	Critical temperature high alarm.
temp1_highest		Highest observed temperature.
temp1_reset_history	Write any value to reset history.

			Temperature attributes are supported on ADM1272 and
			ADM1278.
======================= =======================================================


code:
Kernel driver adm9240
=====================

Supported chips:

  * Analog Devices ADM9240

    Prefix: 'adm9240'

    Addresses scanned: I2C 0x2c - 0x2f

    Datasheet: Publicly available at the Analog Devices website

	http://www.analog.com/UploadedFiles/Data_Sheets/79857778ADM9240_0.pdf

  * Dallas Semiconductor DS1780

    Prefix: 'ds1780'

    Addresses scanned: I2C 0x2c - 0x2f

    Datasheet: Publicly available at the Dallas Semiconductor (Maxim) website

	http://pdfserv.maxim-ic.com/en/ds/DS1780.pdf

  * National Semiconductor LM81

    Prefix: 'lm81'

    Addresses scanned: I2C 0x2c - 0x2f

    Datasheet: Publicly available at the National Semiconductor website

	http://www.national.com/ds.cgi/LM/LM81.pdf

Authors:
    - Frodo Looijaard <frodol@dds.nl>,
    - Philip Edelbrock <phil@netroedge.com>,
    - Michiel Rook <michiel@grendelproject.nl>,
    - Grant Coady <gcoady.lk@gmail.com> with guidance
      from Jean Delvare <jdelvare@suse.de>

Interface
---------
The I2C addresses listed above assume BIOS has not changed the
chip MSB 5-bit address. Each chip reports a unique manufacturer
identification code as well as the chip revision/stepping level.

Description
-----------
[From ADM9240] The ADM9240 is a complete system hardware monitor for
microprocessor-based systems, providing measurement and limit comparison
of up to four power supplies and two processor core voltages, plus
temperature, two fan speeds and chassis intrusion. Measured values can
be read out via an I2C-compatible serial System Management Bus, and values
for limit comparisons can be programmed in over the same serial bus. The
high speed successive approximation ADC allows frequent sampling of all
analog channels to ensure a fast interrupt response to any out-of-limit
measurement.

The ADM9240, DS1780 and LM81 are register compatible, the following
details are common to the three chips. Chip differences are described
after this section.

Measurements
------------
The measurement cycle

The adm9240 driver will take a measurement reading no faster than once
each two seconds. User-space may read sysfs interface faster than the
measurement update rate and will receive cached data from the most
recent measurement.

ADM9240 has a very fast 320us temperature and voltage measurement cycle
with independent fan speed measurement cycles counting alternating rising
edges of the fan tacho inputs.

DS1780 measurement cycle is about once per second including fan speed.

LM81 measurement cycle is about once per 400ms including fan speed.
The LM81 12-bit extended temperature measurement mode is not supported.

Temperature
-----------
On chip temperature is reported as degrees Celsius as 9-bit signed data
with resolution of 0.5 degrees Celsius. High and low temperature limits
are 8-bit signed data with resolution of one degree Celsius.

Temperature alarm is asserted once the temperature exceeds the high limit,
and is cleared when the temperature falls below the temp1_max_hyst value.

Fan Speed
---------
Two fan tacho inputs are provided, the ADM9240 gates an internal 22.5kHz
clock via a divider to an 8-bit counter. Fan speed (rpm) is calculated by:

rpm = (22500 * 60) / (count * divider)

Automatic fan clock divider

  * User sets 0 to fan_min limit

    - low speed alarm is disabled
    - fan clock divider not changed
    - auto fan clock adjuster enabled for valid fan speed reading

  * User sets fan_min limit too low

    - low speed alarm is enabled
    - fan clock divider set to max
    - fan_min set to register value 254 which corresponds
      to 664 rpm on adm9240
    - low speed alarm will be asserted if fan speed is
      less than minimum measurable speed
    - auto fan clock adjuster disabled

  * User sets reasonable fan speed

    - low speed alarm is enabled
    - fan clock divider set to suit fan_min
    - auto fan clock adjuster enabled: adjusts fan_min

  * User sets unreasonably high low fan speed limit

    - resolution of the low speed limit may be reduced
    - alarm will be asserted
    - auto fan clock adjuster enabled: adjusts fan_min

  * fan speed may be displayed as zero until the auto fan clock divider
    adjuster brings fan speed clock divider back into chip measurement
    range, this will occur within a few measurement cycles.

Analog Output
-------------
An analog output provides a 0 to 1.25 volt signal intended for an external
fan speed amplifier circuit. The analog output is set to maximum value on
power up or reset. This doesn't do much on the test Intel SE440BX-2.

Voltage Monitor

^^^^^^^^^^^^^^^

Voltage (IN) measurement is internally scaled:

    === =========== =========== ========= ==========
    nr  label       nominal     maximum   resolution
		      mV          mV         mV
    === =========== =========== ========= ==========
    0   +2.5V        2500        3320       13.0
    1   Vccp1        2700        3600       14.1
    2   +3.3V        3300        4380       17.2
    3     +5V        5000        6640       26.0
    4    +12V       12000       15940       62.5
    5   Vccp2        2700        3600       14.1
    === =========== =========== ========= ==========

The reading is an unsigned 8-bit value, nominal voltage measurement is
represented by a reading of 192, being 3/4 of the measurement range.

An alarm is asserted for any voltage going below or above the set limits.

The driver reports and accepts voltage limits scaled to the above table.

VID Monitor
-----------
The chip has five inputs to read the 5-bit VID and reports the mV value
based on detected CPU type.

Chassis Intrusion
-----------------
An alarm is asserted when the CI pin goes active high. The ADM9240
Datasheet has an example of an external temperature sensor driving
this pin. On an Intel SE440BX-2 the Chassis Intrusion header is
connected to a normally open switch.

The ADM9240 provides an internal open drain on this line, and may output
a 20 ms active low pulse to reset an external Chassis Intrusion latch.

Clear the CI latch by writing value 0 to the sysfs intrusion0_alarm file.

Alarm flags reported as 16-bit word

    ===     =============       ==========================
    bit     label               comment
    ===     =============       ==========================
     0      +2.5 V_Error        high or low limit exceeded
     1      VCCP_Error          high or low limit exceeded
     2      +3.3 V_Error        high or low limit exceeded
     3      +5 V_Error          high or low limit exceeded
     4      Temp_Error          temperature error
     6      FAN1_Error          fan low limit exceeded
     7      FAN2_Error          fan low limit exceeded
     8      +12 V_Error         high or low limit exceeded
     9      VCCP2_Error         high or low limit exceeded
    12      Chassis_Error       CI pin went high
    ===     =============       ==========================

Remaining bits are reserved and thus undefined. It is important to note
that alarm bits may be cleared on read, user-space may latch alarms and
provide the end-user with a method to clear alarm memory.