Skip to contentSkip to conversation

Convert filter.txt to RST

PATCH New Tobin C. Harding 1 participant 5 messages Aug 10, 2018

Subsystems (5)
lore
Share & tools
lore
#0 lore raw

v2 cover Convert filter.txt to RST

seccomp_filter.rst change removed from set, leaving CC list same as v1 for continuity.

Hi,

This is my latest attempt at converting Documentation/filter.txt to RST format. This version removes the SPDX licence identifiers added in the previous version.

This work has gotten a bit mixed up; for reference this set is a progression of the follow sets (newest set last)

1. [PATCH bpf-next 00/13] docs: Convert BPF filter.txt to RST
2. [RFC bpf-next 0/3] docs: Convert filter.txt to RST
3. [RFC bpf-next v2 0/3] docs: Convert filter.txt to RST
4. [PATCH bpf-next 0/4] Convert filter.txt to RST

As discussed on LKML this set does all the conversion in a single patch.

Please note this set adds three files to the MAINTAINERS file for the BPF maintainers.

thanks,
Tobin.

v2:
- Remove SPDX licence identifiers
- Update old intree references to filter.txt

Tobin C. Harding (4):
docs: net: Fix various minor typos
docs: Separate and convert filter.txt to RST
docs: Judiciously use double ticks
docs: Remove filter.txt from the tree

 Documentation/bpf/index.rst                   |   15 +-
 Documentation/networking/00-INDEX             |    2 -
 Documentation/networking/filter.txt           | 1476 -----------------
 Documentation/networking/packet_mmap.txt      |    2 +-
 Documentation/userspace-api/cBPF.rst          |  430 +++++
 Documentation/userspace-api/eBPF.rst          | 1004 +++++++++++
 Documentation/userspace-api/index.rst         |    3 +
 .../userspace-api/seccomp_filter.rst          |    9 +
 Documentation/userspace-api/socket_filter.rst |  181 ++
 MAINTAINERS                                   |    4 +-
 tools/bpf/bpf_asm.c                           |    6 +-
 tools/bpf/bpf_dbg.c                           |    9 +-
 12 files changed, 1653 insertions(+), 1488 deletions(-)
 delete mode 100644 Documentation/networking/filter.txt
 create mode 100644 Documentation/userspace-api/cBPF.rst
 create mode 100644 Documentation/userspace-api/eBPF.rst
 create mode 100644 Documentation/userspace-api/socket_filter.rst
Signature · 1 line
2.17.1
#1 lore raw

PATCH v2 1/4 docs: net: Fix various minor typos

Document contains a few minor typos and grammatical issues. We should however try to keep the current flavour of the document.

Fix typos and grammar if fix is _really_ an improvement.

---
 Documentation/networking/filter.txt | 66 +++++++++++++++--------------
 1 file changed, 35 insertions(+), 31 deletions(-)
Documentation/networking/filter.txt +35 -31
index e6b4ebb2b243..1fe4adf9c4c6 100644
@@ -29,8 +29,8 @@ 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
+SO_LOCK_FILTER option allows locking of 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.
 
@@ -463,7 +463,7 @@ JIT compiler
 ------------
 
 The Linux kernel has a built-in BPF JIT compiler for x86_64, SPARC, PowerPC,
-ARM, ARM64, MIPS and s390 and can be enabled through CONFIG_BPF_JIT. The JIT
+ARM, ARM64, MIPS and s390 which 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:
 
