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

================================
Upgrading ACPI tables via initrd
================================

What is this about
==================

If the ACPI_TABLE_UPGRADE compile option is true, it is possible to
upgrade the ACPI execution environment that is defined by the ACPI tables
via upgrading the ACPI tables provided by the BIOS with an instrumented,
modified, more recent version one, or installing brand new ACPI tables.

When building initrd with kernel in a single image, option
ACPI_TABLE_OVERRIDE_VIA_BUILTIN_INITRD should also be true for this
feature to work.

For a full list of ACPI tables that can be upgraded/installed, take a look
at the char `*table_sigs[MAX_ACPI_SIGNATURE];` definition in
drivers/acpi/tables.c.

All ACPI tables iasl (Intel's ACPI compiler and disassembler) knows should
be overridable, except:

  - ACPI_SIG_RSDP (has a signature of 6 bytes)
  - ACPI_SIG_FACS (does not have an ordinary ACPI table header)

Both could get implemented as well.

What is this for
================

Complain to your platform/BIOS vendor if you find a bug which is so severe
that a workaround is not accepted in the Linux kernel. And this facility
allows you to upgrade the buggy tables before your platform/BIOS vendor
releases an upgraded BIOS binary.

This facility can be used by platform/BIOS vendors to provide a Linux
compatible environment without modifying the underlying platform firmware.

This facility also provides a powerful feature to easily debug and test
ACPI BIOS table compatibility with the Linux kernel by modifying old
platform provided ACPI tables or inserting new ACPI tables.

It can and should be enabled in any kernel because there is no functional
change with not instrumented initrds.

How does it work
================
::

  # Extract the machine's ACPI tables:
  cd /tmp
  acpidump >acpidump
  acpixtract -a acpidump
  # Disassemble, modify and recompile them:
  iasl -d *.dat
  # For example add this statement into a _PRT (PCI Routing Table) function
  # of the DSDT:
  Store("HELLO WORLD", debug)
  # And increase the OEM Revision. For example, before modification:
  DefinitionBlock ("DSDT.aml", "DSDT", 2, "INTEL ", "TEMPLATE", 0x00000000)
  # After modification:
  DefinitionBlock ("DSDT.aml", "DSDT", 2, "INTEL ", "TEMPLATE", 0x00000001)
  iasl -sa dsdt.dsl
  # Add the raw ACPI tables to an uncompressed cpio archive.
  # They must be put into a /kernel/firmware/acpi directory inside the cpio
  # archive. Note that if the table put here matches a platform table
  # (similar Table Signature, and similar OEMID, and similar OEM Table ID)
  # with a more recent OEM Revision, the platform table will be upgraded by
  # this table. If the table put here doesn't match a platform table
  # (dissimilar Table Signature, or dissimilar OEMID, or dissimilar OEM Table
  # ID), this table will be appended.
  mkdir -p kernel/firmware/acpi
  cp dsdt.aml kernel/firmware/acpi
  # A maximum of "NR_ACPI_INITRD_TABLES (64)" tables are currently allowed
  # (see osl.c):
  iasl -sa facp.dsl
  iasl -sa ssdt1.dsl
  cp facp.aml kernel/firmware/acpi
  cp ssdt1.aml kernel/firmware/acpi
  # The uncompressed cpio archive must be the first. Other, typically
  # compressed cpio archives, must be concatenated on top of the uncompressed
  # one. Following command creates the uncompressed cpio archive and
  # concatenates the original initrd on top:
  find kernel | cpio -H newc --create > /boot/instrumented_initrd
  cat /boot/initrd >>/boot/instrumented_initrd
  # reboot with increased acpi debug level, e.g. boot params:
  acpi.debug_level=0x2 acpi.debug_layer=0xFFFFFFFF
  # and check your syslog:
  [    1.268089] ACPI: PCI Interrupt Routing Table [\_SB_.PCI0._PRT]
  [    1.272091] [ACPI Debug]  String [0x0B] "HELLO WORLD"

iasl is able to disassemble and recompile quite a lot different,
also static ACPI tables.

Where to retrieve userspace tools
=================================

iasl and acpixtract are part of Intel's ACPICA project:
https://acpica.org/

and should be packaged by distributions (for example in the acpica package
on SUSE).

acpidump can be found in Len Browns pmtools:
ftp://kernel.org/pub/linux/kernel/people/lenb/acpi/utils/pmtools/acpidump

This tool is also part of the acpica package on SUSE.
Alternatively, used ACPI tables can be retrieved via sysfs in latest kernels:
/sys/firmware/acpi/tables


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

=============
SSDT Overlays
=============

In order to support ACPI open-ended hardware configurations (e.g. development
boards) we need a way to augment the ACPI configuration provided by the firmware
image. A common example is connecting sensors on I2C / SPI buses on development
boards.

Although this can be accomplished by creating a kernel platform driver or
recompiling the firmware image with updated ACPI tables, neither is practical:
the former proliferates board specific kernel code while the latter requires
access to firmware tools which are often not publicly available.

Because ACPI supports external references in AML code a more practical
way to augment firmware ACPI configuration is by dynamically loading
user defined SSDT tables that contain the board specific information.

For example, to enumerate a Bosch BMA222E accelerometer on the I2C bus of the
Minnowboard MAX development board exposed via the LSE connector [1], the
following ASL code can be used::

    DefinitionBlock ("minnowmax.aml", "SSDT", 1, "Vendor", "Accel", 0x00000003)
    {
        External (\_SB.I2C6, DeviceObj)

        Scope (\_SB.I2C6)
        {
            Device (STAC)
            {
                Name (_HID, "BMA222E")
                Name (RBUF, ResourceTemplate ()
                {
                    I2cSerialBus (0x0018, ControllerInitiated, 0x00061A80,
                                AddressingMode7Bit, "\\_SB.I2C6", 0x00,
                                ResourceConsumer, ,)
                    GpioInt (Edge, ActiveHigh, Exclusive, PullDown, 0x0000,
                            "\\_SB.GPO2", 0x00, ResourceConsumer, , )
                    { // Pin list
                        0
                    }
                })

                Method (_CRS, 0, Serialized)
                {
                    Return (RBUF)
                }
            }
        }
    }

which can then be compiled to AML binary format::

    $ iasl minnowmax.asl

    Intel ACPI Component Architecture
    ASL Optimizing Compiler version 20140214-64 [Mar 29 2014]
    Copyright (c) 2000 - 2014 Intel Corporation

    ASL Input:     minnomax.asl - 30 lines, 614 bytes, 7 keywords
    AML Output:    minnowmax.aml - 165 bytes, 6 named objects, 1 executable opcodes

[1] https://www.elinux.org/Minnowboard:MinnowMax#Low_Speed_Expansion_.28Top.29

The resulting AML code can then be loaded by the kernel using one of the methods
below.

Loading ACPI SSDTs from initrd
==============================

This option allows loading of user defined SSDTs from initrd and it is useful
when the system does not support EFI or when there is not enough EFI storage.

It works in a similar way with initrd based ACPI tables override/upgrade: SSDT
AML code must be placed in the first, uncompressed, initrd under the
"kernel/firmware/acpi" path. Multiple files can be used and this will translate
in loading multiple tables. Only SSDT and OEM tables are allowed. See
initrd_table_override.txt for more details.

Here is an example::

    # Add the raw ACPI tables to an uncompressed cpio archive.
    # They must be put into a /kernel/firmware/acpi directory inside the
    # cpio archive.
    # The uncompressed cpio archive must be the first.
    # Other, typically compressed cpio archives, must be
    # concatenated on top of the uncompressed one.
    mkdir -p kernel/firmware/acpi
    cp ssdt.aml kernel/firmware/acpi

    # Create the uncompressed cpio archive and concatenate the original initrd
    # on top:
    find kernel | cpio -H newc --create > /boot/instrumented_initrd
    cat /boot/initrd >>/boot/instrumented_initrd

Loading ACPI SSDTs from EFI variables
=====================================

This is the preferred method, when EFI is supported on the platform, because it
allows a persistent, OS independent way of storing the user defined SSDTs. There
is also work underway to implement EFI support for loading user defined SSDTs
and using this method will make it easier to convert to the EFI loading
mechanism when that will arrive. To enable it, the
CONFIG_EFI_CUSTOM_SSDT_OVERLAYS shoyld be chosen to y.

In order to load SSDTs from an EFI variable the ``"efivar_ssdt=..."`` kernel
command line parameter can be used (the name has a limitation of 16 characters).
The argument for the option is the variable name to use. If there are multiple
variables with the same name but with different vendor GUIDs, all of them will
be loaded.

In order to store the AML code in an EFI variable the efivarfs filesystem can be
used. It is enabled and mounted by default in /sys/firmware/efi/efivars in all
recent distribution.

Creating a new file in /sys/firmware/efi/efivars will automatically create a new
EFI variable. Updating a file in /sys/firmware/efi/efivars will update the EFI
variable. Please note that the file name needs to be specially formatted as
"Name-GUID" and that the first 4 bytes in the file (little-endian format)
represent the attributes of the EFI variable (see EFI_VARIABLE_MASK in
include/linux/efi.h). Writing to the file must also be done with one write
operation.

For example, you can use the following bash script to create/update an EFI
variable with the content from a given file::

    #!/bin/sh -e

    while [ -n "$1" ]; do
            case "$1" in
            "-f") filename="$2"; shift;;
            "-g") guid="$2"; shift;;
            *) name="$1";;
            esac
            shift
    done

    usage()
    {
            echo "Syntax: ${0##*/} -f filename [ -g guid ] name"
            exit 1
    }

    [ -n "$name" -a -f "$filename" ] || usage

    EFIVARFS="/sys/firmware/efi/efivars"

    [ -d "$EFIVARFS" ] || exit 2

    if stat -tf $EFIVARFS | grep -q -v de5e81e4; then
            mount -t efivarfs none $EFIVARFS
    fi

    # try to pick up an existing GUID
    [ -n "$guid" ] || guid=$(find "$EFIVARFS" -name "$name-*" | head -n1 | cut -f2- -d-)

    # use a randomly generated GUID
    [ -n "$guid" ] || guid="$(cat /proc/sys/kernel/random/uuid)"

    # efivarfs expects all of the data in one write
    tmp=$(mktemp)
    /bin/echo -ne "\007\000\000\000" | cat - $filename > $tmp
    dd if=$tmp of="$EFIVARFS/$name-$guid" bs=$(stat -c %s $tmp)
    rm $tmp

Loading ACPI SSDTs from configfs
================================

This option allows loading of user defined SSDTs from user space via the configfs
interface. The CONFIG_ACPI_CONFIGFS option must be select and configfs must be
mounted. In the following examples, we assume that configfs has been mounted in
/sys/kernel/config.

New tables can be loading by creating new directories in /sys/kernel/config/acpi/table
and writing the SSDT AML code in the aml attribute::

    cd /sys/kernel/config/acpi/table
    mkdir my_ssdt
    cat ~/ssdt.aml > my_ssdt/aml

repo_name: angery/linux


code:
Introduction
============

ATA over Ethernet is a network protocol that provides simple access to
block storage on the LAN.

  http://support.coraid.com/documents/AoEr11.txt

The EtherDrive (R) HOWTO for 2.6 and 3.x kernels is found at ...

  http://support.coraid.com/support/linux/EtherDrive-2.6-HOWTO.html

It has many tips and hints!  Please see, especially, recommended
tunings for virtual memory:

  http://support.coraid.com/support/linux/EtherDrive-2.6-HOWTO-5.html#ss5.19

