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

====================================
Netfilter's flowtable infrastructure
====================================

This documentation describes the Netfilter flowtable infrastructure which allows
you to define a fastpath through the flowtable datapath. This infrastructure
also provides hardware offload support. The flowtable supports for the layer 3
IPv4 and IPv6 and the layer 4 TCP and UDP protocols.

Overview
--------

Once the first packet of the flow successfully goes through the IP forwarding
path, from the second packet on, you might decide to offload the flow to the
flowtable through your ruleset. The flowtable infrastructure provides a rule
action that allows you to specify when to add a flow to the flowtable.

A packet that finds a matching entry in the flowtable (ie. flowtable hit) is
transmitted to the output netdevice via neigh_xmit(), hence, packets bypass the
classic IP forwarding path (the visible effect is that you do not see these
packets from any of the Netfilter hooks coming after ingress). In case that
there is no matching entry in the flowtable (ie. flowtable miss), the packet
follows the classic IP forwarding path.

The flowtable uses a resizable hashtable. Lookups are based on the following
n-tuple selectors: layer 2 protocol encapsulation (VLAN and PPPoE), layer 3
source and destination, layer 4 source and destination ports and the input
interface (useful in case there are several conntrack zones in place).

The 'flow add' action allows you to populate the flowtable, the user selectively
specifies what flows are placed into the flowtable. Hence, packets follow the
classic IP forwarding path unless the user explicitly instruct flows to use this
new alternative forwarding path via policy.

The flowtable datapath is represented in Fig.1, which describes the classic IP
forwarding path including the Netfilter hooks and the flowtable fastpath bypass.

::

					 userspace process
					  ^              |
					  |              |
				     _____|____     ____\/___
				    /          \   /         \
				    |   input   |  |  output  |
				    \__________/   \_________/
					 ^               |
					 |               |
      _________      __________      ---------     _____\/_____
     /         \    /          \     |Routing |   /            \
  -->  ingress  ---> prerouting ---> |decision|   | postrouting |--> neigh_xmit
     \_________/    \__________/     ----------   \____________/          ^
       |      ^                          |               ^                |
   flowtable  |                     ____\/___            |                |
       |      |                    /         \           |                |
    __\/___   |                    | forward |------------                |
    |-----|   |                    \_________/                            |
    |-----|   |                 'flow offload' rule                       |
    |-----|   |                   adds entry to                           |
    |_____|   |                     flowtable                             |
       |      |                                                           |
      / \     |                                                           |
     /hit\_no_|                                                           |
     \ ? /                                                                |
      \ /                                                                 |
       |__yes_________________fastpath bypass ____________________________|

	       Fig.1 Netfilter hooks and flowtable interactions

The flowtable entry also stores the NAT configuration, so all packets are
mangled according to the NAT policy that is specified from the classic IP
forwarding path. The TTL is decremented before calling neigh_xmit(). Fragmented
traffic is passed up to follow the classic IP forwarding path given that the
transport header is missing, in this case, flowtable lookups are not possible.
TCP RST and FIN packets are also passed up to the classic IP forwarding path to
release the flow gracefully. Packets that exceed the MTU are also passed up to
the classic forwarding path to report packet-too-big ICMP errors to the sender.

Example configuration
---------------------

Enabling the flowtable bypass is relatively easy, you only need to create a
flowtable and add one rule to your forward chain::

	table inet x {
		flowtable f {
			hook ingress priority 0; devices = { eth0, eth1 };
		}
		chain y {
			type filter hook forward priority 0; policy accept;
			ip protocol tcp flow add @f
			counter packets 0 bytes 0
		}
	}

This example adds the flowtable 'f' to the ingress hook of the eth0 and eth1
netdevices. You can create as many flowtables as you want in case you need to
perform resource partitioning. The flowtable priority defines the order in which
hooks are run in the pipeline, this is convenient in case you already have a
nftables ingress chain (make sure the flowtable priority is smaller than the
nftables ingress chain hence the flowtable runs before in the pipeline).

The 'flow offload' action from the forward chain 'y' adds an entry to the
flowtable for the TCP syn-ack packet coming in the reply direction. Once the
flow is offloaded, you will observe that the counter rule in the example above
does not get updated for the packets that are being forwarded through the
forwarding bypass.

You can identify offloaded flows through the [OFFLOAD] tag when listing your
connection tracking table.

::

	# conntrack -L
	tcp      6 src=10.141.10.2 dst=192.168.10.2 sport=52728 dport=5201 src=192.168.10.2 dst=192.168.10.1 sport=5201 dport=52728 [OFFLOAD] mark=0 use=2

Layer 2 encapsulation
---------------------

Since Linux kernel 5.13, the flowtable infrastructure discovers the real
netdevice behind VLAN and PPPoE netdevices. The flowtable software datapath
parses the VLAN and PPPoE layer 2 headers to extract the ethertype and the
VLAN ID / PPPoE session ID which are used for the flowtable lookups. The
flowtable datapath also deals with layer 2 decapsulation.

You do not need to add the PPPoE and the VLAN devices to your flowtable,
instead the real device is sufficient for the flowtable to track your flows.

Bridge and IP forwarding
------------------------

Since Linux kernel 5.13, you can add bridge ports to the flowtable. The
flowtable infrastructure discovers the topology behind the bridge device. This
allows the flowtable to define a fastpath bypass between the bridge ports
(represented as eth1 and eth2 in the example figure below) and the gateway
device (represented as eth0) in your switch/router.

::

                      fastpath bypass
               .-------------------------.
              /                           \
              |           IP forwarding   |
              |          /             \ \/
              |       br0               eth0 ..... eth0
              .       / \                          *host B*
               -> eth1  eth2
                   .           *switch/router*
                   .
                   .
                 eth0
               *host A*

The flowtable infrastructure also supports for bridge VLAN filtering actions
such as PVID and untagged. You can also stack a classic VLAN device on top of
your bridge port.

If you would like that your flowtable defines a fastpath between your bridge
ports and your IP forwarding path, you have to add your bridge ports (as
represented by the real netdevice) to your flowtable definition.

Counters
--------

The flowtable can synchronize packet and byte counters with the existing
connection tracking entry by specifying the counter statement in your flowtable
definition, e.g.

::

	table inet x {
		flowtable f {
			hook ingress priority 0; devices = { eth0, eth1 };
			counter
		}
	}

Counter support is available since Linux kernel 5.7.

Hardware offload
----------------

If your network device provides hardware offload support, you can turn it on by
means of the 'offload' flag in your flowtable definition, e.g.

::

	table inet x {
		flowtable f {
			hook ingress priority 0; devices = { eth0, eth1 };
			flags offload;
		}
	}

There is a workqueue that adds the flows to the hardware. Note that a few
packets might still run over the flowtable software path until the workqueue has
a chance to offload the flow to the network device.

You can identify hardware offloaded flows through the [HW_OFFLOAD] tag when
listing your connection tracking table. Please, note that the [OFFLOAD] tag
refers to the software offload mode, so there is a distinction between [OFFLOAD]
which refers to the software flowtable fastpath and [HW_OFFLOAD] which refers
to the hardware offload datapath being used by the flow.

The flowtable hardware offload infrastructure also supports for the DSA
(Distributed Switch Architecture).

Limitations
-----------

The flowtable behaves like a cache. The flowtable entries might get stale if
either the destination MAC address or the egress netdevice that is used for
transmission changes.

This might be a problem if:

- You run the flowtable in software mode and you combine bridge and IP
  forwarding in your setup.
- Hardware offload is enabled.

More reading
------------

This documentation is based on the LWN.net articles [1]_\ [2]_. Rafal Milecki
also made a very complete and comprehensive summary called "A state of network
acceleration" that describes how things were before this infrastructure was
mainlined [3]_ and it also makes a rough summary of this work [4]_.

.. [1] https://lwn.net/Articles/738214/
.. [2] https://lwn.net/Articles/742164/
.. [3] http://lists.infradead.org/pipermail/lede-dev/2018-January/010830.html
.. [4] http://lists.infradead.org/pipermail/lede-dev/2018-January/010829.html


code:
===================
Linux NFC subsystem
===================

The Near Field Communication (NFC) subsystem is required to standardize the
NFC device drivers development and to create an unified userspace interface.

This document covers the architecture overview, the device driver interface
description and the userspace interface description.

Architecture overview
=====================

The NFC subsystem is responsible for:
      - NFC adapters management;
      - Polling for targets;
      - Low-level data exchange;

The subsystem is divided in some parts. The 'core' is responsible for
providing the device driver interface. On the other side, it is also
responsible for providing an interface to control operations and low-level
data exchange.

The control operations are available to userspace via generic netlink.

The low-level data exchange interface is provided by the new socket family
PF_NFC. The NFC_SOCKPROTO_RAW performs raw communication with NFC targets.

.. code-block:: none

        +--------------------------------------+
        |              USER SPACE              |
        +--------------------------------------+
            ^                       ^
            | low-level             | control
            | data exchange         | operations
            |                       |
            |                       v
            |                  +-----------+
            | AF_NFC           |  netlink  |
            | socket           +-----------+
            | raw                   ^
            |                       |
            v                       v
        +---------+            +-----------+
        | rawsock | <--------> |   core    |
        +---------+            +-----------+
                                    ^
                                    |
                                    v
                               +-----------+
                               |  driver   |
                               +-----------+

Device Driver Interface
=======================

When registering on the NFC subsystem, the device driver must inform the core
of the set of supported NFC protocols and the set of ops callbacks. The ops
callbacks that must be implemented are the following:

* start_poll - setup the device to poll for targets
* stop_poll - stop on progress polling operation
* activate_target - select and initialize one of the targets found
* deactivate_target - deselect and deinitialize the selected target
* data_exchange - send data and receive the response (transceive operation)

Userspace interface
===================

The userspace interface is divided in control operations and low-level data
exchange operation.

CONTROL OPERATIONS:

Generic netlink is used to implement the interface to the control operations.
The operations are composed by commands and events, all listed below:

* NFC_CMD_GET_DEVICE - get specific device info or dump the device list
* NFC_CMD_START_POLL - setup a specific device to polling for targets
* NFC_CMD_STOP_POLL - stop the polling operation in a specific device
* NFC_CMD_GET_TARGET - dump the list of targets found by a specific device

* NFC_EVENT_DEVICE_ADDED - reports an NFC device addition
* NFC_EVENT_DEVICE_REMOVED - reports an NFC device removal
* NFC_EVENT_TARGETS_FOUND - reports START_POLL results when 1 or more targets
  are found

The user must call START_POLL to poll for NFC targets, passing the desired NFC
protocols through NFC_ATTR_PROTOCOLS attribute. The device remains in polling
state until it finds any target. However, the user can stop the polling
operation by calling STOP_POLL command. In this case, it will be checked if
the requester of STOP_POLL is the same of START_POLL.

If the polling operation finds one or more targets, the event TARGETS_FOUND is
sent (including the device id). The user must call GET_TARGET to get the list of
all targets found by such device. Each reply message has target attributes with
relevant information such as the supported NFC protocols.

All polling operations requested through one netlink socket are stopped when
it's closed.

LOW-LEVEL DATA EXCHANGE:

The userspace must use PF_NFC sockets to perform any data communication with
targets. All NFC sockets use AF_NFC::

        struct sockaddr_nfc {
               sa_family_t sa_family;
               __u32 dev_idx;
               __u32 target_idx;
               __u32 nfc_protocol;
        };

To establish a connection with one target, the user must create an
NFC_SOCKPROTO_RAW socket and call the 'connect' syscall with the sockaddr_nfc
struct correctly filled. All information comes from NFC_EVENT_TARGETS_FOUND
netlink event. As a target can support more than one NFC protocol, the user
must inform which protocol it wants to use.

Internally, 'connect' will result in an activate_target call to the driver.
When the socket is closed, the target is deactivated.

The data format exchanged through the sockets is NFC protocol dependent. For
instance, when communicating with MIFARE tags, the data exchanged are MIFARE
commands and their responses.

The first received package is the response to the first sent package and so
on. In order to allow valid "empty" responses, every data received has a NULL
header of 1 byte.

repo_name: angery/linux


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

=============================================
Open vSwitch datapath developer documentation
=============================================

The Open vSwitch kernel module allows flexible userspace control over
flow-level packet processing on selected network devices.  It can be
used to implement a plain Ethernet switch, network device bonding,
VLAN processing, network access control, flow-based network control,
and so on.

The kernel module implements multiple "datapaths" (analogous to
bridges), each of which can have multiple "vports" (analogous to ports
within a bridge).  Each datapath also has associated with it a "flow
table" that userspace populates with "flows" that map from keys based
on packet headers and metadata to sets of actions.  The most common
action forwards the packet to another vport; other actions are also
implemented.

When a packet arrives on a vport, the kernel module processes it by
extracting its flow key and looking it up in the flow table.  If there
is a matching flow, it executes the associated actions.  If there is
no match, it queues the packet to userspace for processing (as part of
its processing, userspace will likely set up a flow to handle further
packets of the same type entirely in-kernel).

Flow key compatibility
----------------------

Network protocols evolve over time.  New protocols become important
and existing protocols lose their prominence.  For the Open vSwitch
kernel module to remain relevant, it must be possible for newer
versions to parse additional protocols as part of the flow key.  It
might even be desirable, someday, to drop support for parsing
protocols that have become obsolete.  Therefore, the Netlink interface
to Open vSwitch is designed to allow carefully written userspace
applications to work with any version of the flow key, past or future.

To support this forward and backward compatibility, whenever the
kernel module passes a packet to userspace, it also passes along the
flow key that it parsed from the packet.  Userspace then extracts its
own notion of a flow key from the packet and compares it against the
kernel-provided version:

    - If userspace's notion of the flow key for the packet matches the
      kernel's, then nothing special is necessary.

    - If the kernel's flow key includes more fields than the userspace
      version of the flow key, for example if the kernel decoded IPv6
      headers but userspace stopped at the Ethernet type (because it
      does not understand IPv6), then again nothing special is
      necessary.  Userspace can still set up a flow in the usual way,
      as long as it uses the kernel-provided flow key to do it.

    - If the userspace flow key includes more fields than the
      kernel's, for example if userspace decoded an IPv6 header but
      the kernel stopped at the Ethernet type, then userspace can
      forward the packet manually, without setting up a flow in the
      kernel.  This case is bad for performance because every packet
      that the kernel considers part of the flow must go to userspace,
      but the forwarding behavior is correct.  (If userspace can
      determine that the values of the extra fields would not affect
      forwarding behavior, then it could set up a flow anyway.)

How flow keys evolve over time is important to making this work, so
the following sections go into detail.

Flow key format
---------------

A flow key is passed over a Netlink socket as a sequence of Netlink
attributes.  Some attributes represent packet metadata, defined as any
information about a packet that cannot be extracted from the packet
itself, e.g. the vport on which the packet was received.  Most
attributes, however, are extracted from headers within the packet,
e.g. source and destination addresses from Ethernet, IP, or TCP
headers.

The <linux/openvswitch.h> header file defines the exact format of the
flow key attributes.  For informal explanatory purposes here, we write
them as comma-separated strings, with parentheses indicating arguments
and nesting.  For example, the following could represent a flow key
corresponding to a TCP packet that arrived on vport 1::

    in_port(1), eth(src=e0:91:f5:21:d0:b2, dst=00:02:e3:0f:80:a4),
    eth_type(0x0800), ipv4(src=172.16.0.20, dst=172.18.0.52, proto=17, tos=0,
    frag=no), tcp(src=49163, dst=80)

Often we ellipsize arguments not important to the discussion, e.g.::

    in_port(1), eth(...), eth_type(0x0800), ipv4(...), tcp(...)

Wildcarded flow key format
--------------------------

A wildcarded flow is described with two sequences of Netlink attributes
passed over the Netlink socket. A flow key, exactly as described above, and an
optional corresponding flow mask.

A wildcarded flow can represent a group of exact match flows. Each '1' bit
in the mask specifies a exact match with the corresponding bit in the flow key.
A '0' bit specifies a don't care bit, which will match either a '1' or '0' bit
of a incoming packet. Using wildcarded flow can improve the flow set up rate
by reduce the number of new flows need to be processed by the user space program.

Support for the mask Netlink attribute is optional for both the kernel and user
space program. The kernel can ignore the mask attribute, installing an exact
match flow, or reduce the number of don't care bits in the kernel to less than
what was specified by the user space program. In this case, variations in bits
that the kernel does not implement will simply result in additional flow setups.
The kernel module will also work with user space programs that neither support
nor supply flow mask attributes.

Since the kernel may ignore or modify wildcard bits, it can be difficult for
the userspace program to know exactly what matches are installed. There are
two possible approaches: reactively install flows as they miss the kernel
flow table (and therefore not attempt to determine wildcard changes at all)
or use the kernel's response messages to determine the installed wildcards.

When interacting with userspace, the kernel should maintain the match portion
of the key exactly as originally installed. This will provides a handle to
identify the flow for all future operations. However, when reporting the
mask of an installed flow, the mask should include any restrictions imposed
by the kernel.

The behavior when using overlapping wildcarded flows is undefined. It is the
responsibility of the user space program to ensure that any incoming packet
can match at most one flow, wildcarded or not. The current implementation
performs best-effort detection of overlapping wildcarded flows and may reject
some but not all of them. However, this behavior may change in future versions.

Unique flow identifiers
-----------------------

An alternative to using the original match portion of a key as the handle for
flow identification is a unique flow identifier, or "UFID". UFIDs are optional
for both the kernel and user space program.

User space programs that support UFID are expected to provide it during flow
setup in addition to the flow, then refer to the flow using the UFID for all
future operations. The kernel is not required to index flows by the original
flow key if a UFID is specified.

Basic rule for evolving flow keys
---------------------------------

Some care is needed to really maintain forward and backward
compatibility for applications that follow the rules listed under
"Flow key compatibility" above.

The basic rule is obvious::

    ==================================================================
    New network protocol support must only supplement existing flow
    key attributes.  It must not change the meaning of already defined
    flow key attributes.
    ==================================================================

This rule does have less-obvious consequences so it is worth working
through a few examples.  Suppose, for example, that the kernel module
did not already implement VLAN parsing.  Instead, it just interpreted
the 802.1Q TPID (0x8100) as the Ethertype then stopped parsing the
packet.  The flow key for any packet with an 802.1Q header would look
essentially like this, ignoring metadata::

    eth(...), eth_type(0x8100)

Naively, to add VLAN support, it makes sense to add a new "vlan" flow
key attribute to contain the VLAN tag, then continue to decode the
encapsulated headers beyond the VLAN tag using the existing field
definitions.  With this change, a TCP packet in VLAN 10 would have a
flow key much like this::

    eth(...), vlan(vid=10, pcp=0), eth_type(0x0800), ip(proto=6, ...), tcp(...)

But this change would negatively affect a userspace application that
has not been updated to understand the new "vlan" flow key attribute.
The application could, following the flow compatibility rules above,
ignore the "vlan" attribute that it does not understand and therefore
assume that the flow contained IP packets.  This is a bad assumption
(the flow only contains IP packets if one parses and skips over the
802.1Q header) and it could cause the application's behavior to change
across kernel versions even though it follows the compatibility rules.

The solution is to use a set of nested attributes.  This is, for
example, why 802.1Q support uses nested attributes.  A TCP packet in
VLAN 10 is actually expressed as::

    eth(...), eth_type(0x8100), vlan(vid=10, pcp=0), encap(eth_type(0x0800),
    ip(proto=6, ...), tcp(...)))

Notice how the "eth_type", "ip", and "tcp" flow key attributes are
nested inside the "encap" attribute.  Thus, an application that does
not understand the "vlan" key will not see either of those attributes
and therefore will not misinterpret them.  (Also, the outer eth_type
is still 0x8100, not changed to 0x0800.)

Handling malformed packets
--------------------------

