code:
===============================
Creating an input device driver
===============================

The simplest example
~~~~~~~~~~~~~~~~~~~~

Here comes a very simple example of an input device driver. The device has
just one button and the button is accessible at i/o port BUTTON_PORT. When
pressed or released a BUTTON_IRQ happens. The driver could look like::

    #include <linux/input.h>
    #include <linux/module.h>
    #include <linux/init.h>

    #include <asm/irq.h>
    #include <asm/io.h>

    static struct input_dev *button_dev;

    static irqreturn_t button_interrupt(int irq, void *dummy)
    {
	    input_report_key(button_dev, BTN_0, inb(BUTTON_PORT) & 1);
	    input_sync(button_dev);
	    return IRQ_HANDLED;
    }

    static int __init button_init(void)
    {
	    int error;

	    if (request_irq(BUTTON_IRQ, button_interrupt, 0, "button", NULL)) {
		    printk(KERN_ERR "button.c: Can't allocate irq %d\n", button_irq);
		    return -EBUSY;
	    }

	    button_dev = input_allocate_device();
	    if (!button_dev) {
		    printk(KERN_ERR "button.c: Not enough memory\n");
		    error = -ENOMEM;
		    goto err_free_irq;
	    }

	    button_dev->evbit[0] = BIT_MASK(EV_KEY);
	    button_dev->keybit[BIT_WORD(BTN_0)] = BIT_MASK(BTN_0);

	    error = input_register_device(button_dev);
	    if (error) {
		    printk(KERN_ERR "button.c: Failed to register device\n");
		    goto err_free_dev;
	    }

	    return 0;

    err_free_dev:
	    input_free_device(button_dev);
    err_free_irq:
	    free_irq(BUTTON_IRQ, button_interrupt);
	    return error;
    }

    static void __exit button_exit(void)
    {
	    input_unregister_device(button_dev);
	    free_irq(BUTTON_IRQ, button_interrupt);
    }

    module_init(button_init);
    module_exit(button_exit);

What the example does
~~~~~~~~~~~~~~~~~~~~~

First it has to include the <linux/input.h> file, which interfaces to the
input subsystem. This provides all the definitions needed.

In the _init function, which is called either upon module load or when
booting the kernel, it grabs the required resources (it should also check
for the presence of the device).

Then it allocates a new input device structure with input_allocate_device()
and sets up input bitfields. This way the device driver tells the other
parts of the input systems what it is - what events can be generated or
accepted by this input device. Our example device can only generate EV_KEY
type events, and from those only BTN_0 event code. Thus we only set these
two bits. We could have used::

	set_bit(EV_KEY, button_dev->evbit);
	set_bit(BTN_0, button_dev->keybit);

as well, but with more than single bits the first approach tends to be
shorter.

Then the example driver registers the input device structure by calling::

	input_register_device(button_dev);

This adds the button_dev structure to linked lists of the input driver and
calls device handler modules _connect functions to tell them a new input
device has appeared. input_register_device() may sleep and therefore must
not be called from an interrupt or with a spinlock held.

While in use, the only used function of the driver is::

	button_interrupt()

which upon every interrupt from the button checks its state and reports it
via the::

	input_report_key()

call to the input system. There is no need to check whether the interrupt
routine isn't reporting two same value events (press, press for example) to
the input system, because the input_report_* functions check that
themselves.

Then there is the::

	input_sync()

call to tell those who receive the events that we've sent a complete report.
This doesn't seem important in the one button case, but is quite important
for example for mouse movement, where you don't want the X and Y values
to be interpreted separately, because that'd result in a different movement.

dev->open() and dev->close()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In case the driver has to repeatedly poll the device, because it doesn't
have an interrupt coming from it and the polling is too expensive to be done
all the time, or if the device uses a valuable resource (e.g. interrupt), it
can use the open and close callback to know when it can stop polling or
release the interrupt and when it must resume polling or grab the interrupt
again. To do that, we would add this to our example driver::

    static int button_open(struct input_dev *dev)
    {
	    if (request_irq(BUTTON_IRQ, button_interrupt, 0, "button", NULL)) {
		    printk(KERN_ERR "button.c: Can't allocate irq %d\n", button_irq);
		    return -EBUSY;
	    }

	    return 0;
    }

    static void button_close(struct input_dev *dev)
    {
	    free_irq(IRQ_AMIGA_VERTB, button_interrupt);
    }

    static int __init button_init(void)
    {
	    ...
	    button_dev->open = button_open;
	    button_dev->close = button_close;
	    ...
    }

Note that input core keeps track of number of users for the device and
makes sure that dev->open() is called only when the first user connects
to the device and that dev->close() is called when the very last user
disconnects. Calls to both callbacks are serialized.

The open() callback should return a 0 in case of success or any non-zero value
in case of failure. The close() callback (which is void) must always succeed.

Inhibiting input devices
~~~~~~~~~~~~~~~~~~~~~~~~

Inhibiting a device means ignoring input events from it. As such it is about
maintaining relationships with input handlers - either already existing
relationships, or relationships to be established while the device is in
inhibited state.

If a device is inhibited, no input handler will receive events from it.

The fact that nobody wants events from the device is exploited further, by
calling device's close() (if there are users) and open() (if there are users) on
inhibit and uninhibit operations, respectively. Indeed, the meaning of close()
is to stop providing events to the input core and that of open() is to start
providing events to the input core.

Calling the device's close() method on inhibit (if there are users) allows the
driver to save power. Either by directly powering down the device or by
releasing the runtime-PM reference it got in open() when the driver is using
runtime-PM.

Inhibiting and uninhibiting are orthogonal to opening and closing the device by
input handlers. Userspace might want to inhibit a device in anticipation before
any handler is positively matched against it.

Inhibiting and uninhibiting are orthogonal to device's being a wakeup source,
too. Being a wakeup source plays a role when the system is sleeping, not when
the system is operating.  How drivers should program their interaction between
inhibiting, sleeping and being a wakeup source is driver-specific.

Taking the analogy with the network devices - bringing a network interface down
doesn't mean that it should be impossible be wake the system up on LAN through
this interface. So, there may be input drivers which should be considered wakeup
sources even when inhibited. Actually, in many I2C input devices their interrupt
is declared a wakeup interrupt and its handling happens in driver's core, which
is not aware of input-specific inhibit (nor should it be).  Composite devices
containing several interfaces can be inhibited on a per-interface basis and e.g.
inhibiting one interface shouldn't affect the device's capability of being a
wakeup source.

If a device is to be considered a wakeup source while inhibited, special care
must be taken when programming its suspend(), as it might need to call device's
open(). Depending on what close() means for the device in question, not
opening() it before going to sleep might make it impossible to provide any
wakeup events. The device is going to sleep anyway.

Basic event types
~~~~~~~~~~~~~~~~~

The most simple event type is EV_KEY, which is used for keys and buttons.
It's reported to the input system via::

	input_report_key(struct input_dev *dev, int code, int value)

See uapi/linux/input-event-codes.h for the allowable values of code (from 0 to
KEY_MAX). Value is interpreted as a truth value, i.e. any non-zero value means
key pressed, zero value means key released. The input code generates events only
in case the value is different from before.

In addition to EV_KEY, there are two more basic event types: EV_REL and
EV_ABS. They are used for relative and absolute values supplied by the
device. A relative value may be for example a mouse movement in the X axis.
The mouse reports it as a relative difference from the last position,
because it doesn't have any absolute coordinate system to work in. Absolute
events are namely for joysticks and digitizers - devices that do work in an
absolute coordinate systems.

Having the device report EV_REL buttons is as simple as with EV_KEY; simply
set the corresponding bits and call the::

	input_report_rel(struct input_dev *dev, int code, int value)

function. Events are generated only for non-zero values.

However EV_ABS requires a little special care. Before calling
input_register_device, you have to fill additional fields in the input_dev
struct for each absolute axis your device has. If our button device had also
the ABS_X axis::

	button_dev.absmin[ABS_X] = 0;
	button_dev.absmax[ABS_X] = 255;
	button_dev.absfuzz[ABS_X] = 4;
	button_dev.absflat[ABS_X] = 8;

Or, you can just say::

	input_set_abs_params(button_dev, ABS_X, 0, 255, 4, 8);

This setting would be appropriate for a joystick X axis, with the minimum of
0, maximum of 255 (which the joystick *must* be able to reach, no problem if
it sometimes reports more, but it must be able to always reach the min and
max values), with noise in the data up to +- 4, and with a center flat
position of size 8.

If you don't need absfuzz and absflat, you can set them to zero, which mean
that the thing is precise and always returns to exactly the center position
(if it has any).

BITS_TO_LONGS(), BIT_WORD(), BIT_MASK()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

These three macros from bitops.h help some bitfield computations::

	BITS_TO_LONGS(x) - returns the length of a bitfield array in longs for
			   x bits
	BIT_WORD(x)	 - returns the index in the array in longs for bit x
	BIT_MASK(x)	 - returns the index in a long for bit x

The id* and name fields
~~~~~~~~~~~~~~~~~~~~~~~

The dev->name should be set before registering the input device by the input
device driver. It's a string like 'Generic button device' containing a
user friendly name of the device.

The id* fields contain the bus ID (PCI, USB, ...), vendor ID and device ID
of the device. The bus IDs are defined in input.h. The vendor and device IDs
are defined in pci_ids.h, usb_ids.h and similar include files. These fields
should be set by the input device driver before registering it.

The idtype field can be used for specific information for the input device
driver.

The id and name fields can be passed to userland via the evdev interface.

The keycode, keycodemax, keycodesize fields
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

These three fields should be used by input devices that have dense keymaps.
The keycode is an array used to map from scancodes to input system keycodes.
The keycode max should contain the size of the array and keycodesize the
size of each entry in it (in bytes).

Userspace can query and alter current scancode to keycode mappings using
EVIOCGKEYCODE and EVIOCSKEYCODE ioctls on corresponding evdev interface.
When a device has all 3 aforementioned fields filled in, the driver may
rely on kernel's default implementation of setting and querying keycode
mappings.

dev->getkeycode() and dev->setkeycode()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

getkeycode() and setkeycode() callbacks allow drivers to override default
keycode/keycodesize/keycodemax mapping mechanism provided by input core
and implement sparse keycode maps.

Key autorepeat
~~~~~~~~~~~~~~