The aoetools are userland programs that are designed to work with this
driver.  The aoetools are on sourceforge.

  http://aoetools.sourceforge.net/

The scripts in this Documentation/admin-guide/aoe directory are intended to
document the use of the driver and are not necessary if you install
the aoetools.

Creating Device Nodes
=====================

  Users of udev should find the block device nodes created
  automatically, but to create all the necessary device nodes, use the
  udev configuration rules provided in udev.txt (in this directory).

  There is a udev-install.sh script that shows how to install these
  rules on your system.

  There is also an autoload script that shows how to edit
  /etc/modprobe.d/aoe.conf to ensure that the aoe module is loaded when
  necessary.  Preloading the aoe module is preferable to autoloading,
  however, because AoE discovery takes a few seconds.  It can be
  confusing when an AoE device is not present the first time the a
  command is run but appears a second later.

Using Device Nodes
==================

  "cat /dev/etherd/err" blocks, waiting for error diagnostic output,
  like any retransmitted packets.

  "echo eth2 eth4 > /dev/etherd/interfaces" tells the aoe driver to
  limit ATA over Ethernet traffic to eth2 and eth4.  AoE traffic from
  untrusted networks should be ignored as a matter of security.  See
  also the aoe_iflist driver option described below.

  "echo > /dev/etherd/discover" tells the driver to find out what AoE
  devices are available.

  In the future these character devices may disappear and be replaced
  by sysfs counterparts.  Using the commands in aoetools insulates
  users from these implementation details.

  The block devices are named like this::

	e{shelf}.{slot}
	e{shelf}.{slot}p{part}

  ... so that "e0.2" is the third blade from the left (slot 2) in the
  first shelf (shelf address zero).  That's the whole disk.  The first
  partition on that disk would be "e0.2p1".

Using sysfs
===========

  Each aoe block device in /sys/block has the extra attributes of
  state, mac, and netif.  The state attribute is "up" when the device
  is ready for I/O and "down" if detected but unusable.  The
  "down,closewait" state shows that the device is still open and
  cannot come up again until it has been closed.

  The mac attribute is the ethernet address of the remote AoE device.
  The netif attribute is the network interface on the localhost
  through which we are communicating with the remote AoE device.

  There is a script in this directory that formats this information in
  a convenient way.  Users with aoetools should use the aoe-stat
  command::

    root@makki root# sh Documentation/admin-guide/aoe/status.sh
       e10.0            eth3              up
       e10.1            eth3              up
       e10.2            eth3              up
       e10.3            eth3              up
       e10.4            eth3              up
       e10.5            eth3              up
       e10.6            eth3              up
       e10.7            eth3              up
       e10.8            eth3              up
       e10.9            eth3              up
        e4.0            eth1              up
        e4.1            eth1              up
        e4.2            eth1              up
        e4.3            eth1              up
        e4.4            eth1              up
        e4.5            eth1              up
        e4.6            eth1              up
        e4.7            eth1              up
        e4.8            eth1              up
        e4.9            eth1              up

  Use /sys/module/aoe/parameters/aoe_iflist (or better, the driver
  option discussed below) instead of /dev/etherd/interfaces to limit
  AoE traffic to the network interfaces in the given
  whitespace-separated list.  Unlike the old character device, the
  sysfs entry can be read from as well as written to.

  It's helpful to trigger discovery after setting the list of allowed
  interfaces.  The aoetools package provides an aoe-discover script
  for this purpose.  You can also directly use the
  /dev/etherd/discover special file described above.

Driver Options
==============

  There is a boot option for the built-in aoe driver and a
  corresponding module parameter, aoe_iflist.  Without this option,
  all network interfaces may be used for ATA over Ethernet.  Here is a
  usage example for the module parameter::

    modprobe aoe_iflist="eth1 eth3"

  The aoe_deadsecs module parameter determines the maximum number of
  seconds that the driver will wait for an AoE device to provide a
  response to an AoE command.  After aoe_deadsecs seconds have
  elapsed, the AoE device will be marked as "down".  A value of zero
  is supported for testing purposes and makes the aoe driver keep
  trying AoE commands forever.

  The aoe_maxout module parameter has a default of 128.  This is the
  maximum number of unresponded packets that will be sent to an AoE
  target at one time.

  The aoe_dyndevs module parameter defaults to 1, meaning that the
  driver will assign a block device minor number to a discovered AoE
  target based on the order of its discovery.  With dynamic minor
  device numbers in use, a greater range of AoE shelf and slot
  addresses can be supported.  Users with udev will never have to
  think about minor numbers.  Using aoe_dyndevs=0 allows device nodes
  to be pre-created using a static minor-number scheme with the
  aoe-mkshelf script in the aoetools.


code:
#!/bin/sh
# set aoe to autoload by installing the
# aliases in /etc/modprobe.d/

f=/etc/modprobe.d/aoe.conf

if test ! -r $f || test ! -w $f; then
	echo "cannot configure $f for module autoloading" 1>&2
	exit 1
fi

grep major-152 $f >/dev/null
if [ $? = 1 ]; then
	echo alias block-major-152 aoe >> $f
	echo alias char-major-152 aoe >> $f
fi


code:
Example of udev rules
---------------------

 .. include:: udev.txt
    :literal:

Example of udev install rules script
------------------------------------

 .. literalinclude:: udev-install.sh
    :language: shell

Example script to get status
----------------------------

 .. literalinclude:: status.sh
    :language: shell

Example of AoE autoload script
------------------------------

 .. literalinclude:: autoload.sh
    :language: shell


code:
=======================
ATA over Ethernet (AoE)
=======================

.. toctree::
    :maxdepth: 1

    aoe
    todo
    examples

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


code:
#! /bin/sh
# collate and present sysfs information about AoE storage
#
# A more complete version of this script is aoe-stat, in the
# aoetools.

set -e
format="%8s\t%8s\t%8s\n"
me=`basename $0`
sysd=${sysfs_dir:-/sys}

# printf "$format" device mac netif state

# Suse 9.1 Pro doesn't put /sys in /etc/mtab
#test -z "`mount | grep sysfs`" && {
test ! -d "$sysd/block" && {
	echo "$me Error: sysfs is not mounted" 1>&2
	exit 1
}

for d in `ls -d $sysd/block/etherd* 2>/dev/null | grep -v p` end; do
	# maybe ls comes up empty, so we use "end"
	test $d = end && continue

	dev=`echo "$d" | sed 's/.*!//'`
	printf "$format" \
		"$dev" \
		"`cat \"$d/netif\"`" \
		"`cat \"$d/state\"`"
done | sort


code:
TODO
====

There is a potential for deadlock when allocating a struct sk_buff for
data that needs to be written out to aoe storage.  If the data is
being written from a dirty page in order to free that page, and if
there are no other pages available, then deadlock may occur when a
free page is needed for the sk_buff allocation.  This situation has
not been observed, but it would be nice to eliminate any potential for
deadlock under memory pressure.

Because ATA over Ethernet is not fragmented by the kernel's IP code,
the destructor member of the struct sk_buff is available to the aoe
driver.  By using a mempool for allocating all but the first few
sk_buffs, and by registering a destructor, we should be able to
efficiently allocate sk_buffs without introducing any potential for
deadlock.


code:
# install the aoe-specific udev rules from udev.txt into
# the system's udev configuration
#

me="`basename $0`"

# find udev.conf, often /etc/udev/udev.conf
# (or environment can specify where to find udev.conf)
#
if test -z "$conf"; then
	if test -r /etc/udev/udev.conf; then
		conf=/etc/udev/udev.conf
	else
		conf="`find /etc -type f -name udev.conf 2> /dev/null`"
		if test -z "$conf" || test ! -r "$conf"; then
			echo "$me Error: no udev.conf found" 1>&2
			exit 1
		fi
	fi
fi

# find the directory where udev rules are stored, often
# /etc/udev/rules.d
#
rules_d="`sed -n '/^udev_rules=/{ s!udev_rules=!!; s!\"!!g; p; }' $conf`"
if test -z "$rules_d" ; then
	rules_d=/etc/udev/rules.d
fi
if test ! -d "$rules_d"; then
	echo "$me Error: cannot find udev rules directory" 1>&2
	exit 1
fi
sh -xc "cp `dirname $0`/udev.txt $rules_d/60-aoe.rules"


code:
# These rules tell udev what device nodes to create for aoe support.
# They may be installed along the following lines.  Check the section
# 8 udev manpage to see whether your udev supports SUBSYSTEM, and
# whether it uses one or two equal signs for SUBSYSTEM and KERNEL.
#
#   ecashin@makki ~$ su
#   Password:
#   bash# find /etc -type f -name udev.conf
#   /etc/udev/udev.conf
#   bash# grep udev_rules= /etc/udev/udev.conf
#   udev_rules="/etc/udev/rules.d/"
#   bash# ls /etc/udev/rules.d/
#   10-wacom.rules  50-udev.rules
#   bash# cp /path/to/linux/Documentation/admin-guide/aoe/udev.txt \
#           /etc/udev/rules.d/60-aoe.rules
#

# aoe char devices
SUBSYSTEM=="aoe", KERNEL=="discover",	NAME="etherd/%k", GROUP="disk", MODE="0220"
SUBSYSTEM=="aoe", KERNEL=="err",	NAME="etherd/%k", GROUP="disk", MODE="0440"
SUBSYSTEM=="aoe", KERNEL=="interfaces",	NAME="etherd/%k", GROUP="disk", MODE="0220"
SUBSYSTEM=="aoe", KERNEL=="revalidate",	NAME="etherd/%k", GROUP="disk", MODE="0220"
SUBSYSTEM=="aoe", KERNEL=="flush",	NAME="etherd/%k", GROUP="disk", MODE="0220"

# aoe block devices
KERNEL=="etherd*",       GROUP="disk"


code:
===================================
cfag12864b LCD Driver Documentation
===================================

:License:		GPLv2
:Author & Maintainer:	Miguel Ojeda <ojeda@kernel.org>
:Date:			2006-10-27

.. INDEX

	1. DRIVER INFORMATION
	2. DEVICE INFORMATION
	3. WIRING
	4. USERSPACE PROGRAMMING

1. Driver Information
---------------------

This driver supports a cfag12864b LCD.

2. Device Information
---------------------

:Manufacturer:	Crystalfontz
:Device Name:	Crystalfontz 12864b LCD Series
:Device Code:	cfag12864b
:Webpage:	http://www.crystalfontz.com
:Device Webpage: http://www.crystalfontz.com/products/12864b/
:Type:		LCD (Liquid Crystal Display)
:Width:		128
:Height:	64
:Colors:	2 (B/N)
:Controller:	ks0108
:Controllers:	2
:Pages:		8 each controller
:Addresses:	64 each page
:Data size:	1 byte each address
:Memory size:	2 * 8 * 64 * 1 = 1024 bytes = 1 Kbyte

3. Wiring
---------

The cfag12864b LCD Series don't have official wiring.