Don't drop packets in the kernel for malformed protocol headers, bad
checksums, etc.  This would prevent userspace from implementing a
simple Ethernet switch that forwards every packet.

Instead, in such a case, include an attribute with "empty" content.
It doesn't matter if the empty content could be valid protocol values,
as long as those values are rarely seen in practice, because userspace
can always forward all packets with those values to userspace and
handle them individually.

For example, consider a packet that contains an IP header that
indicates protocol 6 for TCP, but which is truncated just after the IP
header, so that the TCP header is missing.  The flow key for this
packet would include a tcp attribute with all-zero src and dst, like
this::

    eth(...), eth_type(0x0800), ip(proto=6, ...), tcp(src=0, dst=0)

As another example, consider a packet with an Ethernet type of 0x8100,
indicating that a VLAN TCI should follow, but which is truncated just
after the Ethernet type.  The flow key for this packet would include
an all-zero-bits vlan and an empty encap attribute, like this::

    eth(...), eth_type(0x8100), vlan(0), encap()

Unlike a TCP packet with source and destination ports 0, an
all-zero-bits VLAN TCI is not that rare, so the CFI bit (aka
VLAN_TAG_PRESENT inside the kernel) is ordinarily set in a vlan
attribute expressly to allow this situation to be distinguished.
Thus, the flow key in this second example unambiguously indicates a
missing or malformed VLAN TCI.

Other rules
-----------

The other rules for flow keys are much less subtle:

    - Duplicate attributes are not allowed at a given nesting level.

    - Ordering of attributes is not significant.

    - When the kernel sends a given flow key to userspace, it always
      composes it the same way.  This allows userspace to hash and
      compare entire flow keys that it may not be able to fully
      interpret.


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

==================
Operational States
==================

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

Linux distinguishes between administrative and operational state of an
interface. Administrative state is the result of "ip link set dev
<dev> up or down" and reflects whether the administrator wants to use
the device for traffic.

However, an interface is not usable just because the admin enabled it
- ethernet requires to be plugged into the switch and, depending on
a site's networking policy and configuration, an 802.1X authentication
to be performed before user data can be transferred. Operational state
shows the ability of an interface to transmit this user data.

Thanks to 802.1X, userspace must be granted the possibility to
influence operational state. To accommodate this, operational state is
split into two parts: Two flags that can be set by the driver only, and
a RFC2863 compatible state that is derived from these flags, a policy,
and changeable from userspace under certain rules.

2. Querying from userspace
==========================

Both admin and operational state can be queried via the netlink
operation RTM_GETLINK. It is also possible to subscribe to RTNLGRP_LINK
to be notified of updates while the interface is admin up. This is
important for setting from userspace.

These values contain interface state:

ifinfomsg::if_flags & IFF_UP:
 Interface is admin up

ifinfomsg::if_flags & IFF_RUNNING:
 Interface is in RFC2863 operational state UP or UNKNOWN. This is for
 backward compatibility, routing daemons, dhcp clients can use this
 flag to determine whether they should use the interface.

ifinfomsg::if_flags & IFF_LOWER_UP:
 Driver has signaled netif_carrier_on()

ifinfomsg::if_flags & IFF_DORMANT:
 Driver has signaled netif_dormant_on()

TLV IFLA_OPERSTATE
------------------

contains RFC2863 state of the interface in numeric representation:

IF_OPER_UNKNOWN (0):
 Interface is in unknown state, neither driver nor userspace has set
 operational state. Interface must be considered for user data as
 setting operational state has not been implemented in every driver.

IF_OPER_NOTPRESENT (1):
 Unused in current kernel (notpresent interfaces normally disappear),
 just a numerical placeholder.

IF_OPER_DOWN (2):
 Interface is unable to transfer data on L1, f.e. ethernet is not
 plugged or interface is ADMIN down.

IF_OPER_LOWERLAYERDOWN (3):
 Interfaces stacked on an interface that is IF_OPER_DOWN show this
 state (f.e. VLAN).

IF_OPER_TESTING (4):
 Interface is in testing mode, for example executing driver self-tests
 or media (cable) test. It can't be used for normal traffic until tests
 complete.

IF_OPER_DORMANT (5):
 Interface is L1 up, but waiting for an external event, f.e. for a
 protocol to establish. (802.1X)

IF_OPER_UP (6):
 Interface is operational up and can be used.

This TLV can also be queried via sysfs.

TLV IFLA_LINKMODE
-----------------

contains link policy. This is needed for userspace interaction
described below.

This TLV can also be queried via sysfs.

3. Kernel driver API
====================

Kernel drivers have access to two flags that map to IFF_LOWER_UP and
IFF_DORMANT. These flags can be set from everywhere, even from
interrupts. It is guaranteed that only the driver has write access,
however, if different layers of the driver manipulate the same flag,
the driver has to provide the synchronisation needed.

__LINK_STATE_NOCARRIER, maps to !IFF_LOWER_UP:

The driver uses netif_carrier_on() to clear and netif_carrier_off() to
set this flag. On netif_carrier_off(), the scheduler stops sending
packets. The name 'carrier' and the inversion are historical, think of
it as lower layer.

Note that for certain kind of soft-devices, which are not managing any
real hardware, it is possible to set this bit from userspace.  One
should use TLV IFLA_CARRIER to do so.

netif_carrier_ok() can be used to query that bit.

__LINK_STATE_DORMANT, maps to IFF_DORMANT:

Set by the driver to express that the device cannot yet be used
because some driver controlled protocol establishment has to
complete. Corresponding functions are netif_dormant_on() to set the
flag, netif_dormant_off() to clear it and netif_dormant() to query.

On device allocation, both flags __LINK_STATE_NOCARRIER and
__LINK_STATE_DORMANT are cleared, so the effective state is equivalent
to netif_carrier_ok() and !netif_dormant().

Whenever the driver CHANGES one of these flags, a workqueue event is
scheduled to translate the flag combination to IFLA_OPERSTATE as
follows:

!netif_carrier_ok():
 IF_OPER_LOWERLAYERDOWN if the interface is stacked, IF_OPER_DOWN
 otherwise. Kernel can recognise stacked interfaces because their
 ifindex != iflink.

netif_carrier_ok() && netif_dormant():
 IF_OPER_DORMANT

netif_carrier_ok() && !netif_dormant():
 IF_OPER_UP if userspace interaction is disabled. Otherwise
 IF_OPER_DORMANT with the possibility for userspace to initiate the
 IF_OPER_UP transition afterwards.

4. Setting from userspace
=========================

Applications have to use the netlink interface to influence the
RFC2863 operational state of an interface. Setting IFLA_LINKMODE to 1
via RTM_SETLINK instructs the kernel that an interface should go to
IF_OPER_DORMANT instead of IF_OPER_UP when the combination
netif_carrier_ok() && !netif_dormant() is set by the
driver. Afterwards, the userspace application can set IFLA_OPERSTATE
to IF_OPER_DORMANT or IF_OPER_UP as long as the driver does not set
netif_carrier_off() or netif_dormant_on(). Changes made by userspace
are multicasted on the netlink group RTNLGRP_LINK.

So basically a 802.1X supplicant interacts with the kernel like this:

- subscribe to RTNLGRP_LINK
- set IFLA_LINKMODE to 1 via RTM_SETLINK
- query RTM_GETLINK once to get initial state
- if initial flags are not (IFF_LOWER_UP && !IFF_DORMANT), wait until
  netlink multicast signals this state
- do 802.1X, eventually abort if flags go down again
- send RTM_SETLINK to set operstate to IF_OPER_UP if authentication
  succeeds, IF_OPER_DORMANT otherwise
- see how operstate and IFF_RUNNING is echoed via netlink multicast
- set interface back to IF_OPER_DORMANT if 802.1X reauthentication
  fails
- restart if kernel changes IFF_LOWER_UP or IFF_DORMANT flag

if supplicant goes down, bring back IFLA_LINKMODE to 0 and
IFLA_OPERSTATE to a sane value.

A routing daemon or dhcp client just needs to care for IFF_RUNNING or
waiting for operstate to go IF_OPER_UP/IF_OPER_UNKNOWN before
considering the interface / querying a DHCP address.

For technical questions and/or comments please e-mail to Stefan Rompf
(stefan at loplof.de).


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

===========
Packet MMAP
===========

Abstract
========

This file documents the mmap() facility available with the PACKET
socket interface. This type of sockets is used for

i) capture network traffic with utilities like tcpdump,
ii) transmit network traffic, or any other that needs raw
    access to network interface.

Howto can be found at:

    https://sites.google.com/site/packetmmap/

Please send your comments to
    - Ulisses Alonso Camaró <uaca@i.hate.spam.alumni.uv.es>
    - Johann Baudy

Why use PACKET_MMAP
===================

Non PACKET_MMAP capture process (plain AF_PACKET) is very
inefficient. It uses very limited buffers and requires one system call to
capture each packet, it requires two if you want to get packet's timestamp
(like libpcap always does).

On the other hand PACKET_MMAP is very efficient. PACKET_MMAP provides a size
configurable circular buffer mapped in user space that can be used to either
send or receive packets. This way reading packets just needs to wait for them,
most of the time there is no need to issue a single system call. Concerning
transmission, multiple packets can be sent through one system call to get the
highest bandwidth. By using a shared buffer between the kernel and the user
also has the benefit of minimizing packet copies.

It's fine to use PACKET_MMAP to improve the performance of the capture and
transmission process, but it isn't everything. At least, if you are capturing
at high speeds (this is relative to the cpu speed), you should check if the
device driver of your network interface card supports some sort of interrupt
load mitigation or (even better) if it supports NAPI, also make sure it is
enabled. For transmission, check the MTU (Maximum Transmission Unit) used and
supported by devices of your network. CPU IRQ pinning of your network interface
card can also be an advantage.

How to use mmap() to improve capture process
============================================

From the user standpoint, you should use the higher level libpcap library, which
is a de facto standard, portable across nearly all operating systems
including Win32.

Packet MMAP support was integrated into libpcap around the time of version 1.3.0;
TPACKET_V3 support was added in version 1.5.0