@@ -572,7 +572,7 @@ 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
+that better performance can be achieved (more details later). This new
 ISA is called 'eBPF' or 'internal BPF' interchangeably. (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'
@@ -647,12 +647,12 @@ Some core changes of the new internal format:
 
   32-bit architectures run 64-bit internal BPF programs via interpreter.
   Their JITs may convert BPF programs that only use 32-bit subregisters into
-  native instruction set and let the rest being interpreted.
+  native instruction set and let the rest be interpreted.
 
-  Operation is 64-bit, because on 64-bit architectures, pointers are also
-  64-bit wide, and we want to pass 64-bit values in/out of kernel functions,
-  so 32-bit eBPF registers would otherwise require to define register-pair
-  ABI, thus, there won't be able to use a direct eBPF register to HW register
+  Operation is 64-bit since on 64-bit architectures pointers are also
+  64-bit wide and we want to pass 64-bit values in/out of kernel functions.
+  32-bit eBPF registers would otherwise require us to define a register-pair
+  ABI, thus we would not be able to use a direct eBPF register to HW register
   mapping and JIT would need to do combine/split/move operations for every
   register in and out of the function, which is complex, bug prone and slow.
   Another reason is the use of atomic 64-bit counters.
@@ -677,7 +677,7 @@ Some core changes of the new internal format:
   situations without performance penalty.
 
   After an in-kernel function call, R1 - R5 are reset to unreadable and R0 has
-  a return value of the function. Since R6 - R9 are callee saved, their state
+  the return value of the function. Since R6 - R9 are callee saved, their state
   is preserved across the call.
 
   For example, consider three C functions:
@@ -715,7 +715,7 @@ Some core changes of the new internal format:
   are currently not supported, but these restrictions can be lifted if necessary
   in the future.
 
-  On 64-bit architectures all register map to HW registers one to one. For
+  On 64-bit architectures all registers map to HW registers one to one. For
   example, x86_64 JIT compiler can map them as ...
 
     R0 - rax
@@ -814,9 +814,10 @@ A program, that is translated internally consists of the following elements:
 
   op:16, jt:8, jf:8, k:32    ==>    op:8, dst_reg:4, src_reg:4, off:16, imm:32
 
-So far 87 internal BPF instructions were implemented. 8-bit 'op' opcode field
-has room for new instructions. Some of them may use 16/24/32 byte encoding. New
-instructions must be multiple of 8 bytes to preserve backward compatibility.
+So far 87 internal BPF instructions have been implemented. 8-bit 'op' opcode
+field has room for new instructions. Some of them may use 16/24/32 byte
+encoding. New instructions must be a multiple of 8 bytes to preserve backward
+compatibility.
 
 Internal BPF is a general purpose RISC instruction set. Not every register and
 every instruction are used during translation from original BPF to new format.
@@ -827,11 +828,11 @@ out of registers and would have to resort to spill/fill to stack.
 
 Internal BPF can used as generic assembler for last step performance
 optimizations, socket filters and seccomp are using it as assembler. Tracing
-filters may use it as assembler to generate code from kernel. In kernel usage
+filters may use it as assembler to generate code from kernel. In-kernel usage
 may not be bounded by security considerations, since generated internal BPF code
-may be optimizing internal code path and not being exposed to the user space.
-Safety of internal BPF can come from a verifier (TBD). In such use cases as
-described, it may be used as safe instruction set.
+may use an optimised internal code path and may not be being exposed to user
+space. Safety of internal BPF can come from a verifier (TBD). In such use cases
+as described, it may be used as safe as the instruction set.
 
 Just like the original BPF, the new format runs within a controlled environment,
 is deterministic and the kernel can easily prove that. The safety of the program
@@ -927,7 +928,7 @@ Classic BPF is using BPF_MISC class to represent A = X and X = A moves.
 eBPF is using BPF_MOV | BPF_X | BPF_ALU code instead. Since there are no
 BPF_MISC operations in eBPF, the class 7 is used as BPF_ALU64 to mean
 exactly the same operations as BPF_ALU, but with 64-bit wide operands
-instead. So BPF_ADD | BPF_X | BPF_ALU64 means 64-bit addition, i.e.:
+instead. So BPF_ADD | BPF_X | BPF_ALU64 means 64-bit addition i.e.
 dst_reg = dst_reg + src_reg
 
 Classic BPF wastes the whole BPF_RET class to represent a single 'ret'
@@ -1005,9 +1006,10 @@ BPF_XADD | BPF_DW | BPF_STX: lock xadd *(u64 *)(dst_reg + off16) += src_reg
 Where size is one of: BPF_B or BPF_H or BPF_W or BPF_DW. Note that 1 and
 2 byte atomic increments are not supported.
 
-eBPF has one 16-byte instruction: BPF_LD | BPF_DW | BPF_IMM which consists
-of two consecutive 'struct bpf_insn' 8-byte blocks and interpreted as single
+eBPF has one 16-byte instruction: BPF_LD | BPF_DW | BPF_IMM which consists of
+two consecutive 'struct bpf_insn' 8-byte blocks and is interpreted as single
 instruction that loads 64-bit immediate value into a dst_reg.
+
 Classic BPF has similar instruction: BPF_LD | BPF_W | BPF_IMM which loads
 32-bit immediate value into a register.
 
@@ -1016,8 +1018,8 @@ eBPF verifier
 The safety of the eBPF program is determined in two steps.
 
 First step does DAG check to disallow loops and other CFG validation.
-In particular it will detect programs that have unreachable instructions.
-(though classic BPF checker allows them)
+In particular it will detect programs that have unreachable instructions
+(though classic BPF checker allows them).
 
 Second step starts from the first insn and descends all possible paths.
 It simulates execution of every insn and observes the state change of
@@ -1078,7 +1080,9 @@ Classic BPF verifier does similar check with M[0-15] memory slots.
 For example:
   bpf_ld R0 = *(u32 *)(R10 - 4)
   bpf_exit
-is invalid program.
+
+is an invalid program.
+
 Though R10 is correct read-only register and has type PTR_TO_STACK
 and R10 - 4 is within stack bounds, there were no stores into that location.
 
@@ -1089,13 +1093,13 @@ Allowed function calls are customized with bpf_verifier_ops->get_func_proto()
 The eBPF verifier will check that registers match argument constraints.
 After the call register R0 will be set to return type of the function.
 
-Function calls is a main mechanism to extend functionality of eBPF programs.
-Socket filters may let programs to call one set of functions, whereas tracing
-filters may allow completely different set.
+Function calls is an important mechanism to extend functionality of eBPF
+programs.  Socket filters may let programs call one set of functions,
+whereas tracing filters may allow a completely different set.
 
-If a function made accessible to eBPF program, it needs to be thought through
-from safety point of view. The verifier will guarantee that the function is
-called with valid arguments.
+If a function is made accessible to eBPF program, it needs to be thought
+through from a safety point of view. The verifier will guarantee that the
+function is called with valid arguments.
 
 seccomp vs socket filters have different security restrictions for classic BPF.
 Seccomp solves this by two stage verifier: classic BPF verifier is followed
@@ -1167,7 +1171,7 @@ checked and found to be non-NULL, all copies can become PTR_TO_MAP_VALUEs.
 As well as range-checking, the tracked information is also used for enforcing
 alignment of pointer accesses.  For instance, on most systems the packet pointer
 is 2 bytes after a 4-byte alignment.  If a program adds 14 bytes to that to jump
-over the Ethernet header, then reads IHL and addes (IHL * 4), the resulting
+over the Ethernet header, then reads IHL and adds (IHL * 4), the resulting
 pointer will have a variable offset known to be 4n+2 for some n, so adding the 2
 bytes (NET_IP_ALIGN) gives a 4-byte alignment and so word-sized accesses through
 that pointer are safe.
Signature · 1 line
2.17.1
#2 lore raw

PATCH v2 2/4 docs: Separate and convert filter.txt to RST

In reply to Tobin C. Harding

RST is the preferred format for kernel documentation now. Convert networking/filter.txt to RST format. Currently filer.txt contains documentation on various things related to BPF. To improve the quality of the kernel documentation we can split this file up. Also, BPF is useful to userspace for applications outside of just networking.

Split filter.txt up into three RST files, all now located under Documentation/userspace-api/. After the split there should be no Sphinx warnings.

Create three new files from the content of filter.txt

- socket-filter.rst on how to write socket filters
- cBPF.rst describing classic BPF and its tools
- eBPF.rst describing extended BPF

Add files to MAINTAINERS.

Do conversion

- Fix line length (72 character maximum).
- Use double spaces after a period (full stop).
- Use RST format directives for code snippets (::).
- Fix indentation of code snippets.
- Use correct heading adornments.

Admittedly double spaces is a style issue and should really not be done however doing the line length change requires double spacing because of the tool I have available (emacs). Line length limint seems more important so lets do both changes.

Because these three files are related (also seccomp_filter.rst) there are a number of references to each. Add an RST reference label to the top of each file and use it with the relative path (starting at Documentation) as is typical in kernel docs. Use a list so as to make the text file readable as well as the rendered HTML.

Add RST reference label to seccomp_filter.rst

---
 Documentation/userspace-api/cBPF.rst          |  430 +++++++
 Documentation/userspace-api/eBPF.rst          | 1005 +++++++++++++++++
 Documentation/userspace-api/index.rst         |    3 +
 .../userspace-api/seccomp_filter.rst          |    9 +
 Documentation/userspace-api/socket_filter.rst |  181 +++
 MAINTAINERS                                   |    4 +-
 6 files changed, 1631 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/userspace-api/cBPF.rst
 create mode 100644 Documentation/userspace-api/eBPF.rst
 create mode 100644 Documentation/userspace-api/socket_filter.rst
Documentation/userspace-api/cBPF.rst new file +430 -0
new file mode 100644
index 000000000000..5e820c5fe46c
@@ -0,0 +1,430 @@
+.. _cbpf:
+
+====================================
+Classic Berkley Packet Filter (cBPF)
+====================================
+
+For an introduction to BPF and Linux Socket Filtering please see
+:ref:`Documentation/userspace-api/socket-filter.rst <socket-filter>`
+
+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
+above linked document.  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 [1].
+
+The BPF architecture consists of the following basic elements:
+
+.. flat-table:: BPF 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, 10       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, 10          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                 Jump on A == k
+  jneq             8                    Jump on A != k
+  jne              8                    Jump on A != k
+  jlt              8                    Jump on A <  k
+  jle              8                    Jump on A <= k
+  jgt              7, 8                 Jump on A >  k
+  jge              7, 8                 Jump on A >= k
+  jset             7, 8                 Jump on A &  k
+
+  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, 9                 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               #k,Lt                Jump to Lt if predicate is true
+   9               a/%a                 Accumulator A
+  10               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                                  prandom_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
+
+(Accelerated) VLAN w/ id 10::
+
+  ld vlan_tci
+  jneq #10, 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 */
+
+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 and s390 which 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.
+
+Reference
+=========
+
+The original BPF paper:
+
+[1] 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]
Documentation/userspace-api/eBPF.rst new file +1005 -0

