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

.. _networking-filter:

=======================================================
Linux Socket Filtering aka Berkeley Packet Filter (BPF)
=======================================================

Notice
------

This file used to document the eBPF format and mechanisms even when not
related to socket filtering.  The ../bpf/index.rst has more details
on eBPF.

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

Linux Socket Filtering (LSF) is derived from the Berkeley Packet Filter.
Though there are some distinct differences between the BSD and Linux
Kernel filtering, but when we speak of BPF or LSF in Linux context, we
mean the very same mechanism of filtering in the Linux kernel.

BPF allows a user-space program to attach a filter onto any socket and
allow or disallow certain types of data to come through the socket. LSF
follows exactly the same filter code structure as BSD's BPF, so referring
to the BSD bpf.4 manpage is very helpful in creating filters.

On Linux, BPF is much simpler than on BSD. One does not have to worry
about devices or anything like that. You simply create your filter code,
send it to the kernel via the SO_ATTACH_FILTER option and if your filter
code passes the kernel check on it, you then immediately begin filtering
data on that socket.

You can also detach filters from your socket via the SO_DETACH_FILTER
option. This will probably not be used much since when you close a socket
that has a filter on it the filter is automagically removed. The other
less common case may be adding a different filter on the same socket where
you had another filter that is still running: the kernel takes care of
removing the old one and placing your new one in its place, assuming your
filter has passed the checks, otherwise if it fails the old filter will
remain on that socket.

SO_LOCK_FILTER option allows to lock the filter attached to a socket. Once
set, a filter cannot be removed or changed. This allows one process to
setup a socket, attach a filter, lock it then drop privileges and be
assured that the filter will be kept until the socket is closed.

The biggest user of this construct might be libpcap. Issuing a high-level
filter command like `tcpdump -i em1 port 22` passes through the libpcap
internal compiler that generates a structure that can eventually be loaded
via SO_ATTACH_FILTER to the kernel. `tcpdump -i em1 port 22 -ddd`
displays what is being placed into this structure.

Although we were only speaking about sockets here, BPF in Linux is used
in many more places. There's xt_bpf for netfilter, cls_bpf in the kernel
qdisc layer, SECCOMP-BPF (SECure COMPuting [1]_), and lots of other places
such as team driver, PTP code, etc where BPF is being used.

.. [1] Documentation/userspace-api/seccomp_filter.rst

Original BPF paper:

Steven McCanne and Van Jacobson. 1993. The BSD packet filter: a new
architecture for user-level packet capture. In Proceedings of the
USENIX Winter 1993 Conference Proceedings on USENIX Winter 1993
Conference Proceedings (USENIX'93). USENIX Association, Berkeley,
CA, USA, 2-2. [http://www.tcpdump.org/papers/bpf-usenix93.pdf]

Structure
---------

User space applications include <linux/filter.h> which contains the
following relevant structures::

	struct sock_filter {	/* Filter block */
		__u16	code;   /* Actual filter code */
		__u8	jt;	/* Jump true */
		__u8	jf;	/* Jump false */
		__u32	k;      /* Generic multiuse field */
	};

Such a structure is assembled as an array of 4-tuples, that contains
a code, jt, jf and k value. jt and jf are jump offsets and k a generic
value to be used for a provided code::

	struct sock_fprog {			/* Required for SO_ATTACH_FILTER. */
		unsigned short		   len;	/* Number of filter blocks */
		struct sock_filter __user *filter;
	};

For socket filtering, a pointer to this structure (as shown in
follow-up example) is being passed to the kernel through setsockopt(2).

Example
-------

::

    #include <sys/socket.h>
    #include <sys/types.h>
    #include <arpa/inet.h>
    #include <linux/if_ether.h>
    /* ... */

    /* From the example above: tcpdump -i em1 port 22 -dd */
    struct sock_filter code[] = {
	    { 0x28,  0,  0, 0x0000000c },
	    { 0x15,  0,  8, 0x000086dd },
	    { 0x30,  0,  0, 0x00000014 },
	    { 0x15,  2,  0, 0x00000084 },
	    { 0x15,  1,  0, 0x00000006 },
	    { 0x15,  0, 17, 0x00000011 },
	    { 0x28,  0,  0, 0x00000036 },
	    { 0x15, 14,  0, 0x00000016 },
	    { 0x28,  0,  0, 0x00000038 },
	    { 0x15, 12, 13, 0x00000016 },
	    { 0x15,  0, 12, 0x00000800 },
	    { 0x30,  0,  0, 0x00000017 },
	    { 0x15,  2,  0, 0x00000084 },
	    { 0x15,  1,  0, 0x00000006 },
	    { 0x15,  0,  8, 0x00000011 },
	    { 0x28,  0,  0, 0x00000014 },
	    { 0x45,  6,  0, 0x00001fff },
	    { 0xb1,  0,  0, 0x0000000e },
	    { 0x48,  0,  0, 0x0000000e },
	    { 0x15,  2,  0, 0x00000016 },
	    { 0x48,  0,  0, 0x00000010 },
	    { 0x15,  0,  1, 0x00000016 },
	    { 0x06,  0,  0, 0x0000ffff },
	    { 0x06,  0,  0, 0x00000000 },
    };

    struct sock_fprog bpf = {
	    .len = ARRAY_SIZE(code),
	    .filter = code,
    };

    sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
    if (sock < 0)
	    /* ... bail out ... */

    ret = setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf));
    if (ret < 0)
	    /* ... bail out ... */

    /* ... */
    close(sock);

The above example code attaches a socket filter for a PF_PACKET socket
in order to let all IPv4/IPv6 packets with port 22 pass. The rest will
be dropped for this socket.

The setsockopt(2) call to SO_DETACH_FILTER doesn't need any arguments
and SO_LOCK_FILTER for preventing the filter to be detached, takes an
integer value with 0 or 1.

Note that socket filters are not restricted to PF_PACKET sockets only,
but can also be used on other socket families.

Summary of system calls:

 * setsockopt(sockfd, SOL_SOCKET, SO_ATTACH_FILTER, &val, sizeof(val));
 * setsockopt(sockfd, SOL_SOCKET, SO_DETACH_FILTER, &val, sizeof(val));
 * setsockopt(sockfd, SOL_SOCKET, SO_LOCK_FILTER,   &val, sizeof(val));

Normally, most use cases for socket filtering on packet sockets will be
covered by libpcap in high-level syntax, so as an application developer
you should stick to that. libpcap wraps its own layer around all that.

Unless i) using/linking to libpcap is not an option, ii) the required BPF
filters use Linux extensions that are not supported by libpcap's compiler,
iii) a filter might be more complex and not cleanly implementable with
libpcap's compiler, or iv) particular filter codes should be optimized
differently than libpcap's internal compiler does; then in such cases
writing such a filter "by hand" can be of an alternative. For example,
xt_bpf and cls_bpf users might have requirements that could result in
more complex filter code, or one that cannot be expressed with libpcap
(e.g. different return codes for various code paths). Moreover, BPF JIT
implementors may wish to manually write test cases and thus need low-level
access to BPF code as well.

BPF engine and instruction set
------------------------------

Under tools/bpf/ there's a small helper tool called bpf_asm which can
be used to write low-level filters for example scenarios mentioned in the
previous section. Asm-like syntax mentioned here has been implemented in
bpf_asm and will be used for further explanations (instead of dealing with
less readable opcodes directly, principles are the same). The syntax is
closely modelled after Steven McCanne's and Van Jacobson's BPF paper.

The BPF architecture consists of the following basic elements:

  =======          ====================================================
  Element          Description
  =======          ====================================================
  A                32 bit wide accumulator
  X                32 bit wide X register
  M[]              16 x 32 bit wide misc registers aka "scratch memory
		   store", addressable from 0 to 15
  =======          ====================================================