How to use mmap() directly to improve capture process
=====================================================

From the system calls stand point, the use of PACKET_MMAP involves
the following process::

    [setup]     socket() -------> creation of the capture socket
		setsockopt() ---> allocation of the circular buffer (ring)
				  option: PACKET_RX_RING
		mmap() ---------> mapping of the allocated buffer to the
				  user process

    [capture]   poll() ---------> to wait for incoming packets

    [shutdown]  close() --------> destruction of the capture socket and
				  deallocation of all associated
				  resources.

socket creation and destruction is straight forward, and is done
the same way with or without PACKET_MMAP::

 int fd = socket(PF_PACKET, mode, htons(ETH_P_ALL));

where mode is SOCK_RAW for the raw interface were link level
information can be captured or SOCK_DGRAM for the cooked
interface where link level information capture is not
supported and a link level pseudo-header is provided
by the kernel.

The destruction of the socket and all associated resources
is done by a simple call to close(fd).

Similarly as without PACKET_MMAP, it is possible to use one socket
for capture and transmission. This can be done by mapping the
allocated RX and TX buffer ring with a single mmap() call.
See "Mapping and use of the circular buffer (ring)".

Next I will describe PACKET_MMAP settings and its constraints,
also the mapping of the circular buffer in the user process and
the use of this buffer.

How to use mmap() directly to improve transmission process
==========================================================
Transmission process is similar to capture as shown below::

    [setup]         socket() -------> creation of the transmission socket
		    setsockopt() ---> allocation of the circular buffer (ring)
				      option: PACKET_TX_RING
		    bind() ---------> bind transmission socket with a network interface
		    mmap() ---------> mapping of the allocated buffer to the
				      user process

    [transmission]  poll() ---------> wait for free packets (optional)
		    send() ---------> send all packets that are set as ready in
				      the ring
				      The flag MSG_DONTWAIT can be used to return
				      before end of transfer.

    [shutdown]      close() --------> destruction of the transmission socket and
				      deallocation of all associated resources.

Socket creation and destruction is also straight forward, and is done
the same way as in capturing described in the previous paragraph::

 int fd = socket(PF_PACKET, mode, 0);

The protocol can optionally be 0 in case we only want to transmit
via this socket, which avoids an expensive call to packet_rcv().
In this case, you also need to bind(2) the TX_RING with sll_protocol = 0
set. Otherwise, htons(ETH_P_ALL) or any other protocol, for example.

Binding the socket to your network interface is mandatory (with zero copy) to
know the header size of frames used in the circular buffer.

As capture, each frame contains two parts::

    --------------------
    | struct tpacket_hdr | Header. It contains the status of
    |                    | of this frame
    |--------------------|
    | data buffer        |
    .                    .  Data that will be sent over the network interface.
    .                    .
    --------------------

 bind() associates the socket to your network interface thanks to
 sll_ifindex parameter of struct sockaddr_ll.

 Initialization example::

    struct sockaddr_ll my_addr;
    struct ifreq s_ifr;
    ...

    strscpy_pad (s_ifr.ifr_name, "eth0", sizeof(s_ifr.ifr_name));

    /* get interface index of eth0 */
    ioctl(this->socket, SIOCGIFINDEX, &s_ifr);

    /* fill sockaddr_ll struct to prepare binding */
    my_addr.sll_family = AF_PACKET;
    my_addr.sll_protocol = htons(ETH_P_ALL);
    my_addr.sll_ifindex =  s_ifr.ifr_ifindex;

    /* bind socket to eth0 */
    bind(this->socket, (struct sockaddr *)&my_addr, sizeof(struct sockaddr_ll));

 A complete tutorial is available at: https://sites.google.com/site/packetmmap/

By default, the user should put data at::

 frame base + TPACKET_HDRLEN - sizeof(struct sockaddr_ll)

So, whatever you choose for the socket mode (SOCK_DGRAM or SOCK_RAW),
the beginning of the user data will be at::

 frame base + TPACKET_ALIGN(sizeof(struct tpacket_hdr))

If you wish to put user data at a custom offset from the beginning of
the frame (for payload alignment with SOCK_RAW mode for instance) you
can set tp_net (with SOCK_DGRAM) or tp_mac (with SOCK_RAW). In order
to make this work it must be enabled previously with setsockopt()
and the PACKET_TX_HAS_OFF option.

PACKET_MMAP settings
====================

To setup PACKET_MMAP from user level code is done with a call like

 - Capture process::

     setsockopt(fd, SOL_PACKET, PACKET_RX_RING, (void *) &req, sizeof(req))

 - Transmission process::

     setsockopt(fd, SOL_PACKET, PACKET_TX_RING, (void *) &req, sizeof(req))

The most significant argument in the previous call is the req parameter,
this parameter must to have the following structure::

    struct tpacket_req
    {
	unsigned int    tp_block_size;  /* Minimal size of contiguous block */
	unsigned int    tp_block_nr;    /* Number of blocks */
	unsigned int    tp_frame_size;  /* Size of frame */
	unsigned int    tp_frame_nr;    /* Total number of frames */
    };

This structure is defined in /usr/include/linux/if_packet.h and establishes a
circular buffer (ring) of unswappable memory.
Being mapped in the capture process allows reading the captured frames and
related meta-information like timestamps without requiring a system call.

Frames are grouped in blocks. Each block is a physically contiguous
region of memory and holds tp_block_size/tp_frame_size frames. The total number
of blocks is tp_block_nr. Note that tp_frame_nr is a redundant parameter because::

    frames_per_block = tp_block_size/tp_frame_size

indeed, packet_set_ring checks that the following condition is true::

    frames_per_block * tp_block_nr == tp_frame_nr

Lets see an example, with the following values::

     tp_block_size= 4096
     tp_frame_size= 2048
     tp_block_nr  = 4
     tp_frame_nr  = 8

we will get the following buffer structure::

	    block #1                 block #2
    +---------+---------+    +---------+---------+
    | frame 1 | frame 2 |    | frame 3 | frame 4 |
    +---------+---------+    +---------+---------+

	    block #3                 block #4
    +---------+---------+    +---------+---------+
    | frame 5 | frame 6 |    | frame 7 | frame 8 |
    +---------+---------+    +---------+---------+

A frame can be of any size with the only condition it can fit in a block. A block
can only hold an integer number of frames, or in other words, a frame cannot
be spawned across two blocks, so there are some details you have to take into
account when choosing the frame_size. See "Mapping and use of the circular
buffer (ring)".

PACKET_MMAP setting constraints
===============================

In kernel versions prior to 2.4.26 (for the 2.4 branch) and 2.6.5 (2.6 branch),
the PACKET_MMAP buffer could hold only 32768 frames in a 32 bit architecture or
16384 in a 64 bit architecture.

Block size limit
----------------

As stated earlier, each block is a contiguous physical region of memory. These
memory regions are allocated with calls to the __get_free_pages() function. As
the name indicates, this function allocates pages of memory, and the second
argument is "order" or a power of two number of pages, that is
(for PAGE_SIZE == 4096) order=0 ==> 4096 bytes, order=1 ==> 8192 bytes,
order=2 ==> 16384 bytes, etc. The maximum size of a
region allocated by __get_free_pages is determined by the MAX_ORDER macro. More
precisely the limit can be calculated as::

   PAGE_SIZE << MAX_ORDER

   In a i386 architecture PAGE_SIZE is 4096 bytes
   In a 2.4/i386 kernel MAX_ORDER is 10
   In a 2.6/i386 kernel MAX_ORDER is 11

So get_free_pages can allocate as much as 4MB or 8MB in a 2.4/2.6 kernel
respectively, with an i386 architecture.

User space programs can include /usr/include/sys/user.h and
/usr/include/linux/mmzone.h to get PAGE_SIZE MAX_ORDER declarations.

The pagesize can also be determined dynamically with the getpagesize (2)
system call.

Block number limit
------------------

To understand the constraints of PACKET_MMAP, we have to see the structure
used to hold the pointers to each block.

Currently, this structure is a dynamically allocated vector with kmalloc
called pg_vec, its size limits the number of blocks that can be allocated::

    +---+---+---+---+
    | x | x | x | x |
    +---+---+---+---+
      |   |   |   |
      |   |   |   v
      |   |   v  block #4
      |   v  block #3
      v  block #2
     block #1

kmalloc allocates any number of bytes of physically contiguous memory from
a pool of pre-determined sizes. This pool of memory is maintained by the slab
allocator which is at the end the responsible for doing the allocation and
hence which imposes the maximum memory that kmalloc can allocate.

In a 2.4/2.6 kernel and the i386 architecture, the limit is 131072 bytes. The
predetermined sizes that kmalloc uses can be checked in the "size-<bytes>"
entries of /proc/slabinfo

In a 32 bit architecture, pointers are 4 bytes long, so the total number of
pointers to blocks is::

     131072/4 = 32768 blocks

PACKET_MMAP buffer size calculator
==================================

Definitions:

==============  ================================================================
<size-max>      is the maximum size of allocable with kmalloc
		(see /proc/slabinfo)
<pointer size>  depends on the architecture -- ``sizeof(void *)``
<page size>     depends on the architecture -- PAGE_SIZE or getpagesize (2)
<max-order>     is the value defined with MAX_ORDER
<frame size>    it's an upper bound of frame's capture size (more on this later)
==============  ================================================================

from these definitions we will derive::

	<block number> = <size-max>/<pointer size>
	<block size> = <pagesize> << <max-order>

so, the max buffer size is::

	<block number> * <block size>

and, the number of frames be::

	<block number> * <block size> / <frame size>

Suppose the following parameters, which apply for 2.6 kernel and an
i386 architecture::

	<size-max> = 131072 bytes
	<pointer size> = 4 bytes
	<pagesize> = 4096 bytes
	<max-order> = 11

and a value for <frame size> of 2048 bytes. These parameters will yield::

	<block number> = 131072/4 = 32768 blocks
	<block size> = 4096 << 11 = 8 MiB.

and hence the buffer will have a 262144 MiB size. So it can hold
262144 MiB / 2048 bytes = 134217728 frames