The common wiring is done to the parallel port as shown::

  Parallel Port                          cfag12864b

    Name Pin#                            Pin# Name

  Strobe ( 1)------------------------------(17) Enable
  Data 0 ( 2)------------------------------( 4) Data 0
  Data 1 ( 3)------------------------------( 5) Data 1
  Data 2 ( 4)------------------------------( 6) Data 2
  Data 3 ( 5)------------------------------( 7) Data 3
  Data 4 ( 6)------------------------------( 8) Data 4
  Data 5 ( 7)------------------------------( 9) Data 5
  Data 6 ( 8)------------------------------(10) Data 6
  Data 7 ( 9)------------------------------(11) Data 7
         (10)                      [+5v]---( 1) Vdd
         (11)                      [GND]---( 2) Ground
         (12)                      [+5v]---(14) Reset
         (13)                      [GND]---(15) Read / Write
    Line (14)------------------------------(13) Controller Select 1
         (15)
    Init (16)------------------------------(12) Controller Select 2
  Select (17)------------------------------(16) Data / Instruction
  Ground (18)---[GND]              [+5v]---(19) LED +
  Ground (19)---[GND]
  Ground (20)---[GND]              E    A             Values:
  Ground (21)---[GND]       [GND]---[P1]---(18) Vee    - R = Resistor = 22 ohm
  Ground (22)---[GND]                |                 - P1 = Preset = 10 Kohm
  Ground (23)---[GND]       ----   S ------( 3) V0     - P2 = Preset = 1 Kohm
  Ground (24)---[GND]       |  |
  Ground (25)---[GND] [GND]---[P2]---[R]---(20) LED -

4. Userspace Programming
------------------------

The cfag12864bfb describes a framebuffer device (/dev/fbX).

It has a size of 1024 bytes = 1 Kbyte.
Each bit represents one pixel. If the bit is high, the pixel will
turn on. If the pixel is low, the pixel will turn off.

You can use the framebuffer as a file: fopen, fwrite, fclose...
Although the LCD won't get updated until the next refresh time arrives.

Also, you can mmap the framebuffer: open & mmap, munmap & close...
which is the best option for most uses.

Check samples/auxdisplay/cfag12864b-example.c
for a real working userspace complete program with usage examples.


code:
=========================
Auxiliary Display Support
=========================

.. toctree::
    :maxdepth: 1

    ks0108.rst
    cfag12864b.rst

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


code:
==========================================
ks0108 LCD Controller Driver Documentation
==========================================

:License:		GPLv2
:Author & Maintainer:	Miguel Ojeda <ojeda@kernel.org>
:Date:			2006-10-27

.. INDEX

	1. DRIVER INFORMATION
	2. DEVICE INFORMATION
	3. WIRING

1. Driver Information
---------------------

This driver supports the ks0108 LCD controller.

2. Device Information
---------------------

:Manufacturer:	Samsung
:Device Name:	KS0108 LCD Controller
:Device Code:	ks0108
:Webpage:	-
:Device Webpage: -
:Type:		LCD Controller (Liquid Crystal Display Controller)
:Width:		64
:Height:	64
:Colors:	2 (B/N)
:Pages:		8
:Addresses:	64 each page
:Data size:	1 byte each address
:Memory size:	8 * 64 * 1 = 512 bytes

3. Wiring
---------

The driver supports data parallel port wiring.

If you aren't building LCD related hardware, you should check
your LCD specific wiring information in the same folder.

For example, check Documentation/admin-guide/auxdisplay/cfag12864b.rst


code:
============================
A block layer cache (bcache)
============================

Say you've got a big slow raid 6, and an ssd or three. Wouldn't it be
nice if you could use them as cache... Hence bcache.

The bcache wiki can be found at:
  https://bcache.evilpiepirate.org

This is the git repository of bcache-tools:
  https://git.kernel.org/pub/scm/linux/kernel/git/colyli/bcache-tools.git/

The latest bcache kernel code can be found from mainline Linux kernel:
  https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/

It's designed around the performance characteristics of SSDs - it only allocates
in erase block sized buckets, and it uses a hybrid btree/log to track cached
extents (which can be anywhere from a single sector to the bucket size). It's
designed to avoid random writes at all costs; it fills up an erase block
sequentially, then issues a discard before reusing it.

Both writethrough and writeback caching are supported. Writeback defaults to
off, but can be switched on and off arbitrarily at runtime. Bcache goes to
great lengths to protect your data - it reliably handles unclean shutdown. (It
doesn't even have a notion of a clean shutdown; bcache simply doesn't return
writes as completed until they're on stable storage).

Writeback caching can use most of the cache for buffering writes - writing
dirty data to the backing device is always done sequentially, scanning from the
start to the end of the index.

Since random IO is what SSDs excel at, there generally won't be much benefit
to caching large sequential IO. Bcache detects sequential IO and skips it;
it also keeps a rolling average of the IO sizes per task, and as long as the
average is above the cutoff it will skip all IO from that task - instead of
caching the first 512k after every seek. Backups and large file copies should
thus entirely bypass the cache.

In the event of a data IO error on the flash it will try to recover by reading
from disk or invalidating cache entries.  For unrecoverable errors (meta data
or dirty data), caching is automatically disabled; if dirty data was present
in the cache it first disables writeback caching and waits for all dirty data
to be flushed.

Getting started:
You'll need bcache util from the bcache-tools repository. Both the cache device
and backing device must be formatted before use::

  bcache make -B /dev/sdb
  bcache make -C /dev/sdc

`bcache make` has the ability to format multiple devices at the same time - if
you format your backing devices and cache device at the same time, you won't
have to manually attach::

  bcache make -B /dev/sda /dev/sdb -C /dev/sdc

If your bcache-tools is not updated to latest version and does not have the
unified `bcache` utility, you may use the legacy `make-bcache` utility to format
bcache device with same -B and -C parameters.

bcache-tools now ships udev rules, and bcache devices are known to the kernel
immediately.  Without udev, you can manually register devices like this::

  echo /dev/sdb > /sys/fs/bcache/register
  echo /dev/sdc > /sys/fs/bcache/register

Registering the backing device makes the bcache device show up in /dev; you can
now format it and use it as normal. But the first time using a new bcache
device, it'll be running in passthrough mode until you attach it to a cache.
If you are thinking about using bcache later, it is recommended to setup all your
slow devices as bcache backing devices without a cache, and you can choose to add
a caching device later.
See 'ATTACHING' section below.

The devices show up as::

  /dev/bcache<N>

As well as (with udev)::

  /dev/bcache/by-uuid/<uuid>
  /dev/bcache/by-label/<label>

To get started::

  mkfs.ext4 /dev/bcache0
  mount /dev/bcache0 /mnt

You can control bcache devices through sysfs at /sys/block/bcache<N>/bcache .
You can also control them through /sys/fs//bcache/<cset-uuid>/ .

Cache devices are managed as sets; multiple caches per set isn't supported yet
but will allow for mirroring of metadata and dirty data in the future. Your new
cache set shows up as /sys/fs/bcache/<UUID>

Attaching
---------

After your cache device and backing device are registered, the backing device
must be attached to your cache set to enable caching. Attaching a backing
device to a cache set is done thusly, with the UUID of the cache set in
/sys/fs/bcache::

  echo <CSET-UUID> > /sys/block/bcache0/bcache/attach

This only has to be done once. The next time you reboot, just reregister all
your bcache devices. If a backing device has data in a cache somewhere, the
/dev/bcache<N> device won't be created until the cache shows up - particularly
important if you have writeback caching turned on.

If you're booting up and your cache device is gone and never coming back, you
can force run the backing device::

  echo 1 > /sys/block/sdb/bcache/running

(You need to use /sys/block/sdb (or whatever your backing device is called), not
/sys/block/bcache0, because bcache0 doesn't exist yet. If you're using a
partition, the bcache directory would be at /sys/block/sdb/sdb2/bcache)

The backing device will still use that cache set if it shows up in the future,
but all the cached data will be invalidated. If there was dirty data in the
cache, don't expect the filesystem to be recoverable - you will have massive
filesystem corruption, though ext4's fsck does work miracles.

Error Handling
--------------

Bcache tries to transparently handle IO errors to/from the cache device without
affecting normal operation; if it sees too many errors (the threshold is
configurable, and defaults to 0) it shuts down the cache device and switches all
the backing devices to passthrough mode.

 - For reads from the cache, if they error we just retry the read from the
   backing device.

 - For writethrough writes, if the write to the cache errors we just switch to
   invalidating the data at that lba in the cache (i.e. the same thing we do for
   a write that bypasses the cache)

 - For writeback writes, we currently pass that error back up to the
   filesystem/userspace. This could be improved - we could retry it as a write
   that skips the cache so we don't have to error the write.

 - When we detach, we first try to flush any dirty data (if we were running in
   writeback mode). It currently doesn't do anything intelligent if it fails to
   read some of the dirty data, though.

Howto/cookbook
--------------

A) Starting a bcache with a missing caching device

If registering the backing device doesn't help, it's already there, you just need
to force it to run without the cache::

	host:~# echo /dev/sdb1 > /sys/fs/bcache/register
	[  119.844831] bcache: register_bcache() error opening /dev/sdb1: device already registered

Next, you try to register your caching device if it's present. However
if it's absent, or registration fails for some reason, you can still
start your bcache without its cache, like so::

	host:/sys/block/sdb/sdb1/bcache# echo 1 > running

Note that this may cause data loss if you were running in writeback mode.

B) Bcache does not find its cache::

	host:/sys/block/md5/bcache# echo 0226553a-37cf-41d5-b3ce-8b1e944543a8 > attach
	[ 1933.455082] bcache: bch_cached_dev_attach() Couldn't find uuid for md5 in set
	[ 1933.478179] bcache: __cached_dev_store() Can't attach 0226553a-37cf-41d5-b3ce-8b1e944543a8
	[ 1933.478179] : cache set not found

In this case, the caching device was simply not registered at boot
or disappeared and came back, and needs to be (re-)registered::

	host:/sys/block/md5/bcache# echo /dev/sdh2 > /sys/fs/bcache/register

C) Corrupt bcache crashes the kernel at device registration time:

This should never happen.  If it does happen, then you have found a bug!
Please report it to the bcache development list: linux-bcache@vger.kernel.org

Be sure to provide as much information that you can including kernel dmesg
output if available so that we may assist.

D) Recovering data without bcache:

If bcache is not available in the kernel, a filesystem on the backing
device is still available at an 8KiB offset. So either via a loopdev
of the backing device created with --offset 8K, or any value defined by
--data-offset when you originally formatted bcache with `bcache make`.

For example::

	losetup -o 8192 /dev/loop0 /dev/your_bcache_backing_dev

This should present your unmodified backing device data in /dev/loop0

If your cache is in writethrough mode, then you can safely discard the
cache device without loosing data.

E) Wiping a cache device

::

	host:~# wipefs -a /dev/sdh2
	16 bytes were erased at offset 0x1018 (bcache)
	they were: c6 85 73 f6 4e 1a 45 ca 82 65 f5 7f 48 ba 6d 81

After you boot back with bcache enabled, you recreate the cache and attach it::

	host:~# bcache make -C /dev/sdh2
	UUID:                   7be7e175-8f4c-4f99-94b2-9c904d227045
	Set UUID:               5bc072a8-ab17-446d-9744-e247949913c1
	version:                0
	nbuckets:               106874
	block_size:             1
	bucket_size:            1024
	nr_in_set:              1
	nr_this_dev:            0
	first_bucket:           1
	[  650.511912] bcache: run_cache_set() invalidating existing data
	[  650.549228] bcache: register_cache() registered cache device sdh2

start backing device with missing cache::

	host:/sys/block/md5/bcache# echo 1 > running