1,005 lines not on this page · raw message

Documentation/userspace-api/index.rst +3 -0
index a3233da7fa88..5e389aaf177c 100644
@@ -18,8 +18,11 @@ place where this information is gathered.
 
    no_new_privs
    seccomp_filter
+   socket_filter
    unshare
    spec_ctrl
+   cBPF
+   eBPF
 
 .. only::  subproject and html
 
Documentation/userspace-api/seccomp_filter.rst +9 -0
index 82a468bc7560..04e734cb90be 100644
@@ -1,3 +1,5 @@
+.. _seccomp-filter:
+
 ===========================================
 Seccomp BPF (SECure COMPuting with filters)
 ===========================================
@@ -40,6 +42,13 @@ path (avoiding pathological sizes or selecting which of the multiplexed
 system calls in socketcall() is allowed, for instance) which could be
 construed, incorrectly, as a more complete sandboxing solution.
 
+For more information on BPF please see:
+
+- Linux Socket Filters -
+  :ref:`Documentation/userspace-api/socket_filter.rst <socket-filter>`
+- Classic BPF (cBPF) - :ref:`Documentation/userspace-api/cBPF.rst <cbpf>`
+- Internal BPF (eBPF) - :ref:`Documentation/userspace-api/eBPF.rst <ebpf>`
+
 Usage
 =====
 