Actually, this buffer size is not possible with an i386 architecture.
Remember that the memory is allocated in kernel space, in the case of
an i386 kernel's memory size is limited to 1GiB.

All memory allocations are not freed until the socket is closed. The memory
allocations are done with GFP_KERNEL priority, this basically means that
the allocation can wait and swap other process' memory in order to allocate
the necessary memory, so normally limits can be reached.

Other constraints
-----------------

If you check the source code you will see that what I draw here as a frame
is not only the link level frame. At the beginning of each frame there is a
header called struct tpacket_hdr used in PACKET_MMAP to hold link level's frame
meta information like timestamp. So what we draw here a frame it's really
the following (from include/linux/if_packet.h)::

 /*
   Frame structure:

   - Start. Frame must be aligned to TPACKET_ALIGNMENT=16
   - struct tpacket_hdr
   - pad to TPACKET_ALIGNMENT=16
   - struct sockaddr_ll
   - Gap, chosen so that packet data (Start+tp_net) aligns to
     TPACKET_ALIGNMENT=16
   - Start+tp_mac: [ Optional MAC header ]
   - Start+tp_net: Packet data, aligned to TPACKET_ALIGNMENT=16.
   - Pad to align to TPACKET_ALIGNMENT=16
 */

The following are conditions that are checked in packet_set_ring

   - tp_block_size must be a multiple of PAGE_SIZE (1)
   - tp_frame_size must be greater than TPACKET_HDRLEN (obvious)
   - tp_frame_size must be a multiple of TPACKET_ALIGNMENT
   - tp_frame_nr   must be exactly frames_per_block*tp_block_nr

Note that tp_block_size should be chosen to be a power of two or there will
be a waste of memory.

Mapping and use of the circular buffer (ring)
---------------------------------------------

The mapping of the buffer in the user process is done with the conventional
mmap function. Even the circular buffer is compound of several physically
discontiguous blocks of memory, they are contiguous to the user space, hence
just one call to mmap is needed::

    mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

If tp_frame_size is a divisor of tp_block_size frames will be
contiguously spaced by tp_frame_size bytes. If not, each
tp_block_size/tp_frame_size frames there will be a gap between
the frames. This is because a frame cannot be spawn across two
blocks.

To use one socket for capture and transmission, the mapping of both the
RX and TX buffer ring has to be done with one call to mmap::

    ...
    setsockopt(fd, SOL_PACKET, PACKET_RX_RING, &foo, sizeof(foo));
    setsockopt(fd, SOL_PACKET, PACKET_TX_RING, &bar, sizeof(bar));
    ...
    rx_ring = mmap(0, size * 2, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    tx_ring = rx_ring + size;

RX must be the first as the kernel maps the TX ring memory right
after the RX one.

At the beginning of each frame there is an status field (see
struct tpacket_hdr). If this field is 0 means that the frame is ready
to be used for the kernel, If not, there is a frame the user can read
and the following flags apply:

Capture process
^^^^^^^^^^^^^^^

From include/linux/if_packet.h::

     #define TP_STATUS_COPY          (1 << 1)
     #define TP_STATUS_LOSING        (1 << 2)
     #define TP_STATUS_CSUMNOTREADY  (1 << 3)
     #define TP_STATUS_CSUM_VALID    (1 << 7)

======================  =======================================================
TP_STATUS_COPY		This flag indicates that the frame (and associated
			meta information) has been truncated because it's
			larger than tp_frame_size. This packet can be
			read entirely with recvfrom().

			In order to make this work it must to be
			enabled previously with setsockopt() and
			the PACKET_COPY_THRESH option.

			The number of frames that can be buffered to
			be read with recvfrom is limited like a normal socket.
			See the SO_RCVBUF option in the socket (7) man page.

TP_STATUS_LOSING	indicates there were packet drops from last time
			statistics where checked with getsockopt() and
			the PACKET_STATISTICS option.

TP_STATUS_CSUMNOTREADY	currently it's used for outgoing IP packets which
			its checksum will be done in hardware. So while
			reading the packet we should not try to check the
			checksum.

TP_STATUS_CSUM_VALID	This flag indicates that at least the transport
			header checksum of the packet has been already
			validated on the kernel side. If the flag is not set
			then we are free to check the checksum by ourselves
			provided that TP_STATUS_CSUMNOTREADY is also not set.
======================  =======================================================

for convenience there are also the following defines::

     #define TP_STATUS_KERNEL        0
     #define TP_STATUS_USER          1

The kernel initializes all frames to TP_STATUS_KERNEL, when the kernel
receives a packet it puts in the buffer and updates the status with
at least the TP_STATUS_USER flag. Then the user can read the packet,
once the packet is read the user must zero the status field, so the kernel
can use again that frame buffer.

The user can use poll (any other variant should apply too) to check if new
packets are in the ring::

    struct pollfd pfd;

    pfd.fd = fd;
    pfd.revents = 0;
    pfd.events = POLLIN|POLLRDNORM|POLLERR;

    if (status == TP_STATUS_KERNEL)
	retval = poll(&pfd, 1, timeout);

It doesn't incur in a race condition to first check the status value and
then poll for frames.

Transmission process
^^^^^^^^^^^^^^^^^^^^

Those defines are also used for transmission::

     #define TP_STATUS_AVAILABLE        0 // Frame is available
     #define TP_STATUS_SEND_REQUEST     1 // Frame will be sent on next send()
     #define TP_STATUS_SENDING          2 // Frame is currently in transmission
     #define TP_STATUS_WRONG_FORMAT     4 // Frame format is not correct

First, the kernel initializes all frames to TP_STATUS_AVAILABLE. To send a
packet, the user fills a data buffer of an available frame, sets tp_len to
current data buffer size and sets its status field to TP_STATUS_SEND_REQUEST.
This can be done on multiple frames. Once the user is ready to transmit, it
calls send(). Then all buffers with status equal to TP_STATUS_SEND_REQUEST are
forwarded to the network device. The kernel updates each status of sent
frames with TP_STATUS_SENDING until the end of transfer.

At the end of each transfer, buffer status returns to TP_STATUS_AVAILABLE.

::

    header->tp_len = in_i_size;
    header->tp_status = TP_STATUS_SEND_REQUEST;
    retval = send(this->socket, NULL, 0, 0);

The user can also use poll() to check if a buffer is available:

(status == TP_STATUS_SENDING)

::

    struct pollfd pfd;
    pfd.fd = fd;
    pfd.revents = 0;
    pfd.events = POLLOUT;
    retval = poll(&pfd, 1, timeout);

What TPACKET versions are available and when to use them?
=========================================================

::

 int val = tpacket_version;
 setsockopt(fd, SOL_PACKET, PACKET_VERSION, &val, sizeof(val));
 getsockopt(fd, SOL_PACKET, PACKET_VERSION, &val, sizeof(val));

where 'tpacket_version' can be TPACKET_V1 (default), TPACKET_V2, TPACKET_V3.

TPACKET_V1:
	- Default if not otherwise specified by setsockopt(2)
	- RX_RING, TX_RING available

TPACKET_V1 --> TPACKET_V2:
	- Made 64 bit clean due to unsigned long usage in TPACKET_V1
	  structures, thus this also works on 64 bit kernel with 32 bit
	  userspace and the like
	- Timestamp resolution in nanoseconds instead of microseconds
	- RX_RING, TX_RING available
	- VLAN metadata information available for packets
	  (TP_STATUS_VLAN_VALID, TP_STATUS_VLAN_TPID_VALID),
	  in the tpacket2_hdr structure:

		- TP_STATUS_VLAN_VALID bit being set into the tp_status field indicates
		  that the tp_vlan_tci field has valid VLAN TCI value
		- TP_STATUS_VLAN_TPID_VALID bit being set into the tp_status field
		  indicates that the tp_vlan_tpid field has valid VLAN TPID value

	- How to switch to TPACKET_V2:

		1. Replace struct tpacket_hdr by struct tpacket2_hdr
		2. Query header len and save
		3. Set protocol version to 2, set up ring as usual
		4. For getting the sockaddr_ll,
		   use ``(void *)hdr + TPACKET_ALIGN(hdrlen)`` instead of
		   ``(void *)hdr + TPACKET_ALIGN(sizeof(struct tpacket_hdr))``

TPACKET_V2 --> TPACKET_V3:
	- Flexible buffer implementation for RX_RING:
		1. Blocks can be configured with non-static frame-size
		2. Read/poll is at a block-level (as opposed to packet-level)
		3. Added poll timeout to avoid indefinite user-space wait
		   on idle links
		4. Added user-configurable knobs:

			4.1 block::timeout
			4.2 tpkt_hdr::sk_rxhash

	- RX Hash data available in user space
	- TX_RING semantics are conceptually similar to TPACKET_V2;
	  use tpacket3_hdr instead of tpacket2_hdr, and TPACKET3_HDRLEN
	  instead of TPACKET2_HDRLEN. In the current implementation,
	  the tp_next_offset field in the tpacket3_hdr MUST be set to
	  zero, indicating that the ring does not hold variable sized frames.
	  Packets with non-zero values of tp_next_offset will be dropped.

AF_PACKET fanout mode
=====================

In the AF_PACKET fanout mode, packet reception can be load balanced among
processes. This also works in combination with mmap(2) on packet sockets.

Currently implemented fanout policies are:

  - PACKET_FANOUT_HASH: schedule to socket by skb's packet hash
  - PACKET_FANOUT_LB: schedule to socket by round-robin
  - PACKET_FANOUT_CPU: schedule to socket by CPU packet arrives on
  - PACKET_FANOUT_RND: schedule to socket by random selection
  - PACKET_FANOUT_ROLLOVER: if one socket is full, rollover to another
  - PACKET_FANOUT_QM: schedule to socket by skbs recorded queue_mapping

Minimal example code by David S. Miller (try things like "./test eth0 hash",
"./test eth0 lb", etc.)::

    #include <stddef.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>

    #include <sys/types.h>
    #include <sys/wait.h>
    #include <sys/socket.h>
    #include <sys/ioctl.h>

    #include <unistd.h>

    #include <linux/if_ether.h>
    #include <linux/if_packet.h>

    #include <net/if.h>

    static const char *device_name;
    static int fanout_type;
    static int fanout_id;

    #ifndef PACKET_FANOUT
    # define PACKET_FANOUT			18
    # define PACKET_FANOUT_HASH		0
    # define PACKET_FANOUT_LB		1
    #endif

    static int setup_socket(void)
    {
	    int err, fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_IP));
	    struct sockaddr_ll ll;
	    struct ifreq ifr;
	    int fanout_arg;

	    if (fd < 0) {
		    perror("socket");
		    return EXIT_FAILURE;
	    }

	    memset(&ifr, 0, sizeof(ifr));
	    strcpy(ifr.ifr_name, device_name);
	    err = ioctl(fd, SIOCGIFINDEX, &ifr);
	    if (err < 0) {
		    perror("SIOCGIFINDEX");
		    return EXIT_FAILURE;
	    }

	    memset(&ll, 0, sizeof(ll));
	    ll.sll_family = AF_PACKET;
	    ll.sll_ifindex = ifr.ifr_ifindex;
	    err = bind(fd, (struct sockaddr *) &ll, sizeof(ll));
	    if (err < 0) {
		    perror("bind");
		    return EXIT_FAILURE;
	    }

	    fanout_arg = (fanout_id | (fanout_type << 16));
	    err = setsockopt(fd, SOL_PACKET, PACKET_FANOUT,
			    &fanout_arg, sizeof(fanout_arg));
	    if (err) {
		    perror("setsockopt");
		    return EXIT_FAILURE;
	    }

	    return fd;
    }

    static void fanout_thread(void)
    {
	    int fd = setup_socket();
	    int limit = 10000;

	    if (fd < 0)
		    exit(fd);

	    while (limit-- > 0) {
		    char buf[1600];
		    int err;

		    err = read(fd, buf, sizeof(buf));
		    if (err < 0) {
			    perror("read");
			    exit(EXIT_FAILURE);
		    }
		    if ((limit % 10) == 0)
			    fprintf(stdout, "(%d) \n", getpid());
	    }

	    fprintf(stdout, "%d: Received 10000 packets\n", getpid());

	    close(fd);
	    exit(0);
    }

    int main(int argc, char **argp)
    {
	    int fd, err;
	    int i;

	    if (argc != 3) {
		    fprintf(stderr, "Usage: %s INTERFACE {hash|lb}\n", argp[0]);
		    return EXIT_FAILURE;
	    }

	    if (!strcmp(argp[2], "hash"))
		    fanout_type = PACKET_FANOUT_HASH;
	    else if (!strcmp(argp[2], "lb"))
		    fanout_type = PACKET_FANOUT_LB;
	    else {
		    fprintf(stderr, "Unknown fanout type [%s]\n", argp[2]);
		    exit(EXIT_FAILURE);
	    }

	    device_name = argp[1];
	    fanout_id = getpid() & 0xffff;

	    for (i = 0; i < 4; i++) {
		    pid_t pid = fork();

		    switch (pid) {
		    case 0:
			    fanout_thread();

		    case -1:
			    perror("fork");
			    exit(EXIT_FAILURE);
		    }
	    }

	    for (i = 0; i < 4; i++) {
		    int status;

		    wait(&status);
	    }

	    return 0;
    }