attach new cache::

	host:/sys/block/md5/bcache# echo 5bc072a8-ab17-446d-9744-e247949913c1 > attach
	[  865.276616] bcache: bch_cached_dev_attach() Caching md5 as bcache0 on set 5bc072a8-ab17-446d-9744-e247949913c1

F) Remove or replace a caching device::

	host:/sys/block/sda/sda7/bcache# echo 1 > detach
	[  695.872542] bcache: cached_dev_detach_finish() Caching disabled for sda7

	host:~# wipefs -a /dev/nvme0n1p4
	wipefs: error: /dev/nvme0n1p4: probing initialization failed: Device or resource busy
	Ooops, it's disabled, but not unregistered, so it's still protected

We need to go and unregister it::

	host:/sys/fs/bcache/b7ba27a1-2398-4649-8ae3-0959f57ba128# ls -l cache0
	lrwxrwxrwx 1 root root 0 Feb 25 18:33 cache0 -> ../../../devices/pci0000:00/0000:00:1d.0/0000:70:00.0/nvme/nvme0/nvme0n1/nvme0n1p4/bcache/
	host:/sys/fs/bcache/b7ba27a1-2398-4649-8ae3-0959f57ba128# echo 1 > stop
	kernel: [  917.041908] bcache: cache_set_free() Cache set b7ba27a1-2398-4649-8ae3-0959f57ba128 unregistered

Now we can wipe it::

	host:~# wipefs -a /dev/nvme0n1p4
	/dev/nvme0n1p4: 16 bytes were erased at offset 0x00001018 (bcache): c6 85 73 f6 4e 1a 45 ca 82 65 f5 7f 48 ba 6d 81

G) dm-crypt and bcache

First setup bcache unencrypted and then install dmcrypt on top of
/dev/bcache<N> This will work faster than if you dmcrypt both the backing
and caching devices and then install bcache on top. [benchmarks?]

H) Stop/free a registered bcache to wipe and/or recreate it

Suppose that you need to free up all bcache references so that you can
fdisk run and re-register a changed partition table, which won't work
if there are any active backing or caching devices left on it:

1) Is it present in /dev/bcache* ? (there are times where it won't be)

   If so, it's easy::

	host:/sys/block/bcache0/bcache# echo 1 > stop

2) But if your backing device is gone, this won't work::

	host:/sys/block/bcache0# cd bcache
	bash: cd: bcache: No such file or directory

   In this case, you may have to unregister the dmcrypt block device that
   references this bcache to free it up::

	host:~# dmsetup remove oldds1
	bcache: bcache_device_free() bcache0 stopped
	bcache: cache_set_free() Cache set 5bc072a8-ab17-446d-9744-e247949913c1 unregistered

   This causes the backing bcache to be removed from /sys/fs/bcache and
   then it can be reused.  This would be true of any block device stacking
   where bcache is a lower device.

3) In other cases, you can also look in /sys/fs/bcache/::

	host:/sys/fs/bcache# ls -l */{cache?,bdev?}
	lrwxrwxrwx 1 root root 0 Mar  5 09:39 0226553a-37cf-41d5-b3ce-8b1e944543a8/bdev1 -> ../../../devices/virtual/block/dm-1/bcache/
	lrwxrwxrwx 1 root root 0 Mar  5 09:39 0226553a-37cf-41d5-b3ce-8b1e944543a8/cache0 -> ../../../devices/virtual/block/dm-4/bcache/
	lrwxrwxrwx 1 root root 0 Mar  5 09:39 5bc072a8-ab17-446d-9744-e247949913c1/cache0 -> ../../../devices/pci0000:00/0000:00:01.0/0000:01:00.0/ata10/host9/target9:0:0/9:0:0:0/block/sdl/sdl2/bcache/

   The device names will show which UUID is relevant, cd in that directory
   and stop the cache::

	host:/sys/fs/bcache/5bc072a8-ab17-446d-9744-e247949913c1# echo 1 > stop

   This will free up bcache references and let you reuse the partition for
   other purposes.

Troubleshooting performance
---------------------------

Bcache has a bunch of config options and tunables. The defaults are intended to
be reasonable for typical desktop and server workloads, but they're not what you
want for getting the best possible numbers when benchmarking.

 - Backing device alignment

   The default metadata size in bcache is 8k.  If your backing device is
   RAID based, then be sure to align this by a multiple of your stride
   width using `bcache make --data-offset`. If you intend to expand your
   disk array in the future, then multiply a series of primes by your
   raid stripe size to get the disk multiples that you would like.

   For example:  If you have a 64k stripe size, then the following offset
   would provide alignment for many common RAID5 data spindle counts::

	64k * 2*2*2*3*3*5*7 bytes = 161280k

   That space is wasted, but for only 157.5MB you can grow your RAID 5
   volume to the following data-spindle counts without re-aligning::

	3,4,5,6,7,8,9,10,12,14,15,18,20,21 ...

 - Bad write performance

   If write performance is not what you expected, you probably wanted to be
   running in writeback mode, which isn't the default (not due to a lack of
   maturity, but simply because in writeback mode you'll lose data if something
   happens to your SSD)::

	# echo writeback > /sys/block/bcache0/bcache/cache_mode

 - Bad performance, or traffic not going to the SSD that you'd expect

   By default, bcache doesn't cache everything. It tries to skip sequential IO -
   because you really want to be caching the random IO, and if you copy a 10
   gigabyte file you probably don't want that pushing 10 gigabytes of randomly
   accessed data out of your cache.

   But if you want to benchmark reads from cache, and you start out with fio
   writing an 8 gigabyte test file - so you want to disable that::

	# echo 0 > /sys/block/bcache0/bcache/sequential_cutoff

   To set it back to the default (4 mb), do::

	# echo 4M > /sys/block/bcache0/bcache/sequential_cutoff

 - Traffic's still going to the spindle/still getting cache misses

   In the real world, SSDs don't always keep up with disks - particularly with
   slower SSDs, many disks being cached by one SSD, or mostly sequential IO. So
   you want to avoid being bottlenecked by the SSD and having it slow everything
   down.

   To avoid that bcache tracks latency to the cache device, and gradually
   throttles traffic if the latency exceeds a threshold (it does this by
   cranking down the sequential bypass).

   You can disable this if you need to by setting the thresholds to 0::

	# echo 0 > /sys/fs/bcache/<cache set>/congested_read_threshold_us
	# echo 0 > /sys/fs/bcache/<cache set>/congested_write_threshold_us

   The default is 2000 us (2 milliseconds) for reads, and 20000 for writes.

 - Still getting cache misses, of the same data

   One last issue that sometimes trips people up is actually an old bug, due to
   the way cache coherency is handled for cache misses. If a btree node is full,
   a cache miss won't be able to insert a key for the new data and the data
   won't be written to the cache.

   In practice this isn't an issue because as soon as a write comes along it'll
   cause the btree node to be split, and you need almost no write traffic for
   this to not show up enough to be noticeable (especially since bcache's btree
   nodes are huge and index large regions of the device). But when you're
   benchmarking, if you're trying to warm the cache by reading a bunch of data
   and there's no other traffic - that can be a problem.

   Solution: warm the cache by doing writes, or use the testing branch (there's
   a fix for the issue there).

Sysfs - backing device
----------------------

Available at /sys/block/<bdev>/bcache, /sys/block/bcache*/bcache and
(if attached) /sys/fs/bcache/<cset-uuid>/bdev*

attach
  Echo the UUID of a cache set to this file to enable caching.

cache_mode
  Can be one of either writethrough, writeback, writearound or none.

clear_stats
  Writing to this file resets the running total stats (not the day/hour/5 minute
  decaying versions).

detach
  Write to this file to detach from a cache set. If there is dirty data in the
  cache, it will be flushed first.

dirty_data
  Amount of dirty data for this backing device in the cache. Continuously
  updated unlike the cache set's version, but may be slightly off.

label
  Name of underlying device.

readahead
  Size of readahead that should be performed.  Defaults to 0.  If set to e.g.
  1M, it will round cache miss reads up to that size, but without overlapping
  existing cache entries.