... is simple. It is handled by the input.c module. Hardware autorepeat is
not used, because it's not present in many devices and even where it is
present, it is broken sometimes (at keyboards: Toshiba notebooks). To enable
autorepeat for your device, just set EV_REP in dev->evbit. All will be
handled by the input system.

Other event types, handling output events
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The other event types up to now are:

- EV_LED - used for the keyboard LEDs.
- EV_SND - used for keyboard beeps.

They are very similar to for example key events, but they go in the other
direction - from the system to the input device driver. If your input device
driver can handle these events, it has to set the respective bits in evbit,
*and* also the callback routine::

    button_dev->event = button_event;

    int button_event(struct input_dev *dev, unsigned int type,
		     unsigned int code, int value)
    {
	    if (type == EV_SND && code == SND_BELL) {
		    outb(value, BUTTON_BELL);
		    return 0;
	    }
	    return -1;
    }

This callback routine can be called from an interrupt or a BH (although that
isn't a rule), and thus must not sleep, and must not take too long to finish.


code:
.. include:: <isonum.txt>

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

:Copyright: |copy| 1999-2001 Vojtech Pavlik <vojtech@ucw.cz> - Sponsored by SuSE

Architecture
============

Input subsystem is a collection of drivers that is designed to support
all input devices under Linux. Most of the drivers reside in
drivers/input, although quite a few live in drivers/hid and
drivers/platform.

The core of the input subsystem is the input module, which must be
loaded before any other of the input modules - it serves as a way of
communication between two groups of modules:

Device drivers
--------------

These modules talk to the hardware (for example via USB), and provide
events (keystrokes, mouse movements) to the input module.

Event handlers
--------------

These modules get events from input core and pass them where needed
via various interfaces - keystrokes to the kernel, mouse movements via
a simulated PS/2 interface to GPM and X, and so on.

Simple Usage
============

For the most usual configuration, with one USB mouse and one USB keyboard,
you'll have to load the following modules (or have them built in to the
kernel)::

	input
	mousedev
	usbcore
	uhci_hcd or ohci_hcd or ehci_hcd
	usbhid
	hid_generic

After this, the USB keyboard will work straight away, and the USB mouse
will be available as a character device on major 13, minor 63::

	crw-r--r--   1 root     root      13,  63 Mar 28 22:45 mice

This device is usually created automatically by the system. The commands
to create it by hand are::

	cd /dev
	mkdir input
	mknod input/mice c 13 63

After that you have to point GPM (the textmode mouse cut&paste tool) and
XFree to this device to use it - GPM should be called like::

	gpm -t ps2 -m /dev/input/mice

And in X::

	Section "Pointer"
	    Protocol    "ImPS/2"
	    Device      "/dev/input/mice"
	    ZAxisMapping 4 5
	EndSection

When you do all of the above, you can use your USB mouse and keyboard.

Detailed Description
====================

Event handlers
--------------

Event handlers distribute the events from the devices to userspace and
in-kernel consumers, as needed.

evdev
~~~~~

``evdev`` is the generic input event interface. It passes the events
generated in the kernel straight to the program, with timestamps. The
event codes are the same on all architectures and are hardware
independent.

This is the preferred interface for userspace to consume user
input, and all clients are encouraged to use it.

See :ref:`event-interface` for notes on API.

The devices are in /dev/input::

	crw-r--r--   1 root     root      13,  64 Apr  1 10:49 event0
	crw-r--r--   1 root     root      13,  65 Apr  1 10:50 event1
	crw-r--r--   1 root     root      13,  66 Apr  1 10:50 event2
	crw-r--r--   1 root     root      13,  67 Apr  1 10:50 event3
	...

There are two ranges of minors: 64 through 95 is the static legacy
range. If there are more than 32 input devices in a system, additional
evdev nodes are created with minors starting with 256.

keyboard
~~~~~~~~

``keyboard`` is in-kernel input handler and is a part of VT code. It
consumes keyboard keystrokes and handles user input for VT consoles.

mousedev
~~~~~~~~

``mousedev`` is a hack to make legacy programs that use mouse input
work. It takes events from either mice or digitizers/tablets and makes
a PS/2-style (a la /dev/psaux) mouse device available to the
userland.

Mousedev devices in /dev/input (as shown above) are::

	crw-r--r--   1 root     root      13,  32 Mar 28 22:45 mouse0
	crw-r--r--   1 root     root      13,  33 Mar 29 00:41 mouse1
	crw-r--r--   1 root     root      13,  34 Mar 29 00:41 mouse2
	crw-r--r--   1 root     root      13,  35 Apr  1 10:50 mouse3
	...
	...
	crw-r--r--   1 root     root      13,  62 Apr  1 10:50 mouse30
	crw-r--r--   1 root     root      13,  63 Apr  1 10:50 mice

Each ``mouse`` device is assigned to a single mouse or digitizer, except
the last one - ``mice``. This single character device is shared by all
mice and digitizers, and even if none are connected, the device is
present.  This is useful for hotplugging USB mice, so that older programs
that do not handle hotplug can open the device even when no mice are
present.

CONFIG_INPUT_MOUSEDEV_SCREEN_[XY] in the kernel configuration are
the size of your screen (in pixels) in XFree86. This is needed if you
want to use your digitizer in X, because its movement is sent to X
via a virtual PS/2 mouse and thus needs to be scaled
accordingly. These values won't be used if you use a mouse only.

Mousedev will generate either PS/2, ImPS/2 (Microsoft IntelliMouse) or
ExplorerPS/2 (IntelliMouse Explorer) protocols, depending on what the
program reading the data wishes. You can set GPM and X to any of
these. You'll need ImPS/2 if you want to make use of a wheel on a USB
mouse and ExplorerPS/2 if you want to use extra (up to 5) buttons.

joydev
~~~~~~

``joydev`` implements v0.x and v1.x Linux joystick API. See
:ref:`joystick-api` for details.

As soon as any joystick is connected, it can be accessed in /dev/input on::

	crw-r--r--   1 root     root      13,   0 Apr  1 10:50 js0
	crw-r--r--   1 root     root      13,   1 Apr  1 10:50 js1
	crw-r--r--   1 root     root      13,   2 Apr  1 10:50 js2
	crw-r--r--   1 root     root      13,   3 Apr  1 10:50 js3
	...

And so on up to js31 in legacy range, and additional nodes with minors
above 256 if there are more joystick devices.

Device drivers
--------------

Device drivers are the modules that generate events.

hid-generic
~~~~~~~~~~~

``hid-generic`` is one of the largest and most complex driver of the
whole suite. It handles all HID devices, and because there is a very
wide variety of them, and because the USB HID specification isn't
simple, it needs to be this big.

Currently, it handles USB mice, joysticks, gamepads, steering wheels,
keyboards, trackballs and digitizers.

However, USB uses HID also for monitor controls, speaker controls, UPSs,
LCDs and many other purposes.

The monitor and speaker controls should be easy to add to the hid/input
interface, but for the UPSs and LCDs it doesn't make much sense. For this,
the hiddev interface was designed. See Documentation/hid/hiddev.rst
for more information about it.

The usage of the usbhid module is very simple, it takes no parameters,
detects everything automatically and when a HID device is inserted, it
detects it appropriately.

However, because the devices vary wildly, you might happen to have a
device that doesn't work well. In that case #define DEBUG at the beginning
of hid-core.c and send me the syslog traces.

usbmouse
~~~~~~~~

For embedded systems, for mice with broken HID descriptors and just any
other use when the big usbhid wouldn't be a good choice, there is the
usbmouse driver. It handles USB mice only. It uses a simpler HIDBP
protocol. This also means the mice must support this simpler protocol. Not
all do. If you don't have any strong reason to use this module, use usbhid
instead.

usbkbd
~~~~~~

Much like usbmouse, this module talks to keyboards with a simplified
HIDBP protocol. It's smaller, but doesn't support any extra special keys.
Use usbhid instead if there isn't any special reason to use this.

psmouse
~~~~~~~

This is driver for all flavors of pointing devices using PS/2
protocol, including Synaptics and ALPS touchpads, Intellimouse
Explorer devices, Logitech PS/2 mice and so on.

atkbd
~~~~~

This is driver for PS/2 (AT) keyboards.

iforce
~~~~~~

A driver for I-Force joysticks and wheels, both over USB and RS232.
It includes Force Feedback support now, even though Immersion
Corp. considers the protocol a trade secret and won't disclose a word
about it.

Verifying if it works
=====================

Typing a couple keys on the keyboard should be enough to check that
a keyboard works and is correctly connected to the kernel keyboard
driver.

Doing a ``cat /dev/input/mouse0`` (c, 13, 32) will verify that a mouse
is also emulated; characters should appear if you move it.

You can test the joystick emulation with the ``jstest`` utility,
available in the joystick package (see :ref:`joystick-doc`).

You can test the event devices with the ``evtest`` utility.

.. _event-interface:

Event interface
===============

You can use blocking and nonblocking reads, and also select() on the
/dev/input/eventX devices, and you'll always get a whole number of input
events on a read. Their layout is::

    struct input_event {
	    struct timeval time;
	    unsigned short type;
	    unsigned short code;
	    unsigned int value;
    };

``time`` is the timestamp, it returns the time at which the event happened.
Type is for example EV_REL for relative movement, EV_KEY for a keypress or
release. More types are defined in include/uapi/linux/input-event-codes.h.

``code`` is event code, for example REL_X or KEY_BACKSPACE, again a complete
list is in include/uapi/linux/input-event-codes.h.

``value`` is the value the event carries. Either a relative change for
EV_REL, absolute new value for EV_ABS (joysticks ...), or 0 for EV_KEY for
release, 1 for keypress and 2 for autorepeat.

See :ref:`input-event-codes` for more information about various even codes.

repo_name: angery/linux


code:
.. include:: <isonum.txt>

################################
Linux Input Subsystem kernel API
################################

.. class:: toc-title

        Table of Contents

.. toctree::
   :maxdepth: 2
   :numbered:

   input-programming
   gameport-programming
   notifier


code:
.. include:: <isonum.txt>

###################################
Linux Input Subsystem userspace API
###################################

.. class:: toc-title

        Table of Contents

.. toctree::
   :maxdepth: 2
   :numbered:

   input
   event-codes
   multi-touch-protocol
   gamepad
   ff
   joydev/index
   uinput
   userio


