aboutsummaryrefslogtreecommitdiffstats
path: root/tools
diff options
context:
space:
mode:
authorLinus Torvalds <torvalds@linux-foundation.org>2017-11-15 14:56:19 -0500
committerLinus Torvalds <torvalds@linux-foundation.org>2017-11-15 14:56:19 -0500
commit5bbcc0f595fadb4cac0eddc4401035ec0bd95b09 (patch)
tree3b65e490cc36a6c6fecac1fa24d9e0ac9ced4455 /tools
parent892204e06cb9e89fbc4b299a678f9ca358e97cac (diff)
parent50895b9de1d3e0258e015e8e55128d835d9a9f19 (diff)
Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/net-next
Pull networking updates from David Miller: "Highlights: 1) Maintain the TCP retransmit queue using an rbtree, with 1GB windows at 100Gb this really has become necessary. From Eric Dumazet. 2) Multi-program support for cgroup+bpf, from Alexei Starovoitov. 3) Perform broadcast flooding in hardware in mv88e6xxx, from Andrew Lunn. 4) Add meter action support to openvswitch, from Andy Zhou. 5) Add a data meta pointer for BPF accessible packets, from Daniel Borkmann. 6) Namespace-ify almost all TCP sysctl knobs, from Eric Dumazet. 7) Turn on Broadcom Tags in b53 driver, from Florian Fainelli. 8) More work to move the RTNL mutex down, from Florian Westphal. 9) Add 'bpftool' utility, to help with bpf program introspection. From Jakub Kicinski. 10) Add new 'cpumap' type for XDP_REDIRECT action, from Jesper Dangaard Brouer. 11) Support 'blocks' of transformations in the packet scheduler which can span multiple network devices, from Jiri Pirko. 12) TC flower offload support in cxgb4, from Kumar Sanghvi. 13) Priority based stream scheduler for SCTP, from Marcelo Ricardo Leitner. 14) Thunderbolt networking driver, from Amir Levy and Mika Westerberg. 15) Add RED qdisc offloadability, and use it in mlxsw driver. From Nogah Frankel. 16) eBPF based device controller for cgroup v2, from Roman Gushchin. 17) Add some fundamental tracepoints for TCP, from Song Liu. 18) Remove garbage collection from ipv6 route layer, this is a significant accomplishment. From Wei Wang. 19) Add multicast route offload support to mlxsw, from Yotam Gigi" * git://git.kernel.org/pub/scm/linux/kernel/git/davem/net-next: (2177 commits) tcp: highest_sack fix geneve: fix fill_info when link down bpf: fix lockdep splat net: cdc_ncm: GetNtbFormat endian fix openvswitch: meter: fix NULL pointer dereference in ovs_meter_cmd_reply_start netem: remove unnecessary 64 bit modulus netem: use 64 bit divide by rate tcp: Namespace-ify sysctl_tcp_default_congestion_control net: Protect iterations over net::fib_notifier_ops in fib_seq_sum() ipv6: set all.accept_dad to 0 by default uapi: fix linux/tls.h userspace compilation error usbnet: ipheth: prevent TX queue timeouts when device not ready vhost_net: conditionally enable tx polling uapi: fix linux/rxrpc.h userspace compilation errors net: stmmac: fix LPI transitioning for dwmac4 atm: horizon: Fix irq release error net-sysfs: trigger netlink notification on ifalias change via sysfs openvswitch: Using kfree_rcu() to simplify the code openvswitch: Make local function ovs_nsh_key_attr_size() static openvswitch: Fix return value check in ovs_meter_cmd_features() ...
Diffstat (limited to 'tools')
-rw-r--r--tools/Makefile14
-rw-r--r--tools/bpf/Makefile (renamed from tools/net/Makefile)18
-rw-r--r--tools/bpf/bpf_asm.c (renamed from tools/net/bpf_asm.c)0
-rw-r--r--tools/bpf/bpf_dbg.c (renamed from tools/net/bpf_dbg.c)0
-rw-r--r--tools/bpf/bpf_exp.l (renamed from tools/net/bpf_exp.l)0
-rw-r--r--tools/bpf/bpf_exp.y (renamed from tools/net/bpf_exp.y)0
-rw-r--r--tools/bpf/bpf_jit_disasm.c (renamed from tools/net/bpf_jit_disasm.c)3
-rw-r--r--tools/bpf/bpftool/Documentation/Makefile34
-rw-r--r--tools/bpf/bpftool/Documentation/bpftool-map.rst131
-rw-r--r--tools/bpf/bpftool/Documentation/bpftool-prog.rst150
-rw-r--r--tools/bpf/bpftool/Documentation/bpftool.rst56
-rw-r--r--tools/bpf/bpftool/Makefile92
-rw-r--r--tools/bpf/bpftool/bash-completion/bpftool354
-rw-r--r--tools/bpf/bpftool/common.c405
-rw-r--r--tools/bpf/bpftool/jit_disasm.c162
-rw-r--r--tools/bpf/bpftool/json_writer.c356
-rw-r--r--tools/bpf/bpftool/json_writer.h72
-rw-r--r--tools/bpf/bpftool/main.c331
-rw-r--r--tools/bpf/bpftool/main.h122
-rw-r--r--tools/bpf/bpftool/map.c899
-rw-r--r--tools/bpf/bpftool/prog.c703
-rw-r--r--tools/include/uapi/linux/bpf.h158
-rw-r--r--tools/lib/bpf/bpf.c89
-rw-r--r--tools/lib/bpf/bpf.h27
-rw-r--r--tools/lib/bpf/libbpf.c179
-rw-r--r--tools/lib/bpf/libbpf.h1
-rw-r--r--tools/testing/selftests/bpf/Makefile25
-rw-r--r--tools/testing/selftests/bpf/bpf_helpers.h67
-rw-r--r--tools/testing/selftests/bpf/cgroup_helpers.c178
-rw-r--r--tools/testing/selftests/bpf/cgroup_helpers.h17
-rw-r--r--tools/testing/selftests/bpf/dev_cgroup.c60
-rw-r--r--tools/testing/selftests/bpf/sockmap_parse_prog.c3
-rw-r--r--tools/testing/selftests/bpf/sockmap_verdict_prog.c2
-rw-r--r--tools/testing/selftests/bpf/test_dev_cgroup.c93
-rw-r--r--tools/testing/selftests/bpf/test_lpm_map.c201
-rw-r--r--tools/testing/selftests/bpf/test_maps.c48
-rw-r--r--tools/testing/selftests/bpf/test_progs.c195
-rw-r--r--tools/testing/selftests/bpf/test_verifier.c894
-rw-r--r--tools/testing/selftests/bpf/test_verifier_log.c171
-rw-r--r--tools/testing/selftests/bpf/test_xdp_meta.c53
-rwxr-xr-xtools/testing/selftests/bpf/test_xdp_meta.sh51
-rwxr-xr-xtools/testing/selftests/net/rtnetlink.sh271
-rw-r--r--tools/testing/selftests/tc-testing/.gitignore1
-rw-r--r--tools/testing/selftests/tc-testing/creating-testcases/AddingTestCases.txt12
-rw-r--r--tools/testing/selftests/tc-testing/creating-testcases/example.json55
-rw-r--r--tools/testing/selftests/tc-testing/creating-testcases/template.json15
-rw-r--r--tools/testing/selftests/tc-testing/tc-tests/actions/gact.json469
-rw-r--r--tools/testing/selftests/tc-testing/tc-tests/actions/ife.json52
-rw-r--r--tools/testing/selftests/tc-testing/tc-tests/actions/mirred.json223
-rw-r--r--tools/testing/selftests/tc-testing/tc-tests/actions/police.json527
-rw-r--r--tools/testing/selftests/tc-testing/tc-tests/actions/simple.json130
-rw-r--r--tools/testing/selftests/tc-testing/tc-tests/actions/skbedit.json320
-rw-r--r--tools/testing/selftests/tc-testing/tc-tests/actions/skbmod.json372
-rw-r--r--tools/testing/selftests/tc-testing/tc-tests/actions/tests.json1165
-rwxr-xr-xtools/testing/selftests/tc-testing/tdc.py29
-rw-r--r--tools/testing/selftests/tc-testing/tdc_config.py14
-rw-r--r--tools/testing/selftests/tc-testing/tdc_config_local_template.py23
-rw-r--r--tools/testing/selftests/tc-testing/tdc_helper.py4
-rw-r--r--tools/testing/vsock/.gitignore2
-rw-r--r--tools/testing/vsock/Makefile9
-rw-r--r--tools/testing/vsock/README36
-rw-r--r--tools/testing/vsock/control.c219
-rw-r--r--tools/testing/vsock/control.h13
-rw-r--r--tools/testing/vsock/timeout.c64
-rw-r--r--tools/testing/vsock/timeout.h14
-rw-r--r--tools/testing/vsock/vsock_diag_test.c681
66 files changed, 9779 insertions, 1355 deletions
diff --git a/tools/Makefile b/tools/Makefile
index c4f41ef9a7a7..c03b4f69d5b7 100644
--- a/tools/Makefile
+++ b/tools/Makefile
@@ -20,7 +20,7 @@ help:
20 @echo ' kvm_stat - top-like utility for displaying kvm statistics' 20 @echo ' kvm_stat - top-like utility for displaying kvm statistics'
21 @echo ' leds - LEDs tools' 21 @echo ' leds - LEDs tools'
22 @echo ' liblockdep - user-space wrapper for kernel locking-validator' 22 @echo ' liblockdep - user-space wrapper for kernel locking-validator'
23 @echo ' net - misc networking tools' 23 @echo ' bpf - misc BPF tools'
24 @echo ' perf - Linux performance measurement and analysis tool' 24 @echo ' perf - Linux performance measurement and analysis tool'
25 @echo ' selftests - various kernel selftests' 25 @echo ' selftests - various kernel selftests'
26 @echo ' spi - spi tools' 26 @echo ' spi - spi tools'
@@ -58,7 +58,7 @@ acpi: FORCE
58cpupower: FORCE 58cpupower: FORCE
59 $(call descend,power/$@) 59 $(call descend,power/$@)
60 60
61cgroup firewire hv guest spi usb virtio vm net iio gpio objtool leds: FORCE 61cgroup firewire hv guest spi usb virtio vm bpf iio gpio objtool leds: FORCE
62 $(call descend,$@) 62 $(call descend,$@)
63 63
64liblockdep: FORCE 64liblockdep: FORCE
@@ -92,7 +92,7 @@ kvm_stat: FORCE
92 92
93all: acpi cgroup cpupower gpio hv firewire liblockdep \ 93all: acpi cgroup cpupower gpio hv firewire liblockdep \
94 perf selftests spi turbostat usb \ 94 perf selftests spi turbostat usb \
95 virtio vm net x86_energy_perf_policy \ 95 virtio vm bpf x86_energy_perf_policy \
96 tmon freefall iio objtool kvm_stat 96 tmon freefall iio objtool kvm_stat
97 97
98acpi_install: 98acpi_install:
@@ -101,7 +101,7 @@ acpi_install:
101cpupower_install: 101cpupower_install:
102 $(call descend,power/$(@:_install=),install) 102 $(call descend,power/$(@:_install=),install)
103 103
104cgroup_install firewire_install gpio_install hv_install iio_install perf_install spi_install usb_install virtio_install vm_install net_install objtool_install: 104cgroup_install firewire_install gpio_install hv_install iio_install perf_install spi_install usb_install virtio_install vm_install bpf_install objtool_install:
105 $(call descend,$(@:_install=),install) 105 $(call descend,$(@:_install=),install)
106 106
107liblockdep_install: 107liblockdep_install:
@@ -125,7 +125,7 @@ kvm_stat_install:
125install: acpi_install cgroup_install cpupower_install gpio_install \ 125install: acpi_install cgroup_install cpupower_install gpio_install \
126 hv_install firewire_install iio_install liblockdep_install \ 126 hv_install firewire_install iio_install liblockdep_install \
127 perf_install selftests_install turbostat_install usb_install \ 127 perf_install selftests_install turbostat_install usb_install \
128 virtio_install vm_install net_install x86_energy_perf_policy_install \ 128 virtio_install vm_install bpf_install x86_energy_perf_policy_install \
129 tmon_install freefall_install objtool_install kvm_stat_install 129 tmon_install freefall_install objtool_install kvm_stat_install
130 130
131acpi_clean: 131acpi_clean:
@@ -134,7 +134,7 @@ acpi_clean:
134cpupower_clean: 134cpupower_clean:
135 $(call descend,power/cpupower,clean) 135 $(call descend,power/cpupower,clean)
136 136
137cgroup_clean hv_clean firewire_clean spi_clean usb_clean virtio_clean vm_clean net_clean iio_clean gpio_clean objtool_clean leds_clean: 137cgroup_clean hv_clean firewire_clean spi_clean usb_clean virtio_clean vm_clean bpf_clean iio_clean gpio_clean objtool_clean leds_clean:
138 $(call descend,$(@:_clean=),clean) 138 $(call descend,$(@:_clean=),clean)
139 139
140liblockdep_clean: 140liblockdep_clean:
@@ -170,7 +170,7 @@ build_clean:
170 170
171clean: acpi_clean cgroup_clean cpupower_clean hv_clean firewire_clean \ 171clean: acpi_clean cgroup_clean cpupower_clean hv_clean firewire_clean \
172 perf_clean selftests_clean turbostat_clean spi_clean usb_clean virtio_clean \ 172 perf_clean selftests_clean turbostat_clean spi_clean usb_clean virtio_clean \
173 vm_clean net_clean iio_clean x86_energy_perf_policy_clean tmon_clean \ 173 vm_clean bpf_clean iio_clean x86_energy_perf_policy_clean tmon_clean \
174 freefall_clean build_clean libbpf_clean libsubcmd_clean liblockdep_clean \ 174 freefall_clean build_clean libbpf_clean libsubcmd_clean liblockdep_clean \
175 gpio_clean objtool_clean leds_clean 175 gpio_clean objtool_clean leds_clean
176 176
diff --git a/tools/net/Makefile b/tools/bpf/Makefile
index 5830670feae1..07a6697466ef 100644
--- a/tools/net/Makefile
+++ b/tools/bpf/Makefile
@@ -4,6 +4,7 @@ prefix = /usr
4CC = gcc 4CC = gcc
5LEX = flex 5LEX = flex
6YACC = bison 6YACC = bison
7MAKE = make
7 8
8CFLAGS += -Wall -O2 9CFLAGS += -Wall -O2
9CFLAGS += -D__EXPORTED_HEADERS__ -I../../include/uapi -I../../include 10CFLAGS += -D__EXPORTED_HEADERS__ -I../../include/uapi -I../../include
@@ -14,7 +15,7 @@ CFLAGS += -D__EXPORTED_HEADERS__ -I../../include/uapi -I../../include
14%.lex.c: %.l 15%.lex.c: %.l
15 $(LEX) -o $@ $< 16 $(LEX) -o $@ $<
16 17
17all : bpf_jit_disasm bpf_dbg bpf_asm 18all: bpf_jit_disasm bpf_dbg bpf_asm bpftool
18 19
19bpf_jit_disasm : CFLAGS += -DPACKAGE='bpf_jit_disasm' 20bpf_jit_disasm : CFLAGS += -DPACKAGE='bpf_jit_disasm'
20bpf_jit_disasm : LDLIBS = -lopcodes -lbfd -ldl 21bpf_jit_disasm : LDLIBS = -lopcodes -lbfd -ldl
@@ -27,10 +28,21 @@ bpf_asm : LDLIBS =
27bpf_asm : bpf_asm.o bpf_exp.yacc.o bpf_exp.lex.o 28bpf_asm : bpf_asm.o bpf_exp.yacc.o bpf_exp.lex.o
28bpf_exp.lex.o : bpf_exp.yacc.c 29bpf_exp.lex.o : bpf_exp.yacc.c
29 30
30clean : 31clean: bpftool_clean
31 rm -rf *.o bpf_jit_disasm bpf_dbg bpf_asm bpf_exp.yacc.* bpf_exp.lex.* 32 rm -rf *.o bpf_jit_disasm bpf_dbg bpf_asm bpf_exp.yacc.* bpf_exp.lex.*
32 33
33install : 34install: bpftool_install
34 install bpf_jit_disasm $(prefix)/bin/bpf_jit_disasm 35 install bpf_jit_disasm $(prefix)/bin/bpf_jit_disasm
35 install bpf_dbg $(prefix)/bin/bpf_dbg 36 install bpf_dbg $(prefix)/bin/bpf_dbg
36 install bpf_asm $(prefix)/bin/bpf_asm 37 install bpf_asm $(prefix)/bin/bpf_asm
38
39bpftool:
40 $(MAKE) -C bpftool
41
42bpftool_install:
43 $(MAKE) -C bpftool install
44
45bpftool_clean:
46 $(MAKE) -C bpftool clean
47
48.PHONY: bpftool FORCE
diff --git a/tools/net/bpf_asm.c b/tools/bpf/bpf_asm.c
index c15aef097b04..c15aef097b04 100644
--- a/tools/net/bpf_asm.c
+++ b/tools/bpf/bpf_asm.c
diff --git a/tools/net/bpf_dbg.c b/tools/bpf/bpf_dbg.c
index 4f254bcc4423..4f254bcc4423 100644
--- a/tools/net/bpf_dbg.c
+++ b/tools/bpf/bpf_dbg.c
diff --git a/tools/net/bpf_exp.l b/tools/bpf/bpf_exp.l
index bd83149e7be0..bd83149e7be0 100644
--- a/tools/net/bpf_exp.l
+++ b/tools/bpf/bpf_exp.l
diff --git a/tools/net/bpf_exp.y b/tools/bpf/bpf_exp.y
index 56ba1de50784..56ba1de50784 100644
--- a/tools/net/bpf_exp.y
+++ b/tools/bpf/bpf_exp.y
diff --git a/tools/net/bpf_jit_disasm.c b/tools/bpf/bpf_jit_disasm.c
index 422d9abd666a..75bf526a0168 100644
--- a/tools/net/bpf_jit_disasm.c
+++ b/tools/bpf/bpf_jit_disasm.c
@@ -27,6 +27,7 @@
27#include <sys/klog.h> 27#include <sys/klog.h>
28#include <sys/types.h> 28#include <sys/types.h>
29#include <sys/stat.h> 29#include <sys/stat.h>
30#include <limits.h>
30 31
31#define CMD_ACTION_SIZE_BUFFER 10 32#define CMD_ACTION_SIZE_BUFFER 10
32#define CMD_ACTION_READ_ALL 3 33#define CMD_ACTION_READ_ALL 3
@@ -51,7 +52,7 @@ static void get_exec_path(char *tpath, size_t size)
51static void get_asm_insns(uint8_t *image, size_t len, int opcodes) 52static void get_asm_insns(uint8_t *image, size_t len, int opcodes)
52{ 53{
53 int count, i, pc = 0; 54 int count, i, pc = 0;
54 char tpath[256]; 55 char tpath[PATH_MAX];
55 struct disassemble_info info; 56 struct disassemble_info info;
56 disassembler_ftype disassemble; 57 disassembler_ftype disassemble;
57 bfd *bfdf; 58 bfd *bfdf;
diff --git a/tools/bpf/bpftool/Documentation/Makefile b/tools/bpf/bpftool/Documentation/Makefile
new file mode 100644
index 000000000000..bde77d7c4390
--- /dev/null
+++ b/tools/bpf/bpftool/Documentation/Makefile
@@ -0,0 +1,34 @@
1include ../../../scripts/Makefile.include
2include ../../../scripts/utilities.mak
3
4INSTALL ?= install
5RM ?= rm -f
6
7# Make the path relative to DESTDIR, not prefix
8ifndef DESTDIR
9prefix?=$(HOME)
10endif
11mandir ?= $(prefix)/share/man
12man8dir = $(mandir)/man8
13
14MAN8_RST = $(wildcard *.rst)
15
16_DOC_MAN8 = $(patsubst %.rst,%.8,$(MAN8_RST))
17DOC_MAN8 = $(addprefix $(OUTPUT),$(_DOC_MAN8))
18
19man: man8
20man8: $(DOC_MAN8)
21
22$(OUTPUT)%.8: %.rst
23 rst2man $< > $@
24
25clean:
26 $(call QUIET_CLEAN, Documentation) $(RM) $(DOC_MAN8)
27
28install: man
29 $(call QUIET_INSTALL, Documentation-man) \
30 $(INSTALL) -d -m 755 $(DESTDIR)$(man8dir); \
31 $(INSTALL) -m 644 $(DOC_MAN8) $(DESTDIR)$(man8dir);
32
33.PHONY: man man8 clean install
34.DEFAULT_GOAL := man
diff --git a/tools/bpf/bpftool/Documentation/bpftool-map.rst b/tools/bpf/bpftool/Documentation/bpftool-map.rst
new file mode 100644
index 000000000000..9f51a268eb06
--- /dev/null
+++ b/tools/bpf/bpftool/Documentation/bpftool-map.rst
@@ -0,0 +1,131 @@
1================
2bpftool-map
3================
4-------------------------------------------------------------------------------
5tool for inspection and simple manipulation of eBPF maps
6-------------------------------------------------------------------------------
7
8:Manual section: 8
9
10SYNOPSIS
11========
12
13 **bpftool** [*OPTIONS*] **map** *COMMAND*
14
15 *OPTIONS* := { { **-j** | **--json** } [{ **-p** | **--pretty** }] | { **-f** | **--bpffs** } }
16
17 *COMMANDS* :=
18 { **show** | **dump** | **update** | **lookup** | **getnext** | **delete**
19 | **pin** | **help** }
20
21MAP COMMANDS
22=============
23
24| **bpftool** **map show** [*MAP*]
25| **bpftool** **map dump** *MAP*
26| **bpftool** **map update** *MAP* **key** *BYTES* **value** *VALUE* [*UPDATE_FLAGS*]
27| **bpftool** **map lookup** *MAP* **key** *BYTES*
28| **bpftool** **map getnext** *MAP* [**key** *BYTES*]
29| **bpftool** **map delete** *MAP* **key** *BYTES*
30| **bpftool** **map pin** *MAP* *FILE*
31| **bpftool** **map help**
32|
33| *MAP* := { **id** *MAP_ID* | **pinned** *FILE* }
34| *VALUE* := { *BYTES* | *MAP* | *PROGRAM* }
35| *UPDATE_FLAGS* := { **any** | **exist** | **noexist** }
36
37DESCRIPTION
38===========
39 **bpftool map show** [*MAP*]
40 Show information about loaded maps. If *MAP* is specified
41 show information only about given map, otherwise list all
42 maps currently loaded on the system.
43
44 Output will start with map ID followed by map type and
45 zero or more named attributes (depending on kernel version).
46
47 **bpftool map dump** *MAP*
48 Dump all entries in a given *MAP*.
49
50 **bpftool map update** *MAP* **key** *BYTES* **value** *VALUE* [*UPDATE_FLAGS*]
51 Update map entry for a given *KEY*.
52
53 *UPDATE_FLAGS* can be one of: **any** update existing entry
54 or add if doesn't exit; **exist** update only if entry already
55 exists; **noexist** update only if entry doesn't exist.
56
57 **bpftool map lookup** *MAP* **key** *BYTES*
58 Lookup **key** in the map.
59
60 **bpftool map getnext** *MAP* [**key** *BYTES*]
61 Get next key. If *key* is not specified, get first key.
62
63 **bpftool map delete** *MAP* **key** *BYTES*
64 Remove entry from the map.
65
66 **bpftool map pin** *MAP* *FILE*
67 Pin map *MAP* as *FILE*.
68
69 Note: *FILE* must be located in *bpffs* mount.
70
71 **bpftool map help**
72 Print short help message.
73
74OPTIONS
75=======
76 -h, --help
77 Print short generic help message (similar to **bpftool help**).
78
79 -v, --version
80 Print version number (similar to **bpftool version**).
81
82 -j, --json
83 Generate JSON output. For commands that cannot produce JSON, this
84 option has no effect.
85
86 -p, --pretty
87 Generate human-readable JSON output. Implies **-j**.
88
89 -f, --bpffs
90 Show file names of pinned maps.
91
92EXAMPLES
93========
94**# bpftool map show**
95::
96
97 10: hash name some_map flags 0x0
98 key 4B value 8B max_entries 2048 memlock 167936B
99
100**# bpftool map update id 10 key 13 00 07 00 value 02 00 00 00 01 02 03 04**
101
102**# bpftool map lookup id 10 key 0 1 2 3**
103
104::
105
106 key: 00 01 02 03 value: 00 01 02 03 04 05 06 07
107
108
109**# bpftool map dump id 10**
110::
111
112 key: 00 01 02 03 value: 00 01 02 03 04 05 06 07
113 key: 0d 00 07 00 value: 02 00 00 00 01 02 03 04
114 Found 2 elements
115
116**# bpftool map getnext id 10 key 0 1 2 3**
117::
118
119 key:
120 00 01 02 03
121 next key:
122 0d 00 07 00
123
124|
125| **# mount -t bpf none /sys/fs/bpf/**
126| **# bpftool map pin id 10 /sys/fs/bpf/map**
127| **# bpftool map del pinned /sys/fs/bpf/map key 13 00 07 00**
128
129SEE ALSO
130========
131 **bpftool**\ (8), **bpftool-prog**\ (8)
diff --git a/tools/bpf/bpftool/Documentation/bpftool-prog.rst b/tools/bpf/bpftool/Documentation/bpftool-prog.rst
new file mode 100644
index 000000000000..36e8d1c3c40d
--- /dev/null
+++ b/tools/bpf/bpftool/Documentation/bpftool-prog.rst
@@ -0,0 +1,150 @@
1================
2bpftool-prog
3================
4-------------------------------------------------------------------------------
5tool for inspection and simple manipulation of eBPF progs
6-------------------------------------------------------------------------------
7
8:Manual section: 8
9
10SYNOPSIS
11========
12
13 **bpftool** [*OPTIONS*] **prog** *COMMAND*
14
15 *OPTIONS* := { { **-j** | **--json** } [{ **-p** | **--pretty** }] | { **-f** | **--bpffs** } }
16
17 *COMMANDS* :=
18 { **show** | **dump xlated** | **dump jited** | **pin** | **help** }
19
20MAP COMMANDS
21=============
22
23| **bpftool** **prog show** [*PROG*]
24| **bpftool** **prog dump xlated** *PROG* [{**file** *FILE* | **opcodes**}]
25| **bpftool** **prog dump jited** *PROG* [{**file** *FILE* | **opcodes**}]
26| **bpftool** **prog pin** *PROG* *FILE*
27| **bpftool** **prog help**
28|
29| *PROG* := { **id** *PROG_ID* | **pinned** *FILE* | **tag** *PROG_TAG* }
30
31DESCRIPTION
32===========
33 **bpftool prog show** [*PROG*]
34 Show information about loaded programs. If *PROG* is
35 specified show information only about given program, otherwise
36 list all programs currently loaded on the system.
37
38 Output will start with program ID followed by program type and
39 zero or more named attributes (depending on kernel version).
40
41 **bpftool prog dump xlated** *PROG* [{ **file** *FILE* | **opcodes** }]
42 Dump eBPF instructions of the program from the kernel.
43 If *FILE* is specified image will be written to a file,
44 otherwise it will be disassembled and printed to stdout.
45
46 **opcodes** controls if raw opcodes will be printed.
47
48 **bpftool prog dump jited** *PROG* [{ **file** *FILE* | **opcodes** }]
49 Dump jited image (host machine code) of the program.
50 If *FILE* is specified image will be written to a file,
51 otherwise it will be disassembled and printed to stdout.
52
53 **opcodes** controls if raw opcodes will be printed.
54
55 **bpftool prog pin** *PROG* *FILE*
56 Pin program *PROG* as *FILE*.
57
58 Note: *FILE* must be located in *bpffs* mount.
59
60 **bpftool prog help**
61 Print short help message.
62
63OPTIONS
64=======
65 -h, --help
66 Print short generic help message (similar to **bpftool help**).
67
68 -v, --version
69 Print version number (similar to **bpftool version**).
70
71 -j, --json
72 Generate JSON output. For commands that cannot produce JSON, this
73 option has no effect.
74
75 -p, --pretty
76 Generate human-readable JSON output. Implies **-j**.
77
78 -f, --bpffs
79 Show file names of pinned programs.
80
81EXAMPLES
82========
83**# bpftool prog show**
84::
85
86 10: xdp name some_prog tag 005a3d2123620c8b
87 loaded_at Sep 29/20:11 uid 0
88 xlated 528B jited 370B memlock 4096B map_ids 10
89
90**# bpftool --json --pretty prog show**
91
92::
93
94 {
95 "programs": [{
96 "id": 10,
97 "type": "xdp",
98 "tag": "005a3d2123620c8b",
99 "loaded_at": "Sep 29/20:11",
100 "uid": 0,
101 "bytes_xlated": 528,
102 "jited": true,
103 "bytes_jited": 370,
104 "bytes_memlock": 4096,
105 "map_ids": [10
106 ]
107 }
108 ]
109 }
110
111|
112| **# bpftool prog dump xlated id 10 file /tmp/t**
113| **# ls -l /tmp/t**
114| -rw------- 1 root root 560 Jul 22 01:42 /tmp/t
115
116**# bpftool prog dum jited tag 005a3d2123620c8b**
117
118::
119
120 push %rbp
121 mov %rsp,%rbp
122 sub $0x228,%rsp
123 sub $0x28,%rbp
124 mov %rbx,0x0(%rbp)
125
126|
127| **# mount -t bpf none /sys/fs/bpf/**
128| **# bpftool prog pin id 10 /sys/fs/bpf/prog**
129| **# ls -l /sys/fs/bpf/**
130| -rw------- 1 root root 0 Jul 22 01:43 prog
131
132**# bpftool prog dum jited pinned /sys/fs/bpf/prog opcodes**
133
134::
135
136 push %rbp
137 55
138 mov %rsp,%rbp
139 48 89 e5
140 sub $0x228,%rsp
141 48 81 ec 28 02 00 00
142 sub $0x28,%rbp
143 48 83 ed 28
144 mov %rbx,0x0(%rbp)
145 48 89 5d 00
146
147
148SEE ALSO
149========
150 **bpftool**\ (8), **bpftool-map**\ (8)
diff --git a/tools/bpf/bpftool/Documentation/bpftool.rst b/tools/bpf/bpftool/Documentation/bpftool.rst
new file mode 100644
index 000000000000..926c03d5a8da
--- /dev/null
+++ b/tools/bpf/bpftool/Documentation/bpftool.rst
@@ -0,0 +1,56 @@
1================
2BPFTOOL
3================
4-------------------------------------------------------------------------------
5tool for inspection and simple manipulation of eBPF programs and maps
6-------------------------------------------------------------------------------
7
8:Manual section: 8
9
10SYNOPSIS
11========
12
13 **bpftool** [*OPTIONS*] *OBJECT* { *COMMAND* | **help** }
14
15 **bpftool** **batch file** *FILE*
16
17 **bpftool** **version**
18
19 *OBJECT* := { **map** | **program** }
20
21 *OPTIONS* := { { **-V** | **--version** } | { **-h** | **--help** }
22 | { **-j** | **--json** } [{ **-p** | **--pretty** }] }
23
24 *MAP-COMMANDS* :=
25 { **show** | **dump** | **update** | **lookup** | **getnext** | **delete**
26 | **pin** | **help** }
27
28 *PROG-COMMANDS* := { **show** | **dump jited** | **dump xlated** | **pin**
29 | **help** }
30
31DESCRIPTION
32===========
33 *bpftool* allows for inspection and simple modification of BPF objects
34 on the system.
35
36 Note that format of the output of all tools is not guaranteed to be
37 stable and should not be depended upon.
38
39OPTIONS
40=======
41 -h, --help
42 Print short help message (similar to **bpftool help**).
43
44 -v, --version
45 Print version number (similar to **bpftool version**).
46
47 -j, --json
48 Generate JSON output. For commands that cannot produce JSON, this
49 option has no effect.
50
51 -p, --pretty
52 Generate human-readable JSON output. Implies **-j**.
53
54SEE ALSO
55========
56 **bpftool-map**\ (8), **bpftool-prog**\ (8)
diff --git a/tools/bpf/bpftool/Makefile b/tools/bpf/bpftool/Makefile
new file mode 100644
index 000000000000..813826c50936
--- /dev/null
+++ b/tools/bpf/bpftool/Makefile
@@ -0,0 +1,92 @@
1include ../../scripts/Makefile.include
2
3include ../../scripts/utilities.mak
4
5ifeq ($(srctree),)
6srctree := $(patsubst %/,%,$(dir $(CURDIR)))
7srctree := $(patsubst %/,%,$(dir $(srctree)))
8srctree := $(patsubst %/,%,$(dir $(srctree)))
9#$(info Determined 'srctree' to be $(srctree))
10endif
11
12ifneq ($(objtree),)
13#$(info Determined 'objtree' to be $(objtree))
14endif
15
16ifneq ($(OUTPUT),)
17#$(info Determined 'OUTPUT' to be $(OUTPUT))
18# Adding $(OUTPUT) as a directory to look for source files,
19# because use generated output files as sources dependency
20# for flex/bison parsers.
21VPATH += $(OUTPUT)
22export VPATH
23endif
24
25ifeq ($(V),1)
26 Q =
27else
28 Q = @
29endif
30
31BPF_DIR = $(srctree)/tools/lib/bpf/
32
33ifneq ($(OUTPUT),)
34 BPF_PATH=$(OUTPUT)
35else
36 BPF_PATH=$(BPF_DIR)
37endif
38
39LIBBPF = $(BPF_PATH)libbpf.a
40
41$(LIBBPF): FORCE
42 $(Q)$(MAKE) -C $(BPF_DIR) OUTPUT=$(OUTPUT) $(OUTPUT)libbpf.a FEATURES_DUMP=$(FEATURE_DUMP_EXPORT)
43
44$(LIBBPF)-clean:
45 $(call QUIET_CLEAN, libbpf)
46 $(Q)$(MAKE) -C $(BPF_DIR) OUTPUT=$(OUTPUT) clean >/dev/null
47
48prefix = /usr
49bash_compdir ?= $(prefix)/share/bash-completion/completions
50
51CC = gcc
52
53CFLAGS += -O2
54CFLAGS += -W -Wall -Wextra -Wno-unused-parameter -Wshadow
55CFLAGS += -D__EXPORTED_HEADERS__ -I$(srctree)/tools/include/uapi -I$(srctree)/tools/include -I$(srctree)/tools/lib/bpf -I$(srctree)/kernel/bpf/
56LIBS = -lelf -lbfd -lopcodes $(LIBBPF)
57
58include $(wildcard *.d)
59
60all: $(OUTPUT)bpftool
61
62SRCS=$(wildcard *.c)
63OBJS=$(patsubst %.c,$(OUTPUT)%.o,$(SRCS)) $(OUTPUT)disasm.o
64
65$(OUTPUT)disasm.o: $(srctree)/kernel/bpf/disasm.c
66 $(QUIET_CC)$(COMPILE.c) -MMD -o $@ $<
67
68$(OUTPUT)bpftool: $(OBJS) $(LIBBPF)
69 $(QUIET_LINK)$(CC) $(CFLAGS) -o $@ $^ $(LIBS)
70
71$(OUTPUT)%.o: %.c
72 $(QUIET_CC)$(COMPILE.c) -MMD -o $@ $<
73
74clean: $(LIBBPF)-clean
75 $(call QUIET_CLEAN, bpftool)
76 $(Q)rm -rf $(OUTPUT)bpftool $(OUTPUT)*.o $(OUTPUT)*.d
77
78install:
79 install $(OUTPUT)bpftool $(prefix)/sbin/bpftool
80 install -m 0755 -d $(bash_compdir)
81 install -m 0644 bash-completion/bpftool $(bash_compdir)
82
83doc:
84 $(Q)$(MAKE) -C Documentation/
85
86doc-install:
87 $(Q)$(MAKE) -C Documentation/ install
88
89FORCE:
90
91.PHONY: all clean FORCE
92.DEFAULT_GOAL := all
diff --git a/tools/bpf/bpftool/bash-completion/bpftool b/tools/bpf/bpftool/bash-completion/bpftool
new file mode 100644
index 000000000000..7febee05c8e7
--- /dev/null
+++ b/tools/bpf/bpftool/bash-completion/bpftool
@@ -0,0 +1,354 @@
1# bpftool(8) bash completion -*- shell-script -*-
2#
3# Copyright (C) 2017 Netronome Systems, Inc.
4#
5# This software is dual licensed under the GNU General License
6# Version 2, June 1991 as shown in the file COPYING in the top-level
7# directory of this source tree or the BSD 2-Clause License provided
8# below. You have the option to license this software under the
9# complete terms of either license.
10#
11# The BSD 2-Clause License:
12#
13# Redistribution and use in source and binary forms, with or
14# without modification, are permitted provided that the following
15# conditions are met:
16#
17# 1. Redistributions of source code must retain the above
18# copyright notice, this list of conditions and the following
19# disclaimer.
20#
21# 2. Redistributions in binary form must reproduce the above
22# copyright notice, this list of conditions and the following
23# disclaimer in the documentation and/or other materials
24# provided with the distribution.
25#
26# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
30# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
31# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
32# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
33# SOFTWARE.
34#
35# Author: Quentin Monnet <quentin.monnet@netronome.com>
36
37# Takes a list of words in argument; each one of them is added to COMPREPLY if
38# it is not already present on the command line. Returns no value.
39_bpftool_once_attr()
40{
41 local w idx found
42 for w in $*; do
43 found=0
44 for (( idx=3; idx < ${#words[@]}-1; idx++ )); do
45 if [[ $w == ${words[idx]} ]]; then
46 found=1
47 break
48 fi
49 done
50 [[ $found -eq 0 ]] && \
51 COMPREPLY+=( $( compgen -W "$w" -- "$cur" ) )
52 done
53}
54
55# Takes a list of words in argument; adds them all to COMPREPLY if none of them
56# is already present on the command line. Returns no value.
57_bpftool_one_of_list()
58{
59 local w idx
60 for w in $*; do
61 for (( idx=3; idx < ${#words[@]}-1; idx++ )); do
62 [[ $w == ${words[idx]} ]] && return 1
63 done
64 done
65 COMPREPLY+=( $( compgen -W "$*" -- "$cur" ) )
66}
67
68_bpftool_get_map_ids()
69{
70 COMPREPLY+=( $( compgen -W "$( bpftool -jp map 2>&1 | \
71 command sed -n 's/.*"id": \(.*\),$/\1/p' )" -- "$cur" ) )
72}
73
74_bpftool_get_prog_ids()
75{
76 COMPREPLY+=( $( compgen -W "$( bpftool -jp prog 2>&1 | \
77 command sed -n 's/.*"id": \(.*\),$/\1/p' )" -- "$cur" ) )
78}
79
80_bpftool_get_prog_tags()
81{
82 COMPREPLY+=( $( compgen -W "$( bpftool -jp prog 2>&1 | \
83 command sed -n 's/.*"tag": "\(.*\)",$/\1/p' )" -- "$cur" ) )
84}
85
86# For bpftool map update: retrieve type of the map to update.
87_bpftool_map_update_map_type()
88{
89 local keyword ref
90 for (( idx=3; idx < ${#words[@]}-1; idx++ )); do
91 if [[ ${words[$((idx-2))]} == "update" ]]; then
92 keyword=${words[$((idx-1))]}
93 ref=${words[$((idx))]}
94 fi
95 done
96 [[ -z $ref ]] && return 0
97
98 local type
99 type=$(bpftool -jp map show $keyword $ref | \
100 command sed -n 's/.*"type": "\(.*\)",$/\1/p')
101 printf $type
102}
103
104_bpftool_map_update_get_id()
105{
106 # Is it the map to update, or a map to insert into the map to update?
107 # Search for "value" keyword.
108 local idx value
109 for (( idx=7; idx < ${#words[@]}-1; idx++ )); do
110 if [[ ${words[idx]} == "value" ]]; then
111 value=1
112 break
113 fi
114 done
115 [[ $value -eq 0 ]] && _bpftool_get_map_ids && return 0
116
117 # Id to complete is for a value. It can be either prog id or map id. This
118 # depends on the type of the map to update.
119 local type=$(_bpftool_map_update_map_type)
120 case $type in
121 array_of_maps|hash_of_maps)
122 _bpftool_get_map_ids
123 return 0
124 ;;
125 prog_array)
126 _bpftool_get_prog_ids
127 return 0
128 ;;
129 *)
130 return 0
131 ;;
132 esac
133}
134
135_bpftool()
136{
137 local cur prev words objword
138 _init_completion || return
139
140 # Deal with simplest keywords
141 case $prev in
142 help|key|opcodes)
143 return 0
144 ;;
145 tag)
146 _bpftool_get_prog_tags
147 return 0
148 ;;
149 file|pinned)
150 _filedir
151 return 0
152 ;;
153 batch)
154 COMPREPLY=( $( compgen -W 'file' -- "$cur" ) )
155 return 0
156 ;;
157 esac
158
159 # Search for object and command
160 local object command cmdword
161 for (( cmdword=1; cmdword < ${#words[@]}-1; cmdword++ )); do
162 [[ -n $object ]] && command=${words[cmdword]} && break
163 [[ ${words[cmdword]} != -* ]] && object=${words[cmdword]}
164 done
165
166 if [[ -z $object ]]; then
167 case $cur in
168 -*)
169 local c='--version --json --pretty'
170 COMPREPLY=( $( compgen -W "$c" -- "$cur" ) )
171 return 0
172 ;;
173 *)
174 COMPREPLY=( $( compgen -W "$( bpftool help 2>&1 | \
175 command sed \
176 -e '/OBJECT := /!d' \
177 -e 's/.*{//' \
178 -e 's/}.*//' \
179 -e 's/|//g' )" -- "$cur" ) )
180 COMPREPLY+=( $( compgen -W 'batch help' -- "$cur" ) )
181 return 0
182 ;;
183 esac
184 fi
185
186 [[ $command == help ]] && return 0
187
188 # Completion depends on object and command in use
189 case $object in
190 prog)
191 case $prev in
192 id)
193 _bpftool_get_prog_ids
194 return 0
195 ;;
196 esac
197
198 local PROG_TYPE='id pinned tag'
199 case $command in
200 show)
201 [[ $prev != "$command" ]] && return 0
202 COMPREPLY=( $( compgen -W "$PROG_TYPE" -- "$cur" ) )
203 return 0
204 ;;
205 dump)
206 case $prev in
207 $command)
208 COMPREPLY+=( $( compgen -W "xlated jited" -- \
209 "$cur" ) )
210 return 0
211 ;;
212 xlated|jited)
213 COMPREPLY=( $( compgen -W "$PROG_TYPE" -- \
214 "$cur" ) )
215 return 0
216 ;;
217 *)
218 _bpftool_once_attr 'file'
219 COMPREPLY+=( $( compgen -W 'opcodes' -- \
220 "$cur" ) )
221 return 0
222 ;;
223 esac
224 ;;
225 pin)
226 if [[ $prev == "$command" ]]; then
227 COMPREPLY=( $( compgen -W "$PROG_TYPE" -- "$cur" ) )
228 else
229 _filedir
230 fi
231 return 0
232 ;;
233 *)
234 [[ $prev == $object ]] && \
235 COMPREPLY=( $( compgen -W 'dump help pin show' -- \
236 "$cur" ) )
237 ;;
238 esac
239 ;;
240 map)
241 local MAP_TYPE='id pinned'
242 case $command in
243 show|dump)
244 case $prev in
245 $command)
246 COMPREPLY=( $( compgen -W "$MAP_TYPE" -- "$cur" ) )
247 return 0
248 ;;
249 id)
250 _bpftool_get_map_ids
251 return 0
252 ;;
253 *)
254 return 0
255 ;;
256 esac
257 ;;
258 lookup|getnext|delete)
259 case $prev in
260 $command)
261 COMPREPLY=( $( compgen -W "$MAP_TYPE" -- "$cur" ) )
262 return 0
263 ;;
264 id)
265 _bpftool_get_map_ids
266 return 0
267 ;;
268 key)
269 return 0
270 ;;
271 *)
272 _bpftool_once_attr 'key'
273 return 0
274 ;;
275 esac
276 ;;
277 update)
278 case $prev in
279 $command)
280 COMPREPLY=( $( compgen -W "$MAP_TYPE" -- "$cur" ) )
281 return 0
282 ;;
283 id)
284 _bpftool_map_update_get_id
285 return 0
286 ;;
287 key)
288 return 0
289 ;;
290 value)
291 # We can have bytes, or references to a prog or a
292 # map, depending on the type of the map to update.
293 case $(_bpftool_map_update_map_type) in
294 array_of_maps|hash_of_maps)
295 local MAP_TYPE='id pinned'
296 COMPREPLY+=( $( compgen -W "$MAP_TYPE" \
297 -- "$cur" ) )
298 return 0
299 ;;
300 prog_array)
301 local PROG_TYPE='id pinned tag'
302 COMPREPLY+=( $( compgen -W "$PROG_TYPE" \
303 -- "$cur" ) )
304 return 0
305 ;;
306 *)
307 return 0
308 ;;
309 esac
310 return 0
311 ;;
312 *)
313 _bpftool_once_attr 'key'
314 local UPDATE_FLAGS='any exist noexist'
315 for (( idx=3; idx < ${#words[@]}-1; idx++ )); do
316 if [[ ${words[idx]} == 'value' ]]; then
317 # 'value' is present, but is not the last
318 # word i.e. we can now have UPDATE_FLAGS.
319 _bpftool_one_of_list "$UPDATE_FLAGS"
320 return 0
321 fi
322 done
323 for (( idx=3; idx < ${#words[@]}-1; idx++ )); do
324 if [[ ${words[idx]} == 'key' ]]; then
325 # 'key' is present, but is not the last
326 # word i.e. we can now have 'value'.
327 _bpftool_once_attr 'value'
328 return 0
329 fi
330 done
331 return 0
332 ;;
333 esac
334 ;;
335 pin)
336 if [[ $prev == "$command" ]]; then
337 COMPREPLY=( $( compgen -W "$PROG_TYPE" -- "$cur" ) )
338 else
339 _filedir
340 fi
341 return 0
342 ;;
343 *)
344 [[ $prev == $object ]] && \
345 COMPREPLY=( $( compgen -W 'delete dump getnext help \
346 lookup pin show update' -- "$cur" ) )
347 ;;
348 esac
349 ;;
350 esac
351} &&
352complete -F _bpftool bpftool
353
354# ex: ts=4 sw=4 et filetype=sh
diff --git a/tools/bpf/bpftool/common.c b/tools/bpf/bpftool/common.c
new file mode 100644
index 000000000000..2bd3b280e6dd
--- /dev/null
+++ b/tools/bpf/bpftool/common.c
@@ -0,0 +1,405 @@
1/*
2 * Copyright (C) 2017 Netronome Systems, Inc.
3 *
4 * This software is dual licensed under the GNU General License Version 2,
5 * June 1991 as shown in the file COPYING in the top-level directory of this
6 * source tree or the BSD 2-Clause License provided below. You have the
7 * option to license this software under the complete terms of either license.
8 *
9 * The BSD 2-Clause License:
10 *
11 * Redistribution and use in source and binary forms, with or
12 * without modification, are permitted provided that the following
13 * conditions are met:
14 *
15 * 1. Redistributions of source code must retain the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer.
18 *
19 * 2. Redistributions in binary form must reproduce the above
20 * copyright notice, this list of conditions and the following
21 * disclaimer in the documentation and/or other materials
22 * provided with the distribution.
23 *
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 * SOFTWARE.
32 */
33
34/* Author: Jakub Kicinski <kubakici@wp.pl> */
35
36#include <errno.h>
37#include <fts.h>
38#include <libgen.h>
39#include <mntent.h>
40#include <stdbool.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44#include <unistd.h>
45#include <linux/limits.h>
46#include <linux/magic.h>
47#include <sys/mount.h>
48#include <sys/types.h>
49#include <sys/vfs.h>
50
51#include <bpf.h>
52
53#include "main.h"
54
55void p_err(const char *fmt, ...)
56{
57 va_list ap;
58
59 va_start(ap, fmt);
60 if (json_output) {
61 jsonw_start_object(json_wtr);
62 jsonw_name(json_wtr, "error");
63 jsonw_vprintf_enquote(json_wtr, fmt, ap);
64 jsonw_end_object(json_wtr);
65 } else {
66 fprintf(stderr, "Error: ");
67 vfprintf(stderr, fmt, ap);
68 fprintf(stderr, "\n");
69 }
70 va_end(ap);
71}
72
73void p_info(const char *fmt, ...)
74{
75 va_list ap;
76
77 if (json_output)
78 return;
79
80 va_start(ap, fmt);
81 vfprintf(stderr, fmt, ap);
82 fprintf(stderr, "\n");
83 va_end(ap);
84}
85
86static bool is_bpffs(char *path)
87{
88 struct statfs st_fs;
89
90 if (statfs(path, &st_fs) < 0)
91 return false;
92
93 return (unsigned long)st_fs.f_type == BPF_FS_MAGIC;
94}
95
96static int mnt_bpffs(const char *target, char *buff, size_t bufflen)
97{
98 bool bind_done = false;
99
100 while (mount("", target, "none", MS_PRIVATE | MS_REC, NULL)) {
101 if (errno != EINVAL || bind_done) {
102 snprintf(buff, bufflen,
103 "mount --make-private %s failed: %s",
104 target, strerror(errno));
105 return -1;
106 }
107
108 if (mount(target, target, "none", MS_BIND, NULL)) {
109 snprintf(buff, bufflen,
110 "mount --bind %s %s failed: %s",
111 target, target, strerror(errno));
112 return -1;
113 }
114
115 bind_done = true;
116 }
117
118 if (mount("bpf", target, "bpf", 0, "mode=0700")) {
119 snprintf(buff, bufflen, "mount -t bpf bpf %s failed: %s",
120 target, strerror(errno));
121 return -1;
122 }
123
124 return 0;
125}
126
127int open_obj_pinned(char *path)
128{
129 int fd;
130
131 fd = bpf_obj_get(path);
132 if (fd < 0) {
133 p_err("bpf obj get (%s): %s", path,
134 errno == EACCES && !is_bpffs(dirname(path)) ?
135 "directory not in bpf file system (bpffs)" :
136 strerror(errno));
137 return -1;
138 }
139
140 return fd;
141}
142
143int open_obj_pinned_any(char *path, enum bpf_obj_type exp_type)
144{
145 enum bpf_obj_type type;
146 int fd;
147
148 fd = open_obj_pinned(path);
149 if (fd < 0)
150 return -1;
151
152 type = get_fd_type(fd);
153 if (type < 0) {
154 close(fd);
155 return type;
156 }
157 if (type != exp_type) {
158 p_err("incorrect object type: %s", get_fd_type_name(type));
159 close(fd);
160 return -1;
161 }
162
163 return fd;
164}
165
166int do_pin_any(int argc, char **argv, int (*get_fd_by_id)(__u32))
167{
168 char err_str[ERR_MAX_LEN];
169 unsigned int id;
170 char *endptr;
171 char *file;
172 char *dir;
173 int err;
174 int fd;
175
176 if (!is_prefix(*argv, "id")) {
177 p_err("expected 'id' got %s", *argv);
178 return -1;
179 }
180 NEXT_ARG();
181
182 id = strtoul(*argv, &endptr, 0);
183 if (*endptr) {
184 p_err("can't parse %s as ID", *argv);
185 return -1;
186 }
187 NEXT_ARG();
188
189 if (argc != 1)
190 usage();
191
192 fd = get_fd_by_id(id);
193 if (fd < 0) {
194 p_err("can't get prog by id (%u): %s", id, strerror(errno));
195 return -1;
196 }
197
198 err = bpf_obj_pin(fd, *argv);
199 if (!err)
200 goto out_close;
201
202 file = malloc(strlen(*argv) + 1);
203 strcpy(file, *argv);
204 dir = dirname(file);
205
206 if (errno != EPERM || is_bpffs(dir)) {
207 p_err("can't pin the object (%s): %s", *argv, strerror(errno));
208 goto out_free;
209 }
210
211 /* Attempt to mount bpffs, then retry pinning. */
212 err = mnt_bpffs(dir, err_str, ERR_MAX_LEN);
213 if (!err) {
214 err = bpf_obj_pin(fd, *argv);
215 if (err)
216 p_err("can't pin the object (%s): %s", *argv,
217 strerror(errno));
218 } else {
219 err_str[ERR_MAX_LEN - 1] = '\0';
220 p_err("can't mount BPF file system to pin the object (%s): %s",
221 *argv, err_str);
222 }
223
224out_free:
225 free(file);
226out_close:
227 close(fd);
228 return err;
229}
230
231const char *get_fd_type_name(enum bpf_obj_type type)
232{
233 static const char * const names[] = {
234 [BPF_OBJ_UNKNOWN] = "unknown",
235 [BPF_OBJ_PROG] = "prog",
236 [BPF_OBJ_MAP] = "map",
237 };
238
239 if (type < 0 || type >= ARRAY_SIZE(names) || !names[type])
240 return names[BPF_OBJ_UNKNOWN];
241
242 return names[type];
243}
244
245int get_fd_type(int fd)
246{
247 char path[PATH_MAX];
248 char buf[512];
249 ssize_t n;
250
251 snprintf(path, sizeof(path), "/proc/%d/fd/%d", getpid(), fd);
252
253 n = readlink(path, buf, sizeof(buf));
254 if (n < 0) {
255 p_err("can't read link type: %s", strerror(errno));
256 return -1;
257 }
258 if (n == sizeof(path)) {
259 p_err("can't read link type: path too long!");
260 return -1;
261 }
262
263 if (strstr(buf, "bpf-map"))
264 return BPF_OBJ_MAP;
265 else if (strstr(buf, "bpf-prog"))
266 return BPF_OBJ_PROG;
267
268 return BPF_OBJ_UNKNOWN;
269}
270
271char *get_fdinfo(int fd, const char *key)
272{
273 char path[PATH_MAX];
274 char *line = NULL;
275 size_t line_n = 0;
276 ssize_t n;
277 FILE *fdi;
278
279 snprintf(path, sizeof(path), "/proc/%d/fdinfo/%d", getpid(), fd);
280
281 fdi = fopen(path, "r");
282 if (!fdi) {
283 p_err("can't open fdinfo: %s", strerror(errno));
284 return NULL;
285 }
286
287 while ((n = getline(&line, &line_n, fdi))) {
288 char *value;
289 int len;
290
291 if (!strstr(line, key))
292 continue;
293
294 fclose(fdi);
295
296 value = strchr(line, '\t');
297 if (!value || !value[1]) {
298 p_err("malformed fdinfo!?");
299 free(line);
300 return NULL;
301 }
302 value++;
303
304 len = strlen(value);
305 memmove(line, value, len);
306 line[len - 1] = '\0';
307
308 return line;
309 }
310
311 p_err("key '%s' not found in fdinfo", key);
312 free(line);
313 fclose(fdi);
314 return NULL;
315}
316
317void print_hex_data_json(uint8_t *data, size_t len)
318{
319 unsigned int i;
320
321 jsonw_start_array(json_wtr);
322 for (i = 0; i < len; i++)
323 jsonw_printf(json_wtr, "\"0x%02hhx\"", data[i]);
324 jsonw_end_array(json_wtr);
325}
326
327int build_pinned_obj_table(struct pinned_obj_table *tab,
328 enum bpf_obj_type type)
329{
330 struct bpf_prog_info pinned_info = {};
331 struct pinned_obj *obj_node = NULL;
332 __u32 len = sizeof(pinned_info);
333 struct mntent *mntent = NULL;
334 enum bpf_obj_type objtype;
335 FILE *mntfile = NULL;
336 FTSENT *ftse = NULL;
337 FTS *fts = NULL;
338 int fd, err;
339
340 mntfile = setmntent("/proc/mounts", "r");
341 if (!mntfile)
342 return -1;
343
344 while ((mntent = getmntent(mntfile))) {
345 char *path[] = { mntent->mnt_dir, NULL };
346
347 if (strncmp(mntent->mnt_type, "bpf", 3) != 0)
348 continue;
349
350 fts = fts_open(path, 0, NULL);
351 if (!fts)
352 continue;
353
354 while ((ftse = fts_read(fts))) {
355 if (!(ftse->fts_info & FTS_F))
356 continue;
357 fd = open_obj_pinned(ftse->fts_path);
358 if (fd < 0)
359 continue;
360
361 objtype = get_fd_type(fd);
362 if (objtype != type) {
363 close(fd);
364 continue;
365 }
366 memset(&pinned_info, 0, sizeof(pinned_info));
367 err = bpf_obj_get_info_by_fd(fd, &pinned_info, &len);
368 if (err) {
369 close(fd);
370 continue;
371 }
372
373 obj_node = malloc(sizeof(*obj_node));
374 if (!obj_node) {
375 close(fd);
376 fts_close(fts);
377 fclose(mntfile);
378 return -1;
379 }
380
381 memset(obj_node, 0, sizeof(*obj_node));
382 obj_node->id = pinned_info.id;
383 obj_node->path = strdup(ftse->fts_path);
384 hash_add(tab->table, &obj_node->hash, obj_node->id);
385
386 close(fd);
387 }
388 fts_close(fts);
389 }
390 fclose(mntfile);
391 return 0;
392}
393
394void delete_pinned_obj_table(struct pinned_obj_table *tab)
395{
396 struct pinned_obj *obj;
397 struct hlist_node *tmp;
398 unsigned int bkt;
399
400 hash_for_each_safe(tab->table, bkt, tmp, obj, hash) {
401 hash_del(&obj->hash);
402 free(obj->path);
403 free(obj);
404 }
405}
diff --git a/tools/bpf/bpftool/jit_disasm.c b/tools/bpf/bpftool/jit_disasm.c
new file mode 100644
index 000000000000..1551d3918d4c
--- /dev/null
+++ b/tools/bpf/bpftool/jit_disasm.c
@@ -0,0 +1,162 @@
1/*
2 * Based on:
3 *
4 * Minimal BPF JIT image disassembler
5 *
6 * Disassembles BPF JIT compiler emitted opcodes back to asm insn's for
7 * debugging or verification purposes.
8 *
9 * Copyright 2013 Daniel Borkmann <daniel@iogearbox.net>
10 * Licensed under the GNU General Public License, version 2.0 (GPLv2)
11 */
12
13#include <stdarg.h>
14#include <stdint.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <assert.h>
18#include <unistd.h>
19#include <string.h>
20#include <bfd.h>
21#include <dis-asm.h>
22#include <sys/types.h>
23#include <sys/stat.h>
24#include <limits.h>
25
26#include "json_writer.h"
27#include "main.h"
28
29static void get_exec_path(char *tpath, size_t size)
30{
31 ssize_t len;
32 char *path;
33
34 snprintf(tpath, size, "/proc/%d/exe", (int) getpid());
35 tpath[size - 1] = 0;
36
37 path = strdup(tpath);
38 assert(path);
39
40 len = readlink(path, tpath, size - 1);
41 assert(len > 0);
42 tpath[len] = 0;
43
44 free(path);
45}
46
47static int oper_count;
48static int fprintf_json(void *out, const char *fmt, ...)
49{
50 va_list ap;
51 char *s;
52
53 va_start(ap, fmt);
54 if (!oper_count) {
55 int i;
56
57 s = va_arg(ap, char *);
58
59 /* Strip trailing spaces */
60 i = strlen(s) - 1;
61 while (s[i] == ' ')
62 s[i--] = '\0';
63
64 jsonw_string_field(json_wtr, "operation", s);
65 jsonw_name(json_wtr, "operands");
66 jsonw_start_array(json_wtr);
67 oper_count++;
68 } else if (!strcmp(fmt, ",")) {
69 /* Skip */
70 } else {
71 s = va_arg(ap, char *);
72 jsonw_string(json_wtr, s);
73 oper_count++;
74 }
75 va_end(ap);
76 return 0;
77}
78
79void disasm_print_insn(unsigned char *image, ssize_t len, int opcodes)
80{
81 disassembler_ftype disassemble;
82 struct disassemble_info info;
83 int count, i, pc = 0;
84 char tpath[PATH_MAX];
85 bfd *bfdf;
86
87 if (!len)
88 return;
89
90 memset(tpath, 0, sizeof(tpath));
91 get_exec_path(tpath, sizeof(tpath));
92
93 bfdf = bfd_openr(tpath, NULL);
94 assert(bfdf);
95 assert(bfd_check_format(bfdf, bfd_object));
96
97 if (json_output)
98 init_disassemble_info(&info, stdout,
99 (fprintf_ftype) fprintf_json);
100 else
101 init_disassemble_info(&info, stdout,
102 (fprintf_ftype) fprintf);
103 info.arch = bfd_get_arch(bfdf);
104 info.mach = bfd_get_mach(bfdf);
105 info.buffer = image;
106 info.buffer_length = len;
107
108 disassemble_init_for_target(&info);
109
110 disassemble = disassembler(bfdf);
111 assert(disassemble);
112
113 if (json_output)
114 jsonw_start_array(json_wtr);
115 do {
116 if (json_output) {
117 jsonw_start_object(json_wtr);
118 oper_count = 0;
119 jsonw_name(json_wtr, "pc");
120 jsonw_printf(json_wtr, "\"0x%x\"", pc);
121 } else {
122 printf("%4x:\t", pc);
123 }
124
125 count = disassemble(pc, &info);
126 if (json_output) {
127 /* Operand array, was started in fprintf_json. Before
128 * that, make sure we have a _null_ value if no operand
129 * other than operation code was present.
130 */
131 if (oper_count == 1)
132 jsonw_null(json_wtr);
133 jsonw_end_array(json_wtr);
134 }
135
136 if (opcodes) {
137 if (json_output) {
138 jsonw_name(json_wtr, "opcodes");
139 jsonw_start_array(json_wtr);
140 for (i = 0; i < count; ++i)
141 jsonw_printf(json_wtr, "\"0x%02hhx\"",
142 (uint8_t)image[pc + i]);
143 jsonw_end_array(json_wtr);
144 } else {
145 printf("\n\t");
146 for (i = 0; i < count; ++i)
147 printf("%02x ",
148 (uint8_t)image[pc + i]);
149 }
150 }
151 if (json_output)
152 jsonw_end_object(json_wtr);
153 else
154 printf("\n");
155
156 pc += count;
157 } while (count > 0 && pc < len);
158 if (json_output)
159 jsonw_end_array(json_wtr);
160
161 bfd_close(bfdf);
162}
diff --git a/tools/bpf/bpftool/json_writer.c b/tools/bpf/bpftool/json_writer.c
new file mode 100644
index 000000000000..c6eef76322ae
--- /dev/null
+++ b/tools/bpf/bpftool/json_writer.c
@@ -0,0 +1,356 @@
1/*
2 * Simple streaming JSON writer
3 *
4 * This takes care of the annoying bits of JSON syntax like the commas
5 * after elements
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 *
12 * Authors: Stephen Hemminger <stephen@networkplumber.org>
13 */
14
15#include <stdio.h>
16#include <stdbool.h>
17#include <stdarg.h>
18#include <assert.h>
19#include <malloc.h>
20#include <inttypes.h>
21#include <stdint.h>
22
23#include "json_writer.h"
24
25struct json_writer {
26 FILE *out; /* output file */
27 unsigned depth; /* nesting */
28 bool pretty; /* optional whitepace */
29 char sep; /* either nul or comma */
30};
31
32/* indentation for pretty print */
33static void jsonw_indent(json_writer_t *self)
34{
35 unsigned i;
36 for (i = 0; i < self->depth; ++i)
37 fputs(" ", self->out);
38}
39
40/* end current line and indent if pretty printing */
41static void jsonw_eol(json_writer_t *self)
42{
43 if (!self->pretty)
44 return;
45
46 putc('\n', self->out);
47 jsonw_indent(self);
48}
49
50/* If current object is not empty print a comma */
51static void jsonw_eor(json_writer_t *self)
52{
53 if (self->sep != '\0')
54 putc(self->sep, self->out);
55 self->sep = ',';
56}
57
58
59/* Output JSON encoded string */
60/* Handles C escapes, does not do Unicode */
61static void jsonw_puts(json_writer_t *self, const char *str)
62{
63 putc('"', self->out);
64 for (; *str; ++str)
65 switch (*str) {
66 case '\t':
67 fputs("\\t", self->out);
68 break;
69 case '\n':
70 fputs("\\n", self->out);
71 break;
72 case '\r':
73 fputs("\\r", self->out);
74 break;
75 case '\f':
76 fputs("\\f", self->out);
77 break;
78 case '\b':
79 fputs("\\b", self->out);
80 break;
81 case '\\':
82 fputs("\\n", self->out);
83 break;
84 case '"':
85 fputs("\\\"", self->out);
86 break;
87 case '\'':
88 fputs("\\\'", self->out);
89 break;
90 default:
91 putc(*str, self->out);
92 }
93 putc('"', self->out);
94}
95
96/* Create a new JSON stream */
97json_writer_t *jsonw_new(FILE *f)
98{
99 json_writer_t *self = malloc(sizeof(*self));
100 if (self) {
101 self->out = f;
102 self->depth = 0;
103 self->pretty = false;
104 self->sep = '\0';
105 }
106 return self;
107}
108
109/* End output to JSON stream */
110void jsonw_destroy(json_writer_t **self_p)
111{
112 json_writer_t *self = *self_p;
113
114 assert(self->depth == 0);
115 fputs("\n", self->out);
116 fflush(self->out);
117 free(self);
118 *self_p = NULL;
119}
120
121void jsonw_pretty(json_writer_t *self, bool on)
122{
123 self->pretty = on;
124}
125
126/* Basic blocks */
127static void jsonw_begin(json_writer_t *self, int c)
128{
129 jsonw_eor(self);
130 putc(c, self->out);
131 ++self->depth;
132 self->sep = '\0';
133}
134
135static void jsonw_end(json_writer_t *self, int c)
136{
137 assert(self->depth > 0);
138
139 --self->depth;
140 if (self->sep != '\0')
141 jsonw_eol(self);
142 putc(c, self->out);
143 self->sep = ',';
144}
145
146
147/* Add a JSON property name */
148void jsonw_name(json_writer_t *self, const char *name)
149{
150 jsonw_eor(self);
151 jsonw_eol(self);
152 self->sep = '\0';
153 jsonw_puts(self, name);
154 putc(':', self->out);
155 if (self->pretty)
156 putc(' ', self->out);
157}
158
159void jsonw_vprintf_enquote(json_writer_t *self, const char *fmt, va_list ap)
160{
161 jsonw_eor(self);
162 putc('"', self->out);
163 vfprintf(self->out, fmt, ap);
164 putc('"', self->out);
165}
166
167void jsonw_printf(json_writer_t *self, const char *fmt, ...)
168{
169 va_list ap;
170
171 va_start(ap, fmt);
172 jsonw_eor(self);
173 vfprintf(self->out, fmt, ap);
174 va_end(ap);
175}
176
177/* Collections */
178void jsonw_start_object(json_writer_t *self)
179{
180 jsonw_begin(self, '{');
181}
182
183void jsonw_end_object(json_writer_t *self)
184{
185 jsonw_end(self, '}');
186}
187
188void jsonw_start_array(json_writer_t *self)
189{
190 jsonw_begin(self, '[');
191}
192
193void jsonw_end_array(json_writer_t *self)
194{
195 jsonw_end(self, ']');
196}
197
198/* JSON value types */
199void jsonw_string(json_writer_t *self, const char *value)
200{
201 jsonw_eor(self);
202 jsonw_puts(self, value);
203}
204
205void jsonw_bool(json_writer_t *self, bool val)
206{
207 jsonw_printf(self, "%s", val ? "true" : "false");
208}
209
210void jsonw_null(json_writer_t *self)
211{
212 jsonw_printf(self, "null");
213}
214
215void jsonw_float_fmt(json_writer_t *self, const char *fmt, double num)
216{
217 jsonw_printf(self, fmt, num);
218}
219
220#ifdef notused
221void jsonw_float(json_writer_t *self, double num)
222{
223 jsonw_printf(self, "%g", num);
224}
225#endif
226
227void jsonw_hu(json_writer_t *self, unsigned short num)
228{
229 jsonw_printf(self, "%hu", num);
230}
231
232void jsonw_uint(json_writer_t *self, uint64_t num)
233{
234 jsonw_printf(self, "%"PRIu64, num);
235}
236
237void jsonw_lluint(json_writer_t *self, unsigned long long int num)
238{
239 jsonw_printf(self, "%llu", num);
240}
241
242void jsonw_int(json_writer_t *self, int64_t num)
243{
244 jsonw_printf(self, "%"PRId64, num);
245}
246
247/* Basic name/value objects */
248void jsonw_string_field(json_writer_t *self, const char *prop, const char *val)
249{
250 jsonw_name(self, prop);
251 jsonw_string(self, val);
252}
253
254void jsonw_bool_field(json_writer_t *self, const char *prop, bool val)
255{
256 jsonw_name(self, prop);
257 jsonw_bool(self, val);
258}
259
260#ifdef notused
261void jsonw_float_field(json_writer_t *self, const char *prop, double val)
262{
263 jsonw_name(self, prop);
264 jsonw_float(self, val);
265}
266#endif
267
268void jsonw_float_field_fmt(json_writer_t *self,
269 const char *prop,
270 const char *fmt,
271 double val)
272{
273 jsonw_name(self, prop);
274 jsonw_float_fmt(self, fmt, val);
275}
276
277void jsonw_uint_field(json_writer_t *self, const char *prop, uint64_t num)
278{
279 jsonw_name(self, prop);
280 jsonw_uint(self, num);
281}
282
283void jsonw_hu_field(json_writer_t *self, const char *prop, unsigned short num)
284{
285 jsonw_name(self, prop);
286 jsonw_hu(self, num);
287}
288
289void jsonw_lluint_field(json_writer_t *self,
290 const char *prop,
291 unsigned long long int num)
292{
293 jsonw_name(self, prop);
294 jsonw_lluint(self, num);
295}
296
297void jsonw_int_field(json_writer_t *self, const char *prop, int64_t num)
298{
299 jsonw_name(self, prop);
300 jsonw_int(self, num);
301}
302
303void jsonw_null_field(json_writer_t *self, const char *prop)
304{
305 jsonw_name(self, prop);
306 jsonw_null(self);
307}
308
309#ifdef TEST
310int main(int argc, char **argv)
311{
312 json_writer_t *wr = jsonw_new(stdout);
313
314 jsonw_start_object(wr);
315 jsonw_pretty(wr, true);
316 jsonw_name(wr, "Vyatta");
317 jsonw_start_object(wr);
318 jsonw_string_field(wr, "url", "http://vyatta.com");
319 jsonw_uint_field(wr, "downloads", 2000000ul);
320 jsonw_float_field(wr, "stock", 8.16);
321
322 jsonw_name(wr, "ARGV");
323 jsonw_start_array(wr);
324 while (--argc)
325 jsonw_string(wr, *++argv);
326 jsonw_end_array(wr);
327
328 jsonw_name(wr, "empty");
329 jsonw_start_array(wr);
330 jsonw_end_array(wr);
331
332 jsonw_name(wr, "NIL");
333 jsonw_start_object(wr);
334 jsonw_end_object(wr);
335
336 jsonw_null_field(wr, "my_null");
337
338 jsonw_name(wr, "special chars");
339 jsonw_start_array(wr);
340 jsonw_string_field(wr, "slash", "/");
341 jsonw_string_field(wr, "newline", "\n");
342 jsonw_string_field(wr, "tab", "\t");
343 jsonw_string_field(wr, "ff", "\f");
344 jsonw_string_field(wr, "quote", "\"");
345 jsonw_string_field(wr, "tick", "\'");
346 jsonw_string_field(wr, "backslash", "\\");
347 jsonw_end_array(wr);
348
349 jsonw_end_object(wr);
350
351 jsonw_end_object(wr);
352 jsonw_destroy(&wr);
353 return 0;
354}
355
356#endif
diff --git a/tools/bpf/bpftool/json_writer.h b/tools/bpf/bpftool/json_writer.h
new file mode 100644
index 000000000000..0fa2fb1b6351
--- /dev/null
+++ b/tools/bpf/bpftool/json_writer.h
@@ -0,0 +1,72 @@
1/*
2 * Simple streaming JSON writer
3 *
4 * This takes care of the annoying bits of JSON syntax like the commas
5 * after elements
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 *
12 * Authors: Stephen Hemminger <stephen@networkplumber.org>
13 */
14
15#ifndef _JSON_WRITER_H_
16#define _JSON_WRITER_H_
17
18#include <stdbool.h>
19#include <stdint.h>
20#include <stdarg.h>
21
22/* Opaque class structure */
23typedef struct json_writer json_writer_t;
24
25/* Create a new JSON stream */
26json_writer_t *jsonw_new(FILE *f);
27/* End output to JSON stream */
28void jsonw_destroy(json_writer_t **self_p);
29
30/* Cause output to have pretty whitespace */
31void jsonw_pretty(json_writer_t *self, bool on);
32
33/* Add property name */
34void jsonw_name(json_writer_t *self, const char *name);
35
36/* Add value */
37void jsonw_vprintf_enquote(json_writer_t *self, const char *fmt, va_list ap);
38void jsonw_printf(json_writer_t *self, const char *fmt, ...);
39void jsonw_string(json_writer_t *self, const char *value);
40void jsonw_bool(json_writer_t *self, bool value);
41void jsonw_float(json_writer_t *self, double number);
42void jsonw_float_fmt(json_writer_t *self, const char *fmt, double num);
43void jsonw_uint(json_writer_t *self, uint64_t number);
44void jsonw_hu(json_writer_t *self, unsigned short number);
45void jsonw_int(json_writer_t *self, int64_t number);
46void jsonw_null(json_writer_t *self);
47void jsonw_lluint(json_writer_t *self, unsigned long long int num);
48
49/* Useful Combinations of name and value */
50void jsonw_string_field(json_writer_t *self, const char *prop, const char *val);
51void jsonw_bool_field(json_writer_t *self, const char *prop, bool value);
52void jsonw_float_field(json_writer_t *self, const char *prop, double num);
53void jsonw_uint_field(json_writer_t *self, const char *prop, uint64_t num);
54void jsonw_hu_field(json_writer_t *self, const char *prop, unsigned short num);
55void jsonw_int_field(json_writer_t *self, const char *prop, int64_t num);
56void jsonw_null_field(json_writer_t *self, const char *prop);
57void jsonw_lluint_field(json_writer_t *self, const char *prop,
58 unsigned long long int num);
59void jsonw_float_field_fmt(json_writer_t *self, const char *prop,
60 const char *fmt, double val);
61
62/* Collections */
63void jsonw_start_object(json_writer_t *self);
64void jsonw_end_object(json_writer_t *self);
65
66void jsonw_start_array(json_writer_t *self);
67void jsonw_end_array(json_writer_t *self);
68
69/* Override default exception handling */
70typedef void (jsonw_err_handler_fn)(const char *);
71
72#endif /* _JSON_WRITER_H_ */
diff --git a/tools/bpf/bpftool/main.c b/tools/bpf/bpftool/main.c
new file mode 100644
index 000000000000..d6e4762170a4
--- /dev/null
+++ b/tools/bpf/bpftool/main.c
@@ -0,0 +1,331 @@
1/*
2 * Copyright (C) 2017 Netronome Systems, Inc.
3 *
4 * This software is dual licensed under the GNU General License Version 2,
5 * June 1991 as shown in the file COPYING in the top-level directory of this
6 * source tree or the BSD 2-Clause License provided below. You have the
7 * option to license this software under the complete terms of either license.
8 *
9 * The BSD 2-Clause License:
10 *
11 * Redistribution and use in source and binary forms, with or
12 * without modification, are permitted provided that the following
13 * conditions are met:
14 *
15 * 1. Redistributions of source code must retain the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer.
18 *
19 * 2. Redistributions in binary form must reproduce the above
20 * copyright notice, this list of conditions and the following
21 * disclaimer in the documentation and/or other materials
22 * provided with the distribution.
23 *
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 * SOFTWARE.
32 */
33
34/* Author: Jakub Kicinski <kubakici@wp.pl> */
35
36#include <bfd.h>
37#include <ctype.h>
38#include <errno.h>
39#include <getopt.h>
40#include <linux/bpf.h>
41#include <linux/version.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <string.h>
45
46#include <bpf.h>
47
48#include "main.h"
49
50const char *bin_name;
51static int last_argc;
52static char **last_argv;
53static int (*last_do_help)(int argc, char **argv);
54json_writer_t *json_wtr;
55bool pretty_output;
56bool json_output;
57bool show_pinned;
58struct pinned_obj_table prog_table;
59struct pinned_obj_table map_table;
60
61void usage(void)
62{
63 last_do_help(last_argc - 1, last_argv + 1);
64
65 exit(-1);
66}
67
68static int do_help(int argc, char **argv)
69{
70 if (json_output) {
71 jsonw_null(json_wtr);
72 return 0;
73 }
74
75 fprintf(stderr,
76 "Usage: %s [OPTIONS] OBJECT { COMMAND | help }\n"
77 " %s batch file FILE\n"
78 " %s version\n"
79 "\n"
80 " OBJECT := { prog | map }\n"
81 " " HELP_SPEC_OPTIONS "\n"
82 "",
83 bin_name, bin_name, bin_name);
84
85 return 0;
86}
87
88static int do_version(int argc, char **argv)
89{
90 unsigned int version[3];
91
92 version[0] = LINUX_VERSION_CODE >> 16;
93 version[1] = LINUX_VERSION_CODE >> 8 & 0xf;
94 version[2] = LINUX_VERSION_CODE & 0xf;
95
96 if (json_output) {
97 jsonw_start_object(json_wtr);
98 jsonw_name(json_wtr, "version");
99 jsonw_printf(json_wtr, "\"%u.%u.%u\"",
100 version[0], version[1], version[2]);
101 jsonw_end_object(json_wtr);
102 } else {
103 printf("%s v%u.%u.%u\n", bin_name,
104 version[0], version[1], version[2]);
105 }
106 return 0;
107}
108
109int cmd_select(const struct cmd *cmds, int argc, char **argv,
110 int (*help)(int argc, char **argv))
111{
112 unsigned int i;
113
114 last_argc = argc;
115 last_argv = argv;
116 last_do_help = help;
117
118 if (argc < 1 && cmds[0].func)
119 return cmds[0].func(argc, argv);
120
121 for (i = 0; cmds[i].func; i++)
122 if (is_prefix(*argv, cmds[i].cmd))
123 return cmds[i].func(argc - 1, argv + 1);
124
125 help(argc - 1, argv + 1);
126
127 return -1;
128}
129
130bool is_prefix(const char *pfx, const char *str)
131{
132 if (!pfx)
133 return false;
134 if (strlen(str) < strlen(pfx))
135 return false;
136
137 return !memcmp(str, pfx, strlen(pfx));
138}
139
140void fprint_hex(FILE *f, void *arg, unsigned int n, const char *sep)
141{
142 unsigned char *data = arg;
143 unsigned int i;
144
145 for (i = 0; i < n; i++) {
146 const char *pfx = "";
147
148 if (!i)
149 /* nothing */;
150 else if (!(i % 16))
151 fprintf(f, "\n");
152 else if (!(i % 8))
153 fprintf(f, " ");
154 else
155 pfx = sep;
156
157 fprintf(f, "%s%02hhx", i ? pfx : "", data[i]);
158 }
159}
160
161static int do_batch(int argc, char **argv);
162
163static const struct cmd cmds[] = {
164 { "help", do_help },
165 { "batch", do_batch },
166 { "prog", do_prog },
167 { "map", do_map },
168 { "version", do_version },
169 { 0 }
170};
171
172static int do_batch(int argc, char **argv)
173{
174 unsigned int lines = 0;
175 char *n_argv[4096];
176 char buf[65536];
177 int n_argc;
178 FILE *fp;
179 int err;
180 int i;
181
182 if (argc < 2) {
183 p_err("too few parameters for batch");
184 return -1;
185 } else if (!is_prefix(*argv, "file")) {
186 p_err("expected 'file', got: %s", *argv);
187 return -1;
188 } else if (argc > 2) {
189 p_err("too many parameters for batch");
190 return -1;
191 }
192 NEXT_ARG();
193
194 fp = fopen(*argv, "r");
195 if (!fp) {
196 p_err("Can't open file (%s): %s", *argv, strerror(errno));
197 return -1;
198 }
199
200 if (json_output)
201 jsonw_start_array(json_wtr);
202 while (fgets(buf, sizeof(buf), fp)) {
203 if (strlen(buf) == sizeof(buf) - 1) {
204 errno = E2BIG;
205 break;
206 }
207
208 n_argc = 0;
209 n_argv[n_argc] = strtok(buf, " \t\n");
210
211 while (n_argv[n_argc]) {
212 n_argc++;
213 if (n_argc == ARRAY_SIZE(n_argv)) {
214 p_err("line %d has too many arguments, skip",
215 lines);
216 n_argc = 0;
217 break;
218 }
219 n_argv[n_argc] = strtok(NULL, " \t\n");
220 }
221
222 if (!n_argc)
223 continue;
224
225 if (json_output) {
226 jsonw_start_object(json_wtr);
227 jsonw_name(json_wtr, "command");
228 jsonw_start_array(json_wtr);
229 for (i = 0; i < n_argc; i++)
230 jsonw_string(json_wtr, n_argv[i]);
231 jsonw_end_array(json_wtr);
232 jsonw_name(json_wtr, "output");
233 }
234
235 err = cmd_select(cmds, n_argc, n_argv, do_help);
236
237 if (json_output)
238 jsonw_end_object(json_wtr);
239
240 if (err)
241 goto err_close;
242
243 lines++;
244 }
245
246 if (errno && errno != ENOENT) {
247 perror("reading batch file failed");
248 err = -1;
249 } else {
250 p_info("processed %d lines", lines);
251 err = 0;
252 }
253err_close:
254 fclose(fp);
255
256 if (json_output)
257 jsonw_end_array(json_wtr);
258
259 return err;
260}
261
262int main(int argc, char **argv)
263{
264 static const struct option options[] = {
265 { "json", no_argument, NULL, 'j' },
266 { "help", no_argument, NULL, 'h' },
267 { "pretty", no_argument, NULL, 'p' },
268 { "version", no_argument, NULL, 'V' },
269 { "bpffs", no_argument, NULL, 'f' },
270 { 0 }
271 };
272 int opt, ret;
273
274 last_do_help = do_help;
275 pretty_output = false;
276 json_output = false;
277 show_pinned = false;
278 bin_name = argv[0];
279
280 hash_init(prog_table.table);
281 hash_init(map_table.table);
282
283 while ((opt = getopt_long(argc, argv, "Vhpjf",
284 options, NULL)) >= 0) {
285 switch (opt) {
286 case 'V':
287 return do_version(argc, argv);
288 case 'h':
289 return do_help(argc, argv);
290 case 'p':
291 pretty_output = true;
292 /* fall through */
293 case 'j':
294 json_output = true;
295 break;
296 case 'f':
297 show_pinned = true;
298 break;
299 default:
300 usage();
301 }
302 }
303
304 argc -= optind;
305 argv += optind;
306 if (argc < 0)
307 usage();
308
309 if (json_output) {
310 json_wtr = jsonw_new(stdout);
311 if (!json_wtr) {
312 p_err("failed to create JSON writer");
313 return -1;
314 }
315 jsonw_pretty(json_wtr, pretty_output);
316 }
317
318 bfd_init();
319
320 ret = cmd_select(cmds, argc, argv, do_help);
321
322 if (json_output)
323 jsonw_destroy(&json_wtr);
324
325 if (show_pinned) {
326 delete_pinned_obj_table(&prog_table);
327 delete_pinned_obj_table(&map_table);
328 }
329
330 return ret;
331}
diff --git a/tools/bpf/bpftool/main.h b/tools/bpf/bpftool/main.h
new file mode 100644
index 000000000000..9c191e222d6f
--- /dev/null
+++ b/tools/bpf/bpftool/main.h
@@ -0,0 +1,122 @@
1/*
2 * Copyright (C) 2017 Netronome Systems, Inc.
3 *
4 * This software is dual licensed under the GNU General License Version 2,
5 * June 1991 as shown in the file COPYING in the top-level directory of this
6 * source tree or the BSD 2-Clause License provided below. You have the
7 * option to license this software under the complete terms of either license.
8 *
9 * The BSD 2-Clause License:
10 *
11 * Redistribution and use in source and binary forms, with or
12 * without modification, are permitted provided that the following
13 * conditions are met:
14 *
15 * 1. Redistributions of source code must retain the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer.
18 *
19 * 2. Redistributions in binary form must reproduce the above
20 * copyright notice, this list of conditions and the following
21 * disclaimer in the documentation and/or other materials
22 * provided with the distribution.
23 *
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 * SOFTWARE.
32 */
33
34/* Author: Jakub Kicinski <kubakici@wp.pl> */
35
36#ifndef __BPF_TOOL_H
37#define __BPF_TOOL_H
38
39/* BFD and kernel.h both define GCC_VERSION, differently */
40#undef GCC_VERSION
41#include <stdbool.h>
42#include <stdio.h>
43#include <linux/bpf.h>
44#include <linux/kernel.h>
45#include <linux/hashtable.h>
46
47#include "json_writer.h"
48
49#define ptr_to_u64(ptr) ((__u64)(unsigned long)(ptr))
50
51#define NEXT_ARG() ({ argc--; argv++; if (argc < 0) usage(); })
52#define NEXT_ARGP() ({ (*argc)--; (*argv)++; if (*argc < 0) usage(); })
53#define BAD_ARG() ({ p_err("what is '%s'?\n", *argv); -1; })
54
55#define ERR_MAX_LEN 1024
56
57#define BPF_TAG_FMT "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx"
58
59#define HELP_SPEC_PROGRAM \
60 "PROG := { id PROG_ID | pinned FILE | tag PROG_TAG }"
61#define HELP_SPEC_OPTIONS \
62 "OPTIONS := { {-j|--json} [{-p|--pretty}] | {-f|--bpffs} }"
63
64enum bpf_obj_type {
65 BPF_OBJ_UNKNOWN,
66 BPF_OBJ_PROG,
67 BPF_OBJ_MAP,
68};
69
70extern const char *bin_name;
71
72extern json_writer_t *json_wtr;
73extern bool json_output;
74extern bool show_pinned;
75extern struct pinned_obj_table prog_table;
76extern struct pinned_obj_table map_table;
77
78void p_err(const char *fmt, ...);
79void p_info(const char *fmt, ...);
80
81bool is_prefix(const char *pfx, const char *str);
82void fprint_hex(FILE *f, void *arg, unsigned int n, const char *sep);
83void usage(void) __attribute__((noreturn));
84
85struct pinned_obj_table {
86 DECLARE_HASHTABLE(table, 16);
87};
88
89struct pinned_obj {
90 __u32 id;
91 char *path;
92 struct hlist_node hash;
93};
94
95int build_pinned_obj_table(struct pinned_obj_table *table,
96 enum bpf_obj_type type);
97void delete_pinned_obj_table(struct pinned_obj_table *tab);
98
99struct cmd {
100 const char *cmd;
101 int (*func)(int argc, char **argv);
102};
103
104int cmd_select(const struct cmd *cmds, int argc, char **argv,
105 int (*help)(int argc, char **argv));
106
107int get_fd_type(int fd);
108const char *get_fd_type_name(enum bpf_obj_type type);
109char *get_fdinfo(int fd, const char *key);
110int open_obj_pinned(char *path);
111int open_obj_pinned_any(char *path, enum bpf_obj_type exp_type);
112int do_pin_any(int argc, char **argv, int (*get_fd_by_id)(__u32));
113
114int do_prog(int argc, char **arg);
115int do_map(int argc, char **arg);
116
117int prog_parse_fd(int *argc, char ***argv);
118
119void disasm_print_insn(unsigned char *image, ssize_t len, int opcodes);
120void print_hex_data_json(uint8_t *data, size_t len);
121
122#endif
diff --git a/tools/bpf/bpftool/map.c b/tools/bpf/bpftool/map.c
new file mode 100644
index 000000000000..e2450c8e88e6
--- /dev/null
+++ b/tools/bpf/bpftool/map.c
@@ -0,0 +1,899 @@
1/*
2 * Copyright (C) 2017 Netronome Systems, Inc.
3 *
4 * This software is dual licensed under the GNU General License Version 2,
5 * June 1991 as shown in the file COPYING in the top-level directory of this
6 * source tree or the BSD 2-Clause License provided below. You have the
7 * option to license this software under the complete terms of either license.
8 *
9 * The BSD 2-Clause License:
10 *
11 * Redistribution and use in source and binary forms, with or
12 * without modification, are permitted provided that the following
13 * conditions are met:
14 *
15 * 1. Redistributions of source code must retain the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer.
18 *
19 * 2. Redistributions in binary form must reproduce the above
20 * copyright notice, this list of conditions and the following
21 * disclaimer in the documentation and/or other materials
22 * provided with the distribution.
23 *
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 * SOFTWARE.
32 */
33
34/* Author: Jakub Kicinski <kubakici@wp.pl> */
35
36#include <assert.h>
37#include <ctype.h>
38#include <errno.h>
39#include <fcntl.h>
40#include <stdbool.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44#include <unistd.h>
45#include <sys/types.h>
46#include <sys/stat.h>
47
48#include <bpf.h>
49
50#include "main.h"
51
52static const char * const map_type_name[] = {
53 [BPF_MAP_TYPE_UNSPEC] = "unspec",
54 [BPF_MAP_TYPE_HASH] = "hash",
55 [BPF_MAP_TYPE_ARRAY] = "array",
56 [BPF_MAP_TYPE_PROG_ARRAY] = "prog_array",
57 [BPF_MAP_TYPE_PERF_EVENT_ARRAY] = "perf_event_array",
58 [BPF_MAP_TYPE_PERCPU_HASH] = "percpu_hash",
59 [BPF_MAP_TYPE_PERCPU_ARRAY] = "percpu_array",
60 [BPF_MAP_TYPE_STACK_TRACE] = "stack_trace",
61 [BPF_MAP_TYPE_CGROUP_ARRAY] = "cgroup_array",
62 [BPF_MAP_TYPE_LRU_HASH] = "lru_hash",
63 [BPF_MAP_TYPE_LRU_PERCPU_HASH] = "lru_percpu_hash",
64 [BPF_MAP_TYPE_LPM_TRIE] = "lpm_trie",
65 [BPF_MAP_TYPE_ARRAY_OF_MAPS] = "array_of_maps",
66 [BPF_MAP_TYPE_HASH_OF_MAPS] = "hash_of_maps",
67 [BPF_MAP_TYPE_DEVMAP] = "devmap",
68 [BPF_MAP_TYPE_SOCKMAP] = "sockmap",
69};
70
71static unsigned int get_possible_cpus(void)
72{
73 static unsigned int result;
74 char buf[128];
75 long int n;
76 char *ptr;
77 int fd;
78
79 if (result)
80 return result;
81
82 fd = open("/sys/devices/system/cpu/possible", O_RDONLY);
83 if (fd < 0) {
84 p_err("can't open sysfs possible cpus");
85 exit(-1);
86 }
87
88 n = read(fd, buf, sizeof(buf));
89 if (n < 2) {
90 p_err("can't read sysfs possible cpus");
91 exit(-1);
92 }
93 close(fd);
94
95 if (n == sizeof(buf)) {
96 p_err("read sysfs possible cpus overflow");
97 exit(-1);
98 }
99
100 ptr = buf;
101 n = 0;
102 while (*ptr && *ptr != '\n') {
103 unsigned int a, b;
104
105 if (sscanf(ptr, "%u-%u", &a, &b) == 2) {
106 n += b - a + 1;
107
108 ptr = strchr(ptr, '-') + 1;
109 } else if (sscanf(ptr, "%u", &a) == 1) {
110 n++;
111 } else {
112 assert(0);
113 }
114
115 while (isdigit(*ptr))
116 ptr++;
117 if (*ptr == ',')
118 ptr++;
119 }
120
121 result = n;
122
123 return result;
124}
125
126static bool map_is_per_cpu(__u32 type)
127{
128 return type == BPF_MAP_TYPE_PERCPU_HASH ||
129 type == BPF_MAP_TYPE_PERCPU_ARRAY ||
130 type == BPF_MAP_TYPE_LRU_PERCPU_HASH;
131}
132
133static bool map_is_map_of_maps(__u32 type)
134{
135 return type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
136 type == BPF_MAP_TYPE_HASH_OF_MAPS;
137}
138
139static bool map_is_map_of_progs(__u32 type)
140{
141 return type == BPF_MAP_TYPE_PROG_ARRAY;
142}
143
144static void *alloc_value(struct bpf_map_info *info)
145{
146 if (map_is_per_cpu(info->type))
147 return malloc(info->value_size * get_possible_cpus());
148 else
149 return malloc(info->value_size);
150}
151
152static int map_parse_fd(int *argc, char ***argv)
153{
154 int fd;
155
156 if (is_prefix(**argv, "id")) {
157 unsigned int id;
158 char *endptr;
159
160 NEXT_ARGP();
161
162 id = strtoul(**argv, &endptr, 0);
163 if (*endptr) {
164 p_err("can't parse %s as ID", **argv);
165 return -1;
166 }
167 NEXT_ARGP();
168
169 fd = bpf_map_get_fd_by_id(id);
170 if (fd < 0)
171 p_err("get map by id (%u): %s", id, strerror(errno));
172 return fd;
173 } else if (is_prefix(**argv, "pinned")) {
174 char *path;
175
176 NEXT_ARGP();
177
178 path = **argv;
179 NEXT_ARGP();
180
181 return open_obj_pinned_any(path, BPF_OBJ_MAP);
182 }
183
184 p_err("expected 'id' or 'pinned', got: '%s'?", **argv);
185 return -1;
186}
187
188static int
189map_parse_fd_and_info(int *argc, char ***argv, void *info, __u32 *info_len)
190{
191 int err;
192 int fd;
193
194 fd = map_parse_fd(argc, argv);
195 if (fd < 0)
196 return -1;
197
198 err = bpf_obj_get_info_by_fd(fd, info, info_len);
199 if (err) {
200 p_err("can't get map info: %s", strerror(errno));
201 close(fd);
202 return err;
203 }
204
205 return fd;
206}
207
208static void print_entry_json(struct bpf_map_info *info, unsigned char *key,
209 unsigned char *value)
210{
211 jsonw_start_object(json_wtr);
212
213 if (!map_is_per_cpu(info->type)) {
214 jsonw_name(json_wtr, "key");
215 print_hex_data_json(key, info->key_size);
216 jsonw_name(json_wtr, "value");
217 print_hex_data_json(value, info->value_size);
218 } else {
219 unsigned int i, n;
220
221 n = get_possible_cpus();
222
223 jsonw_name(json_wtr, "key");
224 print_hex_data_json(key, info->key_size);
225
226 jsonw_name(json_wtr, "values");
227 jsonw_start_array(json_wtr);
228 for (i = 0; i < n; i++) {
229 jsonw_start_object(json_wtr);
230
231 jsonw_int_field(json_wtr, "cpu", i);
232
233 jsonw_name(json_wtr, "value");
234 print_hex_data_json(value + i * info->value_size,
235 info->value_size);
236
237 jsonw_end_object(json_wtr);
238 }
239 jsonw_end_array(json_wtr);
240 }
241
242 jsonw_end_object(json_wtr);
243}
244
245static void print_entry_plain(struct bpf_map_info *info, unsigned char *key,
246 unsigned char *value)
247{
248 if (!map_is_per_cpu(info->type)) {
249 bool single_line, break_names;
250
251 break_names = info->key_size > 16 || info->value_size > 16;
252 single_line = info->key_size + info->value_size <= 24 &&
253 !break_names;
254
255 printf("key:%c", break_names ? '\n' : ' ');
256 fprint_hex(stdout, key, info->key_size, " ");
257
258 printf(single_line ? " " : "\n");
259
260 printf("value:%c", break_names ? '\n' : ' ');
261 fprint_hex(stdout, value, info->value_size, " ");
262
263 printf("\n");
264 } else {
265 unsigned int i, n;
266
267 n = get_possible_cpus();
268
269 printf("key:\n");
270 fprint_hex(stdout, key, info->key_size, " ");
271 printf("\n");
272 for (i = 0; i < n; i++) {
273 printf("value (CPU %02d):%c",
274 i, info->value_size > 16 ? '\n' : ' ');
275 fprint_hex(stdout, value + i * info->value_size,
276 info->value_size, " ");
277 printf("\n");
278 }
279 }
280}
281
282static char **parse_bytes(char **argv, const char *name, unsigned char *val,
283 unsigned int n)
284{
285 unsigned int i = 0;
286 char *endptr;
287
288 while (i < n && argv[i]) {
289 val[i] = strtoul(argv[i], &endptr, 0);
290 if (*endptr) {
291 p_err("error parsing byte: %s", argv[i]);
292 return NULL;
293 }
294 i++;
295 }
296
297 if (i != n) {
298 p_err("%s expected %d bytes got %d", name, n, i);
299 return NULL;
300 }
301
302 return argv + i;
303}
304
305static int parse_elem(char **argv, struct bpf_map_info *info,
306 void *key, void *value, __u32 key_size, __u32 value_size,
307 __u32 *flags, __u32 **value_fd)
308{
309 if (!*argv) {
310 if (!key && !value)
311 return 0;
312 p_err("did not find %s", key ? "key" : "value");
313 return -1;
314 }
315
316 if (is_prefix(*argv, "key")) {
317 if (!key) {
318 if (key_size)
319 p_err("duplicate key");
320 else
321 p_err("unnecessary key");
322 return -1;
323 }
324
325 argv = parse_bytes(argv + 1, "key", key, key_size);
326 if (!argv)
327 return -1;
328
329 return parse_elem(argv, info, NULL, value, key_size, value_size,
330 flags, value_fd);
331 } else if (is_prefix(*argv, "value")) {
332 int fd;
333
334 if (!value) {
335 if (value_size)
336 p_err("duplicate value");
337 else
338 p_err("unnecessary value");
339 return -1;
340 }
341
342 argv++;
343
344 if (map_is_map_of_maps(info->type)) {
345 int argc = 2;
346
347 if (value_size != 4) {
348 p_err("value smaller than 4B for map in map?");
349 return -1;
350 }
351 if (!argv[0] || !argv[1]) {
352 p_err("not enough value arguments for map in map");
353 return -1;
354 }
355
356 fd = map_parse_fd(&argc, &argv);
357 if (fd < 0)
358 return -1;
359
360 *value_fd = value;
361 **value_fd = fd;
362 } else if (map_is_map_of_progs(info->type)) {
363 int argc = 2;
364
365 if (value_size != 4) {
366 p_err("value smaller than 4B for map of progs?");
367 return -1;
368 }
369 if (!argv[0] || !argv[1]) {
370 p_err("not enough value arguments for map of progs");
371 return -1;
372 }
373
374 fd = prog_parse_fd(&argc, &argv);
375 if (fd < 0)
376 return -1;
377
378 *value_fd = value;
379 **value_fd = fd;
380 } else {
381 argv = parse_bytes(argv, "value", value, value_size);
382 if (!argv)
383 return -1;
384 }
385
386 return parse_elem(argv, info, key, NULL, key_size, value_size,
387 flags, NULL);
388 } else if (is_prefix(*argv, "any") || is_prefix(*argv, "noexist") ||
389 is_prefix(*argv, "exist")) {
390 if (!flags) {
391 p_err("flags specified multiple times: %s", *argv);
392 return -1;
393 }
394
395 if (is_prefix(*argv, "any"))
396 *flags = BPF_ANY;
397 else if (is_prefix(*argv, "noexist"))
398 *flags = BPF_NOEXIST;
399 else if (is_prefix(*argv, "exist"))
400 *flags = BPF_EXIST;
401
402 return parse_elem(argv + 1, info, key, value, key_size,
403 value_size, NULL, value_fd);
404 }
405
406 p_err("expected key or value, got: %s", *argv);
407 return -1;
408}
409
410static int show_map_close_json(int fd, struct bpf_map_info *info)
411{
412 char *memlock;
413
414 memlock = get_fdinfo(fd, "memlock");
415 close(fd);
416
417 jsonw_start_object(json_wtr);
418
419 jsonw_uint_field(json_wtr, "id", info->id);
420 if (info->type < ARRAY_SIZE(map_type_name))
421 jsonw_string_field(json_wtr, "type",
422 map_type_name[info->type]);
423 else
424 jsonw_uint_field(json_wtr, "type", info->type);
425
426 if (*info->name)
427 jsonw_string_field(json_wtr, "name", info->name);
428
429 jsonw_name(json_wtr, "flags");
430 jsonw_printf(json_wtr, "%#x", info->map_flags);
431 jsonw_uint_field(json_wtr, "bytes_key", info->key_size);
432 jsonw_uint_field(json_wtr, "bytes_value", info->value_size);
433 jsonw_uint_field(json_wtr, "max_entries", info->max_entries);
434
435 if (memlock)
436 jsonw_int_field(json_wtr, "bytes_memlock", atoi(memlock));
437 free(memlock);
438
439 if (!hash_empty(map_table.table)) {
440 struct pinned_obj *obj;
441
442 jsonw_name(json_wtr, "pinned");
443 jsonw_start_array(json_wtr);
444 hash_for_each_possible(map_table.table, obj, hash, info->id) {
445 if (obj->id == info->id)
446 jsonw_string(json_wtr, obj->path);
447 }
448 jsonw_end_array(json_wtr);
449 }
450
451 jsonw_end_object(json_wtr);
452
453 return 0;
454}
455
456static int show_map_close_plain(int fd, struct bpf_map_info *info)
457{
458 char *memlock;
459
460 memlock = get_fdinfo(fd, "memlock");
461 close(fd);
462
463 printf("%u: ", info->id);
464 if (info->type < ARRAY_SIZE(map_type_name))
465 printf("%s ", map_type_name[info->type]);
466 else
467 printf("type %u ", info->type);
468
469 if (*info->name)
470 printf("name %s ", info->name);
471
472 printf("flags 0x%x\n", info->map_flags);
473 printf("\tkey %uB value %uB max_entries %u",
474 info->key_size, info->value_size, info->max_entries);
475
476 if (memlock)
477 printf(" memlock %sB", memlock);
478 free(memlock);
479
480 printf("\n");
481 if (!hash_empty(map_table.table)) {
482 struct pinned_obj *obj;
483
484 hash_for_each_possible(map_table.table, obj, hash, info->id) {
485 if (obj->id == info->id)
486 printf("\tpinned %s\n", obj->path);
487 }
488 }
489 return 0;
490}
491
492static int do_show(int argc, char **argv)
493{
494 struct bpf_map_info info = {};
495 __u32 len = sizeof(info);
496 __u32 id = 0;
497 int err;
498 int fd;
499
500 if (show_pinned)
501 build_pinned_obj_table(&map_table, BPF_OBJ_MAP);
502
503 if (argc == 2) {
504 fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
505 if (fd < 0)
506 return -1;
507
508 if (json_output)
509 return show_map_close_json(fd, &info);
510 else
511 return show_map_close_plain(fd, &info);
512 }
513
514 if (argc)
515 return BAD_ARG();
516
517 if (json_output)
518 jsonw_start_array(json_wtr);
519 while (true) {
520 err = bpf_map_get_next_id(id, &id);
521 if (err) {
522 if (errno == ENOENT)
523 break;
524 p_err("can't get next map: %s%s", strerror(errno),
525 errno == EINVAL ? " -- kernel too old?" : "");
526 return -1;
527 }
528
529 fd = bpf_map_get_fd_by_id(id);
530 if (fd < 0) {
531 p_err("can't get map by id (%u): %s",
532 id, strerror(errno));
533 return -1;
534 }
535
536 err = bpf_obj_get_info_by_fd(fd, &info, &len);
537 if (err) {
538 p_err("can't get map info: %s", strerror(errno));
539 close(fd);
540 return -1;
541 }
542
543 if (json_output)
544 show_map_close_json(fd, &info);
545 else
546 show_map_close_plain(fd, &info);
547 }
548 if (json_output)
549 jsonw_end_array(json_wtr);
550
551 return errno == ENOENT ? 0 : -1;
552}
553
554static int do_dump(int argc, char **argv)
555{
556 void *key, *value, *prev_key;
557 unsigned int num_elems = 0;
558 struct bpf_map_info info = {};
559 __u32 len = sizeof(info);
560 int err;
561 int fd;
562
563 if (argc != 2)
564 usage();
565
566 fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
567 if (fd < 0)
568 return -1;
569
570 if (map_is_map_of_maps(info.type) || map_is_map_of_progs(info.type)) {
571 p_err("Dumping maps of maps and program maps not supported");
572 close(fd);
573 return -1;
574 }
575
576 key = malloc(info.key_size);
577 value = alloc_value(&info);
578 if (!key || !value) {
579 p_err("mem alloc failed");
580 err = -1;
581 goto exit_free;
582 }
583
584 prev_key = NULL;
585 if (json_output)
586 jsonw_start_array(json_wtr);
587 while (true) {
588 err = bpf_map_get_next_key(fd, prev_key, key);
589 if (err) {
590 if (errno == ENOENT)
591 err = 0;
592 break;
593 }
594
595 if (!bpf_map_lookup_elem(fd, key, value)) {
596 if (json_output)
597 print_entry_json(&info, key, value);
598 else
599 print_entry_plain(&info, key, value);
600 } else {
601 if (json_output) {
602 jsonw_name(json_wtr, "key");
603 print_hex_data_json(key, info.key_size);
604 jsonw_name(json_wtr, "value");
605 jsonw_start_object(json_wtr);
606 jsonw_string_field(json_wtr, "error",
607 "can't lookup element");
608 jsonw_end_object(json_wtr);
609 } else {
610 p_info("can't lookup element with key: ");
611 fprint_hex(stderr, key, info.key_size, " ");
612 fprintf(stderr, "\n");
613 }
614 }
615
616 prev_key = key;
617 num_elems++;
618 }
619
620 if (json_output)
621 jsonw_end_array(json_wtr);
622 else
623 printf("Found %u element%s\n", num_elems,
624 num_elems != 1 ? "s" : "");
625
626exit_free:
627 free(key);
628 free(value);
629 close(fd);
630
631 return err;
632}
633
634static int do_update(int argc, char **argv)
635{
636 struct bpf_map_info info = {};
637 __u32 len = sizeof(info);
638 __u32 *value_fd = NULL;
639 __u32 flags = BPF_ANY;
640 void *key, *value;
641 int fd, err;
642
643 if (argc < 2)
644 usage();
645
646 fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
647 if (fd < 0)
648 return -1;
649
650 key = malloc(info.key_size);
651 value = alloc_value(&info);
652 if (!key || !value) {
653 p_err("mem alloc failed");
654 err = -1;
655 goto exit_free;
656 }
657
658 err = parse_elem(argv, &info, key, value, info.key_size,
659 info.value_size, &flags, &value_fd);
660 if (err)
661 goto exit_free;
662
663 err = bpf_map_update_elem(fd, key, value, flags);
664 if (err) {
665 p_err("update failed: %s", strerror(errno));
666 goto exit_free;
667 }
668
669exit_free:
670 if (value_fd)
671 close(*value_fd);
672 free(key);
673 free(value);
674 close(fd);
675
676 if (!err && json_output)
677 jsonw_null(json_wtr);
678 return err;
679}
680
681static int do_lookup(int argc, char **argv)
682{
683 struct bpf_map_info info = {};
684 __u32 len = sizeof(info);
685 void *key, *value;
686 int err;
687 int fd;
688
689 if (argc < 2)
690 usage();
691
692 fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
693 if (fd < 0)
694 return -1;
695
696 key = malloc(info.key_size);
697 value = alloc_value(&info);
698 if (!key || !value) {
699 p_err("mem alloc failed");
700 err = -1;
701 goto exit_free;
702 }
703
704 err = parse_elem(argv, &info, key, NULL, info.key_size, 0, NULL, NULL);
705 if (err)
706 goto exit_free;
707
708 err = bpf_map_lookup_elem(fd, key, value);
709 if (!err) {
710 if (json_output)
711 print_entry_json(&info, key, value);
712 else
713 print_entry_plain(&info, key, value);
714 } else if (errno == ENOENT) {
715 if (json_output) {
716 jsonw_null(json_wtr);
717 } else {
718 printf("key:\n");
719 fprint_hex(stdout, key, info.key_size, " ");
720 printf("\n\nNot found\n");
721 }
722 } else {
723 p_err("lookup failed: %s", strerror(errno));
724 }
725
726exit_free:
727 free(key);
728 free(value);
729 close(fd);
730
731 return err;
732}
733
734static int do_getnext(int argc, char **argv)
735{
736 struct bpf_map_info info = {};
737 __u32 len = sizeof(info);
738 void *key, *nextkey;
739 int err;
740 int fd;
741
742 if (argc < 2)
743 usage();
744
745 fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
746 if (fd < 0)
747 return -1;
748
749 key = malloc(info.key_size);
750 nextkey = malloc(info.key_size);
751 if (!key || !nextkey) {
752 p_err("mem alloc failed");
753 err = -1;
754 goto exit_free;
755 }
756
757 if (argc) {
758 err = parse_elem(argv, &info, key, NULL, info.key_size, 0,
759 NULL, NULL);
760 if (err)
761 goto exit_free;
762 } else {
763 free(key);
764 key = NULL;
765 }
766
767 err = bpf_map_get_next_key(fd, key, nextkey);
768 if (err) {
769 p_err("can't get next key: %s", strerror(errno));
770 goto exit_free;
771 }
772
773 if (json_output) {
774 jsonw_start_object(json_wtr);
775 if (key) {
776 jsonw_name(json_wtr, "key");
777 print_hex_data_json(key, info.key_size);
778 } else {
779 jsonw_null_field(json_wtr, "key");
780 }
781 jsonw_name(json_wtr, "next_key");
782 print_hex_data_json(nextkey, info.key_size);
783 jsonw_end_object(json_wtr);
784 } else {
785 if (key) {
786 printf("key:\n");
787 fprint_hex(stdout, key, info.key_size, " ");
788 printf("\n");
789 } else {
790 printf("key: None\n");
791 }
792 printf("next key:\n");
793 fprint_hex(stdout, nextkey, info.key_size, " ");
794 printf("\n");
795 }
796
797exit_free:
798 free(nextkey);
799 free(key);
800 close(fd);
801
802 return err;
803}
804
805static int do_delete(int argc, char **argv)
806{
807 struct bpf_map_info info = {};
808 __u32 len = sizeof(info);
809 void *key;
810 int err;
811 int fd;
812
813 if (argc < 2)
814 usage();
815
816 fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
817 if (fd < 0)
818 return -1;
819
820 key = malloc(info.key_size);
821 if (!key) {
822 p_err("mem alloc failed");
823 err = -1;
824 goto exit_free;
825 }
826
827 err = parse_elem(argv, &info, key, NULL, info.key_size, 0, NULL, NULL);
828 if (err)
829 goto exit_free;
830
831 err = bpf_map_delete_elem(fd, key);
832 if (err)
833 p_err("delete failed: %s", strerror(errno));
834
835exit_free:
836 free(key);
837 close(fd);
838
839 if (!err && json_output)
840 jsonw_null(json_wtr);
841 return err;
842}
843
844static int do_pin(int argc, char **argv)
845{
846 int err;
847
848 err = do_pin_any(argc, argv, bpf_map_get_fd_by_id);
849 if (!err && json_output)
850 jsonw_null(json_wtr);
851 return err;
852}
853
854static int do_help(int argc, char **argv)
855{
856 if (json_output) {
857 jsonw_null(json_wtr);
858 return 0;
859 }
860
861 fprintf(stderr,
862 "Usage: %s %s show [MAP]\n"
863 " %s %s dump MAP\n"
864 " %s %s update MAP key BYTES value VALUE [UPDATE_FLAGS]\n"
865 " %s %s lookup MAP key BYTES\n"
866 " %s %s getnext MAP [key BYTES]\n"
867 " %s %s delete MAP key BYTES\n"
868 " %s %s pin MAP FILE\n"
869 " %s %s help\n"
870 "\n"
871 " MAP := { id MAP_ID | pinned FILE }\n"
872 " " HELP_SPEC_PROGRAM "\n"
873 " VALUE := { BYTES | MAP | PROG }\n"
874 " UPDATE_FLAGS := { any | exist | noexist }\n"
875 " " HELP_SPEC_OPTIONS "\n"
876 "",
877 bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
878 bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
879 bin_name, argv[-2], bin_name, argv[-2]);
880
881 return 0;
882}
883
884static const struct cmd cmds[] = {
885 { "show", do_show },
886 { "help", do_help },
887 { "dump", do_dump },
888 { "update", do_update },
889 { "lookup", do_lookup },
890 { "getnext", do_getnext },
891 { "delete", do_delete },
892 { "pin", do_pin },
893 { 0 }
894};
895
896int do_map(int argc, char **argv)
897{
898 return cmd_select(cmds, argc, argv, do_help);
899}
diff --git a/tools/bpf/bpftool/prog.c b/tools/bpf/bpftool/prog.c
new file mode 100644
index 000000000000..f45c44ef9bec
--- /dev/null
+++ b/tools/bpf/bpftool/prog.c
@@ -0,0 +1,703 @@
1/*
2 * Copyright (C) 2017 Netronome Systems, Inc.
3 *
4 * This software is dual licensed under the GNU General License Version 2,
5 * June 1991 as shown in the file COPYING in the top-level directory of this
6 * source tree or the BSD 2-Clause License provided below. You have the
7 * option to license this software under the complete terms of either license.
8 *
9 * The BSD 2-Clause License:
10 *
11 * Redistribution and use in source and binary forms, with or
12 * without modification, are permitted provided that the following
13 * conditions are met:
14 *
15 * 1. Redistributions of source code must retain the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer.
18 *
19 * 2. Redistributions in binary form must reproduce the above
20 * copyright notice, this list of conditions and the following
21 * disclaimer in the documentation and/or other materials
22 * provided with the distribution.
23 *
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 * SOFTWARE.
32 */
33
34/* Author: Jakub Kicinski <kubakici@wp.pl> */
35
36#include <errno.h>
37#include <fcntl.h>
38#include <stdarg.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#include <time.h>
43#include <unistd.h>
44#include <net/if.h>
45#include <sys/types.h>
46#include <sys/stat.h>
47
48#include <bpf.h>
49
50#include "main.h"
51#include "disasm.h"
52
53static const char * const prog_type_name[] = {
54 [BPF_PROG_TYPE_UNSPEC] = "unspec",
55 [BPF_PROG_TYPE_SOCKET_FILTER] = "socket_filter",
56 [BPF_PROG_TYPE_KPROBE] = "kprobe",
57 [BPF_PROG_TYPE_SCHED_CLS] = "sched_cls",
58 [BPF_PROG_TYPE_SCHED_ACT] = "sched_act",
59 [BPF_PROG_TYPE_TRACEPOINT] = "tracepoint",
60 [BPF_PROG_TYPE_XDP] = "xdp",
61 [BPF_PROG_TYPE_PERF_EVENT] = "perf_event",
62 [BPF_PROG_TYPE_CGROUP_SKB] = "cgroup_skb",
63 [BPF_PROG_TYPE_CGROUP_SOCK] = "cgroup_sock",
64 [BPF_PROG_TYPE_LWT_IN] = "lwt_in",
65 [BPF_PROG_TYPE_LWT_OUT] = "lwt_out",
66 [BPF_PROG_TYPE_LWT_XMIT] = "lwt_xmit",
67 [BPF_PROG_TYPE_SOCK_OPS] = "sock_ops",
68 [BPF_PROG_TYPE_SK_SKB] = "sk_skb",
69};
70
71static void print_boot_time(__u64 nsecs, char *buf, unsigned int size)
72{
73 struct timespec real_time_ts, boot_time_ts;
74 time_t wallclock_secs;
75 struct tm load_tm;
76
77 buf[--size] = '\0';
78
79 if (clock_gettime(CLOCK_REALTIME, &real_time_ts) ||
80 clock_gettime(CLOCK_BOOTTIME, &boot_time_ts)) {
81 perror("Can't read clocks");
82 snprintf(buf, size, "%llu", nsecs / 1000000000);
83 return;
84 }
85
86 wallclock_secs = (real_time_ts.tv_sec - boot_time_ts.tv_sec) +
87 nsecs / 1000000000;
88
89 if (!localtime_r(&wallclock_secs, &load_tm)) {
90 snprintf(buf, size, "%llu", nsecs / 1000000000);
91 return;
92 }
93
94 strftime(buf, size, "%b %d/%H:%M", &load_tm);
95}
96
97static int prog_fd_by_tag(unsigned char *tag)
98{
99 struct bpf_prog_info info = {};
100 __u32 len = sizeof(info);
101 unsigned int id = 0;
102 int err;
103 int fd;
104
105 while (true) {
106 err = bpf_prog_get_next_id(id, &id);
107 if (err) {
108 p_err("%s", strerror(errno));
109 return -1;
110 }
111
112 fd = bpf_prog_get_fd_by_id(id);
113 if (fd < 0) {
114 p_err("can't get prog by id (%u): %s",
115 id, strerror(errno));
116 return -1;
117 }
118
119 err = bpf_obj_get_info_by_fd(fd, &info, &len);
120 if (err) {
121 p_err("can't get prog info (%u): %s",
122 id, strerror(errno));
123 close(fd);
124 return -1;
125 }
126
127 if (!memcmp(tag, info.tag, BPF_TAG_SIZE))
128 return fd;
129
130 close(fd);
131 }
132}
133
134int prog_parse_fd(int *argc, char ***argv)
135{
136 int fd;
137
138 if (is_prefix(**argv, "id")) {
139 unsigned int id;
140 char *endptr;
141
142 NEXT_ARGP();
143
144 id = strtoul(**argv, &endptr, 0);
145 if (*endptr) {
146 p_err("can't parse %s as ID", **argv);
147 return -1;
148 }
149 NEXT_ARGP();
150
151 fd = bpf_prog_get_fd_by_id(id);
152 if (fd < 0)
153 p_err("get by id (%u): %s", id, strerror(errno));
154 return fd;
155 } else if (is_prefix(**argv, "tag")) {
156 unsigned char tag[BPF_TAG_SIZE];
157
158 NEXT_ARGP();
159
160 if (sscanf(**argv, BPF_TAG_FMT, tag, tag + 1, tag + 2,
161 tag + 3, tag + 4, tag + 5, tag + 6, tag + 7)
162 != BPF_TAG_SIZE) {
163 p_err("can't parse tag");
164 return -1;
165 }
166 NEXT_ARGP();
167
168 return prog_fd_by_tag(tag);
169 } else if (is_prefix(**argv, "pinned")) {
170 char *path;
171
172 NEXT_ARGP();
173
174 path = **argv;
175 NEXT_ARGP();
176
177 return open_obj_pinned_any(path, BPF_OBJ_PROG);
178 }
179
180 p_err("expected 'id', 'tag' or 'pinned', got: '%s'?", **argv);
181 return -1;
182}
183
184static void show_prog_maps(int fd, u32 num_maps)
185{
186 struct bpf_prog_info info = {};
187 __u32 len = sizeof(info);
188 __u32 map_ids[num_maps];
189 unsigned int i;
190 int err;
191
192 info.nr_map_ids = num_maps;
193 info.map_ids = ptr_to_u64(map_ids);
194
195 err = bpf_obj_get_info_by_fd(fd, &info, &len);
196 if (err || !info.nr_map_ids)
197 return;
198
199 if (json_output) {
200 jsonw_name(json_wtr, "map_ids");
201 jsonw_start_array(json_wtr);
202 for (i = 0; i < info.nr_map_ids; i++)
203 jsonw_uint(json_wtr, map_ids[i]);
204 jsonw_end_array(json_wtr);
205 } else {
206 printf(" map_ids ");
207 for (i = 0; i < info.nr_map_ids; i++)
208 printf("%u%s", map_ids[i],
209 i == info.nr_map_ids - 1 ? "" : ",");
210 }
211}
212
213static void print_prog_json(struct bpf_prog_info *info, int fd)
214{
215 char *memlock;
216
217 jsonw_start_object(json_wtr);
218 jsonw_uint_field(json_wtr, "id", info->id);
219 if (info->type < ARRAY_SIZE(prog_type_name))
220 jsonw_string_field(json_wtr, "type",
221 prog_type_name[info->type]);
222 else
223 jsonw_uint_field(json_wtr, "type", info->type);
224
225 if (*info->name)
226 jsonw_string_field(json_wtr, "name", info->name);
227
228 jsonw_name(json_wtr, "tag");
229 jsonw_printf(json_wtr, "\"" BPF_TAG_FMT "\"",
230 info->tag[0], info->tag[1], info->tag[2], info->tag[3],
231 info->tag[4], info->tag[5], info->tag[6], info->tag[7]);
232
233 if (info->status & BPF_PROG_STATUS_DEV_BOUND) {
234 jsonw_name(json_wtr, "dev");
235 if (info->ifindex) {
236 char name[IF_NAMESIZE];
237
238 if (!if_indextoname(info->ifindex, name))
239 jsonw_printf(json_wtr, "\"ifindex:%d\"",
240 info->ifindex);
241 else
242 jsonw_printf(json_wtr, "\"%s\"", name);
243 } else {
244 jsonw_printf(json_wtr, "\"unknown\"");
245 }
246 }
247
248 if (info->load_time) {
249 char buf[32];
250
251 print_boot_time(info->load_time, buf, sizeof(buf));
252
253 /* Piggy back on load_time, since 0 uid is a valid one */
254 jsonw_string_field(json_wtr, "loaded_at", buf);
255 jsonw_uint_field(json_wtr, "uid", info->created_by_uid);
256 }
257
258 jsonw_uint_field(json_wtr, "bytes_xlated", info->xlated_prog_len);
259
260 if (info->jited_prog_len) {
261 jsonw_bool_field(json_wtr, "jited", true);
262 jsonw_uint_field(json_wtr, "bytes_jited", info->jited_prog_len);
263 } else {
264 jsonw_bool_field(json_wtr, "jited", false);
265 }
266
267 memlock = get_fdinfo(fd, "memlock");
268 if (memlock)
269 jsonw_int_field(json_wtr, "bytes_memlock", atoi(memlock));
270 free(memlock);
271
272 if (info->nr_map_ids)
273 show_prog_maps(fd, info->nr_map_ids);
274
275 if (!hash_empty(prog_table.table)) {
276 struct pinned_obj *obj;
277
278 jsonw_name(json_wtr, "pinned");
279 jsonw_start_array(json_wtr);
280 hash_for_each_possible(prog_table.table, obj, hash, info->id) {
281 if (obj->id == info->id)
282 jsonw_string(json_wtr, obj->path);
283 }
284 jsonw_end_array(json_wtr);
285 }
286
287 jsonw_end_object(json_wtr);
288}
289
290static void print_prog_plain(struct bpf_prog_info *info, int fd)
291{
292 char *memlock;
293
294 printf("%u: ", info->id);
295 if (info->type < ARRAY_SIZE(prog_type_name))
296 printf("%s ", prog_type_name[info->type]);
297 else
298 printf("type %u ", info->type);
299
300 if (*info->name)
301 printf("name %s ", info->name);
302
303 printf("tag ");
304 fprint_hex(stdout, info->tag, BPF_TAG_SIZE, "");
305 printf(" ");
306
307 if (info->status & BPF_PROG_STATUS_DEV_BOUND) {
308 printf("dev ");
309 if (info->ifindex) {
310 char name[IF_NAMESIZE];
311
312 if (!if_indextoname(info->ifindex, name))
313 printf("ifindex:%d ", info->ifindex);
314 else
315 printf("%s ", name);
316 } else {
317 printf("unknown ");
318 }
319 }
320 printf("\n");
321
322 if (info->load_time) {
323 char buf[32];
324
325 print_boot_time(info->load_time, buf, sizeof(buf));
326
327 /* Piggy back on load_time, since 0 uid is a valid one */
328 printf("\tloaded_at %s uid %u\n", buf, info->created_by_uid);
329 }
330
331 printf("\txlated %uB", info->xlated_prog_len);
332
333 if (info->jited_prog_len)
334 printf(" jited %uB", info->jited_prog_len);
335 else
336 printf(" not jited");
337
338 memlock = get_fdinfo(fd, "memlock");
339 if (memlock)
340 printf(" memlock %sB", memlock);
341 free(memlock);
342
343 if (info->nr_map_ids)
344 show_prog_maps(fd, info->nr_map_ids);
345
346 if (!hash_empty(prog_table.table)) {
347 struct pinned_obj *obj;
348
349 printf("\n");
350 hash_for_each_possible(prog_table.table, obj, hash, info->id) {
351 if (obj->id == info->id)
352 printf("\tpinned %s\n", obj->path);
353 }
354 }
355
356 printf("\n");
357}
358
359static int show_prog(int fd)
360{
361 struct bpf_prog_info info = {};
362 __u32 len = sizeof(info);
363 int err;
364
365 err = bpf_obj_get_info_by_fd(fd, &info, &len);
366 if (err) {
367 p_err("can't get prog info: %s", strerror(errno));
368 return -1;
369 }
370
371 if (json_output)
372 print_prog_json(&info, fd);
373 else
374 print_prog_plain(&info, fd);
375
376 return 0;
377}
378
379static int do_show(int argc, char **argv)
380{
381 __u32 id = 0;
382 int err;
383 int fd;
384
385 if (show_pinned)
386 build_pinned_obj_table(&prog_table, BPF_OBJ_PROG);
387
388 if (argc == 2) {
389 fd = prog_parse_fd(&argc, &argv);
390 if (fd < 0)
391 return -1;
392
393 return show_prog(fd);
394 }
395
396 if (argc)
397 return BAD_ARG();
398
399 if (json_output)
400 jsonw_start_array(json_wtr);
401 while (true) {
402 err = bpf_prog_get_next_id(id, &id);
403 if (err) {
404 if (errno == ENOENT) {
405 err = 0;
406 break;
407 }
408 p_err("can't get next program: %s%s", strerror(errno),
409 errno == EINVAL ? " -- kernel too old?" : "");
410 err = -1;
411 break;
412 }
413
414 fd = bpf_prog_get_fd_by_id(id);
415 if (fd < 0) {
416 p_err("can't get prog by id (%u): %s",
417 id, strerror(errno));
418 err = -1;
419 break;
420 }
421
422 err = show_prog(fd);
423 close(fd);
424 if (err)
425 break;
426 }
427
428 if (json_output)
429 jsonw_end_array(json_wtr);
430
431 return err;
432}
433
434static void print_insn(struct bpf_verifier_env *env, const char *fmt, ...)
435{
436 va_list args;
437
438 va_start(args, fmt);
439 vprintf(fmt, args);
440 va_end(args);
441}
442
443static void dump_xlated_plain(void *buf, unsigned int len, bool opcodes)
444{
445 struct bpf_insn *insn = buf;
446 bool double_insn = false;
447 unsigned int i;
448
449 for (i = 0; i < len / sizeof(*insn); i++) {
450 if (double_insn) {
451 double_insn = false;
452 continue;
453 }
454
455 double_insn = insn[i].code == (BPF_LD | BPF_IMM | BPF_DW);
456
457 printf("% 4d: ", i);
458 print_bpf_insn(print_insn, NULL, insn + i, true);
459
460 if (opcodes) {
461 printf(" ");
462 fprint_hex(stdout, insn + i, 8, " ");
463 if (double_insn && i < len - 1) {
464 printf(" ");
465 fprint_hex(stdout, insn + i + 1, 8, " ");
466 }
467 printf("\n");
468 }
469 }
470}
471
472static void print_insn_json(struct bpf_verifier_env *env, const char *fmt, ...)
473{
474 unsigned int l = strlen(fmt);
475 char chomped_fmt[l];
476 va_list args;
477
478 va_start(args, fmt);
479 if (l > 0) {
480 strncpy(chomped_fmt, fmt, l - 1);
481 chomped_fmt[l - 1] = '\0';
482 }
483 jsonw_vprintf_enquote(json_wtr, chomped_fmt, args);
484 va_end(args);
485}
486
487static void dump_xlated_json(void *buf, unsigned int len, bool opcodes)
488{
489 struct bpf_insn *insn = buf;
490 bool double_insn = false;
491 unsigned int i;
492
493 jsonw_start_array(json_wtr);
494 for (i = 0; i < len / sizeof(*insn); i++) {
495 if (double_insn) {
496 double_insn = false;
497 continue;
498 }
499 double_insn = insn[i].code == (BPF_LD | BPF_IMM | BPF_DW);
500
501 jsonw_start_object(json_wtr);
502 jsonw_name(json_wtr, "disasm");
503 print_bpf_insn(print_insn_json, NULL, insn + i, true);
504
505 if (opcodes) {
506 jsonw_name(json_wtr, "opcodes");
507 jsonw_start_object(json_wtr);
508
509 jsonw_name(json_wtr, "code");
510 jsonw_printf(json_wtr, "\"0x%02hhx\"", insn[i].code);
511
512 jsonw_name(json_wtr, "src_reg");
513 jsonw_printf(json_wtr, "\"0x%hhx\"", insn[i].src_reg);
514
515 jsonw_name(json_wtr, "dst_reg");
516 jsonw_printf(json_wtr, "\"0x%hhx\"", insn[i].dst_reg);
517
518 jsonw_name(json_wtr, "off");
519 print_hex_data_json((uint8_t *)(&insn[i].off), 2);
520
521 jsonw_name(json_wtr, "imm");
522 if (double_insn && i < len - 1)
523 print_hex_data_json((uint8_t *)(&insn[i].imm),
524 12);
525 else
526 print_hex_data_json((uint8_t *)(&insn[i].imm),
527 4);
528 jsonw_end_object(json_wtr);
529 }
530 jsonw_end_object(json_wtr);
531 }
532 jsonw_end_array(json_wtr);
533}
534
535static int do_dump(int argc, char **argv)
536{
537 struct bpf_prog_info info = {};
538 __u32 len = sizeof(info);
539 unsigned int buf_size;
540 char *filepath = NULL;
541 bool opcodes = false;
542 unsigned char *buf;
543 __u32 *member_len;
544 __u64 *member_ptr;
545 ssize_t n;
546 int err;
547 int fd;
548
549 if (is_prefix(*argv, "jited")) {
550 member_len = &info.jited_prog_len;
551 member_ptr = &info.jited_prog_insns;
552 } else if (is_prefix(*argv, "xlated")) {
553 member_len = &info.xlated_prog_len;
554 member_ptr = &info.xlated_prog_insns;
555 } else {
556 p_err("expected 'xlated' or 'jited', got: %s", *argv);
557 return -1;
558 }
559 NEXT_ARG();
560
561 if (argc < 2)
562 usage();
563
564 fd = prog_parse_fd(&argc, &argv);
565 if (fd < 0)
566 return -1;
567
568 if (is_prefix(*argv, "file")) {
569 NEXT_ARG();
570 if (!argc) {
571 p_err("expected file path");
572 return -1;
573 }
574
575 filepath = *argv;
576 NEXT_ARG();
577 } else if (is_prefix(*argv, "opcodes")) {
578 opcodes = true;
579 NEXT_ARG();
580 }
581
582 if (argc) {
583 usage();
584 return -1;
585 }
586
587 err = bpf_obj_get_info_by_fd(fd, &info, &len);
588 if (err) {
589 p_err("can't get prog info: %s", strerror(errno));
590 return -1;
591 }
592
593 if (!*member_len) {
594 p_info("no instructions returned");
595 close(fd);
596 return 0;
597 }
598
599 buf_size = *member_len;
600
601 buf = malloc(buf_size);
602 if (!buf) {
603 p_err("mem alloc failed");
604 close(fd);
605 return -1;
606 }
607
608 memset(&info, 0, sizeof(info));
609
610 *member_ptr = ptr_to_u64(buf);
611 *member_len = buf_size;
612
613 err = bpf_obj_get_info_by_fd(fd, &info, &len);
614 close(fd);
615 if (err) {
616 p_err("can't get prog info: %s", strerror(errno));
617 goto err_free;
618 }
619
620 if (*member_len > buf_size) {
621 p_err("too many instructions returned");
622 goto err_free;
623 }
624
625 if (filepath) {
626 fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
627 if (fd < 0) {
628 p_err("can't open file %s: %s", filepath,
629 strerror(errno));
630 goto err_free;
631 }
632
633 n = write(fd, buf, *member_len);
634 close(fd);
635 if (n != *member_len) {
636 p_err("error writing output file: %s",
637 n < 0 ? strerror(errno) : "short write");
638 goto err_free;
639 }
640 } else {
641 if (member_len == &info.jited_prog_len)
642 disasm_print_insn(buf, *member_len, opcodes);
643 else
644 if (json_output)
645 dump_xlated_json(buf, *member_len, opcodes);
646 else
647 dump_xlated_plain(buf, *member_len, opcodes);
648 }
649
650 free(buf);
651
652 return 0;
653
654err_free:
655 free(buf);
656 return -1;
657}
658
659static int do_pin(int argc, char **argv)
660{
661 int err;
662
663 err = do_pin_any(argc, argv, bpf_prog_get_fd_by_id);
664 if (!err && json_output)
665 jsonw_null(json_wtr);
666 return err;
667}
668
669static int do_help(int argc, char **argv)
670{
671 if (json_output) {
672 jsonw_null(json_wtr);
673 return 0;
674 }
675
676 fprintf(stderr,
677 "Usage: %s %s show [PROG]\n"
678 " %s %s dump xlated PROG [{ file FILE | opcodes }]\n"
679 " %s %s dump jited PROG [{ file FILE | opcodes }]\n"
680 " %s %s pin PROG FILE\n"
681 " %s %s help\n"
682 "\n"
683 " " HELP_SPEC_PROGRAM "\n"
684 " " HELP_SPEC_OPTIONS "\n"
685 "",
686 bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
687 bin_name, argv[-2], bin_name, argv[-2]);
688
689 return 0;
690}
691
692static const struct cmd cmds[] = {
693 { "show", do_show },
694 { "help", do_help },
695 { "dump", do_dump },
696 { "pin", do_pin },
697 { 0 }
698};
699
700int do_prog(int argc, char **argv)
701{
702 return cmd_select(cmds, argc, argv, do_help);
703}
diff --git a/tools/include/uapi/linux/bpf.h b/tools/include/uapi/linux/bpf.h
index 30f2ce76b517..e880ae6434ee 100644
--- a/tools/include/uapi/linux/bpf.h
+++ b/tools/include/uapi/linux/bpf.h
@@ -93,6 +93,7 @@ enum bpf_cmd {
93 BPF_PROG_GET_FD_BY_ID, 93 BPF_PROG_GET_FD_BY_ID,
94 BPF_MAP_GET_FD_BY_ID, 94 BPF_MAP_GET_FD_BY_ID,
95 BPF_OBJ_GET_INFO_BY_FD, 95 BPF_OBJ_GET_INFO_BY_FD,
96 BPF_PROG_QUERY,
96}; 97};
97 98
98enum bpf_map_type { 99enum bpf_map_type {
@@ -112,6 +113,7 @@ enum bpf_map_type {
112 BPF_MAP_TYPE_HASH_OF_MAPS, 113 BPF_MAP_TYPE_HASH_OF_MAPS,
113 BPF_MAP_TYPE_DEVMAP, 114 BPF_MAP_TYPE_DEVMAP,
114 BPF_MAP_TYPE_SOCKMAP, 115 BPF_MAP_TYPE_SOCKMAP,
116 BPF_MAP_TYPE_CPUMAP,
115}; 117};
116 118
117enum bpf_prog_type { 119enum bpf_prog_type {
@@ -130,6 +132,7 @@ enum bpf_prog_type {
130 BPF_PROG_TYPE_LWT_XMIT, 132 BPF_PROG_TYPE_LWT_XMIT,
131 BPF_PROG_TYPE_SOCK_OPS, 133 BPF_PROG_TYPE_SOCK_OPS,
132 BPF_PROG_TYPE_SK_SKB, 134 BPF_PROG_TYPE_SK_SKB,
135 BPF_PROG_TYPE_CGROUP_DEVICE,
133}; 136};
134 137
135enum bpf_attach_type { 138enum bpf_attach_type {
@@ -139,16 +142,53 @@ enum bpf_attach_type {
139 BPF_CGROUP_SOCK_OPS, 142 BPF_CGROUP_SOCK_OPS,
140 BPF_SK_SKB_STREAM_PARSER, 143 BPF_SK_SKB_STREAM_PARSER,
141 BPF_SK_SKB_STREAM_VERDICT, 144 BPF_SK_SKB_STREAM_VERDICT,
145 BPF_CGROUP_DEVICE,
142 __MAX_BPF_ATTACH_TYPE 146 __MAX_BPF_ATTACH_TYPE
143}; 147};
144 148
145#define MAX_BPF_ATTACH_TYPE __MAX_BPF_ATTACH_TYPE 149#define MAX_BPF_ATTACH_TYPE __MAX_BPF_ATTACH_TYPE
146 150
147/* If BPF_F_ALLOW_OVERRIDE flag is used in BPF_PROG_ATTACH command 151/* cgroup-bpf attach flags used in BPF_PROG_ATTACH command
148 * to the given target_fd cgroup the descendent cgroup will be able to 152 *
149 * override effective bpf program that was inherited from this cgroup 153 * NONE(default): No further bpf programs allowed in the subtree.
154 *
155 * BPF_F_ALLOW_OVERRIDE: If a sub-cgroup installs some bpf program,
156 * the program in this cgroup yields to sub-cgroup program.
157 *
158 * BPF_F_ALLOW_MULTI: If a sub-cgroup installs some bpf program,
159 * that cgroup program gets run in addition to the program in this cgroup.
160 *
161 * Only one program is allowed to be attached to a cgroup with
162 * NONE or BPF_F_ALLOW_OVERRIDE flag.
163 * Attaching another program on top of NONE or BPF_F_ALLOW_OVERRIDE will
164 * release old program and attach the new one. Attach flags has to match.
165 *
166 * Multiple programs are allowed to be attached to a cgroup with
167 * BPF_F_ALLOW_MULTI flag. They are executed in FIFO order
168 * (those that were attached first, run first)
169 * The programs of sub-cgroup are executed first, then programs of
170 * this cgroup and then programs of parent cgroup.
171 * When children program makes decision (like picking TCP CA or sock bind)
172 * parent program has a chance to override it.
173 *
174 * A cgroup with MULTI or OVERRIDE flag allows any attach flags in sub-cgroups.
175 * A cgroup with NONE doesn't allow any programs in sub-cgroups.
176 * Ex1:
177 * cgrp1 (MULTI progs A, B) ->
178 * cgrp2 (OVERRIDE prog C) ->
179 * cgrp3 (MULTI prog D) ->
180 * cgrp4 (OVERRIDE prog E) ->
181 * cgrp5 (NONE prog F)
182 * the event in cgrp5 triggers execution of F,D,A,B in that order.
183 * if prog F is detached, the execution is E,D,A,B
184 * if prog F and D are detached, the execution is E,A,B
185 * if prog F, E and D are detached, the execution is C,A,B
186 *
187 * All eligible programs are executed regardless of return code from
188 * earlier programs.
150 */ 189 */
151#define BPF_F_ALLOW_OVERRIDE (1U << 0) 190#define BPF_F_ALLOW_OVERRIDE (1U << 0)
191#define BPF_F_ALLOW_MULTI (1U << 1)
152 192
153/* If BPF_F_STRICT_ALIGNMENT is used in BPF_PROG_LOAD command, the 193/* If BPF_F_STRICT_ALIGNMENT is used in BPF_PROG_LOAD command, the
154 * verifier will perform strict alignment checking as if the kernel 194 * verifier will perform strict alignment checking as if the kernel
@@ -176,6 +216,15 @@ enum bpf_attach_type {
176/* Specify numa node during map creation */ 216/* Specify numa node during map creation */
177#define BPF_F_NUMA_NODE (1U << 2) 217#define BPF_F_NUMA_NODE (1U << 2)
178 218
219/* flags for BPF_PROG_QUERY */
220#define BPF_F_QUERY_EFFECTIVE (1U << 0)
221
222#define BPF_OBJ_NAME_LEN 16U
223
224/* Flags for accessing BPF object */
225#define BPF_F_RDONLY (1U << 3)
226#define BPF_F_WRONLY (1U << 4)
227
179union bpf_attr { 228union bpf_attr {
180 struct { /* anonymous struct used by BPF_MAP_CREATE command */ 229 struct { /* anonymous struct used by BPF_MAP_CREATE command */
181 __u32 map_type; /* one of enum bpf_map_type */ 230 __u32 map_type; /* one of enum bpf_map_type */
@@ -189,6 +238,7 @@ union bpf_attr {
189 __u32 numa_node; /* numa node (effective only if 238 __u32 numa_node; /* numa node (effective only if
190 * BPF_F_NUMA_NODE is set). 239 * BPF_F_NUMA_NODE is set).
191 */ 240 */
241 char map_name[BPF_OBJ_NAME_LEN];
192 }; 242 };
193 243
194 struct { /* anonymous struct used by BPF_MAP_*_ELEM commands */ 244 struct { /* anonymous struct used by BPF_MAP_*_ELEM commands */
@@ -211,11 +261,14 @@ union bpf_attr {
211 __aligned_u64 log_buf; /* user supplied buffer */ 261 __aligned_u64 log_buf; /* user supplied buffer */
212 __u32 kern_version; /* checked when prog_type=kprobe */ 262 __u32 kern_version; /* checked when prog_type=kprobe */
213 __u32 prog_flags; 263 __u32 prog_flags;
264 char prog_name[BPF_OBJ_NAME_LEN];
265 __u32 prog_target_ifindex; /* ifindex of netdev to prep for */
214 }; 266 };
215 267
216 struct { /* anonymous struct used by BPF_OBJ_* commands */ 268 struct { /* anonymous struct used by BPF_OBJ_* commands */
217 __aligned_u64 pathname; 269 __aligned_u64 pathname;
218 __u32 bpf_fd; 270 __u32 bpf_fd;
271 __u32 file_flags;
219 }; 272 };
220 273
221 struct { /* anonymous struct used by BPF_PROG_ATTACH/DETACH commands */ 274 struct { /* anonymous struct used by BPF_PROG_ATTACH/DETACH commands */
@@ -243,6 +296,7 @@ union bpf_attr {
243 __u32 map_id; 296 __u32 map_id;
244 }; 297 };
245 __u32 next_id; 298 __u32 next_id;
299 __u32 open_flags;
246 }; 300 };
247 301
248 struct { /* anonymous struct used by BPF_OBJ_GET_INFO_BY_FD */ 302 struct { /* anonymous struct used by BPF_OBJ_GET_INFO_BY_FD */
@@ -250,6 +304,15 @@ union bpf_attr {
250 __u32 info_len; 304 __u32 info_len;
251 __aligned_u64 info; 305 __aligned_u64 info;
252 } info; 306 } info;
307
308 struct { /* anonymous struct used by BPF_PROG_QUERY command */
309 __u32 target_fd; /* container object to query */
310 __u32 attach_type;
311 __u32 query_flags;
312 __u32 attach_flags;
313 __aligned_u64 prog_ids;
314 __u32 prog_cnt;
315 } query;
253} __attribute__((aligned(8))); 316} __attribute__((aligned(8)));
254 317
255/* BPF helper function descriptions: 318/* BPF helper function descriptions:
@@ -554,12 +617,22 @@ union bpf_attr {
554 * int bpf_setsockopt(bpf_socket, level, optname, optval, optlen) 617 * int bpf_setsockopt(bpf_socket, level, optname, optval, optlen)
555 * Calls setsockopt. Not all opts are available, only those with 618 * Calls setsockopt. Not all opts are available, only those with
556 * integer optvals plus TCP_CONGESTION. 619 * integer optvals plus TCP_CONGESTION.
557 * Supported levels: SOL_SOCKET and IPROTO_TCP 620 * Supported levels: SOL_SOCKET and IPPROTO_TCP
621 * @bpf_socket: pointer to bpf_socket
622 * @level: SOL_SOCKET or IPPROTO_TCP
623 * @optname: option name
624 * @optval: pointer to option value
625 * @optlen: length of optval in bytes
626 * Return: 0 or negative error
627 *
628 * int bpf_getsockopt(bpf_socket, level, optname, optval, optlen)
629 * Calls getsockopt. Not all opts are available.
630 * Supported levels: IPPROTO_TCP
558 * @bpf_socket: pointer to bpf_socket 631 * @bpf_socket: pointer to bpf_socket
559 * @level: SOL_SOCKET or IPROTO_TCP 632 * @level: IPPROTO_TCP
560 * @optname: option name 633 * @optname: option name
561 * @optval: pointer to option value 634 * @optval: pointer to option value
562 * @optlen: length of optval in byes 635 * @optlen: length of optval in bytes
563 * Return: 0 or negative error 636 * Return: 0 or negative error
564 * 637 *
565 * int bpf_skb_adjust_room(skb, len_diff, mode, flags) 638 * int bpf_skb_adjust_room(skb, len_diff, mode, flags)
@@ -583,6 +656,27 @@ union bpf_attr {
583 * @map: pointer to sockmap to update 656 * @map: pointer to sockmap to update
584 * @key: key to insert/update sock in map 657 * @key: key to insert/update sock in map
585 * @flags: same flags as map update elem 658 * @flags: same flags as map update elem
659 *
660 * int bpf_xdp_adjust_meta(xdp_md, delta)
661 * Adjust the xdp_md.data_meta by delta
662 * @xdp_md: pointer to xdp_md
663 * @delta: An positive/negative integer to be added to xdp_md.data_meta
664 * Return: 0 on success or negative on error
665 *
666 * int bpf_perf_event_read_value(map, flags, buf, buf_size)
667 * read perf event counter value and perf event enabled/running time
668 * @map: pointer to perf_event_array map
669 * @flags: index of event in the map or bitmask flags
670 * @buf: buf to fill
671 * @buf_size: size of the buf
672 * Return: 0 on success or negative error code
673 *
674 * int bpf_perf_prog_read_value(ctx, buf, buf_size)
675 * read perf prog attached perf event counter and enabled/running time
676 * @ctx: pointer to ctx
677 * @buf: buf to fill
678 * @buf_size: size of the buf
679 * Return : 0 on success or negative error code
586 */ 680 */
587#define __BPF_FUNC_MAPPER(FN) \ 681#define __BPF_FUNC_MAPPER(FN) \
588 FN(unspec), \ 682 FN(unspec), \
@@ -639,6 +733,10 @@ union bpf_attr {
639 FN(redirect_map), \ 733 FN(redirect_map), \
640 FN(sk_redirect_map), \ 734 FN(sk_redirect_map), \
641 FN(sock_map_update), \ 735 FN(sock_map_update), \
736 FN(xdp_adjust_meta), \
737 FN(perf_event_read_value), \
738 FN(perf_prog_read_value), \
739 FN(getsockopt),
642 740
643/* integer value in 'imm' field of BPF_CALL instruction selects which helper 741/* integer value in 'imm' field of BPF_CALL instruction selects which helper
644 * function eBPF program intends to call 742 * function eBPF program intends to call
@@ -682,7 +780,9 @@ enum bpf_func_id {
682#define BPF_F_ZERO_CSUM_TX (1ULL << 1) 780#define BPF_F_ZERO_CSUM_TX (1ULL << 1)
683#define BPF_F_DONT_FRAGMENT (1ULL << 2) 781#define BPF_F_DONT_FRAGMENT (1ULL << 2)
684 782
685/* BPF_FUNC_perf_event_output and BPF_FUNC_perf_event_read flags. */ 783/* BPF_FUNC_perf_event_output, BPF_FUNC_perf_event_read and
784 * BPF_FUNC_perf_event_read_value flags.
785 */
686#define BPF_F_INDEX_MASK 0xffffffffULL 786#define BPF_F_INDEX_MASK 0xffffffffULL
687#define BPF_F_CURRENT_CPU BPF_F_INDEX_MASK 787#define BPF_F_CURRENT_CPU BPF_F_INDEX_MASK
688/* BPF_FUNC_perf_event_output for sk_buff input context. */ 788/* BPF_FUNC_perf_event_output for sk_buff input context. */
@@ -716,7 +816,7 @@ struct __sk_buff {
716 __u32 data_end; 816 __u32 data_end;
717 __u32 napi_id; 817 __u32 napi_id;
718 818
719 /* accessed by BPF_PROG_TYPE_sk_skb types */ 819 /* Accessed by BPF_PROG_TYPE_sk_skb types from here to ... */
720 __u32 family; 820 __u32 family;
721 __u32 remote_ip4; /* Stored in network byte order */ 821 __u32 remote_ip4; /* Stored in network byte order */
722 __u32 local_ip4; /* Stored in network byte order */ 822 __u32 local_ip4; /* Stored in network byte order */
@@ -724,6 +824,9 @@ struct __sk_buff {
724 __u32 local_ip6[4]; /* Stored in network byte order */ 824 __u32 local_ip6[4]; /* Stored in network byte order */
725 __u32 remote_port; /* Stored in network byte order */ 825 __u32 remote_port; /* Stored in network byte order */
726 __u32 local_port; /* stored in host byte order */ 826 __u32 local_port; /* stored in host byte order */
827 /* ... here. */
828
829 __u32 data_meta;
727}; 830};
728 831
729struct bpf_tunnel_key { 832struct bpf_tunnel_key {
@@ -784,6 +887,7 @@ enum xdp_action {
784struct xdp_md { 887struct xdp_md {
785 __u32 data; 888 __u32 data;
786 __u32 data_end; 889 __u32 data_end;
890 __u32 data_meta;
787}; 891};
788 892
789enum sk_action { 893enum sk_action {
@@ -793,6 +897,10 @@ enum sk_action {
793 897
794#define BPF_TAG_SIZE 8 898#define BPF_TAG_SIZE 8
795 899
900enum bpf_prog_status {
901 BPF_PROG_STATUS_DEV_BOUND = (1 << 0),
902};
903
796struct bpf_prog_info { 904struct bpf_prog_info {
797 __u32 type; 905 __u32 type;
798 __u32 id; 906 __u32 id;
@@ -801,6 +909,13 @@ struct bpf_prog_info {
801 __u32 xlated_prog_len; 909 __u32 xlated_prog_len;
802 __aligned_u64 jited_prog_insns; 910 __aligned_u64 jited_prog_insns;
803 __aligned_u64 xlated_prog_insns; 911 __aligned_u64 xlated_prog_insns;
912 __u64 load_time; /* ns since boottime */
913 __u32 created_by_uid;
914 __u32 nr_map_ids;
915 __aligned_u64 map_ids;
916 char name[BPF_OBJ_NAME_LEN];
917 __u32 ifindex;
918 __u32 status;
804} __attribute__((aligned(8))); 919} __attribute__((aligned(8)));
805 920
806struct bpf_map_info { 921struct bpf_map_info {
@@ -810,6 +925,7 @@ struct bpf_map_info {
810 __u32 value_size; 925 __u32 value_size;
811 __u32 max_entries; 926 __u32 max_entries;
812 __u32 map_flags; 927 __u32 map_flags;
928 char name[BPF_OBJ_NAME_LEN];
813} __attribute__((aligned(8))); 929} __attribute__((aligned(8)));
814 930
815/* User bpf_sock_ops struct to access socket values and specify request ops 931/* User bpf_sock_ops struct to access socket values and specify request ops
@@ -859,9 +975,35 @@ enum {
859 BPF_SOCK_OPS_NEEDS_ECN, /* If connection's congestion control 975 BPF_SOCK_OPS_NEEDS_ECN, /* If connection's congestion control
860 * needs ECN 976 * needs ECN
861 */ 977 */
978 BPF_SOCK_OPS_BASE_RTT, /* Get base RTT. The correct value is
979 * based on the path and may be
980 * dependent on the congestion control
981 * algorithm. In general it indicates
982 * a congestion threshold. RTTs above
983 * this indicate congestion
984 */
862}; 985};
863 986
864#define TCP_BPF_IW 1001 /* Set TCP initial congestion window */ 987#define TCP_BPF_IW 1001 /* Set TCP initial congestion window */
865#define TCP_BPF_SNDCWND_CLAMP 1002 /* Set sndcwnd_clamp */ 988#define TCP_BPF_SNDCWND_CLAMP 1002 /* Set sndcwnd_clamp */
866 989
990struct bpf_perf_event_value {
991 __u64 counter;
992 __u64 enabled;
993 __u64 running;
994};
995
996#define BPF_DEVCG_ACC_MKNOD (1ULL << 0)
997#define BPF_DEVCG_ACC_READ (1ULL << 1)
998#define BPF_DEVCG_ACC_WRITE (1ULL << 2)
999
1000#define BPF_DEVCG_DEV_BLOCK (1ULL << 0)
1001#define BPF_DEVCG_DEV_CHAR (1ULL << 1)
1002
1003struct bpf_cgroup_dev_ctx {
1004 __u32 access_type; /* (access << 16) | type */
1005 __u32 major;
1006 __u32 minor;
1007};
1008
867#endif /* _UAPI__LINUX_BPF_H__ */ 1009#endif /* _UAPI__LINUX_BPF_H__ */
diff --git a/tools/lib/bpf/bpf.c b/tools/lib/bpf/bpf.c
index 1d6907d379c9..5128677e4117 100644
--- a/tools/lib/bpf/bpf.c
+++ b/tools/lib/bpf/bpf.c
@@ -46,6 +46,8 @@
46# endif 46# endif
47#endif 47#endif
48 48
49#define min(x, y) ((x) < (y) ? (x) : (y))
50
49static inline __u64 ptr_to_u64(const void *ptr) 51static inline __u64 ptr_to_u64(const void *ptr)
50{ 52{
51 return (__u64) (unsigned long) ptr; 53 return (__u64) (unsigned long) ptr;
@@ -57,10 +59,11 @@ static inline int sys_bpf(enum bpf_cmd cmd, union bpf_attr *attr,
57 return syscall(__NR_bpf, cmd, attr, size); 59 return syscall(__NR_bpf, cmd, attr, size);
58} 60}
59 61
60int bpf_create_map_node(enum bpf_map_type map_type, int key_size, 62int bpf_create_map_node(enum bpf_map_type map_type, const char *name,
61 int value_size, int max_entries, __u32 map_flags, 63 int key_size, int value_size, int max_entries,
62 int node) 64 __u32 map_flags, int node)
63{ 65{
66 __u32 name_len = name ? strlen(name) : 0;
64 union bpf_attr attr; 67 union bpf_attr attr;
65 68
66 memset(&attr, '\0', sizeof(attr)); 69 memset(&attr, '\0', sizeof(attr));
@@ -70,6 +73,8 @@ int bpf_create_map_node(enum bpf_map_type map_type, int key_size,
70 attr.value_size = value_size; 73 attr.value_size = value_size;
71 attr.max_entries = max_entries; 74 attr.max_entries = max_entries;
72 attr.map_flags = map_flags; 75 attr.map_flags = map_flags;
76 memcpy(attr.map_name, name, min(name_len, BPF_OBJ_NAME_LEN - 1));
77
73 if (node >= 0) { 78 if (node >= 0) {
74 attr.map_flags |= BPF_F_NUMA_NODE; 79 attr.map_flags |= BPF_F_NUMA_NODE;
75 attr.numa_node = node; 80 attr.numa_node = node;
@@ -81,14 +86,23 @@ int bpf_create_map_node(enum bpf_map_type map_type, int key_size,
81int bpf_create_map(enum bpf_map_type map_type, int key_size, 86int bpf_create_map(enum bpf_map_type map_type, int key_size,
82 int value_size, int max_entries, __u32 map_flags) 87 int value_size, int max_entries, __u32 map_flags)
83{ 88{
84 return bpf_create_map_node(map_type, key_size, value_size, 89 return bpf_create_map_node(map_type, NULL, key_size, value_size,
85 max_entries, map_flags, -1); 90 max_entries, map_flags, -1);
86} 91}
87 92
88int bpf_create_map_in_map_node(enum bpf_map_type map_type, int key_size, 93int bpf_create_map_name(enum bpf_map_type map_type, const char *name,
89 int inner_map_fd, int max_entries, 94 int key_size, int value_size, int max_entries,
95 __u32 map_flags)
96{
97 return bpf_create_map_node(map_type, name, key_size, value_size,
98 max_entries, map_flags, -1);
99}
100
101int bpf_create_map_in_map_node(enum bpf_map_type map_type, const char *name,
102 int key_size, int inner_map_fd, int max_entries,
90 __u32 map_flags, int node) 103 __u32 map_flags, int node)
91{ 104{
105 __u32 name_len = name ? strlen(name) : 0;
92 union bpf_attr attr; 106 union bpf_attr attr;
93 107
94 memset(&attr, '\0', sizeof(attr)); 108 memset(&attr, '\0', sizeof(attr));
@@ -99,6 +113,8 @@ int bpf_create_map_in_map_node(enum bpf_map_type map_type, int key_size,
99 attr.inner_map_fd = inner_map_fd; 113 attr.inner_map_fd = inner_map_fd;
100 attr.max_entries = max_entries; 114 attr.max_entries = max_entries;
101 attr.map_flags = map_flags; 115 attr.map_flags = map_flags;
116 memcpy(attr.map_name, name, min(name_len, BPF_OBJ_NAME_LEN - 1));
117
102 if (node >= 0) { 118 if (node >= 0) {
103 attr.map_flags |= BPF_F_NUMA_NODE; 119 attr.map_flags |= BPF_F_NUMA_NODE;
104 attr.numa_node = node; 120 attr.numa_node = node;
@@ -107,19 +123,24 @@ int bpf_create_map_in_map_node(enum bpf_map_type map_type, int key_size,
107 return sys_bpf(BPF_MAP_CREATE, &attr, sizeof(attr)); 123 return sys_bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
108} 124}
109 125
110int bpf_create_map_in_map(enum bpf_map_type map_type, int key_size, 126int bpf_create_map_in_map(enum bpf_map_type map_type, const char *name,
111 int inner_map_fd, int max_entries, __u32 map_flags) 127 int key_size, int inner_map_fd, int max_entries,
128 __u32 map_flags)
112{ 129{
113 return bpf_create_map_in_map_node(map_type, key_size, inner_map_fd, 130 return bpf_create_map_in_map_node(map_type, name, key_size,
114 max_entries, map_flags, -1); 131 inner_map_fd, max_entries, map_flags,
132 -1);
115} 133}
116 134
117int bpf_load_program(enum bpf_prog_type type, const struct bpf_insn *insns, 135int bpf_load_program_name(enum bpf_prog_type type, const char *name,
118 size_t insns_cnt, const char *license, 136 const struct bpf_insn *insns,
119 __u32 kern_version, char *log_buf, size_t log_buf_sz) 137 size_t insns_cnt, const char *license,
138 __u32 kern_version, char *log_buf,
139 size_t log_buf_sz)
120{ 140{
121 int fd; 141 int fd;
122 union bpf_attr attr; 142 union bpf_attr attr;
143 __u32 name_len = name ? strlen(name) : 0;
123 144
124 bzero(&attr, sizeof(attr)); 145 bzero(&attr, sizeof(attr));
125 attr.prog_type = type; 146 attr.prog_type = type;
@@ -130,6 +151,7 @@ int bpf_load_program(enum bpf_prog_type type, const struct bpf_insn *insns,
130 attr.log_size = 0; 151 attr.log_size = 0;
131 attr.log_level = 0; 152 attr.log_level = 0;
132 attr.kern_version = kern_version; 153 attr.kern_version = kern_version;
154 memcpy(attr.prog_name, name, min(name_len, BPF_OBJ_NAME_LEN - 1));
133 155
134 fd = sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr)); 156 fd = sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
135 if (fd >= 0 || !log_buf || !log_buf_sz) 157 if (fd >= 0 || !log_buf || !log_buf_sz)
@@ -143,6 +165,15 @@ int bpf_load_program(enum bpf_prog_type type, const struct bpf_insn *insns,
143 return sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr)); 165 return sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
144} 166}
145 167
168int bpf_load_program(enum bpf_prog_type type, const struct bpf_insn *insns,
169 size_t insns_cnt, const char *license,
170 __u32 kern_version, char *log_buf,
171 size_t log_buf_sz)
172{
173 return bpf_load_program_name(type, NULL, insns, insns_cnt, license,
174 kern_version, log_buf, log_buf_sz);
175}
176
146int bpf_verify_program(enum bpf_prog_type type, const struct bpf_insn *insns, 177int bpf_verify_program(enum bpf_prog_type type, const struct bpf_insn *insns,
147 size_t insns_cnt, int strict_alignment, 178 size_t insns_cnt, int strict_alignment,
148 const char *license, __u32 kern_version, 179 const char *license, __u32 kern_version,
@@ -260,6 +291,38 @@ int bpf_prog_detach(int target_fd, enum bpf_attach_type type)
260 return sys_bpf(BPF_PROG_DETACH, &attr, sizeof(attr)); 291 return sys_bpf(BPF_PROG_DETACH, &attr, sizeof(attr));
261} 292}
262 293
294int bpf_prog_detach2(int prog_fd, int target_fd, enum bpf_attach_type type)
295{
296 union bpf_attr attr;
297
298 bzero(&attr, sizeof(attr));
299 attr.target_fd = target_fd;
300 attr.attach_bpf_fd = prog_fd;
301 attr.attach_type = type;
302
303 return sys_bpf(BPF_PROG_DETACH, &attr, sizeof(attr));
304}
305
306int bpf_prog_query(int target_fd, enum bpf_attach_type type, __u32 query_flags,
307 __u32 *attach_flags, __u32 *prog_ids, __u32 *prog_cnt)
308{
309 union bpf_attr attr;
310 int ret;
311
312 bzero(&attr, sizeof(attr));
313 attr.query.target_fd = target_fd;
314 attr.query.attach_type = type;
315 attr.query.query_flags = query_flags;
316 attr.query.prog_cnt = *prog_cnt;
317 attr.query.prog_ids = ptr_to_u64(prog_ids);
318
319 ret = sys_bpf(BPF_PROG_QUERY, &attr, sizeof(attr));
320 if (attach_flags)
321 *attach_flags = attr.query.attach_flags;
322 *prog_cnt = attr.query.prog_cnt;
323 return ret;
324}
325
263int bpf_prog_test_run(int prog_fd, int repeat, void *data, __u32 size, 326int bpf_prog_test_run(int prog_fd, int repeat, void *data, __u32 size,
264 void *data_out, __u32 *size_out, __u32 *retval, 327 void *data_out, __u32 *size_out, __u32 *retval,
265 __u32 *duration) 328 __u32 *duration)
diff --git a/tools/lib/bpf/bpf.h b/tools/lib/bpf/bpf.h
index b8ea5843c39e..6534889e2b2f 100644
--- a/tools/lib/bpf/bpf.h
+++ b/tools/lib/bpf/bpf.h
@@ -24,19 +24,28 @@
24#include <linux/bpf.h> 24#include <linux/bpf.h>
25#include <stddef.h> 25#include <stddef.h>
26 26
27int bpf_create_map_node(enum bpf_map_type map_type, int key_size, 27int bpf_create_map_node(enum bpf_map_type map_type, const char *name,
28 int value_size, int max_entries, __u32 map_flags, 28 int key_size, int value_size, int max_entries,
29 int node); 29 __u32 map_flags, int node);
30int bpf_create_map_name(enum bpf_map_type map_type, const char *name,
31 int key_size, int value_size, int max_entries,
32 __u32 map_flags);
30int bpf_create_map(enum bpf_map_type map_type, int key_size, int value_size, 33int bpf_create_map(enum bpf_map_type map_type, int key_size, int value_size,
31 int max_entries, __u32 map_flags); 34 int max_entries, __u32 map_flags);
32int bpf_create_map_in_map_node(enum bpf_map_type map_type, int key_size, 35int bpf_create_map_in_map_node(enum bpf_map_type map_type, const char *name,
33 int inner_map_fd, int max_entries, 36 int key_size, int inner_map_fd, int max_entries,
34 __u32 map_flags, int node); 37 __u32 map_flags, int node);
35int bpf_create_map_in_map(enum bpf_map_type map_type, int key_size, 38int bpf_create_map_in_map(enum bpf_map_type map_type, const char *name,
36 int inner_map_fd, int max_entries, __u32 map_flags); 39 int key_size, int inner_map_fd, int max_entries,
40 __u32 map_flags);
37 41
38/* Recommend log buffer size */ 42/* Recommend log buffer size */
39#define BPF_LOG_BUF_SIZE 65536 43#define BPF_LOG_BUF_SIZE 65536
44int bpf_load_program_name(enum bpf_prog_type type, const char *name,
45 const struct bpf_insn *insns,
46 size_t insns_cnt, const char *license,
47 __u32 kern_version, char *log_buf,
48 size_t log_buf_sz);
40int bpf_load_program(enum bpf_prog_type type, const struct bpf_insn *insns, 49int bpf_load_program(enum bpf_prog_type type, const struct bpf_insn *insns,
41 size_t insns_cnt, const char *license, 50 size_t insns_cnt, const char *license,
42 __u32 kern_version, char *log_buf, 51 __u32 kern_version, char *log_buf,
@@ -57,6 +66,7 @@ int bpf_obj_get(const char *pathname);
57int bpf_prog_attach(int prog_fd, int attachable_fd, enum bpf_attach_type type, 66int bpf_prog_attach(int prog_fd, int attachable_fd, enum bpf_attach_type type,
58 unsigned int flags); 67 unsigned int flags);
59int bpf_prog_detach(int attachable_fd, enum bpf_attach_type type); 68int bpf_prog_detach(int attachable_fd, enum bpf_attach_type type);
69int bpf_prog_detach2(int prog_fd, int attachable_fd, enum bpf_attach_type type);
60int bpf_prog_test_run(int prog_fd, int repeat, void *data, __u32 size, 70int bpf_prog_test_run(int prog_fd, int repeat, void *data, __u32 size,
61 void *data_out, __u32 *size_out, __u32 *retval, 71 void *data_out, __u32 *size_out, __u32 *retval,
62 __u32 *duration); 72 __u32 *duration);
@@ -65,5 +75,6 @@ int bpf_map_get_next_id(__u32 start_id, __u32 *next_id);
65int bpf_prog_get_fd_by_id(__u32 id); 75int bpf_prog_get_fd_by_id(__u32 id);
66int bpf_map_get_fd_by_id(__u32 id); 76int bpf_map_get_fd_by_id(__u32 id);
67int bpf_obj_get_info_by_fd(int prog_fd, void *info, __u32 *info_len); 77int bpf_obj_get_info_by_fd(int prog_fd, void *info, __u32 *info_len);
68 78int bpf_prog_query(int target_fd, enum bpf_attach_type type, __u32 query_flags,
79 __u32 *attach_flags, __u32 *prog_ids, __u32 *prog_cnt);
69#endif 80#endif
diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c
index 35f6dfcdc565..5aa45f89da93 100644
--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@ -171,6 +171,7 @@ int libbpf_strerror(int err, char *buf, size_t size)
171struct bpf_program { 171struct bpf_program {
172 /* Index in elf obj file, for relocation use. */ 172 /* Index in elf obj file, for relocation use. */
173 int idx; 173 int idx;
174 char *name;
174 char *section_name; 175 char *section_name;
175 struct bpf_insn *insns; 176 struct bpf_insn *insns;
176 size_t insns_cnt; 177 size_t insns_cnt;
@@ -283,6 +284,7 @@ static void bpf_program__exit(struct bpf_program *prog)
283 prog->clear_priv = NULL; 284 prog->clear_priv = NULL;
284 285
285 bpf_program__unload(prog); 286 bpf_program__unload(prog);
287 zfree(&prog->name);
286 zfree(&prog->section_name); 288 zfree(&prog->section_name);
287 zfree(&prog->insns); 289 zfree(&prog->insns);
288 zfree(&prog->reloc_desc); 290 zfree(&prog->reloc_desc);
@@ -293,26 +295,27 @@ static void bpf_program__exit(struct bpf_program *prog)
293} 295}
294 296
295static int 297static int
296bpf_program__init(void *data, size_t size, char *name, int idx, 298bpf_program__init(void *data, size_t size, char *section_name, int idx,
297 struct bpf_program *prog) 299 struct bpf_program *prog)
298{ 300{
299 if (size < sizeof(struct bpf_insn)) { 301 if (size < sizeof(struct bpf_insn)) {
300 pr_warning("corrupted section '%s'\n", name); 302 pr_warning("corrupted section '%s'\n", section_name);
301 return -EINVAL; 303 return -EINVAL;
302 } 304 }
303 305
304 bzero(prog, sizeof(*prog)); 306 bzero(prog, sizeof(*prog));
305 307
306 prog->section_name = strdup(name); 308 prog->section_name = strdup(section_name);
307 if (!prog->section_name) { 309 if (!prog->section_name) {
308 pr_warning("failed to alloc name for prog %s\n", 310 pr_warning("failed to alloc name for prog under section %s\n",
309 name); 311 section_name);
310 goto errout; 312 goto errout;
311 } 313 }
312 314
313 prog->insns = malloc(size); 315 prog->insns = malloc(size);
314 if (!prog->insns) { 316 if (!prog->insns) {
315 pr_warning("failed to alloc insns for %s\n", name); 317 pr_warning("failed to alloc insns for prog under section %s\n",
318 section_name);
316 goto errout; 319 goto errout;
317 } 320 }
318 prog->insns_cnt = size / sizeof(struct bpf_insn); 321 prog->insns_cnt = size / sizeof(struct bpf_insn);
@@ -331,12 +334,12 @@ errout:
331 334
332static int 335static int
333bpf_object__add_program(struct bpf_object *obj, void *data, size_t size, 336bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
334 char *name, int idx) 337 char *section_name, int idx)
335{ 338{
336 struct bpf_program prog, *progs; 339 struct bpf_program prog, *progs;
337 int nr_progs, err; 340 int nr_progs, err;
338 341
339 err = bpf_program__init(data, size, name, idx, &prog); 342 err = bpf_program__init(data, size, section_name, idx, &prog);
340 if (err) 343 if (err)
341 return err; 344 return err;
342 345
@@ -350,8 +353,8 @@ bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
350 * is still valid, so don't need special treat for 353 * is still valid, so don't need special treat for
351 * bpf_close_object(). 354 * bpf_close_object().
352 */ 355 */
353 pr_warning("failed to alloc a new program '%s'\n", 356 pr_warning("failed to alloc a new program under section '%s'\n",
354 name); 357 section_name);
355 bpf_program__exit(&prog); 358 bpf_program__exit(&prog);
356 return -ENOMEM; 359 return -ENOMEM;
357 } 360 }
@@ -364,6 +367,54 @@ bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
364 return 0; 367 return 0;
365} 368}
366 369
370static int
371bpf_object__init_prog_names(struct bpf_object *obj)
372{
373 Elf_Data *symbols = obj->efile.symbols;
374 struct bpf_program *prog;
375 size_t pi, si;
376
377 for (pi = 0; pi < obj->nr_programs; pi++) {
378 char *name = NULL;
379
380 prog = &obj->programs[pi];
381
382 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
383 si++) {
384 GElf_Sym sym;
385
386 if (!gelf_getsym(symbols, si, &sym))
387 continue;
388 if (sym.st_shndx != prog->idx)
389 continue;
390
391 name = elf_strptr(obj->efile.elf,
392 obj->efile.strtabidx,
393 sym.st_name);
394 if (!name) {
395 pr_warning("failed to get sym name string for prog %s\n",
396 prog->section_name);
397 return -LIBBPF_ERRNO__LIBELF;
398 }
399 }
400
401 if (!name) {
402 pr_warning("failed to find sym for prog %s\n",
403 prog->section_name);
404 return -EINVAL;
405 }
406
407 prog->name = strdup(name);
408 if (!prog->name) {
409 pr_warning("failed to allocate memory for prog sym %s\n",
410 name);
411 return -ENOMEM;
412 }
413 }
414
415 return 0;
416}
417
367static struct bpf_object *bpf_object__new(const char *path, 418static struct bpf_object *bpf_object__new(const char *path,
368 void *obj_buf, 419 void *obj_buf,
369 size_t obj_buf_sz) 420 size_t obj_buf_sz)
@@ -528,31 +579,6 @@ bpf_object__init_kversion(struct bpf_object *obj,
528 return 0; 579 return 0;
529} 580}
530 581
531static int
532bpf_object__validate_maps(struct bpf_object *obj)
533{
534 int i;
535
536 /*
537 * If there's only 1 map, the only error case should have been
538 * catched in bpf_object__init_maps().
539 */
540 if (!obj->maps || !obj->nr_maps || (obj->nr_maps == 1))
541 return 0;
542
543 for (i = 1; i < obj->nr_maps; i++) {
544 const struct bpf_map *a = &obj->maps[i - 1];
545 const struct bpf_map *b = &obj->maps[i];
546
547 if (b->offset - a->offset < sizeof(struct bpf_map_def)) {
548 pr_warning("corrupted map section in %s: map \"%s\" too small\n",
549 obj->path, a->name);
550 return -EINVAL;
551 }
552 }
553 return 0;
554}
555
556static int compare_bpf_map(const void *_a, const void *_b) 582static int compare_bpf_map(const void *_a, const void *_b)
557{ 583{
558 const struct bpf_map *a = _a; 584 const struct bpf_map *a = _a;
@@ -564,7 +590,7 @@ static int compare_bpf_map(const void *_a, const void *_b)
564static int 590static int
565bpf_object__init_maps(struct bpf_object *obj) 591bpf_object__init_maps(struct bpf_object *obj)
566{ 592{
567 int i, map_idx, nr_maps = 0; 593 int i, map_idx, map_def_sz, nr_maps = 0;
568 Elf_Scn *scn; 594 Elf_Scn *scn;
569 Elf_Data *data; 595 Elf_Data *data;
570 Elf_Data *symbols = obj->efile.symbols; 596 Elf_Data *symbols = obj->efile.symbols;
@@ -607,6 +633,15 @@ bpf_object__init_maps(struct bpf_object *obj)
607 if (!nr_maps) 633 if (!nr_maps)
608 return 0; 634 return 0;
609 635
636 /* Assume equally sized map definitions */
637 map_def_sz = data->d_size / nr_maps;
638 if (!data->d_size || (data->d_size % nr_maps) != 0) {
639 pr_warning("unable to determine map definition size "
640 "section %s, %d maps in %zd bytes\n",
641 obj->path, nr_maps, data->d_size);
642 return -EINVAL;
643 }
644
610 obj->maps = calloc(nr_maps, sizeof(obj->maps[0])); 645 obj->maps = calloc(nr_maps, sizeof(obj->maps[0]));
611 if (!obj->maps) { 646 if (!obj->maps) {
612 pr_warning("alloc maps for object failed\n"); 647 pr_warning("alloc maps for object failed\n");
@@ -639,7 +674,7 @@ bpf_object__init_maps(struct bpf_object *obj)
639 obj->efile.strtabidx, 674 obj->efile.strtabidx,
640 sym.st_name); 675 sym.st_name);
641 obj->maps[map_idx].offset = sym.st_value; 676 obj->maps[map_idx].offset = sym.st_value;
642 if (sym.st_value + sizeof(struct bpf_map_def) > data->d_size) { 677 if (sym.st_value + map_def_sz > data->d_size) {
643 pr_warning("corrupted maps section in %s: last map \"%s\" too small\n", 678 pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
644 obj->path, map_name); 679 obj->path, map_name);
645 return -EINVAL; 680 return -EINVAL;
@@ -653,12 +688,40 @@ bpf_object__init_maps(struct bpf_object *obj)
653 pr_debug("map %d is \"%s\"\n", map_idx, 688 pr_debug("map %d is \"%s\"\n", map_idx,
654 obj->maps[map_idx].name); 689 obj->maps[map_idx].name);
655 def = (struct bpf_map_def *)(data->d_buf + sym.st_value); 690 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
656 obj->maps[map_idx].def = *def; 691 /*
692 * If the definition of the map in the object file fits in
693 * bpf_map_def, copy it. Any extra fields in our version
694 * of bpf_map_def will default to zero as a result of the
695 * calloc above.
696 */
697 if (map_def_sz <= sizeof(struct bpf_map_def)) {
698 memcpy(&obj->maps[map_idx].def, def, map_def_sz);
699 } else {
700 /*
701 * Here the map structure being read is bigger than what
702 * we expect, truncate if the excess bits are all zero.
703 * If they are not zero, reject this map as
704 * incompatible.
705 */
706 char *b;
707 for (b = ((char *)def) + sizeof(struct bpf_map_def);
708 b < ((char *)def) + map_def_sz; b++) {
709 if (*b != 0) {
710 pr_warning("maps section in %s: \"%s\" "
711 "has unrecognized, non-zero "
712 "options\n",
713 obj->path, map_name);
714 return -EINVAL;
715 }
716 }
717 memcpy(&obj->maps[map_idx].def, def,
718 sizeof(struct bpf_map_def));
719 }
657 map_idx++; 720 map_idx++;
658 } 721 }
659 722
660 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]), compare_bpf_map); 723 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]), compare_bpf_map);
661 return bpf_object__validate_maps(obj); 724 return 0;
662} 725}
663 726
664static int bpf_object__elf_collect(struct bpf_object *obj) 727static int bpf_object__elf_collect(struct bpf_object *obj)
@@ -766,8 +829,12 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
766 pr_warning("Corrupted ELF file: index of strtab invalid\n"); 829 pr_warning("Corrupted ELF file: index of strtab invalid\n");
767 return LIBBPF_ERRNO__FORMAT; 830 return LIBBPF_ERRNO__FORMAT;
768 } 831 }
769 if (obj->efile.maps_shndx >= 0) 832 if (obj->efile.maps_shndx >= 0) {
770 err = bpf_object__init_maps(obj); 833 err = bpf_object__init_maps(obj);
834 if (err)
835 goto out;
836 }
837 err = bpf_object__init_prog_names(obj);
771out: 838out:
772 return err; 839 return err;
773} 840}
@@ -870,11 +937,12 @@ bpf_object__create_maps(struct bpf_object *obj)
870 struct bpf_map_def *def = &obj->maps[i].def; 937 struct bpf_map_def *def = &obj->maps[i].def;
871 int *pfd = &obj->maps[i].fd; 938 int *pfd = &obj->maps[i].fd;
872 939
873 *pfd = bpf_create_map(def->type, 940 *pfd = bpf_create_map_name(def->type,
874 def->key_size, 941 obj->maps[i].name,
875 def->value_size, 942 def->key_size,
876 def->max_entries, 943 def->value_size,
877 0); 944 def->max_entries,
945 def->map_flags);
878 if (*pfd < 0) { 946 if (*pfd < 0) {
879 size_t j; 947 size_t j;
880 int err = *pfd; 948 int err = *pfd;
@@ -982,7 +1050,7 @@ static int bpf_object__collect_reloc(struct bpf_object *obj)
982} 1050}
983 1051
984static int 1052static int
985load_program(enum bpf_prog_type type, struct bpf_insn *insns, 1053load_program(enum bpf_prog_type type, const char *name, struct bpf_insn *insns,
986 int insns_cnt, char *license, u32 kern_version, int *pfd) 1054 int insns_cnt, char *license, u32 kern_version, int *pfd)
987{ 1055{
988 int ret; 1056 int ret;
@@ -995,8 +1063,8 @@ load_program(enum bpf_prog_type type, struct bpf_insn *insns,
995 if (!log_buf) 1063 if (!log_buf)
996 pr_warning("Alloc log buffer for bpf loader error, continue without log\n"); 1064 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
997 1065
998 ret = bpf_load_program(type, insns, insns_cnt, license, 1066 ret = bpf_load_program_name(type, name, insns, insns_cnt, license,
999 kern_version, log_buf, BPF_LOG_BUF_SIZE); 1067 kern_version, log_buf, BPF_LOG_BUF_SIZE);
1000 1068
1001 if (ret >= 0) { 1069 if (ret >= 0) {
1002 *pfd = ret; 1070 *pfd = ret;
@@ -1021,9 +1089,9 @@ load_program(enum bpf_prog_type type, struct bpf_insn *insns,
1021 if (type != BPF_PROG_TYPE_KPROBE) { 1089 if (type != BPF_PROG_TYPE_KPROBE) {
1022 int fd; 1090 int fd;
1023 1091
1024 fd = bpf_load_program(BPF_PROG_TYPE_KPROBE, insns, 1092 fd = bpf_load_program_name(BPF_PROG_TYPE_KPROBE, name,
1025 insns_cnt, license, kern_version, 1093 insns, insns_cnt, license,
1026 NULL, 0); 1094 kern_version, NULL, 0);
1027 if (fd >= 0) { 1095 if (fd >= 0) {
1028 close(fd); 1096 close(fd);
1029 ret = -LIBBPF_ERRNO__PROGTYPE; 1097 ret = -LIBBPF_ERRNO__PROGTYPE;
@@ -1067,8 +1135,8 @@ bpf_program__load(struct bpf_program *prog,
1067 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n", 1135 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
1068 prog->section_name, prog->instances.nr); 1136 prog->section_name, prog->instances.nr);
1069 } 1137 }
1070 err = load_program(prog->type, prog->insns, prog->insns_cnt, 1138 err = load_program(prog->type, prog->name, prog->insns,
1071 license, kern_version, &fd); 1139 prog->insns_cnt, license, kern_version, &fd);
1072 if (!err) 1140 if (!err)
1073 prog->instances.fds[0] = fd; 1141 prog->instances.fds[0] = fd;
1074 goto out; 1142 goto out;
@@ -1096,7 +1164,8 @@ bpf_program__load(struct bpf_program *prog,
1096 continue; 1164 continue;
1097 } 1165 }
1098 1166
1099 err = load_program(prog->type, result.new_insn_ptr, 1167 err = load_program(prog->type, prog->name,
1168 result.new_insn_ptr,
1100 result.new_insn_cnt, 1169 result.new_insn_cnt,
1101 license, kern_version, &fd); 1170 license, kern_version, &fd);
1102 1171
diff --git a/tools/lib/bpf/libbpf.h b/tools/lib/bpf/libbpf.h
index 7959086eb9c9..6e20003109e0 100644
--- a/tools/lib/bpf/libbpf.h
+++ b/tools/lib/bpf/libbpf.h
@@ -207,6 +207,7 @@ struct bpf_map_def {
207 unsigned int key_size; 207 unsigned int key_size;
208 unsigned int value_size; 208 unsigned int value_size;
209 unsigned int max_entries; 209 unsigned int max_entries;
210 unsigned int map_flags;
210}; 211};
211 212
212/* 213/*
diff --git a/tools/testing/selftests/bpf/Makefile b/tools/testing/selftests/bpf/Makefile
index eab7644a07b4..333a48655ee0 100644
--- a/tools/testing/selftests/bpf/Makefile
+++ b/tools/testing/selftests/bpf/Makefile
@@ -13,16 +13,17 @@ CFLAGS += -Wall -O2 -I$(APIDIR) -I$(LIBDIR) -I$(GENDIR) $(GENFLAGS) -I../../../i
13LDLIBS += -lcap -lelf 13LDLIBS += -lcap -lelf
14 14
15TEST_GEN_PROGS = test_verifier test_tag test_maps test_lru_map test_lpm_map test_progs \ 15TEST_GEN_PROGS = test_verifier test_tag test_maps test_lru_map test_lpm_map test_progs \
16 test_align 16 test_align test_verifier_log test_dev_cgroup
17 17
18TEST_GEN_FILES = test_pkt_access.o test_xdp.o test_l4lb.o test_tcp_estats.o test_obj_id.o \ 18TEST_GEN_FILES = test_pkt_access.o test_xdp.o test_l4lb.o test_tcp_estats.o test_obj_id.o \
19 test_pkt_md_access.o test_xdp_redirect.o sockmap_parse_prog.o sockmap_verdict_prog.o 19 test_pkt_md_access.o test_xdp_redirect.o test_xdp_meta.o sockmap_parse_prog.o \
20 sockmap_verdict_prog.o dev_cgroup.o
20 21
21TEST_PROGS := test_kmod.sh test_xdp_redirect.sh 22TEST_PROGS := test_kmod.sh test_xdp_redirect.sh test_xdp_meta.sh
22 23
23include ../lib.mk 24include ../lib.mk
24 25
25BPFOBJ := $(OUTPUT)/libbpf.a 26BPFOBJ := $(OUTPUT)/libbpf.a $(OUTPUT)/cgroup_helpers.c
26 27
27$(TEST_GEN_PROGS): $(BPFOBJ) 28$(TEST_GEN_PROGS): $(BPFOBJ)
28 29
@@ -35,8 +36,20 @@ $(BPFOBJ): force
35 $(MAKE) -C $(BPFDIR) OUTPUT=$(OUTPUT)/ 36 $(MAKE) -C $(BPFDIR) OUTPUT=$(OUTPUT)/
36 37
37CLANG ?= clang 38CLANG ?= clang
39LLC ?= llc
40
41PROBE := $(shell llc -march=bpf -mcpu=probe -filetype=null /dev/null 2>&1)
42
43# Let newer LLVM versions transparently probe the kernel for availability
44# of full BPF instruction set.
45ifeq ($(PROBE),)
46 CPU ?= probe
47else
48 CPU ?= generic
49endif
38 50
39%.o: %.c 51%.o: %.c
40 $(CLANG) -I. -I./include/uapi -I../../../include/uapi \ 52 $(CLANG) -I. -I./include/uapi -I../../../include/uapi \
41 -Wno-compare-distinct-pointer-types \ 53 -Wno-compare-distinct-pointer-types \
42 -O2 -target bpf -c $< -o $@ 54 -O2 -target bpf -emit-llvm -c $< -o - | \
55 $(LLC) -march=bpf -mcpu=$(CPU) -filetype=obj -o $@
diff --git a/tools/testing/selftests/bpf/bpf_helpers.h b/tools/testing/selftests/bpf/bpf_helpers.h
index 50353c10573c..fd9a17fa8a8b 100644
--- a/tools/testing/selftests/bpf/bpf_helpers.h
+++ b/tools/testing/selftests/bpf/bpf_helpers.h
@@ -63,14 +63,25 @@ static unsigned long long (*bpf_get_prandom_u32)(void) =
63 (void *) BPF_FUNC_get_prandom_u32; 63 (void *) BPF_FUNC_get_prandom_u32;
64static int (*bpf_xdp_adjust_head)(void *ctx, int offset) = 64static int (*bpf_xdp_adjust_head)(void *ctx, int offset) =
65 (void *) BPF_FUNC_xdp_adjust_head; 65 (void *) BPF_FUNC_xdp_adjust_head;
66static int (*bpf_xdp_adjust_meta)(void *ctx, int offset) =
67 (void *) BPF_FUNC_xdp_adjust_meta;
66static int (*bpf_setsockopt)(void *ctx, int level, int optname, void *optval, 68static int (*bpf_setsockopt)(void *ctx, int level, int optname, void *optval,
67 int optlen) = 69 int optlen) =
68 (void *) BPF_FUNC_setsockopt; 70 (void *) BPF_FUNC_setsockopt;
71static int (*bpf_getsockopt)(void *ctx, int level, int optname, void *optval,
72 int optlen) =
73 (void *) BPF_FUNC_getsockopt;
69static int (*bpf_sk_redirect_map)(void *ctx, void *map, int key, int flags) = 74static int (*bpf_sk_redirect_map)(void *ctx, void *map, int key, int flags) =
70 (void *) BPF_FUNC_sk_redirect_map; 75 (void *) BPF_FUNC_sk_redirect_map;
71static int (*bpf_sock_map_update)(void *map, void *key, void *value, 76static int (*bpf_sock_map_update)(void *map, void *key, void *value,
72 unsigned long long flags) = 77 unsigned long long flags) =
73 (void *) BPF_FUNC_sock_map_update; 78 (void *) BPF_FUNC_sock_map_update;
79static int (*bpf_perf_event_read_value)(void *map, unsigned long long flags,
80 void *buf, unsigned int buf_size) =
81 (void *) BPF_FUNC_perf_event_read_value;
82static int (*bpf_perf_prog_read_value)(void *ctx, void *buf,
83 unsigned int buf_size) =
84 (void *) BPF_FUNC_perf_prog_read_value;
74 85
75 86
76/* llvm builtin functions that eBPF C program may use to 87/* llvm builtin functions that eBPF C program may use to
@@ -110,7 +121,47 @@ static int (*bpf_skb_under_cgroup)(void *ctx, void *map, int index) =
110static int (*bpf_skb_change_head)(void *, int len, int flags) = 121static int (*bpf_skb_change_head)(void *, int len, int flags) =
111 (void *) BPF_FUNC_skb_change_head; 122 (void *) BPF_FUNC_skb_change_head;
112 123
124/* Scan the ARCH passed in from ARCH env variable (see Makefile) */
125#if defined(__TARGET_ARCH_x86)
126 #define bpf_target_x86
127 #define bpf_target_defined
128#elif defined(__TARGET_ARCH_s930x)
129 #define bpf_target_s930x
130 #define bpf_target_defined
131#elif defined(__TARGET_ARCH_arm64)
132 #define bpf_target_arm64
133 #define bpf_target_defined
134#elif defined(__TARGET_ARCH_mips)
135 #define bpf_target_mips
136 #define bpf_target_defined
137#elif defined(__TARGET_ARCH_powerpc)
138 #define bpf_target_powerpc
139 #define bpf_target_defined
140#elif defined(__TARGET_ARCH_sparc)
141 #define bpf_target_sparc
142 #define bpf_target_defined
143#else
144 #undef bpf_target_defined
145#endif
146
147/* Fall back to what the compiler says */
148#ifndef bpf_target_defined
113#if defined(__x86_64__) 149#if defined(__x86_64__)
150 #define bpf_target_x86
151#elif defined(__s390x__)
152 #define bpf_target_s930x
153#elif defined(__aarch64__)
154 #define bpf_target_arm64
155#elif defined(__mips__)
156 #define bpf_target_mips
157#elif defined(__powerpc__)
158 #define bpf_target_powerpc
159#elif defined(__sparc__)
160 #define bpf_target_sparc
161#endif
162#endif
163
164#if defined(bpf_target_x86)
114 165
115#define PT_REGS_PARM1(x) ((x)->di) 166#define PT_REGS_PARM1(x) ((x)->di)
116#define PT_REGS_PARM2(x) ((x)->si) 167#define PT_REGS_PARM2(x) ((x)->si)
@@ -123,7 +174,7 @@ static int (*bpf_skb_change_head)(void *, int len, int flags) =
123#define PT_REGS_SP(x) ((x)->sp) 174#define PT_REGS_SP(x) ((x)->sp)
124#define PT_REGS_IP(x) ((x)->ip) 175#define PT_REGS_IP(x) ((x)->ip)
125 176
126#elif defined(__s390x__) 177#elif defined(bpf_target_s390x)
127 178
128#define PT_REGS_PARM1(x) ((x)->gprs[2]) 179#define PT_REGS_PARM1(x) ((x)->gprs[2])
129#define PT_REGS_PARM2(x) ((x)->gprs[3]) 180#define PT_REGS_PARM2(x) ((x)->gprs[3])
@@ -136,7 +187,7 @@ static int (*bpf_skb_change_head)(void *, int len, int flags) =
136#define PT_REGS_SP(x) ((x)->gprs[15]) 187#define PT_REGS_SP(x) ((x)->gprs[15])
137#define PT_REGS_IP(x) ((x)->psw.addr) 188#define PT_REGS_IP(x) ((x)->psw.addr)
138 189
139#elif defined(__aarch64__) 190#elif defined(bpf_target_arm64)
140 191
141#define PT_REGS_PARM1(x) ((x)->regs[0]) 192#define PT_REGS_PARM1(x) ((x)->regs[0])
142#define PT_REGS_PARM2(x) ((x)->regs[1]) 193#define PT_REGS_PARM2(x) ((x)->regs[1])
@@ -149,7 +200,7 @@ static int (*bpf_skb_change_head)(void *, int len, int flags) =
149#define PT_REGS_SP(x) ((x)->sp) 200#define PT_REGS_SP(x) ((x)->sp)
150#define PT_REGS_IP(x) ((x)->pc) 201#define PT_REGS_IP(x) ((x)->pc)
151 202
152#elif defined(__mips__) 203#elif defined(bpf_target_mips)
153 204
154#define PT_REGS_PARM1(x) ((x)->regs[4]) 205#define PT_REGS_PARM1(x) ((x)->regs[4])
155#define PT_REGS_PARM2(x) ((x)->regs[5]) 206#define PT_REGS_PARM2(x) ((x)->regs[5])
@@ -162,7 +213,7 @@ static int (*bpf_skb_change_head)(void *, int len, int flags) =
162#define PT_REGS_SP(x) ((x)->regs[29]) 213#define PT_REGS_SP(x) ((x)->regs[29])
163#define PT_REGS_IP(x) ((x)->cp0_epc) 214#define PT_REGS_IP(x) ((x)->cp0_epc)
164 215
165#elif defined(__powerpc__) 216#elif defined(bpf_target_powerpc)
166 217
167#define PT_REGS_PARM1(x) ((x)->gpr[3]) 218#define PT_REGS_PARM1(x) ((x)->gpr[3])
168#define PT_REGS_PARM2(x) ((x)->gpr[4]) 219#define PT_REGS_PARM2(x) ((x)->gpr[4])
@@ -173,7 +224,7 @@ static int (*bpf_skb_change_head)(void *, int len, int flags) =
173#define PT_REGS_SP(x) ((x)->sp) 224#define PT_REGS_SP(x) ((x)->sp)
174#define PT_REGS_IP(x) ((x)->nip) 225#define PT_REGS_IP(x) ((x)->nip)
175 226
176#elif defined(__sparc__) 227#elif defined(bpf_target_sparc)
177 228
178#define PT_REGS_PARM1(x) ((x)->u_regs[UREG_I0]) 229#define PT_REGS_PARM1(x) ((x)->u_regs[UREG_I0])
179#define PT_REGS_PARM2(x) ((x)->u_regs[UREG_I1]) 230#define PT_REGS_PARM2(x) ((x)->u_regs[UREG_I1])
@@ -183,6 +234,8 @@ static int (*bpf_skb_change_head)(void *, int len, int flags) =
183#define PT_REGS_RET(x) ((x)->u_regs[UREG_I7]) 234#define PT_REGS_RET(x) ((x)->u_regs[UREG_I7])
184#define PT_REGS_RC(x) ((x)->u_regs[UREG_I0]) 235#define PT_REGS_RC(x) ((x)->u_regs[UREG_I0])
185#define PT_REGS_SP(x) ((x)->u_regs[UREG_FP]) 236#define PT_REGS_SP(x) ((x)->u_regs[UREG_FP])
237
238/* Should this also be a bpf_target check for the sparc case? */
186#if defined(__arch64__) 239#if defined(__arch64__)
187#define PT_REGS_IP(x) ((x)->tpc) 240#define PT_REGS_IP(x) ((x)->tpc)
188#else 241#else
@@ -191,10 +244,10 @@ static int (*bpf_skb_change_head)(void *, int len, int flags) =
191 244
192#endif 245#endif
193 246
194#ifdef __powerpc__ 247#ifdef bpf_target_powerpc
195#define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ (ip) = (ctx)->link; }) 248#define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ (ip) = (ctx)->link; })
196#define BPF_KRETPROBE_READ_RET_IP BPF_KPROBE_READ_RET_IP 249#define BPF_KRETPROBE_READ_RET_IP BPF_KPROBE_READ_RET_IP
197#elif defined(__sparc__) 250#elif bpf_target_sparc
198#define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ (ip) = PT_REGS_RET(ctx); }) 251#define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ (ip) = PT_REGS_RET(ctx); })
199#define BPF_KRETPROBE_READ_RET_IP BPF_KPROBE_READ_RET_IP 252#define BPF_KRETPROBE_READ_RET_IP BPF_KPROBE_READ_RET_IP
200#else 253#else
diff --git a/tools/testing/selftests/bpf/cgroup_helpers.c b/tools/testing/selftests/bpf/cgroup_helpers.c
new file mode 100644
index 000000000000..f3bca3ade0f3
--- /dev/null
+++ b/tools/testing/selftests/bpf/cgroup_helpers.c
@@ -0,0 +1,178 @@
1// SPDX-License-Identifier: GPL-2.0
2#define _GNU_SOURCE
3#include <sched.h>
4#include <sys/mount.h>
5#include <sys/stat.h>
6#include <sys/types.h>
7#include <linux/limits.h>
8#include <stdio.h>
9#include <linux/sched.h>
10#include <fcntl.h>
11#include <unistd.h>
12#include <ftw.h>
13
14
15#include "cgroup_helpers.h"
16
17/*
18 * To avoid relying on the system setup, when setup_cgroup_env is called
19 * we create a new mount namespace, and cgroup namespace. The cgroup2
20 * root is mounted at CGROUP_MOUNT_PATH
21 *
22 * Unfortunately, most people don't have cgroupv2 enabled at this point in time.
23 * It's easier to create our own mount namespace and manage it ourselves.
24 *
25 * We assume /mnt exists.
26 */
27
28#define WALK_FD_LIMIT 16
29#define CGROUP_MOUNT_PATH "/mnt"
30#define CGROUP_WORK_DIR "/cgroup-test-work-dir"
31#define format_cgroup_path(buf, path) \
32 snprintf(buf, sizeof(buf), "%s%s%s", CGROUP_MOUNT_PATH, \
33 CGROUP_WORK_DIR, path)
34
35/**
36 * setup_cgroup_environment() - Setup the cgroup environment
37 *
38 * After calling this function, cleanup_cgroup_environment should be called
39 * once testing is complete.
40 *
41 * This function will print an error to stderr and return 1 if it is unable
42 * to setup the cgroup environment. If setup is successful, 0 is returned.
43 */
44int setup_cgroup_environment(void)
45{
46 char cgroup_workdir[PATH_MAX + 1];
47
48 format_cgroup_path(cgroup_workdir, "");
49
50 if (unshare(CLONE_NEWNS)) {
51 log_err("unshare");
52 return 1;
53 }
54
55 if (mount("none", "/", NULL, MS_REC | MS_PRIVATE, NULL)) {
56 log_err("mount fakeroot");
57 return 1;
58 }
59
60 if (mount("none", CGROUP_MOUNT_PATH, "cgroup2", 0, NULL) && errno != EBUSY) {
61 log_err("mount cgroup2");
62 return 1;
63 }
64
65 /* Cleanup existing failed runs, now that the environment is setup */
66 cleanup_cgroup_environment();
67
68 if (mkdir(cgroup_workdir, 0777) && errno != EEXIST) {
69 log_err("mkdir cgroup work dir");
70 return 1;
71 }
72
73 return 0;
74}
75
76static int nftwfunc(const char *filename, const struct stat *statptr,
77 int fileflags, struct FTW *pfwt)
78{
79 if ((fileflags & FTW_D) && rmdir(filename))
80 log_err("Removing cgroup: %s", filename);
81 return 0;
82}
83
84
85static int join_cgroup_from_top(char *cgroup_path)
86{
87 char cgroup_procs_path[PATH_MAX + 1];
88 pid_t pid = getpid();
89 int fd, rc = 0;
90
91 snprintf(cgroup_procs_path, sizeof(cgroup_procs_path),
92 "%s/cgroup.procs", cgroup_path);
93
94 fd = open(cgroup_procs_path, O_WRONLY);
95 if (fd < 0) {
96 log_err("Opening Cgroup Procs: %s", cgroup_procs_path);
97 return 1;
98 }
99
100 if (dprintf(fd, "%d\n", pid) < 0) {
101 log_err("Joining Cgroup");
102 rc = 1;
103 }
104
105 close(fd);
106 return rc;
107}
108
109/**
110 * join_cgroup() - Join a cgroup
111 * @path: The cgroup path, relative to the workdir, to join
112 *
113 * This function expects a cgroup to already be created, relative to the cgroup
114 * work dir, and it joins it. For example, passing "/my-cgroup" as the path
115 * would actually put the calling process into the cgroup
116 * "/cgroup-test-work-dir/my-cgroup"
117 *
118 * On success, it returns 0, otherwise on failure it returns 1.
119 */
120int join_cgroup(char *path)
121{
122 char cgroup_path[PATH_MAX + 1];
123
124 format_cgroup_path(cgroup_path, path);
125 return join_cgroup_from_top(cgroup_path);
126}
127
128/**
129 * cleanup_cgroup_environment() - Cleanup Cgroup Testing Environment
130 *
131 * This is an idempotent function to delete all temporary cgroups that
132 * have been created during the test, including the cgroup testing work
133 * directory.
134 *
135 * At call time, it moves the calling process to the root cgroup, and then
136 * runs the deletion process. It is idempotent, and should not fail, unless
137 * a process is lingering.
138 *
139 * On failure, it will print an error to stderr, and try to continue.
140 */
141void cleanup_cgroup_environment(void)
142{
143 char cgroup_workdir[PATH_MAX + 1];
144
145 format_cgroup_path(cgroup_workdir, "");
146 join_cgroup_from_top(CGROUP_MOUNT_PATH);
147 nftw(cgroup_workdir, nftwfunc, WALK_FD_LIMIT, FTW_DEPTH | FTW_MOUNT);
148}
149
150/**
151 * create_and_get_cgroup() - Create a cgroup, relative to workdir, and get the FD
152 * @path: The cgroup path, relative to the workdir, to join
153 *
154 * This function creates a cgroup under the top level workdir and returns the
155 * file descriptor. It is idempotent.
156 *
157 * On success, it returns the file descriptor. On failure it returns 0.
158 * If there is a failure, it prints the error to stderr.
159 */
160int create_and_get_cgroup(char *path)
161{
162 char cgroup_path[PATH_MAX + 1];
163 int fd;
164
165 format_cgroup_path(cgroup_path, path);
166 if (mkdir(cgroup_path, 0777) && errno != EEXIST) {
167 log_err("mkdiring cgroup %s .. %s", path, cgroup_path);
168 return 0;
169 }
170
171 fd = open(cgroup_path, O_RDONLY);
172 if (fd < 0) {
173 log_err("Opening Cgroup");
174 return 0;
175 }
176
177 return fd;
178}
diff --git a/tools/testing/selftests/bpf/cgroup_helpers.h b/tools/testing/selftests/bpf/cgroup_helpers.h
new file mode 100644
index 000000000000..06485e0002b3
--- /dev/null
+++ b/tools/testing/selftests/bpf/cgroup_helpers.h
@@ -0,0 +1,17 @@
1/* SPDX-License-Identifier: GPL-2.0 */
2#ifndef __CGROUP_HELPERS_H
3#define __CGROUP_HELPERS_H
4#include <errno.h>
5#include <string.h>
6
7#define clean_errno() (errno == 0 ? "None" : strerror(errno))
8#define log_err(MSG, ...) fprintf(stderr, "(%s:%d: errno: %s) " MSG "\n", \
9 __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)
10
11
12int create_and_get_cgroup(char *path);
13int join_cgroup(char *path);
14int setup_cgroup_environment(void);
15void cleanup_cgroup_environment(void);
16
17#endif
diff --git a/tools/testing/selftests/bpf/dev_cgroup.c b/tools/testing/selftests/bpf/dev_cgroup.c
new file mode 100644
index 000000000000..ce41a3475f27
--- /dev/null
+++ b/tools/testing/selftests/bpf/dev_cgroup.c
@@ -0,0 +1,60 @@
1/* Copyright (c) 2017 Facebook
2 *
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of version 2 of the GNU General Public
5 * License as published by the Free Software Foundation.
6 */
7
8#include <linux/bpf.h>
9#include <linux/version.h>
10#include "bpf_helpers.h"
11
12SEC("cgroup/dev")
13int bpf_prog1(struct bpf_cgroup_dev_ctx *ctx)
14{
15 short type = ctx->access_type & 0xFFFF;
16#ifdef DEBUG
17 short access = ctx->access_type >> 16;
18 char fmt[] = " %d:%d \n";
19
20 switch (type) {
21 case BPF_DEVCG_DEV_BLOCK:
22 fmt[0] = 'b';
23 break;
24 case BPF_DEVCG_DEV_CHAR:
25 fmt[0] = 'c';
26 break;
27 default:
28 fmt[0] = '?';
29 break;
30 }
31
32 if (access & BPF_DEVCG_ACC_READ)
33 fmt[8] = 'r';
34
35 if (access & BPF_DEVCG_ACC_WRITE)
36 fmt[9] = 'w';
37
38 if (access & BPF_DEVCG_ACC_MKNOD)
39 fmt[10] = 'm';
40
41 bpf_trace_printk(fmt, sizeof(fmt), ctx->major, ctx->minor);
42#endif
43
44 /* Allow access to /dev/zero and /dev/random.
45 * Forbid everything else.
46 */
47 if (ctx->major != 1 || type != BPF_DEVCG_DEV_CHAR)
48 return 0;
49
50 switch (ctx->minor) {
51 case 5: /* 1:5 /dev/zero */
52 case 9: /* 1:9 /dev/urandom */
53 return 1;
54 }
55
56 return 0;
57}
58
59char _license[] SEC("license") = "GPL";
60__u32 _version SEC("version") = LINUX_VERSION_CODE;
diff --git a/tools/testing/selftests/bpf/sockmap_parse_prog.c b/tools/testing/selftests/bpf/sockmap_parse_prog.c
index fae3b96c3aa4..a1dec2b6d9c5 100644
--- a/tools/testing/selftests/bpf/sockmap_parse_prog.c
+++ b/tools/testing/selftests/bpf/sockmap_parse_prog.c
@@ -29,9 +29,6 @@ int bpf_prog1(struct __sk_buff *skb)
29 * fields. 29 * fields.
30 */ 30 */
31 d[7] = 1; 31 d[7] = 1;
32
33 bpf_printk("parse: data[0] = (%u): local_port %i remote %i\n",
34 d[0], lport, bpf_ntohl(rport));
35 return skb->len; 32 return skb->len;
36} 33}
37 34
diff --git a/tools/testing/selftests/bpf/sockmap_verdict_prog.c b/tools/testing/selftests/bpf/sockmap_verdict_prog.c
index 2cd2d552938b..d7bea972cb21 100644
--- a/tools/testing/selftests/bpf/sockmap_verdict_prog.c
+++ b/tools/testing/selftests/bpf/sockmap_verdict_prog.c
@@ -58,8 +58,6 @@ int bpf_prog2(struct __sk_buff *skb)
58 d[6] = 0xe; 58 d[6] = 0xe;
59 d[7] = 0xf; 59 d[7] = 0xf;
60 60
61 bpf_printk("verdict: data[0] = redir(%u:%u)\n", map, sk);
62
63 if (!map) 61 if (!map)
64 return bpf_sk_redirect_map(skb, &sock_map_rx, sk, 0); 62 return bpf_sk_redirect_map(skb, &sock_map_rx, sk, 0);
65 return bpf_sk_redirect_map(skb, &sock_map_tx, sk, 0); 63 return bpf_sk_redirect_map(skb, &sock_map_tx, sk, 0);
diff --git a/tools/testing/selftests/bpf/test_dev_cgroup.c b/tools/testing/selftests/bpf/test_dev_cgroup.c
new file mode 100644
index 000000000000..02c85d6c89b0
--- /dev/null
+++ b/tools/testing/selftests/bpf/test_dev_cgroup.c
@@ -0,0 +1,93 @@
1/* Copyright (c) 2017 Facebook
2 *
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of version 2 of the GNU General Public
5 * License as published by the Free Software Foundation.
6 */
7
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11#include <errno.h>
12#include <assert.h>
13
14#include <linux/bpf.h>
15#include <bpf/bpf.h>
16#include <bpf/libbpf.h>
17
18#include "cgroup_helpers.h"
19
20#define DEV_CGROUP_PROG "./dev_cgroup.o"
21
22#define TEST_CGROUP "test-bpf-based-device-cgroup/"
23
24int main(int argc, char **argv)
25{
26 struct bpf_object *obj;
27 int error = EXIT_FAILURE;
28 int prog_fd, cgroup_fd;
29 __u32 prog_cnt;
30
31 if (bpf_prog_load(DEV_CGROUP_PROG, BPF_PROG_TYPE_CGROUP_DEVICE,
32 &obj, &prog_fd)) {
33 printf("Failed to load DEV_CGROUP program\n");
34 goto err;
35 }
36
37 if (setup_cgroup_environment()) {
38 printf("Failed to load DEV_CGROUP program\n");
39 goto err;
40 }
41
42 /* Create a cgroup, get fd, and join it */
43 cgroup_fd = create_and_get_cgroup(TEST_CGROUP);
44 if (!cgroup_fd) {
45 printf("Failed to create test cgroup\n");
46 goto err;
47 }
48
49 if (join_cgroup(TEST_CGROUP)) {
50 printf("Failed to join cgroup\n");
51 goto err;
52 }
53
54 /* Attach bpf program */
55 if (bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE, 0)) {
56 printf("Failed to attach DEV_CGROUP program");
57 goto err;
58 }
59
60 if (bpf_prog_query(cgroup_fd, BPF_CGROUP_DEVICE, 0, NULL, NULL,
61 &prog_cnt)) {
62 printf("Failed to query attached programs");
63 goto err;
64 }
65
66 /* All operations with /dev/zero and and /dev/urandom are allowed,
67 * everything else is forbidden.
68 */
69 assert(system("rm -f /tmp/test_dev_cgroup_null") == 0);
70 assert(system("mknod /tmp/test_dev_cgroup_null c 1 3"));
71 assert(system("rm -f /tmp/test_dev_cgroup_null") == 0);
72
73 /* /dev/zero is whitelisted */
74 assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0);
75 assert(system("mknod /tmp/test_dev_cgroup_zero c 1 5") == 0);
76 assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0);
77
78 assert(system("dd if=/dev/urandom of=/dev/zero count=64") == 0);
79
80 /* src is allowed, target is forbidden */
81 assert(system("dd if=/dev/urandom of=/dev/full count=64"));
82
83 /* src is forbidden, target is allowed */
84 assert(system("dd if=/dev/random of=/dev/zero count=64"));
85
86 error = 0;
87 printf("test_dev_cgroup:PASS\n");
88
89err:
90 cleanup_cgroup_environment();
91
92 return error;
93}
diff --git a/tools/testing/selftests/bpf/test_lpm_map.c b/tools/testing/selftests/bpf/test_lpm_map.c
index f93a333cbf2c..f61480641b6e 100644
--- a/tools/testing/selftests/bpf/test_lpm_map.c
+++ b/tools/testing/selftests/bpf/test_lpm_map.c
@@ -32,6 +32,10 @@ struct tlpm_node {
32 uint8_t key[]; 32 uint8_t key[];
33}; 33};
34 34
35static struct tlpm_node *tlpm_match(struct tlpm_node *list,
36 const uint8_t *key,
37 size_t n_bits);
38
35static struct tlpm_node *tlpm_add(struct tlpm_node *list, 39static struct tlpm_node *tlpm_add(struct tlpm_node *list,
36 const uint8_t *key, 40 const uint8_t *key,
37 size_t n_bits) 41 size_t n_bits)
@@ -39,9 +43,17 @@ static struct tlpm_node *tlpm_add(struct tlpm_node *list,
39 struct tlpm_node *node; 43 struct tlpm_node *node;
40 size_t n; 44 size_t n;
41 45
46 n = (n_bits + 7) / 8;
47
48 /* 'overwrite' an equivalent entry if one already exists */
49 node = tlpm_match(list, key, n_bits);
50 if (node && node->n_bits == n_bits) {
51 memcpy(node->key, key, n);
52 return list;
53 }
54
42 /* add new entry with @key/@n_bits to @list and return new head */ 55 /* add new entry with @key/@n_bits to @list and return new head */
43 56
44 n = (n_bits + 7) / 8;
45 node = malloc(sizeof(*node) + n); 57 node = malloc(sizeof(*node) + n);
46 assert(node); 58 assert(node);
47 59
@@ -93,6 +105,34 @@ static struct tlpm_node *tlpm_match(struct tlpm_node *list,
93 return best; 105 return best;
94} 106}
95 107
108static struct tlpm_node *tlpm_delete(struct tlpm_node *list,
109 const uint8_t *key,
110 size_t n_bits)
111{
112 struct tlpm_node *best = tlpm_match(list, key, n_bits);
113 struct tlpm_node *node;
114
115 if (!best || best->n_bits != n_bits)
116 return list;
117
118 if (best == list) {
119 node = best->next;
120 free(best);
121 return node;
122 }
123
124 for (node = list; node; node = node->next) {
125 if (node->next == best) {
126 node->next = best->next;
127 free(best);
128 return list;
129 }
130 }
131 /* should never get here */
132 assert(0);
133 return list;
134}
135
96static void test_lpm_basic(void) 136static void test_lpm_basic(void)
97{ 137{
98 struct tlpm_node *list = NULL, *t1, *t2; 138 struct tlpm_node *list = NULL, *t1, *t2;
@@ -115,6 +155,13 @@ static void test_lpm_basic(void)
115 assert(t1 == tlpm_match(list, (uint8_t[]){ 0xff, 0xff }, 15)); 155 assert(t1 == tlpm_match(list, (uint8_t[]){ 0xff, 0xff }, 15));
116 assert(!tlpm_match(list, (uint8_t[]){ 0x7f, 0xff }, 16)); 156 assert(!tlpm_match(list, (uint8_t[]){ 0x7f, 0xff }, 16));
117 157
158 list = tlpm_delete(list, (uint8_t[]){ 0xff, 0xff }, 16);
159 assert(t1 == tlpm_match(list, (uint8_t[]){ 0xff }, 8));
160 assert(t1 == tlpm_match(list, (uint8_t[]){ 0xff, 0xff }, 16));
161
162 list = tlpm_delete(list, (uint8_t[]){ 0xff }, 8);
163 assert(!tlpm_match(list, (uint8_t[]){ 0xff }, 8));
164
118 tlpm_clear(list); 165 tlpm_clear(list);
119} 166}
120 167
@@ -159,7 +206,7 @@ static void test_lpm_order(void)
159 206
160static void test_lpm_map(int keysize) 207static void test_lpm_map(int keysize)
161{ 208{
162 size_t i, j, n_matches, n_nodes, n_lookups; 209 size_t i, j, n_matches, n_matches_after_delete, n_nodes, n_lookups;
163 struct tlpm_node *t, *list = NULL; 210 struct tlpm_node *t, *list = NULL;
164 struct bpf_lpm_trie_key *key; 211 struct bpf_lpm_trie_key *key;
165 uint8_t *data, *value; 212 uint8_t *data, *value;
@@ -171,6 +218,7 @@ static void test_lpm_map(int keysize)
171 */ 218 */
172 219
173 n_matches = 0; 220 n_matches = 0;
221 n_matches_after_delete = 0;
174 n_nodes = 1 << 8; 222 n_nodes = 1 << 8;
175 n_lookups = 1 << 16; 223 n_lookups = 1 << 16;
176 224
@@ -224,15 +272,54 @@ static void test_lpm_map(int keysize)
224 } 272 }
225 } 273 }
226 274
275 /* Remove the first half of the elements in the tlpm and the
276 * corresponding nodes from the bpf-lpm. Then run the same
277 * large number of random lookups in both and make sure they match.
278 * Note: we need to count the number of nodes actually inserted
279 * since there may have been duplicates.
280 */
281 for (i = 0, t = list; t; i++, t = t->next)
282 ;
283 for (j = 0; j < i / 2; ++j) {
284 key->prefixlen = list->n_bits;
285 memcpy(key->data, list->key, keysize);
286 r = bpf_map_delete_elem(map, key);
287 assert(!r);
288 list = tlpm_delete(list, list->key, list->n_bits);
289 assert(list);
290 }
291 for (i = 0; i < n_lookups; ++i) {
292 for (j = 0; j < keysize; ++j)
293 data[j] = rand() & 0xff;
294
295 t = tlpm_match(list, data, 8 * keysize);
296
297 key->prefixlen = 8 * keysize;
298 memcpy(key->data, data, keysize);
299 r = bpf_map_lookup_elem(map, key, value);
300 assert(!r || errno == ENOENT);
301 assert(!t == !!r);
302
303 if (t) {
304 ++n_matches_after_delete;
305 assert(t->n_bits == value[keysize]);
306 for (j = 0; j < t->n_bits; ++j)
307 assert((t->key[j / 8] & (1 << (7 - j % 8))) ==
308 (value[j / 8] & (1 << (7 - j % 8))));
309 }
310 }
311
227 close(map); 312 close(map);
228 tlpm_clear(list); 313 tlpm_clear(list);
229 314
230 /* With 255 random nodes in the map, we are pretty likely to match 315 /* With 255 random nodes in the map, we are pretty likely to match
231 * something on every lookup. For statistics, use this: 316 * something on every lookup. For statistics, use this:
232 * 317 *
233 * printf(" nodes: %zu\n" 318 * printf(" nodes: %zu\n"
234 * "lookups: %zu\n" 319 * " lookups: %zu\n"
235 * "matches: %zu\n", n_nodes, n_lookups, n_matches); 320 * " matches: %zu\n"
321 * "matches(delete): %zu\n",
322 * n_nodes, n_lookups, n_matches, n_matches_after_delete);
236 */ 323 */
237} 324}
238 325
@@ -332,6 +419,108 @@ static void test_lpm_ipaddr(void)
332 close(map_fd_ipv6); 419 close(map_fd_ipv6);
333} 420}
334 421
422static void test_lpm_delete(void)
423{
424 struct bpf_lpm_trie_key *key;
425 size_t key_size;
426 int map_fd;
427 __u64 value;
428
429 key_size = sizeof(*key) + sizeof(__u32);
430 key = alloca(key_size);
431
432 map_fd = bpf_create_map(BPF_MAP_TYPE_LPM_TRIE,
433 key_size, sizeof(value),
434 100, BPF_F_NO_PREALLOC);
435 assert(map_fd >= 0);
436
437 /* Add nodes:
438 * 192.168.0.0/16 (1)
439 * 192.168.0.0/24 (2)
440 * 192.168.128.0/24 (3)
441 * 192.168.1.0/24 (4)
442 *
443 * (1)
444 * / \
445 * (IM) (3)
446 * / \
447 * (2) (4)
448 */
449 value = 1;
450 key->prefixlen = 16;
451 inet_pton(AF_INET, "192.168.0.0", key->data);
452 assert(bpf_map_update_elem(map_fd, key, &value, 0) == 0);
453
454 value = 2;
455 key->prefixlen = 24;
456 inet_pton(AF_INET, "192.168.0.0", key->data);
457 assert(bpf_map_update_elem(map_fd, key, &value, 0) == 0);
458
459 value = 3;
460 key->prefixlen = 24;
461 inet_pton(AF_INET, "192.168.128.0", key->data);
462 assert(bpf_map_update_elem(map_fd, key, &value, 0) == 0);
463
464 value = 4;
465 key->prefixlen = 24;
466 inet_pton(AF_INET, "192.168.1.0", key->data);
467 assert(bpf_map_update_elem(map_fd, key, &value, 0) == 0);
468
469 /* remove non-existent node */
470 key->prefixlen = 32;
471 inet_pton(AF_INET, "10.0.0.1", key->data);
472 assert(bpf_map_lookup_elem(map_fd, key, &value) == -1 &&
473 errno == ENOENT);
474
475 /* assert initial lookup */
476 key->prefixlen = 32;
477 inet_pton(AF_INET, "192.168.0.1", key->data);
478 assert(bpf_map_lookup_elem(map_fd, key, &value) == 0);
479 assert(value == 2);
480
481 /* remove leaf node */
482 key->prefixlen = 24;
483 inet_pton(AF_INET, "192.168.0.0", key->data);
484 assert(bpf_map_delete_elem(map_fd, key) == 0);
485
486 key->prefixlen = 32;
487 inet_pton(AF_INET, "192.168.0.1", key->data);
488 assert(bpf_map_lookup_elem(map_fd, key, &value) == 0);
489 assert(value == 1);
490
491 /* remove leaf (and intermediary) node */
492 key->prefixlen = 24;
493 inet_pton(AF_INET, "192.168.1.0", key->data);
494 assert(bpf_map_delete_elem(map_fd, key) == 0);
495
496 key->prefixlen = 32;
497 inet_pton(AF_INET, "192.168.1.1", key->data);
498 assert(bpf_map_lookup_elem(map_fd, key, &value) == 0);
499 assert(value == 1);
500
501 /* remove root node */
502 key->prefixlen = 16;
503 inet_pton(AF_INET, "192.168.0.0", key->data);
504 assert(bpf_map_delete_elem(map_fd, key) == 0);
505
506 key->prefixlen = 32;
507 inet_pton(AF_INET, "192.168.128.1", key->data);
508 assert(bpf_map_lookup_elem(map_fd, key, &value) == 0);
509 assert(value == 3);
510
511 /* remove last node */
512 key->prefixlen = 24;
513 inet_pton(AF_INET, "192.168.128.0", key->data);
514 assert(bpf_map_delete_elem(map_fd, key) == 0);
515
516 key->prefixlen = 32;
517 inet_pton(AF_INET, "192.168.128.1", key->data);
518 assert(bpf_map_lookup_elem(map_fd, key, &value) == -1 &&
519 errno == ENOENT);
520
521 close(map_fd);
522}
523
335int main(void) 524int main(void)
336{ 525{
337 struct rlimit limit = { RLIM_INFINITY, RLIM_INFINITY }; 526 struct rlimit limit = { RLIM_INFINITY, RLIM_INFINITY };
@@ -354,6 +543,8 @@ int main(void)
354 543
355 test_lpm_ipaddr(); 544 test_lpm_ipaddr();
356 545
546 test_lpm_delete();
547
357 printf("test_lpm: OK\n"); 548 printf("test_lpm: OK\n");
358 return 0; 549 return 0;
359} 550}
diff --git a/tools/testing/selftests/bpf/test_maps.c b/tools/testing/selftests/bpf/test_maps.c
index 50ce52d2013d..040356ecc862 100644
--- a/tools/testing/selftests/bpf/test_maps.c
+++ b/tools/testing/selftests/bpf/test_maps.c
@@ -1043,6 +1043,51 @@ static void test_map_parallel(void)
1043 assert(bpf_map_get_next_key(fd, &key, &key) == -1 && errno == ENOENT); 1043 assert(bpf_map_get_next_key(fd, &key, &key) == -1 && errno == ENOENT);
1044} 1044}
1045 1045
1046static void test_map_rdonly(void)
1047{
1048 int fd, key = 0, value = 0;
1049
1050 fd = bpf_create_map(BPF_MAP_TYPE_HASH, sizeof(key), sizeof(value),
1051 MAP_SIZE, map_flags | BPF_F_RDONLY);
1052 if (fd < 0) {
1053 printf("Failed to create map for read only test '%s'!\n",
1054 strerror(errno));
1055 exit(1);
1056 }
1057
1058 key = 1;
1059 value = 1234;
1060 /* Insert key=1 element. */
1061 assert(bpf_map_update_elem(fd, &key, &value, BPF_ANY) == -1 &&
1062 errno == EPERM);
1063
1064 /* Check that key=2 is not found. */
1065 assert(bpf_map_lookup_elem(fd, &key, &value) == -1 && errno == ENOENT);
1066 assert(bpf_map_get_next_key(fd, &key, &value) == -1 && errno == ENOENT);
1067}
1068
1069static void test_map_wronly(void)
1070{
1071 int fd, key = 0, value = 0;
1072
1073 fd = bpf_create_map(BPF_MAP_TYPE_HASH, sizeof(key), sizeof(value),
1074 MAP_SIZE, map_flags | BPF_F_WRONLY);
1075 if (fd < 0) {
1076 printf("Failed to create map for read only test '%s'!\n",
1077 strerror(errno));
1078 exit(1);
1079 }
1080
1081 key = 1;
1082 value = 1234;
1083 /* Insert key=1 element. */
1084 assert(bpf_map_update_elem(fd, &key, &value, BPF_ANY) == 0);
1085
1086 /* Check that key=2 is not found. */
1087 assert(bpf_map_lookup_elem(fd, &key, &value) == -1 && errno == EPERM);
1088 assert(bpf_map_get_next_key(fd, &key, &value) == -1 && errno == EPERM);
1089}
1090
1046static void run_all_tests(void) 1091static void run_all_tests(void)
1047{ 1092{
1048 test_hashmap(0, NULL); 1093 test_hashmap(0, NULL);
@@ -1060,6 +1105,9 @@ static void run_all_tests(void)
1060 test_map_large(); 1105 test_map_large();
1061 test_map_parallel(); 1106 test_map_parallel();
1062 test_map_stress(); 1107 test_map_stress();
1108
1109 test_map_rdonly();
1110 test_map_wronly();
1063} 1111}
1064 1112
1065int main(void) 1113int main(void)
diff --git a/tools/testing/selftests/bpf/test_progs.c b/tools/testing/selftests/bpf/test_progs.c
index 11ee25cea227..69427531408d 100644
--- a/tools/testing/selftests/bpf/test_progs.c
+++ b/tools/testing/selftests/bpf/test_progs.c
@@ -10,6 +10,7 @@
10#include <string.h> 10#include <string.h>
11#include <assert.h> 11#include <assert.h>
12#include <stdlib.h> 12#include <stdlib.h>
13#include <time.h>
13 14
14#include <linux/types.h> 15#include <linux/types.h>
15typedef __u16 __sum16; 16typedef __u16 __sum16;
@@ -19,6 +20,8 @@ typedef __u16 __sum16;
19#include <linux/ip.h> 20#include <linux/ip.h>
20#include <linux/ipv6.h> 21#include <linux/ipv6.h>
21#include <linux/tcp.h> 22#include <linux/tcp.h>
23#include <linux/filter.h>
24#include <linux/unistd.h>
22 25
23#include <sys/wait.h> 26#include <sys/wait.h>
24#include <sys/resource.h> 27#include <sys/resource.h>
@@ -273,16 +276,26 @@ static void test_bpf_obj_id(void)
273 const int nr_iters = 2; 276 const int nr_iters = 2;
274 const char *file = "./test_obj_id.o"; 277 const char *file = "./test_obj_id.o";
275 const char *jit_sysctl = "/proc/sys/net/core/bpf_jit_enable"; 278 const char *jit_sysctl = "/proc/sys/net/core/bpf_jit_enable";
279 const char *expected_prog_name = "test_obj_id";
280 const char *expected_map_name = "test_map_id";
281 const __u64 nsec_per_sec = 1000000000;
276 282
277 struct bpf_object *objs[nr_iters]; 283 struct bpf_object *objs[nr_iters];
278 int prog_fds[nr_iters], map_fds[nr_iters]; 284 int prog_fds[nr_iters], map_fds[nr_iters];
279 /* +1 to test for the info_len returned by kernel */ 285 /* +1 to test for the info_len returned by kernel */
280 struct bpf_prog_info prog_infos[nr_iters + 1]; 286 struct bpf_prog_info prog_infos[nr_iters + 1];
281 struct bpf_map_info map_infos[nr_iters + 1]; 287 struct bpf_map_info map_infos[nr_iters + 1];
288 /* Each prog only uses one map. +1 to test nr_map_ids
289 * returned by kernel.
290 */
291 __u32 map_ids[nr_iters + 1];
282 char jited_insns[128], xlated_insns[128], zeros[128]; 292 char jited_insns[128], xlated_insns[128], zeros[128];
283 __u32 i, next_id, info_len, nr_id_found, duration = 0; 293 __u32 i, next_id, info_len, nr_id_found, duration = 0;
294 struct timespec real_time_ts, boot_time_ts;
284 int sysctl_fd, jit_enabled = 0, err = 0; 295 int sysctl_fd, jit_enabled = 0, err = 0;
285 __u64 array_value; 296 __u64 array_value;
297 uid_t my_uid = getuid();
298 time_t now, load_time;
286 299
287 sysctl_fd = open(jit_sysctl, 0, O_RDONLY); 300 sysctl_fd = open(jit_sysctl, 0, O_RDONLY);
288 if (sysctl_fd != -1) { 301 if (sysctl_fd != -1) {
@@ -307,6 +320,7 @@ static void test_bpf_obj_id(void)
307 /* Check bpf_obj_get_info_by_fd() */ 320 /* Check bpf_obj_get_info_by_fd() */
308 bzero(zeros, sizeof(zeros)); 321 bzero(zeros, sizeof(zeros));
309 for (i = 0; i < nr_iters; i++) { 322 for (i = 0; i < nr_iters; i++) {
323 now = time(NULL);
310 err = bpf_prog_load(file, BPF_PROG_TYPE_SOCKET_FILTER, 324 err = bpf_prog_load(file, BPF_PROG_TYPE_SOCKET_FILTER,
311 &objs[i], &prog_fds[i]); 325 &objs[i], &prog_fds[i]);
312 /* test_obj_id.o is a dumb prog. It should never fail 326 /* test_obj_id.o is a dumb prog. It should never fail
@@ -316,6 +330,38 @@ static void test_bpf_obj_id(void)
316 error_cnt++; 330 error_cnt++;
317 assert(!err); 331 assert(!err);
318 332
333 /* Insert a magic value to the map */
334 map_fds[i] = bpf_find_map(__func__, objs[i], "test_map_id");
335 assert(map_fds[i] >= 0);
336 err = bpf_map_update_elem(map_fds[i], &array_key,
337 &array_magic_value, 0);
338 assert(!err);
339
340 /* Check getting map info */
341 info_len = sizeof(struct bpf_map_info) * 2;
342 bzero(&map_infos[i], info_len);
343 err = bpf_obj_get_info_by_fd(map_fds[i], &map_infos[i],
344 &info_len);
345 if (CHECK(err ||
346 map_infos[i].type != BPF_MAP_TYPE_ARRAY ||
347 map_infos[i].key_size != sizeof(__u32) ||
348 map_infos[i].value_size != sizeof(__u64) ||
349 map_infos[i].max_entries != 1 ||
350 map_infos[i].map_flags != 0 ||
351 info_len != sizeof(struct bpf_map_info) ||
352 strcmp((char *)map_infos[i].name, expected_map_name),
353 "get-map-info(fd)",
354 "err %d errno %d type %d(%d) info_len %u(%lu) key_size %u value_size %u max_entries %u map_flags %X name %s(%s)\n",
355 err, errno,
356 map_infos[i].type, BPF_MAP_TYPE_ARRAY,
357 info_len, sizeof(struct bpf_map_info),
358 map_infos[i].key_size,
359 map_infos[i].value_size,
360 map_infos[i].max_entries,
361 map_infos[i].map_flags,
362 map_infos[i].name, expected_map_name))
363 goto done;
364
319 /* Check getting prog info */ 365 /* Check getting prog info */
320 info_len = sizeof(struct bpf_prog_info) * 2; 366 info_len = sizeof(struct bpf_prog_info) * 2;
321 bzero(&prog_infos[i], info_len); 367 bzero(&prog_infos[i], info_len);
@@ -325,8 +371,16 @@ static void test_bpf_obj_id(void)
325 prog_infos[i].jited_prog_len = sizeof(jited_insns); 371 prog_infos[i].jited_prog_len = sizeof(jited_insns);
326 prog_infos[i].xlated_prog_insns = ptr_to_u64(xlated_insns); 372 prog_infos[i].xlated_prog_insns = ptr_to_u64(xlated_insns);
327 prog_infos[i].xlated_prog_len = sizeof(xlated_insns); 373 prog_infos[i].xlated_prog_len = sizeof(xlated_insns);
374 prog_infos[i].map_ids = ptr_to_u64(map_ids + i);
375 prog_infos[i].nr_map_ids = 2;
376 err = clock_gettime(CLOCK_REALTIME, &real_time_ts);
377 assert(!err);
378 err = clock_gettime(CLOCK_BOOTTIME, &boot_time_ts);
379 assert(!err);
328 err = bpf_obj_get_info_by_fd(prog_fds[i], &prog_infos[i], 380 err = bpf_obj_get_info_by_fd(prog_fds[i], &prog_infos[i],
329 &info_len); 381 &info_len);
382 load_time = (real_time_ts.tv_sec - boot_time_ts.tv_sec)
383 + (prog_infos[i].load_time / nsec_per_sec);
330 if (CHECK(err || 384 if (CHECK(err ||
331 prog_infos[i].type != BPF_PROG_TYPE_SOCKET_FILTER || 385 prog_infos[i].type != BPF_PROG_TYPE_SOCKET_FILTER ||
332 info_len != sizeof(struct bpf_prog_info) || 386 info_len != sizeof(struct bpf_prog_info) ||
@@ -334,9 +388,14 @@ static void test_bpf_obj_id(void)
334 (jit_enabled && 388 (jit_enabled &&
335 !memcmp(jited_insns, zeros, sizeof(zeros))) || 389 !memcmp(jited_insns, zeros, sizeof(zeros))) ||
336 !prog_infos[i].xlated_prog_len || 390 !prog_infos[i].xlated_prog_len ||
337 !memcmp(xlated_insns, zeros, sizeof(zeros)), 391 !memcmp(xlated_insns, zeros, sizeof(zeros)) ||
392 load_time < now - 60 || load_time > now + 60 ||
393 prog_infos[i].created_by_uid != my_uid ||
394 prog_infos[i].nr_map_ids != 1 ||
395 *(int *)prog_infos[i].map_ids != map_infos[i].id ||
396 strcmp((char *)prog_infos[i].name, expected_prog_name),
338 "get-prog-info(fd)", 397 "get-prog-info(fd)",
339 "err %d errno %d i %d type %d(%d) info_len %u(%lu) jit_enabled %d jited_prog_len %u xlated_prog_len %u jited_prog %d xlated_prog %d\n", 398 "err %d errno %d i %d type %d(%d) info_len %u(%lu) jit_enabled %d jited_prog_len %u xlated_prog_len %u jited_prog %d xlated_prog %d load_time %lu(%lu) uid %u(%u) nr_map_ids %u(%u) map_id %u(%u) name %s(%s)\n",
340 err, errno, i, 399 err, errno, i,
341 prog_infos[i].type, BPF_PROG_TYPE_SOCKET_FILTER, 400 prog_infos[i].type, BPF_PROG_TYPE_SOCKET_FILTER,
342 info_len, sizeof(struct bpf_prog_info), 401 info_len, sizeof(struct bpf_prog_info),
@@ -344,36 +403,12 @@ static void test_bpf_obj_id(void)
344 prog_infos[i].jited_prog_len, 403 prog_infos[i].jited_prog_len,
345 prog_infos[i].xlated_prog_len, 404 prog_infos[i].xlated_prog_len,
346 !!memcmp(jited_insns, zeros, sizeof(zeros)), 405 !!memcmp(jited_insns, zeros, sizeof(zeros)),
347 !!memcmp(xlated_insns, zeros, sizeof(zeros)))) 406 !!memcmp(xlated_insns, zeros, sizeof(zeros)),
348 goto done; 407 load_time, now,
349 408 prog_infos[i].created_by_uid, my_uid,
350 map_fds[i] = bpf_find_map(__func__, objs[i], "test_map_id"); 409 prog_infos[i].nr_map_ids, 1,
351 assert(map_fds[i] >= 0); 410 *(int *)prog_infos[i].map_ids, map_infos[i].id,
352 err = bpf_map_update_elem(map_fds[i], &array_key, 411 prog_infos[i].name, expected_prog_name))
353 &array_magic_value, 0);
354 assert(!err);
355
356 /* Check getting map info */
357 info_len = sizeof(struct bpf_map_info) * 2;
358 bzero(&map_infos[i], info_len);
359 err = bpf_obj_get_info_by_fd(map_fds[i], &map_infos[i],
360 &info_len);
361 if (CHECK(err ||
362 map_infos[i].type != BPF_MAP_TYPE_ARRAY ||
363 map_infos[i].key_size != sizeof(__u32) ||
364 map_infos[i].value_size != sizeof(__u64) ||
365 map_infos[i].max_entries != 1 ||
366 map_infos[i].map_flags != 0 ||
367 info_len != sizeof(struct bpf_map_info),
368 "get-map-info(fd)",
369 "err %d errno %d type %d(%d) info_len %u(%lu) key_size %u value_size %u max_entries %u map_flags %X\n",
370 err, errno,
371 map_infos[i].type, BPF_MAP_TYPE_ARRAY,
372 info_len, sizeof(struct bpf_map_info),
373 map_infos[i].key_size,
374 map_infos[i].value_size,
375 map_infos[i].max_entries,
376 map_infos[i].map_flags))
377 goto done; 412 goto done;
378 } 413 }
379 414
@@ -382,6 +417,7 @@ static void test_bpf_obj_id(void)
382 next_id = 0; 417 next_id = 0;
383 while (!bpf_prog_get_next_id(next_id, &next_id)) { 418 while (!bpf_prog_get_next_id(next_id, &next_id)) {
384 struct bpf_prog_info prog_info = {}; 419 struct bpf_prog_info prog_info = {};
420 __u32 saved_map_id;
385 int prog_fd; 421 int prog_fd;
386 422
387 info_len = sizeof(prog_info); 423 info_len = sizeof(prog_info);
@@ -404,16 +440,33 @@ static void test_bpf_obj_id(void)
404 440
405 nr_id_found++; 441 nr_id_found++;
406 442
443 /* Negative test:
444 * prog_info.nr_map_ids = 1
445 * prog_info.map_ids = NULL
446 */
447 prog_info.nr_map_ids = 1;
448 err = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &info_len);
449 if (CHECK(!err || errno != EFAULT,
450 "get-prog-fd-bad-nr-map-ids", "err %d errno %d(%d)",
451 err, errno, EFAULT))
452 break;
453 bzero(&prog_info, sizeof(prog_info));
454 info_len = sizeof(prog_info);
455
456 saved_map_id = *(int *)(prog_infos[i].map_ids);
457 prog_info.map_ids = prog_infos[i].map_ids;
458 prog_info.nr_map_ids = 2;
407 err = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &info_len); 459 err = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &info_len);
408 prog_infos[i].jited_prog_insns = 0; 460 prog_infos[i].jited_prog_insns = 0;
409 prog_infos[i].xlated_prog_insns = 0; 461 prog_infos[i].xlated_prog_insns = 0;
410 CHECK(err || info_len != sizeof(struct bpf_prog_info) || 462 CHECK(err || info_len != sizeof(struct bpf_prog_info) ||
411 memcmp(&prog_info, &prog_infos[i], info_len), 463 memcmp(&prog_info, &prog_infos[i], info_len) ||
464 *(int *)prog_info.map_ids != saved_map_id,
412 "get-prog-info(next_id->fd)", 465 "get-prog-info(next_id->fd)",
413 "err %d errno %d info_len %u(%lu) memcmp %d\n", 466 "err %d errno %d info_len %u(%lu) memcmp %d map_id %u(%u)\n",
414 err, errno, info_len, sizeof(struct bpf_prog_info), 467 err, errno, info_len, sizeof(struct bpf_prog_info),
415 memcmp(&prog_info, &prog_infos[i], info_len)); 468 memcmp(&prog_info, &prog_infos[i], info_len),
416 469 *(int *)prog_info.map_ids, saved_map_id);
417 close(prog_fd); 470 close(prog_fd);
418 } 471 }
419 CHECK(nr_id_found != nr_iters, 472 CHECK(nr_id_found != nr_iters,
@@ -495,6 +548,75 @@ static void test_pkt_md_access(void)
495 bpf_object__close(obj); 548 bpf_object__close(obj);
496} 549}
497 550
551static void test_obj_name(void)
552{
553 struct {
554 const char *name;
555 int success;
556 int expected_errno;
557 } tests[] = {
558 { "", 1, 0 },
559 { "_123456789ABCDE", 1, 0 },
560 { "_123456789ABCDEF", 0, EINVAL },
561 { "_123456789ABCD\n", 0, EINVAL },
562 };
563 struct bpf_insn prog[] = {
564 BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 0),
565 BPF_EXIT_INSN(),
566 };
567 __u32 duration = 0;
568 int i;
569
570 for (i = 0; i < sizeof(tests) / sizeof(tests[0]); i++) {
571 size_t name_len = strlen(tests[i].name) + 1;
572 union bpf_attr attr;
573 size_t ncopy;
574 int fd;
575
576 /* test different attr.prog_name during BPF_PROG_LOAD */
577 ncopy = name_len < sizeof(attr.prog_name) ?
578 name_len : sizeof(attr.prog_name);
579 bzero(&attr, sizeof(attr));
580 attr.prog_type = BPF_PROG_TYPE_SCHED_CLS;
581 attr.insn_cnt = 2;
582 attr.insns = ptr_to_u64(prog);
583 attr.license = ptr_to_u64("");
584 memcpy(attr.prog_name, tests[i].name, ncopy);
585
586 fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));
587 CHECK((tests[i].success && fd < 0) ||
588 (!tests[i].success && fd != -1) ||
589 (!tests[i].success && errno != tests[i].expected_errno),
590 "check-bpf-prog-name",
591 "fd %d(%d) errno %d(%d)\n",
592 fd, tests[i].success, errno, tests[i].expected_errno);
593
594 if (fd != -1)
595 close(fd);
596
597 /* test different attr.map_name during BPF_MAP_CREATE */
598 ncopy = name_len < sizeof(attr.map_name) ?
599 name_len : sizeof(attr.map_name);
600 bzero(&attr, sizeof(attr));
601 attr.map_type = BPF_MAP_TYPE_ARRAY;
602 attr.key_size = 4;
603 attr.value_size = 4;
604 attr.max_entries = 1;
605 attr.map_flags = 0;
606 memcpy(attr.map_name, tests[i].name, ncopy);
607 fd = syscall(__NR_bpf, BPF_MAP_CREATE, &attr, sizeof(attr));
608 CHECK((tests[i].success && fd < 0) ||
609 (!tests[i].success && fd != -1) ||
610 (!tests[i].success && errno != tests[i].expected_errno),
611 "check-bpf-map-name",
612 "fd %d(%d) errno %d(%d)\n",
613 fd, tests[i].success, errno, tests[i].expected_errno);
614
615 if (fd != -1)
616 close(fd);
617 }
618}
619
498int main(void) 620int main(void)
499{ 621{
500 struct rlimit rinf = { RLIM_INFINITY, RLIM_INFINITY }; 622 struct rlimit rinf = { RLIM_INFINITY, RLIM_INFINITY };
@@ -507,6 +629,7 @@ int main(void)
507 test_tcp_estats(); 629 test_tcp_estats();
508 test_bpf_obj_id(); 630 test_bpf_obj_id();
509 test_pkt_md_access(); 631 test_pkt_md_access();
632 test_obj_name();
510 633
511 printf("Summary: %d PASSED, %d FAILED\n", pass_cnt, error_cnt); 634 printf("Summary: %d PASSED, %d FAILED\n", pass_cnt, error_cnt);
512 return error_cnt ? EXIT_FAILURE : EXIT_SUCCESS; 635 return error_cnt ? EXIT_FAILURE : EXIT_SUCCESS;
diff --git a/tools/testing/selftests/bpf/test_verifier.c b/tools/testing/selftests/bpf/test_verifier.c
index 64ae21f64489..bf092b83e453 100644
--- a/tools/testing/selftests/bpf/test_verifier.c
+++ b/tools/testing/selftests/bpf/test_verifier.c
@@ -3579,7 +3579,7 @@ static struct bpf_test tests[] = {
3579 .prog_type = BPF_PROG_TYPE_SCHED_CLS, 3579 .prog_type = BPF_PROG_TYPE_SCHED_CLS,
3580 }, 3580 },
3581 { 3581 {
3582 "helper access to packet: test19, cls helper fail range zero", 3582 "helper access to packet: test19, cls helper range zero",
3583 .insns = { 3583 .insns = {
3584 BPF_LDX_MEM(BPF_W, BPF_REG_6, BPF_REG_1, 3584 BPF_LDX_MEM(BPF_W, BPF_REG_6, BPF_REG_1,
3585 offsetof(struct __sk_buff, data)), 3585 offsetof(struct __sk_buff, data)),
@@ -3599,8 +3599,7 @@ static struct bpf_test tests[] = {
3599 BPF_MOV64_IMM(BPF_REG_0, 0), 3599 BPF_MOV64_IMM(BPF_REG_0, 0),
3600 BPF_EXIT_INSN(), 3600 BPF_EXIT_INSN(),
3601 }, 3601 },
3602 .result = REJECT, 3602 .result = ACCEPT,
3603 .errstr = "invalid access to packet",
3604 .prog_type = BPF_PROG_TYPE_SCHED_CLS, 3603 .prog_type = BPF_PROG_TYPE_SCHED_CLS,
3605 }, 3604 },
3606 { 3605 {
@@ -4379,10 +4378,10 @@ static struct bpf_test tests[] = {
4379 BPF_LD_MAP_FD(BPF_REG_1, 0), 4378 BPF_LD_MAP_FD(BPF_REG_1, 0),
4380 BPF_EMIT_CALL(BPF_FUNC_map_lookup_elem), 4379 BPF_EMIT_CALL(BPF_FUNC_map_lookup_elem),
4381 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4), 4380 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4),
4382 BPF_MOV64_REG(BPF_REG_1, BPF_REG_0), 4381 BPF_MOV64_IMM(BPF_REG_1, 0),
4383 BPF_MOV64_IMM(BPF_REG_2, 0), 4382 BPF_MOV64_REG(BPF_REG_2, BPF_REG_0),
4384 BPF_MOV64_IMM(BPF_REG_3, 0), 4383 BPF_MOV64_IMM(BPF_REG_3, 0),
4385 BPF_EMIT_CALL(BPF_FUNC_probe_read), 4384 BPF_EMIT_CALL(BPF_FUNC_probe_write_user),
4386 BPF_EXIT_INSN(), 4385 BPF_EXIT_INSN(),
4387 }, 4386 },
4388 .fixup_map2 = { 3 }, 4387 .fixup_map2 = { 3 },
@@ -4486,9 +4485,10 @@ static struct bpf_test tests[] = {
4486 BPF_MOV64_REG(BPF_REG_1, BPF_REG_0), 4485 BPF_MOV64_REG(BPF_REG_1, BPF_REG_0),
4487 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 4486 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1,
4488 offsetof(struct test_val, foo)), 4487 offsetof(struct test_val, foo)),
4489 BPF_MOV64_IMM(BPF_REG_2, 0), 4488 BPF_MOV64_REG(BPF_REG_2, BPF_REG_1),
4489 BPF_MOV64_IMM(BPF_REG_1, 0),
4490 BPF_MOV64_IMM(BPF_REG_3, 0), 4490 BPF_MOV64_IMM(BPF_REG_3, 0),
4491 BPF_EMIT_CALL(BPF_FUNC_probe_read), 4491 BPF_EMIT_CALL(BPF_FUNC_probe_write_user),
4492 BPF_EXIT_INSN(), 4492 BPF_EXIT_INSN(),
4493 }, 4493 },
4494 .fixup_map2 = { 3 }, 4494 .fixup_map2 = { 3 },
@@ -4622,13 +4622,14 @@ static struct bpf_test tests[] = {
4622 BPF_MOV64_REG(BPF_REG_1, BPF_REG_0), 4622 BPF_MOV64_REG(BPF_REG_1, BPF_REG_0),
4623 BPF_MOV64_IMM(BPF_REG_3, 0), 4623 BPF_MOV64_IMM(BPF_REG_3, 0),
4624 BPF_ALU64_REG(BPF_ADD, BPF_REG_1, BPF_REG_3), 4624 BPF_ALU64_REG(BPF_ADD, BPF_REG_1, BPF_REG_3),
4625 BPF_MOV64_IMM(BPF_REG_2, 0), 4625 BPF_MOV64_REG(BPF_REG_2, BPF_REG_1),
4626 BPF_MOV64_IMM(BPF_REG_1, 0),
4626 BPF_MOV64_IMM(BPF_REG_3, 0), 4627 BPF_MOV64_IMM(BPF_REG_3, 0),
4627 BPF_EMIT_CALL(BPF_FUNC_probe_read), 4628 BPF_EMIT_CALL(BPF_FUNC_probe_write_user),
4628 BPF_EXIT_INSN(), 4629 BPF_EXIT_INSN(),
4629 }, 4630 },
4630 .fixup_map2 = { 3 }, 4631 .fixup_map2 = { 3 },
4631 .errstr = "R1 min value is outside of the array range", 4632 .errstr = "R2 min value is outside of the array range",
4632 .result = REJECT, 4633 .result = REJECT,
4633 .prog_type = BPF_PROG_TYPE_TRACEPOINT, 4634 .prog_type = BPF_PROG_TYPE_TRACEPOINT,
4634 }, 4635 },
@@ -4765,13 +4766,14 @@ static struct bpf_test tests[] = {
4765 BPF_JMP_IMM(BPF_JGT, BPF_REG_3, 4766 BPF_JMP_IMM(BPF_JGT, BPF_REG_3,
4766 offsetof(struct test_val, foo), 4), 4767 offsetof(struct test_val, foo), 4),
4767 BPF_ALU64_REG(BPF_ADD, BPF_REG_1, BPF_REG_3), 4768 BPF_ALU64_REG(BPF_ADD, BPF_REG_1, BPF_REG_3),
4768 BPF_MOV64_IMM(BPF_REG_2, 0), 4769 BPF_MOV64_REG(BPF_REG_2, BPF_REG_1),
4770 BPF_MOV64_IMM(BPF_REG_1, 0),
4769 BPF_MOV64_IMM(BPF_REG_3, 0), 4771 BPF_MOV64_IMM(BPF_REG_3, 0),
4770 BPF_EMIT_CALL(BPF_FUNC_probe_read), 4772 BPF_EMIT_CALL(BPF_FUNC_probe_write_user),
4771 BPF_EXIT_INSN(), 4773 BPF_EXIT_INSN(),
4772 }, 4774 },
4773 .fixup_map2 = { 3 }, 4775 .fixup_map2 = { 3 },
4774 .errstr = "R1 min value is outside of the array range", 4776 .errstr = "R2 min value is outside of the array range",
4775 .result = REJECT, 4777 .result = REJECT,
4776 .prog_type = BPF_PROG_TYPE_TRACEPOINT, 4778 .prog_type = BPF_PROG_TYPE_TRACEPOINT,
4777 }, 4779 },
@@ -5350,7 +5352,7 @@ static struct bpf_test tests[] = {
5350 BPF_EMIT_CALL(BPF_FUNC_probe_read), 5352 BPF_EMIT_CALL(BPF_FUNC_probe_read),
5351 BPF_EXIT_INSN(), 5353 BPF_EXIT_INSN(),
5352 }, 5354 },
5353 .errstr = "invalid stack type R1 off=-64 access_size=0", 5355 .errstr = "invalid indirect read from stack off -64+0 size 64",
5354 .result = REJECT, 5356 .result = REJECT,
5355 .prog_type = BPF_PROG_TYPE_TRACEPOINT, 5357 .prog_type = BPF_PROG_TYPE_TRACEPOINT,
5356 }, 5358 },
@@ -5505,7 +5507,7 @@ static struct bpf_test tests[] = {
5505 BPF_MOV64_IMM(BPF_REG_0, 0), 5507 BPF_MOV64_IMM(BPF_REG_0, 0),
5506 BPF_EXIT_INSN(), 5508 BPF_EXIT_INSN(),
5507 }, 5509 },
5508 .errstr = "invalid stack type R1 off=-64 access_size=0", 5510 .errstr = "invalid indirect read from stack off -64+0 size 64",
5509 .result = REJECT, 5511 .result = REJECT,
5510 .prog_type = BPF_PROG_TYPE_TRACEPOINT, 5512 .prog_type = BPF_PROG_TYPE_TRACEPOINT,
5511 }, 5513 },
@@ -5668,7 +5670,7 @@ static struct bpf_test tests[] = {
5668 .prog_type = BPF_PROG_TYPE_SCHED_CLS, 5670 .prog_type = BPF_PROG_TYPE_SCHED_CLS,
5669 }, 5671 },
5670 { 5672 {
5671 "helper access to variable memory: size = 0 not allowed on != NULL", 5673 "helper access to variable memory: size = 0 allowed on != NULL stack pointer",
5672 .insns = { 5674 .insns = {
5673 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 5675 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
5674 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), 5676 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),
@@ -5681,8 +5683,99 @@ static struct bpf_test tests[] = {
5681 BPF_EMIT_CALL(BPF_FUNC_csum_diff), 5683 BPF_EMIT_CALL(BPF_FUNC_csum_diff),
5682 BPF_EXIT_INSN(), 5684 BPF_EXIT_INSN(),
5683 }, 5685 },
5684 .errstr = "invalid stack type R1 off=-8 access_size=0", 5686 .result = ACCEPT,
5685 .result = REJECT, 5687 .prog_type = BPF_PROG_TYPE_SCHED_CLS,
5688 },
5689 {
5690 "helper access to variable memory: size = 0 allowed on != NULL map pointer",
5691 .insns = {
5692 BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
5693 BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
5694 BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
5695 BPF_LD_MAP_FD(BPF_REG_1, 0),
5696 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
5697 BPF_FUNC_map_lookup_elem),
5698 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 6),
5699 BPF_MOV64_REG(BPF_REG_1, BPF_REG_0),
5700 BPF_MOV64_IMM(BPF_REG_2, 0),
5701 BPF_MOV64_IMM(BPF_REG_3, 0),
5702 BPF_MOV64_IMM(BPF_REG_4, 0),
5703 BPF_MOV64_IMM(BPF_REG_5, 0),
5704 BPF_EMIT_CALL(BPF_FUNC_csum_diff),
5705 BPF_EXIT_INSN(),
5706 },
5707 .fixup_map1 = { 3 },
5708 .result = ACCEPT,
5709 .prog_type = BPF_PROG_TYPE_SCHED_CLS,
5710 },
5711 {
5712 "helper access to variable memory: size possible = 0 allowed on != NULL stack pointer",
5713 .insns = {
5714 BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
5715 BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
5716 BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
5717 BPF_LD_MAP_FD(BPF_REG_1, 0),
5718 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
5719 BPF_FUNC_map_lookup_elem),
5720 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 9),
5721 BPF_LDX_MEM(BPF_DW, BPF_REG_2, BPF_REG_0, 0),
5722 BPF_JMP_IMM(BPF_JGT, BPF_REG_2, 8, 7),
5723 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
5724 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),
5725 BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_2, 0),
5726 BPF_MOV64_IMM(BPF_REG_3, 0),
5727 BPF_MOV64_IMM(BPF_REG_4, 0),
5728 BPF_MOV64_IMM(BPF_REG_5, 0),
5729 BPF_EMIT_CALL(BPF_FUNC_csum_diff),
5730 BPF_EXIT_INSN(),
5731 },
5732 .fixup_map1 = { 3 },
5733 .result = ACCEPT,
5734 .prog_type = BPF_PROG_TYPE_SCHED_CLS,
5735 },
5736 {
5737 "helper access to variable memory: size possible = 0 allowed on != NULL map pointer",
5738 .insns = {
5739 BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
5740 BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
5741 BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
5742 BPF_LD_MAP_FD(BPF_REG_1, 0),
5743 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
5744 BPF_FUNC_map_lookup_elem),
5745 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 7),
5746 BPF_MOV64_REG(BPF_REG_1, BPF_REG_0),
5747 BPF_LDX_MEM(BPF_DW, BPF_REG_2, BPF_REG_0, 0),
5748 BPF_JMP_IMM(BPF_JGT, BPF_REG_2, 8, 4),
5749 BPF_MOV64_IMM(BPF_REG_3, 0),
5750 BPF_MOV64_IMM(BPF_REG_4, 0),
5751 BPF_MOV64_IMM(BPF_REG_5, 0),
5752 BPF_EMIT_CALL(BPF_FUNC_csum_diff),
5753 BPF_EXIT_INSN(),
5754 },
5755 .fixup_map1 = { 3 },
5756 .result = ACCEPT,
5757 .prog_type = BPF_PROG_TYPE_SCHED_CLS,
5758 },
5759 {
5760 "helper access to variable memory: size possible = 0 allowed on != NULL packet pointer",
5761 .insns = {
5762 BPF_LDX_MEM(BPF_W, BPF_REG_6, BPF_REG_1,
5763 offsetof(struct __sk_buff, data)),
5764 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
5765 offsetof(struct __sk_buff, data_end)),
5766 BPF_MOV64_REG(BPF_REG_0, BPF_REG_6),
5767 BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, 8),
5768 BPF_JMP_REG(BPF_JGT, BPF_REG_0, BPF_REG_3, 7),
5769 BPF_MOV64_REG(BPF_REG_1, BPF_REG_6),
5770 BPF_LDX_MEM(BPF_DW, BPF_REG_2, BPF_REG_6, 0),
5771 BPF_JMP_IMM(BPF_JGT, BPF_REG_2, 8, 4),
5772 BPF_MOV64_IMM(BPF_REG_3, 0),
5773 BPF_MOV64_IMM(BPF_REG_4, 0),
5774 BPF_MOV64_IMM(BPF_REG_5, 0),
5775 BPF_EMIT_CALL(BPF_FUNC_csum_diff),
5776 BPF_EXIT_INSN(),
5777 },
5778 .result = ACCEPT,
5686 .prog_type = BPF_PROG_TYPE_SCHED_CLS, 5779 .prog_type = BPF_PROG_TYPE_SCHED_CLS,
5687 }, 5780 },
5688 { 5781 {
@@ -6658,6 +6751,253 @@ static struct bpf_test tests[] = {
6658 .result = REJECT, 6751 .result = REJECT,
6659 }, 6752 },
6660 { 6753 {
6754 "meta access, test1",
6755 .insns = {
6756 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
6757 offsetof(struct xdp_md, data_meta)),
6758 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
6759 offsetof(struct xdp_md, data)),
6760 BPF_MOV64_REG(BPF_REG_0, BPF_REG_2),
6761 BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, 8),
6762 BPF_JMP_REG(BPF_JGT, BPF_REG_0, BPF_REG_3, 1),
6763 BPF_LDX_MEM(BPF_B, BPF_REG_0, BPF_REG_2, 0),
6764 BPF_MOV64_IMM(BPF_REG_0, 0),
6765 BPF_EXIT_INSN(),
6766 },
6767 .result = ACCEPT,
6768 .prog_type = BPF_PROG_TYPE_XDP,
6769 },
6770 {
6771 "meta access, test2",
6772 .insns = {
6773 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
6774 offsetof(struct xdp_md, data_meta)),
6775 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
6776 offsetof(struct xdp_md, data)),
6777 BPF_MOV64_REG(BPF_REG_0, BPF_REG_2),
6778 BPF_ALU64_IMM(BPF_SUB, BPF_REG_0, 8),
6779 BPF_MOV64_REG(BPF_REG_4, BPF_REG_2),
6780 BPF_ALU64_IMM(BPF_ADD, BPF_REG_4, 8),
6781 BPF_JMP_REG(BPF_JGT, BPF_REG_4, BPF_REG_3, 1),
6782 BPF_LDX_MEM(BPF_B, BPF_REG_0, BPF_REG_0, 0),
6783 BPF_MOV64_IMM(BPF_REG_0, 0),
6784 BPF_EXIT_INSN(),
6785 },
6786 .result = REJECT,
6787 .errstr = "invalid access to packet, off=-8",
6788 .prog_type = BPF_PROG_TYPE_XDP,
6789 },
6790 {
6791 "meta access, test3",
6792 .insns = {
6793 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
6794 offsetof(struct xdp_md, data_meta)),
6795 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
6796 offsetof(struct xdp_md, data_end)),
6797 BPF_MOV64_REG(BPF_REG_0, BPF_REG_2),
6798 BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, 8),
6799 BPF_JMP_REG(BPF_JGT, BPF_REG_0, BPF_REG_3, 1),
6800 BPF_LDX_MEM(BPF_B, BPF_REG_0, BPF_REG_2, 0),
6801 BPF_MOV64_IMM(BPF_REG_0, 0),
6802 BPF_EXIT_INSN(),
6803 },
6804 .result = REJECT,
6805 .errstr = "invalid access to packet",
6806 .prog_type = BPF_PROG_TYPE_XDP,
6807 },
6808 {
6809 "meta access, test4",
6810 .insns = {
6811 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
6812 offsetof(struct xdp_md, data_meta)),
6813 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
6814 offsetof(struct xdp_md, data_end)),
6815 BPF_LDX_MEM(BPF_W, BPF_REG_4, BPF_REG_1,
6816 offsetof(struct xdp_md, data)),
6817 BPF_MOV64_REG(BPF_REG_0, BPF_REG_4),
6818 BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, 8),
6819 BPF_JMP_REG(BPF_JGT, BPF_REG_0, BPF_REG_3, 1),
6820 BPF_LDX_MEM(BPF_B, BPF_REG_0, BPF_REG_2, 0),
6821 BPF_MOV64_IMM(BPF_REG_0, 0),
6822 BPF_EXIT_INSN(),
6823 },
6824 .result = REJECT,
6825 .errstr = "invalid access to packet",
6826 .prog_type = BPF_PROG_TYPE_XDP,
6827 },
6828 {
6829 "meta access, test5",
6830 .insns = {
6831 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
6832 offsetof(struct xdp_md, data_meta)),
6833 BPF_LDX_MEM(BPF_W, BPF_REG_4, BPF_REG_1,
6834 offsetof(struct xdp_md, data)),
6835 BPF_MOV64_REG(BPF_REG_0, BPF_REG_3),
6836 BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, 8),
6837 BPF_JMP_REG(BPF_JGT, BPF_REG_0, BPF_REG_4, 3),
6838 BPF_MOV64_IMM(BPF_REG_2, -8),
6839 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
6840 BPF_FUNC_xdp_adjust_meta),
6841 BPF_LDX_MEM(BPF_B, BPF_REG_0, BPF_REG_3, 0),
6842 BPF_MOV64_IMM(BPF_REG_0, 0),
6843 BPF_EXIT_INSN(),
6844 },
6845 .result = REJECT,
6846 .errstr = "R3 !read_ok",
6847 .prog_type = BPF_PROG_TYPE_XDP,
6848 },
6849 {
6850 "meta access, test6",
6851 .insns = {
6852 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
6853 offsetof(struct xdp_md, data_meta)),
6854 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
6855 offsetof(struct xdp_md, data)),
6856 BPF_MOV64_REG(BPF_REG_0, BPF_REG_3),
6857 BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, 8),
6858 BPF_MOV64_REG(BPF_REG_4, BPF_REG_2),
6859 BPF_ALU64_IMM(BPF_ADD, BPF_REG_4, 8),
6860 BPF_JMP_REG(BPF_JGT, BPF_REG_4, BPF_REG_0, 1),
6861 BPF_LDX_MEM(BPF_B, BPF_REG_0, BPF_REG_2, 0),
6862 BPF_MOV64_IMM(BPF_REG_0, 0),
6863 BPF_EXIT_INSN(),
6864 },
6865 .result = REJECT,
6866 .errstr = "invalid access to packet",
6867 .prog_type = BPF_PROG_TYPE_XDP,
6868 },
6869 {
6870 "meta access, test7",
6871 .insns = {
6872 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
6873 offsetof(struct xdp_md, data_meta)),
6874 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
6875 offsetof(struct xdp_md, data)),
6876 BPF_MOV64_REG(BPF_REG_0, BPF_REG_3),
6877 BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, 8),
6878 BPF_MOV64_REG(BPF_REG_4, BPF_REG_2),
6879 BPF_ALU64_IMM(BPF_ADD, BPF_REG_4, 8),
6880 BPF_JMP_REG(BPF_JGT, BPF_REG_4, BPF_REG_3, 1),
6881 BPF_LDX_MEM(BPF_B, BPF_REG_0, BPF_REG_2, 0),
6882 BPF_MOV64_IMM(BPF_REG_0, 0),
6883 BPF_EXIT_INSN(),
6884 },
6885 .result = ACCEPT,
6886 .prog_type = BPF_PROG_TYPE_XDP,
6887 },
6888 {
6889 "meta access, test8",
6890 .insns = {
6891 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
6892 offsetof(struct xdp_md, data_meta)),
6893 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
6894 offsetof(struct xdp_md, data)),
6895 BPF_MOV64_REG(BPF_REG_4, BPF_REG_2),
6896 BPF_ALU64_IMM(BPF_ADD, BPF_REG_4, 0xFFFF),
6897 BPF_JMP_REG(BPF_JGT, BPF_REG_4, BPF_REG_3, 1),
6898 BPF_LDX_MEM(BPF_B, BPF_REG_0, BPF_REG_2, 0),
6899 BPF_MOV64_IMM(BPF_REG_0, 0),
6900 BPF_EXIT_INSN(),
6901 },
6902 .result = ACCEPT,
6903 .prog_type = BPF_PROG_TYPE_XDP,
6904 },
6905 {
6906 "meta access, test9",
6907 .insns = {
6908 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
6909 offsetof(struct xdp_md, data_meta)),
6910 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
6911 offsetof(struct xdp_md, data)),
6912 BPF_MOV64_REG(BPF_REG_4, BPF_REG_2),
6913 BPF_ALU64_IMM(BPF_ADD, BPF_REG_4, 0xFFFF),
6914 BPF_ALU64_IMM(BPF_ADD, BPF_REG_4, 1),
6915 BPF_JMP_REG(BPF_JGT, BPF_REG_4, BPF_REG_3, 1),
6916 BPF_LDX_MEM(BPF_B, BPF_REG_0, BPF_REG_2, 0),
6917 BPF_MOV64_IMM(BPF_REG_0, 0),
6918 BPF_EXIT_INSN(),
6919 },
6920 .result = REJECT,
6921 .errstr = "invalid access to packet",
6922 .prog_type = BPF_PROG_TYPE_XDP,
6923 },
6924 {
6925 "meta access, test10",
6926 .insns = {
6927 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
6928 offsetof(struct xdp_md, data_meta)),
6929 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
6930 offsetof(struct xdp_md, data)),
6931 BPF_LDX_MEM(BPF_W, BPF_REG_4, BPF_REG_1,
6932 offsetof(struct xdp_md, data_end)),
6933 BPF_MOV64_IMM(BPF_REG_5, 42),
6934 BPF_MOV64_IMM(BPF_REG_6, 24),
6935 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_5, -8),
6936 BPF_STX_XADD(BPF_DW, BPF_REG_10, BPF_REG_6, -8),
6937 BPF_LDX_MEM(BPF_DW, BPF_REG_5, BPF_REG_10, -8),
6938 BPF_JMP_IMM(BPF_JGT, BPF_REG_5, 100, 6),
6939 BPF_ALU64_REG(BPF_ADD, BPF_REG_3, BPF_REG_5),
6940 BPF_MOV64_REG(BPF_REG_5, BPF_REG_3),
6941 BPF_MOV64_REG(BPF_REG_6, BPF_REG_2),
6942 BPF_ALU64_IMM(BPF_ADD, BPF_REG_6, 8),
6943 BPF_JMP_REG(BPF_JGT, BPF_REG_6, BPF_REG_5, 1),
6944 BPF_LDX_MEM(BPF_B, BPF_REG_2, BPF_REG_2, 0),
6945 BPF_MOV64_IMM(BPF_REG_0, 0),
6946 BPF_EXIT_INSN(),
6947 },
6948 .result = REJECT,
6949 .errstr = "invalid access to packet",
6950 .prog_type = BPF_PROG_TYPE_XDP,
6951 },
6952 {
6953 "meta access, test11",
6954 .insns = {
6955 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
6956 offsetof(struct xdp_md, data_meta)),
6957 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
6958 offsetof(struct xdp_md, data)),
6959 BPF_MOV64_IMM(BPF_REG_5, 42),
6960 BPF_MOV64_IMM(BPF_REG_6, 24),
6961 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_5, -8),
6962 BPF_STX_XADD(BPF_DW, BPF_REG_10, BPF_REG_6, -8),
6963 BPF_LDX_MEM(BPF_DW, BPF_REG_5, BPF_REG_10, -8),
6964 BPF_JMP_IMM(BPF_JGT, BPF_REG_5, 100, 6),
6965 BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_5),
6966 BPF_MOV64_REG(BPF_REG_5, BPF_REG_2),
6967 BPF_MOV64_REG(BPF_REG_6, BPF_REG_2),
6968 BPF_ALU64_IMM(BPF_ADD, BPF_REG_6, 8),
6969 BPF_JMP_REG(BPF_JGT, BPF_REG_6, BPF_REG_3, 1),
6970 BPF_LDX_MEM(BPF_B, BPF_REG_5, BPF_REG_5, 0),
6971 BPF_MOV64_IMM(BPF_REG_0, 0),
6972 BPF_EXIT_INSN(),
6973 },
6974 .result = ACCEPT,
6975 .prog_type = BPF_PROG_TYPE_XDP,
6976 },
6977 {
6978 "meta access, test12",
6979 .insns = {
6980 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
6981 offsetof(struct xdp_md, data_meta)),
6982 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
6983 offsetof(struct xdp_md, data)),
6984 BPF_LDX_MEM(BPF_W, BPF_REG_4, BPF_REG_1,
6985 offsetof(struct xdp_md, data_end)),
6986 BPF_MOV64_REG(BPF_REG_5, BPF_REG_3),
6987 BPF_ALU64_IMM(BPF_ADD, BPF_REG_5, 16),
6988 BPF_JMP_REG(BPF_JGT, BPF_REG_5, BPF_REG_4, 5),
6989 BPF_LDX_MEM(BPF_B, BPF_REG_0, BPF_REG_3, 0),
6990 BPF_MOV64_REG(BPF_REG_5, BPF_REG_2),
6991 BPF_ALU64_IMM(BPF_ADD, BPF_REG_5, 16),
6992 BPF_JMP_REG(BPF_JGT, BPF_REG_5, BPF_REG_3, 1),
6993 BPF_LDX_MEM(BPF_B, BPF_REG_0, BPF_REG_2, 0),
6994 BPF_MOV64_IMM(BPF_REG_0, 0),
6995 BPF_EXIT_INSN(),
6996 },
6997 .result = ACCEPT,
6998 .prog_type = BPF_PROG_TYPE_XDP,
6999 },
7000 {
6661 "arithmetic ops make PTR_TO_CTX unusable", 7001 "arithmetic ops make PTR_TO_CTX unusable",
6662 .insns = { 7002 .insns = {
6663 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 7003 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1,
@@ -7151,6 +7491,520 @@ static struct bpf_test tests[] = {
7151 .prog_type = BPF_PROG_TYPE_XDP, 7491 .prog_type = BPF_PROG_TYPE_XDP,
7152 .flags = F_NEEDS_EFFICIENT_UNALIGNED_ACCESS, 7492 .flags = F_NEEDS_EFFICIENT_UNALIGNED_ACCESS,
7153 }, 7493 },
7494 {
7495 "XDP pkt read, pkt_meta' > pkt_data, good access",
7496 .insns = {
7497 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7498 offsetof(struct xdp_md, data_meta)),
7499 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7500 offsetof(struct xdp_md, data)),
7501 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7502 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7503 BPF_JMP_REG(BPF_JGT, BPF_REG_1, BPF_REG_3, 1),
7504 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7505 BPF_MOV64_IMM(BPF_REG_0, 0),
7506 BPF_EXIT_INSN(),
7507 },
7508 .result = ACCEPT,
7509 .prog_type = BPF_PROG_TYPE_XDP,
7510 },
7511 {
7512 "XDP pkt read, pkt_meta' > pkt_data, bad access 1",
7513 .insns = {
7514 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7515 offsetof(struct xdp_md, data_meta)),
7516 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7517 offsetof(struct xdp_md, data)),
7518 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7519 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7520 BPF_JMP_REG(BPF_JGT, BPF_REG_1, BPF_REG_3, 1),
7521 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -4),
7522 BPF_MOV64_IMM(BPF_REG_0, 0),
7523 BPF_EXIT_INSN(),
7524 },
7525 .errstr = "R1 offset is outside of the packet",
7526 .result = REJECT,
7527 .prog_type = BPF_PROG_TYPE_XDP,
7528 .flags = F_NEEDS_EFFICIENT_UNALIGNED_ACCESS,
7529 },
7530 {
7531 "XDP pkt read, pkt_meta' > pkt_data, bad access 2",
7532 .insns = {
7533 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7534 offsetof(struct xdp_md, data_meta)),
7535 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7536 offsetof(struct xdp_md, data)),
7537 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7538 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7539 BPF_JMP_REG(BPF_JGT, BPF_REG_1, BPF_REG_3, 0),
7540 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7541 BPF_MOV64_IMM(BPF_REG_0, 0),
7542 BPF_EXIT_INSN(),
7543 },
7544 .errstr = "R1 offset is outside of the packet",
7545 .result = REJECT,
7546 .prog_type = BPF_PROG_TYPE_XDP,
7547 },
7548 {
7549 "XDP pkt read, pkt_data > pkt_meta', good access",
7550 .insns = {
7551 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7552 offsetof(struct xdp_md, data_meta)),
7553 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7554 offsetof(struct xdp_md, data)),
7555 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7556 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7557 BPF_JMP_REG(BPF_JGT, BPF_REG_3, BPF_REG_1, 1),
7558 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
7559 BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, -5),
7560 BPF_MOV64_IMM(BPF_REG_0, 0),
7561 BPF_EXIT_INSN(),
7562 },
7563 .result = ACCEPT,
7564 .prog_type = BPF_PROG_TYPE_XDP,
7565 .flags = F_NEEDS_EFFICIENT_UNALIGNED_ACCESS,
7566 },
7567 {
7568 "XDP pkt read, pkt_data > pkt_meta', bad access 1",
7569 .insns = {
7570 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7571 offsetof(struct xdp_md, data_meta)),
7572 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7573 offsetof(struct xdp_md, data)),
7574 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7575 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7576 BPF_JMP_REG(BPF_JGT, BPF_REG_3, BPF_REG_1, 1),
7577 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
7578 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7579 BPF_MOV64_IMM(BPF_REG_0, 0),
7580 BPF_EXIT_INSN(),
7581 },
7582 .errstr = "R1 offset is outside of the packet",
7583 .result = REJECT,
7584 .prog_type = BPF_PROG_TYPE_XDP,
7585 },
7586 {
7587 "XDP pkt read, pkt_data > pkt_meta', bad access 2",
7588 .insns = {
7589 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7590 offsetof(struct xdp_md, data_meta)),
7591 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7592 offsetof(struct xdp_md, data)),
7593 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7594 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7595 BPF_JMP_REG(BPF_JGT, BPF_REG_3, BPF_REG_1, 1),
7596 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7597 BPF_MOV64_IMM(BPF_REG_0, 0),
7598 BPF_EXIT_INSN(),
7599 },
7600 .errstr = "R1 offset is outside of the packet",
7601 .result = REJECT,
7602 .prog_type = BPF_PROG_TYPE_XDP,
7603 },
7604 {
7605 "XDP pkt read, pkt_meta' < pkt_data, good access",
7606 .insns = {
7607 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7608 offsetof(struct xdp_md, data_meta)),
7609 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7610 offsetof(struct xdp_md, data)),
7611 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7612 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7613 BPF_JMP_REG(BPF_JLT, BPF_REG_1, BPF_REG_3, 1),
7614 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
7615 BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, -5),
7616 BPF_MOV64_IMM(BPF_REG_0, 0),
7617 BPF_EXIT_INSN(),
7618 },
7619 .result = ACCEPT,
7620 .prog_type = BPF_PROG_TYPE_XDP,
7621 .flags = F_NEEDS_EFFICIENT_UNALIGNED_ACCESS,
7622 },
7623 {
7624 "XDP pkt read, pkt_meta' < pkt_data, bad access 1",
7625 .insns = {
7626 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7627 offsetof(struct xdp_md, data_meta)),
7628 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7629 offsetof(struct xdp_md, data)),
7630 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7631 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7632 BPF_JMP_REG(BPF_JLT, BPF_REG_1, BPF_REG_3, 1),
7633 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
7634 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7635 BPF_MOV64_IMM(BPF_REG_0, 0),
7636 BPF_EXIT_INSN(),
7637 },
7638 .errstr = "R1 offset is outside of the packet",
7639 .result = REJECT,
7640 .prog_type = BPF_PROG_TYPE_XDP,
7641 },
7642 {
7643 "XDP pkt read, pkt_meta' < pkt_data, bad access 2",
7644 .insns = {
7645 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7646 offsetof(struct xdp_md, data_meta)),
7647 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7648 offsetof(struct xdp_md, data)),
7649 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7650 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7651 BPF_JMP_REG(BPF_JLT, BPF_REG_1, BPF_REG_3, 1),
7652 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7653 BPF_MOV64_IMM(BPF_REG_0, 0),
7654 BPF_EXIT_INSN(),
7655 },
7656 .errstr = "R1 offset is outside of the packet",
7657 .result = REJECT,
7658 .prog_type = BPF_PROG_TYPE_XDP,
7659 },
7660 {
7661 "XDP pkt read, pkt_data < pkt_meta', good access",
7662 .insns = {
7663 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7664 offsetof(struct xdp_md, data_meta)),
7665 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7666 offsetof(struct xdp_md, data)),
7667 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7668 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7669 BPF_JMP_REG(BPF_JLT, BPF_REG_3, BPF_REG_1, 1),
7670 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7671 BPF_MOV64_IMM(BPF_REG_0, 0),
7672 BPF_EXIT_INSN(),
7673 },
7674 .result = ACCEPT,
7675 .prog_type = BPF_PROG_TYPE_XDP,
7676 },
7677 {
7678 "XDP pkt read, pkt_data < pkt_meta', bad access 1",
7679 .insns = {
7680 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7681 offsetof(struct xdp_md, data_meta)),
7682 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7683 offsetof(struct xdp_md, data)),
7684 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7685 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7686 BPF_JMP_REG(BPF_JLT, BPF_REG_3, BPF_REG_1, 1),
7687 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -4),
7688 BPF_MOV64_IMM(BPF_REG_0, 0),
7689 BPF_EXIT_INSN(),
7690 },
7691 .errstr = "R1 offset is outside of the packet",
7692 .result = REJECT,
7693 .prog_type = BPF_PROG_TYPE_XDP,
7694 .flags = F_NEEDS_EFFICIENT_UNALIGNED_ACCESS,
7695 },
7696 {
7697 "XDP pkt read, pkt_data < pkt_meta', bad access 2",
7698 .insns = {
7699 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7700 offsetof(struct xdp_md, data_meta)),
7701 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7702 offsetof(struct xdp_md, data)),
7703 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7704 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7705 BPF_JMP_REG(BPF_JLT, BPF_REG_3, BPF_REG_1, 0),
7706 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7707 BPF_MOV64_IMM(BPF_REG_0, 0),
7708 BPF_EXIT_INSN(),
7709 },
7710 .errstr = "R1 offset is outside of the packet",
7711 .result = REJECT,
7712 .prog_type = BPF_PROG_TYPE_XDP,
7713 },
7714 {
7715 "XDP pkt read, pkt_meta' >= pkt_data, good access",
7716 .insns = {
7717 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7718 offsetof(struct xdp_md, data_meta)),
7719 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7720 offsetof(struct xdp_md, data)),
7721 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7722 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7723 BPF_JMP_REG(BPF_JGE, BPF_REG_1, BPF_REG_3, 1),
7724 BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, -5),
7725 BPF_MOV64_IMM(BPF_REG_0, 0),
7726 BPF_EXIT_INSN(),
7727 },
7728 .result = ACCEPT,
7729 .prog_type = BPF_PROG_TYPE_XDP,
7730 .flags = F_NEEDS_EFFICIENT_UNALIGNED_ACCESS,
7731 },
7732 {
7733 "XDP pkt read, pkt_meta' >= pkt_data, bad access 1",
7734 .insns = {
7735 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7736 offsetof(struct xdp_md, data_meta)),
7737 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7738 offsetof(struct xdp_md, data)),
7739 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7740 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7741 BPF_JMP_REG(BPF_JGE, BPF_REG_1, BPF_REG_3, 1),
7742 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7743 BPF_MOV64_IMM(BPF_REG_0, 0),
7744 BPF_EXIT_INSN(),
7745 },
7746 .errstr = "R1 offset is outside of the packet",
7747 .result = REJECT,
7748 .prog_type = BPF_PROG_TYPE_XDP,
7749 },
7750 {
7751 "XDP pkt read, pkt_meta' >= pkt_data, bad access 2",
7752 .insns = {
7753 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7754 offsetof(struct xdp_md, data_meta)),
7755 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7756 offsetof(struct xdp_md, data)),
7757 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7758 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7759 BPF_JMP_REG(BPF_JGE, BPF_REG_1, BPF_REG_3, 0),
7760 BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, -5),
7761 BPF_MOV64_IMM(BPF_REG_0, 0),
7762 BPF_EXIT_INSN(),
7763 },
7764 .errstr = "R1 offset is outside of the packet",
7765 .result = REJECT,
7766 .prog_type = BPF_PROG_TYPE_XDP,
7767 .flags = F_NEEDS_EFFICIENT_UNALIGNED_ACCESS,
7768 },
7769 {
7770 "XDP pkt read, pkt_data >= pkt_meta', good access",
7771 .insns = {
7772 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7773 offsetof(struct xdp_md, data_meta)),
7774 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7775 offsetof(struct xdp_md, data)),
7776 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7777 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7778 BPF_JMP_REG(BPF_JGE, BPF_REG_3, BPF_REG_1, 1),
7779 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
7780 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7781 BPF_MOV64_IMM(BPF_REG_0, 0),
7782 BPF_EXIT_INSN(),
7783 },
7784 .result = ACCEPT,
7785 .prog_type = BPF_PROG_TYPE_XDP,
7786 },
7787 {
7788 "XDP pkt read, pkt_data >= pkt_meta', bad access 1",
7789 .insns = {
7790 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7791 offsetof(struct xdp_md, data_meta)),
7792 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7793 offsetof(struct xdp_md, data)),
7794 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7795 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7796 BPF_JMP_REG(BPF_JGE, BPF_REG_3, BPF_REG_1, 1),
7797 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
7798 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -4),
7799 BPF_MOV64_IMM(BPF_REG_0, 0),
7800 BPF_EXIT_INSN(),
7801 },
7802 .errstr = "R1 offset is outside of the packet",
7803 .result = REJECT,
7804 .prog_type = BPF_PROG_TYPE_XDP,
7805 .flags = F_NEEDS_EFFICIENT_UNALIGNED_ACCESS,
7806 },
7807 {
7808 "XDP pkt read, pkt_data >= pkt_meta', bad access 2",
7809 .insns = {
7810 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7811 offsetof(struct xdp_md, data_meta)),
7812 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7813 offsetof(struct xdp_md, data)),
7814 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7815 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7816 BPF_JMP_REG(BPF_JGE, BPF_REG_3, BPF_REG_1, 1),
7817 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7818 BPF_MOV64_IMM(BPF_REG_0, 0),
7819 BPF_EXIT_INSN(),
7820 },
7821 .errstr = "R1 offset is outside of the packet",
7822 .result = REJECT,
7823 .prog_type = BPF_PROG_TYPE_XDP,
7824 },
7825 {
7826 "XDP pkt read, pkt_meta' <= pkt_data, good access",
7827 .insns = {
7828 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7829 offsetof(struct xdp_md, data_meta)),
7830 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7831 offsetof(struct xdp_md, data)),
7832 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7833 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7834 BPF_JMP_REG(BPF_JLE, BPF_REG_1, BPF_REG_3, 1),
7835 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
7836 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7837 BPF_MOV64_IMM(BPF_REG_0, 0),
7838 BPF_EXIT_INSN(),
7839 },
7840 .result = ACCEPT,
7841 .prog_type = BPF_PROG_TYPE_XDP,
7842 },
7843 {
7844 "XDP pkt read, pkt_meta' <= pkt_data, bad access 1",
7845 .insns = {
7846 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7847 offsetof(struct xdp_md, data_meta)),
7848 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7849 offsetof(struct xdp_md, data)),
7850 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7851 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7852 BPF_JMP_REG(BPF_JLE, BPF_REG_1, BPF_REG_3, 1),
7853 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
7854 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -4),
7855 BPF_MOV64_IMM(BPF_REG_0, 0),
7856 BPF_EXIT_INSN(),
7857 },
7858 .errstr = "R1 offset is outside of the packet",
7859 .result = REJECT,
7860 .prog_type = BPF_PROG_TYPE_XDP,
7861 .flags = F_NEEDS_EFFICIENT_UNALIGNED_ACCESS,
7862 },
7863 {
7864 "XDP pkt read, pkt_meta' <= pkt_data, bad access 2",
7865 .insns = {
7866 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7867 offsetof(struct xdp_md, data_meta)),
7868 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7869 offsetof(struct xdp_md, data)),
7870 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7871 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7872 BPF_JMP_REG(BPF_JLE, BPF_REG_1, BPF_REG_3, 1),
7873 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7874 BPF_MOV64_IMM(BPF_REG_0, 0),
7875 BPF_EXIT_INSN(),
7876 },
7877 .errstr = "R1 offset is outside of the packet",
7878 .result = REJECT,
7879 .prog_type = BPF_PROG_TYPE_XDP,
7880 },
7881 {
7882 "XDP pkt read, pkt_data <= pkt_meta', good access",
7883 .insns = {
7884 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7885 offsetof(struct xdp_md, data_meta)),
7886 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7887 offsetof(struct xdp_md, data)),
7888 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7889 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7890 BPF_JMP_REG(BPF_JLE, BPF_REG_3, BPF_REG_1, 1),
7891 BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, -5),
7892 BPF_MOV64_IMM(BPF_REG_0, 0),
7893 BPF_EXIT_INSN(),
7894 },
7895 .result = ACCEPT,
7896 .prog_type = BPF_PROG_TYPE_XDP,
7897 .flags = F_NEEDS_EFFICIENT_UNALIGNED_ACCESS,
7898 },
7899 {
7900 "XDP pkt read, pkt_data <= pkt_meta', bad access 1",
7901 .insns = {
7902 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7903 offsetof(struct xdp_md, data_meta)),
7904 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7905 offsetof(struct xdp_md, data)),
7906 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7907 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7908 BPF_JMP_REG(BPF_JLE, BPF_REG_3, BPF_REG_1, 1),
7909 BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8),
7910 BPF_MOV64_IMM(BPF_REG_0, 0),
7911 BPF_EXIT_INSN(),
7912 },
7913 .errstr = "R1 offset is outside of the packet",
7914 .result = REJECT,
7915 .prog_type = BPF_PROG_TYPE_XDP,
7916 },
7917 {
7918 "XDP pkt read, pkt_data <= pkt_meta', bad access 2",
7919 .insns = {
7920 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
7921 offsetof(struct xdp_md, data_meta)),
7922 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
7923 offsetof(struct xdp_md, data)),
7924 BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
7925 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
7926 BPF_JMP_REG(BPF_JLE, BPF_REG_3, BPF_REG_1, 0),
7927 BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, -5),
7928 BPF_MOV64_IMM(BPF_REG_0, 0),
7929 BPF_EXIT_INSN(),
7930 },
7931 .errstr = "R1 offset is outside of the packet",
7932 .result = REJECT,
7933 .prog_type = BPF_PROG_TYPE_XDP,
7934 .flags = F_NEEDS_EFFICIENT_UNALIGNED_ACCESS,
7935 },
7936 {
7937 "bpf_exit with invalid return code. test1",
7938 .insns = {
7939 BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, 0),
7940 BPF_EXIT_INSN(),
7941 },
7942 .errstr = "R0 has value (0x0; 0xffffffff)",
7943 .result = REJECT,
7944 .prog_type = BPF_PROG_TYPE_CGROUP_SOCK,
7945 },
7946 {
7947 "bpf_exit with invalid return code. test2",
7948 .insns = {
7949 BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, 0),
7950 BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1),
7951 BPF_EXIT_INSN(),
7952 },
7953 .result = ACCEPT,
7954 .prog_type = BPF_PROG_TYPE_CGROUP_SOCK,
7955 },
7956 {
7957 "bpf_exit with invalid return code. test3",
7958 .insns = {
7959 BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, 0),
7960 BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 3),
7961 BPF_EXIT_INSN(),
7962 },
7963 .errstr = "R0 has value (0x0; 0x3)",
7964 .result = REJECT,
7965 .prog_type = BPF_PROG_TYPE_CGROUP_SOCK,
7966 },
7967 {
7968 "bpf_exit with invalid return code. test4",
7969 .insns = {
7970 BPF_MOV64_IMM(BPF_REG_0, 1),
7971 BPF_EXIT_INSN(),
7972 },
7973 .result = ACCEPT,
7974 .prog_type = BPF_PROG_TYPE_CGROUP_SOCK,
7975 },
7976 {
7977 "bpf_exit with invalid return code. test5",
7978 .insns = {
7979 BPF_MOV64_IMM(BPF_REG_0, 2),
7980 BPF_EXIT_INSN(),
7981 },
7982 .errstr = "R0 has value (0x2; 0x0)",
7983 .result = REJECT,
7984 .prog_type = BPF_PROG_TYPE_CGROUP_SOCK,
7985 },
7986 {
7987 "bpf_exit with invalid return code. test6",
7988 .insns = {
7989 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
7990 BPF_EXIT_INSN(),
7991 },
7992 .errstr = "R0 is not a known value (ctx)",
7993 .result = REJECT,
7994 .prog_type = BPF_PROG_TYPE_CGROUP_SOCK,
7995 },
7996 {
7997 "bpf_exit with invalid return code. test7",
7998 .insns = {
7999 BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, 0),
8000 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, 4),
8001 BPF_ALU64_REG(BPF_MUL, BPF_REG_0, BPF_REG_2),
8002 BPF_EXIT_INSN(),
8003 },
8004 .errstr = "R0 has unknown scalar value",
8005 .result = REJECT,
8006 .prog_type = BPF_PROG_TYPE_CGROUP_SOCK,
8007 },
7154}; 8008};
7155 8009
7156static int probe_filter_length(const struct bpf_insn *fp) 8010static int probe_filter_length(const struct bpf_insn *fp)
@@ -7198,7 +8052,7 @@ static int create_map_in_map(void)
7198 return inner_map_fd; 8052 return inner_map_fd;
7199 } 8053 }
7200 8054
7201 outer_map_fd = bpf_create_map_in_map(BPF_MAP_TYPE_ARRAY_OF_MAPS, 8055 outer_map_fd = bpf_create_map_in_map(BPF_MAP_TYPE_ARRAY_OF_MAPS, NULL,
7202 sizeof(int), inner_map_fd, 1, 0); 8056 sizeof(int), inner_map_fd, 1, 0);
7203 if (outer_map_fd < 0) 8057 if (outer_map_fd < 0)
7204 printf("Failed to create array of maps '%s'!\n", 8058 printf("Failed to create array of maps '%s'!\n",
diff --git a/tools/testing/selftests/bpf/test_verifier_log.c b/tools/testing/selftests/bpf/test_verifier_log.c
new file mode 100644
index 000000000000..3cc0b561489e
--- /dev/null
+++ b/tools/testing/selftests/bpf/test_verifier_log.c
@@ -0,0 +1,171 @@
1#include <errno.h>
2#include <stdlib.h>
3#include <stdio.h>
4#include <string.h>
5#include <unistd.h>
6
7#include <linux/bpf.h>
8#include <linux/filter.h>
9#include <linux/unistd.h>
10
11#include <bpf/bpf.h>
12
13#define LOG_SIZE (1 << 20)
14
15#define err(str...) printf("ERROR: " str)
16
17static const struct bpf_insn code_sample[] = {
18 /* We need a few instructions to pass the min log length */
19 BPF_MOV64_IMM(BPF_REG_0, 0),
20 BPF_MOV64_IMM(BPF_REG_0, 0),
21 BPF_MOV64_IMM(BPF_REG_0, 0),
22 BPF_MOV64_IMM(BPF_REG_0, 0),
23 BPF_MOV64_IMM(BPF_REG_0, 0),
24 BPF_MOV64_IMM(BPF_REG_0, 0),
25 BPF_MOV64_IMM(BPF_REG_0, 0),
26 BPF_MOV64_IMM(BPF_REG_0, 0),
27 BPF_MOV64_IMM(BPF_REG_0, 0),
28 BPF_MOV64_IMM(BPF_REG_0, 0),
29 BPF_MOV64_IMM(BPF_REG_0, 0),
30 BPF_MOV64_IMM(BPF_REG_0, 0),
31 BPF_MOV64_IMM(BPF_REG_0, 0),
32 BPF_MOV64_IMM(BPF_REG_0, 0),
33 BPF_MOV64_IMM(BPF_REG_0, 0),
34 BPF_MOV64_IMM(BPF_REG_0, 0),
35 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
36 BPF_FUNC_map_lookup_elem),
37 BPF_EXIT_INSN(),
38};
39
40static inline __u64 ptr_to_u64(const void *ptr)
41{
42 return (__u64) (unsigned long) ptr;
43}
44
45static int load(char *log, size_t log_len, int log_level)
46{
47 union bpf_attr attr;
48
49 bzero(&attr, sizeof(attr));
50 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
51 attr.insn_cnt = (__u32)(sizeof(code_sample) / sizeof(struct bpf_insn));
52 attr.insns = ptr_to_u64(code_sample);
53 attr.license = ptr_to_u64("GPL");
54 attr.log_buf = ptr_to_u64(log);
55 attr.log_size = log_len;
56 attr.log_level = log_level;
57
58 return syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));
59}
60
61static void check_ret(int ret, int exp_errno)
62{
63 if (ret > 0) {
64 close(ret);
65 err("broken sample loaded successfully!?\n");
66 exit(1);
67 }
68
69 if (!ret || errno != exp_errno) {
70 err("Program load returned: ret:%d/errno:%d, expected ret:%d/errno:%d\n",
71 ret, errno, -1, exp_errno);
72 exit(1);
73 }
74}
75
76static void check_ones(const char *buf, size_t len, const char *msg)
77{
78 while (len--)
79 if (buf[len] != 1) {
80 err("%s", msg);
81 exit(1);
82 }
83}
84
85static void test_log_good(char *log, size_t buf_len, size_t log_len,
86 size_t exp_len, int exp_errno, const char *full_log)
87{
88 size_t len;
89 int ret;
90
91 memset(log, 1, buf_len);
92
93 ret = load(log, log_len, 1);
94 check_ret(ret, exp_errno);
95
96 len = strnlen(log, buf_len);
97 if (len == buf_len) {
98 err("verifier did not NULL terminate the log\n");
99 exit(1);
100 }
101 if (exp_len && len != exp_len) {
102 err("incorrect log length expected:%zd have:%zd\n",
103 exp_len, len);
104 exit(1);
105 }
106
107 if (strchr(log, 1)) {
108 err("verifier leaked a byte through\n");
109 exit(1);
110 }
111
112 check_ones(log + len + 1, buf_len - len - 1,
113 "verifier wrote bytes past NULL termination\n");
114
115 if (memcmp(full_log, log, LOG_SIZE)) {
116 err("log did not match expected output\n");
117 exit(1);
118 }
119}
120
121static void test_log_bad(char *log, size_t log_len, int log_level)
122{
123 int ret;
124
125 ret = load(log, log_len, log_level);
126 check_ret(ret, EINVAL);
127 if (log)
128 check_ones(log, LOG_SIZE,
129 "verifier touched log with bad parameters\n");
130}
131
132int main(int argc, char **argv)
133{
134 char full_log[LOG_SIZE];
135 char log[LOG_SIZE];
136 size_t want_len;
137 int i;
138
139 memset(log, 1, LOG_SIZE);
140
141 /* Test incorrect attr */
142 printf("Test log_level 0...\n");
143 test_log_bad(log, LOG_SIZE, 0);
144
145 printf("Test log_size < 128...\n");
146 test_log_bad(log, 15, 1);
147
148 printf("Test log_buff = NULL...\n");
149 test_log_bad(NULL, LOG_SIZE, 1);
150
151 /* Test with log big enough */
152 printf("Test oversized buffer...\n");
153 test_log_good(full_log, LOG_SIZE, LOG_SIZE, 0, EACCES, full_log);
154
155 want_len = strlen(full_log);
156
157 printf("Test exact buffer...\n");
158 test_log_good(log, LOG_SIZE, want_len + 2, want_len, EACCES, full_log);
159
160 printf("Test undersized buffers...\n");
161 for (i = 0; i < 64; i++) {
162 full_log[want_len - i + 1] = 1;
163 full_log[want_len - i] = 0;
164
165 test_log_good(log, LOG_SIZE, want_len + 1 - i, want_len - i,
166 ENOSPC, full_log);
167 }
168
169 printf("test_verifier_log: OK\n");
170 return 0;
171}
diff --git a/tools/testing/selftests/bpf/test_xdp_meta.c b/tools/testing/selftests/bpf/test_xdp_meta.c
new file mode 100644
index 000000000000..8d0182650653
--- /dev/null
+++ b/tools/testing/selftests/bpf/test_xdp_meta.c
@@ -0,0 +1,53 @@
1#include <linux/bpf.h>
2#include <linux/if_ether.h>
3#include <linux/pkt_cls.h>
4
5#include "bpf_helpers.h"
6
7#define __round_mask(x, y) ((__typeof__(x))((y) - 1))
8#define round_up(x, y) ((((x) - 1) | __round_mask(x, y)) + 1)
9#define ctx_ptr(ctx, mem) (void *)(unsigned long)ctx->mem
10
11SEC("t")
12int ing_cls(struct __sk_buff *ctx)
13{
14 __u8 *data, *data_meta, *data_end;
15 __u32 diff = 0;
16
17 data_meta = ctx_ptr(ctx, data_meta);
18 data_end = ctx_ptr(ctx, data_end);
19 data = ctx_ptr(ctx, data);
20
21 if (data + ETH_ALEN > data_end ||
22 data_meta + round_up(ETH_ALEN, 4) > data)
23 return TC_ACT_SHOT;
24
25 diff |= ((__u32 *)data_meta)[0] ^ ((__u32 *)data)[0];
26 diff |= ((__u16 *)data_meta)[2] ^ ((__u16 *)data)[2];
27
28 return diff ? TC_ACT_SHOT : TC_ACT_OK;
29}
30
31SEC("x")
32int ing_xdp(struct xdp_md *ctx)
33{
34 __u8 *data, *data_meta, *data_end;
35 int ret;
36
37 ret = bpf_xdp_adjust_meta(ctx, -round_up(ETH_ALEN, 4));
38 if (ret < 0)
39 return XDP_DROP;
40
41 data_meta = ctx_ptr(ctx, data_meta);
42 data_end = ctx_ptr(ctx, data_end);
43 data = ctx_ptr(ctx, data);
44
45 if (data + ETH_ALEN > data_end ||
46 data_meta + round_up(ETH_ALEN, 4) > data)
47 return XDP_DROP;
48
49 __builtin_memcpy(data_meta, data, ETH_ALEN);
50 return XDP_PASS;
51}
52
53char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/test_xdp_meta.sh b/tools/testing/selftests/bpf/test_xdp_meta.sh
new file mode 100755
index 000000000000..307aa856cee3
--- /dev/null
+++ b/tools/testing/selftests/bpf/test_xdp_meta.sh
@@ -0,0 +1,51 @@
1#!/bin/sh
2
3cleanup()
4{
5 if [ "$?" = "0" ]; then
6 echo "selftests: test_xdp_meta [PASS]";
7 else
8 echo "selftests: test_xdp_meta [FAILED]";
9 fi
10
11 set +e
12 ip netns del ns1 2> /dev/null
13 ip netns del ns2 2> /dev/null
14}
15
16ip link set dev lo xdp off 2>/dev/null > /dev/null
17if [ $? -ne 0 ];then
18 echo "selftests: [SKIP] Could not run test without the ip xdp support"
19 exit 0
20fi
21set -e
22
23ip netns add ns1
24ip netns add ns2
25
26trap cleanup 0 2 3 6 9
27
28ip link add veth1 type veth peer name veth2
29
30ip link set veth1 netns ns1
31ip link set veth2 netns ns2
32
33ip netns exec ns1 ip addr add 10.1.1.11/24 dev veth1
34ip netns exec ns2 ip addr add 10.1.1.22/24 dev veth2
35
36ip netns exec ns1 tc qdisc add dev veth1 clsact
37ip netns exec ns2 tc qdisc add dev veth2 clsact
38
39ip netns exec ns1 tc filter add dev veth1 ingress bpf da obj test_xdp_meta.o sec t
40ip netns exec ns2 tc filter add dev veth2 ingress bpf da obj test_xdp_meta.o sec t
41
42ip netns exec ns1 ip link set dev veth1 xdp obj test_xdp_meta.o sec x
43ip netns exec ns2 ip link set dev veth2 xdp obj test_xdp_meta.o sec x
44
45ip netns exec ns1 ip link set dev veth1 up
46ip netns exec ns2 ip link set dev veth2 up
47
48ip netns exec ns1 ping -c 1 10.1.1.22
49ip netns exec ns2 ping -c 1 10.1.1.11
50
51exit 0
diff --git a/tools/testing/selftests/net/rtnetlink.sh b/tools/testing/selftests/net/rtnetlink.sh
index 57b5ff576240..5215493166c9 100755
--- a/tools/testing/selftests/net/rtnetlink.sh
+++ b/tools/testing/selftests/net/rtnetlink.sh
@@ -15,6 +15,14 @@ check_err()
15 fi 15 fi
16} 16}
17 17
18# same but inverted -- used when command must fail for test to pass
19check_fail()
20{
21 if [ $1 -eq 0 ]; then
22 ret=1
23 fi
24}
25
18kci_add_dummy() 26kci_add_dummy()
19{ 27{
20 ip link add name "$devdummy" type dummy 28 ip link add name "$devdummy" type dummy
@@ -29,6 +37,26 @@ kci_del_dummy()
29 check_err $? 37 check_err $?
30} 38}
31 39
40kci_test_netconf()
41{
42 dev="$1"
43 r=$ret
44
45 ip netconf show dev "$dev" > /dev/null
46 check_err $?
47
48 for f in 4 6; do
49 ip -$f netconf show dev "$dev" > /dev/null
50 check_err $?
51 done
52
53 if [ $ret -ne 0 ] ;then
54 echo "FAIL: ip netconf show $dev"
55 test $r -eq 0 && ret=0
56 return 1
57 fi
58}
59
32# add a bridge with vlans on top 60# add a bridge with vlans on top
33kci_test_bridge() 61kci_test_bridge()
34{ 62{
@@ -55,6 +83,11 @@ kci_test_bridge()
55 check_err $? 83 check_err $?
56 ip r s t all > /dev/null 84 ip r s t all > /dev/null
57 check_err $? 85 check_err $?
86
87 for name in "$devbr" "$vlandev" "$devdummy" ; do
88 kci_test_netconf "$name"
89 done
90
58 ip -6 addr del dev "$vlandev" dead:42::1234/64 91 ip -6 addr del dev "$vlandev" dead:42::1234/64
59 check_err $? 92 check_err $?
60 93
@@ -92,6 +125,9 @@ kci_test_gre()
92 check_err $? 125 check_err $?
93 ip addr > /dev/null 126 ip addr > /dev/null
94 check_err $? 127 check_err $?
128
129 kci_test_netconf "$gredev"
130
95 ip addr del dev "$devdummy" 10.23.7.11/24 131 ip addr del dev "$devdummy" 10.23.7.11/24
96 check_err $? 132 check_err $?
97 133
@@ -235,6 +271,237 @@ kci_test_addrlabel()
235 echo "PASS: ipv6 addrlabel" 271 echo "PASS: ipv6 addrlabel"
236} 272}
237 273
274kci_test_ifalias()
275{
276 ret=0
277 namewant=$(uuidgen)
278 syspathname="/sys/class/net/$devdummy/ifalias"
279
280 ip link set dev "$devdummy" alias "$namewant"
281 check_err $?
282
283 if [ $ret -ne 0 ]; then
284 echo "FAIL: cannot set interface alias of $devdummy to $namewant"
285 return 1
286 fi
287
288 ip link show "$devdummy" | grep -q "alias $namewant"
289 check_err $?
290
291 if [ -r "$syspathname" ] ; then
292 read namehave < "$syspathname"
293 if [ "$namewant" != "$namehave" ]; then
294 echo "FAIL: did set ifalias $namewant but got $namehave"
295 return 1
296 fi
297
298 namewant=$(uuidgen)
299 echo "$namewant" > "$syspathname"
300 ip link show "$devdummy" | grep -q "alias $namewant"
301 check_err $?
302
303 # sysfs interface allows to delete alias again
304 echo "" > "$syspathname"
305
306 ip link show "$devdummy" | grep -q "alias $namewant"
307 check_fail $?
308
309 for i in $(seq 1 100); do
310 uuidgen > "$syspathname" &
311 done
312
313 wait
314
315 # re-add the alias -- kernel should free mem when dummy dev is removed
316 ip link set dev "$devdummy" alias "$namewant"
317 check_err $?
318 fi
319
320 if [ $ret -ne 0 ]; then
321 echo "FAIL: set interface alias $devdummy to $namewant"
322 return 1
323 fi
324
325 echo "PASS: set ifalias $namewant for $devdummy"
326}
327
328kci_test_vrf()
329{
330 vrfname="test-vrf"
331 ret=0
332
333 ip link show type vrf 2>/dev/null
334 if [ $? -ne 0 ]; then
335 echo "SKIP: vrf: iproute2 too old"
336 return 0
337 fi
338
339 ip link add "$vrfname" type vrf table 10
340 check_err $?
341 if [ $ret -ne 0 ];then
342 echo "FAIL: can't add vrf interface, skipping test"
343 return 0
344 fi
345
346 ip -br link show type vrf | grep -q "$vrfname"
347 check_err $?
348 if [ $ret -ne 0 ];then
349 echo "FAIL: created vrf device not found"
350 return 1
351 fi
352
353 ip link set dev "$vrfname" up
354 check_err $?
355
356 ip link set dev "$devdummy" master "$vrfname"
357 check_err $?
358 ip link del dev "$vrfname"
359 check_err $?
360
361 if [ $ret -ne 0 ];then
362 echo "FAIL: vrf"
363 return 1
364 fi
365
366 echo "PASS: vrf"
367}
368
369kci_test_encap_vxlan()
370{
371 ret=0
372 vxlan="test-vxlan0"
373 vlan="test-vlan0"
374 testns="$1"
375
376 ip netns exec "$testns" ip link add "$vxlan" type vxlan id 42 group 239.1.1.1 \
377 dev "$devdummy" dstport 4789 2>/dev/null
378 if [ $? -ne 0 ]; then
379 echo "FAIL: can't add vxlan interface, skipping test"
380 return 0
381 fi
382 check_err $?
383
384 ip netns exec "$testns" ip addr add 10.2.11.49/24 dev "$vxlan"
385 check_err $?
386
387 ip netns exec "$testns" ip link set up dev "$vxlan"
388 check_err $?
389
390 ip netns exec "$testns" ip link add link "$vxlan" name "$vlan" type vlan id 1
391 check_err $?
392
393 ip netns exec "$testns" ip link del "$vxlan"
394 check_err $?
395
396 if [ $ret -ne 0 ]; then
397 echo "FAIL: vxlan"
398 return 1
399 fi
400 echo "PASS: vxlan"
401}
402
403kci_test_encap_fou()
404{
405 ret=0
406 name="test-fou"
407 testns="$1"
408
409 ip fou help 2>&1 |grep -q 'Usage: ip fou'
410 if [ $? -ne 0 ];then
411 echo "SKIP: fou: iproute2 too old"
412 return 1
413 fi
414
415 ip netns exec "$testns" ip fou add port 7777 ipproto 47 2>/dev/null
416 if [ $? -ne 0 ];then
417 echo "FAIL: can't add fou port 7777, skipping test"
418 return 1
419 fi
420
421 ip netns exec "$testns" ip fou add port 8888 ipproto 4
422 check_err $?
423
424 ip netns exec "$testns" ip fou del port 9999 2>/dev/null
425 check_fail $?
426
427 ip netns exec "$testns" ip fou del port 7777
428 check_err $?
429
430 if [ $ret -ne 0 ]; then
431 echo "FAIL: fou"
432 return 1
433 fi
434
435 echo "PASS: fou"
436}
437
438# test various encap methods, use netns to avoid unwanted interference
439kci_test_encap()
440{
441 testns="testns"
442 ret=0
443
444 ip netns add "$testns"
445 if [ $? -ne 0 ]; then
446 echo "SKIP encap tests: cannot add net namespace $testns"
447 return 1
448 fi
449
450 ip netns exec "$testns" ip link set lo up
451 check_err $?
452
453 ip netns exec "$testns" ip link add name "$devdummy" type dummy
454 check_err $?
455 ip netns exec "$testns" ip link set "$devdummy" up
456 check_err $?
457
458 kci_test_encap_vxlan "$testns"
459 kci_test_encap_fou "$testns"
460
461 ip netns del "$testns"
462}
463
464kci_test_macsec()
465{
466 msname="test_macsec0"
467 ret=0
468
469 ip macsec help 2>&1 | grep -q "^Usage: ip macsec"
470 if [ $? -ne 0 ]; then
471 echo "SKIP: macsec: iproute2 too old"
472 return 0
473 fi
474
475 ip link add link "$devdummy" "$msname" type macsec port 42 encrypt on
476 check_err $?
477 if [ $ret -ne 0 ];then
478 echo "FAIL: can't add macsec interface, skipping test"
479 return 1
480 fi
481
482 ip macsec add "$msname" tx sa 0 pn 1024 on key 01 12345678901234567890123456789012
483 check_err $?
484
485 ip macsec add "$msname" rx port 1234 address "1c:ed:de:ad:be:ef"
486 check_err $?
487
488 ip macsec add "$msname" rx port 1234 address "1c:ed:de:ad:be:ef" sa 0 pn 1 on key 00 0123456789abcdef0123456789abcdef
489 check_err $?
490
491 ip macsec show > /dev/null
492 check_err $?
493
494 ip link del dev "$msname"
495 check_err $?
496
497 if [ $ret -ne 0 ];then
498 echo "FAIL: macsec"
499 return 1
500 fi
501
502 echo "PASS: macsec"
503}
504
238kci_test_rtnl() 505kci_test_rtnl()
239{ 506{
240 kci_add_dummy 507 kci_add_dummy
@@ -249,6 +516,10 @@ kci_test_rtnl()
249 kci_test_gre 516 kci_test_gre
250 kci_test_bridge 517 kci_test_bridge
251 kci_test_addrlabel 518 kci_test_addrlabel
519 kci_test_ifalias
520 kci_test_vrf
521 kci_test_encap
522 kci_test_macsec
252 523
253 kci_del_dummy 524 kci_del_dummy
254} 525}
diff --git a/tools/testing/selftests/tc-testing/.gitignore b/tools/testing/selftests/tc-testing/.gitignore
index c18dd8d83cee..7a60b85e148f 100644
--- a/tools/testing/selftests/tc-testing/.gitignore
+++ b/tools/testing/selftests/tc-testing/.gitignore
@@ -1 +1,2 @@
1__pycache__/ 1__pycache__/
2*.pyc
diff --git a/tools/testing/selftests/tc-testing/creating-testcases/AddingTestCases.txt b/tools/testing/selftests/tc-testing/creating-testcases/AddingTestCases.txt
index 4e09257bc443..00438331ba47 100644
--- a/tools/testing/selftests/tc-testing/creating-testcases/AddingTestCases.txt
+++ b/tools/testing/selftests/tc-testing/creating-testcases/AddingTestCases.txt
@@ -34,6 +34,12 @@ category: A list of single-word descriptions covering what the command
34setup: The list of commands required to ensure the command under test 34setup: The list of commands required to ensure the command under test
35 succeeds. For example: if testing a filter, the command to create 35 succeeds. For example: if testing a filter, the command to create
36 the qdisc would appear here. 36 the qdisc would appear here.
37 This list can be empty.
38 Each command can be a string to be executed, or a list consisting
39 of a string which is a command to be executed, followed by 1 or
40 more acceptable exit codes for this command.
41 If only a string is given for the command, then an exit code of 0
42 will be expected.
37cmdUnderTest: The tc command being tested itself. 43cmdUnderTest: The tc command being tested itself.
38expExitCode: The code returned by the command under test upon its termination. 44expExitCode: The code returned by the command under test upon its termination.
39 tdc will compare this value against the actual returned value. 45 tdc will compare this value against the actual returned value.
@@ -49,6 +55,12 @@ matchCount: How many times the regex in matchPattern should match. A value
49teardown: The list of commands to clean up after the test is completed. 55teardown: The list of commands to clean up after the test is completed.
50 The environment should be returned to the same state as when 56 The environment should be returned to the same state as when
51 this test was started: qdiscs deleted, actions flushed, etc. 57 this test was started: qdiscs deleted, actions flushed, etc.
58 This list can be empty.
59 Each command can be a string to be executed, or a list consisting
60 of a string which is a command to be executed, followed by 1 or
61 more acceptable exit codes for this command.
62 If only a string is given for the command, then an exit code of 0
63 will be expected.
52 64
53 65
54SETUP/TEARDOWN ERRORS 66SETUP/TEARDOWN ERRORS
diff --git a/tools/testing/selftests/tc-testing/creating-testcases/example.json b/tools/testing/selftests/tc-testing/creating-testcases/example.json
new file mode 100644
index 000000000000..5ec501200970
--- /dev/null
+++ b/tools/testing/selftests/tc-testing/creating-testcases/example.json
@@ -0,0 +1,55 @@
1[
2 {
3 "id": "1f",
4 "name": "simple test to test framework",
5 "category": [
6 "example"
7 ],
8 "setup": [
9 "mkdir mytest"
10 ],
11 "cmdUnderTest": "touch mytest/blorfl",
12 "expExitCode": "0",
13 "verifyCmd": "ls mytest/* | grep '[b]lorfl'",
14 "matchPattern": "orfl",
15 "matchCount": "1",
16 "teardown": [
17 "rm -rf mytest"
18 ]
19 },
20 {
21 "id": "2f",
22 "name": "simple test, no need for verify",
23 "category": [
24 "example"
25 ],
26 "setup": [
27 "mkdir mytest",
28 "touch mytest/blorfl"
29 ],
30 "cmdUnderTest": "ls mytest/blorfl",
31 "expExitCode": "0",
32 "verifyCmd": "/bin/true",
33 "matchPattern": " ",
34 "matchCount": "0",
35 "teardown": [
36 "rm -rf mytest"
37 ]
38 },
39 {
40 "id": "3f",
41 "name": "simple test, no need for setup or teardown (or verify)",
42 "category": [
43 "example"
44 ],
45 "setup": [
46 ],
47 "cmdUnderTest": "ip l l lo",
48 "expExitCode": "0",
49 "verifyCmd": "/bin/true",
50 "matchPattern": " ",
51 "matchCount": "0",
52 "teardown": [
53 ]
54 }
55]
diff --git a/tools/testing/selftests/tc-testing/creating-testcases/template.json b/tools/testing/selftests/tc-testing/creating-testcases/template.json
index 87971744bdd4..8b99b86d65bd 100644
--- a/tools/testing/selftests/tc-testing/creating-testcases/template.json
+++ b/tools/testing/selftests/tc-testing/creating-testcases/template.json
@@ -26,7 +26,13 @@
26 "" 26 ""
27 ], 27 ],
28 "setup": [ 28 "setup": [
29 "" 29 "",
30 [
31 "",
32 0,
33 1,
34 255
35 ]
30 ], 36 ],
31 "cmdUnderTest": "", 37 "cmdUnderTest": "",
32 "expExitCode": "", 38 "expExitCode": "",
@@ -34,7 +40,12 @@
34 "matchPattern": "", 40 "matchPattern": "",
35 "matchCount": "", 41 "matchCount": "",
36 "teardown": [ 42 "teardown": [
37 "" 43 "",
44 [
45 "",
46 0,
47 255
48 ]
38 ] 49 ]
39 } 50 }
40] 51]
diff --git a/tools/testing/selftests/tc-testing/tc-tests/actions/gact.json b/tools/testing/selftests/tc-testing/tc-tests/actions/gact.json
new file mode 100644
index 000000000000..e2187b6e0b7a
--- /dev/null
+++ b/tools/testing/selftests/tc-testing/tc-tests/actions/gact.json
@@ -0,0 +1,469 @@
1[
2 {
3 "id": "e89a",
4 "name": "Add valid pass action",
5 "category": [
6 "actions",
7 "gact"
8 ],
9 "setup": [
10 [
11 "$TC actions flush action gact",
12 0,
13 1,
14 255
15 ]
16 ],
17 "cmdUnderTest": "$TC actions add action pass index 8",
18 "expExitCode": "0",
19 "verifyCmd": "$TC actions list action gact",
20 "matchPattern": "action order [0-9]*: gact action pass.*index 8 ref",
21 "matchCount": "1",
22 "teardown": [
23 "$TC actions flush action gact"
24 ]
25 },
26 {
27 "id": "a02c",
28 "name": "Add valid pipe action",
29 "category": [
30 "actions",
31 "gact"
32 ],
33 "setup": [
34 [
35 "$TC actions flush action gact",
36 0,
37 1,
38 255
39 ]
40 ],
41 "cmdUnderTest": "$TC actions add action pipe index 6",
42 "expExitCode": "0",
43 "verifyCmd": "$TC actions list action gact",
44 "matchPattern": "action order [0-9]*: gact action pipe.*index 6 ref",
45 "matchCount": "1",
46 "teardown": [
47 "$TC actions flush action gact"
48 ]
49 },
50 {
51 "id": "feef",
52 "name": "Add valid reclassify action",
53 "category": [
54 "actions",
55 "gact"
56 ],
57 "setup": [
58 [
59 "$TC actions flush action gact",
60 0,
61 1,
62 255
63 ]
64 ],
65 "cmdUnderTest": "$TC actions add action reclassify index 5",
66 "expExitCode": "0",
67 "verifyCmd": "$TC actions list action gact",
68 "matchPattern": "action order [0-9]*: gact action reclassify.*index 5 ref",
69 "matchCount": "1",
70 "teardown": [
71 "$TC actions flush action gact"
72 ]
73 },
74 {
75 "id": "8a7a",
76 "name": "Add valid drop action",
77 "category": [
78 "actions",
79 "gact"
80 ],
81 "setup": [
82 [
83 "$TC actions flush action gact",
84 0,
85 1,
86 255
87 ]
88 ],
89 "cmdUnderTest": "$TC actions add action drop index 30",
90 "expExitCode": "0",
91 "verifyCmd": "$TC actions list action gact",
92 "matchPattern": "action order [0-9]*: gact action drop.*index 30 ref",
93 "matchCount": "1",
94 "teardown": [
95 "$TC actions flush action gact"
96 ]
97 },
98 {
99 "id": "9a52",
100 "name": "Add valid continue action",
101 "category": [
102 "actions",
103 "gact"
104 ],
105 "setup": [
106 [
107 "$TC actions flush action gact",
108 0,
109 1,
110 255
111 ]
112 ],
113 "cmdUnderTest": "$TC actions add action continue index 432",
114 "expExitCode": "0",
115 "verifyCmd": "$TC actions list action gact",
116 "matchPattern": "action order [0-9]*: gact action continue.*index 432 ref",
117 "matchCount": "1",
118 "teardown": [
119 "$TC actions flush action gact"
120 ]
121 },
122 {
123 "id": "d700",
124 "name": "Add invalid action",
125 "category": [
126 "actions",
127 "gact"
128 ],
129 "setup": [
130 [
131 "$TC actions flush action gact",
132 0,
133 1,
134 255
135 ]
136 ],
137 "cmdUnderTest": "$TC actions add action pump index 386",
138 "expExitCode": "255",
139 "verifyCmd": "$TC actions list action gact",
140 "matchPattern": "action order [0-9]*: gact action.*index 386 ref",
141 "matchCount": "0",
142 "teardown": [
143 "$TC actions flush action gact"
144 ]
145 },
146 {
147 "id": "9215",
148 "name": "Add action with duplicate index",
149 "category": [
150 "actions",
151 "gact"
152 ],
153 "setup": [
154 [
155 "$TC actions flush action gact",
156 0,
157 1,
158 255
159 ],
160 "$TC actions add action pipe index 15"
161 ],
162 "cmdUnderTest": "$TC actions add action drop index 15",
163 "expExitCode": "255",
164 "verifyCmd": "$TC actions list action gact",
165 "matchPattern": "action order [0-9]*: gact action drop.*index 15 ref",
166 "matchCount": "0",
167 "teardown": [
168 "$TC actions flush action gact"
169 ]
170 },
171 {
172 "id": "798e",
173 "name": "Add action with index exceeding 32-bit maximum",
174 "category": [
175 "actions",
176 "gact"
177 ],
178 "setup": [
179 [
180 "$TC actions flush action gact",
181 0,
182 1,
183 255
184 ]
185 ],
186 "cmdUnderTest": "$TC actions add action drop index 4294967296",
187 "expExitCode": "255",
188 "verifyCmd": "actions list action gact",
189 "matchPattern": "action order [0-9]*: gact action drop.*index 4294967296 ref",
190 "matchCount": "0",
191 "teardown": [
192 "$TC actions flush action gact"
193 ]
194 },
195 {
196 "id": "22be",
197 "name": "Add action with index at 32-bit maximum",
198 "category": [
199 "actions",
200 "gact"
201 ],
202 "setup": [
203 [
204 "$TC actions flush action gact",
205 0,
206 1,
207 255
208 ]
209 ],
210 "cmdUnderTest": "$TC actions add action drop index 4294967295",
211 "expExitCode": "0",
212 "verifyCmd": "$TC actions list action gact",
213 "matchPattern": "action order [0-9]*: gact action drop.*index 4294967295 ref",
214 "matchCount": "1",
215 "teardown": [
216 "$TC actions flush action gact"
217 ]
218 },
219 {
220 "id": "ac2a",
221 "name": "List actions",
222 "category": [
223 "actions",
224 "gact"
225 ],
226 "setup": [
227 [
228 "$TC actions flush action gact",
229 0,
230 1,
231 255
232 ],
233 "$TC actions add action reclassify index 101",
234 "$TC actions add action reclassify index 102",
235 "$TC actions add action reclassify index 103",
236 "$TC actions add action reclassify index 104",
237 "$TC actions add action reclassify index 105"
238 ],
239 "cmdUnderTest": "$TC actions list action gact",
240 "expExitCode": "0",
241 "verifyCmd": "$TC actions list action gact",
242 "matchPattern": "action order [0-9]*: gact action reclassify",
243 "matchCount": "5",
244 "teardown": [
245 "$TC actions flush action gact"
246 ]
247 },
248 {
249 "id": "3edf",
250 "name": "Flush gact actions",
251 "category": [
252 "actions",
253 "gact"
254 ],
255 "setup": [
256 "$TC actions add action reclassify index 101",
257 "$TC actions add action reclassify index 102",
258 "$TC actions add action reclassify index 103",
259 "$TC actions add action reclassify index 104",
260 "$TC actions add action reclassify index 105"
261 ],
262 "cmdUnderTest": "$TC actions flush action gact",
263 "expExitCode": "0",
264 "verifyCmd": "$TC actions list action gact",
265 "matchPattern": "action order [0-9]*: gact action reclassify",
266 "matchCount": "0",
267 "teardown": []
268 },
269 {
270 "id": "63ec",
271 "name": "Delete pass action",
272 "category": [
273 "actions",
274 "gact"
275 ],
276 "setup": [
277 [
278 "$TC actions flush action gact",
279 0,
280 1,
281 255
282 ],
283 "$TC actions add action pass index 1"
284 ],
285 "cmdUnderTest": "$TC actions del action gact index 1",
286 "expExitCode": "0",
287 "verifyCmd": "$TC actions list action gact",
288 "matchPattern": "action order [0-9]*: gact action pass.*index 1 ref",
289 "matchCount": "0",
290 "teardown": [
291 "$TC actions flush action gact"
292 ]
293 },
294 {
295 "id": "46be",
296 "name": "Delete pipe action",
297 "category": [
298 "actions",
299 "gact"
300 ],
301 "setup": [
302 [
303 "$TC actions flush action gact",
304 0,
305 1,
306 255
307 ],
308 "$TC actions add action pipe index 9"
309 ],
310 "cmdUnderTest": "$TC actions del action gact index 9",
311 "expExitCode": "0",
312 "verifyCmd": "$TC actions list action gact",
313 "matchPattern": "action order [0-9]*: gact action pipe.*index 9 ref",
314 "matchCount": "0",
315 "teardown": [
316 "$TC actions flush action gact"
317 ]
318 },
319 {
320 "id": "2e08",
321 "name": "Delete reclassify action",
322 "category": [
323 "actions",
324 "gact"
325 ],
326 "setup": [
327 [
328 "$TC actions flush action gact",
329 0,
330 1,
331 255
332 ],
333 "$TC actions add action reclassify index 65536"
334 ],
335 "cmdUnderTest": "$TC actions del action gact index 65536",
336 "expExitCode": "0",
337 "verifyCmd": "$TC actions list action gact",
338 "matchPattern": "action order [0-9]*: gact action reclassify.*index 65536 ref",
339 "matchCount": "0",
340 "teardown": [
341 "$TC actions flush action gact"
342 ]
343 },
344 {
345 "id": "99c4",
346 "name": "Delete drop action",
347 "category": [
348 "actions",
349 "gact"
350 ],
351 "setup": [
352 [
353 "$TC actions flush action gact",
354 0,
355 1,
356 255
357 ],
358 "$TC actions add action drop index 16"
359 ],
360 "cmdUnderTest": "$TC actions del action gact index 16",
361 "expExitCode": "0",
362 "verifyCmd": "$TC actions list action gact",
363 "matchPattern": "action order [0-9]*: gact action drop.*index 16 ref",
364 "matchCount": "0",
365 "teardown": [
366 "$TC actions flush action gact"
367 ]
368 },
369 {
370 "id": "fb6b",
371 "name": "Delete continue action",
372 "category": [
373 "actions",
374 "gact"
375 ],
376 "setup": [
377 [
378 "$TC actions flush action gact",
379 0,
380 1,
381 255
382 ],
383 "$TC actions add action continue index 32"
384 ],
385 "cmdUnderTest": "$TC actions del action gact index 32",
386 "expExitCode": "0",
387 "verifyCmd": "actions list action gact",
388 "matchPattern": "action order [0-9]*: gact action continue.*index 32 ref",
389 "matchCount": "0",
390 "teardown": [
391 "$TC actions flush action gact"
392 ]
393 },
394 {
395 "id": "0eb3",
396 "name": "Delete non-existent action",
397 "category": [
398 "actions",
399 "gact"
400 ],
401 "setup": [
402 [
403 "$TC actions flush action gact",
404 0,
405 1,
406 255
407 ]
408 ],
409 "cmdUnderTest": "$TC actions del action gact index 2",
410 "expExitCode": "255",
411 "verifyCmd": "$TC actions list action gact",
412 "matchPattern": "action order [0-9]*: gact action",
413 "matchCount": "0",
414 "teardown": [
415 "$TC actions flush action gact"
416 ]
417 },
418 {
419 "id": "f02c",
420 "name": "Replace gact action",
421 "category": [
422 "actions",
423 "gact"
424 ],
425 "setup": [
426 [
427 "$TC actions flush action gact",
428 0,
429 1,
430 255
431 ],
432 "$TC actions add action drop index 10",
433 "$TC actions add action drop index 12"
434 ],
435 "cmdUnderTest": "$TC actions replace action ok index 12",
436 "expExitCode": "0",
437 "verifyCmd": "$TC actions ls action gact",
438 "matchPattern": "action order [0-9]*: gact action pass",
439 "matchCount": "1",
440 "teardown": [
441 "$TC actions flush action gact"
442 ]
443 },
444 {
445 "id": "525f",
446 "name": "Get gact action by index",
447 "category": [
448 "actions",
449 "gact"
450 ],
451 "setup": [
452 [
453 "$TC actions flush action gact",
454 0,
455 1,
456 255
457 ],
458 "$TC actions add action drop index 3900800700"
459 ],
460 "cmdUnderTest": "$TC actions get action gact index 3900800700",
461 "expExitCode": "0",
462 "verifyCmd": "$TC actions get action gact index 3900800700",
463 "matchPattern": "index 3900800700",
464 "matchCount": "1",
465 "teardown": [
466 "$TC actions flush action gact"
467 ]
468 }
469]
diff --git a/tools/testing/selftests/tc-testing/tc-tests/actions/ife.json b/tools/testing/selftests/tc-testing/tc-tests/actions/ife.json
new file mode 100644
index 000000000000..9f34f0753969
--- /dev/null
+++ b/tools/testing/selftests/tc-testing/tc-tests/actions/ife.json
@@ -0,0 +1,52 @@
1[
2 {
3 "id": "a568",
4 "name": "Add action with ife type",
5 "category": [
6 "actions",
7 "ife"
8 ],
9 "setup": [
10 [
11 "$TC actions flush action ife",
12 0,
13 1,
14 255
15 ],
16 "$TC actions add action ife encode type 0xDEAD index 1"
17 ],
18 "cmdUnderTest": "$TC actions get action ife index 1",
19 "expExitCode": "0",
20 "verifyCmd": "$TC actions get action ife index 1",
21 "matchPattern": "type 0xDEAD",
22 "matchCount": "1",
23 "teardown": [
24 "$TC actions flush action ife"
25 ]
26 },
27 {
28 "id": "b983",
29 "name": "Add action without ife type",
30 "category": [
31 "actions",
32 "ife"
33 ],
34 "setup": [
35 [
36 "$TC actions flush action ife",
37 0,
38 1,
39 255
40 ],
41 "$TC actions add action ife encode index 1"
42 ],
43 "cmdUnderTest": "$TC actions get action ife index 1",
44 "expExitCode": "0",
45 "verifyCmd": "$TC actions get action ife index 1",
46 "matchPattern": "type 0xED3E",
47 "matchCount": "1",
48 "teardown": [
49 "$TC actions flush action ife"
50 ]
51 }
52]
diff --git a/tools/testing/selftests/tc-testing/tc-tests/actions/mirred.json b/tools/testing/selftests/tc-testing/tc-tests/actions/mirred.json
new file mode 100644
index 000000000000..0fcccf18399b
--- /dev/null
+++ b/tools/testing/selftests/tc-testing/tc-tests/actions/mirred.json
@@ -0,0 +1,223 @@
1[
2 {
3 "id": "5124",
4 "name": "Add mirred mirror to egress action",
5 "category": [
6 "actions",
7 "mirred"
8 ],
9 "setup": [
10 [
11 "$TC actions flush action mirred",
12 0,
13 1,
14 255
15 ]
16 ],
17 "cmdUnderTest": "$TC actions add action mirred egress mirror index 1 dev lo",
18 "expExitCode": "0",
19 "verifyCmd": "$TC actions list action mirred",
20 "matchPattern": "action order [0-9]*: mirred \\(Egress Mirror to device lo\\).*index 1 ref",
21 "matchCount": "1",
22 "teardown": [
23 "$TC actions flush action mirred"
24 ]
25 },
26 {
27 "id": "6fb4",
28 "name": "Add mirred redirect to egress action",
29 "category": [
30 "actions",
31 "mirred"
32 ],
33 "setup": [
34 [
35 "$TC actions flush action mirred",
36 0,
37 1,
38 255
39 ]
40 ],
41 "cmdUnderTest": "$TC actions add action mirred egress redirect index 2 dev lo action pipe",
42 "expExitCode": "0",
43 "verifyCmd": "$TC actions list action mirred",
44 "matchPattern": "action order [0-9]*: mirred \\(Egress Redirect to device lo\\).*index 2 ref",
45 "matchCount": "1",
46 "teardown": [
47 "$TC actions flush action mirred"
48 ]
49 },
50 {
51 "id": "ba38",
52 "name": "Get mirred actions",
53 "category": [
54 "actions",
55 "mirred"
56 ],
57 "setup": [
58 [
59 "$TC actions flush action mirred",
60 0,
61 1,
62 255
63 ],
64 "$TC actions add action mirred egress mirror index 1 dev lo",
65 "$TC actions add action mirred egress redirect index 2 dev lo"
66 ],
67 "cmdUnderTest": "$TC actions show action mirred",
68 "expExitCode": "0",
69 "verifyCmd": "$TC actions list action mirred",
70 "matchPattern": "[Mirror|Redirect] to device lo",
71 "matchCount": "2",
72 "teardown": [
73 "$TC actions flush action mirred"
74 ]
75 },
76 {
77 "id": "d7c0",
78 "name": "Add invalid mirred direction",
79 "category": [
80 "actions",
81 "mirred"
82 ],
83 "setup": [
84 [
85 "$TC actions flush action mirred",
86 0,
87 1,
88 255
89 ]
90 ],
91 "cmdUnderTest": "$TC actions add action mirred inbound mirror index 20 dev lo",
92 "expExitCode": "255",
93 "verifyCmd": "$TC actions list action mirred",
94 "matchPattern": "action order [0-9]*: mirred \\(.*to device lo\\).*index 20 ref",
95 "matchCount": "0",
96 "teardown": [
97 "$TC actions flush action mirred"
98 ]
99 },
100 {
101 "id": "e213",
102 "name": "Add invalid mirred action",
103 "category": [
104 "actions",
105 "mirred"
106 ],
107 "setup": [
108 [
109 "$TC actions flush action mirred",
110 0,
111 1,
112 255
113 ]
114 ],
115 "cmdUnderTest": "$TC actions add action mirred egress remirror index 20 dev lo",
116 "expExitCode": "255",
117 "verifyCmd": "$TC actions list action mirred",
118 "matchPattern": "action order [0-9]*: mirred \\(Egress.*to device lo\\).*index 20 ref",
119 "matchCount": "0",
120 "teardown": [
121 "$TC actions flush action mirred"
122 ]
123 },
124 {
125 "id": "2d89",
126 "name": "Add mirred action with invalid device",
127 "category": [
128 "actions",
129 "mirred"
130 ],
131 "setup": [
132 [
133 "$TC actions flush action mirred",
134 0,
135 1,
136 255
137 ]
138 ],
139 "cmdUnderTest": "$TC actions add action mirred egress mirror index 20 dev eltoh",
140 "expExitCode": "255",
141 "verifyCmd": "$TC actions list action mirred",
142 "matchPattern": "action order [0-9]*: mirred \\(.*to device eltoh\\).*index 20 ref",
143 "matchCount": "0",
144 "teardown": [
145 "$TC actions flush action mirred"
146 ]
147 },
148 {
149 "id": "300b",
150 "name": "Add mirred action with duplicate index",
151 "category": [
152 "actions",
153 "mirred"
154 ],
155 "setup": [
156 [
157 "$TC actions flush action mirred",
158 0,
159 1,
160 255
161 ],
162 "$TC actions add action mirred egress redirect index 15 dev lo"
163 ],
164 "cmdUnderTest": "$TC actions add action mirred egress mirror index 15 dev lo",
165 "expExitCode": "255",
166 "verifyCmd": "$TC actions list action mirred",
167 "matchPattern": "action order [0-9]*: mirred \\(.*to device lo\\).*index 15 ref",
168 "matchCount": "1",
169 "teardown": [
170 "$TC actions flush action mirred"
171 ]
172 },
173 {
174 "id": "a70e",
175 "name": "Delete mirred mirror action",
176 "category": [
177 "actions",
178 "mirred"
179 ],
180 "setup": [
181 [
182 "$TC actions flush action mirred",
183 0,
184 1,
185 255
186 ],
187 "$TC actions add action mirred egress mirror index 5 dev lo"
188 ],
189 "cmdUnderTest": "$TC actions del action mirred index 5",
190 "expExitCode": "0",
191 "verifyCmd": "$TC actions list action mirred",
192 "matchPattern": "action order [0-9]*: mirred \\(Egress Mirror to device lo\\).*index 5 ref",
193 "matchCount": "0",
194 "teardown": [
195 "$TC actions flush action mirred"
196 ]
197 },
198 {
199 "id": "3fb3",
200 "name": "Delete mirred redirect action",
201 "category": [
202 "actions",
203 "mirred"
204 ],
205 "setup": [
206 [
207 "$TC actions flush action mirred",
208 0,
209 1,
210 255
211 ],
212 "$TC actions add action mirred egress redirect index 5 dev lo"
213 ],
214 "cmdUnderTest": "$TC actions del action mirred index 5",
215 "expExitCode": "0",
216 "verifyCmd": "$TC actions list action mirred",
217 "matchPattern": "action order [0-9]*: mirred \\(Egress Redirect to device lo\\).*index 5 ref",
218 "matchCount": "0",
219 "teardown": [
220 "$TC actions flush action mirred"
221 ]
222 }
223]
diff --git a/tools/testing/selftests/tc-testing/tc-tests/actions/police.json b/tools/testing/selftests/tc-testing/tc-tests/actions/police.json
new file mode 100644
index 000000000000..0e602a3f9393
--- /dev/null
+++ b/tools/testing/selftests/tc-testing/tc-tests/actions/police.json
@@ -0,0 +1,527 @@
1[
2 {
3 "id": "49aa",
4 "name": "Add valid basic police action",
5 "category": [
6 "actions",
7 "police"
8 ],
9 "setup": [
10 [
11 "$TC actions flush action police",
12 0,
13 1,
14 255
15 ]
16 ],
17 "cmdUnderTest": "$TC actions add action police rate 1kbit burst 10k index 1",
18 "expExitCode": "0",
19 "verifyCmd": "$TC actions ls action police",
20 "matchPattern": "action order [0-9]*: police 0x1 rate 1Kbit burst 10Kb",
21 "matchCount": "1",
22 "teardown": [
23 "$TC actions flush action police"
24 ]
25 },
26 {
27 "id": "3abe",
28 "name": "Add police action with duplicate index",
29 "category": [
30 "actions",
31 "police"
32 ],
33 "setup": [
34 [
35 "$TC actions flush action police",
36 0,
37 1,
38 255
39 ],
40 "$TC actions add action police rate 4Mbit burst 120k index 9"
41 ],
42 "cmdUnderTest": "$TC actions add action police rate 8kbit burst 24k index 9",
43 "expExitCode": "255",
44 "verifyCmd": "$TC actions ls action police",
45 "matchPattern": "action order [0-9]*: police 0x9",
46 "matchCount": "1",
47 "teardown": [
48 "$TC actions flush action police"
49 ]
50 },
51 {
52 "id": "49fa",
53 "name": "Add valid police action with mtu",
54 "category": [
55 "actions",
56 "police"
57 ],
58 "setup": [
59 [
60 "$TC actions flush action police",
61 0,
62 1,
63 255
64 ]
65 ],
66 "cmdUnderTest": "$TC actions add action police rate 90kbit burst 10k mtu 1k index 98",
67 "expExitCode": "0",
68 "verifyCmd": "$TC actions get action police index 98",
69 "matchPattern": "action order [0-9]*: police 0x62 rate 90Kbit burst 10Kb mtu 1Kb",
70 "matchCount": "1",
71 "teardown": [
72 "$TC actions flush action police"
73 ]
74 },
75 {
76 "id": "7943",
77 "name": "Add valid police action with peakrate",
78 "category": [
79 "actions",
80 "police"
81 ],
82 "setup": [
83 [
84 "$TC actions flush action police",
85 0,
86 1,
87 255
88 ]
89 ],
90 "cmdUnderTest": "$TC actions add action police rate 90kbit burst 10k mtu 2kb peakrate 100kbit index 3",
91 "expExitCode": "0",
92 "verifyCmd": "$TC actions ls action police",
93 "matchPattern": "action order [0-9]*: police 0x3 rate 90Kbit burst 10Kb mtu 2Kb peakrate 100Kbit",
94 "matchCount": "1",
95 "teardown": [
96 "$TC actions flush action police"
97 ]
98 },
99 {
100 "id": "055e",
101 "name": "Add police action with peakrate and no mtu",
102 "category": [
103 "actions",
104 "police"
105 ],
106 "setup": [
107 [
108 "$TC actions flush action police",
109 0,
110 1,
111 255
112 ]
113 ],
114 "cmdUnderTest": "$TC actions add action police rate 5kbit burst 6kb peakrate 10kbit index 9",
115 "expExitCode": "255",
116 "verifyCmd": "$TC actions ls action police",
117 "matchPattern": "action order [0-9]*: police 0x9 rate 5Kb burst 10Kb",
118 "matchCount": "0",
119 "teardown": [
120 "$TC actions flush action police"
121 ]
122 },
123 {
124 "id": "f057",
125 "name": "Add police action with valid overhead",
126 "category": [
127 "actions",
128 "police"
129 ],
130 "setup": [
131 [
132 "$TC actions flush action police",
133 0,
134 1,
135 255
136 ]
137 ],
138 "cmdUnderTest": "$TC actions add action police rate 1mbit burst 100k overhead 64 index 64",
139 "expExitCode": "0",
140 "verifyCmd": "$TC actions get action police index 64",
141 "matchPattern": "action order [0-9]*: police 0x40 rate 1Mbit burst 100Kb mtu 2Kb action reclassify overhead 64b",
142 "matchCount": "1",
143 "teardown": [
144 "$TC actions flush action police"
145 ]
146 },
147 {
148 "id": "7ffb",
149 "name": "Add police action with ethernet linklayer type",
150 "category": [
151 "actions",
152 "police"
153 ],
154 "setup": [
155 [
156 "$TC actions flush action police",
157 0,
158 1,
159 255
160 ]
161 ],
162 "cmdUnderTest": "$TC actions add action police rate 2mbit burst 200k linklayer ethernet index 8",
163 "expExitCode": "0",
164 "verifyCmd": "$TC actions show action police",
165 "matchPattern": "action order [0-9]*: police 0x8 rate 2Mbit burst 200Kb mtu 2Kb action reclassify overhead 0b",
166 "matchCount": "1",
167 "teardown": [
168 "$TC actions flush action police"
169 ]
170 },
171 {
172 "id": "3dda",
173 "name": "Add police action with atm linklayer type",
174 "category": [
175 "actions",
176 "police"
177 ],
178 "setup": [
179 [
180 "$TC actions flush action police",
181 0,
182 1,
183 255
184 ]
185 ],
186 "cmdUnderTest": "$TC actions add action police rate 2mbit burst 200k linklayer atm index 8",
187 "expExitCode": "0",
188 "verifyCmd": "$TC actions show action police",
189 "matchPattern": "action order [0-9]*: police 0x8 rate 2Mbit burst 200Kb mtu 2Kb action reclassify overhead 0b linklayer atm",
190 "matchCount": "1",
191 "teardown": [
192 "$TC actions flush action police"
193 ]
194 },
195 {
196 "id": "551b",
197 "name": "Add police actions with conform-exceed control continue/drop",
198 "category": [
199 "actions",
200 "police"
201 ],
202 "setup": [
203 [
204 "$TC actions flush action police",
205 0,
206 1,
207 255
208 ]
209 ],
210 "cmdUnderTest": "$TC actions add action police rate 3mbit burst 250k conform-exceed continue/drop index 1",
211 "expExitCode": "0",
212 "verifyCmd": "$TC actions get action police index 1",
213 "matchPattern": "action order [0-9]*: police 0x1 rate 3Mbit burst 250Kb mtu 2Kb action continue/drop",
214 "matchCount": "1",
215 "teardown": [
216 "$TC actions flush action police"
217 ]
218 },
219 {
220 "id": "0c70",
221 "name": "Add police actions with conform-exceed control pass/reclassify",
222 "category": [
223 "actions",
224 "police"
225 ],
226 "setup": [
227 [
228 "$TC actions flush action police",
229 0,
230 1,
231 255
232 ]
233 ],
234 "cmdUnderTest": "$TC actions add action police rate 3mbit burst 250k conform-exceed pass/reclassify index 4",
235 "expExitCode": "0",
236 "verifyCmd": "$TC actions ls action police",
237 "matchPattern": "action order [0-9]*: police 0x4 rate 3Mbit burst 250Kb mtu 2Kb action pass/reclassify",
238 "matchCount": "1",
239 "teardown": [
240 "$TC actions flush action police"
241 ]
242 },
243 {
244 "id": "d946",
245 "name": "Add police actions with conform-exceed control pass/pipe",
246 "category": [
247 "actions",
248 "police"
249 ],
250 "setup": [
251 [
252 "$TC actions flush action police",
253 0,
254 1,
255 255
256 ]
257 ],
258 "cmdUnderTest": "$TC actions add action police rate 3mbit burst 250k conform-exceed pass/pipe index 5",
259 "expExitCode": "0",
260 "verifyCmd": "$TC actions ls action police",
261 "matchPattern": "action order [0-9]*: police 0x5 rate 3Mbit burst 250Kb mtu 2Kb action pass/pipe",
262 "matchCount": "1",
263 "teardown": [
264 "$TC actions flush action police"
265 ]
266 },
267 {
268 "id": "336e",
269 "name": "Delete police action",
270 "category": [
271 "actions",
272 "police"
273 ],
274 "setup": [
275 [
276 "$TC actions flush action police",
277 0,
278 1,
279 255
280 ],
281 "$TC actions add action police rate 5mbit burst 2m index 12"
282 ],
283 "cmdUnderTest": "$TC actions delete action police index 12",
284 "expExitCode": "0",
285 "verifyCmd": "$TC actions ls action police",
286 "matchPattern": "action order [0-9]*: police 0xc rate 5Mb burst 2Mb",
287 "matchCount": "0",
288 "teardown": [
289 "$TC actions flush action police"
290 ]
291 },
292 {
293 "id": "77fa",
294 "name": "Get single police action from many actions",
295 "category": [
296 "actions",
297 "police"
298 ],
299 "setup": [
300 [
301 "$TC actions flush action police",
302 0,
303 1,
304 255
305 ],
306 "$TC actions add action police rate 1mbit burst 100k index 1",
307 "$TC actions add action police rate 2mbit burst 200k index 2",
308 "$TC actions add action police rate 3mbit burst 300k index 3",
309 "$TC actions add action police rate 4mbit burst 400k index 4",
310 "$TC actions add action police rate 5mbit burst 500k index 5",
311 "$TC actions add action police rate 6mbit burst 600k index 6",
312 "$TC actions add action police rate 7mbit burst 700k index 7",
313 "$TC actions add action police rate 8mbit burst 800k index 8"
314 ],
315 "cmdUnderTest": "$TC actions get action police index 4",
316 "expExitCode": "0",
317 "verifyCmd": "$TC actions get action police index 4",
318 "matchPattern": "action order [0-9]*: police 0x4 rate 4Mbit burst 400Kb",
319 "matchCount": "1",
320 "teardown": [
321 "$TC actions flush action police"
322 ]
323 },
324 {
325 "id": "aa43",
326 "name": "Get single police action without specifying index",
327 "category": [
328 "actions",
329 "police"
330 ],
331 "setup": [
332 [
333 "$TC actions flush action police",
334 0,
335 1,
336 255
337 ],
338 "$TC actions add action police rate 1mbit burst 100k index 1"
339 ],
340 "cmdUnderTest": "$TC actions get action police",
341 "expExitCode": "255",
342 "verifyCmd": "$TC actions get action police",
343 "matchPattern": "action order [0-9]*: police",
344 "matchCount": "0",
345 "teardown": [
346 "$TC actions flush action police"
347 ]
348 },
349 {
350 "id": "858b",
351 "name": "List police actions",
352 "category": [
353 "actions",
354 "police"
355 ],
356 "setup": [
357 [
358 "$TC actions flush action police",
359 0,
360 1,
361 255
362 ],
363 "$TC actions add action police rate 1mbit burst 100k index 1",
364 "$TC actions add action police rate 2mbit burst 200k index 2",
365 "$TC actions add action police rate 3mbit burst 300k index 3",
366 "$TC actions add action police rate 4mbit burst 400k index 4",
367 "$TC actions add action police rate 5mbit burst 500k index 5",
368 "$TC actions add action police rate 6mbit burst 600k index 6",
369 "$TC actions add action police rate 7mbit burst 700k index 7",
370 "$TC actions add action police rate 8mbit burst 800k index 8"
371 ],
372 "cmdUnderTest": "$TC actions list action police",
373 "expExitCode": "0",
374 "verifyCmd": "$TC actions ls action police",
375 "matchPattern": "action order [0-9]*: police 0x[1-8] rate [1-8]Mbit burst [1-8]00Kb",
376 "matchCount": "8",
377 "teardown": [
378 "$TC actions flush action police"
379 ]
380 },
381 {
382 "id": "1c3a",
383 "name": "Flush police actions",
384 "category": [
385 "actions",
386 "police"
387 ],
388 "setup": [
389 "$TC actions add action police rate 1mbit burst 100k index 1",
390 "$TC actions add action police rate 2mbit burst 200k index 2",
391 "$TC actions add action police rate 3mbit burst 300k index 3",
392 "$TC actions add action police rate 4mbit burst 400k index 4",
393 "$TC actions add action police rate 5mbit burst 500k index 5",
394 "$TC actions add action police rate 6mbit burst 600k index 6",
395 "$TC actions add action police rate 7mbit burst 700k index 7",
396 "$TC actions add action police rate 8mbit burst 800k index 8"
397 ],
398 "cmdUnderTest": "$TC actions flush action police",
399 "expExitCode": "0",
400 "verifyCmd": "$TC actions ls action police",
401 "matchPattern": "action order [0-9]*: police",
402 "matchCount": "0",
403 "teardown": [
404 ""
405 ]
406 },
407 {
408 "id": "7326",
409 "name": "Add police action with control continue",
410 "category": [
411 "actions",
412 "police"
413 ],
414 "setup": [
415 [
416 "$TC actions flush action police",
417 0,
418 1,
419 255
420 ]
421 ],
422 "cmdUnderTest": "$TC actions add action police rate 7mbit burst 1m continue index 1",
423 "expExitCode": "0",
424 "verifyCmd": "$TC actions get action police index 1",
425 "matchPattern": "action order [0-9]*: police 0x1 rate 7Mbit burst 1024Kb mtu 2Kb action continue",
426 "matchCount": "1",
427 "teardown": [
428 "$TC actions flush action police"
429 ]
430 },
431 {
432 "id": "34fa",
433 "name": "Add police action with control drop",
434 "category": [
435 "actions",
436 "police"
437 ],
438 "setup": [
439 [
440 "$TC actions flush action police",
441 0,
442 1,
443 255
444 ]
445 ],
446 "cmdUnderTest": "$TC actions add action police rate 7mbit burst 1m drop index 1",
447 "expExitCode": "0",
448 "verifyCmd": "$TC actions ls action police",
449 "matchPattern": "action order [0-9]*: police 0x1 rate 7Mbit burst 1024Kb mtu 2Kb action drop",
450 "matchCount": "1",
451 "teardown": [
452 "$TC actions flush action police"
453 ]
454 },
455 {
456 "id": "8dd5",
457 "name": "Add police action with control ok",
458 "category": [
459 "actions",
460 "police"
461 ],
462 "setup": [
463 [
464 "$TC actions flush action police",
465 0,
466 1,
467 255
468 ]
469 ],
470 "cmdUnderTest": "$TC actions add action police rate 7mbit burst 1m ok index 1",
471 "expExitCode": "0",
472 "verifyCmd": "$TC actions ls action police",
473 "matchPattern": "action order [0-9]*: police 0x1 rate 7Mbit burst 1024Kb mtu 2Kb action pass",
474 "matchCount": "1",
475 "teardown": [
476 "$TC actions flush action police"
477 ]
478 },
479 {
480 "id": "b9d1",
481 "name": "Add police action with control reclassify",
482 "category": [
483 "actions",
484 "police"
485 ],
486 "setup": [
487 [
488 "$TC actions flush action police",
489 0,
490 1,
491 255
492 ]
493 ],
494 "cmdUnderTest": "$TC actions add action police rate 7mbit burst 1m reclassify index 1",
495 "expExitCode": "0",
496 "verifyCmd": "$TC actions get action police index 1",
497 "matchPattern": "action order [0-9]*: police 0x1 rate 7Mbit burst 1024Kb mtu 2Kb action reclassify",
498 "matchCount": "1",
499 "teardown": [
500 "$TC actions flush action police"
501 ]
502 },
503 {
504 "id": "c534",
505 "name": "Add police action with control pipe",
506 "category": [
507 "actions",
508 "police"
509 ],
510 "setup": [
511 [
512 "$TC actions flush action police",
513 0,
514 1,
515 255
516 ]
517 ],
518 "cmdUnderTest": "$TC actions add action police rate 7mbit burst 1m pipe index 1",
519 "expExitCode": "0",
520 "verifyCmd": "$TC actions ls action police",
521 "matchPattern": "action order [0-9]*: police 0x1 rate 7Mbit burst 1024Kb mtu 2Kb action pipe",
522 "matchCount": "1",
523 "teardown": [
524 "$TC actions flush action police"
525 ]
526 }
527]
diff --git a/tools/testing/selftests/tc-testing/tc-tests/actions/simple.json b/tools/testing/selftests/tc-testing/tc-tests/actions/simple.json
new file mode 100644
index 000000000000..e89a7aa4012d
--- /dev/null
+++ b/tools/testing/selftests/tc-testing/tc-tests/actions/simple.json
@@ -0,0 +1,130 @@
1[
2 {
3 "id": "b078",
4 "name": "Add simple action",
5 "category": [
6 "actions",
7 "simple"
8 ],
9 "setup": [
10 [
11 "$TC actions flush action simple",
12 0,
13 1,
14 255
15 ]
16 ],
17 "cmdUnderTest": "$TC actions add action simple sdata \"A triumph\" index 60",
18 "expExitCode": "0",
19 "verifyCmd": "$TC actions list action simple",
20 "matchPattern": "action order [0-9]*: Simple <A triumph>.*index 60 ref",
21 "matchCount": "1",
22 "teardown": [
23 "$TC actions flush action simple"
24 ]
25 },
26 {
27 "id": "6d4c",
28 "name": "Add simple action with duplicate index",
29 "category": [
30 "actions",
31 "simple"
32 ],
33 "setup": [
34 [
35 "$TC actions flush action simple",
36 0,
37 1,
38 255
39 ],
40 "$TC actions add action simple sdata \"Aruba\" index 4"
41 ],
42 "cmdUnderTest": "$TC actions add action simple sdata \"Jamaica\" index 4",
43 "expExitCode": "255",
44 "verifyCmd": "$TC actions list action simple",
45 "matchPattern": "action order [0-9]*: Simple <Jamaica>.*ref",
46 "matchCount": "0",
47 "teardown": [
48 "$TC actions flush action simple"
49 ]
50 },
51 {
52 "id": "2542",
53 "name": "List simple actions",
54 "category": [
55 "actions",
56 "simple"
57 ],
58 "setup": [
59 [
60 "$TC actions flush action simple",
61 0,
62 1,
63 255
64 ],
65 "$TC actions add action simple sdata \"Rock\"",
66 "$TC actions add action simple sdata \"Paper\"",
67 "$TC actions add action simple sdata \"Scissors\" index 98"
68 ],
69 "cmdUnderTest": "$TC actions list action simple",
70 "expExitCode": "0",
71 "verifyCmd": "$TC actions list action simple",
72 "matchPattern": "action order [0-9]*: Simple <[A-Z][a-z]*>",
73 "matchCount": "3",
74 "teardown": [
75 "$TC actions flush action simple"
76 ]
77 },
78 {
79 "id": "ea67",
80 "name": "Delete simple action",
81 "category": [
82 "actions",
83 "simple"
84 ],
85 "setup": [
86 [
87 "$TC actions flush action simple",
88 0,
89 1,
90 255
91 ],
92 "$TC actions add action simple sdata \"Blinkenlights\" index 1"
93 ],
94 "cmdUnderTest": "$TC actions delete action simple index 1",
95 "expExitCode": "0",
96 "verifyCmd": "$TC actions list action simple",
97 "matchPattern": "action order [0-9]*: Simple <Blinkenlights>.*index 1 ref",
98 "matchCount": "0",
99 "teardown": [
100 "$TC actions flush action simple"
101 ]
102 },
103 {
104 "id": "8ff1",
105 "name": "Flush simple actions",
106 "category": [
107 "actions",
108 "simple"
109 ],
110 "setup": [
111 [
112 "$TC actions flush action simple",
113 0,
114 1,
115 255
116 ],
117 "$TC actions add action simple sdata \"Kirk\"",
118 "$TC actions add action simple sdata \"Spock\" index 50",
119 "$TC actions add action simple sdata \"McCoy\" index 9"
120 ],
121 "cmdUnderTest": "$TC actions flush action simple",
122 "expExitCode": "0",
123 "verifyCmd": "$TC actions list action simple",
124 "matchPattern": "action order [0-9]*: Simple <[A-Z][a-z]*>",
125 "matchCount": "0",
126 "teardown": [
127 ""
128 ]
129 }
130]
diff --git a/tools/testing/selftests/tc-testing/tc-tests/actions/skbedit.json b/tools/testing/selftests/tc-testing/tc-tests/actions/skbedit.json
new file mode 100644
index 000000000000..99635ea4722e
--- /dev/null
+++ b/tools/testing/selftests/tc-testing/tc-tests/actions/skbedit.json
@@ -0,0 +1,320 @@
1[
2 {
3 "id": "6236",
4 "name": "Add skbedit action with valid mark",
5 "category": [
6 "actions",
7 "skbedit"
8 ],
9 "setup": [
10 [
11 "$TC actions flush action skbedit",
12 0,
13 1,
14 255
15 ]
16 ],
17 "cmdUnderTest": "$TC actions add action skbedit mark 1",
18 "expExitCode": "0",
19 "verifyCmd": "$TC actions list action skbedit",
20 "matchPattern": "action order [0-9]*: skbedit mark 1",
21 "matchCount": "1",
22 "teardown": [
23 "$TC actions flush action skbedit"
24 ]
25 },
26 {
27 "id": "407b",
28 "name": "Add skbedit action with invalid mark",
29 "category": [
30 "actions",
31 "skbedit"
32 ],
33 "setup": [
34 [
35 "$TC actions flush action skbedit",
36 0,
37 1,
38 255
39 ]
40 ],
41 "cmdUnderTest": "$TC actions add action skbedit mark 666777888999",
42 "expExitCode": "255",
43 "verifyCmd": "$TC actions list action skbedit",
44 "matchPattern": "action order [0-9]*: skbedit mark",
45 "matchCount": "0",
46 "teardown": [
47 "$TC actions flush action skbedit"
48 ]
49 },
50 {
51 "id": "081d",
52 "name": "Add skbedit action with priority",
53 "category": [
54 "actions",
55 "skbedit"
56 ],
57 "setup": [
58 [
59 "$TC actions flush action skbedit",
60 0,
61 1,
62 255
63 ]
64 ],
65 "cmdUnderTest": "$TC actions add action skbedit prio 99",
66 "expExitCode": "0",
67 "verifyCmd": "$TC actions list action skbedit",
68 "matchPattern": "action order [0-9]*: skbedit priority :99",
69 "matchCount": "1",
70 "teardown": [
71 "$TC actions flush action skbedit"
72 ]
73 },
74 {
75 "id": "cc37",
76 "name": "Add skbedit action with invalid priority",
77 "category": [
78 "actions",
79 "skbedit"
80 ],
81 "setup": [
82 [
83 "$TC actions flush action skbedit",
84 0,
85 1,
86 255
87 ]
88 ],
89 "cmdUnderTest": "$TC actions add action skbedit prio foo",
90 "expExitCode": "255",
91 "verifyCmd": "$TC actions list action skbedit",
92 "matchPattern": "action order [0-9]*: skbedit priority",
93 "matchCount": "0",
94 "teardown": [
95 "$TC actions flush action skbedit"
96 ]
97 },
98 {
99 "id": "3c95",
100 "name": "Add skbedit action with queue_mapping",
101 "category": [
102 "actions",
103 "skbedit"
104 ],
105 "setup": [
106 [
107 "$TC actions flush action skbedit",
108 0,
109 1,
110 255
111 ]
112 ],
113 "cmdUnderTest": "$TC actions add action skbedit queue_mapping 909",
114 "expExitCode": "0",
115 "verifyCmd": "$TC actions list action skbedit",
116 "matchPattern": "action order [0-9]*: skbedit queue_mapping 909",
117 "matchCount": "1",
118 "teardown": [
119 "$TC actions flush action skbedit"
120 ]
121 },
122 {
123 "id": "985c",
124 "name": "Add skbedit action with invalid queue_mapping",
125 "category": [
126 "actions",
127 "skbedit"
128 ],
129 "setup": [
130 [
131 "$TC actions flush action skbedit",
132 0,
133 1,
134 255
135 ]
136 ],
137 "cmdUnderTest": "$TC actions add action skbedit queue_mapping 67000",
138 "expExitCode": "255",
139 "verifyCmd": "$TC actions list action skbedit",
140 "matchPattern": "action order [0-9]*: skbedit queue_mapping",
141 "matchCount": "0",
142 "teardown": [
143 "$TC actions flush action skbedit"
144 ]
145 },
146 {
147 "id": "224f",
148 "name": "Add skbedit action with ptype host",
149 "category": [
150 "actions",
151 "skbedit"
152 ],
153 "setup": [
154 [
155 "$TC actions flush action skbedit",
156 0,
157 1,
158 255
159 ]
160 ],
161 "cmdUnderTest": "$TC actions add action skbedit ptype host",
162 "expExitCode": "0",
163 "verifyCmd": "$TC actions list action skbedit",
164 "matchPattern": "action order [0-9]*: skbedit ptype host",
165 "matchCount": "1",
166 "teardown": [
167 "$TC actions flush action skbedit"
168 ]
169 },
170 {
171 "id": "d1a3",
172 "name": "Add skbedit action with ptype otherhost",
173 "category": [
174 "actions",
175 "skbedit"
176 ],
177 "setup": [
178 [
179 "$TC actions flush action skbedit",
180 0,
181 1,
182 255
183 ]
184 ],
185 "cmdUnderTest": "$TC actions add action skbedit ptype otherhost",
186 "expExitCode": "0",
187 "verifyCmd": "$TC actions list action skbedit",
188 "matchPattern": "action order [0-9]*: skbedit ptype otherhost",
189 "matchCount": "1",
190 "teardown": [
191 "$TC actions flush action skbedit"
192 ]
193 },
194 {
195 "id": "b9c6",
196 "name": "Add skbedit action with invalid ptype",
197 "category": [
198 "actions",
199 "skbedit"
200 ],
201 "setup": [
202 [
203 "$TC actions flush action skbedit",
204 0,
205 1,
206 255
207 ]
208 ],
209 "cmdUnderTest": "$TC actions add action skbedit ptype openair",
210 "expExitCode": "255",
211 "verifyCmd": "$TC actions list action skbedit",
212 "matchPattern": "action order [0-9]*: skbedit ptype openair",
213 "matchCount": "0",
214 "teardown": [
215 "$TC actions flush action skbedit"
216 ]
217 },
218 {
219 "id": "5172",
220 "name": "List skbedit actions",
221 "category": [
222 "actions",
223 "skbedit"
224 ],
225 "setup": [
226 [
227 "$TC actions flush action skbedit",
228 0,
229 1,
230 255
231 ],
232 "$TC actions add action skbedit ptype otherhost",
233 "$TC actions add action skbedit ptype broadcast",
234 "$TC actions add action skbedit mark 59",
235 "$TC actions add action skbedit mark 409"
236 ],
237 "cmdUnderTest": "$TC actions list action skbedit",
238 "expExitCode": "0",
239 "verifyCmd": "$TC actions list action skbedit",
240 "matchPattern": "action order [0-9]*: skbedit",
241 "matchCount": "4",
242 "teardown": [
243 "$TC actions flush action skbedit"
244 ]
245 },
246 {
247 "id": "a6d6",
248 "name": "Add skbedit action with index",
249 "category": [
250 "actions",
251 "skbedit"
252 ],
253 "setup": [
254 [
255 "$TC actions flush action skbedit",
256 0,
257 1,
258 255
259 ]
260 ],
261 "cmdUnderTest": "$TC actions add action skbedit mark 808 index 4040404040",
262 "expExitCode": "0",
263 "verifyCmd": "$TC actions list action skbedit",
264 "matchPattern": "index 4040404040",
265 "matchCount": "1",
266 "teardown": [
267 "$TC actions flush action skbedit"
268 ]
269 },
270 {
271 "id": "38f3",
272 "name": "Delete skbedit action",
273 "category": [
274 "actions",
275 "skbedit"
276 ],
277 "setup": [
278 [
279 "$TC actions flush action skbedit",
280 0,
281 1,
282 255
283 ],
284 "$TC actions add action skbedit mark 42 index 9009"
285 ],
286 "cmdUnderTest": "$TC actions del action skbedit index 9009",
287 "expExitCode": "0",
288 "verifyCmd": "$TC actions list action skbedit",
289 "matchPattern": "action order [0-9]*: skbedit mark 42",
290 "matchCount": "0",
291 "teardown": [
292 "$TC actions flush action skbedit"
293 ]
294 },
295 {
296 "id": "ce97",
297 "name": "Flush skbedit actions",
298 "category": [
299 "actions",
300 "skbedit"
301 ],
302 "setup": [
303 "$TC actions add action skbedit mark 500",
304 "$TC actions add action skbedit mark 501",
305 "$TC actions add action skbedit mark 502",
306 "$TC actions add action skbedit mark 503",
307 "$TC actions add action skbedit mark 504",
308 "$TC actions add action skbedit mark 505",
309 "$TC actions add action skbedit mark 506"
310 ],
311 "cmdUnderTest": "$TC actions flush action skbedit",
312 "expExitCode": "0",
313 "verifyCmd": "$TC actions list action skbedit",
314 "matchPattern": "action order [0-9]*: skbedit",
315 "matchCount": "0",
316 "teardown": [
317 "$TC actions flush action skbedit"
318 ]
319 }
320]
diff --git a/tools/testing/selftests/tc-testing/tc-tests/actions/skbmod.json b/tools/testing/selftests/tc-testing/tc-tests/actions/skbmod.json
new file mode 100644
index 000000000000..e34075059c26
--- /dev/null
+++ b/tools/testing/selftests/tc-testing/tc-tests/actions/skbmod.json
@@ -0,0 +1,372 @@
1[
2 {
3 "id": "7d50",
4 "name": "Add skbmod action to set destination mac",
5 "category": [
6 "actions",
7 "skbmod"
8 ],
9 "setup": [
10 [
11 "$TC actions flush action skbmod",
12 0,
13 1,
14 255
15 ]
16 ],
17 "cmdUnderTest": "$TC actions add action skbmod set dmac 11:22:33:44:55:66 index 5",
18 "expExitCode": "0",
19 "verifyCmd": "$TC actions ls action skbmod",
20 "matchPattern": "action order [0-9]*: skbmod pipe set dmac 11:22:33:44:55:66\\s+index 5",
21 "matchCount": "1",
22 "teardown": [
23 "$TC actions flush action skbmod"
24 ]
25 },
26 {
27 "id": "9b29",
28 "name": "Add skbmod action to set source mac",
29 "category": [
30 "actions",
31 "skbmod"
32 ],
33 "setup": [
34 [
35 "$TC actions flush action skbmod",
36 0,
37 1,
38 255
39 ]
40 ],
41 "cmdUnderTest": "$TC actions add action skbmod set smac 77:88:99:AA:BB:CC index 7",
42 "expExitCode": "0",
43 "verifyCmd": "$TC actions get action skbmod index 7",
44 "matchPattern": "action order [0-9]*: skbmod pipe set smac 77:88:99:aa:bb:cc\\s+index 7",
45 "matchCount": "1",
46 "teardown": [
47 "$TC actions flush action skbmod"
48 ]
49 },
50 {
51 "id": "1724",
52 "name": "Add skbmod action with invalid mac",
53 "category": [
54 "actions",
55 "skbmod"
56 ],
57 "setup": [
58 [
59 "$TC actions flush action skbmod",
60 0,
61 1,
62 255
63 ]
64 ],
65 "cmdUnderTest": "$TC actions add action skbmod set smac 00:44:55:44:55",
66 "expExitCode": "255",
67 "verifyCmd": "$TC actions ls action skbmod",
68 "matchPattern": "action order [0-9]*: skbmod pipe set smac 00:44:55:44:55",
69 "matchCount": "0",
70 "teardown": [
71 "$TC actions flush action skbmod"
72 ]
73 },
74 {
75 "id": "3cf1",
76 "name": "Add skbmod action with valid etype",
77 "category": [
78 "actions",
79 "skbmod"
80 ],
81 "setup": [
82 [
83 "$TC actions flush action skbmod",
84 0,
85 1,
86 255
87 ]
88 ],
89 "cmdUnderTest": "$TC actions add action skbmod set etype 0xfefe",
90 "expExitCode": "0",
91 "verifyCmd": "$TC actions ls action skbmod",
92 "matchPattern": "action order [0-9]*: skbmod pipe set etype 0xFEFE",
93 "matchCount": "1",
94 "teardown": [
95 "$TC actions flush action skbmod"
96 ]
97 },
98 {
99 "id": "a749",
100 "name": "Add skbmod action with invalid etype",
101 "category": [
102 "actions",
103 "skbmod"
104 ],
105 "setup": [
106 [
107 "$TC actions flush action skbmod",
108 0,
109 1,
110 255
111 ]
112 ],
113 "cmdUnderTest": "$TC actions add action skbmod set etype 0xfefef",
114 "expExitCode": "255",
115 "verifyCmd": "$TC actions ls action skbmod",
116 "matchPattern": "action order [0-9]*: skbmod pipe set etype 0xFEFEF",
117 "matchCount": "0",
118 "teardown": [
119 "$TC actions flush action skbmod"
120 ]
121 },
122 {
123 "id": "bfe6",
124 "name": "Add skbmod action to swap mac",
125 "category": [
126 "actions",
127 "skbmod"
128 ],
129 "setup": [
130 [
131 "$TC actions flush action skbmod",
132 0,
133 1,
134 255
135 ]
136 ],
137 "cmdUnderTest": "$TC actions add action skbmod swap mac",
138 "expExitCode": "0",
139 "verifyCmd": "$TC actions get action skbmod index 1",
140 "matchPattern": "action order [0-9]*: skbmod pipe swap mac",
141 "matchCount": "1",
142 "teardown": [
143 "$TC actions flush action skbmod"
144 ]
145 },
146 {
147 "id": "839b",
148 "name": "Add skbmod action with control pipe",
149 "category": [
150 "actions",
151 "skbmod"
152 ],
153 "setup": [
154 [
155 "$TC actions flush action skbmod",
156 0,
157 1,
158 255
159 ]
160 ],
161 "cmdUnderTest": "$TC actions add action skbmod swap mac pipe",
162 "expExitCode": "0",
163 "verifyCmd": "$TC actions ls action skbmod",
164 "matchPattern": "action order [0-9]*: skbmod pipe swap mac",
165 "matchCount": "1",
166 "teardown": [
167 "$TC actions flush action skbmod"
168 ]
169 },
170 {
171 "id": "c167",
172 "name": "Add skbmod action with control reclassify",
173 "category": [
174 "actions",
175 "skbmod"
176 ],
177 "setup": [
178 [
179 "$TC actions flush action skbmod",
180 0,
181 1,
182 255
183 ]
184 ],
185 "cmdUnderTest": "$TC actions add action skbmod set etype 0xbeef reclassify",
186 "expExitCode": "0",
187 "verifyCmd": "$TC actions ls action skbmod",
188 "matchPattern": "action order [0-9]*: skbmod reclassify set etype 0xBEEF",
189 "matchCount": "1",
190 "teardown": [
191 "$TC actions flush action skbmod"
192 ]
193 },
194 {
195 "id": "0c2f",
196 "name": "Add skbmod action with control drop",
197 "category": [
198 "actions",
199 "skbmod"
200 ],
201 "setup": [
202 [
203 "$TC actions flush action skbmod",
204 0,
205 1,
206 255
207 ]
208 ],
209 "cmdUnderTest": "$TC actions add action skbmod set etype 0x0001 drop",
210 "expExitCode": "0",
211 "verifyCmd": "$TC actions get action skbmod index 1",
212 "matchPattern": "action order [0-9]*: skbmod drop set etype 0x1",
213 "matchCount": "1",
214 "teardown": [
215 "$TC actions flush action skbmod"
216 ]
217 },
218 {
219 "id": "d113",
220 "name": "Add skbmod action with control continue",
221 "category": [
222 "actions",
223 "skbmod"
224 ],
225 "setup": [
226 [
227 "$TC actions flush action skbmod",
228 0,
229 1,
230 255
231 ]
232 ],
233 "cmdUnderTest": "$TC actions add action skbmod set etype 0x1 continue",
234 "expExitCode": "0",
235 "verifyCmd": "$TC actions ls action skbmod",
236 "matchPattern": "action order [0-9]*: skbmod continue set etype 0x1",
237 "matchCount": "1",
238 "teardown": [
239 "$TC actions flush action skbmod"
240 ]
241 },
242 {
243 "id": "7242",
244 "name": "Add skbmod action with control pass",
245 "category": [
246 "actions",
247 "skbmod"
248 ],
249 "setup": [
250 [
251 "$TC actions flush action skbmod",
252 0,
253 1,
254 255
255 ]
256 ],
257 "cmdUnderTest": "$TC actions add action skbmod set smac 00:00:00:00:00:01 pass",
258 "expExitCode": "0",
259 "verifyCmd": "$TC actions ls action skbmod",
260 "matchPattern": "action order [0-9]*: skbmod pass set smac 00:00:00:00:00:01",
261 "matchCount": "1",
262 "teardown": [
263 "$TC actions flush action skbmod"
264 ]
265 },
266 {
267 "id": "58cb",
268 "name": "List skbmod actions",
269 "category": [
270 "actions",
271 "skbmod"
272 ],
273 "setup": [
274 [
275 "$TC actions flush action skbmod",
276 0,
277 1,
278 255
279 ],
280 "$TC actions add action skbmod set etype 0x0001",
281 "$TC actions add action skbmod set etype 0x0011",
282 "$TC actions add action skbmod set etype 0x0021",
283 "$TC actions add action skbmod set etype 0x0031",
284 "$TC actions add action skbmod set etype 0x0041"
285 ],
286 "cmdUnderTest": "$TC actions ls action skbmod",
287 "expExitCode": "0",
288 "verifyCmd": "$TC actions ls action skbmod",
289 "matchPattern": "action order [0-9]*: skbmod",
290 "matchCount": "5",
291 "teardown": [
292 "$TC actions flush action skbmod"
293 ]
294 },
295 {
296 "id": "9aa8",
297 "name": "Get a single skbmod action from a list",
298 "category": [
299 "actions",
300 "skbmod"
301 ],
302 "setup": [
303 [
304 "$TC actions flush action skbmod",
305 0,
306 1,
307 255
308 ],
309 "$TC actions add action skbmod set etype 0x0001",
310 "$TC actions add action skbmod set etype 0x0011",
311 "$TC actions add action skbmod set etype 0x0021",
312 "$TC actions add action skbmod set etype 0x0031",
313 "$TC actions add action skbmod set etype 0x0041"
314 ],
315 "cmdUnderTest": "$TC actions ls action skbmod",
316 "expExitCode": "0",
317 "verifyCmd": "$TC actions get action skbmod index 4",
318 "matchPattern": "action order [0-9]*: skbmod pipe set etype 0x0031",
319 "matchCount": "1",
320 "teardown": [
321 "$TC actions flush action skbmod"
322 ]
323 },
324 {
325 "id": "e93a",
326 "name": "Delete an skbmod action",
327 "category": [
328 "actions",
329 "skbmod"
330 ],
331 "setup": [
332 [
333 "$TC actions flush action skbmod",
334 0,
335 1,
336 255
337 ],
338 "$TC actions add action skbmod set etype 0x1111 index 909"
339 ],
340 "cmdUnderTest": "$TC actions del action skbmod index 909",
341 "expExitCode": "0",
342 "verifyCmd": "$TC actions ls action skbmod",
343 "matchPattern": "action order [0-9]*: skbmod pipe set etype 0x1111\\s+index 909",
344 "matchCount": "0",
345 "teardown": [
346 "$TC actions flush action skbmod"
347 ]
348 },
349 {
350 "id": "40c2",
351 "name": "Flush skbmod actions",
352 "category": [
353 "actions",
354 "skbmod"
355 ],
356 "setup": [
357 "$TC actions add action skbmod set etype 0x0001",
358 "$TC actions add action skbmod set etype 0x0011",
359 "$TC actions add action skbmod set etype 0x0021",
360 "$TC actions add action skbmod set etype 0x0031",
361 "$TC actions add action skbmod set etype 0x0041"
362 ],
363 "cmdUnderTest": "$TC actions flush action skbmod",
364 "expExitCode": "0",
365 "verifyCmd": "$TC actions ls action skbmod",
366 "matchPattern": "action order [0-9]*: skbmod",
367 "matchCount": "0",
368 "teardown": [
369 "$TC actions flush action skbmod"
370 ]
371 }
372]
diff --git a/tools/testing/selftests/tc-testing/tc-tests/actions/tests.json b/tools/testing/selftests/tc-testing/tc-tests/actions/tests.json
deleted file mode 100644
index 6973bdc5b5bf..000000000000
--- a/tools/testing/selftests/tc-testing/tc-tests/actions/tests.json
+++ /dev/null
@@ -1,1165 +0,0 @@
1[
2 {
3 "id": "e89a",
4 "name": "Add valid pass action",
5 "category": [
6 "actions",
7 "gact"
8 ],
9 "setup": [
10 [
11 "$TC actions flush action gact",
12 0,
13 1,
14 255
15 ]
16 ],
17 "cmdUnderTest": "$TC actions add action pass index 8",
18 "expExitCode": "0",
19 "verifyCmd": "$TC actions list action gact",
20 "matchPattern": "action order [0-9]*: gact action pass.*index 8 ref",
21 "matchCount": "1",
22 "teardown": [
23 "$TC actions flush action gact"
24 ]
25 },
26 {
27 "id": "a02c",
28 "name": "Add valid pipe action",
29 "category": [
30 "actions",
31 "gact"
32 ],
33 "setup": [
34 [
35 "$TC actions flush action gact",
36 0,
37 1,
38 255
39 ]
40 ],
41 "cmdUnderTest": "$TC actions add action pipe index 6",
42 "expExitCode": "0",
43 "verifyCmd": "$TC actions list action gact",
44 "matchPattern": "action order [0-9]*: gact action pipe.*index 6 ref",
45 "matchCount": "1",
46 "teardown": [
47 "$TC actions flush action gact"
48 ]
49 },
50 {
51 "id": "feef",
52 "name": "Add valid reclassify action",
53 "category": [
54 "actions",
55 "gact"
56 ],
57 "setup": [
58 [
59 "$TC actions flush action gact",
60 0,
61 1,
62 255
63 ]
64 ],
65 "cmdUnderTest": "$TC actions add action reclassify index 5",
66 "expExitCode": "0",
67 "verifyCmd": "$TC actions list action gact",
68 "matchPattern": "action order [0-9]*: gact action reclassify.*index 5 ref",
69 "matchCount": "1",
70 "teardown": [
71 "$TC actions flush action gact"
72 ]
73 },
74 {
75 "id": "8a7a",
76 "name": "Add valid drop action",
77 "category": [
78 "actions",
79 "gact"
80 ],
81 "setup": [
82 [
83 "$TC actions flush action gact",
84 0,
85 1,
86 255
87 ]
88 ],
89 "cmdUnderTest": "$TC actions add action drop index 30",
90 "expExitCode": "0",
91 "verifyCmd": "$TC actions list action gact",
92 "matchPattern": "action order [0-9]*: gact action drop.*index 30 ref",
93 "matchCount": "1",
94 "teardown": [
95 "$TC actions flush action gact"
96 ]
97 },
98 {
99 "id": "9a52",
100 "name": "Add valid continue action",
101 "category": [
102 "actions",
103 "gact"
104 ],
105 "setup": [
106 [
107 "$TC actions flush action gact",
108 0,
109 1,
110 255
111 ]
112 ],
113 "cmdUnderTest": "$TC actions add action continue index 432",
114 "expExitCode": "0",
115 "verifyCmd": "$TC actions list action gact",
116 "matchPattern": "action order [0-9]*: gact action continue.*index 432 ref",
117 "matchCount": "1",
118 "teardown": [
119 "$TC actions flush action gact"
120 ]
121 },
122 {
123 "id": "d700",
124 "name": "Add invalid action",
125 "category": [
126 "actions",
127 "gact"
128 ],
129 "setup": [
130 [
131 "$TC actions flush action gact",
132 0,
133 1,
134 255
135 ]
136 ],
137 "cmdUnderTest": "$TC actions add action pump index 386",
138 "expExitCode": "255",
139 "verifyCmd": "$TC actions list action gact",
140 "matchPattern": "action order [0-9]*: gact action.*index 386 ref",
141 "matchCount": "0",
142 "teardown": [
143 "$TC actions flush action gact"
144 ]
145 },
146 {
147 "id": "9215",
148 "name": "Add action with duplicate index",
149 "category": [
150 "actions",
151 "gact"
152 ],
153 "setup": [
154 [
155 "$TC actions flush action gact",
156 0,
157 1,
158 255
159 ],
160 "$TC actions add action pipe index 15"
161 ],
162 "cmdUnderTest": "$TC actions add action drop index 15",
163 "expExitCode": "255",
164 "verifyCmd": "$TC actions list action gact",
165 "matchPattern": "action order [0-9]*: gact action drop.*index 15 ref",
166 "matchCount": "0",
167 "teardown": [
168 "$TC actions flush action gact"
169 ]
170 },
171 {
172 "id": "798e",
173 "name": "Add action with index exceeding 32-bit maximum",
174 "category": [
175 "actions",
176 "gact"
177 ],
178 "setup": [
179 [
180 "$TC actions flush action gact",
181 0,
182 1,
183 255
184 ]
185 ],
186 "cmdUnderTest": "$TC actions add action drop index 4294967296",
187 "expExitCode": "255",
188 "verifyCmd": "actions list action gact",
189 "matchPattern": "action order [0-9]*: gact action drop.*index 4294967296 ref",
190 "matchCount": "0",
191 "teardown": [
192 "$TC actions flush action gact"
193 ]
194 },
195 {
196 "id": "22be",
197 "name": "Add action with index at 32-bit maximum",
198 "category": [
199 "actions",
200 "gact"
201 ],
202 "setup": [
203 [
204 "$TC actions flush action gact",
205 0,
206 1,
207 255
208 ]
209 ],
210 "cmdUnderTest": "$TC actions add action drop index 4294967295",
211 "expExitCode": "0",
212 "verifyCmd": "$TC actions list action gact",
213 "matchPattern": "action order [0-9]*: gact action drop.*index 4294967295 ref",
214 "matchCount": "1",
215 "teardown": [
216 "$TC actions flush action gact"
217 ]
218 },
219 {
220 "id": "ac2a",
221 "name": "List actions",
222 "category": [
223 "actions",
224 "gact"
225 ],
226 "setup": [
227 [
228 "$TC actions flush action gact",
229 0,
230 1,
231 255
232 ],
233 "$TC actions add action reclassify index 101",
234 "$TC actions add action reclassify index 102",
235 "$TC actions add action reclassify index 103",
236 "$TC actions add action reclassify index 104",
237 "$TC actions add action reclassify index 105"
238 ],
239 "cmdUnderTest": "$TC actions list action gact",
240 "expExitCode": "0",
241 "verifyCmd": "$TC actions list action gact",
242 "matchPattern": "action order [0-9]*: gact action reclassify",
243 "matchCount": "5",
244 "teardown": [
245 "$TC actions flush action gact"
246 ]
247 },
248 {
249 "id": "63ec",
250 "name": "Delete pass action",
251 "category": [
252 "actions",
253 "gact"
254 ],
255 "setup": [
256 [
257 "$TC actions flush action gact",
258 0,
259 1,
260 255
261 ],
262 "$TC actions add action pass index 1"
263 ],
264 "cmdUnderTest": "$TC actions del action gact index 1",
265 "expExitCode": "0",
266 "verifyCmd": "$TC actions list action gact",
267 "matchPattern": "action order [0-9]*: gact action pass.*index 1 ref",
268 "matchCount": "0",
269 "teardown": [
270 "$TC actions flush action gact"
271 ]
272 },
273 {
274 "id": "46be",
275 "name": "Delete pipe action",
276 "category": [
277 "actions",
278 "gact"
279 ],
280 "setup": [
281 [
282 "$TC actions flush action gact",
283 0,
284 1,
285 255
286 ],
287 "$TC actions add action pipe index 9"
288 ],
289 "cmdUnderTest": "$TC actions del action gact index 9",
290 "expExitCode": "0",
291 "verifyCmd": "$TC actions list action gact",
292 "matchPattern": "action order [0-9]*: gact action pipe.*index 9 ref",
293 "matchCount": "0",
294 "teardown": [
295 "$TC actions flush action gact"
296 ]
297 },
298 {
299 "id": "2e08",
300 "name": "Delete reclassify action",
301 "category": [
302 "actions",
303 "gact"
304 ],
305 "setup": [
306 [
307 "$TC actions flush action gact",
308 0,
309 1,
310 255
311 ],
312 "$TC actions add action reclassify index 65536"
313 ],
314 "cmdUnderTest": "$TC actions del action gact index 65536",
315 "expExitCode": "0",
316 "verifyCmd": "$TC actions list action gact",
317 "matchPattern": "action order [0-9]*: gact action reclassify.*index 65536 ref",
318 "matchCount": "0",
319 "teardown": [
320 "$TC actions flush action gact"
321 ]
322 },
323 {
324 "id": "99c4",
325 "name": "Delete drop action",
326 "category": [
327 "actions",
328 "gact"
329 ],
330 "setup": [
331 [
332 "$TC actions flush action gact",
333 0,
334 1,
335 255
336 ],
337 "$TC actions add action drop index 16"
338 ],
339 "cmdUnderTest": "$TC actions del action gact index 16",
340 "expExitCode": "0",
341 "verifyCmd": "$TC actions list action gact",
342 "matchPattern": "action order [0-9]*: gact action drop.*index 16 ref",
343 "matchCount": "0",
344 "teardown": [
345 "$TC actions flush action gact"
346 ]
347 },
348 {
349 "id": "fb6b",
350 "name": "Delete continue action",
351 "category": [
352 "actions",
353 "gact"
354 ],
355 "setup": [
356 [
357 "$TC actions flush action gact",
358 0,
359 1,
360 255
361 ],
362 "$TC actions add action continue index 32"
363 ],
364 "cmdUnderTest": "$TC actions del action gact index 32",
365 "expExitCode": "0",
366 "verifyCmd": "actions list action gact",
367 "matchPattern": "action order [0-9]*: gact action continue.*index 32 ref",
368 "matchCount": "0",
369 "teardown": [
370 "$TC actions flush action gact"
371 ]
372 },
373 {
374 "id": "0eb3",
375 "name": "Delete non-existent action",
376 "category": [
377 "actions",
378 "gact"
379 ],
380 "setup": [
381 [
382 "$TC actions flush action gact",
383 0,
384 1,
385 255
386 ]
387 ],
388 "cmdUnderTest": "$TC actions del action gact index 2",
389 "expExitCode": "255",
390 "verifyCmd": "$TC actions list action gact",
391 "matchPattern": "action order [0-9]*: gact action",
392 "matchCount": "0",
393 "teardown": [
394 "$TC actions flush action gact"
395 ]
396 },
397 {
398 "id": "5124",
399 "name": "Add mirred mirror to egress action",
400 "category": [
401 "actions",
402 "mirred"
403 ],
404 "setup": [
405 [
406 "$TC actions flush action mirred",
407 0,
408 1,
409 255
410 ]
411 ],
412 "cmdUnderTest": "$TC actions add action mirred egress mirror index 1 dev lo",
413 "expExitCode": "0",
414 "verifyCmd": "$TC actions list action mirred",
415 "matchPattern": "action order [0-9]*: mirred \\(Egress Mirror to device lo\\).*index 1 ref",
416 "matchCount": "1",
417 "teardown": [
418 "$TC actions flush action mirred"
419 ]
420 },
421 {
422 "id": "6fb4",
423 "name": "Add mirred redirect to egress action",
424 "category": [
425 "actions",
426 "mirred"
427 ],
428 "setup": [
429 [
430 "$TC actions flush action mirred",
431 0,
432 1,
433 255
434 ]
435 ],
436 "cmdUnderTest": "$TC actions add action mirred egress redirect index 2 dev lo action pipe",
437 "expExitCode": "0",
438 "verifyCmd": "$TC actions list action mirred",
439 "matchPattern": "action order [0-9]*: mirred \\(Egress Redirect to device lo\\).*index 2 ref",
440 "matchCount": "1",
441 "teardown": [
442 "$TC actions flush action mirred"
443 ]
444 },
445 {
446 "id": "ba38",
447 "name": "Get mirred actions",
448 "category": [
449 "actions",
450 "mirred"
451 ],
452 "setup": [
453 [
454 "$TC actions flush action mirred",
455 0,
456 1,
457 255
458 ],
459 "$TC actions add action mirred egress mirror index 1 dev lo",
460 "$TC actions add action mirred egress redirect index 2 dev lo"
461 ],
462 "cmdUnderTest": "$TC actions show action mirred",
463 "expExitCode": "0",
464 "verifyCmd": "$TC actions list action mirred",
465 "matchPattern": "[Mirror|Redirect] to device lo",
466 "matchCount": "2",
467 "teardown": [
468 "$TC actions flush action mirred"
469 ]
470 },
471 {
472 "id": "d7c0",
473 "name": "Add invalid mirred direction",
474 "category": [
475 "actions",
476 "mirred"
477 ],
478 "setup": [
479 [
480 "$TC actions flush action mirred",
481 0,
482 1,
483 255
484 ]
485 ],
486 "cmdUnderTest": "$TC actions add action mirred inbound mirror index 20 dev lo",
487 "expExitCode": "255",
488 "verifyCmd": "$TC actions list action mirred",
489 "matchPattern": "action order [0-9]*: mirred \\(.*to device lo\\).*index 20 ref",
490 "matchCount": "0",
491 "teardown": [
492 "$TC actions flush action mirred"
493 ]
494 },
495 {
496 "id": "e213",
497 "name": "Add invalid mirred action",
498 "category": [
499 "actions",
500 "mirred"
501 ],
502 "setup": [
503 [
504 "$TC actions flush action mirred",
505 0,
506 1,
507 255
508 ]
509 ],
510 "cmdUnderTest": "$TC actions add action mirred egress remirror index 20 dev lo",
511 "expExitCode": "255",
512 "verifyCmd": "$TC actions list action mirred",
513 "matchPattern": "action order [0-9]*: mirred \\(Egress.*to device lo\\).*index 20 ref",
514 "matchCount": "0",
515 "teardown": [
516 "$TC actions flush action mirred"
517 ]
518 },
519 {
520 "id": "2d89",
521 "name": "Add mirred action with invalid device",
522 "category": [
523 "actions",
524 "mirred"
525 ],
526 "setup": [
527 [
528 "$TC actions flush action mirred",
529 0,
530 1,
531 255
532 ]
533 ],
534 "cmdUnderTest": "$TC actions add action mirred egress mirror index 20 dev eltoh",
535 "expExitCode": "255",
536 "verifyCmd": "$TC actions list action mirred",
537 "matchPattern": "action order [0-9]*: mirred \\(.*to device eltoh\\).*index 20 ref",
538 "matchCount": "0",
539 "teardown": [
540 "$TC actions flush action mirred"
541 ]
542 },
543 {
544 "id": "300b",
545 "name": "Add mirred action with duplicate index",
546 "category": [
547 "actions",
548 "mirred"
549 ],
550 "setup": [
551 [
552 "$TC actions flush action mirred",
553 0,
554 1,
555 255
556 ],
557 "$TC actions add action mirred egress redirect index 15 dev lo"
558 ],
559 "cmdUnderTest": "$TC actions add action mirred egress mirror index 15 dev lo",
560 "expExitCode": "255",
561 "verifyCmd": "$TC actions list action mirred",
562 "matchPattern": "action order [0-9]*: mirred \\(.*to device lo\\).*index 15 ref",
563 "matchCount": "1",
564 "teardown": [
565 "$TC actions flush action mirred"
566 ]
567 },
568 {
569 "id": "a70e",
570 "name": "Delete mirred mirror action",
571 "category": [
572 "actions",
573 "mirred"
574 ],
575 "setup": [
576 [
577 "$TC actions flush action mirred",
578 0,
579 1,
580 255
581 ],
582 "$TC actions add action mirred egress mirror index 5 dev lo"
583 ],
584 "cmdUnderTest": "$TC actions del action mirred index 5",
585 "expExitCode": "0",
586 "verifyCmd": "$TC actions list action mirred",
587 "matchPattern": "action order [0-9]*: mirred \\(Egress Mirror to device lo\\).*index 5 ref",
588 "matchCount": "0",
589 "teardown": [
590 "$TC actions flush action mirred"
591 ]
592 },
593 {
594 "id": "3fb3",
595 "name": "Delete mirred redirect action",
596 "category": [
597 "actions",
598 "mirred"
599 ],
600 "setup": [
601 [
602 "$TC actions flush action mirred",
603 0,
604 1,
605 255
606 ],
607 "$TC actions add action mirred egress redirect index 5 dev lo"
608 ],
609 "cmdUnderTest": "$TC actions del action mirred index 5",
610 "expExitCode": "0",
611 "verifyCmd": "$TC actions list action mirred",
612 "matchPattern": "action order [0-9]*: mirred \\(Egress Redirect to device lo\\).*index 5 ref",
613 "matchCount": "0",
614 "teardown": [
615 "$TC actions flush action mirred"
616 ]
617 },
618 {
619 "id": "b078",
620 "name": "Add simple action",
621 "category": [
622 "actions",
623 "simple"
624 ],
625 "setup": [
626 [
627 "$TC actions flush action simple",
628 0,
629 1,
630 255
631 ]
632 ],
633 "cmdUnderTest": "$TC actions add action simple sdata \"A triumph\" index 60",
634 "expExitCode": "0",
635 "verifyCmd": "$TC actions list action simple",
636 "matchPattern": "action order [0-9]*: Simple <A triumph>.*index 60 ref",
637 "matchCount": "1",
638 "teardown": [
639 "$TC actions flush action simple"
640 ]
641 },
642 {
643 "id": "6d4c",
644 "name": "Add simple action with duplicate index",
645 "category": [
646 "actions",
647 "simple"
648 ],
649 "setup": [
650 [
651 "$TC actions flush action simple",
652 0,
653 1,
654 255
655 ],
656 "$TC actions add action simple sdata \"Aruba\" index 4"
657 ],
658 "cmdUnderTest": "$TC actions add action simple sdata \"Jamaica\" index 4",
659 "expExitCode": "255",
660 "verifyCmd": "$TC actions list action simple",
661 "matchPattern": "action order [0-9]*: Simple <Jamaica>.*ref",
662 "matchCount": "0",
663 "teardown": [
664 "$TC actions flush action simple"
665 ]
666 },
667 {
668 "id": "2542",
669 "name": "List simple actions",
670 "category": [
671 "actions",
672 "simple"
673 ],
674 "setup": [
675 [
676 "$TC actions flush action simple",
677 0,
678 1,
679 255
680 ],
681 "$TC actions add action simple sdata \"Rock\"",
682 "$TC actions add action simple sdata \"Paper\"",
683 "$TC actions add action simple sdata \"Scissors\" index 98"
684 ],
685 "cmdUnderTest": "$TC actions list action simple",
686 "expExitCode": "0",
687 "verifyCmd": "$TC actions list action simple",
688 "matchPattern": "action order [0-9]*: Simple <[A-Z][a-z]*>",
689 "matchCount": "3",
690 "teardown": [
691 "$TC actions flush action simple"
692 ]
693 },
694 {
695 "id": "ea67",
696 "name": "Delete simple action",
697 "category": [
698 "actions",
699 "simple"
700 ],
701 "setup": [
702 [
703 "$TC actions flush action simple",
704 0,
705 1,
706 255
707 ],
708 "$TC actions add action simple sdata \"Blinkenlights\" index 1"
709 ],
710 "cmdUnderTest": "$TC actions delete action simple index 1",
711 "expExitCode": "0",
712 "verifyCmd": "$TC actions list action simple",
713 "matchPattern": "action order [0-9]*: Simple <Blinkenlights>.*index 1 ref",
714 "matchCount": "0",
715 "teardown": [
716 "$TC actions flush action simple"
717 ]
718 },
719 {
720 "id": "8ff1",
721 "name": "Flush simple actions",
722 "category": [
723 "actions",
724 "simple"
725 ],
726 "setup": [
727 [
728 "$TC actions flush action simple",
729 0,
730 1,
731 255
732 ],
733 "$TC actions add action simple sdata \"Kirk\"",
734 "$TC actions add action simple sdata \"Spock\" index 50",
735 "$TC actions add action simple sdata \"McCoy\" index 9"
736 ],
737 "cmdUnderTest": "$TC actions flush action simple",
738 "expExitCode": "0",
739 "verifyCmd": "$TC actions list action simple",
740 "matchPattern": "action order [0-9]*: Simple <[A-Z][a-z]*>",
741 "matchCount": "0",
742 "teardown": [
743 ""
744 ]
745 },
746 {
747 "id": "6236",
748 "name": "Add skbedit action with valid mark",
749 "category": [
750 "actions",
751 "skbedit"
752 ],
753 "setup": [
754 [
755 "$TC actions flush action skbedit",
756 0,
757 1,
758 255
759 ]
760 ],
761 "cmdUnderTest": "$TC actions add action skbedit mark 1",
762 "expExitCode": "0",
763 "verifyCmd": "$TC actions list action skbedit",
764 "matchPattern": "action order [0-9]*: skbedit mark 1",
765 "matchCount": "1",
766 "teardown": [
767 "$TC actions flush action skbedit"
768 ]
769 },
770 {
771 "id": "407b",
772 "name": "Add skbedit action with invalid mark",
773 "category": [
774 "actions",
775 "skbedit"
776 ],
777 "setup": [
778 [
779 "$TC actions flush action skbedit",
780 0,
781 1,
782 255
783 ]
784 ],
785 "cmdUnderTest": "$TC actions add action skbedit mark 666777888999",
786 "expExitCode": "255",
787 "verifyCmd": "$TC actions list action skbedit",
788 "matchPattern": "action order [0-9]*: skbedit mark",
789 "matchCount": "0",
790 "teardown": [
791 "$TC actions flush action skbedit"
792 ]
793 },
794 {
795 "id": "081d",
796 "name": "Add skbedit action with priority",
797 "category": [
798 "actions",
799 "skbedit"
800 ],
801 "setup": [
802 [
803 "$TC actions flush action skbedit",
804 0,
805 1,
806 255
807 ]
808 ],
809 "cmdUnderTest": "$TC actions add action skbedit prio 99",
810 "expExitCode": "0",
811 "verifyCmd": "$TC actions list action skbedit",
812 "matchPattern": "action order [0-9]*: skbedit priority :99",
813 "matchCount": "1",
814 "teardown": [
815 "$TC actions flush action skbedit"
816 ]
817 },
818 {
819 "id": "cc37",
820 "name": "Add skbedit action with invalid priority",
821 "category": [
822 "actions",
823 "skbedit"
824 ],
825 "setup": [
826 [
827 "$TC actions flush action skbedit",
828 0,
829 1,
830 255
831 ]
832 ],
833 "cmdUnderTest": "$TC actions add action skbedit prio foo",
834 "expExitCode": "255",
835 "verifyCmd": "$TC actions list action skbedit",
836 "matchPattern": "action order [0-9]*: skbedit priority",
837 "matchCount": "0",
838 "teardown": [
839 "$TC actions flush action skbedit"
840 ]
841 },
842 {
843 "id": "3c95",
844 "name": "Add skbedit action with queue_mapping",
845 "category": [
846 "actions",
847 "skbedit"
848 ],
849 "setup": [
850 [
851 "$TC actions flush action skbedit",
852 0,
853 1,
854 255
855 ]
856 ],
857 "cmdUnderTest": "$TC actions add action skbedit queue_mapping 909",
858 "expExitCode": "0",
859 "verifyCmd": "$TC actions list action skbedit",
860 "matchPattern": "action order [0-9]*: skbedit queue_mapping 909",
861 "matchCount": "1",
862 "teardown": [
863 "$TC actions flush action skbedit"
864 ]
865 },
866 {
867 "id": "985c",
868 "name": "Add skbedit action with invalid queue_mapping",
869 "category": [
870 "actions",
871 "skbedit"
872 ],
873 "setup": [
874 [
875 "$TC actions flush action skbedit",
876 0,
877 1,
878 255
879 ]
880 ],
881 "cmdUnderTest": "$TC actions add action skbedit queue_mapping 67000",
882 "expExitCode": "255",
883 "verifyCmd": "$TC actions list action skbedit",
884 "matchPattern": "action order [0-9]*: skbedit queue_mapping",
885 "matchCount": "0",
886 "teardown": [
887 "$TC actions flush action skbedit"
888 ]
889 },
890 {
891 "id": "224f",
892 "name": "Add skbedit action with ptype host",
893 "category": [
894 "actions",
895 "skbedit"
896 ],
897 "setup": [
898 [
899 "$TC actions flush action skbedit",
900 0,
901 1,
902 255
903 ]
904 ],
905 "cmdUnderTest": "$TC actions add action skbedit ptype host",
906 "expExitCode": "0",
907 "verifyCmd": "$TC actions list action skbedit",
908 "matchPattern": "action order [0-9]*: skbedit ptype host",
909 "matchCount": "1",
910 "teardown": [
911 "$TC actions flush action skbedit"
912 ]
913 },
914 {
915 "id": "d1a3",
916 "name": "Add skbedit action with ptype otherhost",
917 "category": [
918 "actions",
919 "skbedit"
920 ],
921 "setup": [
922 [
923 "$TC actions flush action skbedit",
924 0,
925 1,
926 255
927 ]
928 ],
929 "cmdUnderTest": "$TC actions add action skbedit ptype otherhost",
930 "expExitCode": "0",
931 "verifyCmd": "$TC actions list action skbedit",
932 "matchPattern": "action order [0-9]*: skbedit ptype otherhost",
933 "matchCount": "1",
934 "teardown": [
935 "$TC actions flush action skbedit"
936 ]
937 },
938 {
939 "id": "b9c6",
940 "name": "Add skbedit action with invalid ptype",
941 "category": [
942 "actions",
943 "skbedit"
944 ],
945 "setup": [
946 [
947 "$TC actions flush action skbedit",
948 0,
949 1,
950 255
951 ]
952 ],
953 "cmdUnderTest": "$TC actions add action skbedit ptype openair",
954 "expExitCode": "255",
955 "verifyCmd": "$TC actions list action skbedit",
956 "matchPattern": "action order [0-9]*: skbedit ptype openair",
957 "matchCount": "0",
958 "teardown": [
959 "$TC actions flush action skbedit"
960 ]
961 },
962 {
963 "id": "5172",
964 "name": "List skbedit actions",
965 "category": [
966 "actions",
967 "skbedit"
968 ],
969 "setup": [
970 [
971 "$TC actions flush action skbedit",
972 0,
973 1,
974 255
975 ],
976 "$TC actions add action skbedit ptype otherhost",
977 "$TC actions add action skbedit ptype broadcast",
978 "$TC actions add action skbedit mark 59",
979 "$TC actions add action skbedit mark 409"
980 ],
981 "cmdUnderTest": "$TC actions list action skbedit",
982 "expExitCode": "0",
983 "verifyCmd": "$TC actions list action skbedit",
984 "matchPattern": "action order [0-9]*: skbedit",
985 "matchCount": "4",
986 "teardown": [
987 "$TC actions flush action skbedit"
988 ]
989 },
990 {
991 "id": "a6d6",
992 "name": "Add skbedit action with index",
993 "category": [
994 "actions",
995 "skbedit"
996 ],
997 "setup": [
998 [
999 "$TC actions flush action skbedit",
1000 0,
1001 1,
1002 255
1003 ]
1004 ],
1005 "cmdUnderTest": "$TC actions add action skbedit mark 808 index 4040404040",
1006 "expExitCode": "0",
1007 "verifyCmd": "$TC actions list action skbedit",
1008 "matchPattern": "index 4040404040",
1009 "matchCount": "1",
1010 "teardown": [
1011 "$TC actions flush action skbedit"
1012 ]
1013 },
1014 {
1015 "id": "38f3",
1016 "name": "Delete skbedit action",
1017 "category": [
1018 "actions",
1019 "skbedit"
1020 ],
1021 "setup": [
1022 [
1023 "$TC actions flush action skbedit",
1024 0,
1025 1,
1026 255
1027 ],
1028 "$TC actions add action skbedit mark 42 index 9009"
1029 ],
1030 "cmdUnderTest": "$TC actions del action skbedit index 9009",
1031 "expExitCode": "0",
1032 "verifyCmd": "$TC actions list action skbedit",
1033 "matchPattern": "action order [0-9]*: skbedit mark 42",
1034 "matchCount": "0",
1035 "teardown": [
1036 "$TC actions flush action skbedit"
1037 ]
1038 },
1039 {
1040 "id": "ce97",
1041 "name": "Flush skbedit actions",
1042 "category": [
1043 "actions",
1044 "skbedit"
1045 ],
1046 "setup": [
1047 "$TC actions add action skbedit mark 500",
1048 "$TC actions add action skbedit mark 501",
1049 "$TC actions add action skbedit mark 502",
1050 "$TC actions add action skbedit mark 503",
1051 "$TC actions add action skbedit mark 504",
1052 "$TC actions add action skbedit mark 505",
1053 "$TC actions add action skbedit mark 506"
1054 ],
1055 "cmdUnderTest": "$TC actions flush action skbedit",
1056 "expExitCode": "0",
1057 "verifyCmd": "$TC actions list action skbedit",
1058 "matchPattern": "action order [0-9]*: skbedit",
1059 "matchCount": "0",
1060 "teardown": [
1061 "$TC actions flush action skbedit"
1062 ]
1063 },
1064 {
1065 "id": "f02c",
1066 "name": "Replace gact action",
1067 "category": [
1068 "actions",
1069 "gact"
1070 ],
1071 "setup": [
1072 [
1073 "$TC actions flush action gact",
1074 0,
1075 1,
1076 255
1077 ],
1078 "$TC actions add action drop index 10",
1079 "$TC actions add action drop index 12"
1080 ],
1081 "cmdUnderTest": "$TC actions replace action ok index 12",
1082 "expExitCode": "0",
1083 "verifyCmd": "$TC actions ls action gact",
1084 "matchPattern": "action order [0-9]*: gact action pass",
1085 "matchCount": "1",
1086 "teardown": [
1087 "$TC actions flush action gact"
1088 ]
1089 },
1090 {
1091 "id": "525f",
1092 "name": "Get gact action by index",
1093 "category": [
1094 "actions",
1095 "gact"
1096 ],
1097 "setup": [
1098 [
1099 "$TC actions flush action gact",
1100 0,
1101 1,
1102 255
1103 ],
1104 "$TC actions add action drop index 3900800700"
1105 ],
1106 "cmdUnderTest": "$TC actions get action gact index 3900800700",
1107 "expExitCode": "0",
1108 "verifyCmd": "$TC actions get action gact index 3900800700",
1109 "matchPattern": "index 3900800700",
1110 "matchCount": "1",
1111 "teardown": [
1112 "$TC actions flush action gact"
1113 ]
1114 },
1115 {
1116 "id": "a568",
1117 "name": "Add action with ife type",
1118 "category": [
1119 "actions",
1120 "ife"
1121 ],
1122 "setup": [
1123 [
1124 "$TC actions flush action ife",
1125 0,
1126 1,
1127 255
1128 ],
1129 "$TC actions add action ife encode type 0xDEAD index 1"
1130 ],
1131 "cmdUnderTest": "$TC actions get action ife index 1",
1132 "expExitCode": "0",
1133 "verifyCmd": "$TC actions get action ife index 1",
1134 "matchPattern": "type 0xDEAD",
1135 "matchCount": "1",
1136 "teardown": [
1137 "$TC actions flush action ife"
1138 ]
1139 },
1140 {
1141 "id": "b983",
1142 "name": "Add action without ife type",
1143 "category": [
1144 "actions",
1145 "ife"
1146 ],
1147 "setup": [
1148 [
1149 "$TC actions flush action ife",
1150 0,
1151 1,
1152 255
1153 ],
1154 "$TC actions add action ife encode index 1"
1155 ],
1156 "cmdUnderTest": "$TC actions get action ife index 1",
1157 "expExitCode": "0",
1158 "verifyCmd": "$TC actions get action ife index 1",
1159 "matchPattern": "type 0xED3E",
1160 "matchCount": "1",
1161 "teardown": [
1162 "$TC actions flush action ife"
1163 ]
1164 }
1165] \ No newline at end of file
diff --git a/tools/testing/selftests/tc-testing/tdc.py b/tools/testing/selftests/tc-testing/tdc.py
index b8462e1b74f9..fc373fdf2bdc 100755
--- a/tools/testing/selftests/tc-testing/tdc.py
+++ b/tools/testing/selftests/tc-testing/tdc.py
@@ -50,7 +50,7 @@ def exec_cmd(command, nsonly=True):
50 stderr=subprocess.PIPE) 50 stderr=subprocess.PIPE)
51 (rawout, serr) = proc.communicate() 51 (rawout, serr) = proc.communicate()
52 52
53 if proc.returncode != 0: 53 if proc.returncode != 0 and len(serr) > 0:
54 foutput = serr.decode("utf-8") 54 foutput = serr.decode("utf-8")
55 else: 55 else:
56 foutput = rawout.decode("utf-8") 56 foutput = rawout.decode("utf-8")
@@ -180,15 +180,20 @@ def has_blank_ids(idlist):
180 180
181def load_from_file(filename): 181def load_from_file(filename):
182 """ 182 """
183 Open the JSON file containing the test cases and return them as an 183 Open the JSON file containing the test cases and return them
184 ordered dictionary object. 184 as list of ordered dictionary objects.
185 """ 185 """
186 with open(filename) as test_data: 186 try:
187 testlist = json.load(test_data, object_pairs_hook=OrderedDict) 187 with open(filename) as test_data:
188 idlist = get_id_list(testlist) 188 testlist = json.load(test_data, object_pairs_hook=OrderedDict)
189 if (has_blank_ids(idlist)): 189 except json.JSONDecodeError as jde:
190 for k in testlist: 190 print('IGNORING test case file {}\n\tBECAUSE: {}'.format(filename, jde))
191 k['filename'] = filename 191 testlist = list()
192 else:
193 idlist = get_id_list(testlist)
194 if (has_blank_ids(idlist)):
195 for k in testlist:
196 k['filename'] = filename
192 return testlist 197 return testlist
193 198
194 199
@@ -210,7 +215,7 @@ def set_args(parser):
210 help='Run tests only from the specified category, or if no category is specified, list known categories.') 215 help='Run tests only from the specified category, or if no category is specified, list known categories.')
211 parser.add_argument('-f', '--file', type=str, 216 parser.add_argument('-f', '--file', type=str,
212 help='Run tests from the specified file') 217 help='Run tests from the specified file')
213 parser.add_argument('-l', '--list', type=str, nargs='?', const="", metavar='CATEGORY', 218 parser.add_argument('-l', '--list', type=str, nargs='?', const="++", metavar='CATEGORY',
214 help='List all test cases, or those only within the specified category') 219 help='List all test cases, or those only within the specified category')
215 parser.add_argument('-s', '--show', type=str, nargs=1, metavar='ID', dest='showID', 220 parser.add_argument('-s', '--show', type=str, nargs=1, metavar='ID', dest='showID',
216 help='Display the test case with specified id') 221 help='Display the test case with specified id')
@@ -367,10 +372,10 @@ def set_operation_mode(args):
367 testcases = get_categorized_testlist(alltests, ucat) 372 testcases = get_categorized_testlist(alltests, ucat)
368 373
369 if args.list: 374 if args.list:
370 if (len(args.list) == 0): 375 if (args.list == "++"):
371 list_test_cases(alltests) 376 list_test_cases(alltests)
372 exit(0) 377 exit(0)
373 elif(len(args.list > 0)): 378 elif(len(args.list) > 0):
374 if (args.list not in ucat): 379 if (args.list not in ucat):
375 print("Unknown category " + args.list) 380 print("Unknown category " + args.list)
376 print("Available categories:") 381 print("Available categories:")
diff --git a/tools/testing/selftests/tc-testing/tdc_config.py b/tools/testing/selftests/tc-testing/tdc_config.py
index eb188c729dd6..a023d0d62b25 100644
--- a/tools/testing/selftests/tc-testing/tdc_config.py
+++ b/tools/testing/selftests/tc-testing/tdc_config.py
@@ -18,3 +18,17 @@ NAMES = {
18 # Name of the namespace to use 18 # Name of the namespace to use
19 'NS': 'tcut' 19 'NS': 'tcut'
20 } 20 }
21
22
23ENVIR = { }
24
25# put customizations in tdc_config_local.py
26try:
27 from tdc_config_local import *
28except ImportError as ie:
29 pass
30
31try:
32 NAMES.update(EXTRA_NAMES)
33except NameError as ne:
34 pass
diff --git a/tools/testing/selftests/tc-testing/tdc_config_local_template.py b/tools/testing/selftests/tc-testing/tdc_config_local_template.py
new file mode 100644
index 000000000000..d48fc732a399
--- /dev/null
+++ b/tools/testing/selftests/tc-testing/tdc_config_local_template.py
@@ -0,0 +1,23 @@
1"""
2tdc_config_local.py - tdc plugin-writer-specified values
3
4Copyright (C) 2017 bjb@mojatatu.com
5"""
6
7import os
8
9ENVIR = os.environ.copy()
10
11ENV_LD_LIBRARY_PATH = os.getenv('LD_LIBRARY_PATH', '')
12ENV_OTHER_LIB = os.getenv('OTHER_LIB', '')
13
14
15# example adding value to NAMES, without editing tdc_config.py
16EXTRA_NAMES = dict()
17EXTRA_NAMES['SOME_BIN'] = os.path.join(os.getenv('OTHER_BIN', ''), 'some_bin')
18
19
20# example adding values to ENVIR, without editing tdc_config.py
21ENVIR['VALGRIND_LIB'] = '/usr/lib/valgrind'
22ENVIR['VALGRIND_BIN'] = '/usr/bin/valgrind'
23ENVIR['VGDB_BIN'] = '/usr/bin/vgdb'
diff --git a/tools/testing/selftests/tc-testing/tdc_helper.py b/tools/testing/selftests/tc-testing/tdc_helper.py
index ccf2d2458703..db381120a566 100644
--- a/tools/testing/selftests/tc-testing/tdc_helper.py
+++ b/tools/testing/selftests/tc-testing/tdc_helper.py
@@ -16,7 +16,7 @@ def get_categorized_testlist(alltests, ucat):
16 16
17 17
18def get_unique_item(lst): 18def get_unique_item(lst):
19 """ For a list, return a set of the unique items in the list. """ 19 """ For a list, return a list of the unique items in the list. """
20 return list(set(lst)) 20 return list(set(lst))
21 21
22 22
@@ -58,7 +58,7 @@ def print_sll(items):
58def print_test_case(tcase): 58def print_test_case(tcase):
59 """ Pretty-printing of a given test case. """ 59 """ Pretty-printing of a given test case. """
60 for k in tcase.keys(): 60 for k in tcase.keys():
61 if (type(tcase[k]) == list): 61 if (isinstance(tcase[k], list)):
62 print(k + ":") 62 print(k + ":")
63 print_list(tcase[k]) 63 print_list(tcase[k])
64 else: 64 else:
diff --git a/tools/testing/vsock/.gitignore b/tools/testing/vsock/.gitignore
new file mode 100644
index 000000000000..dc5f11faf530
--- /dev/null
+++ b/tools/testing/vsock/.gitignore
@@ -0,0 +1,2 @@
1*.d
2vsock_diag_test
diff --git a/tools/testing/vsock/Makefile b/tools/testing/vsock/Makefile
new file mode 100644
index 000000000000..66ba0924194d
--- /dev/null
+++ b/tools/testing/vsock/Makefile
@@ -0,0 +1,9 @@
1all: test
2test: vsock_diag_test
3vsock_diag_test: vsock_diag_test.o timeout.o control.o
4
5CFLAGS += -g -O2 -Werror -Wall -I. -I../../include/uapi -I../../include -Wno-pointer-sign -fno-strict-overflow -fno-strict-aliasing -fno-common -MMD -U_FORTIFY_SOURCE -D_GNU_SOURCE
6.PHONY: all test clean
7clean:
8 ${RM} *.o *.d vsock_diag_test
9-include *.d
diff --git a/tools/testing/vsock/README b/tools/testing/vsock/README
new file mode 100644
index 000000000000..2cc6d7302db6
--- /dev/null
+++ b/tools/testing/vsock/README
@@ -0,0 +1,36 @@
1AF_VSOCK test suite
2-------------------
3These tests exercise net/vmw_vsock/ host<->guest sockets for VMware, KVM, and
4Hyper-V.
5
6The following tests are available:
7
8 * vsock_diag_test - vsock_diag.ko module for listing open sockets
9
10The following prerequisite steps are not automated and must be performed prior
11to running tests:
12
131. Build the kernel and these tests.
142. Install the kernel and tests on the host.
153. Install the kernel and tests inside the guest.
164. Boot the guest and ensure that the AF_VSOCK transport is enabled.
17
18Invoke test binaries in both directions as follows:
19
20 # host=server, guest=client
21 (host)# $TEST_BINARY --mode=server \
22 --control-port=1234 \
23 --peer-cid=3
24 (guest)# $TEST_BINARY --mode=client \
25 --control-host=$HOST_IP \
26 --control-port=1234 \
27 --peer-cid=2
28
29 # host=client, guest=server
30 (guest)# $TEST_BINARY --mode=server \
31 --control-port=1234 \
32 --peer-cid=2
33 (host)# $TEST_BINARY --mode=client \
34 --control-port=$GUEST_IP \
35 --control-port=1234 \
36 --peer-cid=3
diff --git a/tools/testing/vsock/control.c b/tools/testing/vsock/control.c
new file mode 100644
index 000000000000..90fd47f0e422
--- /dev/null
+++ b/tools/testing/vsock/control.c
@@ -0,0 +1,219 @@
1/* Control socket for client/server test execution
2 *
3 * Copyright (C) 2017 Red Hat, Inc.
4 *
5 * Author: Stefan Hajnoczi <stefanha@redhat.com>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; version 2
10 * of the License.
11 */
12
13/* The client and server may need to coordinate to avoid race conditions like
14 * the client attempting to connect to a socket that the server is not
15 * listening on yet. The control socket offers a communications channel for
16 * such coordination tasks.
17 *
18 * If the client calls control_expectln("LISTENING"), then it will block until
19 * the server calls control_writeln("LISTENING"). This provides a simple
20 * mechanism for coordinating between the client and the server.
21 */
22
23#include <errno.h>
24#include <netdb.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <unistd.h>
29#include <sys/types.h>
30#include <sys/socket.h>
31
32#include "timeout.h"
33#include "control.h"
34
35static int control_fd = -1;
36
37/* Open the control socket, either in server or client mode */
38void control_init(const char *control_host,
39 const char *control_port,
40 bool server)
41{
42 struct addrinfo hints = {
43 .ai_socktype = SOCK_STREAM,
44 };
45 struct addrinfo *result = NULL;
46 struct addrinfo *ai;
47 int ret;
48
49 ret = getaddrinfo(control_host, control_port, &hints, &result);
50 if (ret != 0) {
51 fprintf(stderr, "%s\n", gai_strerror(ret));
52 exit(EXIT_FAILURE);
53 }
54
55 for (ai = result; ai; ai = ai->ai_next) {
56 int fd;
57 int val = 1;
58
59 fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
60 if (fd < 0)
61 continue;
62
63 if (!server) {
64 if (connect(fd, ai->ai_addr, ai->ai_addrlen) < 0)
65 goto next;
66 control_fd = fd;
67 printf("Control socket connected to %s:%s.\n",
68 control_host, control_port);
69 break;
70 }
71
72 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
73 &val, sizeof(val)) < 0) {
74 perror("setsockopt");
75 exit(EXIT_FAILURE);
76 }
77
78 if (bind(fd, ai->ai_addr, ai->ai_addrlen) < 0)
79 goto next;
80 if (listen(fd, 1) < 0)
81 goto next;
82
83 printf("Control socket listening on %s:%s\n",
84 control_host, control_port);
85 fflush(stdout);
86
87 control_fd = accept(fd, NULL, 0);
88 close(fd);
89
90 if (control_fd < 0) {
91 perror("accept");
92 exit(EXIT_FAILURE);
93 }
94 printf("Control socket connection accepted...\n");
95 break;
96
97next:
98 close(fd);
99 }
100
101 if (control_fd < 0) {
102 fprintf(stderr, "Control socket initialization failed. Invalid address %s:%s?\n",
103 control_host, control_port);
104 exit(EXIT_FAILURE);
105 }
106
107 freeaddrinfo(result);
108}
109
110/* Free resources */
111void control_cleanup(void)
112{
113 close(control_fd);
114 control_fd = -1;
115}
116
117/* Write a line to the control socket */
118void control_writeln(const char *str)
119{
120 ssize_t len = strlen(str);
121 ssize_t ret;
122
123 timeout_begin(TIMEOUT);
124
125 do {
126 ret = send(control_fd, str, len, MSG_MORE);
127 timeout_check("send");
128 } while (ret < 0 && errno == EINTR);
129
130 if (ret != len) {
131 perror("send");
132 exit(EXIT_FAILURE);
133 }
134
135 do {
136 ret = send(control_fd, "\n", 1, 0);
137 timeout_check("send");
138 } while (ret < 0 && errno == EINTR);
139
140 if (ret != 1) {
141 perror("send");
142 exit(EXIT_FAILURE);
143 }
144
145 timeout_end();
146}
147
148/* Return the next line from the control socket (without the trailing newline).
149 *
150 * The program terminates if a timeout occurs.
151 *
152 * The caller must free() the returned string.
153 */
154char *control_readln(void)
155{
156 char *buf = NULL;
157 size_t idx = 0;
158 size_t buflen = 0;
159
160 timeout_begin(TIMEOUT);
161
162 for (;;) {
163 ssize_t ret;
164
165 if (idx >= buflen) {
166 char *new_buf;
167
168 new_buf = realloc(buf, buflen + 80);
169 if (!new_buf) {
170 perror("realloc");
171 exit(EXIT_FAILURE);
172 }
173
174 buf = new_buf;
175 buflen += 80;
176 }
177
178 do {
179 ret = recv(control_fd, &buf[idx], 1, 0);
180 timeout_check("recv");
181 } while (ret < 0 && errno == EINTR);
182
183 if (ret == 0) {
184 fprintf(stderr, "unexpected EOF on control socket\n");
185 exit(EXIT_FAILURE);
186 }
187
188 if (ret != 1) {
189 perror("recv");
190 exit(EXIT_FAILURE);
191 }
192
193 if (buf[idx] == '\n') {
194 buf[idx] = '\0';
195 break;
196 }
197
198 idx++;
199 }
200
201 timeout_end();
202
203 return buf;
204}
205
206/* Wait until a given line is received or a timeout occurs */
207void control_expectln(const char *str)
208{
209 char *line;
210
211 line = control_readln();
212 if (strcmp(str, line) != 0) {
213 fprintf(stderr, "expected \"%s\" on control socket, got \"%s\"\n",
214 str, line);
215 exit(EXIT_FAILURE);
216 }
217
218 free(line);
219}
diff --git a/tools/testing/vsock/control.h b/tools/testing/vsock/control.h
new file mode 100644
index 000000000000..54a07efd267c
--- /dev/null
+++ b/tools/testing/vsock/control.h
@@ -0,0 +1,13 @@
1#ifndef CONTROL_H
2#define CONTROL_H
3
4#include <stdbool.h>
5
6void control_init(const char *control_host, const char *control_port,
7 bool server);
8void control_cleanup(void);
9void control_writeln(const char *str);
10char *control_readln(void);
11void control_expectln(const char *str);
12
13#endif /* CONTROL_H */
diff --git a/tools/testing/vsock/timeout.c b/tools/testing/vsock/timeout.c
new file mode 100644
index 000000000000..c49b3003b2db
--- /dev/null
+++ b/tools/testing/vsock/timeout.c
@@ -0,0 +1,64 @@
1/* Timeout API for single-threaded programs that use blocking
2 * syscalls (read/write/send/recv/connect/accept).
3 *
4 * Copyright (C) 2017 Red Hat, Inc.
5 *
6 * Author: Stefan Hajnoczi <stefanha@redhat.com>
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; version 2
11 * of the License.
12 */
13
14/* Use the following pattern:
15 *
16 * timeout_begin(TIMEOUT);
17 * do {
18 * ret = accept(...);
19 * timeout_check("accept");
20 * } while (ret < 0 && ret == EINTR);
21 * timeout_end();
22 */
23
24#include <stdlib.h>
25#include <stdbool.h>
26#include <unistd.h>
27#include <stdio.h>
28#include "timeout.h"
29
30static volatile bool timeout;
31
32/* SIGALRM handler function. Do not use sleep(2), alarm(2), or
33 * setitimer(2) while using this API - they may interfere with each
34 * other.
35 */
36void sigalrm(int signo)
37{
38 timeout = true;
39}
40
41/* Start a timeout. Call timeout_check() to verify that the timeout hasn't
42 * expired. timeout_end() must be called to stop the timeout. Timeouts cannot
43 * be nested.
44 */
45void timeout_begin(unsigned int seconds)
46{
47 alarm(seconds);
48}
49
50/* Exit with an error message if the timeout has expired */
51void timeout_check(const char *operation)
52{
53 if (timeout) {
54 fprintf(stderr, "%s timed out\n", operation);
55 exit(EXIT_FAILURE);
56 }
57}
58
59/* Stop a timeout */
60void timeout_end(void)
61{
62 alarm(0);
63 timeout = false;
64}
diff --git a/tools/testing/vsock/timeout.h b/tools/testing/vsock/timeout.h
new file mode 100644
index 000000000000..77db9ce9860a
--- /dev/null
+++ b/tools/testing/vsock/timeout.h
@@ -0,0 +1,14 @@
1#ifndef TIMEOUT_H
2#define TIMEOUT_H
3
4enum {
5 /* Default timeout */
6 TIMEOUT = 10 /* seconds */
7};
8
9void sigalrm(int signo);
10void timeout_begin(unsigned int seconds);
11void timeout_check(const char *operation);
12void timeout_end(void);
13
14#endif /* TIMEOUT_H */
diff --git a/tools/testing/vsock/vsock_diag_test.c b/tools/testing/vsock/vsock_diag_test.c
new file mode 100644
index 000000000000..e896a4af52f4
--- /dev/null
+++ b/tools/testing/vsock/vsock_diag_test.c
@@ -0,0 +1,681 @@
1/*
2 * vsock_diag_test - vsock_diag.ko test suite
3 *
4 * Copyright (C) 2017 Red Hat, Inc.
5 *
6 * Author: Stefan Hajnoczi <stefanha@redhat.com>
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; version 2
11 * of the License.
12 */
13
14#include <getopt.h>
15#include <stdio.h>
16#include <stdbool.h>
17#include <stdlib.h>
18#include <string.h>
19#include <errno.h>
20#include <unistd.h>
21#include <signal.h>
22#include <sys/socket.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25#include <linux/list.h>
26#include <linux/net.h>
27#include <linux/netlink.h>
28#include <linux/sock_diag.h>
29#include <netinet/tcp.h>
30
31#include "../../../include/uapi/linux/vm_sockets.h"
32#include "../../../include/uapi/linux/vm_sockets_diag.h"
33
34#include "timeout.h"
35#include "control.h"
36
37enum test_mode {
38 TEST_MODE_UNSET,
39 TEST_MODE_CLIENT,
40 TEST_MODE_SERVER
41};
42
43/* Per-socket status */
44struct vsock_stat {
45 struct list_head list;
46 struct vsock_diag_msg msg;
47};
48
49static const char *sock_type_str(int type)
50{
51 switch (type) {
52 case SOCK_DGRAM:
53 return "DGRAM";
54 case SOCK_STREAM:
55 return "STREAM";
56 default:
57 return "INVALID TYPE";
58 }
59}
60
61static const char *sock_state_str(int state)
62{
63 switch (state) {
64 case TCP_CLOSE:
65 return "UNCONNECTED";
66 case TCP_SYN_SENT:
67 return "CONNECTING";
68 case TCP_ESTABLISHED:
69 return "CONNECTED";
70 case TCP_CLOSING:
71 return "DISCONNECTING";
72 case TCP_LISTEN:
73 return "LISTEN";
74 default:
75 return "INVALID STATE";
76 }
77}
78
79static const char *sock_shutdown_str(int shutdown)
80{
81 switch (shutdown) {
82 case 1:
83 return "RCV_SHUTDOWN";
84 case 2:
85 return "SEND_SHUTDOWN";
86 case 3:
87 return "RCV_SHUTDOWN | SEND_SHUTDOWN";
88 default:
89 return "0";
90 }
91}
92
93static void print_vsock_addr(FILE *fp, unsigned int cid, unsigned int port)
94{
95 if (cid == VMADDR_CID_ANY)
96 fprintf(fp, "*:");
97 else
98 fprintf(fp, "%u:", cid);
99
100 if (port == VMADDR_PORT_ANY)
101 fprintf(fp, "*");
102 else
103 fprintf(fp, "%u", port);
104}
105
106static void print_vsock_stat(FILE *fp, struct vsock_stat *st)
107{
108 print_vsock_addr(fp, st->msg.vdiag_src_cid, st->msg.vdiag_src_port);
109 fprintf(fp, " ");
110 print_vsock_addr(fp, st->msg.vdiag_dst_cid, st->msg.vdiag_dst_port);
111 fprintf(fp, " %s %s %s %u\n",
112 sock_type_str(st->msg.vdiag_type),
113 sock_state_str(st->msg.vdiag_state),
114 sock_shutdown_str(st->msg.vdiag_shutdown),
115 st->msg.vdiag_ino);
116}
117
118static void print_vsock_stats(FILE *fp, struct list_head *head)
119{
120 struct vsock_stat *st;
121
122 list_for_each_entry(st, head, list)
123 print_vsock_stat(fp, st);
124}
125
126static struct vsock_stat *find_vsock_stat(struct list_head *head, int fd)
127{
128 struct vsock_stat *st;
129 struct stat stat;
130
131 if (fstat(fd, &stat) < 0) {
132 perror("fstat");
133 exit(EXIT_FAILURE);
134 }
135
136 list_for_each_entry(st, head, list)
137 if (st->msg.vdiag_ino == stat.st_ino)
138 return st;
139
140 fprintf(stderr, "cannot find fd %d\n", fd);
141 exit(EXIT_FAILURE);
142}
143
144static void check_no_sockets(struct list_head *head)
145{
146 if (!list_empty(head)) {
147 fprintf(stderr, "expected no sockets\n");
148 print_vsock_stats(stderr, head);
149 exit(1);
150 }
151}
152
153static void check_num_sockets(struct list_head *head, int expected)
154{
155 struct list_head *node;
156 int n = 0;
157
158 list_for_each(node, head)
159 n++;
160
161 if (n != expected) {
162 fprintf(stderr, "expected %d sockets, found %d\n",
163 expected, n);
164 print_vsock_stats(stderr, head);
165 exit(EXIT_FAILURE);
166 }
167}
168
169static void check_socket_state(struct vsock_stat *st, __u8 state)
170{
171 if (st->msg.vdiag_state != state) {
172 fprintf(stderr, "expected socket state %#x, got %#x\n",
173 state, st->msg.vdiag_state);
174 exit(EXIT_FAILURE);
175 }
176}
177
178static void send_req(int fd)
179{
180 struct sockaddr_nl nladdr = {
181 .nl_family = AF_NETLINK,
182 };
183 struct {
184 struct nlmsghdr nlh;
185 struct vsock_diag_req vreq;
186 } req = {
187 .nlh = {
188 .nlmsg_len = sizeof(req),
189 .nlmsg_type = SOCK_DIAG_BY_FAMILY,
190 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
191 },
192 .vreq = {
193 .sdiag_family = AF_VSOCK,
194 .vdiag_states = ~(__u32)0,
195 },
196 };
197 struct iovec iov = {
198 .iov_base = &req,
199 .iov_len = sizeof(req),
200 };
201 struct msghdr msg = {
202 .msg_name = &nladdr,
203 .msg_namelen = sizeof(nladdr),
204 .msg_iov = &iov,
205 .msg_iovlen = 1,
206 };
207
208 for (;;) {
209 if (sendmsg(fd, &msg, 0) < 0) {
210 if (errno == EINTR)
211 continue;
212
213 perror("sendmsg");
214 exit(EXIT_FAILURE);
215 }
216
217 return;
218 }
219}
220
221static ssize_t recv_resp(int fd, void *buf, size_t len)
222{
223 struct sockaddr_nl nladdr = {
224 .nl_family = AF_NETLINK,
225 };
226 struct iovec iov = {
227 .iov_base = buf,
228 .iov_len = len,
229 };
230 struct msghdr msg = {
231 .msg_name = &nladdr,
232 .msg_namelen = sizeof(nladdr),
233 .msg_iov = &iov,
234 .msg_iovlen = 1,
235 };
236 ssize_t ret;
237
238 do {
239 ret = recvmsg(fd, &msg, 0);
240 } while (ret < 0 && errno == EINTR);
241
242 if (ret < 0) {
243 perror("recvmsg");
244 exit(EXIT_FAILURE);
245 }
246
247 return ret;
248}
249
250static void add_vsock_stat(struct list_head *sockets,
251 const struct vsock_diag_msg *resp)
252{
253 struct vsock_stat *st;
254
255 st = malloc(sizeof(*st));
256 if (!st) {
257 perror("malloc");
258 exit(EXIT_FAILURE);
259 }
260
261 st->msg = *resp;
262 list_add_tail(&st->list, sockets);
263}
264
265/*
266 * Read vsock stats into a list.
267 */
268static void read_vsock_stat(struct list_head *sockets)
269{
270 long buf[8192 / sizeof(long)];
271 int fd;
272
273 fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_SOCK_DIAG);
274 if (fd < 0) {
275 perror("socket");
276 exit(EXIT_FAILURE);
277 }
278
279 send_req(fd);
280
281 for (;;) {
282 const struct nlmsghdr *h;
283 ssize_t ret;
284
285 ret = recv_resp(fd, buf, sizeof(buf));
286 if (ret == 0)
287 goto done;
288 if (ret < sizeof(*h)) {
289 fprintf(stderr, "short read of %zd bytes\n", ret);
290 exit(EXIT_FAILURE);
291 }
292
293 h = (struct nlmsghdr *)buf;
294
295 while (NLMSG_OK(h, ret)) {
296 if (h->nlmsg_type == NLMSG_DONE)
297 goto done;
298
299 if (h->nlmsg_type == NLMSG_ERROR) {
300 const struct nlmsgerr *err = NLMSG_DATA(h);
301
302 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(*err)))
303 fprintf(stderr, "NLMSG_ERROR\n");
304 else {
305 errno = -err->error;
306 perror("NLMSG_ERROR");
307 }
308
309 exit(EXIT_FAILURE);
310 }
311
312 if (h->nlmsg_type != SOCK_DIAG_BY_FAMILY) {
313 fprintf(stderr, "unexpected nlmsg_type %#x\n",
314 h->nlmsg_type);
315 exit(EXIT_FAILURE);
316 }
317 if (h->nlmsg_len <
318 NLMSG_LENGTH(sizeof(struct vsock_diag_msg))) {
319 fprintf(stderr, "short vsock_diag_msg\n");
320 exit(EXIT_FAILURE);
321 }
322
323 add_vsock_stat(sockets, NLMSG_DATA(h));
324
325 h = NLMSG_NEXT(h, ret);
326 }
327 }
328
329done:
330 close(fd);
331}
332
333static void free_sock_stat(struct list_head *sockets)
334{
335 struct vsock_stat *st;
336 struct vsock_stat *next;
337
338 list_for_each_entry_safe(st, next, sockets, list)
339 free(st);
340}
341
342static void test_no_sockets(unsigned int peer_cid)
343{
344 LIST_HEAD(sockets);
345
346 read_vsock_stat(&sockets);
347
348 check_no_sockets(&sockets);
349
350 free_sock_stat(&sockets);
351}
352
353static void test_listen_socket_server(unsigned int peer_cid)
354{
355 union {
356 struct sockaddr sa;
357 struct sockaddr_vm svm;
358 } addr = {
359 .svm = {
360 .svm_family = AF_VSOCK,
361 .svm_port = 1234,
362 .svm_cid = VMADDR_CID_ANY,
363 },
364 };
365 LIST_HEAD(sockets);
366 struct vsock_stat *st;
367 int fd;
368
369 fd = socket(AF_VSOCK, SOCK_STREAM, 0);
370
371 if (bind(fd, &addr.sa, sizeof(addr.svm)) < 0) {
372 perror("bind");
373 exit(EXIT_FAILURE);
374 }
375
376 if (listen(fd, 1) < 0) {
377 perror("listen");
378 exit(EXIT_FAILURE);
379 }
380
381 read_vsock_stat(&sockets);
382
383 check_num_sockets(&sockets, 1);
384 st = find_vsock_stat(&sockets, fd);
385 check_socket_state(st, TCP_LISTEN);
386
387 close(fd);
388 free_sock_stat(&sockets);
389}
390
391static void test_connect_client(unsigned int peer_cid)
392{
393 union {
394 struct sockaddr sa;
395 struct sockaddr_vm svm;
396 } addr = {
397 .svm = {
398 .svm_family = AF_VSOCK,
399 .svm_port = 1234,
400 .svm_cid = peer_cid,
401 },
402 };
403 int fd;
404 int ret;
405 LIST_HEAD(sockets);
406 struct vsock_stat *st;
407
408 control_expectln("LISTENING");
409
410 fd = socket(AF_VSOCK, SOCK_STREAM, 0);
411
412 timeout_begin(TIMEOUT);
413 do {
414 ret = connect(fd, &addr.sa, sizeof(addr.svm));
415 timeout_check("connect");
416 } while (ret < 0 && errno == EINTR);
417 timeout_end();
418
419 if (ret < 0) {
420 perror("connect");
421 exit(EXIT_FAILURE);
422 }
423
424 read_vsock_stat(&sockets);
425
426 check_num_sockets(&sockets, 1);
427 st = find_vsock_stat(&sockets, fd);
428 check_socket_state(st, TCP_ESTABLISHED);
429
430 control_expectln("DONE");
431 control_writeln("DONE");
432
433 close(fd);
434 free_sock_stat(&sockets);
435}
436
437static void test_connect_server(unsigned int peer_cid)
438{
439 union {
440 struct sockaddr sa;
441 struct sockaddr_vm svm;
442 } addr = {
443 .svm = {
444 .svm_family = AF_VSOCK,
445 .svm_port = 1234,
446 .svm_cid = VMADDR_CID_ANY,
447 },
448 };
449 union {
450 struct sockaddr sa;
451 struct sockaddr_vm svm;
452 } clientaddr;
453 socklen_t clientaddr_len = sizeof(clientaddr.svm);
454 LIST_HEAD(sockets);
455 struct vsock_stat *st;
456 int fd;
457 int client_fd;
458
459 fd = socket(AF_VSOCK, SOCK_STREAM, 0);
460
461 if (bind(fd, &addr.sa, sizeof(addr.svm)) < 0) {
462 perror("bind");
463 exit(EXIT_FAILURE);
464 }
465
466 if (listen(fd, 1) < 0) {
467 perror("listen");
468 exit(EXIT_FAILURE);
469 }
470
471 control_writeln("LISTENING");
472
473 timeout_begin(TIMEOUT);
474 do {
475 client_fd = accept(fd, &clientaddr.sa, &clientaddr_len);
476 timeout_check("accept");
477 } while (client_fd < 0 && errno == EINTR);
478 timeout_end();
479
480 if (client_fd < 0) {
481 perror("accept");
482 exit(EXIT_FAILURE);
483 }
484 if (clientaddr.sa.sa_family != AF_VSOCK) {
485 fprintf(stderr, "expected AF_VSOCK from accept(2), got %d\n",
486 clientaddr.sa.sa_family);
487 exit(EXIT_FAILURE);
488 }
489 if (clientaddr.svm.svm_cid != peer_cid) {
490 fprintf(stderr, "expected peer CID %u from accept(2), got %u\n",
491 peer_cid, clientaddr.svm.svm_cid);
492 exit(EXIT_FAILURE);
493 }
494
495 read_vsock_stat(&sockets);
496
497 check_num_sockets(&sockets, 2);
498 find_vsock_stat(&sockets, fd);
499 st = find_vsock_stat(&sockets, client_fd);
500 check_socket_state(st, TCP_ESTABLISHED);
501
502 control_writeln("DONE");
503 control_expectln("DONE");
504
505 close(client_fd);
506 close(fd);
507 free_sock_stat(&sockets);
508}
509
510static struct {
511 const char *name;
512 void (*run_client)(unsigned int peer_cid);
513 void (*run_server)(unsigned int peer_cid);
514} test_cases[] = {
515 {
516 .name = "No sockets",
517 .run_server = test_no_sockets,
518 },
519 {
520 .name = "Listen socket",
521 .run_server = test_listen_socket_server,
522 },
523 {
524 .name = "Connect",
525 .run_client = test_connect_client,
526 .run_server = test_connect_server,
527 },
528 {},
529};
530
531static void init_signals(void)
532{
533 struct sigaction act = {
534 .sa_handler = sigalrm,
535 };
536
537 sigaction(SIGALRM, &act, NULL);
538 signal(SIGPIPE, SIG_IGN);
539}
540
541static unsigned int parse_cid(const char *str)
542{
543 char *endptr = NULL;
544 unsigned long int n;
545
546 errno = 0;
547 n = strtoul(str, &endptr, 10);
548 if (errno || *endptr != '\0') {
549 fprintf(stderr, "malformed CID \"%s\"\n", str);
550 exit(EXIT_FAILURE);
551 }
552 return n;
553}
554
555static const char optstring[] = "";
556static const struct option longopts[] = {
557 {
558 .name = "control-host",
559 .has_arg = required_argument,
560 .val = 'H',
561 },
562 {
563 .name = "control-port",
564 .has_arg = required_argument,
565 .val = 'P',
566 },
567 {
568 .name = "mode",
569 .has_arg = required_argument,
570 .val = 'm',
571 },
572 {
573 .name = "peer-cid",
574 .has_arg = required_argument,
575 .val = 'p',
576 },
577 {
578 .name = "help",
579 .has_arg = no_argument,
580 .val = '?',
581 },
582 {},
583};
584
585static void usage(void)
586{
587 fprintf(stderr, "Usage: vsock_diag_test [--help] [--control-host=<host>] --control-port=<port> --mode=client|server --peer-cid=<cid>\n"
588 "\n"
589 " Server: vsock_diag_test --control-port=1234 --mode=server --peer-cid=3\n"
590 " Client: vsock_diag_test --control-host=192.168.0.1 --control-port=1234 --mode=client --peer-cid=2\n"
591 "\n"
592 "Run vsock_diag.ko tests. Must be launched in both\n"
593 "guest and host. One side must use --mode=client and\n"
594 "the other side must use --mode=server.\n"
595 "\n"
596 "A TCP control socket connection is used to coordinate tests\n"
597 "between the client and the server. The server requires a\n"
598 "listen address and the client requires an address to\n"
599 "connect to.\n"
600 "\n"
601 "The CID of the other side must be given with --peer-cid=<cid>.\n");
602 exit(EXIT_FAILURE);
603}
604
605int main(int argc, char **argv)
606{
607 const char *control_host = NULL;
608 const char *control_port = NULL;
609 int mode = TEST_MODE_UNSET;
610 unsigned int peer_cid = VMADDR_CID_ANY;
611 int i;
612
613 init_signals();
614
615 for (;;) {
616 int opt = getopt_long(argc, argv, optstring, longopts, NULL);
617
618 if (opt == -1)
619 break;
620
621 switch (opt) {
622 case 'H':
623 control_host = optarg;
624 break;
625 case 'm':
626 if (strcmp(optarg, "client") == 0)
627 mode = TEST_MODE_CLIENT;
628 else if (strcmp(optarg, "server") == 0)
629 mode = TEST_MODE_SERVER;
630 else {
631 fprintf(stderr, "--mode must be \"client\" or \"server\"\n");
632 return EXIT_FAILURE;
633 }
634 break;
635 case 'p':
636 peer_cid = parse_cid(optarg);
637 break;
638 case 'P':
639 control_port = optarg;
640 break;
641 case '?':
642 default:
643 usage();
644 }
645 }
646
647 if (!control_port)
648 usage();
649 if (mode == TEST_MODE_UNSET)
650 usage();
651 if (peer_cid == VMADDR_CID_ANY)
652 usage();
653
654 if (!control_host) {
655 if (mode != TEST_MODE_SERVER)
656 usage();
657 control_host = "0.0.0.0";
658 }
659
660 control_init(control_host, control_port, mode == TEST_MODE_SERVER);
661
662 for (i = 0; test_cases[i].name; i++) {
663 void (*run)(unsigned int peer_cid);
664
665 printf("%s...", test_cases[i].name);
666 fflush(stdout);
667
668 if (mode == TEST_MODE_CLIENT)
669 run = test_cases[i].run_client;
670 else
671 run = test_cases[i].run_server;
672
673 if (run)
674 run(peer_cid);
675
676 printf("ok\n");
677 }
678
679 control_cleanup();
680 return EXIT_SUCCESS;
681}