A program, that is translated by bpf_asm into "opcodes" is an array that
consists of the following elements (as already mentioned)::

  op:16, jt:8, jf:8, k:32

The element op is a 16 bit wide opcode that has a particular instruction
encoded. jt and jf are two 8 bit wide jump targets, one for condition
"jump if true", the other one "jump if false". Eventually, element k
contains a miscellaneous argument that can be interpreted in different
ways depending on the given instruction in op.

The instruction set consists of load, store, branch, alu, miscellaneous
and return instructions that are also represented in bpf_asm syntax. This
table lists all bpf_asm instructions available resp. what their underlying
opcodes as defined in linux/filter.h stand for:

  ===========      ===================  =====================
  Instruction      Addressing mode      Description
  ===========      ===================  =====================
  ld               1, 2, 3, 4, 12       Load word into A
  ldi              4                    Load word into A
  ldh              1, 2                 Load half-word into A
  ldb              1, 2                 Load byte into A
  ldx              3, 4, 5, 12          Load word into X
  ldxi             4                    Load word into X
  ldxb             5                    Load byte into X

  st               3                    Store A into M[]
  stx              3                    Store X into M[]

  jmp              6                    Jump to label
  ja               6                    Jump to label
  jeq              7, 8, 9, 10          Jump on A == <x>
  jneq             9, 10                Jump on A != <x>
  jne              9, 10                Jump on A != <x>
  jlt              9, 10                Jump on A <  <x>
  jle              9, 10                Jump on A <= <x>
  jgt              7, 8, 9, 10          Jump on A >  <x>
  jge              7, 8, 9, 10          Jump on A >= <x>
  jset             7, 8, 9, 10          Jump on A &  <x>

  add              0, 4                 A + <x>
  sub              0, 4                 A - <x>
  mul              0, 4                 A * <x>
  div              0, 4                 A / <x>
  mod              0, 4                 A % <x>
  neg                                   !A
  and              0, 4                 A & <x>
  or               0, 4                 A | <x>
  xor              0, 4                 A ^ <x>
  lsh              0, 4                 A << <x>
  rsh              0, 4                 A >> <x>

  tax                                   Copy A into X
  txa                                   Copy X into A

  ret              4, 11                Return
  ===========      ===================  =====================

The next table shows addressing formats from the 2nd column:

  ===============  ===================  ===============================================
  Addressing mode  Syntax               Description
  ===============  ===================  ===============================================
   0               x/%x                 Register X
   1               [k]                  BHW at byte offset k in the packet
   2               [x + k]              BHW at the offset X + k in the packet
   3               M[k]                 Word at offset k in M[]
   4               #k                   Literal value stored in k
   5               4*([k]&0xf)          Lower nibble * 4 at byte offset k in the packet
   6               L                    Jump label L
   7               #k,Lt,Lf             Jump to Lt if true, otherwise jump to Lf
   8               x/%x,Lt,Lf           Jump to Lt if true, otherwise jump to Lf
   9               #k,Lt                Jump to Lt if predicate is true
  10               x/%x,Lt              Jump to Lt if predicate is true
  11               a/%a                 Accumulator A
  12               extension            BPF extension
  ===============  ===================  ===============================================

The Linux kernel also has a couple of BPF extensions that are used along
with the class of load instructions by "overloading" the k argument with
a negative offset + a particular extension offset. The result of such BPF
extensions are loaded into A.

Possible BPF extensions are shown in the following table:

  ===================================   =================================================
  Extension                             Description
  ===================================   =================================================
  len                                   skb->len
  proto                                 skb->protocol
  type                                  skb->pkt_type
  poff                                  Payload start offset
  ifidx                                 skb->dev->ifindex
  nla                                   Netlink attribute of type X with offset A
  nlan                                  Nested Netlink attribute of type X with offset A
  mark                                  skb->mark
  queue                                 skb->queue_mapping
  hatype                                skb->dev->type
  rxhash                                skb->hash
  cpu                                   raw_smp_processor_id()
  vlan_tci                              skb_vlan_tag_get(skb)
  vlan_avail                            skb_vlan_tag_present(skb)
  vlan_tpid                             skb->vlan_proto
  rand                                  get_random_u32()
  ===================================   =================================================

These extensions can also be prefixed with '#'.
Examples for low-level BPF:

**ARP packets**::

  ldh [12]
  jne #0x806, drop
  ret #-1
  drop: ret #0

**IPv4 TCP packets**::

  ldh [12]
  jne #0x800, drop
  ldb [23]
  jneq #6, drop
  ret #-1
  drop: ret #0

**icmp random packet sampling, 1 in 4**::

  ldh [12]
  jne #0x800, drop
  ldb [23]
  jneq #1, drop
  # get a random uint32 number
  ld rand
  mod #4
  jneq #1, drop
  ret #-1
  drop: ret #0

**SECCOMP filter example**::

  ld [4]                  /* offsetof(struct seccomp_data, arch) */
  jne #0xc000003e, bad    /* AUDIT_ARCH_X86_64 */
  ld [0]                  /* offsetof(struct seccomp_data, nr) */
  jeq #15, good           /* __NR_rt_sigreturn */
  jeq #231, good          /* __NR_exit_group */
  jeq #60, good           /* __NR_exit */
  jeq #0, good            /* __NR_read */
  jeq #1, good            /* __NR_write */
  jeq #5, good            /* __NR_fstat */
  jeq #9, good            /* __NR_mmap */
  jeq #14, good           /* __NR_rt_sigprocmask */
  jeq #13, good           /* __NR_rt_sigaction */
  jeq #35, good           /* __NR_nanosleep */
  bad: ret #0             /* SECCOMP_RET_KILL_THREAD */
  good: ret #0x7fff0000   /* SECCOMP_RET_ALLOW */

Examples for low-level BPF extension:

**Packet for interface index 13**::

  ld ifidx
  jneq #13, drop
  ret #-1
  drop: ret #0

**(Accelerated) VLAN w/ id 10**::

  ld vlan_tci
  jneq #10, drop
  ret #-1
  drop: ret #0

The above example code can be placed into a file (here called "foo"), and
then be passed to the bpf_asm tool for generating opcodes, output that xt_bpf
and cls_bpf understands and can directly be loaded with. Example with above
ARP code::

    $ ./bpf_asm foo
    4,40 0 0 12,21 0 1 2054,6 0 0 4294967295,6 0 0 0,

In copy and paste C-like output::

    $ ./bpf_asm -c foo
    { 0x28,  0,  0, 0x0000000c },
    { 0x15,  0,  1, 0x00000806 },
    { 0x06,  0,  0, 0xffffffff },
    { 0x06,  0,  0, 0000000000 },

In particular, as usage with xt_bpf or cls_bpf can result in more complex BPF
filters that might not be obvious at first, it's good to test filters before
attaching to a live system. For that purpose, there's a small tool called
bpf_dbg under tools/bpf/ in the kernel source directory. This debugger allows
for testing BPF filters against given pcap files, single stepping through the
BPF code on the pcap's packets and to do BPF machine register dumps.

Starting bpf_dbg is trivial and just requires issuing::

    # ./bpf_dbg

In case input and output do not equal stdin/stdout, bpf_dbg takes an
alternative stdin source as a first argument, and an alternative stdout
sink as a second one, e.g. `./bpf_dbg test_in.txt test_out.txt`.

Other than that, a particular libreadline configuration can be set via
file "~/.bpf_dbg_init" and the command history is stored in the file
"~/.bpf_dbg_history".

Interaction in bpf_dbg happens through a shell that also has auto-completion
support (follow-up example commands starting with '>' denote bpf_dbg shell).
The usual workflow would be to ...

