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

#########
UML HowTo
#########

.. contents:: :local:

************
Introduction
************

Welcome to User Mode Linux

User Mode Linux is the first Open Source virtualization platform (first
release date 1991) and second virtualization platform for an x86 PC.

How is UML Different from a VM using Virtualization package X?
==============================================================

We have come to assume that virtualization also means some level of
hardware emulation. In fact, it does not. As long as a virtualization
package provides the OS with devices which the OS can recognize and
has a driver for, the devices do not need to emulate real hardware.
Most OSes today have built-in support for a number of "fake"
devices used only under virtualization.
User Mode Linux takes this concept to the ultimate extreme - there
is not a single real device in sight. It is 100% artificial or if
we use the correct term 100% paravirtual. All UML devices are abstract
concepts which map onto something provided by the host - files, sockets,
pipes, etc.

The other major difference between UML and various virtualization
packages is that there is a distinct difference between the way the UML
kernel and the UML programs operate.
The UML kernel is just a process running on Linux - same as any other
program. It can be run by an unprivileged user and it does not require
anything in terms of special CPU features.
The UML userspace, however, is a bit different. The Linux kernel on the
host machine assists UML in intercepting everything the program running
on a UML instance is trying to do and making the UML kernel handle all
of its requests.
This is different from other virtualization packages which do not make any
difference between the guest kernel and guest programs. This difference
results in a number of advantages and disadvantages of UML over let's say
QEMU which we will cover later in this document.

Why Would I Want User Mode Linux?
=================================

* If User Mode Linux kernel crashes, your host kernel is still fine. It
  is not accelerated in any way (vhost, kvm, etc) and it is not trying to
  access any devices directly.  It is, in fact, a process like any other.

* You can run a usermode kernel as a non-root user (you may need to
  arrange appropriate permissions for some devices).

* You can run a very small VM with a minimal footprint for a specific
  task (for example 32M or less).

* You can get extremely high performance for anything which is a "kernel
  specific task" such as forwarding, firewalling, etc while still being
  isolated from the host kernel.

* You can play with kernel concepts without breaking things.

* You are not bound by "emulating" hardware, so you can try weird and
  wonderful concepts which are very difficult to support when emulating
  real hardware such as time travel and making your system clock
  dependent on what UML does (very useful for things like tests).

* It's fun.

Why not to run UML
==================

* The syscall interception technique used by UML makes it inherently
  slower for any userspace applications. While it can do kernel tasks
  on par with most other virtualization packages, its userspace is
  **slow**. The root cause is that UML has a very high cost of creating
  new processes and threads (something most Unix/Linux applications
  take for granted).

* UML is strictly uniprocessor at present. If you want to run an
  application which needs many CPUs to function, it is clearly the
  wrong choice.

***********************
Building a UML instance
***********************

There is no UML installer in any distribution. While you can use off
the shelf install media to install into a blank VM using a virtualization
package, there is no UML equivalent. You have to use appropriate tools on
your host to build a viable filesystem image.

This is extremely easy on Debian - you can do it using debootstrap. It is
also easy on OpenWRT - the build process can build UML images. All other
distros - YMMV.

Creating an image
=================

Create a sparse raw disk image::

   # dd if=/dev/zero of=disk_image_name bs=1 count=1 seek=16G

This will create a 16G disk image. The OS will initially allocate only one
block and will allocate more as they are written by UML. As of kernel
version 4.19 UML fully supports TRIM (as usually used by flash drives).
Using TRIM inside the UML image by specifying discard as a mount option
or by running ``tune2fs -o discard /dev/ubdXX`` will request UML to
return any unused blocks to the OS.

Create a filesystem on the disk image and mount it::

   # mkfs.ext4 ./disk_image_name && mount ./disk_image_name /mnt

This example uses ext4, any other filesystem such as ext3, btrfs, xfs,
jfs, etc will work too.

Create a minimal OS installation on the mounted filesystem::

   # debootstrap buster /mnt http://deb.debian.org/debian

debootstrap does not set up the root password, fstab, hostname or
anything related to networking. It is up to the user to do that.

Set the root password - the easiest way to do that is to chroot into the
mounted image::

   # chroot /mnt
   # passwd
   # exit

Edit key system files
=====================

UML block devices are called ubds. The fstab created by debootstrap
will be empty and it needs an entry for the root file system::

   /dev/ubd0   ext4    discard,errors=remount-ro  0       1

The image hostname will be set to the same as the host on which you
are creating its image. It is a good idea to change that to avoid
"Oh, bummer, I rebooted the wrong machine".

UML supports two classes of network devices - the older uml_net ones
which are scheduled for obsoletion. These are called ethX. It also
supports the newer vector IO devices which are significantly faster
and have support for some standard virtual network encapsulations like
Ethernet over GRE and Ethernet over L2TPv3. These are called vec0.

Depending on which one is in use, ``/etc/network/interfaces`` will
need entries like::

   # legacy UML network devices
   auto eth0
   iface eth0 inet dhcp

   # vector UML network devices
   auto vec0
   iface vec0 inet dhcp

We now have a UML image which is nearly ready to run, all we need is a
UML kernel and modules for it.

Most distributions have a UML package. Even if you intend to use your own
kernel, testing the image with a stock one is always a good start. These
packages come with a set of modules which should be copied to the target
filesystem. The location is distribution dependent. For Debian these
reside under /usr/lib/uml/modules. Copy recursively the content of this
directory to the mounted UML filesystem::

   # cp -rax /usr/lib/uml/modules /mnt/lib/modules

If you have compiled your own kernel, you need to use the usual "install
modules to a location" procedure by running::

  # make INSTALL_MOD_PATH=/mnt/lib/modules modules_install

This will install modules into /mnt/lib/modules/$(KERNELRELEASE).
To specify the full module installation path, use::

  # make MODLIB=/mnt/lib/modules modules_install

At this point the image is ready to be brought up.

*************************
Setting Up UML Networking
*************************

UML networking is designed to emulate an Ethernet connection. This
connection may be either point-to-point (similar to a connection
between machines using a back-to-back cable) or a connection to a
switch. UML supports a wide variety of means to build these
connections to all of: local machine, remote machine(s), local and
remote UML and other VM instances.

+-----------+--------+------------------------------------+------------+
| Transport |  Type  |        Capabilities                | Throughput |
+===========+========+====================================+============+
| tap       | vector | checksum, tso                      | > 8Gbit    |
+-----------+--------+------------------------------------+------------+
| hybrid    | vector | checksum, tso, multipacket rx      | > 6GBit    |
+-----------+--------+------------------------------------+------------+
| raw       | vector | checksum, tso, multipacket rx, tx" | > 6GBit    |
+-----------+--------+------------------------------------+------------+
| EoGRE     | vector | multipacket rx, tx                 | > 3Gbit    |
+-----------+--------+------------------------------------+------------+
| Eol2tpv3  | vector | multipacket rx, tx                 | > 3Gbit    |
+-----------+--------+------------------------------------+------------+
| bess      | vector | multipacket rx, tx                 | > 3Gbit    |
+-----------+--------+------------------------------------+------------+
| fd        | vector | dependent on fd type               | varies     |
+-----------+--------+------------------------------------+------------+
| tuntap    | legacy | none                               | ~ 500Mbit  |
+-----------+--------+------------------------------------+------------+
| daemon    | legacy | none                               | ~ 450Mbit  |
+-----------+--------+------------------------------------+------------+
| socket    | legacy | none                               | ~ 450Mbit  |
+-----------+--------+------------------------------------+------------+
| pcap      | legacy | rx only                            | ~ 450Mbit  |
+-----------+--------+------------------------------------+------------+
| ethertap  | legacy | obsolete                           | ~ 500Mbit  |
+-----------+--------+------------------------------------+------------+
| vde       | legacy | obsolete                           | ~ 500Mbit  |
+-----------+--------+------------------------------------+------------+

* All transports which have tso and checksum offloads can deliver speeds
  approaching 10G on TCP streams.

* All transports which have multi-packet rx and/or tx can deliver pps
  rates of up to 1Mps or more.

* All legacy transports are generally limited to ~600-700MBit and 0.05Mps.

* GRE and L2TPv3 allow connections to all of: local machine, remote
  machines, remote network devices and remote UML instances.

* Socket allows connections only between UML instances.

* Daemon and bess require running a local switch. This switch may be
  connected to the host as well.

Network configuration privileges
================================

The majority of the supported networking modes need ``root`` privileges.
For example, in the legacy tuntap networking mode, users were required
to be part of the group associated with the tunnel device.

For newer network drivers like the vector transports, ``root`` privilege
is required to fire an ioctl to setup the tun interface and/or use
raw sockets where needed.

This can be achieved by granting the user a particular capability instead
of running UML as root.  In case of vector transport, a user can add the
capability ``CAP_NET_ADMIN`` or ``CAP_NET_RAW`` to the uml binary.
Thenceforth, UML can be run with normal user privilges, along with
full networking.

For example::

   # sudo setcap cap_net_raw,cap_net_admin+ep linux

Configuring vector transports
===============================

All vector transports support a similar syntax:

If X is the interface number as in vec0, vec1, vec2, etc, the general
syntax for options is::

   vecX:transport="Transport Name",option=value,option=value,...,option=value

Common options
--------------

These options are common for all transports:

* ``depth=int`` - sets the queue depth for vector IO. This is the
  amount of packets UML will attempt to read or write in a single
  system call. The default number is 64 and is generally sufficient
  for most applications that need throughput in the 2-4 Gbit range.
  Higher speeds may require larger values.

* ``mac=XX:XX:XX:XX:XX`` - sets the interface MAC address value.

* ``gro=[0,1]`` - sets GRO off or on. Enables receive/transmit offloads.
  The effect of this option depends on the host side support in the transport
  which is being configured. In most cases it will enable TCP segmentation and
  RX/TX checksumming offloads. The setting must be identical on the host side
  and the UML side. The UML kernel will produce warnings if it is not.
  For example, GRO is enabled by default on local machine interfaces
  (e.g. veth pairs, bridge, etc), so it should be enabled in UML in the
  corresponding UML transports (raw, tap, hybrid) in order for networking to
  operate correctly.

* ``mtu=int`` - sets the interface MTU

* ``headroom=int`` - adjusts the default headroom (32 bytes) reserved
  if a packet will need to be re-encapsulated into for instance VXLAN.

* ``vec=0`` - disable multipacket IO and fall back to packet at a
  time mode

Shared Options
--------------

* ``ifname=str`` Transports which bind to a local network interface
  have a shared option - the name of the interface to bind to.

* ``src, dst, src_port, dst_port`` - all transports which use sockets
  which have the notion of source and destination and/or source port
  and destination port use these to specify them.

* ``v6=[0,1]`` to specify if a v6 connection is desired for all
  transports which operate over IP. Additionally, for transports that
  have some differences in the way they operate over v4 and v6 (for example
  EoL2TPv3), sets the correct mode of operation. In the absence of this
  option, the socket type is determined based on what do the src and dst
  arguments resolve/parse to.

tap transport
-------------

Example::

   vecX:transport=tap,ifname=tap0,depth=128,gro=1