running
  1 if bcache is running (i.e. whether the /dev/bcache device exists, whether
  it's in passthrough mode or caching).

sequential_cutoff
  A sequential IO will bypass the cache once it passes this threshold; the
  most recent 128 IOs are tracked so sequential IO can be detected even when
  it isn't all done at once.

sequential_merge
  If non zero, bcache keeps a list of the last 128 requests submitted to compare
  against all new requests to determine which new requests are sequential
  continuations of previous requests for the purpose of determining sequential
  cutoff. This is necessary if the sequential cutoff value is greater than the
  maximum acceptable sequential size for any single request.

state
  The backing device can be in one of four different states:

  no cache: Has never been attached to a cache set.

  clean: Part of a cache set, and there is no cached dirty data.

  dirty: Part of a cache set, and there is cached dirty data.

  inconsistent: The backing device was forcibly run by the user when there was
  dirty data cached but the cache set was unavailable; whatever data was on the
  backing device has likely been corrupted.

stop
  Write to this file to shut down the bcache device and close the backing
  device.

writeback_delay
  When dirty data is written to the cache and it previously did not contain
  any, waits some number of seconds before initiating writeback. Defaults to
  30.

writeback_percent
  If nonzero, bcache tries to keep around this percentage of the cache dirty by
  throttling background writeback and using a PD controller to smoothly adjust
  the rate.

writeback_rate
  Rate in sectors per second - if writeback_percent is nonzero, background
  writeback is throttled to this rate. Continuously adjusted by bcache but may
  also be set by the user.

writeback_running
  If off, writeback of dirty data will not take place at all. Dirty data will
  still be added to the cache until it is mostly full; only meant for
  benchmarking. Defaults to on.

Sysfs - backing device stats
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There are directories with these numbers for a running total, as well as
versions that decay over the past day, hour and 5 minutes; they're also
aggregated in the cache set directory as well.

bypassed
  Amount of IO (both reads and writes) that has bypassed the cache

cache_hits, cache_misses, cache_hit_ratio
  Hits and misses are counted per individual IO as bcache sees them; a
  partial hit is counted as a miss.

cache_bypass_hits, cache_bypass_misses
  Hits and misses for IO that is intended to skip the cache are still counted,
  but broken out here.

cache_miss_collisions
  Counts instances where data was going to be inserted into the cache from a
  cache miss, but raced with a write and data was already present (usually 0
  since the synchronization for cache misses was rewritten)

cache_readaheads
  Count of times readahead occurred.

Sysfs - cache set
~~~~~~~~~~~~~~~~~

Available at /sys/fs/bcache/<cset-uuid>

average_key_size
  Average data per key in the btree.

bdev<0..n>
  Symlink to each of the attached backing devices.

block_size
  Block size of the cache devices.

btree_cache_size
  Amount of memory currently used by the btree cache

bucket_size
  Size of buckets

cache<0..n>
  Symlink to each of the cache devices comprising this cache set.

cache_available_percent
  Percentage of cache device which doesn't contain dirty data, and could
  potentially be used for writeback.  This doesn't mean this space isn't used
  for clean cached data; the unused statistic (in priority_stats) is typically
  much lower.

clear_stats
  Clears the statistics associated with this cache

dirty_data
  Amount of dirty data is in the cache (updated when garbage collection runs).

flash_vol_create
  Echoing a size to this file (in human readable units, k/M/G) creates a thinly
  provisioned volume backed by the cache set.

io_error_halflife, io_error_limit
  These determines how many errors we accept before disabling the cache.
  Each error is decayed by the half life (in # ios).  If the decaying count
  reaches io_error_limit dirty data is written out and the cache is disabled.

journal_delay_ms
  Journal writes will delay for up to this many milliseconds, unless a cache
  flush happens sooner. Defaults to 100.

root_usage_percent
  Percentage of the root btree node in use.  If this gets too high the node
  will split, increasing the tree depth.

stop
  Write to this file to shut down the cache set - waits until all attached
  backing devices have been shut down.

tree_depth
  Depth of the btree (A single node btree has depth 0).

unregister
  Detaches all backing devices and closes the cache devices; if dirty data is
  present it will disable writeback caching and wait for it to be flushed.

Sysfs - cache set internal
~~~~~~~~~~~~~~~~~~~~~~~~~~

This directory also exposes timings for a number of internal operations, with
separate files for average duration, average frequency, last occurrence and max
duration: garbage collection, btree read, btree node sorts and btree splits.

active_journal_entries
  Number of journal entries that are newer than the index.

btree_nodes
  Total nodes in the btree.

btree_used_percent
  Average fraction of btree in use.

bset_tree_stats
  Statistics about the auxiliary search trees

btree_cache_max_chain
  Longest chain in the btree node cache's hash table

cache_read_races
  Counts instances where while data was being read from the cache, the bucket
  was reused and invalidated - i.e. where the pointer was stale after the read
  completed. When this occurs the data is reread from the backing device.

trigger_gc
  Writing to this file forces garbage collection to run.

Sysfs - Cache device
~~~~~~~~~~~~~~~~~~~~

Available at /sys/block/<cdev>/bcache

block_size
  Minimum granularity of writes - should match hardware sector size.

btree_written
  Sum of all btree writes, in (kilo/mega/giga) bytes

bucket_size
  Size of buckets

cache_replacement_policy
  One of either lru, fifo or random.

discard
  Boolean; if on a discard/TRIM will be issued to each bucket before it is
  reused. Defaults to off, since SATA TRIM is an unqueued command (and thus
  slow).

freelist_percent
  Size of the freelist as a percentage of nbuckets. Can be written to to
  increase the number of buckets kept on the freelist, which lets you
  artificially reduce the size of the cache at runtime. Mostly for testing
  purposes (i.e. testing how different size caches affect your hit rate), but
  since buckets are discarded when they move on to the freelist will also make
  the SSD's garbage collection easier by effectively giving it more reserved
  space.

io_errors
  Number of errors that have occurred, decayed by io_error_halflife.

metadata_written
  Sum of all non data writes (btree writes and all other metadata).

nbuckets
  Total buckets in this cache

priority_stats
  Statistics about how recently data in the cache has been accessed.
  This can reveal your working set size.  Unused is the percentage of
  the cache that doesn't contain any data.  Metadata is bcache's
  metadata overhead.  Average is the average priority of cache buckets.
  Next is a list of quantiles with the priority threshold of each.

written
  Sum of all data that has been written to the cache; comparison with
  btree_written gives the amount of write inflation in bcache.


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

The Android binderfs Filesystem
===============================

Android binderfs is a filesystem for the Android binder IPC mechanism.  It
allows to dynamically add and remove binder devices at runtime.  Binder devices
located in a new binderfs instance are independent of binder devices located in
other binderfs instances.  Mounting a new binderfs instance makes it possible
to get a set of private binder devices.

Mounting binderfs
-----------------

Android binderfs can be mounted with::

  mkdir /dev/binderfs
  mount -t binder binder /dev/binderfs

at which point a new instance of binderfs will show up at ``/dev/binderfs``.
In a fresh instance of binderfs no binder devices will be present.  There will
only be a ``binder-control`` device which serves as the request handler for
binderfs. Mounting another binderfs instance at a different location will
create a new and separate instance from all other binderfs mounts.  This is
identical to the behavior of e.g. ``devpts`` and ``tmpfs``. The Android
binderfs filesystem can be mounted in user namespaces.

Options
-------
max
  binderfs instances can be mounted with a limit on the number of binder
  devices that can be allocated. The ``max=<count>`` mount option serves as
  a per-instance limit. If ``max=<count>`` is set then only ``<count>`` number
  of binder devices can be allocated in this binderfs instance.

stats
  Using ``stats=global`` enables global binder statistics.
  ``stats=global`` is only available for a binderfs instance mounted in the
  initial user namespace. An attempt to use the option to mount a binderfs
  instance in another user namespace will return a permission error.

Allocating binder Devices
-------------------------

.. _ioctl: http://man7.org/linux/man-pages/man2/ioctl.2.html

To allocate a new binder device in a binderfs instance a request needs to be
sent through the ``binder-control`` device node.  A request is sent in the form
of an `ioctl() <ioctl_>`_.

What a program needs to do is to open the ``binder-control`` device node and
send a ``BINDER_CTL_ADD`` request to the kernel.  Users of binderfs need to
tell the kernel which name the new binder device should get.  By default a name
can only contain up to ``BINDERFS_MAX_NAME`` chars including the terminating
zero byte.

Once the request is made via an `ioctl() <ioctl_>`_ passing a ``struct
binder_device`` with the name to the kernel it will allocate a new binder
device and return the major and minor number of the new device in the struct
(This is necessary because binderfs allocates a major device number
dynamically.).  After the `ioctl() <ioctl_>`_ returns there will be a new
binder device located under /dev/binderfs with the chosen name.

Deleting binder Devices
-----------------------

.. _unlink: http://man7.org/linux/man-pages/man2/unlink.2.html
.. _rm: http://man7.org/linux/man-pages/man1/rm.1.html

Binderfs binder devices can be deleted via `unlink() <unlink_>`_.  This means
that the `rm() <rm_>`_ tool can be used to delete them. Note that the
``binder-control`` device cannot be deleted since this would make the binderfs
instance unusable.  The ``binder-control`` device will be deleted when the
binderfs instance is unmounted and all references to it have been dropped.

Binder features
---------------

Assuming an instance of binderfs has been mounted at ``/dev/binderfs``, the
features supported by the binder driver can be located under
``/dev/binderfs/features/``. The presence of individual files can be tested
to determine whether a particular feature is supported by the driver.

Example::

        cat /dev/binderfs/features/oneway_spam_detection
        1


code:
Kernel Support for miscellaneous Binary Formats (binfmt_misc)
=============================================================

This Kernel feature allows you to invoke almost (for restrictions see below)
every program by simply typing its name in the shell.
This includes for example compiled Java(TM), Python or Emacs programs.

To achieve this you must tell binfmt_misc which interpreter has to be invoked
with which binary. Binfmt_misc recognises the binary-type by matching some bytes
at the beginning of the file with a magic byte sequence (masking out specified
bits) you have supplied. Binfmt_misc can also recognise a filename extension
aka ``.com`` or ``.exe``.

First you must mount binfmt_misc::

	mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc

To actually register a new binary type, you have to set up a string looking like
``:name:type:offset:magic:mask:interpreter:flags`` (where you can choose the
``:`` upon your needs) and echo it to ``/proc/sys/fs/binfmt_misc/register``.

Here is what the fields mean:

- ``name``
   is an identifier string. A new /proc file will be created with this
   name below ``/proc/sys/fs/binfmt_misc``; cannot contain slashes ``/`` for
   obvious reasons.
- ``type``
   is the type of recognition. Give ``M`` for magic and ``E`` for extension.
- ``offset``
   is the offset of the magic/mask in the file, counted in bytes. This
   defaults to 0 if you omit it (i.e. you write ``:name:type::magic...``).
   Ignored when using filename extension matching.
- ``magic``
   is the byte sequence binfmt_misc is matching for. The magic string
   may contain hex-encoded characters like ``\x0a`` or ``\xA4``. Note that you
   must escape any NUL bytes; parsing halts at the first one. In a shell
   environment you might have to write ``\\x0a`` to prevent the shell from
   eating your ``\``.
   If you chose filename extension matching, this is the extension to be
   recognised (without the ``.``, the ``\x0a`` specials are not allowed).
   Extension    matching is case sensitive, and slashes ``/`` are not allowed!
- ``mask``
   is an (optional, defaults to all 0xff) mask. You can mask out some
   bits from matching by supplying a string like magic and as long as magic.
   The mask is anded with the byte sequence of the file. Note that you must
   escape any NUL bytes; parsing halts at the first one. Ignored when using
   filename extension matching.
- ``interpreter``
   is the program that should be invoked with the binary as first
   argument (specify the full path)
- ``flags``
   is an optional field that controls several aspects of the invocation
   of the interpreter. It is a string of capital letters, each controls a
   certain aspect. The following flags are supported:

      ``P`` - preserve-argv[0]
            Legacy behavior of binfmt_misc is to overwrite
            the original argv[0] with the full path to the binary. When this
            flag is included, binfmt_misc will add an argument to the argument
            vector for this purpose, thus preserving the original ``argv[0]``.
            e.g. If your interp is set to ``/bin/foo`` and you run ``blah``
            (which is in ``/usr/local/bin``), then the kernel will execute
            ``/bin/foo`` with ``argv[]`` set to ``["/bin/foo", "/usr/local/bin/blah", "blah"]``.  The interp has to be aware of this so it can
            execute ``/usr/local/bin/blah``
            with ``argv[]`` set to ``["blah"]``.
      ``O`` - open-binary
	    Legacy behavior of binfmt_misc is to pass the full path
            of the binary to the interpreter as an argument. When this flag is
            included, binfmt_misc will open the file for reading and pass its
            descriptor as an argument, instead of the full path, thus allowing
            the interpreter to execute non-readable binaries. This feature
            should be used with care - the interpreter has to be trusted not to
            emit the contents of the non-readable binary.
      ``C`` - credentials
            Currently, the behavior of binfmt_misc is to calculate
            the credentials and security token of the new process according to
            the interpreter. When this flag is included, these attributes are
            calculated according to the binary. It also implies the ``O`` flag.
            This feature should be used with care as the interpreter
            will run with root permissions when a setuid binary owned by root
            is run with binfmt_misc.
      ``F`` - fix binary
            The usual behaviour of binfmt_misc is to spawn the
	    binary lazily when the misc format file is invoked.  However,
	    this doesn't work very well in the face of mount namespaces and
	    changeroots, so the ``F`` mode opens the binary as soon as the
	    emulation is installed and uses the opened image to spawn the
	    emulator, meaning it is always available once installed,
	    regardless of how the environment changes.

There are some restrictions:

 - the whole register string may not exceed 1920 characters
 - the magic must reside in the first 128 bytes of the file, i.e.
   offset+size(magic) has to be less than 128
 - the interpreter string may not exceed 127 characters

To use binfmt_misc you have to mount it first. You can mount it with
``mount -t binfmt_misc none /proc/sys/fs/binfmt_misc`` command, or you can add
a line ``none  /proc/sys/fs/binfmt_misc binfmt_misc defaults 0 0`` to your
``/etc/fstab`` so it auto mounts on boot.

You may want to add the binary formats in one of your ``/etc/rc`` scripts during
boot-up. Read the manual of your init program to figure out how to do this
right.

Think about the order of adding entries! Later added entries are matched first!

A few examples (assumed you are in ``/proc/sys/fs/binfmt_misc``):

- enable support for em86 (like binfmt_em86, for Alpha AXP only)::

    echo ':i386:M::\x7fELF\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x03:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff:/bin/em86:' > register
    echo ':i486:M::\x7fELF\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x06:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff:/bin/em86:' > register

- enable support for packed DOS applications (pre-configured dosemu hdimages)::

    echo ':DEXE:M::\x0eDEX::/usr/bin/dosexec:' > register

- enable support for Windows executables using wine::

    echo ':DOSWin:M::MZ::/usr/local/bin/wine:' > register

For java support see Documentation/admin-guide/java.rst

You can enable/disable binfmt_misc or one binary type by echoing 0 (to disable)
or 1 (to enable) to ``/proc/sys/fs/binfmt_misc/status`` or
``/proc/.../the_name``.
Catting the file tells you the current status of ``binfmt_misc/the_entry``.

You can remove one entry or all entries by echoing -1 to ``/proc/.../the_name``
or ``/proc/sys/fs/binfmt_misc/status``.

Hints
-----

If you want to pass special arguments to your interpreter, you can
write a wrapper script for it.
See :doc:`Documentation/admin-guide/java.rst <./java>` for an example.

Your interpreter should NOT look in the PATH for the filename; the kernel
passes it the full filename (or the file descriptor) to use.  Using ``$PATH`` can
cause unexpected behaviour and can be a security hazard.

Richard Günther <rguenth@tat.physik.uni-tuebingen.de>


code:
digraph conn_states {
	StandAllone  -> WFConnection   [ label = "ioctl_set_net()" ]
	WFConnection -> Unconnected    [ label = "unable to bind()" ]
	WFConnection -> WFReportParams [ label = "in connect() after accept" ]
	WFReportParams -> StandAllone  [ label = "checks in receive_param()" ]
	WFReportParams -> Connected    [ label = "in receive_param()" ]
	WFReportParams -> WFBitMapS    [ label = "sync_handshake()" ]
	WFReportParams -> WFBitMapT    [ label = "sync_handshake()" ]
	WFBitMapS -> SyncSource        [ label = "receive_bitmap()" ]
	WFBitMapT -> SyncTarget        [ label = "receive_bitmap()" ]
	SyncSource -> Connected
	SyncTarget -> Connected
	SyncSource -> PausedSyncS
	SyncTarget -> PausedSyncT
	PausedSyncS -> SyncSource
	PausedSyncT -> SyncTarget
	Connected   -> WFConnection    [ label = "* on network error" ]
}


code:
================================
kernel data structure for DRBD-9
================================

This describes the in kernel data structure for DRBD-9. Starting with
Linux v3.14 we are reorganizing DRBD to use this data structure.

Basic Data Structure
====================

A node has a number of DRBD resources.  Each such resource has a number of
devices (aka volumes) and connections to other nodes ("peer nodes"). Each DRBD
device is represented by a block device locally.

The DRBD objects are interconnected to form a matrix as depicted below; a
drbd_peer_device object sits at each intersection between a drbd_device and a
drbd_connection::

  /--------------+---------------+.....+---------------\
  |   resource   |    device     |     |    device     |
  +--------------+---------------+.....+---------------+
  |  connection  |  peer_device  |     |  peer_device  |
  +--------------+---------------+.....+---------------+
  :              :               :     :               :
  :              :               :     :               :
  +--------------+---------------+.....+---------------+
  |  connection  |  peer_device  |     |  peer_device  |
  \--------------+---------------+.....+---------------/

In this table, horizontally, devices can be accessed from resources by their
volume number.  Likewise, peer_devices can be accessed from connections by
their volume number.  Objects in the vertical direction are connected by double
linked lists.  There are back pointers from peer_devices to their connections a
devices, and from connections and devices to their resource.

All resources are in the drbd_resources double-linked list.  In addition, all
devices can be accessed by their minor device number via the drbd_devices idr.

The drbd_resource, drbd_connection, and drbd_device objects are reference
counted.  The peer_device objects only serve to establish the links between
devices and connections; their lifetime is determined by the lifetime of the
device and connection which they reference.


code:
digraph disk_states {
	Diskless -> Inconsistent       [ label = "ioctl_set_disk()" ]
	Diskless -> Consistent         [ label = "ioctl_set_disk()" ]
	Diskless -> Outdated           [ label = "ioctl_set_disk()" ]
	Consistent -> Outdated         [ label = "receive_param()" ]
	Consistent -> UpToDate         [ label = "receive_param()" ]
	Consistent -> Inconsistent     [ label = "start resync" ]
	Outdated   -> Inconsistent     [ label = "start resync" ]
	UpToDate   -> Inconsistent     [ label = "ioctl_replicate" ]
	Inconsistent -> UpToDate       [ label = "resync completed" ]
	Consistent -> Failed           [ label = "io completion error" ]
	Outdated   -> Failed           [ label = "io completion error" ]
	UpToDate   -> Failed           [ label = "io completion error" ]
	Inconsistent -> Failed         [ label = "io completion error" ]
	Failed -> Diskless             [ label = "sending notify to peer" ]
}


code:
// vim: set sw=2 sts=2 :
digraph {
  rankdir=BT
  bgcolor=white

  node [shape=plaintext]
  node [fontcolor=black]

  StandAlone     [ style=filled,fillcolor=gray,label=StandAlone ]

  node [fontcolor=lightgray]

  Unconnected    [ label=Unconnected ]

  CommTrouble [ shape=record,
    label="{communication loss|{Timeout|BrokenPipe|NetworkFailure}}" ]

  node [fontcolor=gray]

  subgraph cluster_try_connect {
    label="try to connect, handshake"
    rank=max
    WFConnection   [ label=WFConnection ]
    WFReportParams [ label=WFReportParams ]
  }

  TearDown       [ label=TearDown ]

  Connected      [ label=Connected,style=filled,fillcolor=green,fontcolor=black ]

  node [fontcolor=lightblue]

  StartingSyncS  [ label=StartingSyncS ]
  StartingSyncT  [ label=StartingSyncT ]

  subgraph cluster_bitmap_exchange {
    node [fontcolor=red]
    fontcolor=red
    label="new application (WRITE?) requests blocked\lwhile bitmap is exchanged"

    WFBitMapT      [ label=WFBitMapT ]
    WFSyncUUID     [ label=WFSyncUUID ]
    WFBitMapS      [ label=WFBitMapS ]
  }

  node [fontcolor=blue]

  cluster_resync [ shape=record,label="{<any>resynchronisation process running\l'concurrent' application requests allowed|{{<T>PausedSyncT\nSyncTarget}|{<S>PausedSyncS\nSyncSource}}}" ]

  node [shape=box,fontcolor=black]

  // drbdadm [label="drbdadm connect"]
  // handshake [label="drbd_connect()\ndrbd_do_handshake\ndrbd_sync_handshake() etc."]
  // comm_error [label="communication trouble"]

  //
  // edges
  // --------------------------------------

  StandAlone -> Unconnected [ label="drbdadm connect" ]
  Unconnected -> StandAlone  [ label="drbdadm disconnect\lor serious communication trouble" ]
  Unconnected -> WFConnection [ label="receiver thread is started" ]
  WFConnection -> WFReportParams [ headlabel="accept()\land/or                        \lconnect()\l" ]

  WFReportParams -> StandAlone [ label="during handshake\lpeers do not agree\labout something essential" ]
  WFReportParams -> Connected [ label="data identical\lno sync needed",color=green,fontcolor=green ]

    WFReportParams -> WFBitMapS
    WFReportParams -> WFBitMapT
    WFBitMapT -> WFSyncUUID [minlen=0.1,constraint=false]

      WFBitMapS -> cluster_resync:S
      WFSyncUUID -> cluster_resync:T

  edge [color=green]
  cluster_resync:any -> Connected [ label="resnyc done",fontcolor=green ]

  edge [color=red]
  WFReportParams -> CommTrouble
  Connected -> CommTrouble
  cluster_resync:any -> CommTrouble
  edge [color=black]
  CommTrouble -> Unconnected [label="receiver thread is stopped" ]

}


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

.. The here included files are intended to help understand the implementation

Data flows that Relate some functions, and write packets
========================================================

.. kernel-figure:: DRBD-8.3-data-packets.svg
    :alt:   DRBD-8.3-data-packets.svg
    :align: center

.. kernel-figure:: DRBD-data-packets.svg
    :alt:   DRBD-data-packets.svg
    :align: center

Sub graphs of DRBD's state transitions
======================================

.. kernel-figure:: conn-states-8.dot
    :alt:   conn-states-8.dot
    :align: center

.. kernel-figure:: disk-states-8.dot
    :alt:   disk-states-8.dot
    :align: center

.. kernel-figure:: peer-states-8.dot
    :alt:   peer-states-8.dot
    :align: center


code:
==========================================
Distributed Replicated Block Device - DRBD
==========================================

Description
===========

  DRBD is a shared-nothing, synchronously replicated block device. It
  is designed to serve as a building block for high availability
  clusters and in this context, is a "drop-in" replacement for shared
  storage. Simplistically, you could see it as a network RAID 1.

  Please visit https://www.drbd.org to find out more.

.. toctree::
   :maxdepth: 1

   data-structure-v9
   figures


code:
digraph peer_states {
	Secondary -> Primary           [ label = "recv state packet" ]
	Primary   -> Secondary 	       [ label = "recv state packet" ]
	Primary   -> Unknown 	       [ label = "connection lost" ]
	Secondary  -> Unknown  	       [ label = "connection lost" ]
	Unknown   -> Primary           [ label = "connected" ]
	Unknown   -> Secondary         [ label = "connected" ]
}


code:
=============
Floppy Driver
=============

FAQ list:
=========

A FAQ list may be found in the fdutils package (see below), and also
at <https://fdutils.linux.lu/faq.html>.

LILO configuration options (Thinkpad users, read this)
======================================================

The floppy driver is configured using the 'floppy=' option in
lilo. This option can be typed at the boot prompt, or entered in the
lilo configuration file.

Example: If your kernel is called linux-2.6.9, type the following line
at the lilo boot prompt (if you have a thinkpad)::

 linux-2.6.9 floppy=thinkpad

You may also enter the following line in /etc/lilo.conf, in the description
of linux-2.6.9::

 append = "floppy=thinkpad"

Several floppy related options may be given, example::

 linux-2.6.9 floppy=daring floppy=two_fdc
 append = "floppy=daring floppy=two_fdc"

If you give options both in the lilo config file and on the boot
prompt, the option strings of both places are concatenated, the boot
prompt options coming last. That's why there are also options to
restore the default behavior.

Module configuration options
============================

If you use the floppy driver as a module, use the following syntax::

	modprobe floppy floppy="<options>"

Example::

	modprobe floppy floppy="omnibook messages"

If you need certain options enabled every time you load the floppy driver,
you can put::

	options floppy floppy="omnibook messages"

in a configuration file in /etc/modprobe.d/.

The floppy driver related options are:

 floppy=asus_pci
	Sets the bit mask to allow only units 0 and 1. (default)

 floppy=daring
	Tells the floppy driver that you have a well behaved floppy controller.
	This allows more efficient and smoother operation, but may fail on
	certain controllers. This may speed up certain operations.

 floppy=0,daring
	Tells the floppy driver that your floppy controller should be used
	with caution.

 floppy=one_fdc
	Tells the floppy driver that you have only one floppy controller.
	(default)

 floppy=two_fdc / floppy=<address>,two_fdc
	Tells the floppy driver that you have two floppy controllers.
	The second floppy controller is assumed to be at <address>.
	This option is not needed if the second controller is at address
	0x370, and if you use the 'cmos' option.

 floppy=thinkpad
	Tells the floppy driver that you have a Thinkpad. Thinkpads use an
	inverted convention for the disk change line.

 floppy=0,thinkpad
	Tells the floppy driver that you don't have a Thinkpad.

 floppy=omnibook / floppy=nodma
	Tells the floppy driver not to use Dma for data transfers.
	This is needed on HP Omnibooks, which don't have a workable
	DMA channel for the floppy driver. This option is also useful
	if you frequently get "Unable to allocate DMA memory" messages.
	Indeed, dma memory needs to be continuous in physical memory,
	and is thus harder to find, whereas non-dma buffers may be
	allocated in virtual memory. However, I advise against this if
	you have an FDC without a FIFO (8272A or 82072). 82072A and
	later are OK. You also need at least a 486 to use nodma.
	If you use nodma mode, I suggest you also set the FIFO
	threshold to 10 or lower, in order to limit the number of data
	transfer interrupts.

	If you have a FIFO-able FDC, the floppy driver automatically
	falls back on non DMA mode if no DMA-able memory can be found.
	If you want to avoid this, explicitly ask for 'yesdma'.

 floppy=yesdma
	Tells the floppy driver that a workable DMA channel is available.
	(default)

 floppy=nofifo
	Disables the FIFO entirely. This is needed if you get "Bus
	master arbitration error" messages from your Ethernet card (or
	from other devices) while accessing the floppy.

 floppy=usefifo
	Enables the FIFO. (default)

 floppy=<threshold>,fifo_depth
	Sets the FIFO threshold. This is mostly relevant in DMA
	mode. If this is higher, the floppy driver tolerates more
	interrupt latency, but it triggers more interrupts (i.e. it
	imposes more load on the rest of the system). If this is
	lower, the interrupt latency should be lower too (faster
	processor). The benefit of a lower threshold is less
	interrupts.

	To tune the fifo threshold, switch on over/underrun messages
	using 'floppycontrol --messages'. Then access a floppy
	disk. If you get a huge amount of "Over/Underrun - retrying"
	messages, then the fifo threshold is too low. Try with a
	higher value, until you only get an occasional Over/Underrun.
	It is a good idea to compile the floppy driver as a module
	when doing this tuning. Indeed, it allows to try different
	fifo values without rebooting the machine for each test. Note
	that you need to do 'floppycontrol --messages' every time you
	re-insert the module.

	Usually, tuning the fifo threshold should not be needed, as
	the default (0xa) is reasonable.

 floppy=<drive>,<type>,cmos
	Sets the CMOS type of <drive> to <type>. This is mandatory if
	you have more than two floppy drives (only two can be
	described in the physical CMOS), or if your BIOS uses
	non-standard CMOS types. The CMOS types are:

	       ==  ==================================
		0  Use the value of the physical CMOS
		1  5 1/4 DD
		2  5 1/4 HD
		3  3 1/2 DD
		4  3 1/2 HD
		5  3 1/2 ED
		6  3 1/2 ED
	       16  unknown or not installed
	       ==  ==================================

	(Note: there are two valid types for ED drives. This is because 5 was
	initially chosen to represent floppy *tapes*, and 6 for ED drives.
	AMI ignored this, and used 5 for ED drives. That's why the floppy
	driver handles both.)

 floppy=unexpected_interrupts
	Print a warning message when an unexpected interrupt is received.
	(default)

 floppy=no_unexpected_interrupts / floppy=L40SX
	Don't print a message when an unexpected interrupt is received. This
	is needed on IBM L40SX laptops in certain video modes. (There seems
	to be an interaction between video and floppy. The unexpected
	interrupts affect only performance, and can be safely ignored.)

 floppy=broken_dcl
	Don't use the disk change line, but assume that the disk was
	changed whenever the device node is reopened. Needed on some
	boxes where the disk change line is broken or unsupported.
	This should be regarded as a stopgap measure, indeed it makes
	floppy operation less efficient due to unneeded cache
	flushings, and slightly more unreliable. Please verify your
	cable, connection and jumper settings if you have any DCL
	problems. However, some older drives, and also some laptops
	are known not to have a DCL.

 floppy=debug
	Print debugging messages.

 floppy=messages
	Print informational messages for some operations (disk change
	notifications, warnings about over and underruns, and about
	autodetection).

 floppy=silent_dcl_clear
	Uses a less noisy way to clear the disk change line (which
	doesn't involve seeks). Implied by 'daring' option.

 floppy=<nr>,irq
	Sets the floppy IRQ to <nr> instead of 6.

 floppy=<nr>,dma
	Sets the floppy DMA channel to <nr> instead of 2.

 floppy=slow
	Use PS/2 stepping rate::

	   PS/2 floppies have much slower step rates than regular floppies.
	   It's been recommended that take about 1/4 of the default speed
	   in some more extreme cases.

Supporting utilities and additional documentation:
==================================================

Additional parameters of the floppy driver can be configured at
runtime. Utilities which do this can be found in the fdutils package.
This package also contains a new version of mtools which allows to
access high capacity disks (up to 1992K on a high density 3 1/2 disk!).
It also contains additional documentation about the floppy driver.

The latest version can be found at fdutils homepage:

 https://fdutils.linux.lu

The fdutils releases can be found at:

 https://fdutils.linux.lu/download.html

 http://www.tux.org/pub/knaff/fdutils/

 ftp://metalab.unc.edu/pub/Linux/utils/disk-management/

Reporting problems about the floppy driver
==========================================

If you have a question or a bug report about the floppy driver, mail
me at Alain.Knaff@poboxes.com . If you post to Usenet, preferably use
comp.os.linux.hardware. As the volume in these groups is rather high,
be sure to include the word "floppy" (or "FLOPPY") in the subject
line.  If the reported problem happens when mounting floppy disks, be
sure to mention also the type of the filesystem in the subject line.

Be sure to read the FAQ before mailing/posting any bug reports!

Alain

Changelog
=========

10-30-2004 :
		Cleanup, updating, add reference to module configuration.
		James Nelson <james4765@gmail.com>

6-3-2000 :
		Original Document


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

=============
Block Devices
=============

.. toctree::
   :maxdepth: 1

   floppy
   nbd
   paride
   ramdisk
   zram

   drbd/index


code:
==================================
Network Block Device (TCP version)
==================================

1) Overview
-----------

What is it: With this compiled in the kernel (or as a module), Linux
can use a remote server as one of its block devices. So every time
the client computer wants to read, e.g., /dev/nb0, it sends a
request over TCP to the server, which will reply with the data read.
This can be used for stations with low disk space (or even diskless)
to borrow disk space from another computer.
Unlike NFS, it is possible to put any filesystem on it, etc.

For more information, or to download the nbd-client and nbd-server
tools, go to http://nbd.sf.net/.

The nbd kernel module need only be installed on the client
system, as the nbd-server is completely in userspace. In fact,
the nbd-server has been successfully ported to other operating
systems, including Windows.

A) NBD parameters
-----------------