* load bpf 6,40 0 0 12,21 0 3 2048,48 0 0 23,21 0 1 1,6 0 0 65535,6 0 0 0
  Loads a BPF filter from standard output of bpf_asm, or transformed via
  e.g. ``tcpdump -iem1 -ddd port 22 | tr '\n' ','``. Note that for JIT
  debugging (next section), this command creates a temporary socket and
  loads the BPF code into the kernel. Thus, this will also be useful for
  JIT developers.

* load pcap foo.pcap

  Loads standard tcpdump pcap file.

* run [<n>]

bpf passes:1 fails:9
  Runs through all packets from a pcap to account how many passes and fails
  the filter will generate. A limit of packets to traverse can be given.

* disassemble::

	l0:	ldh [12]
	l1:	jeq #0x800, l2, l5
	l2:	ldb [23]
	l3:	jeq #0x1, l4, l5
	l4:	ret #0xffff
	l5:	ret #0

  Prints out BPF code disassembly.

* dump::

	/* { op, jt, jf, k }, */
	{ 0x28,  0,  0, 0x0000000c },
	{ 0x15,  0,  3, 0x00000800 },
	{ 0x30,  0,  0, 0x00000017 },
	{ 0x15,  0,  1, 0x00000001 },
	{ 0x06,  0,  0, 0x0000ffff },
	{ 0x06,  0,  0, 0000000000 },

  Prints out C-style BPF code dump.

* breakpoint 0::

	breakpoint at: l0:	ldh [12]

* breakpoint 1::

	breakpoint at: l1:	jeq #0x800, l2, l5

  ...

  Sets breakpoints at particular BPF instructions. Issuing a `run` command
  will walk through the pcap file continuing from the current packet and
  break when a breakpoint is being hit (another `run` will continue from
  the currently active breakpoint executing next instructions):

  * run::

	-- register dump --
	pc:       [0]                       <-- program counter
	code:     [40] jt[0] jf[0] k[12]    <-- plain BPF code of current instruction
	curr:     l0:	ldh [12]              <-- disassembly of current instruction
	A:        [00000000][0]             <-- content of A (hex, decimal)
	X:        [00000000][0]             <-- content of X (hex, decimal)
	M[0,15]:  [00000000][0]             <-- folded content of M (hex, decimal)
	-- packet dump --                   <-- Current packet from pcap (hex)
	len: 42
	    0: 00 19 cb 55 55 a4 00 14 a4 43 78 69 08 06 00 01
	16: 08 00 06 04 00 01 00 14 a4 43 78 69 0a 3b 01 26
	32: 00 00 00 00 00 00 0a 3b 01 01
	(breakpoint)
	>

  * breakpoint::

	breakpoints: 0 1

    Prints currently set breakpoints.

* step [-<n>, +<n>]

  Performs single stepping through the BPF program from the current pc
  offset. Thus, on each step invocation, above register dump is issued.
  This can go forwards and backwards in time, a plain `step` will break
  on the next BPF instruction, thus +1. (No `run` needs to be issued here.)

* select <n>

  Selects a given packet from the pcap file to continue from. Thus, on
  the next `run` or `step`, the BPF program is being evaluated against
  the user pre-selected packet. Numbering starts just as in Wireshark
  with index 1.

* quit

  Exits bpf_dbg.

JIT compiler
------------

The Linux kernel has a built-in BPF JIT compiler for x86_64, SPARC,
PowerPC, ARM, ARM64, MIPS, RISC-V and s390 and can be enabled through
CONFIG_BPF_JIT. The JIT compiler is transparently invoked for each
attached filter from user space or for internal kernel users if it has
been previously enabled by root::

  echo 1 > /proc/sys/net/core/bpf_jit_enable

For JIT developers, doing audits etc, each compile run can output the generated
opcode image into the kernel log via::

  echo 2 > /proc/sys/net/core/bpf_jit_enable

Example output from dmesg::

    [ 3389.935842] flen=6 proglen=70 pass=3 image=ffffffffa0069c8f
    [ 3389.935847] JIT code: 00000000: 55 48 89 e5 48 83 ec 60 48 89 5d f8 44 8b 4f 68
    [ 3389.935849] JIT code: 00000010: 44 2b 4f 6c 4c 8b 87 d8 00 00 00 be 0c 00 00 00
    [ 3389.935850] JIT code: 00000020: e8 1d 94 ff e0 3d 00 08 00 00 75 16 be 17 00 00
    [ 3389.935851] JIT code: 00000030: 00 e8 28 94 ff e0 83 f8 01 75 07 b8 ff ff 00 00
    [ 3389.935852] JIT code: 00000040: eb 02 31 c0 c9 c3

When CONFIG_BPF_JIT_ALWAYS_ON is enabled, bpf_jit_enable is permanently set to 1 and
setting any other value than that will return in failure. This is even the case for
setting bpf_jit_enable to 2, since dumping the final JIT image into the kernel log
is discouraged and introspection through bpftool (under tools/bpf/bpftool/) is the
generally recommended approach instead.

In the kernel source tree under tools/bpf/, there's bpf_jit_disasm for
generating disassembly out of the kernel log's hexdump::

	# ./bpf_jit_disasm
	70 bytes emitted from JIT compiler (pass:3, flen:6)
	ffffffffa0069c8f + <x>:
	0:	push   %rbp
	1:	mov    %rsp,%rbp
	4:	sub    $0x60,%rsp
	8:	mov    %rbx,-0x8(%rbp)
	c:	mov    0x68(%rdi),%r9d
	10:	sub    0x6c(%rdi),%r9d
	14:	mov    0xd8(%rdi),%r8
	1b:	mov    $0xc,%esi
	20:	callq  0xffffffffe0ff9442
	25:	cmp    $0x800,%eax
	2a:	jne    0x0000000000000042
	2c:	mov    $0x17,%esi
	31:	callq  0xffffffffe0ff945e
	36:	cmp    $0x1,%eax
	39:	jne    0x0000000000000042
	3b:	mov    $0xffff,%eax
	40:	jmp    0x0000000000000044
	42:	xor    %eax,%eax
	44:	leaveq
	45:	retq

	Issuing option `-o` will "annotate" opcodes to resulting assembler
	instructions, which can be very useful for JIT developers:

	# ./bpf_jit_disasm -o
	70 bytes emitted from JIT compiler (pass:3, flen:6)
	ffffffffa0069c8f + <x>:
	0:	push   %rbp
		55
	1:	mov    %rsp,%rbp
		48 89 e5
	4:	sub    $0x60,%rsp
		48 83 ec 60
	8:	mov    %rbx,-0x8(%rbp)
		48 89 5d f8
	c:	mov    0x68(%rdi),%r9d
		44 8b 4f 68
	10:	sub    0x6c(%rdi),%r9d
		44 2b 4f 6c
	14:	mov    0xd8(%rdi),%r8
		4c 8b 87 d8 00 00 00
	1b:	mov    $0xc,%esi
		be 0c 00 00 00
	20:	callq  0xffffffffe0ff9442
		e8 1d 94 ff e0
	25:	cmp    $0x800,%eax
		3d 00 08 00 00
	2a:	jne    0x0000000000000042
		75 16
	2c:	mov    $0x17,%esi
		be 17 00 00 00
	31:	callq  0xffffffffe0ff945e
		e8 28 94 ff e0
	36:	cmp    $0x1,%eax
		83 f8 01
	39:	jne    0x0000000000000042
		75 07
	3b:	mov    $0xffff,%eax
		b8 ff ff 00 00
	40:	jmp    0x0000000000000044
		eb 02
	42:	xor    %eax,%eax
		31 c0
	44:	leaveq
		c9
	45:	retq
		c3

For BPF JIT developers, bpf_jit_disasm, bpf_asm and bpf_dbg provides a useful
toolchain for developing and testing the kernel's JIT compiler.