This will connect vec0 to tap0 on the host. Tap0 must already exist (for example
created using tunctl) and UP.

tap0 can be configured as a point-to-point interface and given an IP
address so that UML can talk to the host. Alternatively, it is possible
to connect UML to a tap interface which is connected to a bridge.

While tap relies on the vector infrastructure, it is not a true vector
transport at this point, because Linux does not support multi-packet
IO on tap file descriptors for normal userspace apps like UML. This
is a privilege which is offered only to something which can hook up
to it at kernel level via specialized interfaces like vhost-net. A
vhost-net like helper for UML is planned at some point in the future.

Privileges required: tap transport requires either:

* tap interface to exist and be created persistent and owned by the
  UML user using tunctl. Example ``tunctl -u uml-user -t tap0``

* binary to have ``CAP_NET_ADMIN`` privilege

hybrid transport
----------------

Example::

   vecX:transport=hybrid,ifname=tap0,depth=128,gro=1

This is an experimental/demo transport which couples tap for transmit
and a raw socket for receive. The raw socket allows multi-packet
receive resulting in significantly higher packet rates than normal tap.

Privileges required: hybrid requires ``CAP_NET_RAW`` capability by
the UML user as well as the requirements for the tap transport.

raw socket transport
--------------------

Example::

   vecX:transport=raw,ifname=p-veth0,depth=128,gro=1

This transport uses vector IO on raw sockets. While you can bind to any
interface including a physical one, the most common use it to bind to
the "peer" side of a veth pair with the other side configured on the
host.

Example host configuration for Debian:

**/etc/network/interfaces**::

   auto veth0
   iface veth0 inet static
	address 192.168.4.1
	netmask 255.255.255.252
	broadcast 192.168.4.3
	pre-up ip link add veth0 type veth peer name p-veth0 && \
          ifconfig p-veth0 up

UML can now bind to p-veth0 like this::

   vec0:transport=raw,ifname=p-veth0,depth=128,gro=1

If the UML guest is configured with 192.168.4.2 and netmask 255.255.255.0
it can talk to the host on 192.168.4.1

The raw transport also provides some support for offloading some of the
filtering to the host. The two options to control it are:

* ``bpffile=str`` filename of raw bpf code to be loaded as a socket filter

* ``bpfflash=int`` 0/1 allow loading of bpf from inside User Mode Linux.
  This option allows the use of the ethtool load firmware command to
  load bpf code.

In either case the bpf code is loaded into the host kernel. While this is
presently limited to legacy bpf syntax (not ebpf), it is still a security
risk. It is not recommended to allow this unless the User Mode Linux
instance is considered trusted.

Privileges required: raw socket transport requires `CAP_NET_RAW`
capability.

GRE socket transport
--------------------

Example::

   vecX:transport=gre,src=$src_host,dst=$dst_host

This will configure an Ethernet over ``GRE`` (aka ``GRETAP`` or
``GREIRB``) tunnel which will connect the UML instance to a ``GRE``
endpoint at host dst_host. ``GRE`` supports the following additional
options:

* ``rx_key=int`` - GRE 32-bit integer key for rx packets, if set,
  ``txkey`` must be set too

* ``tx_key=int`` - GRE 32-bit integer key for tx packets, if set
  ``rx_key`` must be set too

* ``sequence=[0,1]`` - enable GRE sequence

* ``pin_sequence=[0,1]`` - pretend that the sequence is always reset
  on each packet (needed to interoperate with some really broken
  implementations)

* ``v6=[0,1]`` - force IPv4 or IPv6 sockets respectively

* GRE checksum is not presently supported

GRE has a number of caveats:

* You can use only one GRE connection per IP address. There is no way to
  multiplex connections as each GRE tunnel is terminated directly on
  the UML instance.

* The key is not really a security feature. While it was intended as such
  its "security" is laughable. It is, however, a useful feature to
  ensure that the tunnel is not misconfigured.

An example configuration for a Linux host with a local address of
192.168.128.1 to connect to a UML instance at 192.168.129.1

**/etc/network/interfaces**::

   auto gt0
   iface gt0 inet static
    address 10.0.0.1
    netmask 255.255.255.0
    broadcast 10.0.0.255
    mtu 1500
    pre-up ip link add gt0 type gretap local 192.168.128.1 \
           remote 192.168.129.1 || true
    down ip link del gt0 || true

Additionally, GRE has been tested versus a variety of network equipment.

Privileges required: GRE requires ``CAP_NET_RAW``

l2tpv3 socket transport
-----------------------

_Warning_. L2TPv3 has a "bug". It is the "bug" known as "has more
options than GNU ls". While it has some advantages, there are usually
easier (and less verbose) ways to connect a UML instance to something.
For example, most devices which support L2TPv3 also support GRE.

Example::

    vec0:transport=l2tpv3,udp=1,src=$src_host,dst=$dst_host,srcport=$src_port,dstport=$dst_port,depth=128,rx_session=0xffffffff,tx_session=0xffff

This will configure an Ethernet over L2TPv3 fixed tunnel which will
connect the UML instance to a L2TPv3 endpoint at host $dst_host using
the L2TPv3 UDP flavour and UDP destination port $dst_port.

L2TPv3 always requires the following additional options:

* ``rx_session=int`` - l2tpv3 32-bit integer session for rx packets

* ``tx_session=int`` - l2tpv3 32-bit integer session for tx packets

As the tunnel is fixed these are not negotiated and they are
preconfigured on both ends.

Additionally, L2TPv3 supports the following optional parameters.

* ``rx_cookie=int`` - l2tpv3 32-bit integer cookie for rx packets - same
  functionality as GRE key, more to prevent misconfiguration than provide
  actual security

* ``tx_cookie=int`` - l2tpv3 32-bit integer cookie for tx packets

* ``cookie64=[0,1]`` - use 64-bit cookies instead of 32-bit.

* ``counter=[0,1]`` - enable l2tpv3 counter

* ``pin_counter=[0,1]`` - pretend that the counter is always reset on
  each packet (needed to interoperate with some really broken
  implementations)

* ``v6=[0,1]`` - force v6 sockets

* ``udp=[0,1]`` - use raw sockets (0) or UDP (1) version of the protocol

L2TPv3 has a number of caveats:

* you can use only one connection per IP address in raw mode. There is
  no way to multiplex connections as each L2TPv3 tunnel is terminated
  directly on the UML instance. UDP mode can use different ports for
  this purpose.

Here is an example of how to configure a Linux host to connect to UML
via L2TPv3:

**/etc/network/interfaces**::

   auto l2tp1
   iface l2tp1 inet static
    address 192.168.126.1
    netmask 255.255.255.0
    broadcast 192.168.126.255
    mtu 1500
    pre-up ip l2tp add tunnel remote 127.0.0.1 \
           local 127.0.0.1 encap udp tunnel_id 2 \
           peer_tunnel_id 2 udp_sport 1706 udp_dport 1707 && \
           ip l2tp add session name l2tp1 tunnel_id 2 \
           session_id 0xffffffff peer_session_id 0xffffffff
    down ip l2tp del session tunnel_id 2 session_id 0xffffffff && \
           ip l2tp del tunnel tunnel_id 2

Privileges required: L2TPv3 requires ``CAP_NET_RAW`` for raw IP mode and
no special privileges for the UDP mode.

BESS socket transport
---------------------

BESS is a high performance modular network switch.

https://github.com/NetSys/bess

It has support for a simple sequential packet socket mode which in the
more recent versions is using vector IO for high performance.

Example::

   vecX:transport=bess,src=$unix_src,dst=$unix_dst

This will configure a BESS transport using the unix_src Unix domain
socket address as source and unix_dst socket address as destination.

For BESS configuration and how to allocate a BESS Unix domain socket port
please see the BESS documentation.

https://github.com/NetSys/bess/wiki/Built-In-Modules-and-Ports

BESS transport does not require any special privileges.

Configuring Legacy transports
=============================

Legacy transports are now considered obsolete. Please use the vector
versions.

***********
Running UML
***********

This section assumes that either the user-mode-linux package from the
distribution or a custom built kernel has been installed on the host.

These add an executable called linux to the system. This is the UML
kernel. It can be run just like any other executable.
It will take most normal linux kernel arguments as command line
arguments.  Additionally, it will need some UML-specific arguments
in order to do something useful.

Arguments
=========

Mandatory Arguments:
--------------------

* ``mem=int[K,M,G]`` - amount of memory. By default in bytes. It will
  also accept K, M or G qualifiers.

* ``ubdX[s,d,c,t]=`` virtual disk specification. This is not really
  mandatory, but it is likely to be needed in nearly all cases so we can
  specify a root file system.
  The simplest possible image specification is the name of the image
  file for the filesystem (created using one of the methods described
  in `Creating an image`_).

  * UBD devices support copy on write (COW). The changes are kept in
    a separate file which can be discarded allowing a rollback to the
    original pristine image.  If COW is desired, the UBD image is
    specified as: ``cow_file,master_image``.
    Example:``ubd0=Filesystem.cow,Filesystem.img``

  * UBD devices can be set to use synchronous IO. Any writes are
    immediately flushed to disk. This is done by adding ``s`` after
    the ``ubdX`` specification.

  * UBD performs some heuristics on devices specified as a single
    filename to make sure that a COW file has not been specified as
    the image. To turn them off, use the ``d`` flag after ``ubdX``.

  * UBD supports TRIM - asking the Host OS to reclaim any unused
    blocks in the image. To turn it off, specify the ``t`` flag after
    ``ubdX``.

* ``root=`` root device - most likely ``/dev/ubd0`` (this is a Linux
  filesystem image)

Important Optional Arguments
----------------------------

If UML is run as "linux" with no extra arguments, it will try to start an
xterm for every console configured inside the image (up to 6 in most
Linux distributions). Each console is started inside an
xterm. This makes it nice and easy to use UML on a host with a GUI. It is,
however, the wrong approach if UML is to be used as a testing harness or run
in a text-only environment.

In order to change this behaviour we need to specify an alternative console
and wire it to one of the supported "line" channels. For this we need to map a
console to use something different from the default xterm.

Example which will divert console number 1 to stdin/stdout::

   con1=fd:0,fd:1

UML supports a wide variety of serial line channels which are specified using
the following syntax

   conX=channel_type:options[,channel_type:options]

If the channel specification contains two parts separated by comma, the first
one is input, the second one output.

* The null channel - Discard all input or output. Example ``con=null`` will set
  all consoles to null by default.

* The fd channel - use file descriptor numbers for input/output. Example:
  ``con1=fd:0,fd:1.``

* The port channel - start a telnet server on TCP port number. Example:
  ``con1=port:4321``.  The host must have /usr/sbin/in.telnetd (usually part of
  a telnetd package) and the port-helper from the UML utilities (see the
  information for the xterm channel below).  UML will not boot until a client
  connects.

* The pty and pts channels - use system pty/pts.

* The tty channel - bind to an existing system tty. Example: ``con1=/dev/tty8``
  will make UML use the host 8th console (usually unused).