AF_PACKET TPACKET_V3 example
============================

AF_PACKET's TPACKET_V3 ring buffer can be configured to use non-static frame
sizes by doing it's own memory management. It is based on blocks where polling
works on a per block basis instead of per ring as in TPACKET_V2 and predecessor.

It is said that TPACKET_V3 brings the following benefits:

 * ~15% - 20% reduction in CPU-usage
 * ~20% increase in packet capture rate
 * ~2x increase in packet density
 * Port aggregation analysis
 * Non static frame size to capture entire packet payload

So it seems to be a good candidate to be used with packet fanout.

Minimal example code by Daniel Borkmann based on Chetan Loke's lolpcap (compile
it with gcc -Wall -O2 blob.c, and try things like "./a.out eth0", etc.)::

    /* Written from scratch, but kernel-to-user space API usage
    * dissected from lolpcap:
    *  Copyright 2011, Chetan Loke <loke.chetan@gmail.com>
    *  License: GPL, version 2.0
    */

    #include <stdio.h>
    #include <stdlib.h>
    #include <stdint.h>
    #include <string.h>
    #include <assert.h>
    #include <net/if.h>
    #include <arpa/inet.h>
    #include <netdb.h>
    #include <poll.h>
    #include <unistd.h>
    #include <signal.h>
    #include <inttypes.h>
    #include <sys/socket.h>
    #include <sys/mman.h>
    #include <linux/if_packet.h>
    #include <linux/if_ether.h>
    #include <linux/ip.h>

    #ifndef likely
    # define likely(x)		__builtin_expect(!!(x), 1)
    #endif
    #ifndef unlikely
    # define unlikely(x)		__builtin_expect(!!(x), 0)
    #endif

    struct block_desc {
	    uint32_t version;
	    uint32_t offset_to_priv;
	    struct tpacket_hdr_v1 h1;
    };

    struct ring {
	    struct iovec *rd;
	    uint8_t *map;
	    struct tpacket_req3 req;
    };

    static unsigned long packets_total = 0, bytes_total = 0;
    static sig_atomic_t sigint = 0;

    static void sighandler(int num)
    {
	    sigint = 1;
    }

    static int setup_socket(struct ring *ring, char *netdev)
    {
	    int err, i, fd, v = TPACKET_V3;
	    struct sockaddr_ll ll;
	    unsigned int blocksiz = 1 << 22, framesiz = 1 << 11;
	    unsigned int blocknum = 64;

	    fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	    if (fd < 0) {
		    perror("socket");
		    exit(1);
	    }

	    err = setsockopt(fd, SOL_PACKET, PACKET_VERSION, &v, sizeof(v));
	    if (err < 0) {
		    perror("setsockopt");
		    exit(1);
	    }

	    memset(&ring->req, 0, sizeof(ring->req));
	    ring->req.tp_block_size = blocksiz;
	    ring->req.tp_frame_size = framesiz;
	    ring->req.tp_block_nr = blocknum;
	    ring->req.tp_frame_nr = (blocksiz * blocknum) / framesiz;
	    ring->req.tp_retire_blk_tov = 60;
	    ring->req.tp_feature_req_word = TP_FT_REQ_FILL_RXHASH;

	    err = setsockopt(fd, SOL_PACKET, PACKET_RX_RING, &ring->req,
			    sizeof(ring->req));
	    if (err < 0) {
		    perror("setsockopt");
		    exit(1);
	    }

	    ring->map = mmap(NULL, ring->req.tp_block_size * ring->req.tp_block_nr,
			    PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, fd, 0);
	    if (ring->map == MAP_FAILED) {
		    perror("mmap");
		    exit(1);
	    }

	    ring->rd = malloc(ring->req.tp_block_nr * sizeof(*ring->rd));
	    assert(ring->rd);
	    for (i = 0; i < ring->req.tp_block_nr; ++i) {
		    ring->rd[i].iov_base = ring->map + (i * ring->req.tp_block_size);
		    ring->rd[i].iov_len = ring->req.tp_block_size;
	    }

	    memset(&ll, 0, sizeof(ll));
	    ll.sll_family = PF_PACKET;
	    ll.sll_protocol = htons(ETH_P_ALL);
	    ll.sll_ifindex = if_nametoindex(netdev);
	    ll.sll_hatype = 0;
	    ll.sll_pkttype = 0;
	    ll.sll_halen = 0;

	    err = bind(fd, (struct sockaddr *) &ll, sizeof(ll));
	    if (err < 0) {
		    perror("bind");
		    exit(1);
	    }

	    return fd;
    }

    static void display(struct tpacket3_hdr *ppd)
    {
	    struct ethhdr *eth = (struct ethhdr *) ((uint8_t *) ppd + ppd->tp_mac);
	    struct iphdr *ip = (struct iphdr *) ((uint8_t *) eth + ETH_HLEN);

	    if (eth->h_proto == htons(ETH_P_IP)) {
		    struct sockaddr_in ss, sd;
		    char sbuff[NI_MAXHOST], dbuff[NI_MAXHOST];

		    memset(&ss, 0, sizeof(ss));
		    ss.sin_family = PF_INET;
		    ss.sin_addr.s_addr = ip->saddr;
		    getnameinfo((struct sockaddr *) &ss, sizeof(ss),
				sbuff, sizeof(sbuff), NULL, 0, NI_NUMERICHOST);

		    memset(&sd, 0, sizeof(sd));
		    sd.sin_family = PF_INET;
		    sd.sin_addr.s_addr = ip->daddr;
		    getnameinfo((struct sockaddr *) &sd, sizeof(sd),
				dbuff, sizeof(dbuff), NULL, 0, NI_NUMERICHOST);

		    printf("%s -> %s, ", sbuff, dbuff);
	    }

	    printf("rxhash: 0x%x\n", ppd->hv1.tp_rxhash);
    }

    static void walk_block(struct block_desc *pbd, const int block_num)
    {
	    int num_pkts = pbd->h1.num_pkts, i;
	    unsigned long bytes = 0;
	    struct tpacket3_hdr *ppd;

	    ppd = (struct tpacket3_hdr *) ((uint8_t *) pbd +
					pbd->h1.offset_to_first_pkt);
	    for (i = 0; i < num_pkts; ++i) {
		    bytes += ppd->tp_snaplen;
		    display(ppd);

		    ppd = (struct tpacket3_hdr *) ((uint8_t *) ppd +
						ppd->tp_next_offset);
	    }

	    packets_total += num_pkts;
	    bytes_total += bytes;
    }

    static void flush_block(struct block_desc *pbd)
    {
	    pbd->h1.block_status = TP_STATUS_KERNEL;
    }

    static void teardown_socket(struct ring *ring, int fd)
    {
	    munmap(ring->map, ring->req.tp_block_size * ring->req.tp_block_nr);
	    free(ring->rd);
	    close(fd);
    }

    int main(int argc, char **argp)
    {
	    int fd, err;
	    socklen_t len;
	    struct ring ring;
	    struct pollfd pfd;
	    unsigned int block_num = 0, blocks = 64;
	    struct block_desc *pbd;
	    struct tpacket_stats_v3 stats;

	    if (argc != 2) {
		    fprintf(stderr, "Usage: %s INTERFACE\n", argp[0]);
		    return EXIT_FAILURE;
	    }

	    signal(SIGINT, sighandler);

	    memset(&ring, 0, sizeof(ring));
	    fd = setup_socket(&ring, argp[argc - 1]);
	    assert(fd > 0);

	    memset(&pfd, 0, sizeof(pfd));
	    pfd.fd = fd;
	    pfd.events = POLLIN | POLLERR;
	    pfd.revents = 0;

	    while (likely(!sigint)) {
		    pbd = (struct block_desc *) ring.rd[block_num].iov_base;

		    if ((pbd->h1.block_status & TP_STATUS_USER) == 0) {
			    poll(&pfd, 1, -1);
			    continue;
		    }

		    walk_block(pbd, block_num);
		    flush_block(pbd);
		    block_num = (block_num + 1) % blocks;
	    }

	    len = sizeof(stats);
	    err = getsockopt(fd, SOL_PACKET, PACKET_STATISTICS, &stats, &len);
	    if (err < 0) {
		    perror("getsockopt");
		    exit(1);
	    }

	    fflush(stdout);
	    printf("\nReceived %u packets, %lu bytes, %u dropped, freeze_q_cnt: %u\n",
		stats.tp_packets, bytes_total, stats.tp_drops,
		stats.tp_freeze_q_cnt);

	    teardown_socket(&ring, fd);
	    return 0;
    }