BPF kernel internals
--------------------
Internally, for the kernel interpreter, a different instruction set
format with similar underlying principles from BPF described in previous
paragraphs is being used. However, the instruction set format is modelled
closer to the underlying architecture to mimic native instruction sets, so
that a better performance can be achieved (more details later). This new
ISA is called eBPF.  See the ../bpf/index.rst for details.  (Note: eBPF which
originates from [e]xtended BPF is not the same as BPF extensions! While
eBPF is an ISA, BPF extensions date back to classic BPF's 'overloading'
of BPF_LD | BPF_{B,H,W} | BPF_ABS instruction.)

The new instruction set was originally designed with the possible goal in
mind to write programs in "restricted C" and compile into eBPF with a optional
GCC/LLVM backend, so that it can just-in-time map to modern 64-bit CPUs with
minimal performance overhead over two steps, that is, C -> eBPF -> native code.

Currently, the new format is being used for running user BPF programs, which
includes seccomp BPF, classic socket filters, cls_bpf traffic classifier,
team driver's classifier for its load-balancing mode, netfilter's xt_bpf
extension, PTP dissector/classifier, and much more. They are all internally
converted by the kernel into the new instruction set representation and run
in the eBPF interpreter. For in-kernel handlers, this all works transparently
by using bpf_prog_create() for setting up the filter, resp.
bpf_prog_destroy() for destroying it. The function
bpf_prog_run(filter, ctx) transparently invokes eBPF interpreter or JITed
code to run the filter. 'filter' is a pointer to struct bpf_prog that we
got from bpf_prog_create(), and 'ctx' the given context (e.g.
skb pointer). All constraints and restrictions from bpf_check_classic() apply
before a conversion to the new layout is being done behind the scenes!

Currently, the classic BPF format is being used for JITing on most
32-bit architectures, whereas x86-64, aarch64, s390x, powerpc64,
sparc64, arm32, riscv64, riscv32 perform JIT compilation from eBPF
instruction set.

Testing
-------

Next to the BPF toolchain, the kernel also ships a test module that contains
various test cases for classic and eBPF that can be executed against
the BPF interpreter and JIT compiler. It can be found in lib/test_bpf.c and
enabled via Kconfig::

  CONFIG_TEST_BPF=m

After the module has been built and installed, the test suite can be executed
via insmod or modprobe against 'test_bpf' module. Results of the test cases
including timings in nsec can be found in the kernel log (dmesg).

Misc
----

Also trinity, the Linux syscall fuzzer, has built-in support for BPF and
SECCOMP-BPF kernel fuzzing.

Written by
----------

The document was written in the hope that it is found useful and in order
to give potential BPF hackers or security auditors a better overview of
the underlying architecture.

- Jay Schulist <jschlst@samba.org>
- Daniel Borkmann <daniel@iogearbox.net>
- Alexei Starovoitov <ast@kernel.org>


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

===============================================
Generic networking statistics for netlink users
===============================================

Statistic counters are grouped into structs:

==================== ===================== =====================
Struct               TLV type              Description
==================== ===================== =====================
gnet_stats_basic     TCA_STATS_BASIC       Basic statistics
gnet_stats_rate_est  TCA_STATS_RATE_EST    Rate estimator
gnet_stats_queue     TCA_STATS_QUEUE       Queue statistics
none                 TCA_STATS_APP         Application specific
==================== ===================== =====================

Collecting:
-----------

Declare the statistic structs you need::

	struct mystruct {
		struct gnet_stats_basic	bstats;
		struct gnet_stats_queue	qstats;
		...
	};

Update statistics, in dequeue() methods only, (while owning qdisc->running)::

	mystruct->tstats.packet++;
	mystruct->qstats.backlog += skb->pkt_len;

Export to userspace (Dump):
---------------------------

::

    my_dumping_routine(struct sk_buff *skb, ...)
    {
	    struct gnet_dump dump;

	    if (gnet_stats_start_copy(skb, TCA_STATS2, &mystruct->lock, &dump,
				    TCA_PAD) < 0)
		    goto rtattr_failure;

	    if (gnet_stats_copy_basic(&dump, &mystruct->bstats) < 0 ||
		gnet_stats_copy_queue(&dump, &mystruct->qstats) < 0 ||
		    gnet_stats_copy_app(&dump, &xstats, sizeof(xstats)) < 0)
		    goto rtattr_failure;

	    if (gnet_stats_finish_copy(&dump) < 0)
		    goto rtattr_failure;
	    ...
    }

TCA_STATS/TCA_XSTATS backward compatibility:
--------------------------------------------

Prior users of struct tc_stats and xstats can maintain backward
compatibility by calling the compat wrappers to keep providing the
existing TLV types::

    my_dumping_routine(struct sk_buff *skb, ...)
    {
	if (gnet_stats_start_copy_compat(skb, TCA_STATS2, TCA_STATS,
					TCA_XSTATS, &mystruct->lock, &dump,
					TCA_PAD) < 0)
		    goto rtattr_failure;
	    ...
    }

A struct tc_stats will be filled out during gnet_stats_copy_* calls
and appended to the skb. TCA_XSTATS is provided if gnet_stats_copy_app
was called.

Locking:
--------

Locks are taken before writing and released once all statistics have
been written. Locks are always released in case of an error. You
are responsible for making sure that the lock is initialized.

Rate Estimator:
---------------

0) Prepare an estimator attribute. Most likely this would be in user
   space. The value of this TLV should contain a tc_estimator structure.
   As usual, such a TLV needs to be 32 bit aligned and therefore the
   length needs to be appropriately set, etc. The estimator interval
   and ewma log need to be converted to the appropriate values.
   tc_estimator.c::tc_setup_estimator() is advisable to be used as the
   conversion routine. It does a few clever things. It takes a time
   interval in microsecs, a time constant also in microsecs and a struct
   tc_estimator to  be populated. The returned tc_estimator can be
   transported to the kernel.  Transfer such a structure in a TLV of type
   TCA_RATE to your code in the kernel.

In the kernel when setting up:

1) make sure you have basic stats and rate stats setup first.
2) make sure you have initialized stats lock that is used to setup such
   stats.
3) Now initialize a new estimator::

    int ret = gen_new_estimator(my_basicstats,my_rate_est_stats,
	mystats_lock, attr_with_tcestimator_struct);

    if ret == 0
	success
    else
	failed

From now on, every time you dump my_rate_est_stats it will contain
up-to-date info.

Once you are done, call gen_kill_estimator(my_basicstats,
my_rate_est_stats) Make sure that my_basicstats and my_rate_est_stats
are still valid (i.e still exist) at the time of making this call.

Authors:
--------
- Thomas Graf <tgraf@suug.ch>
- Jamal Hadi Salim <hadi@cyberus.ca>

repo_name: angery/linux


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

==================
Generic HDLC layer
==================

Krzysztof Halasa <khc@pm.waw.pl>

Generic HDLC layer currently supports:

1. Frame Relay (ANSI, CCITT, Cisco and no LMI)

   - Normal (routed) and Ethernet-bridged (Ethernet device emulation)
     interfaces can share a single PVC.
   - ARP support (no InARP support in the kernel - there is an
     experimental InARP user-space daemon available on:
     http://www.kernel.org/pub/linux/utils/net/hdlc/).

2. raw HDLC - either IP (IPv4) interface or Ethernet device emulation
3. Cisco HDLC
4. PPP
5. X.25 (uses X.25 routines).

Generic HDLC is a protocol driver only - it needs a low-level driver
for your particular hardware.

Ethernet device emulation (using HDLC or Frame-Relay PVC) is compatible
with IEEE 802.1Q (VLANs) and 802.1D (Ethernet bridging).

Make sure the hdlc.o and the hardware driver are loaded. It should
create a number of "hdlc" (hdlc0 etc) network devices, one for each
WAN port. You'll need the "sethdlc" utility, get it from:

	http://www.kernel.org/pub/linux/utils/net/hdlc/

Compile sethdlc.c utility::

	gcc -O2 -Wall -o sethdlc sethdlc.c

Make sure you're using a correct version of sethdlc for your kernel.

Use sethdlc to set physical interface, clock rate, HDLC mode used,
and add any required PVCs if using Frame Relay.
Usually you want something like::

	sethdlc hdlc0 clock int rate 128000
	sethdlc hdlc0 cisco interval 10 timeout 25

or::

	sethdlc hdlc0 rs232 clock ext
	sethdlc hdlc0 fr lmi ansi
	sethdlc hdlc0 create 99
	ifconfig hdlc0 up
	ifconfig pvc0 localIP pointopoint remoteIP

In Frame Relay mode, ifconfig master hdlc device up (without assigning
any IP address to it) before using pvc devices.

Setting interface:

* v35 | rs232 | x21 | t1 | e1
    - sets physical interface for a given port
      if the card has software-selectable interfaces
  loopback
    - activate hardware loopback (for testing only)
* clock ext
    - both RX clock and TX clock external
* clock int
    - both RX clock and TX clock internal
* clock txint
    - RX clock external, TX clock internal
* clock txfromrx
    - RX clock external, TX clock derived from RX clock
* rate
    - sets clock rate in bps (for "int" or "txint" clock only)

Setting protocol:

* hdlc - sets raw HDLC (IP-only) mode

  nrz / nrzi / fm-mark / fm-space / manchester - sets transmission code

  no-parity / crc16 / crc16-pr0 (CRC16 with preset zeros) / crc32-itu

  crc16-itu (CRC16 with ITU-T polynomial) / crc16-itu-pr0 - sets parity

* hdlc-eth - Ethernet device emulation using HDLC. Parity and encoding
  as above.

* cisco - sets Cisco HDLC mode (IP, IPv6 and IPX supported)

  interval - time in seconds between keepalive packets

  timeout - time in seconds after last received keepalive packet before
	    we assume the link is down

* ppp - sets synchronous PPP mode

* x25 - sets X.25 mode

* fr - Frame Relay mode

  lmi ansi / ccitt / cisco / none - LMI (link management) type

  dce - Frame Relay DCE (network) side LMI instead of default DTE (user).

  It has nothing to do with clocks!

  - t391 - link integrity verification polling timer (in seconds) - user
  - t392 - polling verification timer (in seconds) - network
  - n391 - full status polling counter - user
  - n392 - error threshold - both user and network
  - n393 - monitored events count - both user and network

Frame-Relay only:

* create n | delete n - adds / deletes PVC interface with DLCI #n.
  Newly created interface will be named pvc0, pvc1 etc.

* create ether n | delete ether n - adds a device for Ethernet-bridged
  frames. The device will be named pvceth0, pvceth1 etc.

Board-specific issues
---------------------

n2.o and c101.o need parameters to work::

	insmod n2 hw=io,irq,ram,ports[:io,irq,...]

example::

	insmod n2 hw=0x300,10,0xD0000,01

or::

	insmod c101 hw=irq,ram[:irq,...]

example::

	insmod c101 hw=9,0xdc000

If built into the kernel, these drivers need kernel (command line) parameters::

	n2.hw=io,irq,ram,ports:...

or::

	c101.hw=irq,ram:...

If you have a problem with N2, C101 or PLX200SYN card, you can issue the
"private" command to see port's packet descriptor rings (in kernel logs)::

	sethdlc hdlc0 private

The hardware driver has to be build with #define DEBUG_RINGS.
Attaching this info to bug reports would be helpful. Anyway, let me know
if you have problems using this.

For patches and other info look at:
<http://www.kernel.org/pub/linux/utils/net/hdlc/>.


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

===============
Generic Netlink
===============

A wiki document on how to use Generic Netlink can be found here:

 * https://wiki.linuxfoundation.org/networking/generic_netlink_howto


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

=====================================
The Linux kernel GTP tunneling module
=====================================

Documentation by
		 Harald Welte <laforge@gnumonks.org> and
		 Andreas Schultz <aschultz@tpip.net>

In 'drivers/net/gtp.c' you are finding a kernel-level implementation
of a GTP tunnel endpoint.

What is GTP
===========

GTP is the Generic Tunnel Protocol, which is a 3GPP protocol used for
tunneling User-IP payload between a mobile station (phone, modem)
and the interconnection between an external packet data network (such
as the internet).

So when you start a 'data connection' from your mobile phone, the
phone will use the control plane to signal for the establishment of
such a tunnel between that external data network and the phone.  The
tunnel endpoints thus reside on the phone and in the gateway.  All
intermediate nodes just transport the encapsulated packet.

The phone itself does not implement GTP but uses some other
technology-dependent protocol stack for transmitting the user IP
payload, such as LLC/SNDCP/RLC/MAC.

At some network element inside the cellular operator infrastructure
(SGSN in case of GPRS/EGPRS or classic UMTS, hNodeB in case of a 3G
femtocell, eNodeB in case of 4G/LTE), the cellular protocol stacking
is translated into GTP *without breaking the end-to-end tunnel*.  So
intermediate nodes just perform some specific relay function.

At some point the GTP packet ends up on the so-called GGSN (GSM/UMTS)
or P-GW (LTE), which terminates the tunnel, decapsulates the packet
and forwards it onto an external packet data network.  This can be
public internet, but can also be any private IP network (or even
theoretically some non-IP network like X.25).

You can find the protocol specification in 3GPP TS 29.060, available
publicly via the 3GPP website at http://www.3gpp.org/DynaReport/29060.htm

A direct PDF link to v13.6.0 is provided for convenience below:
http://www.etsi.org/deliver/etsi_ts/129000_129099/129060/13.06.00_60/ts_129060v130600p.pdf

The Linux GTP tunnelling module
===============================

The module implements the function of a tunnel endpoint, i.e. it is
able to decapsulate tunneled IP packets in the uplink originated by
the phone, and encapsulate raw IP packets received from the external
packet network in downlink towards the phone.

It *only* implements the so-called 'user plane', carrying the User-IP
payload, called GTP-U.  It does not implement the 'control plane',
which is a signaling protocol used for establishment and teardown of
GTP tunnels (GTP-C).

So in order to have a working GGSN/P-GW setup, you will need a
userspace program that implements the GTP-C protocol and which then
uses the netlink interface provided by the GTP-U module in the kernel
to configure the kernel module.

This split architecture follows the tunneling modules of other
protocols, e.g. PPPoE or L2TP, where you also run a userspace daemon
to handle the tunnel establishment, authentication etc. and only the
data plane is accelerated inside the kernel.

Don't be confused by terminology:  The GTP User Plane goes through
kernel accelerated path, while the GTP Control Plane goes to
Userspace :)

The official homepage of the module is at
https://osmocom.org/projects/linux-kernel-gtp-u/wiki

Userspace Programs with Linux Kernel GTP-U support
==================================================

At the time of this writing, there are at least two Free Software
implementations that implement GTP-C and can use the netlink interface
to make use of the Linux kernel GTP-U support:

* OpenGGSN (classic 2G/3G GGSN in C):
  https://osmocom.org/projects/openggsn/wiki/OpenGGSN

* ergw (GGSN + P-GW in Erlang):
  https://github.com/travelping/ergw

Userspace Library / Command Line Utilities
==========================================

There is a userspace library called 'libgtpnl' which is based on
libmnl and which implements a C-language API towards the netlink
interface provided by the Kernel GTP module:

http://git.osmocom.org/libgtpnl/

Protocol Versions
=================

There are two different versions of GTP-U: v0 [GSM TS 09.60] and v1
[3GPP TS 29.281].  Both are implemented in the Kernel GTP module.
Version 0 is a legacy version, and deprecated from recent 3GPP
specifications.

GTP-U uses UDP for transporting PDUs.  The receiving UDP port is 2151
for GTPv1-U and 3386 for GTPv0-U.