code:
.. include:: <isonum.txt>

======================
Linux Joystick support
======================

:Copyright: |copy| 1996-2000 Vojtech Pavlik <vojtech@ucw.cz> - Sponsored by SuSE

.. class:: toc-title

	Table of Contents

.. toctree::
	:maxdepth: 3

	joystick
	joystick-api


code:
.. _joystick-api:

=====================
Programming Interface
=====================

:Author: Ragnar Hojland Espinosa <ragnar@macula.net> - 7 Aug 1998

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

.. important::
   This document describes legacy ``js`` interface. Newer clients are
   encouraged to switch to the generic event (``evdev``) interface.

The 1.0 driver uses a new, event based approach to the joystick driver.
Instead of the user program polling for the joystick values, the joystick
driver now reports only any changes of its state. See joystick-api.txt,
joystick.h and jstest.c included in the joystick package for more
information. The joystick device can be used in either blocking or
nonblocking mode, and supports select() calls.

For backward compatibility the old (v0.x) interface is still included.
Any call to the joystick driver using the old interface will return values
that are compatible to the old interface. This interface is still limited
to 2 axes, and applications using it usually decode only 2 buttons, although
the driver provides up to 32.

Initialization
==============

Open the joystick device following the usual semantics (that is, with open).
Since the driver now reports events instead of polling for changes,
immediately after the open it will issue a series of synthetic events
(JS_EVENT_INIT) that you can read to obtain the initial state of the
joystick.

By default, the device is opened in blocking mode::

	int fd = open ("/dev/input/js0", O_RDONLY);

Event Reading
=============

::

	struct js_event e;
	read (fd, &e, sizeof(e));

where js_event is defined as::

	struct js_event {
		__u32 time;     /* event timestamp in milliseconds */
		__s16 value;    /* value */
		__u8 type;      /* event type */
		__u8 number;    /* axis/button number */
	};

If the read is successful, it will return sizeof(e), unless you wanted to read
more than one event per read as described in section 3.1.

js_event.type
-------------

The possible values of ``type`` are::

	#define JS_EVENT_BUTTON         0x01    /* button pressed/released */
	#define JS_EVENT_AXIS           0x02    /* joystick moved */
	#define JS_EVENT_INIT           0x80    /* initial state of device */

As mentioned above, the driver will issue synthetic JS_EVENT_INIT ORed
events on open. That is, if it's issuing an INIT BUTTON event, the
current type value will be::

	int type = JS_EVENT_BUTTON | JS_EVENT_INIT;	/* 0x81 */

If you choose not to differentiate between synthetic or real events
you can turn off the JS_EVENT_INIT bits::

	type &= ~JS_EVENT_INIT;				/* 0x01 */

js_event.number
---------------

The values of ``number`` correspond to the axis or button that
generated the event. Note that they carry separate numeration (that
is, you have both an axis 0 and a button 0). Generally,

        =============== =======
	Axis		number
        =============== =======
	1st Axis X	0
	1st Axis Y	1
	2nd Axis X	2
	2nd Axis Y	3
	...and so on
        =============== =======

Hats vary from one joystick type to another. Some can be moved in 8
directions, some only in 4. The driver, however, always reports a hat as two
independent axes, even if the hardware doesn't allow independent movement.

js_event.value
--------------

For an axis, ``value`` is a signed integer between -32767 and +32767
representing the position of the joystick along that axis. If you
don't read a 0 when the joystick is ``dead``, or if it doesn't span the
full range, you should recalibrate it (with, for example, jscal).

For a button, ``value`` for a press button event is 1 and for a release
button event is 0.

Though this::

	if (js_event.type == JS_EVENT_BUTTON) {
		buttons_state ^= (1 << js_event.number);
	}

may work well if you handle JS_EVENT_INIT events separately,

::

	if ((js_event.type & ~JS_EVENT_INIT) == JS_EVENT_BUTTON) {
		if (js_event.value)
			buttons_state |= (1 << js_event.number);
		else
			buttons_state &= ~(1 << js_event.number);
	}

is much safer since it can't lose sync with the driver. As you would
have to write a separate handler for JS_EVENT_INIT events in the first
snippet, this ends up being shorter.

js_event.time
-------------

The time an event was generated is stored in ``js_event.time``. It's a time
in milliseconds since ... well, since sometime in the past.  This eases the
task of detecting double clicks, figuring out if movement of axis and button
presses happened at the same time, and similar.

Reading
=======

If you open the device in blocking mode, a read will block (that is,
wait) forever until an event is generated and effectively read. There
are two alternatives if you can't afford to wait forever (which is,
admittedly, a long time;)

	a) use select to wait until there's data to be read on fd, or
	   until it timeouts. There's a good example on the select(2)
	   man page.

	b) open the device in non-blocking mode (O_NONBLOCK)

O_NONBLOCK
----------

If read returns -1 when reading in O_NONBLOCK mode, this isn't
necessarily a "real" error (check errno(3)); it can just mean there
are no events pending to be read on the driver queue. You should read
all events on the queue (that is, until you get a -1).

For example,

::

	while (1) {
		while (read (fd, &e, sizeof(e)) > 0) {
			process_event (e);
		}
		/* EAGAIN is returned when the queue is empty */
		if (errno != EAGAIN) {
			/* error */
		}
		/* do something interesting with processed events */
	}

One reason for emptying the queue is that if it gets full you'll start
missing events since the queue is finite, and older events will get
overwritten.

The other reason is that you want to know all that happened, and not
delay the processing till later.

Why can the queue get full? Because you don't empty the queue as
mentioned, or because too much time elapses from one read to another
and too many events to store in the queue get generated. Note that
high system load may contribute to space those reads even more.

If time between reads is enough to fill the queue and lose an event,
the driver will switch to startup mode and next time you read it,
synthetic events (JS_EVENT_INIT) will be generated to inform you of
the actual state of the joystick.

.. note::

 As of version 1.2.8, the queue is circular and able to hold 64
 events. You can increment this size bumping up JS_BUFF_SIZE in
 joystick.h and recompiling the driver.

In the above code, you might as well want to read more than one event
at a time using the typical read(2) functionality. For that, you would
replace the read above with something like::

	struct js_event mybuffer[0xff];
	int i = read (fd, mybuffer, sizeof(mybuffer));

In this case, read would return -1 if the queue was empty, or some
other value in which the number of events read would be i /
sizeof(js_event)  Again, if the buffer was full, it's a good idea to
process the events and keep reading it until you empty the driver queue.

IOCTLs
======

The joystick driver defines the following ioctl(2) operations::

				/* function			3rd arg  */
	#define JSIOCGAXES	/* get number of axes		char	 */
	#define JSIOCGBUTTONS	/* get number of buttons	char	 */
	#define JSIOCGVERSION	/* get driver version		int	 */
	#define JSIOCGNAME(len) /* get identifier string	char	 */
	#define JSIOCSCORR	/* set correction values	&js_corr */
	#define JSIOCGCORR	/* get correction values	&js_corr */

For example, to read the number of axes::

	char number_of_axes;
	ioctl (fd, JSIOCGAXES, &number_of_axes);

JSIOGCVERSION
-------------

JSIOGCVERSION is a good way to check in run-time whether the running
driver is 1.0+ and supports the event interface. If it is not, the
IOCTL will fail. For a compile-time decision, you can test the
JS_VERSION symbol::

	#ifdef JS_VERSION
	#if JS_VERSION > 0xsomething

JSIOCGNAME
----------

JSIOCGNAME(len) allows you to get the name string of the joystick - the same
as is being printed at boot time. The 'len' argument is the length of the
buffer provided by the application asking for the name. It is used to avoid
possible overrun should the name be too long::

	char name[128];
	if (ioctl(fd, JSIOCGNAME(sizeof(name)), name) < 0)
		strscpy(name, "Unknown", sizeof(name));
	printf("Name: %s\n", name);

JSIOC[SG]CORR
-------------

For usage on JSIOC[SG]CORR I suggest you to look into jscal.c  They are
not needed in a normal program, only in joystick calibration software
such as jscal or kcmjoy. These IOCTLs and data types aren't considered
to be in the stable part of the API, and therefore may change without
warning in following releases of the driver.

Both JSIOCSCORR and JSIOCGCORR expect &js_corr to be able to hold
information for all axes. That is, struct js_corr corr[MAX_AXIS];

struct js_corr is defined as::

	struct js_corr {
		__s32 coef[8];
		__u16 prec;
		__u16 type;
	};

and ``type``::

	#define JS_CORR_NONE            0x00    /* returns raw values */
	#define JS_CORR_BROKEN          0x01    /* broken line */

Backward compatibility
======================

The 0.x joystick driver API is quite limited and its usage is deprecated.
The driver offers backward compatibility, though. Here's a quick summary::

	struct JS_DATA_TYPE js;
	while (1) {
		if (read (fd, &js, JS_RETURN) != JS_RETURN) {
			/* error */
		}
		usleep (1000);
	}

As you can figure out from the example, the read returns immediately,
with the actual state of the joystick::

	struct JS_DATA_TYPE {
		int buttons;    /* immediate button state */
		int x;          /* immediate x axis value */
		int y;          /* immediate y axis value */
	};

and JS_RETURN is defined as::

	#define JS_RETURN       sizeof(struct JS_DATA_TYPE)

To test the state of the buttons,

::

	first_button_state  = js.buttons & 1;
	second_button_state = js.buttons & 2;

The axis values do not have a defined range in the original 0.x driver,
except that the values are non-negative. The 1.2.8+ drivers use a
fixed range for reporting the values, 1 being the minimum, 128 the
center, and 255 maximum value.

The v0.8.0.2 driver also had an interface for 'digital joysticks', (now
called Multisystem joysticks in this driver), under /dev/djsX. This driver
doesn't try to be compatible with that interface.

Final Notes
===========

::

  ____/|	Comments, additions, and specially corrections are welcome.
  \ o.O|	Documentation valid for at least version 1.2.8 of the joystick
   =(_)=	driver and as usual, the ultimate source for documentation is
     U		to "Use The Source Luke" or, at your convenience, Vojtech ;)


code:
.. include:: <isonum.txt>

.. _joystick-doc:

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

The joystick driver for Linux provides support for a variety of joysticks
and similar devices. It is based on a larger project aiming to support all
input devices in Linux.

The mailing list for the project is:

	linux-input@vger.kernel.org