max_part
	Number of partitions per device (default: 0).

nbds_max
	Number of block devices that should be initialized (default: 16).


code:
===================================
Linux and parallel port IDE devices
===================================

PARIDE v1.03   (c) 1997-8  Grant Guenther <grant@torque.net>

1. Introduction
===============

Owing to the simplicity and near universality of the parallel port interface
to personal computers, many external devices such as portable hard-disk,
CD-ROM, LS-120 and tape drives use the parallel port to connect to their
host computer.  While some devices (notably scanners) use ad-hoc methods
to pass commands and data through the parallel port interface, most
external devices are actually identical to an internal model, but with
a parallel-port adapter chip added in.  Some of the original parallel port
adapters were little more than mechanisms for multiplexing a SCSI bus.
(The Iomega PPA-3 adapter used in the ZIP drives is an example of this
approach).  Most current designs, however, take a different approach.
The adapter chip reproduces a small ISA or IDE bus in the external device
and the communication protocol provides operations for reading and writing
device registers, as well as data block transfer functions.  Sometimes,
the device being addressed via the parallel cable is a standard SCSI
controller like an NCR 5380.  The "ditto" family of external tape
drives use the ISA replicator to interface a floppy disk controller,
which is then connected to a floppy-tape mechanism.  The vast majority
of external parallel port devices, however, are now based on standard
IDE type devices, which require no intermediate controller.  If one
were to open up a parallel port CD-ROM drive, for instance, one would
find a standard ATAPI CD-ROM drive, a power supply, and a single adapter
that interconnected a standard PC parallel port cable and a standard
IDE cable.  It is usually possible to exchange the CD-ROM device with
any other device using the IDE interface.