Documentation/userspace-api/socket_filter.rst new file +181 -0

181 lines not on this page · raw message

MAINTAINERS +3 -1
index 82f277462349..1611f9f6607f 100644
@@ -2746,8 +2746,10 @@ T:	git git://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git
 Q:	https://patchwork.ozlabs.org/project/netdev/list/?delegate=77147
 S:	Supported
 F:	arch/x86/net/bpf_jit*
-F:	Documentation/networking/filter.txt
 F:	Documentation/bpf/
+F:	Documentation/userspace-api/socket_filter.rst
+F:	Documentation/userspace-api/eBPF.rst
+F:	Documentation/userspace-api/cBPF.rst
 F:	include/linux/bpf*
 F:	include/linux/filter.h
 F:	include/trace/events/xdp.h
Signature · 1 line
2.17.1
#3 lore raw

PATCH v2 3/4 docs: Judiciously use double ticks

In reply to Tobin C. Harding

Double ticks _can_ make the documentation easier to follow in HTML. They can however make the documentation _harder_ to read in plain text. We should use double ticks but judiciously.

Judiciously use double ticks to replace single ticks.

---
 Documentation/userspace-api/eBPF.rst | 69 ++++++++++++++--------------
 1 file changed, 34 insertions(+), 35 deletions(-)