send "subscribe linux-input" to majordomo@vger.kernel.org to subscribe to it.

Usage
=====

For basic usage you just choose the right options in kernel config and
you should be set.

Utilities
---------

For testing and other purposes (for example serial devices), there is a set
of utilities, such as ``jstest``, ``jscal``, and ``evtest``,
usually packaged as ``joystick``, ``input-utils``, ``evtest``, and so on.

``inputattach`` utility is required if your joystick is connected to a
serial port.

Device nodes
------------

For applications to be able to use the joysticks, device nodes should be
created in /dev. Normally it is done automatically by the system, but
it can also be done by hand::

    cd /dev
    rm js*
    mkdir input
    mknod input/js0 c 13 0
    mknod input/js1 c 13 1
    mknod input/js2 c 13 2
    mknod input/js3 c 13 3
    ln -s input/js0 js0
    ln -s input/js1 js1
    ln -s input/js2 js2
    ln -s input/js3 js3

For testing with inpututils it's also convenient to create these::

    mknod input/event0 c 13 64
    mknod input/event1 c 13 65
    mknod input/event2 c 13 66
    mknod input/event3 c 13 67

Modules needed
--------------

For all joystick drivers to function, you'll need the userland interface
module in kernel, either loaded or compiled in::

	modprobe joydev

For gameport joysticks, you'll have to load the gameport driver as well::

	modprobe ns558

And for serial port joysticks, you'll need the serial input line
discipline module loaded and the inputattach utility started::

	modprobe serport
	inputattach -xxx /dev/tts/X &

In addition to that, you'll need the joystick driver module itself, most
usually you'll have an analog joystick::

	modprobe analog

For automatic module loading, something like this might work - tailor to
your needs::

	alias tty-ldisc-2 serport
	alias char-major-13 input
	above input joydev ns558 analog
	options analog map=gamepad,none,2btn

Verifying that it works
-----------------------

For testing the joystick driver functionality, there is the jstest
program in the utilities package. You run it by typing::

	jstest /dev/input/js0

And it should show a line with the joystick values, which update as you
move the stick, and press its buttons. The axes should all be zero when the
joystick is in the center position. They should not jitter by themselves to
other close values, and they also should be steady in any other position of
the stick. They should have the full range from -32767 to 32767. If all this
is met, then it's all fine, and you can play the games. :)

If it's not, then there might be a problem. Try to calibrate the joystick,
and if it still doesn't work, read the drivers section of this file, the
troubleshooting section, and the FAQ.

Calibration
-----------

For most joysticks you won't need any manual calibration, since the
joystick should be autocalibrated by the driver automagically. However, with
some analog joysticks, that either do not use linear resistors, or if you
want better precision, you can use the jscal program::

	jscal -c /dev/input/js0

included in the joystick package to set better correction coefficients than
what the driver would choose itself.

After calibrating the joystick you can verify if you like the new
calibration using the jstest command, and if you do, you then can save the
correction coefficients into a file::

	jscal -p /dev/input/js0 > /etc/joystick.cal

And add a line to your rc script executing that file::

	source /etc/joystick.cal

This way, after the next reboot your joystick will remain calibrated. You
can also add the ``jscal -p`` line to your shutdown script.

Hardware-specific driver information
====================================

In this section each of the separate hardware specific drivers is described.

Analog joysticks
----------------

The analog.c driver uses the standard analog inputs of the gameport, and thus
supports all standard joysticks and gamepads. It uses a very advanced
routine for this, allowing for data precision that can't be found on any
other system.

It also supports extensions like additional hats and buttons compatible
with CH Flightstick Pro, ThrustMaster FCS or 6 and 8 button gamepads. Saitek
Cyborg 'digital' joysticks are also supported by this driver, because
they're basically souped up CHF sticks.

However the only types that can be autodetected are:

* 2-axis, 4-button joystick
* 3-axis, 4-button joystick
* 4-axis, 4-button joystick
* Saitek Cyborg 'digital' joysticks

For other joystick types (more/less axes, hats, and buttons) support
you'll need to specify the types either on the kernel command line or on the
module command line, when inserting analog into the kernel. The
parameters are::

	analog.map=<type1>,<type2>,<type3>,....

'type' is type of the joystick from the table below, defining joysticks
present on gameports in the system, starting with gameport0, second 'type'
entry defining joystick on gameport1 and so on.

	========= =====================================================
	Type      Meaning
	========= =====================================================
	none      No analog joystick on that port
	auto      Autodetect joystick
	2btn      2-button n-axis joystick
	y-joy     Two 2-button 2-axis joysticks on an Y-cable
	y-pad     Two 2-button 2-axis gamepads on an Y-cable
	fcs       Thrustmaster FCS compatible joystick
	chf       Joystick with a CH Flightstick compatible hat
	fullchf   CH Flightstick compatible with two hats and 6 buttons
	gamepad   4/6-button n-axis gamepad
	gamepad8  8-button 2-axis gamepad
	========= =====================================================

In case your joystick doesn't fit in any of the above categories, you can
specify the type as a number by combining the bits in the table below. This
is not recommended unless you really know what are you doing. It's not
dangerous, but not simple either.

	==== =========================
	Bit  Meaning
	==== =========================
	 0   Axis X1
	 1   Axis Y1
	 2   Axis X2
	 3   Axis Y2
	 4   Button A
	 5   Button B
	 6   Button C
	 7   Button D
	 8   CHF Buttons X and Y
	 9   CHF Hat 1
	10   CHF Hat 2
	11   FCS Hat
	12   Pad Button X
	13   Pad Button Y
	14   Pad Button U
	15   Pad Button V
	16   Saitek F1-F4 Buttons
	17   Saitek Digital Mode
	19   GamePad
	20   Joy2 Axis X1
	21   Joy2 Axis Y1
	22   Joy2 Axis X2
	23   Joy2 Axis Y2
	24   Joy2 Button A
	25   Joy2 Button B
	26   Joy2 Button C
	27   Joy2 Button D
	31   Joy2 GamePad
	==== =========================

Microsoft SideWinder joysticks
------------------------------

Microsoft 'Digital Overdrive' protocol is supported by the sidewinder.c
module. All currently supported joysticks:

* Microsoft SideWinder 3D Pro
* Microsoft SideWinder Force Feedback Pro
* Microsoft SideWinder Force Feedback Wheel
* Microsoft SideWinder FreeStyle Pro
* Microsoft SideWinder GamePad (up to four, chained)
* Microsoft SideWinder Precision Pro
* Microsoft SideWinder Precision Pro USB

are autodetected, and thus no module parameters are needed.

There is one caveat with the 3D Pro. There are 9 buttons reported,
although the joystick has only 8. The 9th button is the mode switch on the
rear side of the joystick. However, moving it, you'll reset the joystick,
and make it unresponsive for about a one third of a second. Furthermore, the
joystick will also re-center itself, taking the position it was in during
this time as a new center position. Use it if you want, but think first.

The SideWinder Standard is not a digital joystick, and thus is supported
by the analog driver described above.

Logitech ADI devices
--------------------

Logitech ADI protocol is supported by the adi.c module. It should support
any Logitech device using this protocol. This includes, but is not limited
to:

* Logitech CyberMan 2
* Logitech ThunderPad Digital
* Logitech WingMan Extreme Digital
* Logitech WingMan Formula
* Logitech WingMan Interceptor
* Logitech WingMan GamePad
* Logitech WingMan GamePad USB
* Logitech WingMan GamePad Extreme
* Logitech WingMan Extreme Digital 3D

ADI devices are autodetected, and the driver supports up to two (any
combination of) devices on a single gameport, using a Y-cable or chained
together.

Logitech WingMan Joystick, Logitech WingMan Attack, Logitech WingMan
Extreme and Logitech WingMan ThunderPad are not digital joysticks and are
handled by the analog driver described above. Logitech WingMan Warrior and
Logitech Magellan are supported by serial drivers described below.  Logitech
WingMan Force and Logitech WingMan Formula Force are supported by the
I-Force driver described below. Logitech CyberMan is not supported yet.

Gravis GrIP
-----------

Gravis GrIP protocol is supported by the grip.c module. It currently
supports:

* Gravis GamePad Pro
* Gravis BlackHawk Digital
* Gravis Xterminator
* Gravis Xterminator DualControl

All these devices are autodetected, and you can even use any combination
of up to two of these pads either chained together or using a Y-cable on a
single gameport.

GrIP MultiPort isn't supported yet. Gravis Stinger is a serial device and is
supported by the stinger driver. Other Gravis joysticks are supported by the
analog driver.

FPGaming A3D and MadCatz A3D
----------------------------

The Assassin 3D protocol created by FPGaming, is used both by FPGaming
themselves and is licensed to MadCatz. A3D devices are supported by the
a3d.c module. It currently supports:

* FPGaming Assassin 3D
* MadCatz Panther
* MadCatz Panther XL

All these devices are autodetected. Because the Assassin 3D and the Panther
allow connecting analog joysticks to them, you'll need to load the analog
driver as well to handle the attached joysticks.

The trackball should work with USB mousedev module as a normal mouse. See
the USB documentation for how to setup a USB mouse.

ThrustMaster DirectConnect (BSP)
--------------------------------

The TM DirectConnect (BSP) protocol is supported by the tmdc.c
module. This includes, but is not limited to:

* ThrustMaster Millennium 3D Interceptor
* ThrustMaster 3D Rage Pad
* ThrustMaster Fusion Digital Game Pad

Devices not directly supported, but hopefully working are:

* ThrustMaster FragMaster
* ThrustMaster Attack Throttle

If you have one of these, contact me.

TMDC devices are autodetected, and thus no parameters to the module
are needed. Up to two TMDC devices can be connected to one gameport, using
a Y-cable.

Creative Labs Blaster
---------------------

The Blaster protocol is supported by the cobra.c module. It supports only
the:

* Creative Blaster GamePad Cobra

Up to two of these can be used on a single gameport, using a Y-cable.

Genius Digital joysticks
------------------------

The Genius digitally communicating joysticks are supported by the gf2k.c
module. This includes:

* Genius Flight2000 F-23 joystick
* Genius Flight2000 F-31 joystick
* Genius G-09D gamepad

Other Genius digital joysticks are not supported yet, but support can be
added fairly easily.

InterAct Digital joysticks
--------------------------