There are three versions of GTP-C: v0, v1, and v2.  As the kernel
doesn't implement GTP-C, we don't have to worry about this.  It's the
responsibility of the control plane implementation in userspace to
implement that.

IPv6
====

The 3GPP specifications indicate either IPv4 or IPv6 can be used both
on the inner (user) IP layer, or on the outer (transport) layer.

Unfortunately, the Kernel module currently supports IPv6 neither for
the User IP payload, nor for the outer IP layer.  Patches or other
Contributions to fix this are most welcome!

Mailing List
============

If you have questions regarding how to use the Kernel GTP module from
your own software, or want to contribute to the code, please use the
osmocom-net-grps mailing list for related discussion. The list can be
reached at osmocom-net-gprs@lists.osmocom.org and the mailman
interface for managing your subscription is at
https://lists.osmocom.org/mailman/listinfo/osmocom-net-gprs

Issue Tracker
=============

The Osmocom project maintains an issue tracker for the Kernel GTP-U
module at
https://osmocom.org/projects/linux-kernel-gtp-u/issues

History / Acknowledgements
==========================

The Module was originally created in 2012 by Harald Welte, but never
completed.  Pablo came in to finish the mess Harald left behind.  But
doe to a lack of user interest, it never got merged.

In 2015, Andreas Schultz came to the rescue and fixed lots more bugs,
extended it with new features and finally pushed all of us to get it
mainline, where it was merged in 4.7.0.

Architectural Details
=====================

Local GTP-U entity and tunnel identification
--------------------------------------------

GTP-U uses UDP for transporting PDU's. The receiving UDP port is 2152
for GTPv1-U and 3386 for GTPv0-U.

There is only one GTP-U entity (and therefor SGSN/GGSN/S-GW/PDN-GW
instance) per IP address. Tunnel Endpoint Identifier (TEID) are unique
per GTP-U entity.

A specific tunnel is only defined by the destination entity. Since the
destination port is constant, only the destination IP and TEID define
a tunnel. The source IP and Port have no meaning for the tunnel.

Therefore:

  * when sending, the remote entity is defined by the remote IP and
    the tunnel endpoint id. The source IP and port have no meaning and
    can be changed at any time.

  * when receiving the local entity is defined by the local
    destination IP and the tunnel endpoint id. The source IP and port
    have no meaning and can change at any time.

[3GPP TS 29.281] Section 4.3.0 defines this so::

  The TEID in the GTP-U header is used to de-multiplex traffic
  incoming from remote tunnel endpoints so that it is delivered to the
  User plane entities in a way that allows multiplexing of different
  users, different packet protocols and different QoS levels.
  Therefore no two remote GTP-U endpoints shall send traffic to a
  GTP-U protocol entity using the same TEID value except
  for data forwarding as part of mobility procedures.

The definition above only defines that two remote GTP-U endpoints
*should not* send to the same TEID, it *does not* forbid or exclude
such a scenario. In fact, the mentioned mobility procedures make it
necessary that the GTP-U entity accepts traffic for TEIDs from
multiple or unknown peers.

Therefore, the receiving side identifies tunnels exclusively based on
TEIDs, not based on the source IP!

APN vs. Network Device
======================

The GTP-U driver creates a Linux network device for each Gi/SGi
interface.

[3GPP TS 29.281] calls the Gi/SGi reference point an interface. This
may lead to the impression that the GGSN/P-GW can have only one such
interface.

Correct is that the Gi/SGi reference point defines the interworking
between +the 3GPP packet domain (PDN) based on GTP-U tunnel and IP
based networks.

There is no provision in any of the 3GPP documents that limits the
number of Gi/SGi interfaces implemented by a GGSN/P-GW.

[3GPP TS 29.061] Section 11.3 makes it clear that the selection of a
specific Gi/SGi interfaces is made through the Access Point Name
(APN)::

  2. each private network manages its own addressing. In general this
     will result in different private networks having overlapping
     address ranges. A logically separate connection (e.g. an IP in IP
     tunnel or layer 2 virtual circuit) is used between the GGSN/P-GW
     and each private network.

     In this case the IP address alone is not necessarily unique.  The
     pair of values, Access Point Name (APN) and IPv4 address and/or
     IPv6 prefixes, is unique.

In order to support the overlapping address range use case, each APN
is mapped to a separate Gi/SGi interface (network device).

.. note::

   The Access Point Name is purely a control plane (GTP-C) concept.
   At the GTP-U level, only Tunnel Endpoint Identifiers are present in
   GTP-U packets and network devices are known

Therefore for a given UE the mapping in IP to PDN network is:

  * network device + MS IP -> Peer IP + Peer TEID,

and from PDN to IP network:

  * local GTP-U IP + TEID  -> network device

Furthermore, before a received T-PDU is injected into the network
device the MS IP is checked against the IP recorded in PDP context.


code:
===============================
IEEE 802.15.4 Developer's Guide
===============================

Introduction
============
The IEEE 802.15.4 working group focuses on standardization of the bottom
two layers: Medium Access Control (MAC) and Physical access (PHY). And there
are mainly two options available for upper layers:

- ZigBee - proprietary protocol from the ZigBee Alliance
- 6LoWPAN - IPv6 networking over low rate personal area networks

The goal of the Linux-wpan is to provide a complete implementation
of the IEEE 802.15.4 and 6LoWPAN protocols. IEEE 802.15.4 is a stack
of protocols for organizing Low-Rate Wireless Personal Area Networks.

The stack is composed of three main parts:

- IEEE 802.15.4 layer;  We have chosen to use plain Berkeley socket API,
  the generic Linux networking stack to transfer IEEE 802.15.4 data
  messages and a special protocol over netlink for configuration/management
- MAC - provides access to shared channel and reliable data delivery
- PHY - represents device drivers

Socket API
==========

::

    int sd = socket(PF_IEEE802154, SOCK_DGRAM, 0);