Documentation/userspace-api/eBPF.rst +34 -35
index 6fe1d966aee9..e4764fbf5376 100644
@@ -153,7 +153,7 @@ to in-kernel function.  If R1 - R5 registers are mapped to CPU registers
 that are used for argument passing on given architecture, the JIT
 compiler doesn't need to emit extra moves.  Function arguments will be
 in the correct registers and BPF_CALL instruction will be JITed as
-single 'call' HW instruction.  This calling convention was picked to
+single ``call`` HW instruction.  This calling convention was picked to
 cover common call situations without performance penalty.
 
 After an in-kernel function call, R1 - R5 are reset to unreadable and R0
@@ -266,7 +266,7 @@ Which is in this example equivalent in C to::
 
 In-kernel functions foo() and bar() with prototype: u64 (*)(u64 arg1,
 u64 arg2, u64 arg3, u64 arg4, u64 arg5); will receive arguments in
-proper registers and place their return value into '%rax' which is R0 in
+proper registers and place their return value into ``%rax`` which is R0 in
 eBPF.  Prologue and epilogue are emitted by JIT and are implicit in the
 interpreter.  R0-R5 are scratch registers, so eBPF program needs to
 preserve them across the calls as defined by calling convention.
@@ -423,7 +423,7 @@ exactly the same operations as BPF_ALU, but with 64-bit wide operands
 instead.  So BPF_ADD | BPF_X | BPF_ALU64 means 64-bit addition i.e.
 dst_reg = dst_reg + src_reg
 
-Classic BPF wastes the whole BPF_RET class to represent a single 'ret'
+Classic BPF wastes the whole BPF_RET class to represent a single ``ret``
 operation.  Classic BPF_RET | BPF_K means copy imm32 into return
 register and perform function exit.  eBPF is modeled to match CPU, so
 BPF_JMP | BPF_EXIT in eBPF means function exit only.  The eBPF program
@@ -467,7 +467,7 @@ eBPF has two non-generic instructions: (BPF_ABS | <size> | BPF_LD) and
 
 They had to be carried over from classic to have strong performance of
 socket filters running in eBPF interpreter.  These instructions can only
-be used when interpreter context is a pointer to 'struct sk_buff' and
+be used when interpreter context is a pointer to ``struct sk_buff`` and
 have seven implicit operands.  Register R6 is an implicit input that
 must contain pointer to sk_buff.  Register R0 is an implicit output
 which contains the data fetched from the packet.  Registers R1-R5 are
@@ -500,7 +500,7 @@ Where size is one of: BPF_B or BPF_H or BPF_W or BPF_DW.  Note that 1
 and 2 byte atomic increments are not supported.
 
 eBPF has one 16-byte instruction: BPF_LD | BPF_DW | BPF_IMM which