The InterAct digitally communicating joysticks are supported by the
interact.c module. This includes:

* InterAct HammerHead/FX gamepad
* InterAct ProPad8 gamepad

Other InterAct digital joysticks are not supported yet, but support can be
added fairly easily.

PDPI Lightning 4 gamecards
--------------------------

PDPI Lightning 4 gamecards are supported by the lightning.c module.
Once the module is loaded, the analog driver can be used to handle the
joysticks. Digitally communicating joystick will work only on port 0, while
using Y-cables, you can connect up to 8 analog joysticks to a single L4
card, 16 in case you have two in your system.

Trident 4DWave / Aureal Vortex
------------------------------

Soundcards with a Trident 4DWave DX/NX or Aureal Vortex/Vortex2 chipset
provide an "Enhanced Game Port" mode where the soundcard handles polling the
joystick.  This mode is supported by the pcigame.c module. Once loaded the
analog driver can use the enhanced features of these gameports..

Crystal SoundFusion
-------------------

Soundcards with Crystal SoundFusion chipsets provide an "Enhanced Game
Port", much like the 4DWave or Vortex above. This, and also the normal mode
for the port of the SoundFusion is supported by the cs461x.c module.

SoundBlaster Live!
------------------

The Live! has a special PCI gameport, which, although it doesn't provide
any "Enhanced" stuff like 4DWave and friends, is quite a bit faster than
its ISA counterparts. It also requires special support, hence the
emu10k1-gp.c module for it instead of the normal ns558.c one.

SoundBlaster 64 and 128 - ES1370 and ES1371, ESS Solo1 and S3 SonicVibes
------------------------------------------------------------------------

These PCI soundcards have specific gameports. They are handled by the
sound drivers themselves. Make sure you select gameport support in the
joystick menu and sound card support in the sound menu for your appropriate
card.

Amiga
-----

Amiga joysticks, connected to an Amiga, are supported by the amijoy.c
driver. Since they can't be autodetected, the driver has a command line:

	amijoy.map=<a>,<b>

a and b define the joysticks connected to the JOY0DAT and JOY1DAT ports of
the Amiga.

	====== ===========================
	Value  Joystick type
	====== ===========================
	  0    None
	  1    1-button digital joystick
	====== ===========================

No more joystick types are supported now, but that should change in the
future if I get an Amiga in the reach of my fingers.

Game console and 8-bit pads and joysticks
-----------------------------------------

These pads and joysticks are not designed for PCs and other computers
Linux runs on, and usually require a special connector for attaching
them through a parallel port.

See :ref:`joystick-parport` for more info.

SpaceTec/LabTec devices
-----------------------

SpaceTec serial devices communicate using the SpaceWare protocol. It is
supported by the spaceorb.c and spaceball.c drivers. The devices currently
supported by spaceorb.c are:

* SpaceTec SpaceBall Avenger
* SpaceTec SpaceOrb 360

Devices currently supported by spaceball.c are:

* SpaceTec SpaceBall 4000 FLX

In addition to having the spaceorb/spaceball and serport modules in the
kernel, you also need to attach a serial port to it. To do that, run the
inputattach program::

	inputattach --spaceorb /dev/tts/x &

or::

	inputattach --spaceball /dev/tts/x &

where /dev/tts/x is the serial port which the device is connected to. After
doing this, the device will be reported and will start working.

There is one caveat with the SpaceOrb. The button #6, the one on the bottom
side of the orb, although reported as an ordinary button, causes internal
recentering of the spaceorb, moving the zero point to the position in which
the ball is at the moment of pressing the button. So, think first before
you bind it to some other function.

SpaceTec SpaceBall 2003 FLX and 3003 FLX are not supported yet.

Logitech SWIFT devices
----------------------

The SWIFT serial protocol is supported by the warrior.c module. It
currently supports only the:

* Logitech WingMan Warrior

but in the future, Logitech CyberMan (the original one, not CM2) could be
supported as well. To use the module, you need to run inputattach after you
insert/compile the module into your kernel::

	inputattach --warrior /dev/tts/x &

/dev/tts/x is the serial port your Warrior is attached to.

Magellan / Space Mouse
----------------------

The Magellan (or Space Mouse), manufactured by LogiCad3d (formerly Space
Systems), for many other companies (Logitech, HP, ...) is supported by the
joy-magellan module. It currently supports only the:

* Magellan 3D
* Space Mouse

models; the additional buttons on the 'Plus' versions are not supported yet.

To use it, you need to attach the serial port to the driver using the::

	inputattach --magellan /dev/tts/x &

command. After that the Magellan will be detected, initialized, will beep,
and the /dev/input/jsX device should become usable.

I-Force devices
---------------

All I-Force devices are supported by the iforce module. This includes:

* AVB Mag Turbo Force
* AVB Top Shot Pegasus
* AVB Top Shot Force Feedback Racing Wheel
* Boeder Force Feedback Wheel
* Logitech WingMan Force
* Logitech WingMan Force Wheel
* Guillemot Race Leader Force Feedback
* Guillemot Force Feedback Racing Wheel
* Thrustmaster Motor Sport GT

To use it, you need to attach the serial port to the driver using the::

	inputattach --iforce /dev/tts/x &

command. After that the I-Force device will be detected, and the
/dev/input/jsX device should become usable.

In case you're using the device via the USB port, the inputattach command
isn't needed.

The I-Force driver now supports force feedback via the event interface.

Please note that Logitech WingMan 3D devices are _not_ supported by this
module, rather by hid. Force feedback is not supported for those devices.
Logitech gamepads are also hid devices.

Gravis Stinger gamepad
----------------------

The Gravis Stinger serial port gamepad, designed for use with laptop
computers, is supported by the stinger.c module. To use it, attach the
serial port to the driver using::

	inputattach --stinger /dev/tty/x &

where x is the number of the serial port.

Troubleshooting
===============

There is quite a high probability that you run into some problems. For
testing whether the driver works, if in doubt, use the jstest utility in
some of its modes. The most useful modes are "normal" - for the 1.x
interface, and "old" for the "0.x" interface. You run it by typing::

	jstest --normal /dev/input/js0
	jstest --old    /dev/input/js0

Additionally you can do a test with the evtest utility::

	evtest /dev/input/event0

Oh, and read the FAQ! :)

FAQ
===

:Q: Running 'jstest /dev/input/js0' results in "File not found" error. What's the
    cause?
:A: The device files don't exist. Create them (see section 2.2).

:Q: Is it possible to connect my old Atari/Commodore/Amiga/console joystick
    or pad that uses a 9-pin D-type Cannon connector to the serial port of my
    PC?
:A: Yes, it is possible, but it'll burn your serial port or the pad. It
    won't work, of course.

:Q: My joystick doesn't work with Quake / Quake 2. What's the cause?
:A: Quake / Quake 2 don't support joystick. Use joy2key to simulate keypresses
    for them.


code:
.. include:: <isonum.txt>

=========================
Multi-touch (MT) Protocol
=========================

:Copyright: |copy| 2009-2010	Henrik Rydberg <rydberg@euromail.se>

Introduction
------------

In order to utilize the full power of the new multi-touch and multi-user
devices, a way to report detailed data from multiple contacts, i.e.,
objects in direct contact with the device surface, is needed.  This
document describes the multi-touch (MT) protocol which allows kernel
drivers to report details for an arbitrary number of contacts.

The protocol is divided into two types, depending on the capabilities of the
hardware. For devices handling anonymous contacts (type A), the protocol
describes how to send the raw data for all contacts to the receiver. For
devices capable of tracking identifiable contacts (type B), the protocol
describes how to send updates for individual contacts via event slots.

.. note::
   MT protocol type A is obsolete, all kernel drivers have been
   converted to use type B.

Protocol Usage
--------------

Contact details are sent sequentially as separate packets of ABS_MT
events. Only the ABS_MT events are recognized as part of a contact
packet. Since these events are ignored by current single-touch (ST)
applications, the MT protocol can be implemented on top of the ST protocol
in an existing driver.

Drivers for type A devices separate contact packets by calling
input_mt_sync() at the end of each packet. This generates a SYN_MT_REPORT
event, which instructs the receiver to accept the data for the current
contact and prepare to receive another.

Drivers for type B devices separate contact packets by calling
input_mt_slot(), with a slot as argument, at the beginning of each packet.
This generates an ABS_MT_SLOT event, which instructs the receiver to
prepare for updates of the given slot.

All drivers mark the end of a multi-touch transfer by calling the usual
input_sync() function. This instructs the receiver to act upon events
accumulated since last EV_SYN/SYN_REPORT and prepare to receive a new set
of events/packets.