The address family, socket addresses etc. are defined in the
include/net/af_ieee802154.h header or in the special header
in the userspace package (see either https://linux-wpan.org/wpan-tools.html
or the git tree at https://github.com/linux-wpan/wpan-tools).

6LoWPAN Linux implementation
============================

The IEEE 802.15.4 standard specifies an MTU of 127 bytes, yielding about 80
octets of actual MAC payload once security is turned on, on a wireless link
with a link throughput of 250 kbps or less.  The 6LoWPAN adaptation format
[RFC4944] was specified to carry IPv6 datagrams over such constrained links,
taking into account limited bandwidth, memory, or energy resources that are
expected in applications such as wireless Sensor Networks.  [RFC4944] defines
a Mesh Addressing header to support sub-IP forwarding, a Fragmentation header
to support the IPv6 minimum MTU requirement [RFC2460], and stateless header
compression for IPv6 datagrams (LOWPAN_HC1 and LOWPAN_HC2) to reduce the
relatively large IPv6 and UDP headers down to (in the best case) several bytes.

In September 2011 the standard update was published - [RFC6282].
It deprecates HC1 and HC2 compression and defines IPHC encoding format which is
used in this Linux implementation.

All the code related to 6lowpan you may find in files: net/6lowpan/*
and net/ieee802154/6lowpan/*

To setup a 6LoWPAN interface you need:
1. Add IEEE802.15.4 interface and set channel and PAN ID;
2. Add 6lowpan interface by command like:
# ip link add link wpan0 name lowpan0 type lowpan
3. Bring up 'lowpan0' interface

Drivers
=======

Like with WiFi, there are several types of devices implementing IEEE 802.15.4.
1) 'HardMAC'. The MAC layer is implemented in the device itself, the device
exports a management (e.g. MLME) and data API.
2) 'SoftMAC' or just radio. These types of devices are just radio transceivers
possibly with some kinds of acceleration like automatic CRC computation and
comparation, automagic ACK handling, address matching, etc.

Those types of devices require different approach to be hooked into Linux kernel.

HardMAC
-------

See the header include/net/ieee802154_netdev.h. You have to implement Linux
net_device, with .type = ARPHRD_IEEE802154. Data is exchanged with socket family
code via plain sk_buffs. On skb reception skb->cb must contain additional
info as described in the struct ieee802154_mac_cb. During packet transmission
the skb->cb is used to provide additional data to device's header_ops->create
function. Be aware that this data can be overridden later (when socket code
submits skb to qdisc), so if you need something from that cb later, you should
store info in the skb->data on your own.

To hook the MLME interface you have to populate the ml_priv field of your
net_device with a pointer to struct ieee802154_mlme_ops instance. The fields
assoc_req, assoc_resp, disassoc_req, start_req, and scan_req are optional.
All other fields are required.

SoftMAC
-------

The MAC is the middle layer in the IEEE 802.15.4 Linux stack. This moment it
provides interface for drivers registration and management of slave interfaces.

NOTE: Currently the only monitor device type is supported - it's IEEE 802.15.4
stack interface for network sniffers (e.g. WireShark).

This layer is going to be extended soon.

See header include/net/mac802154.h and several drivers in
drivers/net/ieee802154/.

Fake drivers
------------

In addition there is a driver available which simulates a real device with
SoftMAC (fakelb - IEEE 802.15.4 loopback driver) interface. This option
provides a possibility to test and debug the stack without usage of real hardware.

Device drivers API
==================

The include/net/mac802154.h defines following functions:

.. c:function:: struct ieee802154_dev *ieee802154_alloc_device (size_t priv_size, struct ieee802154_ops *ops)

Allocation of IEEE 802.15.4 compatible device.

.. c:function:: void ieee802154_free_device(struct ieee802154_dev *dev)

Freeing allocated device.

.. c:function:: int ieee802154_register_device(struct ieee802154_dev *dev)

Register PHY in the system.

.. c:function:: void ieee802154_unregister_device(struct ieee802154_dev *dev)

Freeing registered PHY.

.. c:function:: void ieee802154_rx_irqsafe(struct ieee802154_hw *hw, struct sk_buff *skb, u8 lqi)

Telling 802.15.4 module there is a new received frame in the skb with
the RF Link Quality Indicator (LQI) from the hardware device.

.. c:function:: void ieee802154_xmit_complete(struct ieee802154_hw *hw, struct sk_buff *skb, bool ifs_handling)

Telling 802.15.4 module the frame in the skb is or going to be
transmitted through the hardware device

The device driver must implement the following callbacks in the IEEE 802.15.4
operations structure at least::

   struct ieee802154_ops {
        ...
        int     (*start)(struct ieee802154_hw *hw);
        void    (*stop)(struct ieee802154_hw *hw);
        ...
        int     (*xmit_async)(struct ieee802154_hw *hw, struct sk_buff *skb);
        int     (*ed)(struct ieee802154_hw *hw, u8 *level);
        int     (*set_channel)(struct ieee802154_hw *hw, u8 page, u8 channel);
        ...
   };

.. c:function:: int start(struct ieee802154_hw *hw)

Handler that 802.15.4 module calls for the hardware device initialization.

.. c:function:: void stop(struct ieee802154_hw *hw)

Handler that 802.15.4 module calls for the hardware device cleanup.

.. c:function:: int xmit_async(struct ieee802154_hw *hw, struct sk_buff *skb)

Handler that 802.15.4 module calls for each frame in the skb going to be
transmitted through the hardware device.

.. c:function:: int ed(struct ieee802154_hw *hw, u8 *level)

Handler that 802.15.4 module calls for Energy Detection from the hardware
device.

.. c:function:: int set_channel(struct ieee802154_hw *hw, u8 page, u8 channel)

Set radio for listening on specific channel of the hardware device.

Moreover IEEE 802.15.4 device operations structure should be filled.


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

===================================
Identifier Locator Addressing (ILA)
===================================

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

Identifier-locator addressing (ILA) is a technique used with IPv6 that
differentiates between location and identity of a network node. Part of an
address expresses the immutable identity of the node, and another part
indicates the location of the node which can be dynamic. Identifier-locator
addressing can be used to efficiently implement overlay networks for
network virtualization as well as solutions for use cases in mobility.

ILA can be thought of as means to implement an overlay network without
encapsulation. This is accomplished by performing network address
translation on destination addresses as a packet traverses a network. To
the network, an ILA translated packet appears to be no different than any
other IPv6 packet. For instance, if the transport protocol is TCP then an
ILA translated packet looks like just another TCP/IPv6 packet. The
advantage of this is that ILA is transparent to the network so that
optimizations in the network, such as ECMP, RSS, GRO, GSO, etc., just work.

The ILA protocol is described in Internet-Draft draft-herbert-intarea-ila.

ILA terminology
===============

  - Identifier
		A number that identifies an addressable node in the network
		independent of its location. ILA identifiers are sixty-four
		bit values.

  - Locator
		A network prefix that routes to a physical host. Locators
		provide the topological location of an addressed node. ILA
		locators are sixty-four bit prefixes.

  - ILA mapping
		A mapping of an ILA identifier to a locator (or to a
		locator and meta data). An ILA domain maintains a database
		that contains mappings for all destinations in the domain.

  - SIR address
		An IPv6 address composed of a SIR prefix (upper sixty-
		four bits) and an identifier (lower sixty-four bits).
		SIR addresses are visible to applications and provide a
		means for them to address nodes independent of their
		location.

  - ILA address
		An IPv6 address composed of a locator (upper sixty-four
		bits) and an identifier (low order sixty-four bits). ILA
		addresses are never visible to an application.

  - ILA host
		An end host that is capable of performing ILA translations
		on transmit or receive.

  - ILA router
		A network node that performs ILA translation and forwarding
		of translated packets.

  - ILA forwarding cache
		A type of ILA router that only maintains a working set
		cache of mappings.

  - ILA node
		A network node capable of performing ILA translations. This
		can be an ILA router, ILA forwarding cache, or ILA host.

Operation
=========

There are two fundamental operations with ILA:

  - Translate a SIR address to an ILA address. This is performed on ingress
    to an ILA overlay.

  - Translate an ILA address to a SIR address. This is performed on egress
    from the ILA overlay.

ILA can be deployed either on end hosts or intermediate devices in the
network; these are provided by "ILA hosts" and "ILA routers" respectively.
Configuration and datapath for these two points of deployment is somewhat
different.

The diagram below illustrates the flow of packets through ILA as well
as showing ILA hosts and routers::

    +--------+                                                +--------+
    | Host A +-+                                         +--->| Host B |
    |        | |              (2) ILA                   (')   |        |
    +--------+ |            ...addressed....           (   )  +--------+
	       V  +---+--+  .  packet      .  +---+--+  (_)
   (1) SIR     |  | ILA  |----->-------->---->| ILA  |   |   (3) SIR
    addressed  +->|router|  .              .  |router|->-+    addressed
    packet        +---+--+  .     IPv6     .  +---+--+        packet
		   /        .    Network   .
		  /         .              .   +--+-++--------+
    +--------+   /          .              .   |ILA ||  Host  |
    |  Host  +--+           .              .- -|host||        |
    |        |              .              .   +--+-++--------+
    +--------+              ................

Transport checksum handling
===========================

When an address is translated by ILA, an encapsulated transport checksum
that includes the translated address in a pseudo header may be rendered
incorrect on the wire. This is a problem for intermediate devices,
including checksum offload in NICs, that process the checksum. There are
three options to deal with this:

- no action	Allow the checksum to be incorrect on the wire. Before
		a receiver verifies a checksum the ILA to SIR address
		translation must be done.

- adjust transport checksum
		When ILA translation is performed the packet is parsed
		and if a transport layer checksum is found then it is
		adjusted to reflect the correct checksum per the
		translated address.

- checksum neutral mapping
		When an address is translated the difference can be offset
		elsewhere in a part of the packet that is covered by
		the checksum. The low order sixteen bits of the identifier
		are used. This method is preferred since it doesn't require
		parsing a packet beyond the IP header and in most cases the
		adjustment can be precomputed and saved with the mapping.

Note that the checksum neutral adjustment affects the low order sixteen
bits of the identifier. When ILA to SIR address translation is done on
egress the low order bits are restored to the original value which
restores the identifier as it was originally sent.

Identifier types
================

ILA defines different types of identifiers for different use cases.

The defined types are:

      0: interface identifier

      1: locally unique identifier

      2: virtual networking identifier for IPv4 address

      3: virtual networking identifier for IPv6 unicast address

      4: virtual networking identifier for IPv6 multicast address

      5: non-local address identifier

In the current implementation of kernel ILA only locally unique identifiers
(LUID) are supported. LUID allows for a generic, unformatted 64 bit
identifier.

Identifier formats
==================

Kernel ILA supports two optional fields in an identifier for formatting:
"C-bit" and "identifier type". The presence of these fields is determined
by configuration as demonstrated below.

If the identifier type is present it occupies the three highest order
bits of an identifier. The possible values are given in the above list.

If the C-bit is present,  this is used as an indication that checksum
neutral mapping has been done. The C-bit can only be set in an
ILA address, never a SIR address.

In the simplest format the identifier types, C-bit, and checksum
adjustment value are not present so an identifier is considered an
unstructured sixty-four bit value::

     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |                            Identifier                         |
     +                                                               +
     |                                                               |
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

The checksum neutral adjustment may be configured to always be
present using neutral-map-auto. In this case there is no C-bit, but the
checksum adjustment is in the low order 16 bits. The identifier is
still sixty-four bits::

     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |                            Identifier                         |
     |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |                               |  Checksum-neutral adjustment  |
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

The C-bit may used to explicitly indicate that checksum neutral
mapping has been applied to an ILA address. The format is::

     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |     |C|                    Identifier                         |
     |     +-+                       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |                               |  Checksum-neutral adjustment  |
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

The identifier type field may be present to indicate the identifier
type. If it is not present then the type is inferred based on mapping
configuration. The checksum neutral adjustment may automatically
used with the identifier type as illustrated below::

     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     | Type|                      Identifier                         |
     +-+-+-+                         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |                               |  Checksum-neutral adjustment  |
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

If the identifier type and the C-bit can be present simultaneously so
the identifier format would be::

     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     | Type|C|                    Identifier                         |
     +-+-+-+-+                       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |                               |  Checksum-neutral adjustment  |
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Configuration
=============

There are two methods to configure ILA mappings. One is by using LWT routes
and the other is ila_xlat (called from NFHOOK PREROUTING hook). ila_xlat
is intended to be used in the receive path for ILA hosts .

An ILA router has also been implemented in XDP. Description of that is
outside the scope of this document.

The usage of for ILA LWT routes is:

ip route add DEST/128 encap ila LOC csum-mode MODE ident-type TYPE via ADDR

Destination (DEST) can either be a SIR address (for an ILA host or ingress
ILA router) or an ILA address (egress ILA router). LOC is the sixty-four
bit locator (with format W:X:Y:Z) that overwrites the upper sixty-four
bits of the destination address.  Checksum MODE is one of "no-action",
"adj-transport", "neutral-map", and "neutral-map-auto". If neutral-map is
set then the C-bit will be present. Identifier TYPE one of "luid" or
"use-format." In the case of use-format, the identifier type field is
present and the effective type is taken from that.

The usage of ila_xlat is:

ip ila add loc_match MATCH loc LOC csum-mode MODE ident-type TYPE

MATCH indicates the incoming locator that must be matched to apply
a the translaiton. LOC is the locator that overwrites the upper
sixty-four bits of the destination address. MODE and TYPE have the
same meanings as described above.

Some examples
=============

::

     # Configure an ILA route that uses checksum neutral mapping as well
     # as type field. Note that the type field is set in the SIR address
     # (the 2000 implies type is 1 which is LUID).
     ip route add 3333:0:0:1:2000:0:1:87/128 encap ila 2001:0:87:0 \
	  csum-mode neutral-map ident-type use-format

     # Configure an ILA LWT route that uses auto checksum neutral mapping
     # (no C-bit) and configure identifier type to be LUID so that the
     # identifier type field will not be present.
     ip route add 3333:0:0:1:2000:0:2:87/128 encap ila 2001:0:87:1 \
	  csum-mode neutral-map-auto ident-type luid

     ila_xlat configuration

     # Configure an ILA to SIR mapping that matches a locator and overwrites
     # it with a SIR address (3333:0:0:1 in this example). The C-bit and
     # identifier field are used.
     ip ila add loc_match 2001:0:119:0 loc 3333:0:0:1 \
	 csum-mode neutral-map-auto ident-type use-format

     # Configure an ILA to SIR mapping where checksum neutral is automatically
     # set without the C-bit and the identifier type is configured to be LUID
     # so that the identifier type field is not present.
     ip ila add loc_match 2001:0:119:0 loc 3333:0:0:1 \
	 csum-mode neutral-map-auto ident-type use-format


code:
Networking
==========

Refer to :ref:`netdev-FAQ` for a guide on netdev development process specifics.

Contents:

.. toctree::
   :maxdepth: 2

   af_xdp
   bareudp
   batman-adv
   can
   can_ucan_protocol
   device_drivers/index
   dsa/index
   devlink/index
   caif/index
   ethtool-netlink
   ieee802154
   j1939
   kapi
   msg_zerocopy
   failover
   net_dim
   net_failover
   page_pool
   phy
   sfp-phylink
   alias
   bridge
   snmp_counter
   checksum-offloads
   segmentation-offloads
   scaling
   tls
   tls-offload
   nfc
   6lowpan
   6pack
   arcnet-hardware
   arcnet
   atm
   ax25
   bonding
   cdc_mbim
   dccp
   dctcp
   dns_resolver
   driver
   eql
   fib_trie
   filter
   generic-hdlc
   generic_netlink
   gen_stats
   gtp
   ila
   ioam6-sysctl
   ipddp
   ip_dynaddr
   ipsec
   ip-sysctl
   ipv6
   ipvlan
   ipvs-sysctl
   kcm
   l2tp
   lapb-module
   mac80211-injection
   mctp
   mpls-sysctl
   mptcp-sysctl
   multiqueue
   netconsole
   netdev-features
   netdevices
   netfilter-sysctl
   netif-msg
   nexthop-group-resilient
   nf_conntrack-sysctl
   nf_flowtable
   openvswitch
   operstates
   packet_mmap
   phonet
   pktgen
   plip
   ppp_generic
   proc_net_tcp
   radiotap-headers
   rds
   regulatory
   representors
   rxrpc
   sctp
   secid
   seg6-sysctl
   skbuff
   smc-sysctl
   statistics
   strparser
   switchdev
   sysfs-tagging
   tc-actions-env-rules
   tc-queue-filters
   tcp-thin
   team
   timestamping
   tipc
   tproxy
   tuntap
   udplite
   vrf
   vxlan
   x25-iface
   x25
   xfrm_device
   xfrm_proc
   xfrm_sync
   xfrm_sysctl

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


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

=====================
IOAM6 Sysfs variables
=====================

/proc/sys/net/conf/<iface>/ioam6_* variables:
=============================================

ioam6_enabled - BOOL
        Accept (= enabled) or ignore (= disabled) IPv6 IOAM options on ingress
        for this interface.

        * 0 - disabled (default)
        * 1 - enabled

ioam6_id - SHORT INTEGER
        Define the IOAM id of this interface.

        Default is ~0.

ioam6_id_wide - INTEGER
        Define the wide IOAM id of this interface.

        Default is ~0.