-consists of two consecutive 'struct bpf_insn' 8-byte blocks and is
+consists of two consecutive ``struct bpf_insn`` 8-byte blocks and is
 interpreted as single instruction that loads 64-bit immediate value into
 a dst_reg.
 
@@ -563,8 +563,8 @@ alignment checked.  For example::
 will be rejected, since R1 doesn't have a valid pointer type at the time
 of execution of instruction bpf_xadd.
 
-At the start R1 type is PTR_TO_CTX (a pointer to generic 'struct
-bpf_context').  A callback is used to customize verifier to restrict
+At the start R1 type is PTR_TO_CTX (a pointer to generic ``struct
+bpf_context``).  A callback is used to customize verifier to restrict
 eBPF program access to only certain fields within ctx structure with
 specified size and alignment.
 
@@ -626,7 +626,7 @@ Register value tracking
 
 In order to determine the safety of an eBPF program, the verifier must
 track the range of possible values in each register and also in each
-stack slot.  This is done with 'struct bpf_reg_state', defined in
+stack slot.  This is done with ``struct bpf_reg_state``, defined in
 include/linux/bpf_verifier.h, which unifies tracking of scalar and
 pointer values.  Each register state has a type, which is either
 NOT_INIT (the register has not been written to), SCALAR_VALUE (some
@@ -713,7 +713,7 @@ data via skb->data and skb->data_end pointers, e.g.::
   6:  r0 = *(u16 *)(r3 +12) /* access 12 and 13 bytes of the packet */
 
 this 2byte load from the packet is safe to do, since the program author
-did check 'if (skb->data + 14 > skb->data_end) goto err' at insn #5
+did check ``if (skb->data + 14 > skb->data_end) goto err`` at insn #5
 which means that in the fall-through case the register R3 (which points
 to skb->data) has at least 14 directly accessible bytes.  The verifier
 marks it as R3=pkt(id=0,off=0,r=14).  id=0 means that no additional
@@ -721,8 +721,8 @@ variables were added to the register.  off=0 means that no additional
 constants were added.  r=14 is the range of safe access which means that
 bytes [R3, R3 + 14) are ok.  Note that R5 is marked as
 R5=pkt(id=0,off=14,r=14).  It also points to the packet data, but
-constant 14 was added to the register, so it now points to 'skb->data +
-14' and accessible range is [R5, R5 + 14 - 14) which is zero bytes.
+constant 14 was added to the register, so it now points to ``skb->data +
+14`` and accessible range is [R5, R5 + 14 - 14) which is zero bytes.
 
 More complex packet access may look like::
 
@@ -743,30 +743,29 @@ More complex packet access may look like::
   R0=inv(id=0,umax_value=255,var_off=(0x0; 0xff)) R1=pkt_end R2=pkt(id=2,off=8,r=8) R3=pkt(id=2,off=0,r=8) R4=inv(id=0,umax_value=3570,var_off=(0x0; 0xfffe)) R5=pkt(id=0,off=14,r=14) R10=fp
   19:  r1 = *(u8 *)(r3 +4)
 
-The state of the register R3 is R3=pkt(id=2,off=0,r=8) id=2 means that
-two 'r3 += rX' instructions were seen, so r3 points to some offset
-within a packet and since the program author did 'if (r3 + 8 > r1) goto
-err' at insn #18, the safe range is [R3, R3 + 8).  The verifier only
-allows 'add'/'sub' operations on packet registers.  Any other operation
-will set the register state to 'SCALAR_VALUE' and it won't be available
-for direct packet access.  Operation 'r3 += rX' may overflow and become
-less than original skb->data, therefore the verifier has to prevent
-that.  So when it sees 'r3 += rX' instruction and rX is more than 16-bit
-value, any subsequent bounds-check of r3 against skb->data_end will not
-give us 'range' information, so attempts to read through the pointer
-will give "invalid access to packet" error.  Ex. after insn 'r4 = *(u8
-*)(r3 +12)' (insn #7 above) the state of r4 is
-R4=inv(id=0,umax_value=255,var_off=(0x0; 0xff)) which means that upper
-56 bits of the register are guaranteed to be zero, and nothing is known
-about the lower 8 bits.  After insn 'r4 *= 14' the state becomes
-R4=inv(id=0,umax_value=3570,var_off=(0x0; 0xfffe)), since multiplying an
-8-bit value by constant 14 will keep upper 52 bits as zero, also the
-least significant bit will be zero as 14 is even.  Similarly 'r2 >>= 48'
-will make R2=inv(id=0,umax_value=65535,var_off=(0x0; 0xffff)), since the
-shift is not sign extending.  This logic is implemented in
-adjust_reg_min_max_vals() function, which calls
-adjust_ptr_min_max_vals() for adding pointer to scalar (or vice versa)
-and adjust_scalar_min_max_vals() for operations on two scalars.
+The state of the register R3 is ``R3=pkt(id=2,off=0,r=8)`` id=2 means that
+two ``r3 += rX`` instructions were seen, so r3 points to some offset within
+a packet and since the program author did ``if (r3 + 8 > r1) goto err`` at
+insn #18, the safe range is [R3, R3 + 8).  The verifier only allows
+'add'/'sub' operations on packet registers.  Any other operation will set
+the register state to 'SCALAR_VALUE' and it won't be available for direct
+packet access.  Operation ``r3 += rX`` may overflow and become less than
+original skb->data, therefore the verifier has to prevent that.  So when it
+sees ``r3 += rX`` instruction and rX is more than 16-bit value, any
+subsequent bounds-check of r3 against skb->data_end will not give us
+'range' information, so attempts to read through the pointer will give
+"invalid access to packet" error.  Ex. after insn ``r4 = *(u8 *)(r3 +12)``
+(insn #7 above) the state of r4 is R4=inv(id=0,umax_value=255,var_off=(0x0;
+0xff)) which means that upper 56 bits of the register are guaranteed to be
+zero, and nothing is known about the lower 8 bits.  After insn ``r4 *= 14``
+the state becomes R4=inv(id=0,umax_value=3570,var_off=(0x0; 0xfffe)), since
+multiplying an 8-bit value by constant 14 will keep upper 52 bits as zero,
+also the least significant bit will be zero as 14 is even.  Similarly ``r2
+>>= 48`` will make R2=inv(id=0,umax_value=65535,var_off=(0x0; 0xffff)),
+since the shift is not sign extending.  This logic is implemented in
+adjust_reg_min_max_vals() function, which calls adjust_ptr_min_max_vals()
+for adding pointer to scalar (or vice versa) and
+adjust_scalar_min_max_vals() for operations on two scalars.
 
 The end result is that bpf program author can access packet directly
 using normal C code as::