PACKET_QDISC_BYPASS
===================

If there is a requirement to load the network with many packets in a similar
fashion as pktgen does, you might set the following option after socket
creation::

    int one = 1;
    setsockopt(fd, SOL_PACKET, PACKET_QDISC_BYPASS, &one, sizeof(one));

This has the side-effect, that packets sent through PF_PACKET will bypass the
kernel's qdisc layer and are forcedly pushed to the driver directly. Meaning,
packet are not buffered, tc disciplines are ignored, increased loss can occur
and such packets are also not visible to other PF_PACKET sockets anymore. So,
you have been warned; generally, this can be useful for stress testing various
components of a system.

On default, PACKET_QDISC_BYPASS is disabled and needs to be explicitly enabled
on PF_PACKET sockets.

PACKET_TIMESTAMP
================

The PACKET_TIMESTAMP setting determines the source of the timestamp in
the packet meta information for mmap(2)ed RX_RING and TX_RINGs.  If your
NIC is capable of timestamping packets in hardware, you can request those
hardware timestamps to be used. Note: you may need to enable the generation
of hardware timestamps with SIOCSHWTSTAMP (see related information from
Documentation/networking/timestamping.rst).

PACKET_TIMESTAMP accepts the same integer bit field as SO_TIMESTAMPING::

    int req = SOF_TIMESTAMPING_RAW_HARDWARE;
    setsockopt(fd, SOL_PACKET, PACKET_TIMESTAMP, (void *) &req, sizeof(req))

For the mmap(2)ed ring buffers, such timestamps are stored in the
``tpacket{,2,3}_hdr`` structure's tp_sec and ``tp_{n,u}sec`` members.
To determine what kind of timestamp has been reported, the tp_status field
is binary or'ed with the following possible bits ...

::

    TP_STATUS_TS_RAW_HARDWARE
    TP_STATUS_TS_SOFTWARE

... that are equivalent to its ``SOF_TIMESTAMPING_*`` counterparts. For the
RX_RING, if neither is set (i.e. PACKET_TIMESTAMP is not set), then a
software fallback was invoked *within* PF_PACKET's processing code (less
precise).

Getting timestamps for the TX_RING works as follows: i) fill the ring frames,
ii) call sendto() e.g. in blocking mode, iii) wait for status of relevant
frames to be updated resp. the frame handed over to the application, iv) walk
through the frames to pick up the individual hw/sw timestamps.

Only (!) if transmit timestamping is enabled, then these bits are combined
with binary | with TP_STATUS_AVAILABLE, so you must check for that in your
application (e.g. !(tp_status & (TP_STATUS_SEND_REQUEST | TP_STATUS_SENDING))
in a first step to see if the frame belongs to the application, and then
one can extract the type of timestamp in a second step from tp_status)!

If you don't care about them, thus having it disabled, checking for
TP_STATUS_AVAILABLE resp. TP_STATUS_WRONG_FORMAT is sufficient. If in the
TX_RING part only TP_STATUS_AVAILABLE is set, then the tp_sec and tp_{n,u}sec
members do not contain a valid value. For TX_RINGs, by default no timestamp
is generated!

See include/linux/net_tstamp.h and Documentation/networking/timestamping.rst
for more information on hardware timestamps.

Miscellaneous bits
==================

- Packet sockets work well together with Linux socket filters, thus you also
  might want to have a look at Documentation/networking/filter.rst

THANKS
======

   Jesse Brandeburg, for fixing my grammathical/spelling errors


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

=============
Page Pool API
=============

The page_pool allocator is optimized for the XDP mode that uses one frame
per-page, but it can fallback on the regular page allocator APIs.

Basic use involves replacing alloc_pages() calls with the
page_pool_alloc_pages() call.  Drivers should use page_pool_dev_alloc_pages()
replacing dev_alloc_pages().

API keeps track of inflight pages, in order to let API user know
when it is safe to free a page_pool object.  Thus, API users
must run page_pool_release_page() when a page is leaving the page_pool or
call page_pool_put_page() where appropriate in order to maintain correct
accounting.

API user must call page_pool_put_page() once on a page, as it
will either recycle the page, or in case of refcnt > 1, it will
release the DMA mapping and inflight state accounting.

Architecture overview
=====================

.. code-block:: none

    +------------------+
    |       Driver     |
    +------------------+
            ^
            |
            |
            |
            v
    +--------------------------------------------+
    |                request memory              |
    +--------------------------------------------+
        ^                                  ^
        |                                  |
        | Pool empty                       | Pool has entries
        |                                  |
        v                                  v
    +-----------------------+     +------------------------+
    | alloc (and map) pages |     |  get page from cache   |
    +-----------------------+     +------------------------+
                                    ^                    ^
                                    |                    |
                                    | cache available    | No entries, refill
                                    |                    | from ptr-ring
                                    |                    |
                                    v                    v
                          +-----------------+     +------------------+
                          |   Fast cache    |     |  ptr-ring cache  |
                          +-----------------+     +------------------+

API interface
=============
The number of pools created **must** match the number of hardware queues
unless hardware restrictions make that impossible. This would otherwise beat the
purpose of page pool, which is allocate pages fast from cache without locking.
This lockless guarantee naturally comes from running under a NAPI softirq.
The protection doesn't strictly have to be NAPI, any guarantee that allocating
a page will cause no race conditions is enough.

* page_pool_create(): Create a pool.
    * flags:      PP_FLAG_DMA_MAP, PP_FLAG_DMA_SYNC_DEV
    * order:      2^order pages on allocation
    * pool_size:  size of the ptr_ring
    * nid:        preferred NUMA node for allocation
    * dev:        struct device. Used on DMA operations
    * dma_dir:    DMA direction
    * max_len:    max DMA sync memory size
    * offset:     DMA address offset

* page_pool_put_page(): The outcome of this depends on the page refcnt. If the
  driver bumps the refcnt > 1 this will unmap the page. If the page refcnt is 1
  the allocator owns the page and will try to recycle it in one of the pool
  caches. If PP_FLAG_DMA_SYNC_DEV is set, the page will be synced for_device
  using dma_sync_single_range_for_device().

* page_pool_put_full_page(): Similar to page_pool_put_page(), but will DMA sync
  for the entire memory area configured in area pool->max_len.

* page_pool_recycle_direct(): Similar to page_pool_put_full_page() but caller
  must guarantee safe context (e.g NAPI), since it will recycle the page
  directly into the pool fast cache.

* page_pool_release_page(): Unmap the page (if mapped) and account for it on
  inflight counters.

* page_pool_dev_alloc_pages(): Get a page from the page allocator or page_pool
  caches.

* page_pool_get_dma_addr(): Retrieve the stored DMA address.

* page_pool_get_dma_dir(): Retrieve the stored DMA direction.

* page_pool_put_page_bulk(): Tries to refill a number of pages into the
  ptr_ring cache holding ptr_ring producer lock. If the ptr_ring is full,
  page_pool_put_page_bulk() will release leftover pages to the page allocator.
  page_pool_put_page_bulk() is suitable to be run inside the driver NAPI tx
  completion loop for the XDP_REDIRECT use case.
  Please note the caller must not use data area after running
  page_pool_put_page_bulk(), as this function overwrites it.

* page_pool_get_stats(): Retrieve statistics about the page_pool. This API
  is only available if the kernel has been configured with
  ``CONFIG_PAGE_POOL_STATS=y``. A pointer to a caller allocated ``struct
  page_pool_stats`` structure is passed to this API which is filled in. The
  caller can then report those stats to the user (perhaps via ethtool,
  debugfs, etc.). See below for an example usage of this API.

Stats API and structures
------------------------
If the kernel is configured with ``CONFIG_PAGE_POOL_STATS=y``, the API
``page_pool_get_stats()`` and structures described below are available. It
takes a  pointer to a ``struct page_pool`` and a pointer to a ``struct
page_pool_stats`` allocated by the caller.

The API will fill in the provided ``struct page_pool_stats`` with
statistics about the page_pool.

The stats structure has the following fields::

    struct page_pool_stats {
        struct page_pool_alloc_stats alloc_stats;
        struct page_pool_recycle_stats recycle_stats;
    };