* The xterm channel - this is the default - bring up an xterm on this channel
  and direct IO to it. Note that in order for xterm to work, the host must
  have the UML distribution package installed. This usually contains the
  port-helper and other utilities needed for UML to communicate with the xterm.
  Alternatively, these need to be complied and installed from source. All
  options applicable to consoles also apply to UML serial lines which are
  presented as ttyS inside UML.

Starting UML
============

We can now run UML.
::

   # linux mem=2048M umid=TEST \
    ubd0=Filesystem.img \
    vec0:transport=tap,ifname=tap0,depth=128,gro=1 \
    root=/dev/ubda con=null con0=null,fd:2 con1=fd:0,fd:1

This will run an instance with ``2048M RAM`` and try to use the image file
called ``Filesystem.img`` as root. It will connect to the host using tap0.
All consoles except ``con1`` will be disabled and console 1 will
use standard input/output making it appear in the same terminal it was started.

Logging in
============

If you have not set up a password when generating the image, you will have to
shut down the UML instance, mount the image, chroot into it and set it - as
described in the Generating an Image section.  If the password is already set,
you can just log in.

The UML Management Console
============================

In addition to managing the image from "the inside" using normal sysadmin tools,
it is possible to perform a number of low-level operations using the UML
management console. The UML management console is a low-level interface to the
kernel on a running UML instance, somewhat like the i386 SysRq interface. Since
there is a full-blown operating system under UML, there is much greater
flexibility possible than with the SysRq mechanism.

There are a number of things you can do with the mconsole interface:

* get the kernel version
* add and remove devices
* halt or reboot the machine
* Send SysRq commands
* Pause and resume the UML
* Inspect processes running inside UML
* Inspect UML internal /proc state

You need the mconsole client (uml\_mconsole) which is a part of the UML
tools package available in most Linux distritions.

You also need ``CONFIG_MCONSOLE`` (under 'General Setup') enabled in the UML
kernel.  When you boot UML, you'll see a line like::

   mconsole initialized on /home/jdike/.uml/umlNJ32yL/mconsole

If you specify a unique machine id on the UML command line, i.e.
``umid=debian``, you'll see this::

   mconsole initialized on /home/jdike/.uml/debian/mconsole

That file is the socket that uml_mconsole will use to communicate with
UML.  Run it with either the umid or the full path as its argument::

   # uml_mconsole debian

or

   # uml_mconsole /home/jdike/.uml/debian/mconsole

You'll get a prompt, at which you can run one of these commands:

* version
* help
* halt
* reboot
* config
* remove
* sysrq
* help
* cad
* stop
* go
* proc
* stack

version
-------

This command takes no arguments.  It prints the UML version::

   (mconsole)  version
   OK Linux OpenWrt 4.14.106 #0 Tue Mar 19 08:19:41 2019 x86_64

There are a couple actual uses for this.  It's a simple no-op which
can be used to check that a UML is running.  It's also a way of
sending a device interrupt to the UML. UML mconsole is treated internally as
a UML device.

help
----

This command takes no arguments. It prints a short help screen with the
supported mconsole commands.

halt and reboot
---------------

These commands take no arguments.  They shut the machine down immediately, with
no syncing of disks and no clean shutdown of userspace.  So, they are
pretty close to crashing the machine::

   (mconsole)  halt
   OK

config
------

"config" adds a new device to the virtual machine. This is supported
by most UML device drivers. It takes one argument, which is the
device to add, with the same syntax as the kernel command line::

   (mconsole) config ubd3=/home/jdike/incoming/roots/root_fs_debian22

remove
------

"remove" deletes a device from the system.  Its argument is just the
name of the device to be removed. The device must be idle in whatever
sense the driver considers necessary.  In the case of the ubd driver,
the removed block device must not be mounted, swapped on, or otherwise
open, and in the case of the network driver, the device must be down::

   (mconsole)  remove ubd3

sysrq
-----

This command takes one argument, which is a single letter.  It calls the
generic kernel's SysRq driver, which does whatever is called for by
that argument.  See the SysRq documentation in
Documentation/admin-guide/sysrq.rst in your favorite kernel tree to
see what letters are valid and what they do.

cad
---

This invokes the ``Ctl-Alt-Del`` action in the running image.  What exactly
this ends up doing is up to init, systemd, etc.  Normally, it reboots the
machine.

stop
----

This puts the UML in a loop reading mconsole requests until a 'go'
mconsole command is received. This is very useful as a
debugging/snapshotting tool.

go
--

This resumes a UML after being paused by a 'stop' command. Note that
when the UML has resumed, TCP connections may have timed out and if
the UML is paused for a long period of time, crond might go a little
crazy, running all the jobs it didn't do earlier.

proc
----

This takes one argument - the name of a file in /proc which is printed
to the mconsole standard output

stack
-----

This takes one argument - the pid number of a process. Its stack is
printed to a standard output.

*******************
Advanced UML Topics
*******************

Sharing Filesystems between Virtual Machines
============================================

Don't attempt to share filesystems simply by booting two UMLs from the
same file.  That's the same thing as booting two physical machines
from a shared disk.  It will result in filesystem corruption.

Using layered block devices
---------------------------

The way to share a filesystem between two virtual machines is to use
the copy-on-write (COW) layering capability of the ubd block driver.
Any changed blocks are stored in the private COW file, while reads come
from either device - the private one if the requested block is valid in
it, the shared one if not.  Using this scheme, the majority of data
which is unchanged is shared between an arbitrary number of virtual
machines, each of which has a much smaller file containing the changes
that it has made.  With a large number of UMLs booting from a large root
filesystem, this leads to a huge disk space saving.

Sharing file system data will also help performance, since the host will
be able to cache the shared data using a much smaller amount of memory,
so UML disk requests will be served from the host's memory rather than
its disks.  There is a major caveat in doing this on multisocket NUMA
machines.  On such hardware, running many UML instances with a shared
master image and COW changes may cause issues like NMIs from excess of
inter-socket traffic.

If you are running UML on high-end hardware like this, make sure to
bind UML to a set of logical CPUs residing on the same socket using the
``taskset`` command or have a look at the "tuning" section.

To add a copy-on-write layer to an existing block device file, simply
add the name of the COW file to the appropriate ubd switch::

   ubd0=root_fs_cow,root_fs_debian_22

where ``root_fs_cow`` is the private COW file and ``root_fs_debian_22`` is
the existing shared filesystem.  The COW file need not exist.  If it
doesn't, the driver will create and initialize it.

Disk Usage
----------

UML has TRIM support which will release any unused space in its disk
image files to the underlying OS. It is important to use either ls -ls
or du to verify the actual file size.

COW validity.
-------------

Any changes to the master image will invalidate all COW files. If this
happens, UML will *NOT* automatically delete any of the COW files and
will refuse to boot. In this case the only solution is to either
restore the old image (including its last modified timestamp) or remove
all COW files which will result in their recreation. Any changes in
the COW files will be lost.

Cows can moo - uml_moo : Merging a COW file with its backing file
-----------------------------------------------------------------

Depending on how you use UML and COW devices, it may be advisable to
merge the changes in the COW file into the backing file every once in
a while.

The utility that does this is uml_moo.  Its usage is::

   uml_moo COW_file new_backing_file

There's no need to specify the backing file since that information is
already in the COW file header.  If you're paranoid, boot the new
merged file, and if you're happy with it, move it over the old backing
file.

``uml_moo`` creates a new backing file by default as a safety measure.
It also has a destructive merge option which will merge the COW file
directly into its current backing file.  This is really only usable
when the backing file only has one COW file associated with it.  If
there are multiple COWs associated with a backing file, a -d merge of
one of them will invalidate all of the others.  However, it is
convenient if you're short of disk space, and it should also be
noticeably faster than a non-destructive merge.

``uml_moo`` is installed with the UML distribution packages and is
available as a part of UML utilities.

Host file access
==================

If you want to access files on the host machine from inside UML, you
can treat it as a separate machine and either nfs mount directories
from the host or copy files into the virtual machine with scp.
However, since UML is running on the host, it can access those
files just like any other process and make them available inside the
virtual machine without the need to use the network.
This is possible with the hostfs virtual filesystem.  With it, you
can mount a host directory into the UML filesystem and access the
files contained in it just as you would on the host.

*SECURITY WARNING*

Hostfs without any parameters to the UML Image will allow the image
to mount any part of the host filesystem and write to it. Always
confine hostfs to a specific "harmless" directory (for example ``/var/tmp``)
if running UML. This is especially important if UML is being run as root.

Using hostfs
------------

To begin with, make sure that hostfs is available inside the virtual
machine with::

   # cat /proc/filesystems

``hostfs`` should be listed.  If it's not, either rebuild the kernel
with hostfs configured into it or make sure that hostfs is built as a
module and available inside the virtual machine, and insmod it.

Now all you need to do is run mount::

   # mount none /mnt/host -t hostfs

will mount the host's ``/`` on the virtual machine's ``/mnt/host``.
If you don't want to mount the host root directory, then you can
specify a subdirectory to mount with the -o switch to mount::

   # mount none /mnt/home -t hostfs -o /home

will mount the host's /home on the virtual machine's /mnt/home.

hostfs as the root filesystem
-----------------------------

It's possible to boot from a directory hierarchy on the host using
hostfs rather than using the standard filesystem in a file.
To start, you need that hierarchy.  The easiest way is to loop mount
an existing root_fs file::

   #  mount root_fs uml_root_dir -o loop

You need to change the filesystem type of ``/`` in ``etc/fstab`` to be
'hostfs', so that line looks like this::

   /dev/ubd/0       /        hostfs      defaults          1   1

Then you need to chown to yourself all the files in that directory
that are owned by root.  This worked for me::

   #  find . -uid 0 -exec chown jdike {} \;

Next, make sure that your UML kernel has hostfs compiled in, not as a
module.  Then run UML with the boot device pointing at that directory::

   ubd0=/path/to/uml/root/directory

UML should then boot as it does normally.

Hostfs Caveats
--------------

Hostfs does not support keeping track of host filesystem changes on the
host (outside UML). As a result, if a file is changed without UML's
knowledge, UML will not know about it and its own in-memory cache of
the file may be corrupt. While it is possible to fix this, it is not
something which is being worked on at present.

Tuning UML
============

UML at present is strictly uniprocessor. It will, however spin up a
number of threads to handle various functions.

The UBD driver, SIGIO and the MMU emulation do that. If the system is
idle, these threads will be migrated to other processors on a SMP host.
This, unfortunately, will usually result in LOWER performance because of
all of the cache/memory synchronization traffic between cores. As a
result, UML will usually benefit from being pinned on a single CPU,
especially on a large system. This can result in performance differences
of 5 times or higher on some benchmarks.

Similarly, on large multi-node NUMA systems UML will benefit if all of
its memory is allocated from the same NUMA node it will run on. The
OS will *NOT* do that by default. In order to do that, the sysadmin
needs to create a suitable tmpfs ramdisk bound to a particular node
and use that as the source for UML RAM allocation by specifying it
in the TMP or TEMP environment variables. UML will look at the values
of ``TMPDIR``, ``TMP`` or ``TEMP`` for that. If that fails, it will
look for shmfs mounted under ``/dev/shm``. If everything else fails use
``/tmp/`` regardless of the filesystem type used for it::

   mount -t tmpfs -ompol=bind:X none /mnt/tmpfs-nodeX
   TEMP=/mnt/tmpfs-nodeX taskset -cX linux options options options..