The document describes the support in Linux for parallel port IDE
devices.  It does not cover parallel port SCSI devices, "ditto" tape
drives or scanners.  Many different devices are supported by the
parallel port IDE subsystem, including:

	- MicroSolutions backpack CD-ROM
	- MicroSolutions backpack PD/CD
	- MicroSolutions backpack hard-drives
	- MicroSolutions backpack 8000t tape drive
	- SyQuest EZ-135, EZ-230 & SparQ drives
	- Avatar Shark
	- Imation Superdisk LS-120
	- Maxell Superdisk LS-120
	- FreeCom Power CD
	- Hewlett-Packard 5GB and 8GB tape drives
	- Hewlett-Packard 7100 and 7200 CD-RW drives

as well as most of the clone and no-name products on the market.

To support such a wide range of devices, PARIDE, the parallel port IDE
subsystem, is actually structured in three parts.   There is a base
paride module which provides a registry and some common methods for
accessing the parallel ports.  The second component is a set of
high-level drivers for each of the different types of supported devices:

	===	=============
	pd	IDE disk
	pcd	ATAPI CD-ROM
	pf	ATAPI disk
	pt	ATAPI tape
	pg	ATAPI generic
	===	=============

(Currently, the pg driver is only used with CD-R drives).

The high-level drivers function according to the relevant standards.
The third component of PARIDE is a set of low-level protocol drivers
for each of the parallel port IDE adapter chips.  Thanks to the interest
and encouragement of Linux users from many parts of the world,
support is available for almost all known adapter protocols:

	====    ====================================== ====
        aten    ATEN EH-100                            (HK)
        bpck    Microsolutions backpack                (US)
        comm    DataStor (old-type) "commuter" adapter (TW)
        dstr    DataStor EP-2000                       (TW)
        epat    Shuttle EPAT                           (UK)
        epia    Shuttle EPIA                           (UK)
	fit2    FIT TD-2000			       (US)
	fit3    FIT TD-3000			       (US)
	friq    Freecom IQ cable                       (DE)
        frpw    Freecom Power                          (DE)
        kbic    KingByte KBIC-951A and KBIC-971A       (TW)
	ktti    KT Technology PHd adapter              (SG)
        on20    OnSpec 90c20                           (US)
        on26    OnSpec 90c26                           (US)
	====    ====================================== ====

2. Using the PARIDE subsystem
=============================

While configuring the Linux kernel, you may choose either to build
the PARIDE drivers into your kernel, or to build them as modules.

In either case, you will need to select "Parallel port IDE device support"
as well as at least one of the high-level drivers and at least one
of the parallel port communication protocols.  If you do not know
what kind of parallel port adapter is used in your drive, you could
begin by checking the file names and any text files on your DOS
installation floppy.  Alternatively, you can look at the markings on
the adapter chip itself.  That's usually sufficient to identify the
correct device.

You can actually select all the protocol modules, and allow the PARIDE
subsystem to try them all for you.