The ``struct page_pool_alloc_stats`` has the following fields:
  * ``fast``: successful fast path allocations
  * ``slow``: slow path order-0 allocations
  * ``slow_high_order``: slow path high order allocations
  * ``empty``: ptr ring is empty, so a slow path allocation was forced.
  * ``refill``: an allocation which triggered a refill of the cache
  * ``waive``: pages obtained from the ptr ring that cannot be added to
    the cache due to a NUMA mismatch.

The ``struct page_pool_recycle_stats`` has the following fields:
  * ``cached``: recycling placed page in the page pool cache
  * ``cache_full``: page pool cache was full
  * ``ring``: page placed into the ptr ring
  * ``ring_full``: page released from page pool because the ptr ring was full
  * ``released_refcnt``: page released (and not recycled) because refcnt > 1

Coding examples
===============

Registration
------------

.. code-block:: c

    /* Page pool registration */
    struct page_pool_params pp_params = { 0 };
    struct xdp_rxq_info xdp_rxq;
    int err;

    pp_params.order = 0;
    /* internal DMA mapping in page_pool */
    pp_params.flags = PP_FLAG_DMA_MAP;
    pp_params.pool_size = DESC_NUM;
    pp_params.nid = NUMA_NO_NODE;
    pp_params.dev = priv->dev;
    pp_params.dma_dir = xdp_prog ? DMA_BIDIRECTIONAL : DMA_FROM_DEVICE;
    page_pool = page_pool_create(&pp_params);

    err = xdp_rxq_info_reg(&xdp_rxq, ndev, 0);
    if (err)
        goto err_out;

    err = xdp_rxq_info_reg_mem_model(&xdp_rxq, MEM_TYPE_PAGE_POOL, page_pool);
    if (err)
        goto err_out;

NAPI poller
-----------

.. code-block:: c

    /* NAPI Rx poller */
    enum dma_data_direction dma_dir;

    dma_dir = page_pool_get_dma_dir(dring->page_pool);
    while (done < budget) {
        if (some error)
            page_pool_recycle_direct(page_pool, page);
        if (packet_is_xdp) {
            if XDP_DROP:
                page_pool_recycle_direct(page_pool, page);
        } else (packet_is_skb) {
            page_pool_release_page(page_pool, page);
            new_page = page_pool_dev_alloc_pages(page_pool);
        }
    }

Stats
-----

.. code-block:: c

	#ifdef CONFIG_PAGE_POOL_STATS
	/* retrieve stats */
	struct page_pool_stats stats = { 0 };
	if (page_pool_get_stats(page_pool, &stats)) {
		/* perhaps the driver reports statistics with ethool */
		ethtool_print_allocation_stats(&stats.alloc_stats);
		ethtool_print_recycle_stats(&stats.recycle_stats);
	}
	#endif

Driver unload
-------------

.. code-block:: c

    /* Driver unload */
    page_pool_put_full_page(page_pool, page, false);
    xdp_rxq_info_unreg(&xdp_rxq);


code:
.. SPDX-License-Identifier: GPL-2.0
.. include:: <isonum.txt>

============================
Linux Phonet protocol family
============================

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

Phonet is a packet protocol used by Nokia cellular modems for both IPC
and RPC. With the Linux Phonet socket family, Linux host processes can
receive and send messages from/to the modem, or any other external
device attached to the modem. The modem takes care of routing.

Phonet packets can be exchanged through various hardware connections
depending on the device, such as:

  - USB with the CDC Phonet interface,
  - infrared,
  - Bluetooth,
  - an RS232 serial port (with a dedicated "FBUS" line discipline),
  - the SSI bus with some TI OMAP processors.

Packets format
--------------

Phonet packets have a common header as follows::

  struct phonethdr {
    uint8_t  pn_media;  /* Media type (link-layer identifier) */
    uint8_t  pn_rdev;   /* Receiver device ID */
    uint8_t  pn_sdev;   /* Sender device ID */
    uint8_t  pn_res;    /* Resource ID or function */
    uint16_t pn_length; /* Big-endian message byte length (minus 6) */
    uint8_t  pn_robj;   /* Receiver object ID */
    uint8_t  pn_sobj;   /* Sender object ID */
  };

On Linux, the link-layer header includes the pn_media byte (see below).
The next 7 bytes are part of the network-layer header.

The device ID is split: the 6 higher-order bits constitute the device
address, while the 2 lower-order bits are used for multiplexing, as are
the 8-bit object identifiers. As such, Phonet can be considered as a
network layer with 6 bits of address space and 10 bits for transport
protocol (much like port numbers in IP world).

The modem always has address number zero. All other device have a their
own 6-bit address.

Link layer
----------

Phonet links are always point-to-point links. The link layer header
consists of a single Phonet media type byte. It uniquely identifies the
link through which the packet is transmitted, from the modem's
perspective. Each Phonet network device shall prepend and set the media
type byte as appropriate. For convenience, a common phonet_header_ops
link-layer header operations structure is provided. It sets the
media type according to the network device hardware address.

Linux Phonet network interfaces support a dedicated link layer packets
type (ETH_P_PHONET) which is out of the Ethernet type range. They can
only send and receive Phonet packets.

The virtual TUN tunnel device driver can also be used for Phonet. This
requires IFF_TUN mode, _without_ the IFF_NO_PI flag. In this case,
there is no link-layer header, so there is no Phonet media type byte.

Note that Phonet interfaces are not allowed to re-order packets, so
only the (default) Linux FIFO qdisc should be used with them.

Network layer
-------------

The Phonet socket address family maps the Phonet packet header::

  struct sockaddr_pn {
    sa_family_t spn_family;    /* AF_PHONET */
    uint8_t     spn_obj;       /* Object ID */
    uint8_t     spn_dev;       /* Device ID */
    uint8_t     spn_resource;  /* Resource or function */
    uint8_t     spn_zero[...]; /* Padding */
  };

The resource field is only used when sending and receiving;
It is ignored by bind() and getsockname().

Low-level datagram protocol
---------------------------

Applications can send Phonet messages using the Phonet datagram socket
protocol from the PF_PHONET family. Each socket is bound to one of the
2^10 object IDs available, and can send and receive packets with any
other peer.

::

  struct sockaddr_pn addr = { .spn_family = AF_PHONET, };
  ssize_t len;
  socklen_t addrlen = sizeof(addr);
  int fd;

  fd = socket(PF_PHONET, SOCK_DGRAM, 0);
  bind(fd, (struct sockaddr *)&addr, sizeof(addr));
  /* ... */

  sendto(fd, msg, msglen, 0, (struct sockaddr *)&addr, sizeof(addr));
  len = recvfrom(fd, buf, sizeof(buf), 0,
		 (struct sockaddr *)&addr, &addrlen);

This protocol follows the SOCK_DGRAM connection-less semantics.
However, connect() and getpeername() are not supported, as they did
not seem useful with Phonet usages (could be added easily).

Resource subscription
---------------------

A Phonet datagram socket can be subscribed to any number of 8-bits
Phonet resources, as follow::

  uint32_t res = 0xXX;
  ioctl(fd, SIOCPNADDRESOURCE, &res);

Subscription is similarly cancelled using the SIOCPNDELRESOURCE I/O
control request, or when the socket is closed.

Note that no more than one socket can be subcribed to any given
resource at a time. If not, ioctl() will return EBUSY.

Phonet Pipe protocol
--------------------

The Phonet Pipe protocol is a simple sequenced packets protocol
with end-to-end congestion control. It uses the passive listening
socket paradigm. The listening socket is bound to an unique free object
ID. Each listening socket can handle up to 255 simultaneous
connections, one per accept()'d socket.

::

  int lfd, cfd;

  lfd = socket(PF_PHONET, SOCK_SEQPACKET, PN_PROTO_PIPE);
  listen (lfd, INT_MAX);

  /* ... */
  cfd = accept(lfd, NULL, NULL);
  for (;;)
  {
    char buf[...];
    ssize_t len = read(cfd, buf, sizeof(buf));

    /* ... */

    write(cfd, msg, msglen);
  }

Connections are traditionally established between two endpoints by a
"third party" application. This means that both endpoints are passive.

As of Linux kernel version 2.6.39, it is also possible to connect
two endpoints directly, using connect() on the active side. This is
intended to support the newer Nokia Wireless Modem API, as found in
e.g. the Nokia Slim Modem in the ST-Ericsson U8500 platform::

  struct sockaddr_spn spn;
  int fd;

  fd = socket(PF_PHONET, SOCK_SEQPACKET, PN_PROTO_PIPE);
  memset(&spn, 0, sizeof(spn));
  spn.spn_family = AF_PHONET;
  spn.spn_obj = ...;
  spn.spn_dev = ...;
  spn.spn_resource = 0xD9;
  connect(fd, (struct sockaddr *)&spn, sizeof(spn));
  /* normal I/O here ... */
  close(fd);

.. Warning:

   When polling a connected pipe socket for writability, there is an
   intrinsic race condition whereby writability might be lost between the
   polling and the writing system calls. In this case, the socket will
   block until write becomes possible again, unless non-blocking mode
   is enabled.

The pipe protocol provides two socket options at the SOL_PNPIPE level:

  PNPIPE_ENCAP accepts one integer value (int) of:

    PNPIPE_ENCAP_NONE:
      The socket operates normally (default).

    PNPIPE_ENCAP_IP:
      The socket is used as a backend for a virtual IP
      interface. This requires CAP_NET_ADMIN capability. GPRS data
      support on Nokia modems can use this. Note that the socket cannot
      be reliably poll()'d or read() from while in this mode.

  PNPIPE_IFINDEX
      is a read-only integer value. It contains the
      interface index of the network interface created by PNPIPE_ENCAP,
      or zero if encapsulation is off.

  PNPIPE_HANDLE
      is a read-only integer value. It contains the underlying
      identifier ("pipe handle") of the pipe. This is only defined for
      socket descriptors that are already connected or being connected.

Authors
-------

Linux Phonet was initially written by Sakari Ailus.

Other contributors include Mikä Liljeberg, Andras Domokos,
Carlos Chinea and Rémi Denis-Courmont.

Copyright |copy| 2008 Nokia Corporation.