*******************************************
Contributing to UML and Developing with UML
*******************************************

UML is an excellent platform to develop new Linux kernel concepts -
filesystems, devices, virtualization, etc. It provides unrivalled
opportunities to create and test them without being constrained to
emulating specific hardware.

Example - want to try how Linux will work with 4096 "proper" network
devices?

Not an issue with UML. At the same time, this is something which
is difficult with other virtualization packages - they are
constrained by the number of devices allowed on the hardware bus
they are trying to emulate (for example 16 on a PCI bus in qemu).

If you have something to contribute such as a patch, a bugfix, a
new feature, please send it to ``linux-um@lists.infradead.org``.

Please follow all standard Linux patch guidelines such as cc-ing
relevant maintainers and run ``./scripts/checkpatch.pl`` on your patch.
For more details see ``Documentation/process/submitting-patches.rst``

Note - the list does not accept HTML or attachments, all emails must
be formatted as plain text.

Developing always goes hand in hand with debugging. First of all,
you can always run UML under gdb and there will be a whole section
later on on how to do that. That, however, is not the only way to
debug a Linux kernel. Quite often adding tracing statements and/or
using UML specific approaches such as ptracing the UML kernel process
are significantly more informative.

Tracing UML
=============

When running, UML consists of a main kernel thread and a number of
helper threads. The ones of interest for tracing are NOT the ones
that are already ptraced by UML as a part of its MMU emulation.

These are usually the first three threads visible in a ps display.
The one with the lowest PID number and using most CPU is usually the
kernel thread. The other threads are the disk
(ubd) device helper thread and the SIGIO helper thread.
Running ptrace on this thread usually results in the following picture::

   host$ strace -p 16566
   --- SIGIO {si_signo=SIGIO, si_code=POLL_IN, si_band=65} ---
   epoll_wait(4, [{EPOLLIN, {u32=3721159424, u64=3721159424}}], 64, 0) = 1
   epoll_wait(4, [], 64, 0)                = 0
   rt_sigreturn({mask=[PIPE]})             = 16967
   ptrace(PTRACE_GETREGS, 16967, NULL, 0xd5f34f38) = 0
   ptrace(PTRACE_GETREGSET, 16967, NT_X86_XSTATE, [{iov_base=0xd5f35010, iov_len=832}]) = 0
   ptrace(PTRACE_GETSIGINFO, 16967, NULL, {si_signo=SIGTRAP, si_code=0x85, si_pid=16967, si_uid=0}) = 0
   ptrace(PTRACE_SETREGS, 16967, NULL, 0xd5f34f38) = 0
   ptrace(PTRACE_SETREGSET, 16967, NT_X86_XSTATE, [{iov_base=0xd5f35010, iov_len=2696}]) = 0
   ptrace(PTRACE_SYSEMU, 16967, NULL, 0)   = 0
   --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=16967, si_uid=0, si_status=SIGTRAP, si_utime=65, si_stime=89} ---
   wait4(16967, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], WSTOPPED|__WALL, NULL) = 16967
   ptrace(PTRACE_GETREGS, 16967, NULL, 0xd5f34f38) = 0
   ptrace(PTRACE_GETREGSET, 16967, NT_X86_XSTATE, [{iov_base=0xd5f35010, iov_len=832}]) = 0
   ptrace(PTRACE_GETSIGINFO, 16967, NULL, {si_signo=SIGTRAP, si_code=0x85, si_pid=16967, si_uid=0}) = 0
   timer_settime(0, 0, {it_interval={tv_sec=0, tv_nsec=0}, it_value={tv_sec=0, tv_nsec=2830912}}, NULL) = 0
   getpid()                                = 16566
   clock_nanosleep(CLOCK_MONOTONIC, 0, {tv_sec=1, tv_nsec=0}, NULL) = ? ERESTART_RESTARTBLOCK (Interrupted by signal)
   --- SIGALRM {si_signo=SIGALRM, si_code=SI_TIMER, si_timerid=0, si_overrun=0, si_value={int=1631716592, ptr=0x614204f0}} ---
   rt_sigreturn({mask=[PIPE]})             = -1 EINTR (Interrupted system call)

This is a typical picture from a mostly idle UML instance.

* UML interrupt controller uses epoll - this is UML waiting for IO
  interrupts:

   epoll_wait(4, [{EPOLLIN, {u32=3721159424, u64=3721159424}}], 64, 0) = 1

* The sequence of ptrace calls is part of MMU emulation and running the
  UML userspace.
* ``timer_settime`` is part of the UML high res timer subsystem mapping
  timer requests from inside UML onto the host high resolution timers.
* ``clock_nanosleep`` is UML going into idle (similar to the way a PC
  will execute an ACPI idle).

As you can see UML will generate quite a bit of output even in idle. The output
can be very informative when observing IO. It shows the actual IO calls, their
arguments and returns values.

Kernel debugging
================

You can run UML under gdb now, though it will not necessarily agree to
be started under it. If you are trying to track a runtime bug, it is
much better to attach gdb to a running UML instance and let UML run.

Assuming the same PID number as in the previous example, this would be::

   # gdb -p 16566

This will STOP the UML instance, so you must enter `cont` at the GDB
command line to request it to continue. It may be a good idea to make
this into a gdb script and pass it to gdb as an argument.

Developing Device Drivers
=========================

Nearly all UML drivers are monolithic. While it is possible to build a
UML driver as a kernel module, that limits the possible functionality
to in-kernel only and non-UML specific.  The reason for this is that
in order to really leverage UML, one needs to write a piece of
userspace code which maps driver concepts onto actual userspace host
calls.

This forms the so-called "user" portion of the driver. While it can
reuse a lot of kernel concepts, it is generally just another piece of
userspace code. This portion needs some matching "kernel" code which
resides inside the UML image and which implements the Linux kernel part.

*Note: There are very few limitations in the way "kernel" and "user" interact*.

UML does not have a strictly defined kernel-to-host API. It does not
try to emulate a specific architecture or bus. UML's "kernel" and
"user" can share memory, code and interact as needed to implement
whatever design the software developer has in mind. The only
limitations are purely technical. Due to a lot of functions and
variables having the same names, the developer should be careful
which includes and libraries they are trying to refer to.

As a result a lot of userspace code consists of simple wrappers.
E.g. ``os_close_file()`` is just a wrapper around ``close()``
which ensures that the userspace function close does not clash
with similarly named function(s) in the kernel part.

Using UML as a Test Platform
============================

UML is an excellent test platform for device driver development. As
with most things UML, "some user assembly may be required". It is
up to the user to build their emulation environment. UML at present
provides only the kernel infrastructure.

Part of this infrastructure is the ability to load and parse fdt
device tree blobs as used in Arm or Open Firmware platforms. These
are supplied as an optional extra argument to the kernel command
line::

    dtb=filename

The device tree is loaded and parsed at boottime and is accessible by
drivers which query it. At this moment in time this facility is
intended solely for development purposes. UML's own devices do not
query the device tree.

Security Considerations
-----------------------

Drivers or any new functionality should default to not
accepting arbitrary filename, bpf code or other parameters
which can affect the host from inside the UML instance.
For example, specifying the socket used for IPC communication
between a driver and the host at the UML command line is OK
security-wise. Allowing it as a loadable module parameter
isn't.

If such functionality is desireable for a particular application
(e.g. loading BPF "firmware" for raw socket network transports),
it should be off by default and should be explicitly turned on
as a command line parameter at startup.

Even with this in mind, the level of isolation between UML
and the host is relatively weak. If the UML userspace is
allowed to load arbitrary kernel drivers, an attacker can
use this to break out of UML. Thus, if UML is used in
a production application, it is recommended that all modules
are loaded at boot and kernel module loading is disabled
afterwards.


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

================
1-Wire Subsystem
================