For the "brand-name" products listed above, here are the protocol
and high-level drivers that you would use:

	================	============	======	========
	Manufacturer		Model		Driver	Protocol
	================	============	======	========
	MicroSolutions		CD-ROM		pcd	bpck
	MicroSolutions		PD drive	pf	bpck
	MicroSolutions		hard-drive	pd	bpck
	MicroSolutions          8000t tape      pt      bpck
	SyQuest			EZ, SparQ	pd	epat
	Imation			Superdisk	pf	epat
	Maxell                  Superdisk       pf      friq
	Avatar			Shark		pd	epat
	FreeCom			CD-ROM		pcd	frpw
	Hewlett-Packard		5GB Tape	pt	epat
	Hewlett-Packard		7200e (CD)	pcd	epat
	Hewlett-Packard		7200e (CD-R)	pg	epat
	================	============	======	========

2.1  Configuring built-in drivers
---------------------------------

We recommend that you get to know how the drivers work and how to
configure them as loadable modules, before attempting to compile a
kernel with the drivers built-in.

If you built all of your PARIDE support directly into your kernel,
and you have just a single parallel port IDE device, your kernel should
locate it automatically for you.  If you have more than one device,
you may need to give some command line options to your bootloader
(eg: LILO), how to do that is beyond the scope of this document.

The high-level drivers accept a number of command line parameters, all
of which are documented in the source files in linux/drivers/block/paride.
By default, each driver will automatically try all parallel ports it
can find, and all protocol types that have been installed, until it finds
a parallel port IDE adapter.  Once it finds one, the probe stops.  So,
if you have more than one device, you will need to tell the drivers
how to identify them.  This requires specifying the port address, the
protocol identification number and, for some devices, the drive's
chain ID.  While your system is booting, a number of messages are
displayed on the console.  Like all such messages, they can be
reviewed with the 'dmesg' command.  Among those messages will be
some lines like::

	paride: bpck registered as protocol 0
	paride: epat registered as protocol 1

The numbers will always be the same until you build a new kernel with
different protocol selections.  You should note these numbers as you
will need them to identify the devices.

If you happen to be using a MicroSolutions backpack device, you will
also need to know the unit ID number for each drive.  This is usually
the last two digits of the drive's serial number (but read MicroSolutions'
documentation about this).

As an example, let's assume that you have a MicroSolutions PD/CD drive
with unit ID number 36 connected to the parallel port at 0x378, a SyQuest
EZ-135 connected to the chained port on the PD/CD drive and also an
Imation Superdisk connected to port 0x278.  You could give the following
options on your boot command::

	pd.drive0=0x378,1 pf.drive0=0x278,1 pf.drive1=0x378,0,36

In the last option, pf.drive1 configures device /dev/pf1, the 0x378
is the parallel port base address, the 0 is the protocol registration
number and 36 is the chain ID.

Please note:  while PARIDE will work both with and without the
PARPORT parallel port sharing system that is included by the
"Parallel port support" option, PARPORT must be included and enabled
if you want to use chains of devices on the same parallel port.

2.2  Loading and configuring PARIDE as modules
----------------------------------------------

It is much faster and simpler to get to understand the PARIDE drivers
if you use them as loadable kernel modules.

Note 1:
	using these drivers with the "kerneld" automatic module loading
	system is not recommended for beginners, and is not documented here.

Note 2:
	if you build PARPORT support as a loadable module, PARIDE must
	also be built as loadable modules, and PARPORT must be loaded before
	the PARIDE modules.

To use PARIDE, you must begin by::

	insmod paride

this loads a base module which provides a registry for the protocols,
among other tasks.

Then, load as many of the protocol modules as you think you might need.
As you load each module, it will register the protocols that it supports,
and print a log message to your kernel log file and your console. For
example::

	# insmod epat
	paride: epat registered as protocol 0
	# insmod kbic
	paride: k951 registered as protocol 1
        paride: k971 registered as protocol 2

Finally, you can load high-level drivers for each kind of device that
you have connected.  By default, each driver will autoprobe for a single
device, but you can support up to four similar devices by giving their
individual coordinates when you load the driver.

For example, if you had two no-name CD-ROM drives both using the
KingByte KBIC-951A adapter, one on port 0x378 and the other on 0x3bc
you could give the following command::

	# insmod pcd drive0=0x378,1 drive1=0x3bc,1

For most adapters, giving a port address and protocol number is sufficient,
but check the source files in linux/drivers/block/paride for more
information.  (Hopefully someone will write some man pages one day !).

As another example, here's what happens when PARPORT is installed, and
a SyQuest EZ-135 is attached to port 0x378::

	# insmod paride
	paride: version 1.0 installed
	# insmod epat
	paride: epat registered as protocol 0
	# insmod pd
	pd: pd version 1.0, major 45, cluster 64, nice 0
	pda: Sharing parport1 at 0x378
	pda: epat 1.0, Shuttle EPAT chip c3 at 0x378, mode 5 (EPP-32), delay 1
	pda: SyQuest EZ135A, 262144 blocks [128M], (512/16/32), removable media
	 pda: pda1

Note that the last line is the output from the generic partition table
scanner - in this case it reports that it has found a disk with one partition.

2.3  Using a PARIDE device
--------------------------

Once the drivers have been loaded, you can access PARIDE devices in the
same way as their traditional counterparts.  You will probably need to
create the device "special files".  Here is a simple script that you can
cut to a file and execute::

  #!/bin/bash
  #
  # mkd -- a script to create the device special files for the PARIDE subsystem
  #
  function mkdev {
    mknod $1 $2 $3 $4 ; chmod 0660 $1 ; chown root:disk $1
  }
  #
  function pd {
    D=$( printf \\$( printf "x%03x" $[ $1 + 97 ] ) )
    mkdev pd$D b 45 $[ $1 * 16 ]
    for P in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
    do mkdev pd$D$P b 45 $[ $1 * 16 + $P ]
    done
  }
  #
  cd /dev
  #
  for u in 0 1 2 3 ; do pd $u ; done
  for u in 0 1 2 3 ; do mkdev pcd$u b 46 $u ; done
  for u in 0 1 2 3 ; do mkdev pf$u  b 47 $u ; done
  for u in 0 1 2 3 ; do mkdev pt$u  c 96 $u ; done
  for u in 0 1 2 3 ; do mkdev npt$u c 96 $[ $u + 128 ] ; done
  for u in 0 1 2 3 ; do mkdev pg$u  c 97 $u ; done
  #
  # end of mkd

With the device files and drivers in place, you can access PARIDE devices
like any other Linux device.   For example, to mount a CD-ROM in pcd0, use::

	mount /dev/pcd0 /cdrom

If you have a fresh Avatar Shark cartridge, and the drive is pda, you
might do something like::

	fdisk /dev/pda		-- make a new partition table with
				   partition 1 of type 83

	mke2fs /dev/pda1	-- to build the file system

	mkdir /shark		-- make a place to mount the disk

	mount /dev/pda1 /shark

Devices like the Imation superdisk work in the same way, except that
they do not have a partition table.  For example to make a 120MB
floppy that you could share with a DOS system::

	mkdosfs /dev/pf0
	mount /dev/pf0 /mnt

2.4  The pf driver
------------------

The pf driver is intended for use with parallel port ATAPI disk
devices.  The most common devices in this category are PD drives
and LS-120 drives.  Traditionally, media for these devices are not
partitioned.  Consequently, the pf driver does not support partitioned
media.  This may be changed in a future version of the driver.

2.5  Using the pt driver
------------------------

The pt driver for parallel port ATAPI tape drives is a minimal driver.
It does not yet support many of the standard tape ioctl operations.
For best performance, a block size of 32KB should be used.  You will
probably want to set the parallel port delay to 0, if you can.

2.6  Using the pg driver
------------------------

The pg driver can be used in conjunction with the cdrecord program
to create CD-ROMs.  Please get cdrecord version 1.6.1 or later
from ftp://ftp.fokus.gmd.de/pub/unix/cdrecord/ .  To record CD-R media
your parallel port should ideally be set to EPP mode, and the "port delay"
should be set to 0.  With those settings it is possible to record at 2x
speed without any buffer underruns.  If you cannot get the driver to work
in EPP mode, try to use "bidirectional" or "PS/2" mode and 1x speeds only.

3. Troubleshooting
==================

3.1  Use EPP mode if you can
----------------------------

The most common problems that people report with the PARIDE drivers
concern the parallel port CMOS settings.  At this time, none of the
PARIDE protocol modules support ECP mode, or any ECP combination modes.
If you are able to do so, please set your parallel port into EPP mode
using your CMOS setup procedure.

3.2  Check the port delay
-------------------------

Some parallel ports cannot reliably transfer data at full speed.  To
offset the errors, the PARIDE protocol modules introduce a "port
delay" between each access to the i/o ports.  Each protocol sets
a default value for this delay.  In most cases, the user can override
the default and set it to 0 - resulting in somewhat higher transfer
rates.  In some rare cases (especially with older 486 systems) the
default delays are not long enough.  if you experience corrupt data
transfers, or unexpected failures, you may wish to increase the
port delay.   The delay can be programmed using the "driveN" parameters
to each of the high-level drivers.  Please see the notes above, or
read the comments at the beginning of the driver source files in
linux/drivers/block/paride.

3.3  Some drives need a printer reset
-------------------------------------

There appear to be a number of "noname" external drives on the market
that do not always power up correctly.  We have noticed this with some
drives based on OnSpec and older Freecom adapters.  In these rare cases,
the adapter can often be reinitialised by issuing a "printer reset" on
the parallel port.  As the reset operation is potentially disruptive in
multiple device environments, the PARIDE drivers will not do it
automatically.  You can however, force a printer reset by doing::

	insmod lp reset=1
	rmmod lp

If you have one of these marginal cases, you should probably build
your paride drivers as modules, and arrange to do the printer reset
before loading the PARIDE drivers.

3.4  Use the verbose option and dmesg if you need help
------------------------------------------------------

While a lot of testing has gone into these drivers to make them work
as smoothly as possible, problems will arise.  If you do have problems,
please check all the obvious things first:  does the drive work in
DOS with the manufacturer's drivers ?  If that doesn't yield any useful
clues, then please make sure that only one drive is hooked to your system,
and that either (a) PARPORT is enabled or (b) no other device driver
is using your parallel port (check in /proc/ioports).  Then, load the
appropriate drivers (you can load several protocol modules if you want)
as in::

	# insmod paride
	# insmod epat
	# insmod bpck
	# insmod kbic
	...
	# insmod pd verbose=1

(using the correct driver for the type of device you have, of course).
The verbose=1 parameter will cause the drivers to log a trace of their
activity as they attempt to locate your drive.

Use 'dmesg' to capture a log of all the PARIDE messages (any messages
beginning with paride:, a protocol module's name or a driver's name) and
include that with your bug report.  You can submit a bug report in one
of two ways.  Either send it directly to the author of the PARIDE suite,
by e-mail to grant@torque.net, or join the linux-parport mailing list
and post your report there.

3.5  For more information or help
---------------------------------

You can join the linux-parport mailing list by sending a mail message
to:

		linux-parport-request@torque.net

with the single word::

		subscribe

in the body of the mail message (not in the subject line).   Please be
sure that your mail program is correctly set up when you do this,  as
the list manager is a robot that will subscribe you using the reply
address in your mail headers.  REMOVE any anti-spam gimmicks you may
have in your mail headers, when sending mail to the list server.

You might also find some useful information on the linux-parport
web pages (although they are not always up to date) at

	http://web.archive.org/web/%2E/http://www.torque.net/parport/