The main difference between the stateless type A protocol and the stateful
type B slot protocol lies in the usage of identifiable contacts to reduce
the amount of data sent to userspace. The slot protocol requires the use of
the ABS_MT_TRACKING_ID, either provided by the hardware or computed from
the raw data [#f5]_.

For type A devices, the kernel driver should generate an arbitrary
enumeration of the full set of anonymous contacts currently on the
surface. The order in which the packets appear in the event stream is not
important.  Event filtering and finger tracking is left to user space [#f3]_.

For type B devices, the kernel driver should associate a slot with each
identified contact, and use that slot to propagate changes for the contact.
Creation, replacement and destruction of contacts is achieved by modifying
the ABS_MT_TRACKING_ID of the associated slot.  A non-negative tracking id
is interpreted as a contact, and the value -1 denotes an unused slot.  A
tracking id not previously present is considered new, and a tracking id no
longer present is considered removed.  Since only changes are propagated,
the full state of each initiated contact has to reside in the receiving
end.  Upon receiving an MT event, one simply updates the appropriate
attribute of the current slot.

Some devices identify and/or track more contacts than they can report to the
driver.  A driver for such a device should associate one type B slot with each
contact that is reported by the hardware.  Whenever the identity of the
contact associated with a slot changes, the driver should invalidate that
slot by changing its ABS_MT_TRACKING_ID.  If the hardware signals that it is
tracking more contacts than it is currently reporting, the driver should use
a BTN_TOOL_*TAP event to inform userspace of the total number of contacts
being tracked by the hardware at that moment.  The driver should do this by
explicitly sending the corresponding BTN_TOOL_*TAP event and setting
use_count to false when calling input_mt_report_pointer_emulation().
The driver should only advertise as many slots as the hardware can report.
Userspace can detect that a driver can report more total contacts than slots
by noting that the largest supported BTN_TOOL_*TAP event is larger than the
total number of type B slots reported in the absinfo for the ABS_MT_SLOT axis.

The minimum value of the ABS_MT_SLOT axis must be 0.

Protocol Example A
------------------

Here is what a minimal event sequence for a two-contact touch would look
like for a type A device::

   ABS_MT_POSITION_X x[0]
   ABS_MT_POSITION_Y y[0]
   SYN_MT_REPORT
   ABS_MT_POSITION_X x[1]
   ABS_MT_POSITION_Y y[1]
   SYN_MT_REPORT
   SYN_REPORT

The sequence after moving one of the contacts looks exactly the same; the
raw data for all present contacts are sent between every synchronization
with SYN_REPORT.

Here is the sequence after lifting the first contact::

   ABS_MT_POSITION_X x[1]
   ABS_MT_POSITION_Y y[1]
   SYN_MT_REPORT
   SYN_REPORT

And here is the sequence after lifting the second contact::

   SYN_MT_REPORT
   SYN_REPORT

If the driver reports one of BTN_TOUCH or ABS_PRESSURE in addition to the
ABS_MT events, the last SYN_MT_REPORT event may be omitted. Otherwise, the
last SYN_REPORT will be dropped by the input core, resulting in no
zero-contact event reaching userland.

Protocol Example B
------------------

Here is what a minimal event sequence for a two-contact touch would look
like for a type B device::

   ABS_MT_SLOT 0
   ABS_MT_TRACKING_ID 45
   ABS_MT_POSITION_X x[0]
   ABS_MT_POSITION_Y y[0]
   ABS_MT_SLOT 1
   ABS_MT_TRACKING_ID 46
   ABS_MT_POSITION_X x[1]
   ABS_MT_POSITION_Y y[1]
   SYN_REPORT

Here is the sequence after moving contact 45 in the x direction::

   ABS_MT_SLOT 0
   ABS_MT_POSITION_X x[0]
   SYN_REPORT

Here is the sequence after lifting the contact in slot 0::

   ABS_MT_TRACKING_ID -1
   SYN_REPORT

The slot being modified is already 0, so the ABS_MT_SLOT is omitted.  The
message removes the association of slot 0 with contact 45, thereby
destroying contact 45 and freeing slot 0 to be reused for another contact.

Finally, here is the sequence after lifting the second contact::

   ABS_MT_SLOT 1
   ABS_MT_TRACKING_ID -1
   SYN_REPORT

Event Usage
-----------

A set of ABS_MT events with the desired properties is defined. The events
are divided into categories, to allow for partial implementation.  The
minimum set consists of ABS_MT_POSITION_X and ABS_MT_POSITION_Y, which
allows for multiple contacts to be tracked.  If the device supports it, the
ABS_MT_TOUCH_MAJOR and ABS_MT_WIDTH_MAJOR may be used to provide the size
of the contact area and approaching tool, respectively.

The TOUCH and WIDTH parameters have a geometrical interpretation; imagine
looking through a window at someone gently holding a finger against the
glass.  You will see two regions, one inner region consisting of the part
of the finger actually touching the glass, and one outer region formed by
the perimeter of the finger. The center of the touching region (a) is
ABS_MT_POSITION_X/Y and the center of the approaching finger (b) is
ABS_MT_TOOL_X/Y. The touch diameter is ABS_MT_TOUCH_MAJOR and the finger
diameter is ABS_MT_WIDTH_MAJOR. Now imagine the person pressing the finger
harder against the glass. The touch region will increase, and in general,
the ratio ABS_MT_TOUCH_MAJOR / ABS_MT_WIDTH_MAJOR, which is always smaller
than unity, is related to the contact pressure. For pressure-based devices,
ABS_MT_PRESSURE may be used to provide the pressure on the contact area
instead. Devices capable of contact hovering can use ABS_MT_DISTANCE to
indicate the distance between the contact and the surface.

::

	  Linux MT                               Win8
         __________                     _______________________
        /          \                   |                       |
       /            \                  |                       |
      /     ____     \                 |                       |
     /     /    \     \                |                       |
     \     \  a  \     \               |       a               |
      \     \____/      \              |                       |
       \                 \             |                       |
        \        b        \            |           b           |
         \                 \           |                       |
          \                 \          |                       |
           \                 \         |                       |
            \                /         |                       |
             \              /          |                       |
              \            /           |                       |
               \__________/            |_______________________|

In addition to the MAJOR parameters, the oval shape of the touch and finger
regions can be described by adding the MINOR parameters, such that MAJOR
and MINOR are the major and minor axis of an ellipse. The orientation of
the touch ellipse can be described with the ORIENTATION parameter, and the
direction of the finger ellipse is given by the vector (a - b).

For type A devices, further specification of the touch shape is possible
via ABS_MT_BLOB_ID.

The ABS_MT_TOOL_TYPE may be used to specify whether the touching tool is a
finger or a pen or something else. Finally, the ABS_MT_TRACKING_ID event
may be used to track identified contacts over time [#f5]_.

In the type B protocol, ABS_MT_TOOL_TYPE and ABS_MT_TRACKING_ID are
implicitly handled by input core; drivers should instead call
input_mt_report_slot_state().

Event Semantics
---------------

ABS_MT_TOUCH_MAJOR
    The length of the major axis of the contact. The length should be given in
    surface units. If the surface has an X times Y resolution, the largest
    possible value of ABS_MT_TOUCH_MAJOR is sqrt(X^2 + Y^2), the diagonal [#f4]_.

ABS_MT_TOUCH_MINOR
    The length, in surface units, of the minor axis of the contact. If the
    contact is circular, this event can be omitted [#f4]_.

ABS_MT_WIDTH_MAJOR
    The length, in surface units, of the major axis of the approaching
    tool. This should be understood as the size of the tool itself. The
    orientation of the contact and the approaching tool are assumed to be the
    same [#f4]_.

ABS_MT_WIDTH_MINOR
    The length, in surface units, of the minor axis of the approaching
    tool. Omit if circular [#f4]_.

    The above four values can be used to derive additional information about
    the contact. The ratio ABS_MT_TOUCH_MAJOR / ABS_MT_WIDTH_MAJOR approximates
    the notion of pressure. The fingers of the hand and the palm all have
    different characteristic widths.

ABS_MT_PRESSURE
    The pressure, in arbitrary units, on the contact area. May be used instead
    of TOUCH and WIDTH for pressure-based devices or any device with a spatial
    signal intensity distribution.

    If the resolution is zero, the pressure data is in arbitrary units.
    If the resolution is non-zero, the pressure data is in units/gram. See
    :ref:`input-event-codes` for details.

ABS_MT_DISTANCE
    The distance, in surface units, between the contact and the surface. Zero
    distance means the contact is touching the surface. A positive number means
    the contact is hovering above the surface.

ABS_MT_ORIENTATION
    The orientation of the touching ellipse. The value should describe a signed
    quarter of a revolution clockwise around the touch center. The signed value
    range is arbitrary, but zero should be returned for an ellipse aligned with
    the Y axis (north) of the surface, a negative value when the ellipse is
    turned to the left, and a positive value when the ellipse is turned to the
    right. When aligned with the X axis in the positive direction, the range
    max should be returned; when aligned with the X axis in the negative
    direction, the range -max should be returned.

    Touch ellipses are symmetrical by default. For devices capable of true 360
    degree orientation, the reported orientation must exceed the range max to
    indicate more than a quarter of a revolution. For an upside-down finger,
    range max * 2 should be returned.

    Orientation can be omitted if the touch area is circular, or if the
    information is not available in the kernel driver. Partial orientation
    support is possible if the device can distinguish between the two axes, but
    not (uniquely) any values in between. In such cases, the range of
    ABS_MT_ORIENTATION should be [0, 1] [#f4]_.

ABS_MT_POSITION_X
    The surface X coordinate of the center of the touching ellipse.

ABS_MT_POSITION_Y
    The surface Y coordinate of the center of the touching ellipse.

ABS_MT_TOOL_X
    The surface X coordinate of the center of the approaching tool. Omit if
    the device cannot distinguish between the intended touch point and the
    tool itself.

ABS_MT_TOOL_Y
    The surface Y coordinate of the center of the approaching tool. Omit if the
    device cannot distinguish between the intended touch point and the tool
    itself.

    The four position values can be used to separate the position of the touch
    from the position of the tool. If both positions are present, the major
    tool axis points towards the touch point [#f1]_. Otherwise, the tool axes are
    aligned with the touch axes.

ABS_MT_TOOL_TYPE
    The type of approaching tool. A lot of kernel drivers cannot distinguish
    between different tool types, such as a finger or a pen. In such cases, the
    event should be omitted. The protocol currently mainly supports
    MT_TOOL_FINGER, MT_TOOL_PEN, and MT_TOOL_PALM [#f2]_.
    For type B devices, this event is handled by input core; drivers should
    instead use input_mt_report_slot_state(). A contact's ABS_MT_TOOL_TYPE may
    change over time while still touching the device, because the firmware may
    not be able to determine which tool is being used when it first appears.

ABS_MT_BLOB_ID
    The BLOB_ID groups several packets together into one arbitrarily shaped
    contact. The sequence of points forms a polygon which defines the shape of
    the contact. This is a low-level anonymous grouping for type A devices, and
    should not be confused with the high-level trackingID [#f5]_. Most type A
    devices do not have blob capability, so drivers can safely omit this event.

ABS_MT_TRACKING_ID
    The TRACKING_ID identifies an initiated contact throughout its life cycle
    [#f5]_. The value range of the TRACKING_ID should be large enough to ensure
    unique identification of a contact maintained over an extended period of
    time. For type B devices, this event is handled by input core; drivers
    should instead use input_mt_report_slot_state().

Event Computation
-----------------

The flora of different hardware unavoidably leads to some devices fitting
better to the MT protocol than others. To simplify and unify the mapping,
this section gives recipes for how to compute certain events.

For devices reporting contacts as rectangular shapes, signed orientation
cannot be obtained. Assuming X and Y are the lengths of the sides of the
touching rectangle, here is a simple formula that retains the most
information possible::

   ABS_MT_TOUCH_MAJOR := max(X, Y)
   ABS_MT_TOUCH_MINOR := min(X, Y)
   ABS_MT_ORIENTATION := bool(X > Y)

The range of ABS_MT_ORIENTATION should be set to [0, 1], to indicate that
the device can distinguish between a finger along the Y axis (0) and a
finger along the X axis (1).

For Win8 devices with both T and C coordinates, the position mapping is::

   ABS_MT_POSITION_X := T_X
   ABS_MT_POSITION_Y := T_Y
   ABS_MT_TOOL_X := C_X
   ABS_MT_TOOL_Y := C_Y

Unfortunately, there is not enough information to specify both the touching
ellipse and the tool ellipse, so one has to resort to approximations.  One
simple scheme, which is compatible with earlier usage, is::

   ABS_MT_TOUCH_MAJOR := min(X, Y)
   ABS_MT_TOUCH_MINOR := <not used>
   ABS_MT_ORIENTATION := <not used>
   ABS_MT_WIDTH_MAJOR := min(X, Y) + distance(T, C)
   ABS_MT_WIDTH_MINOR := min(X, Y)

Rationale: We have no information about the orientation of the touching
ellipse, so approximate it with an inscribed circle instead. The tool
ellipse should align with the vector (T - C), so the diameter must
increase with distance(T, C). Finally, assume that the touch diameter is
equal to the tool thickness, and we arrive at the formulas above.

Finger Tracking
---------------

The process of finger tracking, i.e., to assign a unique trackingID to each
initiated contact on the surface, is a Euclidian Bipartite Matching
problem.  At each event synchronization, the set of actual contacts is
matched to the set of contacts from the previous synchronization. A full
implementation can be found in [#f3]_.

Gestures
--------

In the specific application of creating gesture events, the TOUCH and WIDTH
parameters can be used to, e.g., approximate finger pressure or distinguish
between index finger and thumb. With the addition of the MINOR parameters,
one can also distinguish between a sweeping finger and a pointing finger,
and with ORIENTATION, one can detect twisting of fingers.

Notes
-----

In order to stay compatible with existing applications, the data reported
in a finger packet must not be recognized as single-touch events.

For type A devices, all finger data bypasses input filtering, since
subsequent events of the same type refer to different fingers.

.. [#f1] Also, the difference (TOOL_X - POSITION_X) can be used to model tilt.
.. [#f2] The list can of course be extended.
.. [#f3] The mtdev project: http://bitmath.org/code/mtdev/.
.. [#f4] See the section on event computation.
.. [#f5] See the section on finger tracking.


code:
=================
Keyboard notifier
=================

One can use register_keyboard_notifier to get called back on keyboard
events (see kbd_keycode() function for details).  The passed structure is
keyboard_notifier_param (see <linux/keyboard.h>):

- 'vc' always provide the VC for which the keyboard event applies;
- 'down' is 1 for a key press event, 0 for a key release;
- 'shift' is the current modifier state, mask bit indexes are KG_*;
- 'ledstate' is the current LED state;
- 'value' depends on the type of event.

- KBD_KEYCODE events are always sent before other events, value is the keycode.
- KBD_UNBOUND_KEYCODE events are sent if the keycode is not bound to a keysym.
  value is the keycode.
- KBD_UNICODE events are sent if the keycode -> keysym translation produced a
  unicode character. value is the unicode value.
- KBD_KEYSYM events are sent if the keycode -> keysym translation produced a
  non-unicode character. value is the keysym.
- KBD_POST_KEYSYM events are sent after the treatment of non-unicode keysyms.
  That permits one to inspect the resulting LEDs for instance.

For each kind of event but the last, the callback may return NOTIFY_STOP in
order to "eat" the event: the notify loop is stopped and the keyboard event is
dropped.

In a rough C snippet, we have::

    kbd_keycode(keycode) {
	...
	params.value = keycode;
	if (notifier_call_chain(KBD_KEYCODE,&params) == NOTIFY_STOP)
	    || !bound) {
		notifier_call_chain(KBD_UNBOUND_KEYCODE,&params);
		return;
	}

	if (unicode) {
		param.value = unicode;
		if (notifier_call_chain(KBD_UNICODE,&params) == NOTIFY_STOP)
			return;
		emit unicode;
		return;
	}

	params.value = keysym;
	if (notifier_call_chain(KBD_KEYSYM,&params) == NOTIFY_STOP)
		return;
	apply keysym;
	notifier_call_chain(KBD_POST_KEYSYM,&params);
    }

.. note:: This notifier is usually called from interrupt context.


code:
<svg width="7.95in" height="3.70in" version="1.1" viewBox="1956 1041 9354.492 4306.001" xmlns="http://www.w3.org/2000/svg">
 <polyline transform="translate(-121.88 -68.4)" points="4200 3600 4200 3075 4950 2325 7425 2325 8250 3150 8250 3600" fill="none" stroke="#000" stroke-width="15"/>
 <polyline transform="translate(-121.88 -68.4)" points="4200 3675 4200 5400" fill="none" stroke="#000" stroke-dasharray="40, 40" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="8250 3675 8250 5400" fill="none" stroke="#000" stroke-dasharray="40, 40" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="3675 3600 8700 3600" fill="none" stroke="#000" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="8775 3600 10200 3600" fill="none" stroke="#000" stroke-dasharray="40, 40" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="8325 3150 9075 3150" fill="none" stroke="#000" stroke-dasharray="40, 40" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="7500 2325 10200 2325" fill="none" stroke="#000" stroke-dasharray="40, 40" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="3600 3600 3e3 3600" fill="none" stroke="#000" stroke-dasharray="40, 40" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="4125 3075 3e3 3075" fill="none" stroke="#000" stroke-dasharray="40, 40" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="4217 5400 8158 5400" fill="none" stroke="#000" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="8053 5430 8173 5400 8053 5370" fill="none" stroke="#000" stroke-miterlimit="8" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="4322 5370 4202 5400 4322 5430" fill="none" stroke="#000" stroke-miterlimit="8" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="10125 2342 10125 3583" fill="none" stroke="#000" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="10095 3478 10125 3598 10155 3478" fill="none" stroke="#000" stroke-miterlimit="8" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="10155 2447 10125 2327 10095 2447" fill="none" stroke="#000" stroke-miterlimit="8" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="3e3 3167 3e3 3583" fill="none" stroke="#000" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="2970 3478 3e3 3598 3030 3478" fill="none" stroke="#000" stroke-miterlimit="8" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="3030 3272 3e3 3152 2970 3272" fill="none" stroke="#000" stroke-miterlimit="8" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="9075 3167 9075 3583" fill="none" stroke="#000" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="9045 3478 9075 3598 9105 3478" fill="none" stroke="#000" stroke-miterlimit="8" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="9105 3272 9075 3152 9045 3272" fill="none" stroke="#000" stroke-miterlimit="8" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="4950 2325 4950 1200" fill="none" stroke="#000" stroke-dasharray="40, 40" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="7425 2325 7425 1200" fill="none" stroke="#000" stroke-dasharray="40, 40" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="4200 3075 4200 2400 3600 1800 3600 1200" fill="none" stroke="#000" stroke-dasharray="40, 40" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="8250 3150 8250 2475 8775 1950 8775 1200" fill="none" stroke="#000" stroke-dasharray="40, 40" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="3617 1275 4933 1275" fill="none" stroke="#000" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="4828 1305 4948 1275 4828 1245" fill="none" stroke="#000" stroke-miterlimit="8" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="3722 1245 3602 1275 3722 1305" fill="none" stroke="#000" stroke-miterlimit="8" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="7442 1275 8683 1275" fill="none" stroke="#000" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="8578 1305 8698 1275 8578 1245" fill="none" stroke="#000" stroke-miterlimit="8" stroke-width="7"/>
 <polyline transform="translate(-121.88 -68.4)" points="7547 1245 7427 1275 7547 1305" fill="none" stroke="#000" stroke-miterlimit="8" stroke-width="7"/>
 <text x="5953.125" y="5256.6001" fill="#000000" font-family="sans-serif" font-size="144px" stroke-width=".025in" text-anchor="middle" xml:space="preserve">Effect duration</text>
 <text x="10078.125" y="2931.5999" fill="#000000" font-family="sans-serif" font-size="144px" stroke-width=".025in" xml:space="preserve">Effect magnitude</text>
 <text x="9028.125" y="3381.5999" fill="#000000" font-family="sans-serif" font-size="144px" stroke-width=".025in" xml:space="preserve">Fade level</text>
 <text x="4153.125" y="1131.6" fill="#000000" font-family="sans-serif" font-size="144px" stroke-width=".025in" text-anchor="middle" xml:space="preserve">Attack length</text>
 <text x="8053.125" y="1131.6" fill="#000000" font-family="sans-serif" font-size="144px" stroke-width=".025in" text-anchor="middle" xml:space="preserve">Fade length</text>
 <text x="2803.125" y="3306.5999" fill="#000000" font-family="sans-serif" font-size="144px" stroke-width=".025in" text-anchor="end" xml:space="preserve">Attack level</text>
</svg>


code:
=============
uinput module
=============

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

uinput is a kernel module that makes it possible to emulate input devices
from userspace. By writing to /dev/uinput (or /dev/input/uinput) device, a
process can create a virtual input device with specific capabilities. Once
this virtual device is created, the process can send events through it,
that will be delivered to userspace and in-kernel consumers.

Interface
=========

::

  linux/uinput.h

The uinput header defines ioctls to create, set up, and destroy virtual
devices.

libevdev
========

libevdev is a wrapper library for evdev devices that provides interfaces to
create uinput devices and send events. libevdev is less error-prone than
accessing uinput directly, and should be considered for new software.

For examples and more information about libevdev:
https://www.freedesktop.org/software/libevdev/doc/latest/

Examples
========

Keyboard events
---------------

This first example shows how to create a new virtual device, and how to
send a key event. All default imports and error handlers were removed for
the sake of simplicity.

.. code-block:: c

   #include <linux/uinput.h>

   void emit(int fd, int type, int code, int val)
   {
      struct input_event ie;

      ie.type = type;
      ie.code = code;
      ie.value = val;
      /* timestamp values below are ignored */
      ie.time.tv_sec = 0;
      ie.time.tv_usec = 0;

      write(fd, &ie, sizeof(ie));
   }

   int main(void)
   {
      struct uinput_setup usetup;

      int fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);

      /*
       * The ioctls below will enable the device that is about to be
       * created, to pass key events, in this case the space key.
       */
      ioctl(fd, UI_SET_EVBIT, EV_KEY);
      ioctl(fd, UI_SET_KEYBIT, KEY_SPACE);

      memset(&usetup, 0, sizeof(usetup));
      usetup.id.bustype = BUS_USB;
      usetup.id.vendor = 0x1234; /* sample vendor */
      usetup.id.product = 0x5678; /* sample product */
      strcpy(usetup.name, "Example device");

      ioctl(fd, UI_DEV_SETUP, &usetup);
      ioctl(fd, UI_DEV_CREATE);

      /*
       * On UI_DEV_CREATE the kernel will create the device node for this
       * device. We are inserting a pause here so that userspace has time
       * to detect, initialize the new device, and can start listening to
       * the event, otherwise it will not notice the event we are about
       * to send. This pause is only needed in our example code!
       */
      sleep(1);

      /* Key press, report the event, send key release, and report again */
      emit(fd, EV_KEY, KEY_SPACE, 1);
      emit(fd, EV_SYN, SYN_REPORT, 0);
      emit(fd, EV_KEY, KEY_SPACE, 0);
      emit(fd, EV_SYN, SYN_REPORT, 0);

      /*
       * Give userspace some time to read the events before we destroy the
       * device with UI_DEV_DESTROY.
       */
      sleep(1);

      ioctl(fd, UI_DEV_DESTROY);
      close(fd);

      return 0;
   }

Mouse movements
---------------

This example shows how to create a virtual device that behaves like a physical
mouse.

.. code-block:: c

   #include <linux/uinput.h>

   /* emit function is identical to of the first example */

   int main(void)
   {
      struct uinput_setup usetup;
      int i = 50;

      int fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);

      /* enable mouse button left and relative events */
      ioctl(fd, UI_SET_EVBIT, EV_KEY);
      ioctl(fd, UI_SET_KEYBIT, BTN_LEFT);

      ioctl(fd, UI_SET_EVBIT, EV_REL);
      ioctl(fd, UI_SET_RELBIT, REL_X);
      ioctl(fd, UI_SET_RELBIT, REL_Y);

      memset(&usetup, 0, sizeof(usetup));
      usetup.id.bustype = BUS_USB;
      usetup.id.vendor = 0x1234; /* sample vendor */
      usetup.id.product = 0x5678; /* sample product */
      strcpy(usetup.name, "Example device");

      ioctl(fd, UI_DEV_SETUP, &usetup);
      ioctl(fd, UI_DEV_CREATE);

      /*
       * On UI_DEV_CREATE the kernel will create the device node for this
       * device. We are inserting a pause here so that userspace has time
       * to detect, initialize the new device, and can start listening to
       * the event, otherwise it will not notice the event we are about
       * to send. This pause is only needed in our example code!
       */
      sleep(1);

      /* Move the mouse diagonally, 5 units per axis */
      while (i--) {
         emit(fd, EV_REL, REL_X, 5);
         emit(fd, EV_REL, REL_Y, 5);
         emit(fd, EV_SYN, SYN_REPORT, 0);
         usleep(15000);
      }

      /*
       * Give userspace some time to read the events before we destroy the
       * device with UI_DEV_DESTROY.
       */
      sleep(1);

      ioctl(fd, UI_DEV_DESTROY);
      close(fd);

      return 0;
   }

uinput old interface
--------------------

Before uinput version 5, there wasn't a dedicated ioctl to set up a virtual
device. Programs supporting older versions of uinput interface need to fill
a uinput_user_dev structure and write it to the uinput file descriptor to
configure the new uinput device. New code should not use the old interface
but interact with uinput via ioctl calls, or use libevdev.

.. code-block:: c

   #include <linux/uinput.h>

   /* emit function is identical to of the first example */

   int main(void)
   {
      struct uinput_user_dev uud;
      int version, rc, fd;

      fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
      rc = ioctl(fd, UI_GET_VERSION, &version);

      if (rc == 0 && version >= 5) {
         /* use UI_DEV_SETUP */
         return 0;
      }

      /*
       * The ioctls below will enable the device that is about to be
       * created, to pass key events, in this case the space key.
       */
      ioctl(fd, UI_SET_EVBIT, EV_KEY);
      ioctl(fd, UI_SET_KEYBIT, KEY_SPACE);

      memset(&uud, 0, sizeof(uud));
      snprintf(uud.name, UINPUT_MAX_NAME_SIZE, "uinput old interface");
      write(fd, &uud, sizeof(uud));

      ioctl(fd, UI_DEV_CREATE);

      /*
       * On UI_DEV_CREATE the kernel will create the device node for this
       * device. We are inserting a pause here so that userspace has time
       * to detect, initialize the new device, and can start listening to
       * the event, otherwise it will not notice the event we are about
       * to send. This pause is only needed in our example code!
       */
      sleep(1);

      /* Key press, report the event, send key release, and report again */
      emit(fd, EV_KEY, KEY_SPACE, 1);
      emit(fd, EV_SYN, SYN_REPORT, 0);
      emit(fd, EV_KEY, KEY_SPACE, 0);
      emit(fd, EV_SYN, SYN_REPORT, 0);

      /*
       * Give userspace some time to read the events before we destroy the
       * device with UI_DEV_DESTROY.
       */
      sleep(1);

      ioctl(fd, UI_DEV_DESTROY);

      close(fd);
      return 0;
   }


code:
.. include:: <isonum.txt>

===================
The userio Protocol
===================

:Copyright: |copy| 2015 Stephen Chandler Paul <thatslyude@gmail.com>

Sponsored by Red Hat

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

This module is intended to try to make the lives of input driver developers
easier by allowing them to test various serio devices (mainly the various
touchpads found on laptops) without having to have the physical device in front
of them. userio accomplishes this by allowing any privileged userspace program
to directly interact with the kernel's serio driver and control a virtual serio
port from there.

Usage overview
==============

In order to interact with the userio kernel module, one simply opens the
/dev/userio character device in their applications. Commands are sent to the
kernel module by writing to the device, and any data received from the serio
driver is read as-is from the /dev/userio device. All of the structures and
macros you need to interact with the device are defined in <linux/userio.h> and
<linux/serio.h>.

Command Structure
=================

The struct used for sending commands to /dev/userio is as follows::

	struct userio_cmd {
		__u8 type;
		__u8 data;
	};

``type`` describes the type of command that is being sent. This can be any one
of the USERIO_CMD macros defined in <linux/userio.h>. ``data`` is the argument
that goes along with the command. In the event that the command doesn't have an
argument, this field can be left untouched and will be ignored by the kernel.
Each command should be sent by writing the struct directly to the character
device. In the event that the command you send is invalid, an error will be
returned by the character device and a more descriptive error will be printed
to the kernel log. Only one command can be sent at a time, any additional data
written to the character device after the initial command will be ignored.

To close the virtual serio port, just close /dev/userio.

Commands
========

USERIO_CMD_REGISTER
~~~~~~~~~~~~~~~~~~~

Registers the port with the serio driver and begins transmitting data back and
forth. Registration can only be performed once a port type is set with
USERIO_CMD_SET_PORT_TYPE. Has no argument.

USERIO_CMD_SET_PORT_TYPE
~~~~~~~~~~~~~~~~~~~~~~~~

Sets the type of port we're emulating, where ``data`` is the port type being
set. Can be any of the macros from <linux/serio.h>. For example: SERIO_8042
would set the port type to be a normal PS/2 port.

USERIO_CMD_SEND_INTERRUPT
~~~~~~~~~~~~~~~~~~~~~~~~~

Sends an interrupt through the virtual serio port to the serio driver, where
``data`` is the interrupt data being sent.

Userspace tools
===============

The userio userspace tools are able to record PS/2 devices using some of the
debugging information from i8042, and play back the devices on /dev/userio. The
latest version of these tools can be found at:

	https://github.com/Lyude/ps2emu


code:
=======
Credits
=======

I want to thank all who contributed to this project and especially to:
(in alphabetical order)

Thomas Bogendörfer (tsbogend@bigbug.franken.de)
  Tester, lots of bugfixes and hints.

Alan Cox (alan@lxorguk.ukuu.org.uk)
  For help getting into standard-kernel.

Henner Eisen (eis@baty.hanse.de)
  For X.25 implementation.

Volker Götz (volker@oops.franken.de)
  For contribution of man-pages, the imontty-tool and a perfect
  maintaining of the mailing-list at hub-wue.

Matthias Hessler (hessler@isdn4linux.de)
  For creating and maintaining the FAQ.

Bernhard Hailer (Bernhard.Hailer@lrz.uni-muenchen.de)
  For creating the FAQ, and the leafsite HOWTO.

Michael 'Ghandi' Herold (michael@abadonna.franken.de)
  For contribution of the vbox answering machine.

Michael Hipp (Michael.Hipp@student.uni-tuebingen.de)
  For his Sync-PPP-code.

Karsten Keil (keil@isdn4linux.de)
  For adding 1TR6-support to the Teles-driver.
  For the HiSax-driver.

Michael Knigge (knick@cove.han.de)
  For contributing the imon-tool

Andreas Kool (akool@Kool.f.EUnet.de)
  For contribution of the isdnlog/isdnrep-tool

Pedro Roque Marques (roque@di.fc.ul.pt)
  For lot of new ideas and the pcbit driver.

Eberhard Mönkeberg (emoenke@gwdg.de)
  For testing and help to get into kernel.

Thomas Neumann (tn@ruhr.de)
  For help with Cisco-SLARP and keepalive

Jan den Ouden (denouden@groovin.xs4all.nl)
  For contribution of the original teles-driver

Carsten Paeth (calle@calle.in-berlin.de)
  For the AVM-B1-CAPI2.0 driver

Thomas Pfeiffer (pfeiffer@pds.de)
  For V.110, extended T.70 and Hylafax extensions in isdn_tty.c

Max Riegel (riegel@max.franken.de)
  For making the ICN hardware-documentation and test-equipment available.

Armin Schindler (mac@melware.de)
  For the eicon active card driver.

Gerhard 'Fido' Schneider (fido@wuff.mayn.de)
  For heavy-duty-beta-testing with his BBS ;)

Thomas Uhl (uhl@think.de)
  For distributing the cards.
  For pushing me to work ;-)


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

====
ISDN
====

.. toctree::
   :maxdepth: 2

   interface_capi

   m_isdn

   credits

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`