Signature · 1 line
2.17.1
#4 lore raw

PATCH v2 4/4 docs: Remove filter.txt from the tree

In reply to Tobin C. Harding

We just split up the content of filter.txt into three RST files. We can remove filter.txt now. As we remove filter.txt we need to update all intree references.

Remove filter.txt and update references to the new RST files.

---
 Documentation/bpf/index.rst              |   15 +-
 Documentation/networking/00-INDEX        |    2 -
 Documentation/networking/filter.txt      | 1480 ----------------------
 Documentation/networking/packet_mmap.txt |    2 +-
 tools/bpf/bpf_asm.c                      |    6 +-
 tools/bpf/bpf_dbg.c                      |    9 +-
 6 files changed, 23 insertions(+), 1491 deletions(-)
 delete mode 100644 Documentation/networking/filter.txt
Documentation/bpf/index.rst +10 -5
index 00a8450a602f..512221a606f7 100644
@@ -5,10 +5,16 @@ BPF Documentation
 This directory contains documentation for the BPF (Berkeley Packet
 Filter) facility, with a focus on the extended BPF version (eBPF).
 
-This kernel side documentation is still work in progress.  The main
-textual documentation is (for historical reasons) described in
-`Documentation/networking/filter.txt`_, which describe both classical
-and extended BPF instruction-set.
+This kernel side documentation is still work in progress.  Currently
+documentation for BPF can be found in the following places:
+
+- Introduction to BPF (Linux Socket Filter) -
+  :ref:`Documentation/userspace-api/socket-filter.rst <socket-filter>`
+- Classic BPF (cBPF) - :ref:`Documentation/userspace-api/cBPF.rst <cbpf>`
+- Internal BPF (eBPF) - :ref:`Documentation/userspace-api/eBPF.rst <ebpf>`
+- SECCOMP BPF -
+  :ref:`Documentation/userspace-api/seccomp_filter.rst <seccomp-filter>`
+
 The Cilium project also maintains a `BPF and XDP Reference Guide`_
 that goes into great technical depth about the BPF Architecture.
 