.. toctree::
   :maxdepth: 1

   w1-generic.rst
   w1-netlink.rst
   masters/index
   slaves/index

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`

repo_name: angery/linux


code:
====================
Kernel driver ds2482
====================

Supported chips:

  * Maxim DS2482-100, Maxim DS2482-800

    Prefix: 'ds2482'

    Addresses scanned: None

    Datasheets:

        - http://datasheets.maxim-ic.com/en/ds/DS2482-100.pdf
        - http://datasheets.maxim-ic.com/en/ds/DS2482-800.pdf

Author: Ben Gardner <bgardner@wabtec.com>

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

The Maxim/Dallas Semiconductor DS2482 is a I2C device that provides
one (DS2482-100) or eight (DS2482-800) 1-wire busses.

General Remarks
---------------

Valid addresses are 0x18, 0x19, 0x1a, and 0x1b.

However, the device cannot be detected without writing to the i2c bus, so no
detection is done. You should instantiate the device explicitly.

::

  $ modprobe ds2482
  $ echo ds2482 0x18 > /sys/bus/i2c/devices/i2c-0/new_device


code:
====================
Kernel driver ds2490
====================

Supported chips:

  * Maxim DS2490 based

Author: Evgeniy Polyakov <johnpol@2ka.mipt.ru>

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

The Maxim/Dallas Semiconductor DS2490 is a chip
which allows to build USB <-> W1 bridges.

DS9490(R) is a USB <-> W1 bus master device
which has 0x81 family ID integrated chip and DS2490
low-level operational chip.

Notes and limitations.

- The weak pullup current is a minimum of 0.9mA and maximum of 6.0mA.
- The 5V strong pullup is supported with a minimum of 5.9mA and a
  maximum of 30.4 mA.  (From DS2490.pdf)
- The hardware will detect when devices are attached to the bus on the
  next bus (reset?) operation, however only a message is printed as
  the core w1 code doesn't make use of the information.  Connecting
  one device tends to give multiple new device notifications.
- The number of USB bus transactions could be reduced if w1_reset_send
  was added to the API.  The name is just a suggestion.  It would take
  a write buffer and a read buffer (along with sizes) as arguments.
  The ds2490 block I/O command supports reset, write buffer, read
  buffer, and strong pullup all in one command, instead of the current
  1 reset bus, 2 write the match rom command and slave rom id, 3 block
  write and read data.  The write buffer needs to have the match rom
  command and slave rom id prepended to the front of the requested
  write buffer, both of which are known to the driver.
- The hardware supports normal, flexible, and overdrive bus
  communication speeds, but only the normal is supported.
- The registered w1_bus_master functions don't define error
  conditions.  If a bus search is in progress and the ds2490 is
  removed it can produce a good amount of error output before the bus
  search finishes.
- The hardware supports detecting some error conditions, such as
  short, alarming presence on reset, and no presence on reset, but the
  driver doesn't query those values.
- The ds2490 specification doesn't cover short bulk in reads in
  detail, but my observation is if fewer bytes are requested than are
  available, the bulk read will return an error and the hardware will
  clear the entire bulk in buffer.  It would be possible to read the
  maximum buffer size to not run into this error condition, only extra
  bytes in the buffer is a logic error in the driver.  The code should
  match reads and writes as well as data sizes.  Reads and
  writes are serialized and the status verifies that the chip is idle
  (and data is available) before the read is executed, so it should
  not happen.
- Running x86_64 2.6.24 UHCI under qemu 0.9.0 under x86_64 2.6.22-rc6
  with a OHCI controller, ds2490 running in the guest would operate
  normally the first time the module was loaded after qemu attached
  the ds2490 hardware, but if the module was unloaded, then reloaded
  most of the time one of the bulk out or in, and usually the bulk in
  would fail.  qemu sets a 50ms timeout and the bulk in would timeout
  even when the status shows data available.  A bulk out write would
  show a successful completion, but the ds2490 status register would
  show 0 bytes written.  Detaching qemu from the ds2490 hardware and
  reattaching would clear the problem.  usbmon output in the guest and
  host did not explain the problem.  My guess is a bug in either qemu
  or the host OS and more likely the host OS.

03-06-2008 David Fries <David@Fries.net>


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

=====================
1-wire Master Drivers
=====================

.. toctree::
   :maxdepth: 1

   ds2482
   ds2490
   mxc-w1
   omap-hdq
   w1-gpio


code:
====================
Kernel driver mxc_w1
====================

Supported chips:

  * Freescale MX27, MX31 and probably other i.MX SoCs

    Datasheets:

        - http://www.freescale.com/files/32bit/doc/data_sheet/MCIMX31.pdf?fpsp=1
	- http://cache.freescale.com/files/dsp/doc/archive/MCIMX27.pdf?fsrch=1&WT_TYPE=Data%20Sheets&WT_VENDOR=FREESCALE&WT_FILE_FORMAT=pdf&WT_ASSET=Documentation

Author:

	Originally based on Freescale code, prepared for mainline by
	Sascha Hauer <s.hauer@pengutronix.de>


code:
========================================
Kernel driver for omap HDQ/1-wire module
========================================

Supported chips:
================
HDQ/1-wire controller on the TI OMAP 2430/3430 platforms.

A useful link about HDQ basics:
===============================
http://focus.ti.com/lit/an/slua408a/slua408a.pdf

Description:
============
The HDQ/1-Wire module of TI OMAP2430/3430 platforms implement the hardware
protocol of the master functions of the Benchmark HDQ and the Dallas
Semiconductor 1-Wire protocols. These protocols use a single wire for
communication between the master (HDQ/1-Wire controller) and the slave
(HDQ/1-Wire external compliant device).

A typical application of the HDQ/1-Wire module is the communication with battery
monitor (gas gauge) integrated circuits.

The controller supports operation in both HDQ and 1-wire mode. The essential
difference between the HDQ and 1-wire mode is how the slave device responds to
initialization pulse.In HDQ mode, the firmware does not require the host to
create an initialization pulse to the slave.However, the slave can be reset by
using an initialization pulse (also referred to as a break pulse).The slave
does not respond with a presence pulse as it does in the 1-Wire protocol.

Remarks:
========
The driver (drivers/w1/masters/omap_hdq.c) supports the HDQ mode of the
controller. In this mode, as we can not read the ID which obeys the W1
spec(family:id:crc), a module parameter can be passed to the driver which will
be used to calculate the CRC and pass back an appropriate slave ID to the W1
core.

By default the master driver and the BQ slave i/f
driver(drivers/w1/slaves/w1_bq27000.c) sets the ID to 1.
Please note to load both the modules with a different ID if required, but note
that the ID used should be same for both master and slave driver loading.

e.g::

  insmod omap_hdq.ko W1_ID=2
  insmod w1_bq27000.ko F_ID=2

The driver also supports 1-wire mode. In this mode, there is no need to
pass slave ID as parameter. The driver will auto-detect slaves connected
to the bus using SEARCH_ROM procedure. 1-wire mode can be selected by
setting "ti,mode" property to "1w" in DT (see
Documentation/devicetree/bindings/w1/omap-hdq.txt for more details).
By default driver is in HDQ mode.


code:
=====================
Kernel driver w1-gpio
=====================

Author: Ville Syrjala <syrjala@sci.fi>

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

GPIO 1-wire bus master driver. The driver uses the GPIO API to control the
wire and the GPIO pin can be specified using GPIO machine descriptor tables.
It is also possible to define the master using device tree, see
Documentation/devicetree/bindings/w1/w1-gpio.yaml

Example (mach-at91)
-------------------

::

  #include <linux/gpio/machine.h>
  #include <linux/w1-gpio.h>

  static struct gpiod_lookup_table foo_w1_gpiod_table = {
	.dev_id = "w1-gpio",
	.table = {
		GPIO_LOOKUP_IDX("at91-gpio", AT91_PIN_PB20, NULL, 0,
			GPIO_ACTIVE_HIGH|GPIO_OPEN_DRAIN),
	},
  };

  static struct w1_gpio_platform_data foo_w1_gpio_pdata = {
	.ext_pullup_enable_pin	= -EINVAL,
  };

  static struct platform_device foo_w1_device = {
	.name			= "w1-gpio",
	.id			= -1,
	.dev.platform_data	= &foo_w1_gpio_pdata,
  };

  ...
	at91_set_GPIO_periph(foo_w1_gpio_pdata.pin, 1);
	at91_set_multi_drive(foo_w1_gpio_pdata.pin, 1);
	gpiod_add_lookup_table(&foo_w1_gpiod_table);
	platform_device_register(&foo_w1_device);


code:
=======================
w1_ds2406 kernel driver
=======================

Supported chips:

  * Maxim DS2406 (and other family 0x12) addressable switches

Author: Scott Alfter <scott@alfter.us>

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

The w1_ds2406 driver allows connected devices to be switched on and off.
These chips also provide 128 bytes of OTP EPROM, but reading/writing it is
not supported.  In TSOC-6 form, the DS2406 provides two switch outputs and
can be provided with power on a dedicated input.  In TO-92 form, it provides
one output and uses parasitic power only.

The driver provides two sysfs files.  state is readable; it gives the
current state of each switch, with PIO A in bit 0 and PIO B in bit 1.  The
driver ORs this state with 0x30, so shell scripts get an ASCII 0/1/2/3 to
work with.  output is writable; bits 0 and 1 control PIO A and B,
respectively.  Bits 2-7 are ignored, so it's safe to write ASCII data.

CRCs are checked on read and write.  Failed checks cause an I/O error to be
returned.  On a failed write, the switch status is not changed.


code:
=======================
Kernel driver w1_ds2413
=======================

Supported chips:

  * Maxim DS2413 1-Wire Dual Channel Addressable Switch

supported family codes:

        ================        ====
        W1_FAMILY_DS2413        0x3A
        ================        ====

Author: Mariusz Bialonczyk <manio@skyboo.net>

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

The DS2413 chip has two open-drain outputs (PIO A and PIO B).
Support is provided through the sysfs files "output" and "state".

Reading state
-------------
The "state" file provides one-byte value which is in the same format as for
the chip PIO_ACCESS_READ command (refer the datasheet for details):

======== =============================================================
Bit 0:   PIOA Pin State
Bit 1:   PIOA Output Latch State
Bit 2:   PIOB Pin State
Bit 3:   PIOB Output Latch State
Bit 4-7: Complement of Bit 3 to Bit 0 (verified by the kernel module)
======== =============================================================

This file is readonly.

Writing output
--------------
You can set the PIO pins using the "output" file.
It is writable, you can write one-byte value to this sysfs file.
Similarly the byte format is the same as for the PIO_ACCESS_WRITE command:

======== ======================================
Bit 0:   PIOA
Bit 1:   PIOB
Bit 2-7: No matter (driver will set it to "1"s)
======== ======================================

The chip has some kind of basic protection against transmission errors.
When reading the state, there is a four complement bits.
The driver is checking this complement, and when it is wrong then it is
returning I/O error.

When writing output, the master must repeat the PIO Output Data byte in
its inverted form and it is waiting for a confirmation.
If the write is unsuccessful for three times, the write also returns
I/O error.


code:
Kernel driver w1_ds2423
=======================

Supported chips:

  * Maxim DS2423 based counter devices.

supported family codes:

        ===============	====
	W1_THERM_DS2423	0x1D
        ===============	====

Author: Mika Laitio <lamikr@pilppa.org>

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

Support is provided through the sysfs w1_slave file. Each opening and
read sequence of w1_slave file initiates the read of counters and ram
available in DS2423 pages 12 - 15.

Result of each page is provided as an ASCII output where each counter
value and associated ram buffer is outpputed to own line.

Each lines will contain the values of 42 bytes read from the counter and
memory page along the crc=YES or NO for indicating whether the read operation
was successful and CRC matched.
If the operation was successful, there is also in the end of each line
a counter value expressed as an integer after c=

Meaning of 42 bytes represented is following:

 - 1 byte from ram page
 - 4 bytes for the counter value
 - 4 zero bytes
 - 2 bytes for crc16 which was calculated from the data read since the previous crc bytes
 - 31 remaining bytes from the ram page
 - crc=YES/NO indicating whether read was ok and crc matched
 - c=<int> current counter value

example from the successful read::

  00 02 00 00 00 00 00 00 00 6d 38 00 ff ff 00 00 fe ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff crc=YES c=2
  00 02 00 00 00 00 00 00 00 e0 1f 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff crc=YES c=2
  00 29 c6 5d 18 00 00 00 00 04 37 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff crc=YES c=408798761
  00 05 00 00 00 00 00 00 00 8d 39 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff crc=YES c=5

example from the read with crc errors::

  00 02 00 00 00 00 00 00 00 6d 38 00 ff ff 00 00 fe ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff crc=YES c=2
  00 02 00 00 22 00 00 00 00 e0 1f 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff crc=NO
  00 e1 61 5d 19 00 00 00 00 df 0b 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff 00 00 ff ff crc=NO
  00 05 00 00 20 00 00 00 00 8d 39 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff crc=NO


code:
Kernel driver w1_ds2438
=======================

Supported chips:

  * Maxim DS2438 Smart Battery Monitor

supported family codes:
        ================        ====
        W1_FAMILY_DS2438        0x26
        ================        ====

Author: Mariusz Bialonczyk <manio@skyboo.net>

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

The DS2438 chip provides several functions that are desirable to carry in
a battery pack. It also has a 40 bytes of nonvolatile EEPROM.
Because the ability of temperature, current and voltage measurement, the chip
is also often used in weather stations and applications such as: rain gauge,
wind speed/direction measuring, humidity sensing, etc.

Current support is provided through the following sysfs files (all files
except "iad" and "offset" are readonly):

"iad"
-----
This file controls the 'Current A/D Control Bit' (IAD) in the
Status/Configuration Register.
Writing a zero value will clear the IAD bit and disables the current
measurements.
Writing value "1" is setting the IAD bit (enables the measurements).
The IAD bit is enabled by default in the DS2438.

When writing to sysfs file bits 2-7 are ignored, so it's safe to write ASCII.
An I/O error is returned when there is a problem setting the new value.

"page0"
-------
This file provides full 8 bytes of the chip Page 0 (00h).
This page contains the most frequently accessed information of the DS2438.
Internally when this file is read, the additional CRC byte is also obtained
from the slave device. If it is correct, the 8 bytes page data are passed
to userspace, otherwise an I/O error is returned.

"page1"
-------
This file provides full 8 bytes of the chip Page 1 (01h).
This page contains the ICA, elapsed time meter and current offset data of the DS2438.
Internally when this file is read, the additional CRC byte is also obtained
from the slave device. If it is correct, the 8 bytes page data are passed
to userspace, otherwise an I/O error is returned.

"offset"
--------
This file controls the 2-byte Offset Register of the chip.
Writing a 2-byte value will change the Offset Register, which changes the
current measurement done by the chip. Changing this register to the two's complement
of the current register while forcing zero current through the load will calibrate
the chip, canceling offset errors in the current ADC.

"temperature"
-------------
Opening and reading this file initiates the CONVERT_T (temperature conversion)
command of the chip, afterwards the temperature is read from the device
registers and provided as an ASCII decimal value.

Important: The returned value has to be divided by 256 to get a real
temperature in degrees Celsius.

"vad", "vdd"
------------
Opening and reading this file initiates the CONVERT_V (voltage conversion)
command of the chip.

Depending on a sysfs filename a different input for the A/D will be selected:

vad:
    general purpose A/D input (VAD)
vdd:
    battery input (VDD)

After the voltage conversion the value is returned as decimal ASCII.
Note: To get a volts the value has to be divided by 100.


code:
========================
Kernel driver w1_ds28e04
========================

Supported chips:

  * Maxim DS28E04-100 4096-Bit Addressable 1-Wire EEPROM with PIO

supported family codes:

        =================	====
	W1_FAMILY_DS28E04	0x1C
        =================	====

Author: Markus Franke, <franke.m@sebakmt.com> <franm@hrz.tu-chemnitz.de>

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

Support is provided through the sysfs files "eeprom" and "pio". CRC checking
during memory accesses can optionally be enabled/disabled via the device
attribute "crccheck". The strong pull-up can optionally be enabled/disabled
via the module parameter "w1_strong_pullup".

Memory Access

	A read operation on the "eeprom" file reads the given amount of bytes
	from the EEPROM of the DS28E04.

	A write operation on the "eeprom" file writes the given byte sequence
	to the EEPROM of the DS28E04. If CRC checking mode is enabled only
	fully aligned blocks of 32 bytes with valid CRC16 values (in bytes 30
	and 31) are allowed to be written.

PIO Access

	The 2 PIOs of the DS28E04-100 are accessible via the "pio" sysfs file.

	The current status of the PIO's is returned as an 8 bit value. Bit 0/1
	represent the state of PIO_0/PIO_1. Bits 2..7 do not care. The PIO's are
	driven low-active, i.e. the driver delivers/expects low-active values.


code:
========================
Kernel driver w1_ds28e17
========================

Supported chips:

  * Maxim DS28E17 1-Wire-to-I2C Master Bridge

supported family codes:

        =================  ====
	W1_FAMILY_DS28E17  0x19
        =================  ====

Author: Jan Kandziora <jjj@gmx.de>

Description
-----------
The DS28E17 is a Onewire slave device which acts as an I2C bus master.

This driver creates a new I2C bus for any DS28E17 device detected. I2C buses
come and go as the DS28E17 devices come and go. I2C slave devices connected to
a DS28E17 can be accessed by the kernel or userspace tools as if they were
connected to a "native" I2C bus master.

An udev rule like the following::

  SUBSYSTEM=="i2c-dev", KERNEL=="i2c-[0-9]*", ATTRS{name}=="w1-19-*", \
          SYMLINK+="i2c-$attr{name}"

may be used to create stable /dev/i2c- entries based on the unique id of the
DS28E17 chip.

Driver parameters are:

speed:
	This sets up the default I2C speed a DS28E17 get configured for as soon
	it is connected. The power-on default	of the DS28E17 is 400kBaud, but
	chips may come and go on the Onewire bus without being de-powered and
	as soon the "w1_ds28e17" driver notices a freshly connected, or
	reconnected DS28E17 device on the Onewire bus, it will re-apply this
	setting.

	Valid values are 100, 400, 900 [kBaud]. Any other value means to leave
	alone the current DS28E17 setting on detect. The default value is 100.

stretch:
	This sets up the default stretch value used for freshly connected
	DS28E17 devices. It is a multiplier used on the calculation of the busy
	wait time for an I2C transfer. This is to account for I2C slave devices
	which make heavy use of the I2C clock stretching feature and thus, the
	needed timeout cannot be pre-calculated correctly. As the w1_ds28e17
	driver checks the DS28E17's busy flag in a loop after the precalculated
	wait time, it should be hardly needed to tweak this setting.

	Leave it at 1 unless you get ETIMEDOUT errors and a "w1_slave_driver
	19-00000002dbd8: busy timeout" in the kernel log.

	Valid values are 1 to 9. The default is 1.

The driver creates sysfs files /sys/bus/w1/devices/19-<id>/speed and
/sys/bus/w1/devices/19-<id>/stretch for each device, preloaded with the default
settings from the driver parameters. They may be changed anytime. In addition a
directory /sys/bus/w1/devices/19-<id>/i2c-<nnn> for the I2C bus master sysfs
structure is created.

See https://github.com/ianka/w1_ds28e17 for even more information.


code:
======================
Kernel driver w1_therm
======================

Supported chips:

  * Maxim ds18*20 based temperature sensors.
  * Maxim ds1825 based temperature sensors.
  * GXCAS GX20MH01 temperature sensor.
  * Maxim MAX31850 thermoelement interface.

Author: Evgeniy Polyakov <johnpol@2ka.mipt.ru>

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

w1_therm provides basic temperature conversion for ds18*20, ds28ea00, GX20MH01
and MAX31850 devices.

Supported family codes:

====================	====
W1_THERM_DS18S20	0x10
W1_THERM_DS1822		0x22
W1_THERM_DS18B20	0x28
W1_THERM_DS1825		0x3B
W1_THERM_DS28EA00	0x42
====================	====

Support is provided through the sysfs entry ``w1_slave``. Each open and
read sequence will initiate a temperature conversion, then provide two
lines of ASCII output. The first line contains the nine hex bytes
read along with a calculated crc value and YES or NO if it matched.
If the crc matched the returned values are retained. The second line
displays the retained values along with a temperature in millidegrees
Centigrade after t=.

Alternatively, temperature can be read using ``temperature`` sysfs, it
returns only the temperature in millidegrees Centigrade.

A bulk read of all devices on the bus could be done writing ``trigger``
to ``therm_bulk_read`` entry at w1_bus_master level. This will
send the convert command to all devices on the bus, and if parasite
powered devices are detected on the bus (and strong pullup is enabled
in the module), it will drive the line high during the longer conversion
time required by parasited powered device on the line. Reading
``therm_bulk_read`` will return 0 if no bulk conversion pending,
-1 if at least one sensor still in conversion, 1 if conversion is complete
but at least one sensor value has not been read yet. Result temperature is
then accessed by reading the ``temperature`` entry of each device, which
may return empty if conversion is still in progress. Note that if a bulk
read is sent but one sensor is not read immediately, the next access to
``temperature`` on this device will return the temperature measured at the
time of issue of the bulk read command (not the current temperature).

A strong pullup will be applied during the conversion if required.

``conv_time`` is used to get current conversion time (read), and
adjust it (write). A temperature conversion time depends on the device type and
it's current resolution. Default conversion time is set by the driver according
to the device datasheet. A conversion time for many original device clones
deviate from datasheet specs. There are three options: 1) manually set the
correct conversion time by writing a value in milliseconds to ``conv_time``; 2)
auto measure and set a conversion time by writing ``1`` to
``conv_time``; 3) use ``features`` to enable poll for conversion
completion. Options 2, 3 can't be used in parasite power mode. To get back to
the default conversion time write ``0`` to ``conv_time``.

Writing a resolution value (in bits) to ``w1_slave`` will change the
precision of the sensor for the next readings. Allowed resolutions are defined by
the sensor. Resolution is reset when the sensor gets power-cycled.

To store the current resolution in EEPROM, write ``0`` to ``w1_slave``.
Since the EEPROM has a limited amount of writes (>50k), this command should be
used wisely.

Alternatively, resolution can be read or written using the dedicated
``resolution`` entry on each device, if supported by the sensor.

Some non-genuine DS18B20 chips are fixed in 12-bit mode only, so the actual
resolution is read back from the chip and verified.

Note: Changing the resolution reverts the conversion time to default.

The write-only sysfs entry ``eeprom_cmd`` is an alternative for EEPROM operations.
Write ``save`` to save device RAM to EEPROM. Write ``restore`` to restore EEPROM
data in device RAM.

``ext_power`` entry allows checking the power state of each device. Reads
``0`` if the device is parasite powered, ``1`` if the device is externally powered.

Sysfs ``alarms`` allow read or write TH and TL (Temperature High an Low) alarms.
Values shall be space separated and in the device range (typical -55 degC
to 125 degC). Values are integer as they are store in a 8bit register in
the device. Lowest value is automatically put to TL. Once set, alarms could
be search at master level.

The module parameter strong_pullup can be set to 0 to disable the
strong pullup, 1 to enable autodetection or 2 to force strong pullup.
In case of autodetection, the driver will use the "READ POWER SUPPLY"
command to check if there are pariste powered devices on the bus.
If so, it will activate the master's strong pullup.
In case the detection of parasite devices using this command fails
(seems to be the case with some DS18S20) the strong pullup can
be force-enabled.

If the strong pullup is enabled, the master's strong pullup will be
driven when the conversion is taking place, provided the master driver
does support the strong pullup (or it falls back to a pullup
resistor).  The DS18b20 temperature sensor specification lists a
maximum current draw of 1.5mA and that a 5k pullup resistor is not
sufficient.  The strong pullup is designed to provide the additional
current required.

The DS28EA00 provides an additional two pins for implementing a sequence
detection algorithm.  This feature allows you to determine the physical
location of the chip in the 1-wire bus without needing pre-existing
knowledge of the bus ordering.  Support is provided through the sysfs
``w1_seq``. The file will contain a single line with an integer value
representing the device index in the bus starting at 0.

``features`` sysfs entry controls optional driver settings per device.
Insufficient power in parasite mode, line noise and insufficient conversion
time may lead to conversion failure. Original DS18B20 and some clones allow for
detection of invalid conversion. Write bit mask ``1`` to ``features`` to enable
checking the conversion success. If byte 6 of scratchpad memory is 0xC after
conversion and temperature reads 85.00 (powerup value) or 127.94 (insufficient
power), the driver returns a conversion error. Bit mask ``2`` enables poll for
conversion completion (normal power only) by generating read cycles on the bus
after conversion starts. In parasite power mode this feature is not available.
Feature bit masks may be combined (OR). More details in
Documentation/ABI/testing/sysfs-driver-w1_therm

GX20MH01 device shares family number 0x28 with DS18*20. The device is generally
compatible with DS18B20. Added are lowest 2\ :sup:`-5`, 2\ :sup:`-6` temperature
bits in Config register; R2 bit in Config register enabling 13 and 14 bit
resolutions. The device is powered up in 14-bit resolution mode. The conversion
times specified in the datasheet are too low and have to be increased. The
device supports driver features ``1`` and ``2``.

MAX31850 device shares family number 0x3B with DS1825. The device is generally
compatible with DS1825. The higher 4 bits of Config register read all 1,
indicating 15, but the device is always operating in 14-bit resolution mode.


code:
=========================================
Introduction to the 1-wire (w1) subsystem
=========================================

The 1-wire bus is a simple master-slave bus that communicates via a single
signal wire (plus ground, so two wires).

Devices communicate on the bus by pulling the signal to ground via an open
drain output and by sampling the logic level of the signal line.

The w1 subsystem provides the framework for managing w1 masters and
communication with slaves.

All w1 slave devices must be connected to a w1 bus master device.

Example w1 master devices:

    - DS9490 usb device
    - W1-over-GPIO
    - DS2482 (i2c to w1 bridge)
    - Emulated devices, such as a RS232 converter, parallel port adapter, etc

What does the w1 subsystem do?
------------------------------

When a w1 master driver registers with the w1 subsystem, the following occurs:

 - sysfs entries for that w1 master are created
 - the w1 bus is periodically searched for new slave devices

When a device is found on the bus, w1 core tries to load the driver for its family
and check if it is loaded. If so, the family driver is attached to the slave.
If there is no driver for the family, default one is assigned, which allows to perform
almost any kind of operations. Each logical operation is a transaction
in nature, which can contain several (two or one) low-level operations.
Let's see how one can read EEPROM context:
1. one must write control buffer, i.e. buffer containing command byte
and two byte address. At this step bus is reset and appropriate device
is selected using either W1_SKIP_ROM or W1_MATCH_ROM command.
Then provided control buffer is being written to the wire.
2. reading. This will issue reading eeprom response.

It is possible that between 1. and 2. w1 master thread will reset bus for searching
and slave device will be even removed, but in this case 0xff will
be read, since no device was selected.

W1 device families
------------------

Slave devices are handled by a driver written for a family of w1 devices.

A family driver populates a struct w1_family_ops (see w1_family.h) and
registers with the w1 subsystem.

Current family drivers:

w1_therm
  - (ds18?20 thermal sensor family driver)
    provides temperature reading function which is bound to ->rbin() method
    of the above w1_family_ops structure.

w1_smem
  - driver for simple 64bit memory cell provides ID reading method.

You can call above methods by reading appropriate sysfs files.

What does a w1 master driver need to implement?
-----------------------------------------------

The driver for w1 bus master must provide at minimum two functions.

Emulated devices must provide the ability to set the output signal level
(write_bit) and sample the signal level (read_bit).

Devices that support the 1-wire natively must provide the ability to write and
sample a bit (touch_bit) and reset the bus (reset_bus).

Most hardware provides higher-level functions that offload w1 handling.
See struct w1_bus_master definition in w1.h for details.

w1 master sysfs interface
-------------------------

========================= =====================================================
<xx-xxxxxxxxxxxx>         A directory for a found device. The format is
                          family-serial
bus                       (standard) symlink to the w1 bus
driver                    (standard) symlink to the w1 driver
w1_master_add             (rw) manually register a slave device
w1_master_attempts        (ro) the number of times a search was attempted
w1_master_max_slave_count (rw) maximum number of slaves to search for at a time
w1_master_name            (ro) the name of the device (w1_bus_masterX)
w1_master_pullup          (rw) 5V strong pullup 0 enabled, 1 disabled
w1_master_remove          (rw) manually remove a slave device
w1_master_search          (rw) the number of searches left to do,
                          -1=continual (default)
w1_master_slave_count     (ro) the number of slaves found
w1_master_slaves          (ro) the names of the slaves, one per line
w1_master_timeout         (ro) the delay in seconds between searches
w1_master_timeout_us      (ro) the delay in microseconds beetwen searches
========================= =====================================================

If you have a w1 bus that never changes (you don't add or remove devices),
you can set the module parameter search_count to a small positive number
for an initially small number of bus searches.  Alternatively it could be
set to zero, then manually add the slave device serial numbers by
w1_master_add device file.  The w1_master_add and w1_master_remove files
generally only make sense when searching is disabled, as a search will
redetect manually removed devices that are present and timeout manually
added devices that aren't on the bus.

Bus searches occur at an interval, specified as a sum of timeout and
timeout_us module parameters (either of which may be 0) for as long as
w1_master_search remains greater than 0 or is -1.  Each search attempt
decrements w1_master_search by 1 (down to 0) and increments
w1_master_attempts by 1.

w1 slave sysfs interface
------------------------

=================== ============================================================
bus                 (standard) symlink to the w1 bus
driver              (standard) symlink to the w1 driver
name                the device name, usually the same as the directory name
w1_slave            (optional) a binary file whose meaning depends on the
                    family driver
rw		    (optional) created for slave devices which do not have
		    appropriate family driver. Allows to read/write binary data.
=================== ============================================================


code:
===============================================
Userspace communication protocol over connector
===============================================

Message types
=============

There are three types of messages between w1 core and userspace:

1. Events. They are generated each time a new master or slave device
   is found either due to automatic or requested search.
2. Userspace commands.
3. Replies to userspace commands.

Protocol
========

::

  [struct cn_msg] - connector header.
	Its length field is equal to size of the attached data
  [struct w1_netlink_msg] - w1 netlink header.
	__u8 type 	- message type.
			W1_LIST_MASTERS
				list current bus masters
			W1_SLAVE_ADD/W1_SLAVE_REMOVE
				slave add/remove events
			W1_MASTER_ADD/W1_MASTER_REMOVE
				master add/remove events
			W1_MASTER_CMD
				userspace command for bus master
				device (search/alarm search)
			W1_SLAVE_CMD
				userspace command for slave device
				(read/write/touch)
	__u8 status	- error indication from kernel
	__u16 len	- size of data attached to this header data
	union {
		__u8 id[8];			 - slave unique device id
		struct w1_mst {
			__u32		id;	 - master's id
			__u32		res;	 - reserved
		} mst;
	} id;

  [struct w1_netlink_cmd] - command for given master or slave device.
	__u8 cmd	- command opcode.
			W1_CMD_READ 	- read command
			W1_CMD_WRITE	- write command
			W1_CMD_SEARCH	- search command
			W1_CMD_ALARM_SEARCH - alarm search command
			W1_CMD_TOUCH	- touch command
				(write and sample data back to userspace)
			W1_CMD_RESET	- send bus reset
			W1_CMD_SLAVE_ADD	- add slave to kernel list
			W1_CMD_SLAVE_REMOVE	- remove slave from kernel list
			W1_CMD_LIST_SLAVES	- get slaves list from kernel
	__u8 res	- reserved
	__u16 len	- length of data for this command
		For read command data must be allocated like for write command
	__u8 data[0]	- data for this command

Each connector message can include one or more w1_netlink_msg with
zero or more attached w1_netlink_cmd messages.

For event messages there are no w1_netlink_cmd embedded structures,
only connector header and w1_netlink_msg strucutre with "len" field
being zero and filled type (one of event types) and id:
either 8 bytes of slave unique id in host order,
or master's id, which is assigned to bus master device
when it is added to w1 core.

Currently replies to userspace commands are only generated for read
command request. One reply is generated exactly for one w1_netlink_cmd
read request. Replies are not combined when sent - i.e. typical reply
messages looks like the following::

  [cn_msg][w1_netlink_msg][w1_netlink_cmd]
  cn_msg.len = sizeof(struct w1_netlink_msg) +
	     sizeof(struct w1_netlink_cmd) +
	     cmd->len;
  w1_netlink_msg.len = sizeof(struct w1_netlink_cmd) + cmd->len;
  w1_netlink_cmd.len = cmd->len;

Replies to W1_LIST_MASTERS should send a message back to the userspace
which will contain list of all registered master ids in the following
format::

	cn_msg (CN_W1_IDX.CN_W1_VAL as id, len is equal to sizeof(struct
	w1_netlink_msg) plus number of masters multiplied by 4)
	w1_netlink_msg (type: W1_LIST_MASTERS, len is equal to
		number of masters multiplied by 4 (u32 size))
	id0 ... idN

Each message is at most 4k in size, so if number of master devices
exceeds this, it will be split into several messages.

W1 search and alarm search commands.

request::

  [cn_msg]
    [w1_netlink_msg type = W1_MASTER_CMD
	id is equal to the bus master id to use for searching]
    [w1_netlink_cmd cmd = W1_CMD_SEARCH or W1_CMD_ALARM_SEARCH]

reply::

  [cn_msg, ack = 1 and increasing, 0 means the last message,
	seq is equal to the request seq]
  [w1_netlink_msg type = W1_MASTER_CMD]
  [w1_netlink_cmd cmd = W1_CMD_SEARCH or W1_CMD_ALARM_SEARCH
	len is equal to number of IDs multiplied by 8]
  [64bit-id0 ... 64bit-idN]

Length in each header corresponds to the size of the data behind it, so
w1_netlink_cmd->len = N * 8; where N is number of IDs in this message.
Can be zero.

::

  w1_netlink_msg->len = sizeof(struct w1_netlink_cmd) + N * 8;
  cn_msg->len = sizeof(struct w1_netlink_msg) +
	      sizeof(struct w1_netlink_cmd) +
	      N*8;

W1 reset command::

  [cn_msg]
    [w1_netlink_msg type = W1_MASTER_CMD
	id is equal to the bus master id to use for searching]
    [w1_netlink_cmd cmd = W1_CMD_RESET]

Command status replies
======================

Each command (either root, master or slave with or without w1_netlink_cmd
structure) will be 'acked' by the w1 core. Format of the reply is the same
as request message except that length parameters do not account for data
requested by the user, i.e. read/write/touch IO requests will not contain
data, so w1_netlink_cmd.len will be 0, w1_netlink_msg.len will be size
of the w1_netlink_cmd structure and cn_msg.len will be equal to the sum
of the sizeof(struct w1_netlink_msg) and sizeof(struct w1_netlink_cmd).
If reply is generated for master or root command (which do not have
w1_netlink_cmd attached), reply will contain only cn_msg and w1_netlink_msg
structures.

w1_netlink_msg.status field will carry positive error value
(EINVAL for example) or zero in case of success.

All other fields in every structure will mirror the same parameters in the
request message (except lengths as described above).

Status reply is generated for every w1_netlink_cmd embedded in the
w1_netlink_msg, if there are no w1_netlink_cmd structures,
reply will be generated for the w1_netlink_msg.

All w1_netlink_cmd command structures are handled in every w1_netlink_msg,
even if there were errors, only length mismatch interrupts message processing.

Operation steps in w1 core when new command is received
=======================================================

When new message (w1_netlink_msg) is received w1 core detects if it is
master or slave request, according to w1_netlink_msg.type field.
Then master or slave device is searched for.
When found, master device (requested or those one on where slave device
is found) is locked. If slave command is requested, then reset/select
procedure is started to select given device.

Then all requested in w1_netlink_msg operations are performed one by one.
If command requires reply (like read command) it is sent on command completion.

When all commands (w1_netlink_cmd) are processed master device is unlocked
and next w1_netlink_msg header processing started.

Connector [1] specific documentation
====================================

Each connector message includes two u32 fields as "address".
w1 uses CN_W1_IDX and CN_W1_VAL defined in include/linux/connector.h header.
Each message also includes sequence and acknowledge numbers.
Sequence number for event messages is appropriate bus master sequence number
increased with each event message sent "through" this master.
Sequence number for userspace requests is set by userspace application.
Sequence number for reply is the same as was in request, and
acknowledge number is set to seq+1.

Additional documentation, source code examples
==============================================

1. Documentation/driver-api/connector.rst
2. http://www.ioremap.net/archive/w1

   This archive includes userspace application w1d.c which uses
   read/write/search commands for all master/slave devices found on the bus.


code:
=========================================================
Converting old watchdog drivers to the watchdog framework
=========================================================

by Wolfram Sang <wsa@kernel.org>

Before the watchdog framework came into the kernel, every driver had to
implement the API on its own. Now, as the framework factored out the common
components, those drivers can be lightened making it a user of the framework.
This document shall guide you for this task. The necessary steps are described
as well as things to look out for.

Remove the file_operations struct
---------------------------------

Old drivers define their own file_operations for actions like open(), write(),
etc... These are now handled by the framework and just call the driver when
needed. So, in general, the 'file_operations' struct and assorted functions can
go. Only very few driver-specific details have to be moved to other functions.
Here is a overview of the functions and probably needed actions:

- open: Everything dealing with resource management (file-open checks, magic
  close preparations) can simply go. Device specific stuff needs to go to the
  driver specific start-function. Note that for some drivers, the start-function
  also serves as the ping-function. If that is the case and you need start/stop
  to be balanced (clocks!), you are better off refactoring a separate start-function.

- close: Same hints as for open apply.

- write: Can simply go, all defined behaviour is taken care of by the framework,
  i.e. ping on write and magic char ('V') handling.

- ioctl: While the driver is allowed to have extensions to the IOCTL interface,
  the most common ones are handled by the framework, supported by some assistance
  from the driver:

	WDIOC_GETSUPPORT:
		Returns the mandatory watchdog_info struct from the driver

	WDIOC_GETSTATUS:
		Needs the status-callback defined, otherwise returns 0

	WDIOC_GETBOOTSTATUS:
		Needs the bootstatus member properly set. Make sure it is 0 if you
		don't have further support!

	WDIOC_SETOPTIONS:
		No preparations needed

	WDIOC_KEEPALIVE:
		If wanted, options in watchdog_info need to have WDIOF_KEEPALIVEPING
		set

	WDIOC_SETTIMEOUT:
		Options in watchdog_info need to have WDIOF_SETTIMEOUT set
		and a set_timeout-callback has to be defined. The core will also
		do limit-checking, if min_timeout and max_timeout in the watchdog
		device are set. All is optional.

	WDIOC_GETTIMEOUT:
		No preparations needed

	WDIOC_GETTIMELEFT:
		It needs get_timeleft() callback to be defined. Otherwise it
		will return EOPNOTSUPP

  Other IOCTLs can be served using the ioctl-callback. Note that this is mainly
  intended for porting old drivers; new drivers should not invent private IOCTLs.
  Private IOCTLs are processed first. When the callback returns with
  -ENOIOCTLCMD, the IOCTLs of the framework will be tried, too. Any other error
  is directly given to the user.

Example conversion::

  -static const struct file_operations s3c2410wdt_fops = {
  -       .owner          = THIS_MODULE,
  -       .llseek         = no_llseek,
  -       .write          = s3c2410wdt_write,
  -       .unlocked_ioctl = s3c2410wdt_ioctl,
  -       .open           = s3c2410wdt_open,
  -       .release        = s3c2410wdt_release,
  -};

Check the functions for device-specific stuff and keep it for later
refactoring. The rest can go.

Remove the miscdevice
---------------------

Since the file_operations are gone now, you can also remove the 'struct
miscdevice'. The framework will create it on watchdog_dev_register() called by
watchdog_register_device()::

  -static struct miscdevice s3c2410wdt_miscdev = {
  -       .minor          = WATCHDOG_MINOR,
  -       .name           = "watchdog",
  -       .fops           = &s3c2410wdt_fops,
  -};

Remove obsolete includes and defines
------------------------------------

Because of the simplifications, a few defines are probably unused now. Remove
them. Includes can be removed, too. For example::

  - #include <linux/fs.h>
  - #include <linux/miscdevice.h> (if MODULE_ALIAS_MISCDEV is not used)
  - #include <linux/uaccess.h> (if no custom IOCTLs are used)

Add the watchdog operations
---------------------------

All possible callbacks are defined in 'struct watchdog_ops'. You can find it
explained in 'watchdog-kernel-api.txt' in this directory. start() and
owner must be set, the rest are optional. You will easily find corresponding
functions in the old driver. Note that you will now get a pointer to the
watchdog_device as a parameter to these functions, so you probably have to
change the function header. Other changes are most likely not needed, because
here simply happens the direct hardware access. If you have device-specific
code left from the above steps, it should be refactored into these callbacks.

Here is a simple example::

  +static struct watchdog_ops s3c2410wdt_ops = {
  +       .owner = THIS_MODULE,
  +       .start = s3c2410wdt_start,
  +       .stop = s3c2410wdt_stop,
  +       .ping = s3c2410wdt_keepalive,
  +       .set_timeout = s3c2410wdt_set_heartbeat,
  +};

A typical function-header change looks like::

  -static void s3c2410wdt_keepalive(void)
  +static int s3c2410wdt_keepalive(struct watchdog_device *wdd)
   {
  ...
  +
  +       return 0;
   }

  ...

  -       s3c2410wdt_keepalive();
  +       s3c2410wdt_keepalive(&s3c2410_wdd);

Add the watchdog device
-----------------------

Now we need to create a 'struct watchdog_device' and populate it with the
necessary information for the framework. The struct is also explained in detail
in 'watchdog-kernel-api.txt' in this directory. We pass it the mandatory
watchdog_info struct and the newly created watchdog_ops. Often, old drivers
have their own record-keeping for things like bootstatus and timeout using
static variables. Those have to be converted to use the members in
watchdog_device. Note that the timeout values are unsigned int. Some drivers
use signed int, so this has to be converted, too.

Here is a simple example for a watchdog device::

  +static struct watchdog_device s3c2410_wdd = {
  +       .info = &s3c2410_wdt_ident,
  +       .ops = &s3c2410wdt_ops,
  +};

Handle the 'nowayout' feature
-----------------------------

A few drivers use nowayout statically, i.e. there is no module parameter for it
and only CONFIG_WATCHDOG_NOWAYOUT determines if the feature is going to be
used. This needs to be converted by initializing the status variable of the
watchdog_device like this::

        .status = WATCHDOG_NOWAYOUT_INIT_STATUS,

Most drivers, however, also allow runtime configuration of nowayout, usually
by adding a module parameter. The conversion for this would be something like::

	watchdog_set_nowayout(&s3c2410_wdd, nowayout);

The module parameter itself needs to stay, everything else related to nowayout
can go, though. This will likely be some code in open(), close() or write().

Register the watchdog device
----------------------------

Replace misc_register(&miscdev) with watchdog_register_device(&watchdog_dev).
Make sure the return value gets checked and the error message, if present,
still fits. Also convert the unregister case::

  -       ret = misc_register(&s3c2410wdt_miscdev);
  +       ret = watchdog_register_device(&s3c2410_wdd);

  ...

  -       misc_deregister(&s3c2410wdt_miscdev);
  +       watchdog_unregister_device(&s3c2410_wdd);

Update the Kconfig-entry
------------------------

The entry for the driver now needs to select WATCHDOG_CORE:

  +       select WATCHDOG_CORE

Create a patch and send it to upstream
--------------------------------------

Make sure you understood Documentation/process/submitting-patches.rst and send your patch to
linux-watchdog@vger.kernel.org. We are looking forward to it :)


code:
===========================
HPE iLO NMI Watchdog Driver
===========================

for iLO based ProLiant Servers
==============================

Last reviewed: 08/20/2018

 The HPE iLO NMI Watchdog driver is a kernel module that provides basic
 watchdog functionality and handler for the iLO "Generate NMI to System"
 virtual button.

 All references to iLO in this document imply it also works on iLO2 and all
 subsequent generations.

 Watchdog functionality is enabled like any other common watchdog driver. That
 is, an application needs to be started that kicks off the watchdog timer. A
 basic application exists in tools/testing/selftests/watchdog/ named
 watchdog-test.c. Simply compile the C file and kick it off. If the system
 gets into a bad state and hangs, the HPE ProLiant iLO timer register will
 not be updated in a timely fashion and a hardware system reset (also known as
 an Automatic Server Recovery (ASR)) event will occur.

 The hpwdt driver also has the following module parameters:

 ============  ================================================================
 soft_margin   allows the user to set the watchdog timer value.
               Default value is 30 seconds.
 timeout       an alias of soft_margin.
 pretimeout    allows the user to set the watchdog pretimeout value.
               This is the number of seconds before timeout when an
               NMI is delivered to the system. Setting the value to
               zero disables the pretimeout NMI.
               Default value is 9 seconds.
 nowayout      basic watchdog parameter that does not allow the timer to
               be restarted or an impending ASR to be escaped.
               Default value is set when compiling the kernel. If it is set
               to "Y", then there is no way of disabling the watchdog once
               it has been started.
 kdumptimeout  Minimum timeout in seconds to apply upon receipt of an NMI
               before calling panic. (-1) disables the watchdog.  When value
               is > 0, the timer is reprogrammed with the greater of
               value or current timeout value.
 ============  ================================================================

 NOTE:
       More information about watchdog drivers in general, including the ioctl
       interface to /dev/watchdog can be found in
       Documentation/watchdog/watchdog-api.rst and Documentation/IPMI.txt.

 Due to limitations in the iLO hardware, the NMI pretimeout if enabled,
 can only be set to 9 seconds.  Attempts to set pretimeout to other
 non-zero values will be rounded, possibly to zero.  Users should verify
 the pretimeout value after attempting to set pretimeout or timeout.

 Upon receipt of an NMI from the iLO, the hpwdt driver will initiate a
 panic. This is to allow for a crash dump to be collected.  It is incumbent
 upon the user to have properly configured the system for kdump.

 The default Linux kernel behavior upon panic is to print a kernel tombstone
 and loop forever.  This is generally not what a watchdog user wants.

 For those wishing to learn more please see:
	Documentation/admin-guide/kdump/kdump.rst
	Documentation/admin-guide/kernel-parameters.txt (panic=)
	Your Linux Distribution specific documentation.

 If the hpwdt does not receive the NMI associated with an expiring timer,
 the iLO will proceed to reset the system at timeout if the timer hasn't
 been updated.

--

 The HPE iLO NMI Watchdog Driver and documentation were originally developed
 by Tom Mingarelli.


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

======================
Linux Watchdog Support
======================

.. toctree::
    :maxdepth: 1

    hpwdt
    mlx-wdt
    pcwd-watchdog
    watchdog-api
    watchdog-kernel-api
    watchdog-parameters
    watchdog-pm
    wdt
    convert_drivers_to_kernel_api

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`