@@ -30,7 +36,6 @@ Two sets of Questions and Answers (Q&A) are maintained.
 
 
 .. Links:
-.. _Documentation/networking/filter.txt: ../networking/filter.txt
 .. _man-pages: https://www.kernel.org/doc/man-pages/
 .. _bpf(2): http://man7.org/linux/man-pages/man2/bpf.2.html
 .. _BPF and XDP Reference Guide: http://cilium.readthedocs.io/en/latest/bpf/
Documentation/networking/00-INDEX +0 -2
index 02a323c43261..95960ae21c09 100644
@@ -78,8 +78,6 @@ eql.txt
 	- serial IP load balancing
 fib_trie.txt
 	- Level Compressed Trie (LC-trie) notes: a structure for routing.
-filter.txt
-	- Linux Socket Filtering
 fore200e.txt
 	- FORE Systems PCA-200E/SBA-200E ATM NIC driver info.
 framerelay.txt
Documentation/networking/filter.txt deleted +0 -1480

1,480 lines not on this page · raw message

Documentation/networking/packet_mmap.txt +1 -1
index 999eb41da81d..70a9d6f4a907 100644
@@ -1051,7 +1051,7 @@ for more information on hardware timestamps.
 -------------------------------------------------------------------------------
 
 - Packet sockets work well together with Linux socket filters, thus you also
-  might want to have a look at Documentation/networking/filter.txt
+  might want to have a look at Documentation/userspace-api/socket_filter.rst
 
 --------------------------------------------------------------------------------
 + THANKS
tools/bpf/bpf_asm.c +5 -1
index c15aef097b04..3bb41ecd81e2 100644
@@ -10,7 +10,11 @@
  *
  * How to get into it:
  *
- * 1) read Documentation/networking/filter.txt
+ * 1) read:
+ *     - Documentation/userspace-api/socket_filter.rst
+ *     - Documentation/userspace-api/cBPF.rst
+ *     - Documentation/userspace-api/eBPF.rst
+ *
  * 2) Run `bpf_asm [-c] <filter-prog file>` to translate into binary
  *    blob that is loadable with xt_bpf, cls_bpf et al. Note: -c will
  *    pretty print a C-like construct.
tools/bpf/bpf_dbg.c +7 -2
index 61b9aa5d6415..883369fac63a 100644
@@ -12,8 +12,13 @@
  * for making a verdict when multiple simple BPF programs are combined
  * into one in order to prevent parsing same headers multiple times.
  *
- * More on how to debug BPF opcodes see Documentation/networking/filter.txt
- * which is the main document on BPF. Mini howto for getting started:
+ * More on how to debug BPF opcodes see:
+ *  - Documentation/userspace-api/cBPF.rst
+ *
+ * And for introduction to Linux Socket Filters see:
+ *  - Documentation/userspace-api/socket_filter.rst
+ *
+ * Mini howto for getting started:
  *
  *  1) `./bpf_dbg` to enter the shell (shell cmds denoted with '>'):
  *  2) > load bpf 6,40 0 0 12,21 0 3 20... (output from `bpf_asm` or
Signature · 1 line
2.17.1