flow_parser: add shared parser library
Subsystems (2)
v12 cover flow_parser: add shared parser library
This series extracts the testpmd flow CLI parser into a reusable library, enabling external applications to parse rte_flow rules using testpmd syntax.
Motivation
----------
External applications like Suricata IDS [1] need to express hardware filtering rules in a consistent, human-readable format. Rather than inventing custom syntax, reusing testpmd's well-tested flow grammar provides immediate compatibility with existing documentation and user knowledge.
Note: This library provides only one way to create rte_flow structures. Applications can also construct rte_flow_attr, rte_flow_item[], and rte_flow_action[] directly in C code.
Design
------
The library (librte_flow_parser) exposes the following APIs:
- rte_flow_parser_parse_attr_str(): Parse attributes only
- rte_flow_parser_parse_pattern_str(): Parse patterns only
- rte_flow_parser_parse_actions_str(): Parse actions only
Testpmd is updated to use the library, ensuring a single maintained parser implementation.
Testing and Demo
-------
- Functional tests in dpdk-test
- Example application: examples/flow_parsing
Changes
-------
v12:
- flipped the ethdev dependency on cmdline, now cmdline depends on ethdev
- added Bruce's ACK from v11 to the MSVC commit
v11:
- targetting 26.07 now
- MAJOR overhaul of the patch set to make every part of the library API public and reusable, while only parsing flow testpmd commands.
- library splitted into a "simple" part and "cmdline" part
- testpmd changed to use the "cmdline" part of the library, and also to handle most of the "set" commands itself, while still using the library to parse the parameters of the "set" commands. Previous "operation callbacks" are now replaced by command-codes (enum) and the caller is expected to handle the command execution itself. Likewise, the ownership of helper structures, e.g. for vxlan/raw/sample etc. is in the hands of the caller, and the library only uses/fills them in with the parsed parameters.
v10:
- rebased to avoid Github Actions CI build failure
- merge conflict solved in rel_notes/release_26_03.rst
- release notes shortened
v9:
- removed extra new line from the flow parser docs file
v8:
- rte_port/queue_id_t typedefs removal to be included in a separate patch series
- move of accidental changes of rte_flow parser library from the testpmd commit
- DynaNIC copyright name update
v7:
- Fixed implicit integer comparison (while (left) -> while (left != 0))
- NULL checks fixed
- arpa header removed for Windows compatibility
- minor comments from the last review addressed
v6:
- Inconsistent Experimental API Version adjusted
- Fixes Tag added to MSVC build commit
- Non-Standard Header Guards updated
- Implicit Pointer Comparison and Return Type issues addressed in many places
- commit message in patch 6 updated
v5:
- removed/replaced (f)printf code from the library
- reverted back to exporting the internal/private API as it is needed by testpmd and cannot be easily split further.
- adjusted length of certain lines
- marking port/queue id typedef as experimental
- updated release rel_notes
- copyeright adjustments
v4:
- ethdev changes in separate commit
- library's public API only exposes attribute, pattern and action parsing, while the full command parsing is kept internal for testpmd usage only.
- Addressed Stephen's comments from V3
- dpdk-test now have tests focused on public and internal library functions
v3:
- Add more functional tests
- More concise MAINTAINERS updates
- Updated license headers
- A thing to note: When playing with flow commands, I figured, some may use non-flow commands, such as raw decap/encap, policy meter and others. Flow parser library itself now supports set command to set e.g. the decap/ encap parameters, as the flow syntax only supports defining the index of the encap/decap configs. The library, however, does not support e.g. create command to create policy meters, as that is just an ID and it can be created separately using rte_meter APIs.
[1] https://github.com/OISF/suricata/pull/13950
Lukas Sismis (6):
cmdline: include stddef.h for MSVC compatibility
ethdev: add RSS type helper APIs
ethdev: add flow parser library app/testpmd: use flow parser from ethdev examples/flow_parsing: add flow parser demo
test: add flow parser functional tests
MAINTAINERS | 6 +- app/test-pmd/cmd_flex_item.c | 47 +- app/test-pmd/cmdline.c | 249 +- app/test-pmd/config.c | 115 +- app/test-pmd/flow_parser.c | 288 + app/test-pmd/flow_parser_cli.c | 478 + app/test-pmd/meson.build | 3 +- app/test-pmd/testpmd.h | 135 +- app/test/meson.build | 2 + app/test/test_ethdev_api.c | 56 + app/test/test_flow_parser.c | 790 + app/test/test_flow_parser_simple.c | 445 + doc/api/doxy-api-index.md | 2 + doc/guides/prog_guide/flow_parser_lib.rst | 99 + doc/guides/prog_guide/index.rst | 1 + doc/guides/rel_notes/release_26_07.rst | 11 + doc/guides/sample_app_ug/flow_parsing.rst | 60 + doc/guides/sample_app_ug/index.rst | 1 + examples/flow_parsing/main.c | 409 + examples/flow_parsing/meson.build | 8 + examples/meson.build | 1 + lib/cmdline/cmdline_parse.h | 2 + lib/cmdline/meson.build | 8 +- lib/cmdline/rte_flow_parser_cmdline.c | 138 + lib/cmdline/rte_flow_parser_cmdline.h | 82 + lib/ethdev/meson.build | 3 + lib/ethdev/rte_ethdev.c | 109 + lib/ethdev/rte_ethdev.h | 60 + .../ethdev/rte_flow_parser.c | 12350 ++++++++-------- lib/ethdev/rte_flow_parser.h | 130 + lib/ethdev/rte_flow_parser_config.h | 583 + lib/ethdev/rte_flow_parser_internal.h | 124 + lib/meson.build | 4 +- 33 files changed, 10157 insertions(+), 6642 deletions(-) create mode 100644 app/test-pmd/flow_parser.c create mode 100644 app/test-pmd/flow_parser_cli.c create mode 100644 app/test/test_flow_parser.c create mode 100644 app/test/test_flow_parser_simple.c create mode 100644 doc/guides/prog_guide/flow_parser_lib.rst create mode 100644 doc/guides/sample_app_ug/flow_parsing.rst create mode 100644 examples/flow_parsing/main.c create mode 100644 examples/flow_parsing/meson.build create mode 100644 lib/cmdline/rte_flow_parser_cmdline.c create mode 100644 lib/cmdline/rte_flow_parser_cmdline.h rename app/test-pmd/cmdline_flow.c => lib/ethdev/rte_flow_parser.c (59%) create mode 100644 lib/ethdev/rte_flow_parser.h create mode 100644 lib/ethdev/rte_flow_parser_config.h create mode 100644 lib/ethdev/rte_flow_parser_internal.h
Signature · 1 line
2.43.7
PATCH v12 1/6 cmdline: include stddef.h for MSVC compatibility
Include <stddef.h> at the top of cmdline_parse.h before the fallback offsetof macro definition. This improves MSVC build compatibility by ensuring the standard offsetof is available before the fallback definition, avoiding macro redefinition warnings when building with /WX (warnings as errors).
The standard header provides offsetof on all platforms, and including it first ensures the fallback is only used when truly needed.
--- lib/cmdline/cmdline_parse.h | 2 ++ 1 file changed, 2 insertions(+)
lib/cmdline/cmdline_parse.h +2 -0
@@ -7,6 +7,8 @@ #ifndef _CMDLINE_PARSE_H_ #define _CMDLINE_PARSE_H_ +#include <stddef.h> + #ifdef __cplusplus extern "C" { #endif
Signature · 1 line
2.43.7
PATCH v12 2/6 ethdev: add RSS type helper APIs
In reply to Lukas SismisAdd a global RSS type string table and helper functions to convert between RSS type names and values.
Add unit tests for RSS type helper.
--- app/test/test_ethdev_api.c | 56 +++++++++++++ doc/guides/rel_notes/release_26_07.rst | 5 ++ lib/ethdev/rte_ethdev.c | 109 +++++++++++++++++++++++++ lib/ethdev/rte_ethdev.h | 60 ++++++++++++++ 4 files changed, 230 insertions(+)
app/test/test_ethdev_api.c +56 -0
@@ -2,6 +2,9 @@* Copyright (C) 2023, Advanced Micro Devices, Inc. */ +#include <stdbool.h> +#include <string.h> +#include <rte_log.h> #include <rte_ethdev.h>
@@ -162,12 +165,65 @@ ethdev_api_queue_status(void)return TEST_SUCCESS ; } +static int +ethdev_api_rss_type_helpers (void ) +{ +const struct rte_eth_rss_type_info *tbl; +const char *zero_name =NULL ; +unsigned int i; +bool has_zero = false; +const char *name; +uint64_t type; + + tbl =rte_eth_rss_type_info_get (); +TEST_ASSERT_NOT_NULL (tbl,"rss type table missing" ); + +for (i =0 ; tbl[i].str !=NULL ; i++) { +TEST_ASSERT_SUCCESS (rte_eth_rss_type_from_str (tbl[i].str, + &type),"rss type lookup failed for %s" , tbl[i].str); +TEST_ASSERT_EQUAL (type, tbl[i].rss_type, +"rss type mismatch for %s" , tbl[i].str); + +if (tbl[i].rss_type ==0 && !has_zero) { + has_zero = true; + zero_name = tbl[i].str; + } + + name =rte_eth_rss_type_to_str (tbl[i].rss_type); +TEST_ASSERT_NOT_NULL (name,"rss type name missing for %s" , + tbl[i].str); +TEST_ASSERT_SUCCESS (rte_eth_rss_type_from_str (name, &type), +"rss type round-trip lookup failed for %s" , name); +TEST_ASSERT_EQUAL (type, tbl[i].rss_type, +"rss type round-trip mismatch for %s" , name); + } + +TEST_ASSERT (tbl[i].str ==NULL ,"rss type table not NULL terminated" ); +TEST_ASSERT (rte_eth_rss_type_from_str (NULL , &type) !=0 , +"rss type from NULL str should fail" ); +TEST_ASSERT (rte_eth_rss_type_from_str ("ipv4" ,NULL ) !=0 , +"rss type from NULL rss_type should fail" ); +TEST_ASSERT (rte_eth_rss_type_from_str ("not-a-type" , &type) !=0 , +"rss type unknown should fail" ); + name =rte_eth_rss_type_to_str (0 ); +if (has_zero) { +TEST_ASSERT_NOT_NULL (name,"rss type 0 should be defined" ); +TEST_ASSERT (strcmp (name, zero_name) ==0 , +"rss type 0 name mismatch" ); + }else { +TEST_ASSERT (name ==NULL ,"rss type 0 should be NULL" ); + } + +return TEST_SUCCESS ; +} +static struct unit_test_suite ethdev_api_testsuite = { .suite_name ="ethdev API tests" , .setup =NULL , .teardown =NULL , .unit_test_cases = {TEST_CASE (ethdev_api_queue_status), +TEST_CASE (ethdev_api_rss_type_helpers),/* TODO: Add deferred_start queue status test */ TEST_CASES_END ()/**< NULL terminate unit test array */ }
doc/guides/rel_notes/release_26_07.rst +5 -0
@@ -63,6 +63,11 @@ New Features ``rte_eal_init`` and the application is responsible for probing each device, * ``--auto-probing`` enables the initial bus probing, which is the current default behavior. +* **Added experimental RSS type helper APIs in ethdev.** + + * Added new APIs to convert between RSS type names and values. + * Added new API call to obtain the global RSS string table. + Removed Items -------------
lib/ethdev/rte_ethdev.c +109 -0
115 lines not on this page · raw message
lib/ethdev/rte_ethdev.h +60 -0
66 lines not on this page · raw message
Signature · 1 line
2.43.7
PATCH v12 3/6 ethdev: add flow parser library
In reply to Lukas SismisAdd flow rule string parsing to librte_ethdev. The parser converts flow command strings into rte_flow C structures.
Two public headers:
- rte_flow_parser.h: standalone string-to-struct helpers for attributes, patterns, and actions. Thread-safe per-lcore.
- rte_flow_parser_cmdline.h: full command parsing with cmdline dynamic token integration and tab completion. Applications register configuration storage via rte_flow_parser_config and receive parsed commands through a dispatch callback.
Configuration is application-owned: the library stores no mutable config state. Applications allocate encap/decap, raw, ipv6_ext, and sample slot storage and register pointers at init time.
Setter APIs serialize pattern/action items into raw encap/decap and ipv6 extension configurations.
--- MAINTAINERS | 2 +- doc/api/doxy-api-index.md | 2 + doc/guides/prog_guide/flow_parser_lib.rst | 99 + doc/guides/prog_guide/index.rst | 1 + doc/guides/rel_notes/release_26_07.rst | 6 + lib/cmdline/meson.build | 8 +- lib/cmdline/rte_flow_parser_cmdline.c | 138 + lib/cmdline/rte_flow_parser_cmdline.h | 82 + lib/ethdev/meson.build | 3 + lib/ethdev/rte_flow_parser.c | 14230 ++++++++++++++++++++ lib/ethdev/rte_flow_parser.h | 130 + lib/ethdev/rte_flow_parser_config.h | 583 + lib/ethdev/rte_flow_parser_internal.h | 124 + lib/meson.build | 4 +- 14 files changed, 15406 insertions(+), 6 deletions(-) create mode 100644 doc/guides/prog_guide/flow_parser_lib.rst create mode 100644 lib/cmdline/rte_flow_parser_cmdline.c create mode 100644 lib/cmdline/rte_flow_parser_cmdline.h create mode 100644 lib/ethdev/rte_flow_parser.c create mode 100644 lib/ethdev/rte_flow_parser.h create mode 100644 lib/ethdev/rte_flow_parser_config.h create mode 100644 lib/ethdev/rte_flow_parser_internal.h
MAINTAINERS +1 -1
@@ -444,8 +444,8 @@ F: doc/guides/prog_guide/ethdev/switch_representation.rst Flow API M: Ori Kam <[email protected]> T: git://dpdk.org/next/dpdk-next-net -F: app/test-pmd/cmdline_flow.c F: doc/guides/prog_guide/ethdev/flow_offload.rst +F: doc/guides/prog_guide/flow_parser_lib.rst F: lib/ethdev/rte_flow* Traffic Management API
doc/api/doxy-api-index.md +2 -0
@@ -13,6 +13,8 @@ The public API headers are grouped by topics: [ethdev](@ref rte_ethdev.h), [ethctrl](@ref rte_eth_ctrl.h), [rte_flow](@ref rte_flow.h), + [flow_parser](@ref rte_flow_parser.h), + [flow_parser_cmdline](@ref rte_flow_parser_cmdline.h), [rte_tm](@ref rte_tm.h), [rte_mtr](@ref rte_mtr.h), [bbdev](@ref rte_bbdev.h),
doc/guides/prog_guide/flow_parser_lib.rst new file +99 -0
99 lines not on this page · raw message
doc/guides/prog_guide/index.rst +1 -0
@@ -121,6 +121,7 @@ Utility Libraries argparse_lib cmdline + flow_parser_lib ptr_compress_lib timer_lib rcu_lib
doc/guides/rel_notes/release_26_07.rst +6 -0
@@ -68,6 +68,12 @@ New Features * Added new APIs to convert between RSS type names and values. * Added new API call to obtain the global RSS string table. +* **Added experimental flow parser to ethdev.** + + * Introduced ``rte_flow_parser`` helpers in ethdev to convert the + testpmd's ``flow`` CLI commands into ``rte_flow`` structures. + See ``rte_flow_parser.h`` and ``rte_flow_parser_cmdline.h``. + Removed Items -------------
lib/cmdline/meson.build +5 -3
@@ -12,7 +12,8 @@ sources = files('cmdline.c', 'cmdline_parse_string.c', 'cmdline_rdline.c', 'cmdline_socket.c', - 'cmdline_vt100.c') + 'cmdline_vt100.c', + 'rte_flow_parser_cmdline.c') headers = files('cmdline.h', 'cmdline_parse.h',
@@ -25,7 +26,8 @@ headers = files('cmdline.h', 'cmdline_vt100.h', 'cmdline_socket.h', 'cmdline_cirbuf.h', - 'cmdline_parse_portlist.h') + 'cmdline_parse_portlist.h', + 'rte_flow_parser_cmdline.h') if is_windows sources += files('cmdline_os_windows.c')
@@ -33,4 +35,4 @@ else sources += files('cmdline_os_unix.c') endif -deps += ['net'] +deps += ['net', 'ethdev']
lib/cmdline/rte_flow_parser_cmdline.c new file +138 -0
138 lines not on this page · raw message
lib/cmdline/rte_flow_parser_cmdline.h new file +82 -0
82 lines not on this page · raw message
lib/ethdev/meson.build +3 -0
@@ -11,6 +11,7 @@ sources = files( 'rte_ethdev_cman.c', 'rte_ethdev_telemetry.c', 'rte_flow.c', + 'rte_flow_parser.c', 'rte_mtr.c', 'rte_tm.c', 'sff_telemetry.c',
@@ -26,6 +27,8 @@ headers = files( 'rte_ethdev_trace_fp.h', 'rte_dev_info.h', 'rte_flow.h', + 'rte_flow_parser.h', + 'rte_flow_parser_config.h', 'rte_mtr.h', 'rte_tm.h', )
lib/ethdev/rte_flow_parser.c new file +14230 -0
2,607 lines not on this page · raw message
lib/ethdev/rte_flow_parser.h new file +130 -0
130 lines not on this page · raw message
lib/ethdev/rte_flow_parser_config.h new file +583 -0
583 lines not on this page · raw message
lib/ethdev/rte_flow_parser_internal.h new file +124 -0
124 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.43.7
Part of the diff is not shown here. View the raw message.
PATCH v12 4/6 app/testpmd: use flow parser from ethdev
In reply to Lukas SismisReplace the embedded flow command parser with the shared parser from librte_ethdev.
Testpmd owns all configuration storage (encap/decap, raw, ipv6_ext, sample slots) and registers it via rte_flow_parser_config_register. Parsed flow commands are dispatched to port_flow_* functions.
SET commands (raw_encap, raw_decap, sample_actions, ipv6_ext_push, ipv6_ext_remove) are handled by testpmd's own cmdline callback, which delegates pattern/action item tokenization to the library for tab completion.
--- MAINTAINERS | 1 + app/test-pmd/cmd_flex_item.c | 47 +- app/test-pmd/cmdline.c | 249 +- app/test-pmd/cmdline_flow.c | 14434 ------------------------------- app/test-pmd/config.c | 115 +- app/test-pmd/flow_parser.c | 288 + app/test-pmd/flow_parser_cli.c | 478 + app/test-pmd/meson.build | 3 +- app/test-pmd/testpmd.h | 135 +- 9 files changed, 957 insertions(+), 14793 deletions(-) delete mode 100644 app/test-pmd/cmdline_flow.c create mode 100644 app/test-pmd/flow_parser.c create mode 100644 app/test-pmd/flow_parser_cli.c
MAINTAINERS +1 -0
@@ -446,6 +446,7 @@ M: Ori Kam <[email protected]> T: git://dpdk.org/next/dpdk-next-net F: doc/guides/prog_guide/ethdev/flow_offload.rst F: doc/guides/prog_guide/flow_parser_lib.rst +F: app/test-pmd/flow_parser* F: lib/ethdev/rte_flow* Traffic Management API
app/test-pmd/cmd_flex_item.c +28 -19
73 lines not on this page · raw message
app/test-pmd/cmdline.c +132 -117
417 lines not on this page · raw message
app/test-pmd/cmdline_flow.c deleted +0 -14434
2,503 lines not on this page · raw message
app/test-pmd/config.c +13 -102
115 lines not on this page · raw message
app/test-pmd/flow_parser.c new file +288 -0
288 lines not on this page · raw message
app/test-pmd/flow_parser_cli.c new file +478 -0
478 lines not on this page · raw message
app/test-pmd/testpmd.h +15 -120
135 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.43.7
Part of the diff is not shown here. View the raw message.
PATCH v12 5/6 examples/flow_parsing: add flow parser demo
In reply to Lukas SismisAdd a standalone example demonstrating the flow parser API. Parses attribute, pattern, and action strings into rte_flow structures and prints the results.
--- MAINTAINERS | 2 + doc/guides/sample_app_ug/flow_parsing.rst | 60 ++++ doc/guides/sample_app_ug/index.rst | 1 + examples/flow_parsing/main.c | 409 ++++++++++++++++++++++ examples/flow_parsing/meson.build | 8 + examples/meson.build | 1 + 6 files changed, 481 insertions(+) create mode 100644 doc/guides/sample_app_ug/flow_parsing.rst create mode 100644 examples/flow_parsing/main.c create mode 100644 examples/flow_parsing/meson.build
MAINTAINERS +2 -0
@@ -448,6 +448,8 @@ F: doc/guides/prog_guide/ethdev/flow_offload.rst F: doc/guides/prog_guide/flow_parser_lib.rst F: app/test-pmd/flow_parser* F: lib/ethdev/rte_flow* +F: doc/guides/sample_app_ug/flow_parsing.rst +F: examples/flow_parsing/ Traffic Management API M: Cristian Dumitrescu <[email protected]>
doc/guides/sample_app_ug/flow_parsing.rst new file +60 -0
60 lines not on this page · raw message
doc/guides/sample_app_ug/index.rst +1 -0
@@ -16,6 +16,7 @@ Sample Applications User Guides skeleton rxtx_callbacks flow_filtering + flow_parsing ip_frag ipv4_multicast ip_reassembly
examples/flow_parsing/main.c new file +409 -0
409 lines not on this page · raw message
examples/flow_parsing/meson.build new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2026 DynaNIC Semiconductors, Ltd. + +# meson file, for building this example as part of a main DPDK build. + +allow_experimental_apis = true +deps += 'ethdev' +sources = files('main.c')
examples/meson.build +1 -0
@@ -17,6 +17,7 @@ all_examples = [ 'eventdev_pipeline', 'fips_validation', 'flow_filtering', + 'flow_parsing', 'helloworld', 'ip_fragmentation', 'ip_pipeline',
Signature · 1 line
2.43.7
PATCH v12 6/6 test: add flow parser functional tests
In reply to Lukas SismisUnit tests covering:
- Simple API: parse_attr_str, parse_pattern_str, parse_actions_str, parse_flow_rule
- Cmdline API: rte_flow_parser_parse with flow create, validate, indirect_action, meter, modify_field, queue, and port_id commands
- Setter APIs: raw_encap/decap set + get round-trip, boundary checks for out-of-range indices
- Config registration: pointer identity verification
- Cmdline integration: dynamic token population
Simple API tests work without config registration.
--- MAINTAINERS | 1 + app/test/meson.build | 2 + app/test/test_flow_parser.c | 790 +++++++++++++++++++++++++++++ app/test/test_flow_parser_simple.c | 445 ++++++++++++++++ 4 files changed, 1238 insertions(+) create mode 100644 app/test/test_flow_parser.c create mode 100644 app/test/test_flow_parser_simple.c
MAINTAINERS +1 -0
@@ -450,6 +450,7 @@ F: app/test-pmd/flow_parser* F: lib/ethdev/rte_flow* F: doc/guides/sample_app_ug/flow_parsing.rst F: examples/flow_parsing/ +F: app/test/test_flow_parser* Traffic Management API M: Cristian Dumitrescu <[email protected]>
app/test/meson.build +2 -0
@@ -88,6 +88,8 @@ source_file_deps = { 'test_fib6_perf.c': ['fib'], 'test_fib_perf.c': ['net', 'fib'], 'test_flow_classify.c': ['net', 'acl', 'table', 'ethdev', 'flow_classify'], + 'test_flow_parser.c': ['ethdev', 'cmdline'], + 'test_flow_parser_simple.c': ['ethdev'], 'test_func_reentrancy.c': ['hash', 'lpm'], 'test_graph.c': ['graph'], 'test_graph_feature_arc.c': ['graph'],
app/test/test_flow_parser.c new file +790 -0
790 lines not on this page · raw message
app/test/test_flow_parser_simple.c new file +445 -0
445 lines not on this page · raw message
Signature · 1 line
2.43.7
út 5. 5. 2026 v 20:39 odesílatel Lukas Sismis <[email protected]> napsal:
Quoted 175 lines
This series extracts the testpmd flow CLI parser into a reusable library, enabling external applications to parse
rte_flowrules using testpmd syntax.Motivation
----------
External applications like Suricata IDS [1] need to express hardware filtering
rules in a consistent, human-readable format. Rather than inventing custom syntax, reusing testpmd's well-tested flow grammar provides immediate compatibility with existing documentation and user knowledge.Note: This library provides only one way to create
rte_flowstructures. Applications can also constructrte_flow_attr, rte_flow_item[], and rte_flow_action[] directly in C code.Design
------
The library (librte_flow_parser) exposes the following APIs:
-rte_flow_parser_parse_attr_str(): Parse attributes only
-rte_flow_parser_parse_pattern_str(): Parse patterns only
-rte_flow_parser_parse_actions_str(): Parse actions onlyTestpmd is updated to use the library, ensuring a single maintained parser implementation.
Testing and Demo
-------
- Functional tests in dpdk-test
- Example application: examples/flow_parsingChanges
-------
v12:
- flipped the ethdev dependency on cmdline, now cmdline depends on ethdev
- added Bruce's ACK from v11 to the MSVC commitv11:
- targetting 26.07 now
- MAJOR overhaul of the patch set to make every part of the library API public
and reusable, while only parsing flow testpmd commands.
- library splitted into a "simple" part and "cmdline" part
- testpmd changed to use the "cmdline" part of the library, and also to handle
most of the "set" commands itself, while still using the library to
parse
the parameters of the "set" commands. Previous "operation callbacks" are
now
replaced by command-codes (enum) and the caller is expected to handle the command execution itself. Likewise, the ownership of helper
structures,
e.g. for vxlan/raw/sample etc. is in the hands of the caller, and the
library
only uses/fills them in with the parsed parameters.v10:
- rebased to avoid Github Actions CI build failure
- merge conflict solved inrel_notes/release_26_03.rst
- release notes shortenedv9:
- removed extra new line from the flow parser docs filev8:
- rte_port/queue_id_t typedefs removal to be included in a separate patch series
- move of accidental changes ofrte_flowparser library from the testpmd commit
- DynaNIC copyright name updatev7:
- Fixed implicit integer comparison (while (left) -> while (left != 0))
- NULL checks fixed
- arpa header removed for Windows compatibility
- minor comments from the last review addressedv6:
- Inconsistent Experimental API Version adjusted
- Fixes Tag added to MSVC build commit
- Non-Standard Header Guards updated
- Implicit Pointer Comparison and Return Type issues addressed in many places
- commit message in patch 6 updatedv5:
- removed/replaced (f)printf code from the library
- reverted back to exporting the internal/private API as it is needed by testpmd and cannot be easily split further.
- adjusted length of certain lines
- marking port/queue id typedef as experimental
- updated releaserel_notes
- copyeright adjustmentsv4:
- ethdev changes in separate commit
- library's public API only exposes attribute, pattern and action parsing, while the full command parsing is kept internal for testpmd usage only.
- Addressed Stephen's comments from V3
- dpdk-test now have tests focused on public and internal library functionsv3:
- Add more functional tests
- More conciseMAINTAINERSupdates
- Updated license headers
- A thing to note: When playing with flow commands, I figured, some may use non-flow commands, such as raw decap/encap, policy meter and others. Flow parser library itself now supportssetcommand to set e.g. the
decap/
encap parameters, as the flow syntax only supports defining the index of
the
encap/decap configs. The library, however, does not support e.g.createcommand to create policy meters, as that is just an ID and it can be
created
separately usingrte_meterAPIs.[1] https://github.com/OISF/suricata/pull/13950
Lukas Sismis (6):
cmdline: includestddef.hfor MSVC compatibility
ethdev: add RSS type helper APIs
ethdev: add flow parser library app/testpmd: use flow parser from ethdev examples/flow_parsing: add flow parser demo
test: add flow parser functional testsMAINTAINERS | 6 +- app/test-pmd/cmd_flex_item.c | 47 +- app/test-pmd/cmdline.c | 249 +- app/test-pmd/config.c | 115 +- app/test-pmd/flow_parser.c | 288 + app/test-pmd/flow_parser_cli.c | 478 + app/test-pmd/meson.build | 3 +- app/test-pmd/testpmd.h | 135 +- app/test/meson.build | 2 + app/test/test_ethdev_api.c | 56 + app/test/test_flow_parser.c | 790 + app/test/test_flow_parser_simple.c | 445 + doc/api/doxy-api-index.md | 2 + doc/guides/prog_guide/flow_parser_lib.rst | 99 + doc/guides/prog_guide/index.rst | 1 + doc/guides/rel_notes/release_26_07.rst | 11 + doc/guides/sample_app_ug/flow_parsing.rst | 60 + doc/guides/sample_app_ug/index.rst | 1 + examples/flow_parsing/main.c | 409 + examples/flow_parsing/meson.build | 8 + examples/meson.build | 1 + lib/cmdline/cmdline_parse.h | 2 + lib/cmdline/meson.build | 8 +- lib/cmdline/rte_flow_parser_cmdline.c | 138 + lib/cmdline/rte_flow_parser_cmdline.h | 82 + lib/ethdev/meson.build | 3 + lib/ethdev/rte_ethdev.c | 109 + lib/ethdev/rte_ethdev.h | 60 + .../ethdev/rte_flow_parser.c | 12350 ++++++++-------- lib/ethdev/rte_flow_parser.h | 130 + lib/ethdev/rte_flow_parser_config.h | 583 + lib/ethdev/rte_flow_parser_internal.h | 124 + lib/meson.build | 4 +- 33 files changed, 10157 insertions(+), 6642 deletions(-) create mode 100644 app/test-pmd/flow_parser.c create mode 100644 app/test-pmd/flow_parser_cli.c create mode 100644 app/test/test_flow_parser.c create mode 100644 app/test/test_flow_parser_simple.c create mode 100644 doc/guides/prog_guide/flow_parser_lib.rst create mode 100644 doc/guides/sample_app_ug/flow_parsing.rst create mode 100644 examples/flow_parsing/main.c create mode 100644 examples/flow_parsing/meson.build create mode 100644 lib/cmdline/rte_flow_parser_cmdline.c create mode 100644 lib/cmdline/rte_flow_parser_cmdline.h rename app/test-pmd/cmdline_flow.c => lib/ethdev/rte_flow_parser.c (59%) create mode 100644 lib/ethdev/rte_flow_parser.h create mode 100644 lib/ethdev/rte_flow_parser_config.h create mode 100644 lib/ethdev/rte_flow_parser_internal.h
Quoted 4 lines
--
2.43.7
Apparently, I missed documenting one field, so GH Actions will fail. But Stephen, can you please check and decide if this direction is viable? I didn't make the full parser part of the cmdline part, but now the cmdline has a dependency on ethdev.
I generally think, no matter the way you look at it, some added dependency will be present (and likely of cmdline on ethdev).
Thank you.
Quoted 21 lines · On Tue, 5 May 2026 20:39:07 +0200 Lukas Sismis <[email protected]> wrote:
This series extracts the testpmd flow CLI parser into a reusable library, enabling external applications to parse
rte_flowrules using testpmd syntax.Motivation
----------
External applications like Suricata IDS [1] need to express hardware filtering rules in a consistent, human-readable format. Rather than inventing custom syntax, reusing testpmd's well-tested flow grammar provides immediate compatibility with existing documentation and user knowledge.Note: This library provides only one way to create
rte_flowstructures. Applications can also constructrte_flow_attr, rte_flow_item[], and rte_flow_action[] directly in C code.Design
------
The library (librte_flow_parser) exposes the following APIs:
-rte_flow_parser_parse_attr_str(): Parse attributes only
-rte_flow_parser_parse_pattern_str(): Parse patterns only
-rte_flow_parser_parse_actions_str(): Parse actions only
Quoted 2 lines
Testpmd is updated to use the library, ensuring a single maintained parser implementation.
I wish it was not just a port of testpmd code to a library but had been done as a clean implementation; that said the current version is much better.
AI had lots of feedback. The part that matters to me is the new dependency chain; and also having a syntax that looks too much like testpmd.
Would prefer that only the flow part of the string was passed.
---
I have enough material for a comprehensive architectural review. Let me write it up.
---
Below is my deep-dive review of the v12 series. Architecturally, this is a major step beyond earlier versions in terms of polish (header split, doc page, real example, real tests), but the underlying structure is still essentially the testpmd cmdline_flow.c lifted wholesale into lib/ethdev, with a thin "simple API" wrapper that synthesizes fake testpmd commands. Several of the deeper structural problems remain, plus there are concrete bugs.
```
Series-level architectural review
=================================
Context
-------
The series moves the ~14,400-line app/test-pmd/cmdline_flow.c into a
new lib/ethdev/rte_flow_parser.c, exposes a "simple" string-to-rte_flow
API in lib/ethdev/rte_flow_parser.h, exposes a fuller cmdline-aware API
in lib/ethdev/rte_flow_parser_config.h, and adds cmdline glue in
lib/cmdline/rte_flow_parser_cmdline.[ch]. testpmd (patch 4) is then
ported to consume the library via a dispatch callback that maps
RTE_FLOW_PARSER_CMD_* enum values back onto its existing port_flow_*
functions.
The main functional change versus past versions is that the simple API
(parse_attr_str / parse_pattern_str / parse_actions_str /
parse_flow_rule) now exists separately from the full command grammar.
Internally however the simple API is still implemented by string-
synthesizing a fake "flow validate 0 ..." command, running it through
the full parser, and harvesting one output field. So the architectural
center of gravity is unchanged: this is the testpmd grammar exposed as
a library.
Errors
======
Patch 3/6 -- ethdev: add flow parser library
---------------------------------------------
A1. lib/cmdline now depends on lib/ethdev (layer inversion).
lib/cmdline/meson.build:
-deps += ['net']
+deps += ['net', 'ethdev']
lib/cmdline is a foundational utility used by examples, internal
tools, and tests that have nothing to do with networking. Pulling
ethdev into it just so rte_flow_parser_cmdline.c can call into
rte_flow_parser_* exports inverts the layering. Every consumer of
libcmdline now links libethdev.
The cmdline/flow-parser glue belongs in either lib/ethdev (and the
header in lib/ethdev too, with ethdev depending on cmdline -- the
natural direction) or in a new top-level lib/flow_parser that
depends on both. It does not belong inside lib/cmdline.
A2. The "simple API" returns aliased pointers into a single 4096-byte
static buffer, with no way for a caller to retain a result.
lib/ethdev/rte_flow_parser.c:
#define FLOW_PARSER_SIMPLE_BUF_SIZE 4096
static uint8_t flow_parser_simple_parse_buf[FLOW_PARSER_SIMPLE_BUF_SIZE];
...
static int parser_simple_parse(const char *cmd, ... **out) {
memset(flow_parser_simple_parse_buf, 0, sizeof(...));
ret = rte_flow_parser_parse(cmd,
(struct rte_flow_parser_output *)flow_parser_simple_parse_buf,
sizeof(flow_parser_simple_parse_buf));
...
*out = (struct rte_flow_parser_output *)flow_parser_simple_parse_buf;
}
Then rte_flow_parser_parse_pattern_str() does:
*pattern = out->args.vc.pattern; /* points into buf */
*pattern_n = out->args.vc.pattern_n;
Three resulting problems:
(a) Two consecutive calls alias. Any caller that wants to hold two
parsed patterns simultaneously (e.g. parse two flows and call
rte_flow_create() on each) cannot, without writing their own
deep-copy via rte_flow_conv(). This is a pervasive footgun and
is only loosely documented as "Points to internal storage valid
until the next parse call."
(b) The 4096-byte cap silently rejects any flow rule whose
serialized output exceeds the buffer (returns -ENOBUFS), with
no way for the caller to predict what fits.
(c) The simple API itself uses parse_pattern_str inside a setter
example flow in the example program:
ret = rte_flow_parser_parse_pattern_str(..., &items, &items_n);
if (ret == 0)
ret = rte_flow_parser_raw_encap_conf_set(0, items, items_n);
This particular sequence is safe today because raw_encap_conf_set
doesn't re-enter the parser, but nothing in the API contract
prevents a future parser call between (A) and (B), and the
example pattern teaches users a fragile idiom.
Suggested direction: provide a caller-supplied output mode -- e.g.
rte_flow_parser_parse_pattern_str(src, items, items_cap, &items_n)
where the caller provides storage. Or return an opaque handle owning
the storage (rte_flow_parser_pattern_new / _free), modeled on
rte_flow_conv().
A3. All cmdline tab-completion hooks for dynamic IDs are stubbed out
to return zero candidates, with no override mechanism.
lib/ethdev/rte_flow_parser.c:
static inline int
parser_port_id_is_invalid(uint16_t port_id)
{
(void)port_id;
return 0; /* always "valid" */
}
static inline uint16_t
parser_flow_rule_count(uint16_t port_id) { return 0; }
static inline int
parser_flow_rule_id_get(...) { return -ENOENT; }
/* same pattern for pattern/actions templates, tables, queues,
* RSS queues, indirect actions */
These are the routines comp_rule_id, comp_pattern_template_id,
comp_actions_template_id, comp_table_id, comp_queue_id, etc. all
call into when cmdline asks for tab-completion candidates. With
these stubs in place, the library version of testpmd interactive
mode can never tab-complete a rule ID, template ID, table ID,
queue ID, or indirect action ID -- a regression versus the
current testpmd cmdline_flow.c which queries port_flow_list,
port_flow_template_list, etc. directly.
patch 4 (testpmd integration) does not register or override these
stubs anywhere. There is no callback registration interface for
the application to provide "give me rule IDs for port N" / "give
me table IDs for port N" / etc.
A complete library extraction needs an introspection ops struct
that the application registers alongside rte_flow_parser_config,
e.g.:
struct rte_flow_parser_introspect_ops {
uint16_t (*flow_rule_count)(uint16_t port_id);
int (*flow_rule_id_get)(uint16_t port_id, unsigned idx,
uint64_t *rule_id);
/* templates, tables, queues, indirect actions, ... */
};
int rte_flow_parser_introspect_register(
const struct rte_flow_parser_introspect_ops *ops);
A4. testpmd dispatch repurposes rte_flow_attr.reserved as a side
channel for relaxed_matching.
app/test-pmd/flow_parser.c (patch 4):
case RTE_FLOW_PARSER_CMD_PATTERN_TEMPLATE_CREATE:
port_flow_pattern_template_create(in->port,
in->args.vc.pat_templ_id,
&((const struct rte_flow_pattern_template_attr) {
.relaxed_matching = in->args.vc.attr.reserved,
.ingress = in->args.vc.attr.ingress,
.egress = in->args.vc.attr.egress,
.transfer = in->args.vc.attr.transfer,
}),
in->args.vc.pattern);
rte_flow_attr.reserved is documented in lib/ethdev/rte_flow.h as
reserved and required to be zero. Smuggling
pattern_template_attr.relaxed_matching through that field couples
the library output to a hack and breaks the moment anyone sets
rte_flow_attr.reserved for any other purpose, or starts validating
it. The output struct already has a vc.{pat_templ,act_templ,table}
arm -- relaxed_matching belongs there, not overlaid on attr.reserved.
A5. Public preprocessor macros in rte_flow_parser_config.h are
unprefixed and one of them collides with a generic name.
lib/ethdev/rte_flow_parser_config.h:
#define ACTION_RAW_ENCAP_MAX_DATA 512
#define RAW_ENCAP_CONFS_MAX_NUM 8
#define ACTION_RSS_QUEUE_NUM 128
#define ACTION_VXLAN_ENCAP_ITEMS_NUM 6
#define ACTION_NVGRE_ENCAP_ITEMS_NUM 5
#define ACTION_IPV6_EXT_PUSH_MAX_DATA 512
#define IPV6_EXT_PUSH_CONFS_MAX_NUM 8
#define ACTION_SAMPLE_ACTIONS_NUM 10
#define RAW_SAMPLE_CONFS_MAX_NUM 8
#ifndef RSS_HASH_KEY_LENGTH
#define RSS_HASH_KEY_LENGTH 64
#endif
Every one of these is now exported by an installed public header
with no RTE_FLOW_PARSER_ prefix. RSS_HASH_KEY_LENGTH in particular
is a generic name almost guaranteed to collide -- any application
that defined its own RSS_HASH_KEY_LENGTH=40 (matching its hardware)
before including this header would silently get 40 inside flow
parser slots, with the parser's slot layout corrupted by mismatched
array sizes.
All of these need an RTE_FLOW_PARSER_ prefix and the #ifndef guard
on RSS_HASH_KEY_LENGTH should be removed -- it is an invitation to
define-mismatch bugs.
A6. Doc/header inconsistency: parser_parse() declared in config.h
but documented as living in cmdline.h.
doc/guides/prog_guide/flow_parser_lib.rst:
"rte_flow_parser_parse() from rte_flow_parser_cmdline.h parses
complete flow CLI commands ..."
but the declaration is in lib/ethdev/rte_flow_parser_config.h
(line 15342 of the diff). The doc is also internally inconsistent:
the same .rst earlier says "Additional functions for full command
parsing and cmdline integration are available in
rte_flow_parser_cmdline.h. These include rte_flow_parser_parse()
..." -- which is wrong twice.
A7. local_cmd_flow->help_str = ... mutates the cmdline instruction.
lib/cmdline/rte_flow_parser_cmdline.c:
if (local_cmd_flow != NULL)
local_cmd_flow->help_str = help ? help : name;
This mutates the cmdline_parse_inst_t passed to
rte_flow_parser_cmdline_register(). Idiomatic cmdline usage in DPDK
declares cmdline_parse_inst_t variables as static const aggregates
(see lib/cmdline/cmdline_parse.h examples and the rest of testpmd).
Passing such an instance here writes to read-only memory and
segfaults. The .rst note ("The library writes to inst->help_str
dynamically ... must remain valid for the lifetime of the cmdline
session") flags the lifetime question but does not flag the
mutability requirement, which is the actually fatal one.
The fix is to keep help_str storage internal to the library and
return it via a side channel (e.g. an out-pointer in the get_help
callback) rather than mutating the caller's instruction.
Patch 4/6 -- app/testpmd: use flow parser from ethdev
------------------------------------------------------
A8. Tab completion regression for dynamic IDs.
As described in A3, removing app/test-pmd/cmdline_flow.c and
replacing it with the library means testpmd's interactive flow
command-line loses tab completion on rule IDs, pattern/actions
template IDs, table IDs, queue IDs, RSS queue IDs, and indirect
action IDs. Today's cmdline_flow.c calls port_flow_list,
port_flow_template_list, port_flow_template_table_list, etc. The
replacement library calls parser_flow_rule_count, etc., which
return 0.
Until the introspection callback (A3) is in place, this patch
needs at minimum a release note entry explicitly calling out the
loss of tab completion. As written, the change description in the
patch does not mention it.
Warnings
========
Patch 2/6 -- ethdev: add RSS type helper APIs
----------------------------------------------
W1. The "all" entry hardcodes the OR of every RTE_ETH_RSS_* protocol
bit and will silently go stale.
lib/ethdev/rte_ethdev.c:
{ "all", RTE_ETH_RSS_ETH | RTE_ETH_RSS_VLAN | RTE_ETH_RSS_IP |
RTE_ETH_RSS_TCP | RTE_ETH_RSS_UDP | RTE_ETH_RSS_SCTP |
RTE_ETH_RSS_L2_PAYLOAD | RTE_ETH_RSS_L2TPV3 |
RTE_ETH_RSS_ESP | RTE_ETH_RSS_AH | RTE_ETH_RSS_PFCP |
RTE_ETH_RSS_GTPU | RTE_ETH_RSS_ECPRI | RTE_ETH_RSS_MPLS |
RTE_ETH_RSS_L2TPV2 | RTE_ETH_RSS_IB_BTH },
Whenever a new RTE_ETH_RSS_* protocol bit is added, this list will
drift unless the contributor remembers this table. There is an
existing convention RTE_ETH_RSS_PROTO_MASK in rte_ethdev.h that
collects these; consider using it (or extending it) so the table
tracks the canonical mask automatically.
W2. rte_eth_rss_type_to_str(0) returns "none" but
rte_eth_rss_type_to_str(RTE_ETH_RSS_IPV4 | RTE_ETH_RSS_IPV6)
returns NULL.
The "to_str" function uses == on the table, so it succeeds only
for values exactly present as a table entry. The Doxygen says
"RSS type value (RTE_ETH_RSS_*)" which a caller will reasonably
read as accepting any combination of RTE_ETH_RSS_* bits. The
doc should explicitly state that only single-entry table values
round-trip; arbitrary OR combinations return NULL.
Patch 3/6 -- ethdev: add flow parser library
---------------------------------------------
W3. enum rte_flow_parser_command + enum parser_token + token-to-cmd
switch is a three-way invariant.
Adding a new flow command requires:
- new entry in enum parser_token (private)
- new entry in enum rte_flow_parser_command (public)
- new case in parser_token_to_command()
with the comment in flow parser .c file flagging this explicitly.
This is a maintenance burden and an ABI risk -- forgetting the
third step silently maps the new command to
RTE_FLOW_PARSER_CMD_UNKNOWN. Consider whether the public enum
could be derived from the private one (table-driven) so there is
a single source of truth.
W4. rte_flow_parser_parse_attr_str() synthesizes a full validate
command including pattern and actions just to harvest the attr.
lib/ethdev/rte_flow_parser.c:
ret = parser_format_cmd(&cmd, "flow validate 0 ",
src, " pattern eth / end actions drop / end");
This wraps the user input with a hardcoded port id 0 and a
default pattern/actions that the simple API immediately throws
away. If the testpmd grammar ever cross-validates attr against
pattern/actions (e.g. "drop" not allowed on egress + transfer),
the simple API breaks for combinations that should be valid in
isolation. This is the architectural fragility of the synthesize-
and-strip approach in concrete form.
W5. parser_format_cmd uses libc malloc on every simple-API call.
lib/ethdev/rte_flow_parser.c:
static int parser_format_cmd(char **dst, ...) {
len = strlen(prefix) + strlen(body) + strlen(suffix) + 1;
*dst = malloc(len);
...
snprintf(*dst, len, "%s%s%s", prefix, body, suffix);
Plain malloc, not rte_malloc, is appropriate here since the simple
API claims to work without rte_eal_init. But the cost is a malloc/
free pair per parse call. For an API that may be used to bulk-load
flow rules from a config file or remote control plane, this is
pessimal. Consider a stack-or-VLA-based formatter, since the input
string length is already known.
W6. parser_str_strip_trailing_end heuristic strips at most one
"/ end".
lib/ethdev/rte_flow_parser.c:
/* parser_str_strip_trailing_end ... */
if (strncmp(p - 3, "end", 3) != 0)
return strlen(src);
Inputs like "drop / end / end" or "drop / end\t/end " strip only
the outermost. The function's comment claims tolerance for any
whitespace placement; it does not flag that only one trailing
"/ end" is stripped. This is fine in practice for human input but
surprising for programmatically generated input.
W7. No rte_flow_parser_config_unregister().
rte_flow_parser_config_register replaces the previous registration
and frees indirect action list configurations created by prior
parsing sessions, but there is no unregister entry point. A test
harness that wants a clean shutdown -- or a long-lived process
that wants to release the SLIST of indlst_conf entries -- has to
re-register a zeroed config to flush. Add an unregister API and
call it from indlst_conf_cleanup at the same time.
W8. struct rte_flow_parser_vxlan_encap_conf and friends mix bit-
fields and uint8_t arrays in a public header.
struct rte_flow_parser_vxlan_encap_conf {
uint32_t select_ipv4:1;
uint32_t select_vlan:1;
uint32_t select_tos_ttl:1;
uint8_t vni[3];
...
};
C bit-field layout is implementation-defined (order, alignment,
signedness of unnamed bit-fields). For a public ABI this is
tolerable on DPDK's supported toolchains but fragile across them.
At minimum, reserve the remaining 29 bits explicitly:
uint32_t reserved:29;
to lock in the layout. A more conservative choice is plain
uint8_t flags; with named bits.
W9. char type[16] in struct rte_flow_parser_tunnel_ops and char
file[128]/filename[128] in rte_flow_parser_output use unnamed
magic constants.
struct rte_flow_parser_tunnel_ops {
uint32_t id;
char type[16];
...
};
... struct { char file[128]; ... } dump;
... struct { ... char filename[128]; } flex;
These bake fixed maxima into the ABI. Define and document
RTE_FLOW_PARSER_TUNNEL_TYPE_LEN, RTE_FLOW_PARSER_DUMP_FILE_LEN,
etc. so contributors don't have to grep to see "is 16 enough for
any future tunnel name?".
W10. The output struct's union arm vc has multiple raw pointer
fields whose ownership is undocumented.
struct rte_flow_parser_output {
...
union {
struct {
...
struct rte_flow_item *pattern;
struct rte_flow_action *actions;
struct rte_flow_action *masks;
uint8_t *data;
...
} vc;
struct {
uint64_t *rule;
uint64_t rule_n;
...
} destroy;
...
} args;
};
All these pointers point either into the caller-supplied output
buffer (rte_flow_parser_parse) or into the static simple-API
buffer (parser_simple_parse). None of this is documented per
field. Add a per-field comment ("points into the result_size
buffer; valid until the next call") so a caller can see the
contract without reading the implementation.
W11. parser_token_to_command() default branch logs ERR with no rate
limit.
static enum rte_flow_parser_command
parser_token_to_command(enum parser_token token) {
switch (token) {
...
default:
RTE_LOG_LINE(ERR, ETHDEV, "unknown parser token %u",
(unsigned int)token);
return RTE_FLOW_PARSER_CMD_UNKNOWN;
}
}
An attacker-controlled or fuzzed input that lands a parse on an
unmapped token can flood the log. Use RTE_LOG_LINE_DP or downgrade
to DEBUG.
W12. parser_ctx_set_raw_common uses 0x06 / 0x11 instead of
IPPROTO_TCP / IPPROTO_UDP.
case RTE_FLOW_ITEM_TYPE_UDP:
size = sizeof(struct rte_udp_hdr);
proto = 0x11;
break;
case RTE_FLOW_ITEM_TYPE_TCP:
size = sizeof(struct rte_tcp_hdr);
proto = 0x06;
break;
Other branches in the same function correctly use named constants
(RTE_ETHER_TYPE_IPV4, IPPROTO_ROUTING). Use IPPROTO_TCP /
IPPROTO_UDP for consistency.
Patch 4/6 -- app/test-pmd: use flow parser from ethdev
-------------------------------------------------------
W13. testpmd_flow_dispatch() (app/test-pmd/flow_parser.c) is missing
a release note for the dropped 14k-line app/test-pmd/cmdline_flow.c.
The release_notes for 26.07 mention the new flow parser library
but should also note the testpmd-internal restructuring, since
third-party patches against cmdline_flow.c will need rebasing.
Info
====
I1. Patch 1 ordering. The cmdline-stddef.h patch (patch 1/6) is
independent of the rest of the series. It would land cleanly on
its own and shorten this series's review surface.
I2. Series cover letter is missing from the bundle (no [PATCH v12 0/6]
visible). For a 14k+ line series, a v12 cover letter summarizing
what changed since v11 helps reviewers focus.
I3. Test coverage. test_flow_parser.c and test_flow_parser_simple.c
exercise the parse path well, but I do not see a test that
deliberately triggers the -ENOBUFS path on the simple API
(large pattern overflowing the 4096-byte static buffer) or the
aliasing pattern in A2(a). A negative test confirming that two
consecutive simple-API calls invalidate the first result would
document the contract concretely.
I4. enum rte_flow_parser_command places
RTE_FLOW_PARSER_CMD_INDIRECT_ACTION_FLOW_CONF_CREATE alone at
the end after the meter-policy block, breaking the per-section
grouping established earlier. Move it into the indirect-action
block.
I5. struct rte_flow_parser_action_vxlan_encap_data uses an anonymous
union for ipv4/ipv6 items. This is the right size optimization
but readers have to know to spell .item_ipv4 / .item_ipv6
without a containing union name. Either name the union or add
a comment.
Summary
=======
The split into rte_flow_parser.h (simple) and rte_flow_parser_config.h
(full) is the right direction and a real improvement over earlier
versions. The remaining structural issues are:
- cmdline -> ethdev layer inversion (A1)
- aliased pointer return semantics with a 4KB static buffer (A2)
- tab-completion stubs with no override hook (A3, A8)
- hack repurposing of rte_flow_attr.reserved in testpmd glue (A4)
- unprefixed/colliding public macro names (A5)
- mutated cmdline instruction (A7)
A2 and A3 are the two that most directly justify the "cut/paste"
critique: they reflect that the parser was extracted from testpmd
without designing a context-handle ownership model or a callback
seam for application-side state. Resolving them likely needs the
parser to take a context handle (alloc/free) and an introspection
ops struct in addition to the existing config registration.
```A few notes on findings I considered but did not include:
- I did not flag the RTE_LOG_LINE calls in indirect_action_flow_conf_create for stale severity since they are correct uses.
- The for (i = n - 1; i >= 0; --i) loop with int i and uint32_t n is safe for the realistic input range so I did not flag it as integer truncation.
- The select_ipv4:1-style bit-fields are also present in existing public DPDK structs (rte_flow_attr), so I downgraded that to a Warning rather than an Error.
- Skipped patches 1/6 (trivial stddef.h include), 5/6 (example) and 6/6 (tests) since I had no findings beyond I3 and the test framework usage looked correct (REGISTER_FAST_TEST with NOHUGE_OK, ASAN_OK).
No Reviewed-by is given since the series has multiple Errors and Warnings outstanding.
st 6. 5. 2026 v 0:00 odesílatel Stephen Hemminger < [email protected]> napsal:
Quoted 30 lines
Quoted 2 lines · On Tue, 5 May 2026 20:39:07 +0200 Lukas Sismis <[email protected]> wrote:
This series extracts the testpmd flow CLI parser into a reusable library, enabling external applications to parse
rte_flowrules using testpmdsyntax.
Quoted 4 lines
Motivation
----------
External applications like Suricata IDS [1] need to express hardwarefiltering
Quoted 1 line
rules in a consistent, human-readable format. Rather than inventing
custom
Quoted 14 lines
syntax, reusing testpmd's well-tested flow grammar provides immediate compatibility with existing documentation and user knowledge.
Note: This library provides only one way to create
rte_flowstructures. Applications can also constructrte_flow_attr, rte_flow_item[], and rte_flow_action[] directly in C code.Design
------
The library (librte_flow_parser) exposes the following APIs:
-rte_flow_parser_parse_attr_str(): Parse attributes only
-rte_flow_parser_parse_pattern_str(): Parse patterns only
-rte_flow_parser_parse_actions_str(): Parse actions onlyQuoted 2 lines
Testpmd is updated to use the library, ensuring a single maintained parser implementation.
Quoted 10 lines
I wish it was not just a port of testpmd code to a library but had been done as a clean implementation; that said the current version is much better.
AI had lots of feedback. The part that matters to me is the new dependency chain; and also having a syntax that looks too much like testpmd.
Would prefer that only the flow part of the string was passed.
Thanks for the feedback.
Clean implementation would be best, but it is also worth noting that it would encompass great engineering effort to get there. Porting/extracting testpmd's flow parser to a separate library was the original intention, to test the waters and see if it would be used by the community and work well in the DPDK environment. More specifically, the very first original intention was to reuse the simple network pattern language to define rte_flow rule structures (eth / ipv4 / ...). Since carving out just the network layer pattern parser seemed not feasible (the pattern section contains extra network-independent information, e.g., port_id/conntrack/represented ports/encaps), the scope extended to the full "flow create" command of the testpmd. That then included an even larger scope of features to consider in the library.
To comment on the dependency problem, I would like to mention that if this were a separate library, there would be no changes in dependencies in the core libraries.
---
I don't quite understand your wish of "only the flow part of the string was passed". If you mean to e.g. pass only the pattern string to get pattern structures returned, then the simple API is for that purpose, e.g.:
/**
* Parse a flow pattern from a CLI snippet.
*
* Parses pattern strings as used inside a flow command, such as
* "eth / ipv4 src is 192.168.1.1 / tcp dst is 80 / end". *
*/__rte_experimental
int rte_flow_parser_parse_pattern_str(const char *src,
const struct rte_flow_item **pattern,
uint32_t *pattern_n);
If you meant to say you want to pass the full "flow create ... " command to output attribute + patterns + actions structures in one call *only*, then it is possible. But while iterating on this, I came to the conclusion that "flow create" is truly a control directive of the testpmd application and should not be dragged to the rte_flow parser library. So I don't think it is a good idea. I envision that custom applications could define their own rule-specification syntax, whether it would be the usual "flow create X", YAML-structure, or something else.
---
On the related note, to comment on your concern about "having a syntax that looks too much like testpmd". Having testpmd syntax is exactly the intent of this work: to have a single parser for both the testpmd and the rte_flow parser library itself. With all this work, I thought about dailing back and e.g. reducing the scope of the patch to only introduce a string parser for the limited set of network-layer patterns (withot the tokenizer). But this would lead to code duplication (which I wanted to avoid with all this work), as I didn't find a straightforward way to have part of the testpmd parser internally and the other in the library.
Perhaps, this can be a good point to decide if a port of testpmd rte_flow parser would be a welcome contribution by DPDK maintainers, especially at this early stage of the library creation. I would greatly appreciate "a clean library rewrite," but at this moment, I estimate the complexity to be higher than the capacity that I have currently.
Quoted 554 lines
---
I have enough material for a comprehensive architectural review. Let me write it up.
---
Below is my deep-dive review of the v12 series. Architecturally, this is a major step beyond earlier versions in terms of polish (header split, doc page, real example, real tests), but the underlying structure is still essentially the testpmd
cmdline_flow.clifted wholesale intolib/ethdev, with a thin "simple API" wrapper that synthesizes fake testpmd commands. Several of the deeper structural problems remain, plus there are concrete bugs.``` Series-level architectural review ================================= Context ------- The series moves the ~14,400-line app/test-pmd/cmdline_flow.c into a new lib/ethdev/rte_flow_parser.c, exposes a "simple" string-to-rte_flow API in lib/ethdev/rte_flow_parser.h, exposes a fuller cmdline-aware API in lib/ethdev/rte_flow_parser_config.h, and adds cmdline glue in lib/cmdline/rte_flow_parser_cmdline.[ch]. testpmd (patch 4) is then ported to consume the library via a dispatch callback that maps RTE_FLOW_PARSER_CMD_* enum values back onto its existing port_flow_* functions. The main functional change versus past versions is that the simple API (parse_attr_str / parse_pattern_str / parse_actions_str / parse_flow_rule) now exists separately from the full command grammar. Internally however the simple API is still implemented by string- synthesizing a fake "flow validate 0 ..." command, running it through the full parser, and harvesting one output field. So the architectural center of gravity is unchanged: this is the testpmd grammar exposed as a library. Errors ====== Patch 3/6 -- ethdev: add flow parser library --------------------------------------------- A1. lib/cmdline now depends on lib/ethdev (layer inversion). lib/cmdline/meson.build: -deps += ['net'] +deps += ['net', 'ethdev'] lib/cmdline is a foundational utility used by examples, internal tools, and tests that have nothing to do with networking. Pulling ethdev into it just so rte_flow_parser_cmdline.c can call into rte_flow_parser_* exports inverts the layering. Every consumer of libcmdline now links libethdev. The cmdline/flow-parser glue belongs in either lib/ethdev (and the header in lib/ethdev too, with ethdev depending on cmdline -- the natural direction) or in a new top-level lib/flow_parser that depends on both. It does not belong inside lib/cmdline. A2. The "simple API" returns aliased pointers into a single 4096-byte static buffer, with no way for a caller to retain a result. lib/ethdev/rte_flow_parser.c: #define FLOW_PARSER_SIMPLE_BUF_SIZE 4096 static uint8_t flow_parser_simple_parse_buf[FLOW_PARSER_SIMPLE_BUF_SIZE]; ... static int parser_simple_parse(const char *cmd, ... **out) { memset(flow_parser_simple_parse_buf, 0, sizeof(...)); ret = rte_flow_parser_parse(cmd, (struct rte_flow_parser_output *)flow_parser_simple_parse_buf, sizeof(flow_parser_simple_parse_buf)); ... *out = (struct rte_flow_parser_output *)flow_parser_simple_parse_buf; } Then rte_flow_parser_parse_pattern_str() does: *pattern = out->args.vc.pattern; /* points into buf */ *pattern_n = out->args.vc.pattern_n; Three resulting problems: (a) Two consecutive calls alias. Any caller that wants to hold two parsed patterns simultaneously (e.g. parse two flows and call rte_flow_create() on each) cannot, without writing their own deep-copy via rte_flow_conv(). This is a pervasive footgun and is only loosely documented as "Points to internal storage valid until the next parse call." (b) The 4096-byte cap silently rejects any flow rule whose serialized output exceeds the buffer (returns -ENOBUFS), with no way for the caller to predict what fits. (c) The simple API itself uses parse_pattern_str inside a setter example flow in the example program: ret = rte_flow_parser_parse_pattern_str(..., &items, &items_n); if (ret == 0) ret = rte_flow_parser_raw_encap_conf_set(0, items, items_n); This particular sequence is safe today because raw_encap_conf_set doesn't re-enter the parser, but nothing in the API contract prevents a future parser call between (A) and (B), and the example pattern teaches users a fragile idiom. Suggested direction: provide a caller-supplied output mode -- e.g. rte_flow_parser_parse_pattern_str(src, items, items_cap, &items_n) where the caller provides storage. Or return an opaque handle owning the storage (rte_flow_parser_pattern_new / _free), modeled on rte_flow_conv(). A3. All cmdline tab-completion hooks for dynamic IDs are stubbed out to return zero candidates, with no override mechanism. lib/ethdev/rte_flow_parser.c: static inline int parser_port_id_is_invalid(uint16_t port_id) { (void)port_id; return 0; /* always "valid" */ } static inline uint16_t parser_flow_rule_count(uint16_t port_id) { return 0; } static inline int parser_flow_rule_id_get(...) { return -ENOENT; } /* same pattern for pattern/actions templates, tables, queues, * RSS queues, indirect actions */ These are the routines comp_rule_id, comp_pattern_template_id, comp_actions_template_id, comp_table_id, comp_queue_id, etc. all call into when cmdline asks for tab-completion candidates. With these stubs in place, the library version of testpmd interactive mode can never tab-complete a rule ID, template ID, table ID, queue ID, or indirect action ID -- a regression versus the current testpmd cmdline_flow.c which queries port_flow_list, port_flow_template_list, etc. directly. patch 4 (testpmd integration) does not register or override these stubs anywhere. There is no callback registration interface for the application to provide "give me rule IDs for port N" / "give me table IDs for port N" / etc. A complete library extraction needs an introspection ops struct that the application registers alongside rte_flow_parser_config, e.g.: struct rte_flow_parser_introspect_ops { uint16_t (*flow_rule_count)(uint16_t port_id); int (*flow_rule_id_get)(uint16_t port_id, unsigned idx, uint64_t *rule_id); /* templates, tables, queues, indirect actions, ... */ }; int rte_flow_parser_introspect_register( const struct rte_flow_parser_introspect_ops *ops); A4. testpmd dispatch repurposes rte_flow_attr.reserved as a side channel for relaxed_matching. app/test-pmd/flow_parser.c (patch 4): case RTE_FLOW_PARSER_CMD_PATTERN_TEMPLATE_CREATE: port_flow_pattern_template_create(in->port, in->args.vc.pat_templ_id, &((const struct rte_flow_pattern_template_attr) { .relaxed_matching = in->args.vc.attr.reserved, .ingress = in->args.vc.attr.ingress, .egress = in->args.vc.attr.egress, .transfer = in->args.vc.attr.transfer, }), in->args.vc.pattern); rte_flow_attr.reserved is documented in lib/ethdev/rte_flow.h as reserved and required to be zero. Smuggling pattern_template_attr.relaxed_matching through that field couples the library output to a hack and breaks the moment anyone sets rte_flow_attr.reserved for any other purpose, or starts validating it. The output struct already has a vc.{pat_templ,act_templ,table} arm -- relaxed_matching belongs there, not overlaid on attr.reserved. A5. Public preprocessor macros in rte_flow_parser_config.h are unprefixed and one of them collides with a generic name. lib/ethdev/rte_flow_parser_config.h: #define ACTION_RAW_ENCAP_MAX_DATA 512 #define RAW_ENCAP_CONFS_MAX_NUM 8 #define ACTION_RSS_QUEUE_NUM 128 #define ACTION_VXLAN_ENCAP_ITEMS_NUM 6 #define ACTION_NVGRE_ENCAP_ITEMS_NUM 5 #define ACTION_IPV6_EXT_PUSH_MAX_DATA 512 #define IPV6_EXT_PUSH_CONFS_MAX_NUM 8 #define ACTION_SAMPLE_ACTIONS_NUM 10 #define RAW_SAMPLE_CONFS_MAX_NUM 8 #ifndef RSS_HASH_KEY_LENGTH #define RSS_HASH_KEY_LENGTH 64 #endif Every one of these is now exported by an installed public header with no RTE_FLOW_PARSER_ prefix. RSS_HASH_KEY_LENGTH in particular is a generic name almost guaranteed to collide -- any application that defined its own RSS_HASH_KEY_LENGTH=40 (matching its hardware) before including this header would silently get 40 inside flow parser slots, with the parser's slot layout corrupted by mismatched array sizes. All of these need an RTE_FLOW_PARSER_ prefix and the #ifndef guard on RSS_HASH_KEY_LENGTH should be removed -- it is an invitation to define-mismatch bugs. A6. Doc/header inconsistency: parser_parse() declared in config.h but documented as living in cmdline.h. doc/guides/prog_guide/flow_parser_lib.rst: "rte_flow_parser_parse() from rte_flow_parser_cmdline.h parses complete flow CLI commands ..." but the declaration is in lib/ethdev/rte_flow_parser_config.h (line 15342 of the diff). The doc is also internally inconsistent: the same .rst earlier says "Additional functions for full command parsing and cmdline integration are available in rte_flow_parser_cmdline.h. These include rte_flow_parser_parse() ..." -- which is wrong twice. A7. local_cmd_flow->help_str = ... mutates the cmdline instruction. lib/cmdline/rte_flow_parser_cmdline.c: if (local_cmd_flow != NULL) local_cmd_flow->help_str = help ? help : name; This mutates the cmdline_parse_inst_t passed to rte_flow_parser_cmdline_register(). Idiomatic cmdline usage in DPDK declares cmdline_parse_inst_t variables as static const aggregates (see lib/cmdline/cmdline_parse.h examples and the rest of testpmd). Passing such an instance here writes to read-only memory and segfaults. The .rst note ("The library writes to inst->help_str dynamically ... must remain valid for the lifetime of the cmdline session") flags the lifetime question but does not flag the mutability requirement, which is the actually fatal one. The fix is to keep help_str storage internal to the library and return it via a side channel (e.g. an out-pointer in the get_help callback) rather than mutating the caller's instruction. Patch 4/6 -- app/testpmd: use flow parser from ethdev ------------------------------------------------------ A8. Tab completion regression for dynamic IDs. As described in A3, removing app/test-pmd/cmdline_flow.c and replacing it with the library means testpmd's interactive flow command-line loses tab completion on rule IDs, pattern/actions template IDs, table IDs, queue IDs, RSS queue IDs, and indirect action IDs. Today's cmdline_flow.c calls port_flow_list, port_flow_template_list, port_flow_template_table_list, etc. The replacement library calls parser_flow_rule_count, etc., which return 0. Until the introspection callback (A3) is in place, this patch needs at minimum a release note entry explicitly calling out the loss of tab completion. As written, the change description in the patch does not mention it. Warnings ======== Patch 2/6 -- ethdev: add RSS type helper APIs ---------------------------------------------- W1. The "all" entry hardcodes the OR of every RTE_ETH_RSS_* protocol bit and will silently go stale. lib/ethdev/rte_ethdev.c: { "all", RTE_ETH_RSS_ETH | RTE_ETH_RSS_VLAN | RTE_ETH_RSS_IP | RTE_ETH_RSS_TCP | RTE_ETH_RSS_UDP | RTE_ETH_RSS_SCTP | RTE_ETH_RSS_L2_PAYLOAD | RTE_ETH_RSS_L2TPV3 | RTE_ETH_RSS_ESP | RTE_ETH_RSS_AH | RTE_ETH_RSS_PFCP | RTE_ETH_RSS_GTPU | RTE_ETH_RSS_ECPRI | RTE_ETH_RSS_MPLS | RTE_ETH_RSS_L2TPV2 | RTE_ETH_RSS_IB_BTH }, Whenever a new RTE_ETH_RSS_* protocol bit is added, this list will drift unless the contributor remembers this table. There is an existing convention RTE_ETH_RSS_PROTO_MASK in rte_ethdev.h that collects these; consider using it (or extending it) so the table tracks the canonical mask automatically. W2. rte_eth_rss_type_to_str(0) returns "none" but rte_eth_rss_type_to_str(RTE_ETH_RSS_IPV4 | RTE_ETH_RSS_IPV6) returns NULL. The "to_str" function uses == on the table, so it succeeds only for values exactly present as a table entry. The Doxygen says "RSS type value (RTE_ETH_RSS_*)" which a caller will reasonably read as accepting any combination of RTE_ETH_RSS_* bits. The doc should explicitly state that only single-entry table values round-trip; arbitrary OR combinations return NULL. Patch 3/6 -- ethdev: add flow parser library --------------------------------------------- W3. enum rte_flow_parser_command + enum parser_token + token-to-cmd switch is a three-way invariant. Adding a new flow command requires: - new entry in enum parser_token (private) - new entry in enum rte_flow_parser_command (public) - new case in parser_token_to_command() with the comment in flow parser .c file flagging this explicitly. This is a maintenance burden and an ABI risk -- forgetting the third step silently maps the new command to RTE_FLOW_PARSER_CMD_UNKNOWN. Consider whether the public enum could be derived from the private one (table-driven) so there is a single source of truth. W4. rte_flow_parser_parse_attr_str() synthesizes a full validate command including pattern and actions just to harvest the attr. lib/ethdev/rte_flow_parser.c: ret = parser_format_cmd(&cmd, "flow validate 0 ", src, " pattern eth / end actions drop / end"); This wraps the user input with a hardcoded port id 0 and a default pattern/actions that the simple API immediately throws away. If the testpmd grammar ever cross-validates attr against pattern/actions (e.g. "drop" not allowed on egress + transfer), the simple API breaks for combinations that should be valid in isolation. This is the architectural fragility of the synthesize- and-strip approach in concrete form. W5. parser_format_cmd uses libc malloc on every simple-API call. lib/ethdev/rte_flow_parser.c: static int parser_format_cmd(char **dst, ...) { len = strlen(prefix) + strlen(body) + strlen(suffix) + 1; *dst = malloc(len); ... snprintf(*dst, len, "%s%s%s", prefix, body, suffix); Plain malloc, not rte_malloc, is appropriate here since the simple API claims to work without rte_eal_init. But the cost is a malloc/ free pair per parse call. For an API that may be used to bulk-load flow rules from a config file or remote control plane, this is pessimal. Consider a stack-or-VLA-based formatter, since the input string length is already known. W6. parser_str_strip_trailing_end heuristic strips at most one "/ end". lib/ethdev/rte_flow_parser.c: /* parser_str_strip_trailing_end ... */ if (strncmp(p - 3, "end", 3) != 0) return strlen(src); Inputs like "drop / end / end" or "drop / end\t/end " strip only the outermost. The function's comment claims tolerance for any whitespace placement; it does not flag that only one trailing "/ end" is stripped. This is fine in practice for human input but surprising for programmatically generated input. W7. No rte_flow_parser_config_unregister(). rte_flow_parser_config_register replaces the previous registration and frees indirect action list configurations created by prior parsing sessions, but there is no unregister entry point. A test harness that wants a clean shutdown -- or a long-lived process that wants to release the SLIST of indlst_conf entries -- has to re-register a zeroed config to flush. Add an unregister API and call it from indlst_conf_cleanup at the same time. W8. struct rte_flow_parser_vxlan_encap_conf and friends mix bit- fields and uint8_t arrays in a public header. struct rte_flow_parser_vxlan_encap_conf { uint32_t select_ipv4:1; uint32_t select_vlan:1; uint32_t select_tos_ttl:1; uint8_t vni[3]; ... }; C bit-field layout is implementation-defined (order, alignment, signedness of unnamed bit-fields). For a public ABI this is tolerable on DPDK's supported toolchains but fragile across them. At minimum, reserve the remaining 29 bits explicitly: uint32_t reserved:29; to lock in the layout. A more conservative choice is plain uint8_t flags; with named bits. W9. char type[16] in struct rte_flow_parser_tunnel_ops and char file[128]/filename[128] in rte_flow_parser_output use unnamed magic constants. struct rte_flow_parser_tunnel_ops { uint32_t id; char type[16]; ... }; ... struct { char file[128]; ... } dump; ... struct { ... char filename[128]; } flex; These bake fixed maxima into the ABI. Define and document RTE_FLOW_PARSER_TUNNEL_TYPE_LEN, RTE_FLOW_PARSER_DUMP_FILE_LEN, etc. so contributors don't have to grep to see "is 16 enough for any future tunnel name?". W10. The output struct's union arm vc has multiple raw pointer fields whose ownership is undocumented. struct rte_flow_parser_output { ... union { struct { ... struct rte_flow_item *pattern; struct rte_flow_action *actions; struct rte_flow_action *masks; uint8_t *data; ... } vc; struct { uint64_t *rule; uint64_t rule_n; ... } destroy; ... } args; }; All these pointers point either into the caller-supplied output buffer (rte_flow_parser_parse) or into the static simple-API buffer (parser_simple_parse). None of this is documented per field. Add a per-field comment ("points into the result_size buffer; valid until the next call") so a caller can see the contract without reading the implementation. W11. parser_token_to_command() default branch logs ERR with no rate limit. static enum rte_flow_parser_command parser_token_to_command(enum parser_token token) { switch (token) { ... default: RTE_LOG_LINE(ERR, ETHDEV, "unknown parser token %u", (unsigned int)token); return RTE_FLOW_PARSER_CMD_UNKNOWN; } } An attacker-controlled or fuzzed input that lands a parse on an unmapped token can flood the log. Use RTE_LOG_LINE_DP or downgrade to DEBUG. W12. parser_ctx_set_raw_common uses 0x06 / 0x11 instead of IPPROTO_TCP / IPPROTO_UDP. case RTE_FLOW_ITEM_TYPE_UDP: size = sizeof(struct rte_udp_hdr); proto = 0x11; break; case RTE_FLOW_ITEM_TYPE_TCP: size = sizeof(struct rte_tcp_hdr); proto = 0x06; break; Other branches in the same function correctly use named constants (RTE_ETHER_TYPE_IPV4, IPPROTO_ROUTING). Use IPPROTO_TCP / IPPROTO_UDP for consistency. Patch 4/6 -- app/test-pmd: use flow parser from ethdev ------------------------------------------------------- W13. testpmd_flow_dispatch() (app/test-pmd/flow_parser.c) is missing a release note for the dropped 14k-line app/test-pmd/cmdline_flow.c. The release_notes for 26.07 mention the new flow parser library but should also note the testpmd-internal restructuring, since third-party patches against cmdline_flow.c will need rebasing. Info ==== I1. Patch 1 ordering. The cmdline-stddef.h patch (patch 1/6) is independent of the rest of the series. It would land cleanly on its own and shorten this series's review surface. I2. Series cover letter is missing from the bundle (no [PATCH v12 0/6] visible). For a 14k+ line series, a v12 cover letter summarizing what changed since v11 helps reviewers focus. I3. Test coverage. test_flow_parser.c and test_flow_parser_simple.c exercise the parse path well, but I do not see a test that deliberately triggers the -ENOBUFS path on the simple API (large pattern overflowing the 4096-byte static buffer) or the aliasing pattern in A2(a). A negative test confirming that two consecutive simple-API calls invalidate the first result would document the contract concretely. I4. enum rte_flow_parser_command places RTE_FLOW_PARSER_CMD_INDIRECT_ACTION_FLOW_CONF_CREATE alone at the end after the meter-policy block, breaking the per-section grouping established earlier. Move it into the indirect-action block. I5. struct rte_flow_parser_action_vxlan_encap_data uses an anonymous union for ipv4/ipv6 items. This is the right size optimization but readers have to know to spell .item_ipv4 / .item_ipv6 without a containing union name. Either name the union or add a comment. Summary ======= The split into rte_flow_parser.h (simple) and rte_flow_parser_config.h (full) is the right direction and a real improvement over earlier versions. The remaining structural issues are: - cmdline -> ethdev layer inversion (A1) - aliased pointer return semantics with a 4KB static buffer (A2) - tab-completion stubs with no override hook (A3, A8) - hack repurposing of rte_flow_attr.reserved in testpmd glue (A4) - unprefixed/colliding public macro names (A5) - mutated cmdline instruction (A7) A2 and A3 are the two that most directly justify the "cut/paste" critique: they reflect that the parser was extracted from testpmd without designing a context-handle ownership model or a callback seam for application-side state. Resolving them likely needs the parser to take a context handle (alloc/free) and an introspection ops struct in addition to the existing config registration. ```A few notes on findings I considered but did not include:
- I did not flag the
RTE_LOG_LINEcalls inindirect_action_flow_conf_createfor stale severity since they are correct uses.
- Thefor (i = n - 1; i >= 0; --i)loop withint ianduint32_t nis safe for the realistic input range so I did not flag it as integer truncation.
- Theselect_ipv4:1-style bit-fields are also present in existing public DPDK structs (rte_flow_attr), so I downgraded that to a Warning rather than an Error.
- Skipped patches 1/6 (trivialstddef.hinclude), 5/6 (example) and 6/6 (tests) since I had no findings beyond I3 and the test framework usage looked correct (REGISTER_FAST_TESTwithNOHUGE_OK, ASAN_OK).No
Reviewed-byis given since the series has multiple Errors and Warnings outstanding.
cover flow_compile: textual flow rule compiler
In reply to Lukas SismisBackground
----------
Multiple efforts over the past few cycles have tried to make testpmd's flow rule grammar reusable from outside testpmd. External applications that need rte_flow want a documented way to turn human-written rules into the rte_flow_attr/item/action arrays accepted by rte_flow_create().
The most recent attempt is Lukas Sismis's series, currently at v12:
http://patches.dpdk.org/project/dpdk/list/?series=37384 (or most recent thread on [email protected])
That series factors testpmd's existing cmdline_flow.c into a library and updates testpmd to consume it. It works, but inherits two properties of cmdline_flow.c that I think are worth avoiding in a reusable library:
- Coupling to librte_cmdline. Even after the v12 split into a "simple" part and a "cmdline" part, the parser is still organized around testpmd's command interpreter, and v12 has cmdline depending on ethdev to break a previous circular dependency. A library used by daemons, control planes, or unit tests should not need that.
- Ad-hoc grammar. cmdline_flow.c implements parsing per-token in long dispatch logic; the grammar emerges from the code rather than being stated, and adding a new flow item requires touching the parser.
This RFC explores a different shape and is posted to ask the list which one is preferred before more work goes into either.
So I started a new green field library for parsing flow rules (with the help of AI assistance). It is only a few hours old, but passes tests and passes review.
This series
-----------
lib/flow_compile -- a small new library providing the same service via a pcap_compile()-style API:
char errbuf[RTE_FLOW_COMPILE_ERRBUF_SIZE];
struct rte_flow_compile *fc = rte_flow_compile(rule, errbuf);
if (fc == NULL)
fail(errbuf); /* "line:col: message" */
rte_flow_compile_create(port_id, fc, &flow_error);
rte_flow_compile_free(fc);Design properties:
- Hand-rolled lexer + recursive descent parser. No flex/bison.
- Parser is driven entirely by descriptor tables of items and actions. Adding a new flow item is a table edit, not a parser change. A custom-setter hook on each field covers the layouts that do not fit a plain byte range (bitfields, indirect arrays).
- Dependencies: rte_ethdev and rte_net only. No librte_cmdline, no flex/bison. Builds clean on Linux, FreeBSD, and Windows.
- Per-allocation rte_zmalloc for spec/mask/last/conf payloads; rte_flow_compile_free() walks the pattern and action arrays. ASan/LSan run clean on the autotest.
The grammar follows testpmd's syntax closely so familiar rules carry over:
ingress pattern eth / ipv4 src is 10.0.0.1 / end actions queue index 3 / count / end
and is documented as a formal BNF in the programmer's guide chapter (patch 2).
Initial coverage: eth, vlan, ipv4, ipv6, tcp, udp, vxlan, port_id, port_representor, represented_port items; drop, passthru, queue, mark, jump, count, port_id and representor variants, of_pop_vlan, vxlan_decap actions. Variable-conf items and actions (RSS, RAW) require custom setters and are deferred to a follow-up.
What this RFC is *not*
----------------------
Not a replacement for cmdline_flow.c in testpmd. If the shape here is acceptable, the next step is a separate series adding a "flow compile <port> <rule>" command in testpmd alongside the existing parser, so users can adopt the library incrementally without breaking scripts that depend on the current syntax.
What I'd like feedback on
-------------------------
1. API shape. pcap_compile-style (one string -> opaque object -> arrays) versus the three-call attr/pattern/actions form Sismis's v12 exposes. What does your application actually want?
2. Library placement. Stand-alone at lib/flow_compile/ versus addition to lib/ethdev. This series treats it as a control-path parser layered on top of ethdev rather than part of ethdev itself; v12 places its parser inside ethdev.
3. Table-driven extension model. Is "to add a new flow item, add a row to the descriptor table" the right contract? Should the tables live alongside each rte_flow_item_* definition in rte_flow.h, or in their own file as here?
4. Convergence. If this design is preferred, I'm happy to coordinate with Lukas to fold in the testpmd-side changes from his series.
5. API code. Is it readable enough. Lots of code here but doing lexer/parser is prime template territory and AI has a good chance here.
Stephen Hemminger (3):
flow_compile: introduce textual flow rule compiler
doc: add programmer's guide for flow rule compiler test/flow_compile: add unit tests for flow rule compiler
MAINTAINERS | 8 + app/test/meson.build | 2 + app/test/test_flow_compile.c | 230 +++ doc/guides/prog_guide/flow_compile_lib.rst | 170 ++ doc/guides/prog_guide/index.rst | 1 + doc/guides/rel_notes/release_26_07.rst | 5 + lib/flow_compile/flow_compile_lex.c | 488 +++++ lib/flow_compile/flow_compile_parse.c | 634 ++++++ lib/flow_compile/flow_compile_priv.h | 181 ++ lib/flow_compile/flow_compile_tables.c | 245 +++ lib/flow_compile/meson.build | 15 + lib/flow_compile/rte_flow_compile.h | 158 ++ lib/flow_compile/rte_flow_compile_api.c | 132 ++ lib/flow_compile/version.map | 13 + lib/meson.build | 1 + 15 files changed, 2283 insertions(+) create mode 100644 app/test/test_flow_compile.c create mode 100644 doc/guides/prog_guide/flow_compile_lib.rst create mode 100644 lib/flow_compile/flow_compile_lex.c create mode 100644 lib/flow_compile/flow_compile_parse.c create mode 100644 lib/flow_compile/flow_compile_priv.h create mode 100644 lib/flow_compile/flow_compile_tables.c create mode 100644 lib/flow_compile/meson.build create mode 100644 lib/flow_compile/rte_flow_compile.h create mode 100644 lib/flow_compile/rte_flow_compile_api.c create mode 100644 lib/flow_compile/version.map
Signature · 35 lines
2.43.7 Stephen Hemminger (3): flow_compile: introduce textual flow rule compiler doc: add programmer's guide for flow rule compiler test/flow_compile: add unit tests for flow rule compiler MAINTAINERS | 7 + app/test/meson.build | 1 + app/test/test_flow_compile.c | 234 ++++++++ doc/guides/prog_guide/flow_compile_lib.rst | 272 +++++++++ doc/guides/prog_guide/index.rst | 1 + doc/guides/rel_notes/release_26_07.rst | 6 + lib/flow_compile/flow_compile_lex.c | 510 +++++++++++++++++ lib/flow_compile/flow_compile_parse.c | 634 +++++++++++++++++++++ lib/flow_compile/flow_compile_priv.h | 181 ++++++ lib/flow_compile/flow_compile_tables.c | 245 ++++++++ lib/flow_compile/meson.build | 15 + lib/flow_compile/rte_flow_compile.h | 158 +++++ lib/flow_compile/rte_flow_compile_api.c | 132 +++++ lib/meson.build | 1 + 14 files changed, 2397 insertions(+) create mode 100644 app/test/test_flow_compile.c create mode 100644 doc/guides/prog_guide/flow_compile_lib.rst create mode 100644 lib/flow_compile/flow_compile_lex.c create mode 100644 lib/flow_compile/flow_compile_parse.c create mode 100644 lib/flow_compile/flow_compile_priv.h create mode 100644 lib/flow_compile/flow_compile_tables.c create mode 100644 lib/flow_compile/meson.build create mode 100644 lib/flow_compile/rte_flow_compile.h create mode 100644 lib/flow_compile/rte_flow_compile_api.c -- 2.53.0
RFC 1/3 flow_compile: introduce textual flow rule compiler
Currently the only way to compile a flow rule from text is to link against testpmd's cmdline_flow.c, which is tightly coupled to librte_cmdline and the testpmd command framework. Recent attempts to extract it as a library have produced ad-hoc copies rather than a clean separation.
Add librte_flow_compile, modelled on libpcap's pcap_compile(): a textual rule goes in, an opaque compiled object comes out, and diagnostics of the form "line:col: message" go in a caller-supplied buffer. Accessors return the rte_flow_attr/item/action arrays ready for rte_flow_create(); a convenience entry point installs the rule directly on a port.
The parser is recursive descent driven by descriptor tables of items and actions, so adding a new item type is purely a table edit -- the parser has no per-type knowledge. A custom-setter hook handles fields whose layout cannot be expressed as a plain byte range (bitfields, indirect arrays).
Dependencies are limited to rte_ethdev and rte_net; no librte_cmdline, no flex/bison, no platform-specific headers. The grammar follows testpmd's syntax so familiar rules carry over and is documented in the programmer's guide.
Initial coverage spans the common items (eth, vlan, ipv4, ipv6, tcp, udp, vxlan, port_id, port_representor, represented_port) and actions (drop, passthru, queue, mark, jump, count, port_id and representor variants, of_pop_vlan, vxlan_decap). Items and actions with variable-length conf (RSS, RAW) require a custom setter and are deferred to a follow-up.
--- lib/flow_compile/flow_compile_lex.c | 510 +++++++++++++++++++ lib/flow_compile/flow_compile_parse.c | 634 ++++++++++++++++++++++++ lib/flow_compile/flow_compile_priv.h | 181 +++++++ lib/flow_compile/flow_compile_tables.c | 245 +++++++++ lib/flow_compile/meson.build | 15 + lib/flow_compile/rte_flow_compile.h | 158 ++++++ lib/flow_compile/rte_flow_compile_api.c | 132 +++++ lib/meson.build | 1 + 8 files changed, 1876 insertions(+) create mode 100644 lib/flow_compile/flow_compile_lex.c create mode 100644 lib/flow_compile/flow_compile_parse.c create mode 100644 lib/flow_compile/flow_compile_priv.h create mode 100644 lib/flow_compile/flow_compile_tables.c create mode 100644 lib/flow_compile/meson.build create mode 100644 lib/flow_compile/rte_flow_compile.h create mode 100644 lib/flow_compile/rte_flow_compile_api.c
lib/flow_compile/flow_compile_lex.c new file +510 -0
@@ -0,0 +1,510 @@ +/* SPDX-License-Identifier: BSD-3-Clause +* Copyright (c) 2026 Stephen Hemminger <[email protected]> +*/ + +#include <errno.h> +#include <stdarg.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> + +#include <rte_errno.h> +#include <rte_ether.h> + +#include "flow_compile_priv.h" + +/* +* Diagnostics. +* +* On the first error we capture, all subsequent calls become no-ops +* so that the user sees the *first* problem (which is usually the +* cause) rather than a cascade. +*/ +int +flow_compile_errf (struct flow_compile_ctx *cc,const struct token *at, +const char *fmt, ...) +{ +if (cc->errbuf[0 ] !='\0' ) +return -1 ;/* keep the first error */ + +uint16_t line = at !=NULL ? at->line : cc->line; +uint16_t col = at !=NULL ? at->col : cc->col; + +int n =snprintf (cc->errbuf,RTE_FLOW_COMPILE_ERRBUF_SIZE , +"%u:%u: " , (unsigned int )line, (unsigned int )col); +if (n <0 ) + n =0 ; +if (n >= (int )RTE_FLOW_COMPILE_ERRBUF_SIZE ) + n = (int )RTE_FLOW_COMPILE_ERRBUF_SIZE -1 ; + +va_list ap; +va_start (ap, fmt); +vsnprintf (cc->errbuf + n, (size_t )RTE_FLOW_COMPILE_ERRBUF_SIZE - (size_t )n, + fmt, ap); +va_end (ap); + + rte_errno =EINVAL ; +return -1 ; +} + +/* ------------------------------------------------------------------ */ +/* Character classes. +* +* The grammar is pure ASCII; using <ctype.h> would tie behavior to +* the active locale. Inline predicates compile down to a single +* range comparison. +*/ + +static inline bool +is_ascii_alpha (int c) +{ +return (c >='a' && c <='z' ) || (c >='A' && c <='Z' ); +} + +static inline bool +is_ascii_alnum (int c) +{ +return is_ascii_alpha (c) || (c >='0' && c <='9' ); +} + +static inline bool +is_ascii_space (int c) +{ +return c ==' ' || c =='\t' || c =='\n' || + c =='\r' || c =='\v' || c =='\f' ; +} + +static inline bool +is_word_start (int c) +{ +return is_ascii_alpha (c) || c =='_' ; +} + +/* +* Characters that can appear inside an unquoted value lexeme. +* The lexer reads a run of these and then classifies the run. +* +* '_' is intentionally absent: identifiers (which are the only +* tokens that legitimately contain '_') are taken by the +* alpha-start branch in flow_compile_lex(), so '_' inside a +* digit-started run can never produce a useful token. +* +* '-' is included so that the IEEE 802 / Windows hyphen-separated +* MAC form (XX-XX-XX-XX-XX-XX) reaches match_mac(), which delegates +* to rte_ether_unformat_addr() and accepts it. +*/ +static inline bool +is_value_cont (int c) +{ +return is_ascii_alnum (c) || c =='.' || c ==':' || c =='-' ; +} + +/* ------------------------------------------------------------------ */ +/* Source navigation. All movement goes through advance() so that +* line/column tracking is trivially correct, including across CRLF. +*/ + +static void +advance (struct flow_compile_ctx *cc,size_t n) +{ +for (size_t i =0 ; i < n && *cc->cur !='\0' ; i++) { +if (*cc->cur =='\n' ) { + cc->line++; + cc->col =1 ; + }else { + cc->col++; + } + cc->cur++; + } +} + +static void +skip_ws_and_comments (struct flow_compile_ctx *cc) +{ +for (;;) { +while (*cc->cur !='\0' &&is_ascii_space ((unsigned char )*cc->cur)) +advance (cc,1 ); +if (*cc->cur =='#' ) { +while (*cc->cur !='\0' && *cc->cur !='\n' ) +advance (cc,1 ); +continue ; + } +break ; + } +} + +/* ------------------------------------------------------------------ */ +/* Classifiers for the value-lexeme run. +* +* These never read past ``end``; ``s`` is not required to be NUL +* terminated within the run. +*/ + +static inline bool +is_dec_digit (int c) +{ +return c >='0' && c <='9' ; +} + +static inline bool +is_hex_digit (int c) +{ +return (c >='0' && c <='9' ) || + (c >='a' && c <='f' ) || + (c >='A' && c <='F' ); +} + +static bool +all_decimal (const char *s,size_t n) +{ +if (n ==0 ) +return false; +for (size_t i =0 ; i < n; i++) +if (!is_dec_digit ((unsigned char )s[i])) +return false; +return true; +} + +static bool +hex_prefixed (const char *s,size_t n,size_t *body_len) +{ +if (n <3 || s[0 ] !='0' || (s[1 ] !='x' && s[1 ] !='X' )) +return false; +for (size_t i =2 ; i < n; i++) +if (!is_hex_digit ((unsigned char )s[i])) +return false; + *body_len = n -2 ; +return true; +} + +static int +parse_uint (const char *s,size_t n,uint64_t *out) +{ +uint64_t v =0 ; +size_t i =0 ; +int base =10 ; + +if (n >=2 && s[0 ] =='0' && (s[1 ] =='x' || s[1 ] =='X' )) { + base =16 ; + i =2 ; +if (i == n) +return -1 ; + } +for (; i < n; i++) { +uint64_t d; +int c = (unsigned char )s[i]; +if (c >='0' && c <='9' ) + d = (uint64_t )(c -'0' ); +else if (base ==16 && c >='a' && c <='f' ) + d = (uint64_t )(c -'a' +10 ); +else if (base ==16 && c >='A' && c <='F' ) + d = (uint64_t )(c -'A' +10 ); +else +return -1 ; +/* overflow check */ +if (v > (UINT64_MAX - d) / (uint64_t )base) +return -1 ; + v = v * (uint64_t )base + d; + } + *out = v; +return 0 ; +} + +/* +* Hex-only integer parser. Used by the MAC and IPv6 matchers, where +* the leading "0x" of the general parse_uint() is implied by context. +* Caller guarantees n in [1, 16]. +*/ +static int +parse_hex (const char *s,size_t n,uint64_t *out) +{ +uint64_t v =0 ; +for (size_t i =0 ; i < n; i++) { +int c = (unsigned char )s[i]; +uint64_t d; +if (c >='0' && c <='9' ) + d = (uint64_t )(c -'0' ); +else if (c >='a' && c <='f' ) + d = (uint64_t )(c -'a' +10 ); +else if (c >='A' && c <='F' ) + d = (uint64_t )(c -'A' +10 ); +else +return -1 ; + v = (v <<4 ) | d; + } + *out = v; +return 0 ; +} + +static bool +match_ipv4 (const char *s,size_t n,uint8_t out[4 ]) +{ +int parts =0 ; +uint32_t v =0 ; +size_t i =0 ; +bool in_part = false; + +while (i < n) { +int c = (unsigned char )s[i]; +if (is_dec_digit (c)) { + v = v *10u + (uint32_t )(c -'0' ); +if (v >255u ) +return false; + in_part = true; + i++; + }else if (c =='.' ) { +if (!in_part) +return false; + out[parts++] = (uint8_t )v; +if (parts ==4 ) +return false; + v =0 ; + in_part = false; + i++; + }else { +return false; + } + } +if (!in_part || parts !=3 ) +return false; + out[parts] = (uint8_t )v; +return true; +} + +/* +* Recognize a MAC address in any form ``rte_ether_unformat_addr()`` +* accepts (colon-separated ``xx:xx:xx:xx:xx:xx`` and Cisco dotted +* ``xxxx.xxxx.xxxx``). Delegates the actual parsing so behavior +* stays in lockstep with the rest of DPDK. +*/ +static bool +match_mac (const char *s,size_t n,uint8_t out[6 ]) +{ +/* The longest accepted form is the 17-byte colon notation; +* Cisco notation is 14 bytes. Cap at 18 to leave room for the +* NUL that rte_ether_unformat_addr() requires. +*/ +char buf[18 ]; +if (n >=sizeof (buf)) +return false; +memcpy (buf, s, n); + buf[n] ='\0' ; + +struct rte_ether_addr ea; +if (rte_ether_unformat_addr (buf, &ea) !=0 ) +return false; +memcpy (out, ea.addr_bytes,RTE_ETHER_ADDR_LEN ); +return true; +} + +/* +* IPv6 textual form per RFC 4291 / RFC 5952. +* +* Accepts: +* - 8 groups of 1-4 hex digits separated by ':' +* - "::" once, replacing one or more zero groups +* - mixed form is *not* accepted (no embedded IPv4 dotted-quad). +* This matches what the rest of DPDK uses internally. +*/ +static bool +match_ipv6 (const char *s,size_t n,uint8_t out[16 ]) +{ +uint16_t head[8 ] = {0 }; +uint16_t tail[8 ] = {0 }; +int nh =0 , nt =0 ; +bool seen_dcolon = false; +size_t i =0 ; + +if (n >=2 && s[0 ] ==':' && s[1 ] ==':' ) { + seen_dcolon = true; + i =2 ; + } + +while (i < n) { +/* read one hex group */ +size_t g0 = i; +while (i < n &&is_hex_digit ((unsigned char )s[i])) + i++; +size_t glen = i - g0; +if (glen ==0 || glen >4 ) +return false; +uint64_t v; +if (parse_hex (s + g0, glen, &v) <0 || v >0xffffu ) +return false; +uint16_t *dst = seen_dcolon ? tail : head; +int *cnt = seen_dcolon ? &nt : &nh; +if (*cnt ==8 ) +return false; + dst[(*cnt)++] = (uint16_t )v; + +if (i == n) +break ; +if (s[i] !=':' ) +return false; + i++; +if (i < n && s[i] ==':' ) { +if (seen_dcolon) +return false; + seen_dcolon = true; + i++; +if (i == n) +break ; + } + } + +int total = nh + nt; +if (seen_dcolon) { +if (total >=8 ) +return false; + }else { +if (total !=8 ) +return false; + } + +int gap =8 - total; +int p =0 ; +for (int j =0 ; j < nh; j++, p++) { + out[p *2 ] = (uint8_t )(head[j] >>8 ); + out[p *2 +1 ] = (uint8_t )head[j]; + } +for (int j =0 ; j < gap; j++, p++) { + out[p *2 ] =0 ; + out[p *2 +1 ] =0 ; + } +for (int j =0 ; j < nt; j++, p++) { + out[p *2 ] = (uint8_t )(tail[j] >>8 ); + out[p *2 +1 ] = (uint8_t )tail[j]; + } +return true; +} + +/* ------------------------------------------------------------------ */ +/* Quoted string handling. We support only simple double quoted +* strings with backslash escaping for backslash and quote. +*/ + +static int +scan_string (struct flow_compile_ctx *cc,struct token *tk) +{ + tk->kind =TK_STRING ; + tk->line = cc->line; + tk->col = cc->col; +advance (cc,1 );/* eat opening quote */ + tk->text = cc->cur; + +while (*cc->cur !='\0' && *cc->cur !='"' ) { +if (*cc->cur =='\\' && cc->cur[1 ] !='\0' ) +advance (cc,1 ); +advance (cc,1 ); + } +if (*cc->cur !='"' ) +return flow_compile_errf (cc, tk,"unterminated string" ); + tk->len = (uint16_t )(cc->cur - tk->text); +advance (cc,1 );/* eat closing quote */ +return 0 ; +} + +/* ------------------------------------------------------------------ */ +/* Top-level scan. */ + +int +flow_compile_lex (struct flow_compile_ctx *cc) +{ +skip_ws_and_comments (cc); + +struct token *tk = &cc->tok; +memset (tk,0 ,sizeof (*tk)); + tk->line = cc->line; + tk->col = cc->col; + tk->text = cc->cur; + +int c = (unsigned char )*cc->cur; + +/* Single-character tokens and EOF. */ +switch (c) { +case '\0' : + tk->kind =TK_EOF ; +return 0 ; +case '/' : + tk->kind =TK_SLASH ; + tk->len =1 ; +advance (cc,1 ); +return 0 ; +case ',' : + tk->kind =TK_COMMA ; + tk->len =1 ; +advance (cc,1 ); +return 0 ; +case '{' : + tk->kind =TK_LBRACE ; + tk->len =1 ; +advance (cc,1 ); +return 0 ; +case '}' : + tk->kind =TK_RBRACE ; + tk->len =1 ; +advance (cc,1 ); +return 0 ; +case '"' : +return scan_string (cc, tk); +default : +break ; + } + +/* Identifier (alpha/_ start, no dots/colons). */ +if (is_word_start (c)) { +size_t len =0 ; +while (is_ascii_alnum ((unsigned char )cc->cur[len]) || + cc->cur[len] =='_' ) + len++; + tk->kind =TK_IDENT ; + tk->len = (uint16_t )len; +advance (cc, len); +return 0 ; + } + +/* A value run. We accept :: as start (IPv6) and digit start +* for everything else. +*/ +if (is_dec_digit (c) || c ==':' ) { +size_t len =0 ; +while (is_value_cont ((unsigned char )cc->cur[len])) + len++; +if (len ==0 ) +return flow_compile_errf (cc,NULL , +"unexpected character '%c'" , c); + +/* Classify in order: MAC (rigid shape), IPv4, hex string, +* decimal, IPv6. IPv6 is tried last because a bare hex +* group like "1234" is also a valid uint. +*/ +if (match_mac (cc->cur, len, tk->v.mac)) { + tk->kind =TK_MAC ; + }else if (match_ipv4 (cc->cur, len, tk->v.ipv4)) { + tk->kind =TK_IPV4 ; + }else { +size_t hex_body; +if (hex_prefixed (cc->cur, len, &hex_body) && + hex_body >16 ) { + tk->kind =TK_HEXSTR ; + }else if (hex_prefixed (cc->cur, len, &hex_body) || +all_decimal (cc->cur, len)) { +if (parse_uint (cc->cur, len, &tk->v.u) <0 ) +return flow_compile_errf (cc,NULL , +"integer out of range" ); + tk->kind =TK_UINT ; + }else if (match_ipv6 (cc->cur, len, tk->v.ipv6)) { + tk->kind =TK_IPV6 ; + }else { +return flow_compile_errf (cc,NULL , +"unrecognized token '%.*s'" , + (int )len, cc->cur); + } + } + tk->len = (uint16_t )len; +advance (cc, len); +return 0 ; + } + +return flow_compile_errf (cc,NULL ,"unexpected character '%c'" , c); +}
lib/flow_compile/flow_compile_parse.c new file +634 -0
634 lines not on this page · raw message
lib/flow_compile/flow_compile_priv.h new file +181 -0
181 lines not on this page · raw message
lib/flow_compile/flow_compile_tables.c new file +245 -0
245 lines not on this page · raw message
lib/flow_compile/meson.build new file +15 -0
@@ -0,0 +1,15 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2026 Stephen Hemminger + +sources += files( + 'flow_compile_lex.c', + 'flow_compile_parse.c', + 'flow_compile_tables.c', + 'rte_flow_compile_api.c', +) + +headers += files( + 'rte_flow_compile.h', +) + +deps += ['ethdev']
lib/flow_compile/rte_flow_compile.h new file +158 -0
158 lines not on this page · raw message
lib/flow_compile/rte_flow_compile_api.c new file +132 -0
132 lines not on this page · raw message
lib/meson.build +1 -0
@@ -40,6 +40,7 @@ libraries = [ 'efd', 'eventdev', 'dispatcher', # dispatcher depends on eventdev + 'flow_compile', 'gpudev', 'gro', 'gso',
Signature · 1 line
2.53.0
Re: [RFC 1/3] flow_compile: introduce textual flow rule compiler
Quoted 19 lines · Stephen Hemminger
Currently the only way to compile a flow rule from text is to link against testpmd's
cmdline_flow.c, which is tightly coupled tolibrte_cmdlineand the testpmd command framework. Recent attempts to extract it as a library have produced ad-hoc copies rather than a clean separation.Add
librte_flow_compile, modelled on libpcap'spcap_compile(): a textual rule goes in, an opaque compiled object comes out, and diagnostics of the form "line:col: message" go in a caller-supplied buffer. Accessors return the rte_flow_attr/item/action arrays ready forrte_flow_create(); a convenience entry point installs the rule directly on a port.The parser is recursive descent driven by descriptor tables of items and actions, so adding a new item type is purely a table edit -- the parser has no per-type knowledge. A custom-setter hook handles fields whose layout cannot be expressed as a plain byte range (bitfields, indirect arrays).
Quoted 5 lines
Dependencies are limited to
rte_ethdevandrte_net; nolibrte_cmdline, no flex/bison, no platform-specific headers. The grammar follows testpmd's syntax so familiar rules carry over and is documented in the programmer's guide.
Was there a particular reason to avoid using flex/bison here, or did their use just not make sense? In general I would prefer using code-generation tools where possible rather than maintaining (metaphorically) hand-written code.
/Bruce
RE: [RFC 1/3] flow_compile: introduce textual flow rule compiler
Quoted 26 lines · Stephen Hemminger
Quoted 19 lines
Currently the only way to compile a flow rule from text is to link against testpmd's
cmdline_flow.c, which is tightly coupled tolibrte_cmdlineand the testpmd command framework. Recent attempts to extract it as a library have produced ad-hoc copies rather than a clean separation.Add
librte_flow_compile, modelled on libpcap'spcap_compile(): a textual rule goes in, an opaque compiled object comes out, and diagnostics of the form "line:col: message" go in a caller-supplied buffer. Accessors return the rte_flow_attr/item/action arrays ready forrte_flow_create(); a convenience entry point installs the rule directly on a port.The parser is recursive descent driven by descriptor tables of items and actions, so adding a new item type is purely a table edit -- the parser has no per-type knowledge. A custom-setter hook handles fields whose layout cannot be expressed as a plain byte range (bitfields, indirect arrays).
Quoted 5 lines
Dependencies are limited to
rte_ethdevandrte_net; nolibrte_cmdline, no flex/bison, no platform-specific headers. The grammar follows testpmd's syntax so familiar rules carry over and is documented in the programmer's guide.
Quoted 4 lines
Was there a particular reason to avoid using flex/bison here, or did their use just not make sense? In general I would prefer using code-generation tools where possible rather than maintaining (metaphorically) hand-written code.
In general, I like the idea of flow_compile(const char *) and the idea to make it independent from cmdline lib.
Though I have the same question as Bruce: why not to use flex/bison here? At first glance, that's the right tools for that kind of job and seems much better then hand-written (AI generated) peace of code that no-one would probably understand. Konstantin
Re: [RFC 1/3] flow_compile: introduce textual flow rule compiler
In reply to Bruce RichardsonQuoted 11 lines · On Wed, 6 May 2026 09:06:22 +0100 Bruce Richardson…
Quoted 6 lines
Dependencies are limited to
rte_ethdevandrte_net; nolibrte_cmdline, no flex/bison, no platform-specific headers. The grammar follows testpmd's syntax so familiar rules carry over and is documented in the programmer's guide.Was there a particular reason to avoid using flex/bison here, or did their use just not make sense? In general I would prefer using code-generation tools where possible rather than maintaining (metaphorically) hand-written code.
/Bruce
As long as we are willing to accept flex/bison as build dependency, it would make sense to use it.
Re: [RFC 1/3] flow_compile: introduce textual flow rule compiler
Quoted 9 lines · Stephen Hemminger
Quoted 6 lines · On Wed, 6 May 2026 09:06:22 +0100 Bruce Richardson…
Quoted 6 lines
Dependencies are limited to
rte_ethdevandrte_net; nolibrte_cmdline, no flex/bison, no platform-specific headers. The grammar follows testpmd's syntax so familiar rules carry over and is documented in the programmer's guide.
Quoted 8 lines
Quoted 5 lines
Was there a particular reason to avoid using flex/bison here, or did their use just not make sense? In general I would prefer using code-generation tools where possible rather than maintaining (metaphorically) hand-written code.
/Bruce
As long as we are willing to accept flex/bison as build dependency, it would make sense to use it.
Google search points to https://github.com/lexxmark/winflexbison as available ports for Windows, so I see no issue with making these build dependencies.
/Bruce
Re: [RFC 1/3] flow_compile: introduce textual flow rule compiler
Quoted 16 lines · On Wed, 6 May 2026 16:56:30 +0100 Bruce Richardson…
Quoted 15 lines · Stephen Hemminger
Quoted 11 lines · On Wed, 6 May 2026 09:06:22 +0100 Bruce Richardson…
Quoted 6 lines
Dependencies are limited to
rte_ethdevandrte_net; nolibrte_cmdline, no flex/bison, no platform-specific headers. The grammar follows testpmd's syntax so familiar rules carry over and is documented in the programmer's guide.Was there a particular reason to avoid using flex/bison here, or did their use just not make sense? In general I would prefer using code-generation tools where possible rather than maintaining (metaphorically) hand-written code.
/Bruce
Quoted 8 lines
Quoted 2 lines
As long as we are willing to accept flex/bison as build dependency, it would make sense to use it.
Google search points to https://github.com/lexxmark/winflexbison as available ports for Windows, so I see no issue with making these build dependencies.
/Bruce
Right, I am pushing AI to use flex/bison.
Surprisingly it is resisting; showing a bit of emotional ownership to the code which is both humorous, odd and scary.
RFC 2/3 doc: add programmer's guide for flow rule compiler
In reply to Stephen HemmingerAdd a chapter to the programmer's guide describing the new rte_flow_compile library: API summary, BNF grammar, field qualifier semantics (is/spec/last/mask/prefix), diagnostic format, and the table-driven extension model for adding items and actions.
Documents the limitations of the initial implementation (item/action coverage, missing RSS and RAW handling) and the textual MAC and IPv6 forms accepted.
--- MAINTAINERS | 6 + doc/guides/prog_guide/flow_compile_lib.rst | 272 +++++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + doc/guides/rel_notes/release_26_07.rst | 6 + 4 files changed, 285 insertions(+) create mode 100644 doc/guides/prog_guide/flow_compile_lib.rst
MAINTAINERS +6 -0
@@ -448,6 +448,12 @@ F: app/test-pmd/cmdline_flow.c F: doc/guides/prog_guide/ethdev/flow_offload.rst F: lib/ethdev/rte_flow* +Flow Compiler API +M: Stephen Hemminger <[email protected]> +T: git://dpdk.org/next/dpdk-next-net +F: lib/flow_compile/ +F: doc/guides/prog_guide/flow_compile_lib.rst + Traffic Management API M: Cristian Dumitrescu <[email protected]> T: git://dpdk.org/next/dpdk-next-net
doc/guides/prog_guide/flow_compile_lib.rst new file +272 -0
272 lines not on this page · raw message
doc/guides/prog_guide/index.rst +1 -0
@@ -121,6 +121,7 @@ Utility Libraries argparse_lib cmdline + flow_compile_lib ptr_compress_lib timer_lib rcu_lib
doc/guides/rel_notes/release_26_07.rst +6 -0
@@ -64,6 +64,12 @@ New Features * ``--auto-probing`` enables the initial bus probing, which is the current default behavior. +* **Added library to compile flow definitions.** + + New library that works like libpcap ``pcap_compile`` function to compile + a text string into flow rules. + + Removed Items -------------
Signature · 1 line
2.53.0
RFC 3/3 test/flow_compile: add unit tests for flow rule compiler
In reply to Stephen HemmingerAdd an autotest for the new rte_flow_compile library. The tests exercise the parser end to end without needing a real ethdev port:
each case compiles a textual rule and inspects the resulting attribute, pattern and action arrays directly.
Coverage spans the common happy paths (simple drop, IPv4/IPv6 match with queue and count actions, MAC matching, CIDR-style prefix masks) and a set of error-path cases. The error tests assert a substring of the diagnostic rather than the full message so that wording can evolve without churning the tests.
Registered as flow_compile_autotest in the fast test suite so it runs under the standard meson test invocation.
--- MAINTAINERS | 1 + app/test/meson.build | 1 + app/test/test_flow_compile.c | 234 +++++++++++++++++++++++++++++++++++ 3 files changed, 236 insertions(+) create mode 100644 app/test/test_flow_compile.c
MAINTAINERS +1 -0
@@ -453,6 +453,7 @@ M: Stephen Hemminger <[email protected]> T: git://dpdk.org/next/dpdk-next-net F: lib/flow_compile/ F: doc/guides/prog_guide/flow_compile_lib.rst +F: app/test/test_flow_compile.c Traffic Management API M: Cristian Dumitrescu <[email protected]>
app/test/meson.build +1 -0
@@ -88,6 +88,7 @@ source_file_deps = { 'test_fib6_perf.c': ['fib'], 'test_fib_perf.c': ['net', 'fib'], 'test_flow_classify.c': ['net', 'acl', 'table', 'ethdev', 'flow_classify'], + 'test_flow_compile.c': ['net', 'ethdev', 'flow_compile'], 'test_func_reentrancy.c': ['hash', 'lpm'], 'test_graph.c': ['graph'], 'test_graph_feature_arc.c': ['graph'],
app/test/test_flow_compile.c new file +234 -0
234 lines not on this page · raw message
Signature · 1 line
2.53.0
Re: [RFC PATCH 0/3] flow_compile: textual flow rule compiler
In reply to Stephen Hemmingerst 6. 5. 2026 v 5:33 odesílatel Stephen Hemminger < [email protected]> napsal:
Quoted 86 lines
Background
----------Multiple efforts over the past few cycles have tried to make testpmd's flow rule grammar reusable from outside testpmd. External applications that need
rte_flowwant a documented way to turn human-written rules into the rte_flow_attr/item/action arrays accepted byrte_flow_create().The most recent attempt is Lukas Sismis's series, currently at v12:
http://patches.dpdk.org/project/dpdk/list/?series=37384 (or most recent thread on [email protected])
That series factors testpmd's existing
cmdline_flow.cinto a library and updates testpmd to consume it. It works, but inherits two properties ofcmdline_flow.cthat I think are worth avoiding in a reusable library:- Coupling to
librte_cmdline. Even after the v12 split into a "simple" part and a "cmdline" part, the parser is still organized around testpmd's command interpreter, and v12 has cmdline depending on ethdev to break a previous circular dependency. A library used by daemons, control planes, or unit tests should not need that.- Ad-hoc grammar.
cmdline_flow.cimplements parsing per-token in long dispatch logic; the grammar emerges from the code rather than being stated, and adding a new flow item requires touching the parser.This RFC explores a different shape and is posted to ask the list which one is preferred before more work goes into either.
So I started a new green field library for parsing flow rules (with the help of AI assistance). It is only a few hours old, but passes tests and passes review.
This series
-----------
lib/flow_compile-- a small new library providing the same service via a pcap_compile()-style API:char errbuf[RTE_FLOW_COMPILE_ERRBUF_SIZE]; struct rte_flow_compile *fc = rte_flow_compile(rule, errbuf); if (fc == NULL) fail(errbuf); /* "line:col: message" */ rte_flow_compile_create(port_id, fc, &flow_error); rte_flow_compile_free(fc);Design properties:
- Hand-rolled lexer + recursive descent parser. No flex/bison.
- Parser is driven entirely by descriptor tables of items and actions. Adding a new flow item is a table edit, not a parser change. A custom-setter hook on each field covers the layouts that do not fit a plain byte range (bitfields, indirect arrays).
- Dependencies:rte_ethdevandrte_netonly. Nolibrte_cmdline, no flex/bison. Builds clean on Linux, FreeBSD, and Windows.
- Per-allocationrte_zmallocfor spec/mask/last/conf payloads;rte_flow_compile_free()walks the pattern and action arrays. ASan/LSan run clean on the autotest.The grammar follows testpmd's syntax closely so familiar rules carry over:
ingress pattern eth / ipv4 src is 10.0.0.1 / end actions queue index 3 / count / end
and is documented as a formal BNF in the programmer's guide chapter (patch 2).
Initial coverage: eth, vlan, ipv4, ipv6, tcp, udp, vxlan,
port_id,port_representor,represented_portitems; drop, passthru, queue, mark, jump, count,port_idand representor variants,of_pop_vlan,vxlan_decapactions. Variable-conf items and actions (RSS, RAW) require custom setters and are deferred to a follow-up.What this RFC is *not*
----------------------
Quoted 10 lines
Not a replacement for
cmdline_flow.cin testpmd. If the shape here is acceptable, the next step is a separate series adding a "flow compile <port> <rule>" command in testpmd alongside the existing parser, so users can adopt the library incrementally without breaking scripts that depend on the current syntax.What I'd like feedback on
-------------------------
Hi Stephen,
Thank you for looking into this. I genuinely appreciate it. I found this almost by accident, so here are some of my answers:
Quoted 5 lines
1. API shape. pcap_compile-style (one string -> opaque object -> arrays) versus the three-call attr/pattern/actions form Sismis's v12 exposes. What does your application actually want?
Generally, I am fine with pcap_compile style as per your suggestions. The original intent was to only use traffic patterns because everything else was set by the application itself. You can see an example of the use here:
https://github.com/OISF/suricata/pull/15290/changes#diff-4d5f5239a7124ed4b4d45501788bddffe803911f19c157e3c4ac7676a84d68b1R301
That is why I divided the simple API into 3 calls -- to let the application decide which part of the flow expression to parse. But a single entry point to the library is fine too, as the application could just fill it into the desired rule.
2. Library placement. Stand-alone at lib/flow_compile/ versus
Quoted 4 lines
addition to lib/ethdev. This series treats it as a control-path parser layered on top of ethdev rather than part of ethdev itself; v12 places its parser inside ethdev.
My general take on this is that it can be so useful for developers, so it should be part of the lib/ethdev to make it more visible. As highlighted by Thomas, it heavily interacts with the rte_flow objects.
But, as it probes for the flex/bison tools and skips the library if they are unavailable, wouldn't it be a problem if it is part of lib/ethdev directly? This can be a very strong argument for a separate library, then.
Quoted 11 lines
3. Table-driven extension model. Is "to add a new flow item, add a row to the descriptor table" the right contract? Should the tables live alongside each rte_flow_item_* definition in
rte_flow.h, or in their own file as here?4. Convergence. If this design is preferred, I'm happy to coordinate with Lukas to fold in the testpmd-side changes from his series.
(My) original idea was to reuse one parser for both the testpmd and the library to avoid multiple implementations of essentially the same thing.
How would "flow compile" be useful if testpmd already has the "flow create" command? Perhaps as a library demo only? I would expect testpmd users to like the flow create endpoint more for its more comprehensive support. Similarly, at this moment, since testpmd supports interactivity, I cannot see how the _compile API would replace functions in testpmd. But perhaps it would be part of a greater effort to migrate to flex/bison solution. Since this is also a simple, single-rule, stateless parser, it is not fully compatible with all of TestPMD's commands (e.g., "set raw_encap"). (Ok, noticed, you highlighted this)
Perhaps it is fine, just wanted to highlight this.
From the user-as-an-engineer's perspective, I would be generally happy for this parser to exist. The drop-filter feature in Suricata, in my view, requires just a simple network pattern specification so looking at the supported patterns already ticks off most of the items I've had in mind, except, e.g., MPLS. I can also see this as a viable way for Suricata user-specified decap options for better applicability of RSS.
Quoted 74 lines
5. API code. Is it readable enough. Lots of code here but doing lexer/parser is prime template territory and AI has a good chance here.
Stephen Hemminger (3):
flow_compile: introduce textual flow rule compiler
doc: add programmer's guide for flow rule compiler test/flow_compile: add unit tests for flow rule compilerMAINTAINERS | 8 + app/test/meson.build | 2 + app/test/test_flow_compile.c | 230 +++ doc/guides/prog_guide/flow_compile_lib.rst | 170 ++ doc/guides/prog_guide/index.rst | 1 + doc/guides/rel_notes/release_26_07.rst | 5 + lib/flow_compile/flow_compile_lex.c | 488 +++++ lib/flow_compile/flow_compile_parse.c | 634 ++++++ lib/flow_compile/flow_compile_priv.h | 181 ++ lib/flow_compile/flow_compile_tables.c | 245 +++ lib/flow_compile/meson.build | 15 + lib/flow_compile/rte_flow_compile.h | 158 ++ lib/flow_compile/rte_flow_compile_api.c | 132 ++ lib/flow_compile/version.map | 13 + lib/meson.build | 1 + 15 files changed, 2283 insertions(+) create mode 100644 app/test/test_flow_compile.c create mode 100644 doc/guides/prog_guide/flow_compile_lib.rst create mode 100644 lib/flow_compile/flow_compile_lex.c create mode 100644 lib/flow_compile/flow_compile_parse.c create mode 100644 lib/flow_compile/flow_compile_priv.h create mode 100644 lib/flow_compile/flow_compile_tables.c create mode 100644 lib/flow_compile/meson.build create mode 100644 lib/flow_compile/rte_flow_compile.h create mode 100644 lib/flow_compile/rte_flow_compile_api.c create mode 100644 lib/flow_compile/version.map--
2.43.7Stephen Hemminger (3):
flow_compile: introduce textual flow rule compiler
doc: add programmer's guide for flow rule compiler test/flow_compile: add unit tests for flow rule compilerMAINTAINERS | 7 + app/test/meson.build | 1 + app/test/test_flow_compile.c | 234 ++++++++ doc/guides/prog_guide/flow_compile_lib.rst | 272 +++++++++ doc/guides/prog_guide/index.rst | 1 + doc/guides/rel_notes/release_26_07.rst | 6 + lib/flow_compile/flow_compile_lex.c | 510 +++++++++++++++++ lib/flow_compile/flow_compile_parse.c | 634 +++++++++++++++++++++ lib/flow_compile/flow_compile_priv.h | 181 ++++++ lib/flow_compile/flow_compile_tables.c | 245 ++++++++ lib/flow_compile/meson.build | 15 + lib/flow_compile/rte_flow_compile.h | 158 +++++ lib/flow_compile/rte_flow_compile_api.c | 132 +++++ lib/meson.build | 1 + 14 files changed, 2397 insertions(+) create mode 100644 app/test/test_flow_compile.c create mode 100644 doc/guides/prog_guide/flow_compile_lib.rst create mode 100644 lib/flow_compile/flow_compile_lex.c create mode 100644 lib/flow_compile/flow_compile_parse.c create mode 100644 lib/flow_compile/flow_compile_priv.h create mode 100644 lib/flow_compile/flow_compile_tables.c create mode 100644 lib/flow_compile/meson.build create mode 100644 lib/flow_compile/rte_flow_compile.h create mode 100644 lib/flow_compile/rte_flow_compile_api.c--
2.53.0
Re: [RFC PATCH 0/3] flow_compile: textual flow rule compiler
Quoted 14 lines · On Fri, 22 May 2026 17:27:26 +0200 Lukáš Šišmiš <[email protected]> wrote:
(My) original idea was to reuse one parser for both the testpmd and the library to avoid multiple implementations of essentially the same thing.
How would "flow compile" be useful if testpmd already has the "flow create" command? Perhaps as a library demo only? I would expect testpmd users to like the
flow createendpoint more for its more comprehensive support. Similarly, at this moment, since testpmd supports interactivity, I cannot see how the_compileAPI would replace functions in testpmd. But perhaps it would be part of a greater effort to migrate to flex/bison solution. Since this is also a simple, single-rule, stateless parser, it is not fully compatible with all of TestPMD's commands (e.g., "setraw_encap"). (Ok, noticed, you highlighted this)
Perhaps it is fine, just wanted to highlight this.
Quoted 7 lines
From the user-as-an-engineer's perspective, I would be generally happy for this parser to exist. The drop-filter feature in Suricata, in my view, requires just a simple network pattern specification so looking at the supported patterns already ticks off most of the items I've had in mind, except, e.g., MPLS. I can also see this as a viable way for Suricata user-specified decap options for better applicability of RSS.
I am taking this is in a slightly different direction in next step. The syntax of testpmd filters is just raw expression of what rte_flow items are. The compiler should not need all the seperators and end marker. It should be user friendly and hide the internals not expose them
v2 cover flow_compile: textual flow rule compiler
In reply to Lukas SismisBackground
----------
Multiple efforts over the past few cycles have tried to make testpmd's flow rule grammar reusable from outside testpmd. External applications that need rte_flow want a documented way to turn human-written rules into the rte_flow_attr/item/action arrays accepted by rte_flow_create().
The most recent attempt is Lukas Sismis's series, currently at v12:
http://patches.dpdk.org/project/dpdk/list/?series=37384
That series factors testpmd's existing cmdline_flow.c into a library and updates testpmd to consume it. It works, but inherits two properties of cmdline_flow.c that I think are worth avoiding in a reusable library:
- Coupling to librte_cmdline. Even after the v12 split into a "simple" part and a "cmdline" part, the parser is still organized around testpmd's command interpreter, and v12 has cmdline depending on ethdev to break a previous circular dependency. A library used by daemons, control planes, or unit tests should not need that.
- Ad-hoc grammar. cmdline_flow.c implements parsing per-token in long dispatch logic; the grammar emerges from the code rather than being stated, and adding a new flow item requires touching the parser.
This RFC explores a different shape and is posted to ask the list which one is preferred before more work goes into either.
I started a new green-field library for parsing flow rules (with AI assistance for the boilerplate). It is young but passes tests and reviews clean under the project's AI review guidelines.
This series
-----------
lib/flow_compile -- a small new library providing the same service via a pcap_compile()-style API:
char errbuf[RTE_FLOW_COMPILE_ERRBUF_SIZE];
struct rte_flow_compile *fc = rte_flow_compile(rule, errbuf);
if (fc == NULL)
fail(errbuf); /* "line:col: message" */
rte_flow_compile_create(port_id, fc, &flow_error);
rte_flow_compile_free(fc);Design properties:
- Flex lexer plus bison grammar. Both are reentrant (%option reentrant, %define api.pure full), so multiple compilations may run concurrently and the parser holds no static mutable state. The grammar itself is short (~200 lines) because all per-type knowledge lives in descriptor tables, not in productions.
- Parser is driven entirely by descriptor tables of items and actions. Adding a new flow item is a table edit, not a grammar change. A custom-setter hook on each field is the escape valve for layouts that don't fit a plain byte range (bitfields, indirect arrays).
- Dependencies: rte_ethdev (for rte_flow.h) and rte_net (for MAC parsing). No librte_cmdline. Flex and bison are required at build time to regenerate the lexer and parser; if either tool is missing the library is silently skipped via meson's has_flex_bison check, the same pattern other DPDK components use for optional generators.
- Per-allocation rte_zmalloc for spec/mask/last/conf payloads; rte_flow_compile_free() walks the pattern and action arrays and releases every non-NULL slot before freeing the arrays. Parse-error paths use the same walker, so partially constructed rules clean up uniformly. ASan/LSan run clean on the autotest, including the failure cases.
The grammar follows testpmd's syntax closely so familiar rules carry over:
ingress pattern eth / ipv4 src is 10.0.0.1 / end actions queue index 3 / count / end
and is documented as a formal BNF in the programmer's guide chapter (patch 2).
Initial coverage: eth, vlan, ipv4, ipv6, tcp, udp, vxlan, port_id, port_representor, represented_port items; drop, passthru, queue, mark, jump, count, port_id and representor variants, of_pop_vlan, vxlan_decap actions. Variable-conf items and actions (RSS, RAW) need custom setters and are deferred to a follow-up.
What this RFC is *not*
----------------------
Not a replacement for cmdline_flow.c in testpmd. If the shape here is acceptable, the next step is a separate series adding a "flow compile <port> <rule>" command in testpmd alongside the existing parser, so users can adopt the library incrementally without breaking scripts that depend on the current syntax.
What I'd like feedback on
-------------------------
1. API shape. pcap_compile-style (one string -> opaque object -> arrays) versus the three-call attr/pattern/actions form Sismis's v12 exposes. What does your application actually want?
2. Library placement. Stand-alone at lib/flow_compile/ versus addition to lib/ethdev. This series treats it as a control-path parser layered on top of ethdev rather than part of ethdev itself; v12 places its parser inside ethdev.
3. Table-driven extension model. Is "to add a new flow item, add a row to the descriptor table" the right contract? Should the tables live alongside each rte_flow_item_* definition in rte_flow.h, or in their own file as here?
4. Build-tool dependency. Flex and bison are not currently required to build DPDK. Adding a library that needs them (with a clean has_flex_bison fallback so the rest of DPDK still builds without them) is the cleanest way I see to get a real grammar. If this gets used by testpmd then what is now an optional dependency would get hardened in.
5. Convergence. If this design is preferred, I'm happy to coordinate with Lukas to fold in the testpmd-side changes from his series.
6. Readability. AI generated code like this tends to be either opaque or too verbose for humans. Often have to nudge it into submission.
Stephen Hemminger (4):
config: add support for using flex and bison
flow_compile: introduce textual flow rule compiler
doc: add programmer's guide for flow rule compiler test/flow_compile: add unit tests for flow rule compiler
MAINTAINERS | 7 + app/test/meson.build | 1 + app/test/test_flow_compile.c | 255 ++++++++++ config/meson.build | 23 + doc/guides/prog_guide/flow_compile_lib.rst | 302 ++++++++++++ doc/guides/prog_guide/index.rst | 1 + doc/guides/rel_notes/release_26_07.rst | 6 + lib/flow_compile/flow_compile.l | 227 +++++++++ lib/flow_compile/flow_compile.y | 311 +++++++++++++ lib/flow_compile/flow_compile_priv.h | 127 +++++ lib/flow_compile/flow_compile_setters.c | 516 +++++++++++++++++++++ lib/flow_compile/flow_compile_tables.c | 243 ++++++++++ lib/flow_compile/meson.build | 22 + lib/flow_compile/rte_flow_compile.h | 158 +++++++ lib/flow_compile/rte_flow_compile_api.c | 160 +++++++ lib/meson.build | 1 + 16 files changed, 2360 insertions(+) create mode 100644 app/test/test_flow_compile.c create mode 100644 doc/guides/prog_guide/flow_compile_lib.rst create mode 100644 lib/flow_compile/flow_compile.l create mode 100644 lib/flow_compile/flow_compile.y create mode 100644 lib/flow_compile/flow_compile_priv.h create mode 100644 lib/flow_compile/flow_compile_setters.c create mode 100644 lib/flow_compile/flow_compile_tables.c create mode 100644 lib/flow_compile/meson.build create mode 100644 lib/flow_compile/rte_flow_compile.h create mode 100644 lib/flow_compile/rte_flow_compile_api.c
Signature · 1 line
2.53.0
RFC v2 1/4 config: add support for using flex and bison
For the flow parsing library need flex and bison and these might be useful in future for other libraries. Detect and provide generators for building.
--- config/meson.build | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+)
config/meson.build +23 -0
@@ -296,6 +296,29 @@ if (pcap_dep.found() and cc.has_header('pcap.h', dependencies: pcap_dep) dpdk_extra_ldflags += '-l@0@'.format(pcap_lib) endif +# flex and bison are required for libraries using grammars. +flex = find_program('flex', required: false) +if flex.found() + flex_gen = generator(flex, + output: '@[email protected]', + arguments: ['--outfile=@OUTPUT@', '@INPUT@'], + ) +endif + +bison = find_program('bison', required: false) +if bison.found() + # Parser generator. Emits both the .c and a .tab.h + bison_gen = generator(bison, + output: ['@[email protected]', '@[email protected]'], + arguments: [ + '--defines=@OUTPUT1@', + '--output=@OUTPUT0@', + '@INPUT@', + ], + ) +endif +has_flex_bison = flex.found() and bison.found() + # for clang 32-bit compiles we need libatomic for 64-bit atomic ops if cc.get_id() == 'clang' and dpdk_conf.get('RTE_ARCH_64') == false atomic_dep = cc.find_library('atomic', required: true)
Signature · 1 line
2.53.0
RFC v2 2/4 flow_compile: introduce textual flow rule compiler
In reply to Stephen HemmingerCurrently the only way to compile a flow rule from text is to link against testpmd's cmdline_flow.c, which is tightly coupled to librte_cmdline and the testpmd command framework. Recent attempts to extract it as a library have produced ad-hoc copies rather than a clean separation.
Add librte_flow_compile, modelled on libpcap's pcap_compile(): a textual rule goes in, an opaque compiled object comes out, and diagnostics of the form "line:col: message" go in a caller-supplied buffer. Accessors return the rte_flow_attr/item/action arrays ready for rte_flow_create(); convenience entry points validate the rule against a port (rte_flow_compile_validate) or install it directly (rte_flow_compile_create).
The grammar is a small bison LALR parser (flow_compile.y) fed by a reentrant flex lexer (flow_compile.l). The grammar itself is generic -- it knows only about attributes, items, fields, actions and parameters, with no per-type productions. All per-type knowledge lives in descriptor tables (flow_compile_tables.c) that map item and action names to their rte_flow structures and the field offsets within them, so adding a new item or action type is purely a table edit. The descriptor mechanism currently handles fixed-shape fields only.
Runtime dependencies are limited to rte_ethdev and rte_net; in particular there is no dependency on librte_cmdline. Flex and bison are required at build time only; if either is missing the library is silently skipped via meson's has_flex_bison check. The grammar follows testpmd's syntax so familiar rules carry over, and is documented in the programmer's guide.
Initial coverage spans the common items (eth, vlan, ipv4, ipv6, tcp, udp, vxlan, port_id, port_representor, represented_port) and actions (drop, passthru, queue, mark, jump, count, port_id and representor variants, of_pop_vlan, vxlan_decap). Items and actions with variable-length conf (RSS, RAW) need a future extension to the descriptor mechanism and are deferred.
--- lib/flow_compile/flow_compile.l | 227 +++++++++++ lib/flow_compile/flow_compile.y | 311 ++++++++++++++ lib/flow_compile/flow_compile_priv.h | 127 ++++++ lib/flow_compile/flow_compile_setters.c | 516 ++++++++++++++++++++++++ lib/flow_compile/flow_compile_tables.c | 243 +++++++++++ lib/flow_compile/meson.build | 22 + lib/flow_compile/rte_flow_compile.h | 158 ++++++++ lib/flow_compile/rte_flow_compile_api.c | 160 ++++++++ lib/meson.build | 1 + 9 files changed, 1765 insertions(+) create mode 100644 lib/flow_compile/flow_compile.l create mode 100644 lib/flow_compile/flow_compile.y create mode 100644 lib/flow_compile/flow_compile_priv.h create mode 100644 lib/flow_compile/flow_compile_setters.c create mode 100644 lib/flow_compile/flow_compile_tables.c create mode 100644 lib/flow_compile/meson.build create mode 100644 lib/flow_compile/rte_flow_compile.h create mode 100644 lib/flow_compile/rte_flow_compile_api.c
lib/flow_compile/flow_compile.l new file +227 -0
@@ -0,0 +1,227 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * Copyright (c) 2026 Stephen Hemminger <[email protected]> + * + * Lexer for the flow rule compiler. Reentrant, bison-bridge mode: + * token values go through *yylval, source position through *yylloc. + * Generated by flex(1) at build time; not committed to the tree. + */ + +%option reentrant bison-bridge bison-locations +%option noyywrap nounput noinput +%option prefix="flow_compile_yy" +%option never-interactive +%option warn nodefault +%option extra-type="struct flow_compile_ctx *" + +%top{ +#include <errno.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> + +#include <arpa/inet.h> +#include <sys/socket.h> + +#include <rte_byteorder.h> +#include <rte_errno.h> +#include <rte_ether.h> + +#include "flow_compile_priv.h" +} + +%{ +/* + * The bison-generated header must be visible BEFORE flex emits its + * own YYSTYPE *yylval_r / YYLTYPE *yylloc_r declarations. flex + * places %{ %} content between its forward declarations and the + * generated lexer body, so this is the right home for it; %top{} + * lands too early. + */ +#include "flow_compile.tab.h" + +/* + * %define api.prefix {flow_compile_yy} renames bison's YYSTYPE + * and YYLTYPE to FLOW_COMPILE_YYSTYPE / FLOW_COMPILE_YYLTYPE, but + * flex still emits references to the unprefixed names. Bridge + * with typedefs so flex's generated code compiles. + */ +typedef FLOW_COMPILE_YYSTYPE YYSTYPE; +typedef FLOW_COMPILE_YYLTYPE YYLTYPE; +/* + * YY_USER_ACTION runs before every rule action. Updates yylloc + * to span the matched lexeme and advances the running line/column + * tracked in the ctx so flow_compile_errf() has a position when + * called outside a successful match. + * + * Bare brace block (not do/while) because flex emits this followed + * directly by the rule action with no intervening semicolon. + */ +#define YY_USER_ACTION \ + { \ + struct flow_compile_ctx *_cc = yyextra; \ + yylloc->first_line = _cc->line; \ + yylloc->first_column = _cc->col; \ + for (int _i = 0; _i < yyleng; _i++) { \ + if (yytext[_i] == '\n') { \ + _cc->line++; \ + _cc->col = 1; \ + } else { \ + _cc->col++; \ + } \ + } \ + yylloc->last_line = _cc->line; \ + yylloc->last_column = _cc->col; \ + } + +#define FAIL(...) \ + do { \ + flow_compile_errf(yyextra, __VA_ARGS__); \ + /* Returning 0 (EOF) terminates the parse. We've \ + * already populated errbuf via flow_compile_errf, \ + * and that wins over any subsequent message bison \ + * would generate via yyerror -- first-error-wins. \ + */ \ + return 0; \ + } while (0) + +/* Copy yytext into a NUL-terminated buffer for libc parsers. */ +static inline char * +nul_terminate(char *buf, size_t buflen, const char *src, size_t srclen) +{ + if (srclen >= buflen) + return NULL; + memcpy(buf, src, srclen); + buf[srclen] = '\0'; + return buf; +} + +#define NULTERM(_buf) \ + nul_terminate((_buf), sizeof(_buf), yytext, (size_t)yyleng) +%} + +DEC [0-9]+ +HEX_PFX 0[xX][0-9A-Fa-f]+ +DEC_OCT ([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]) +HEXG [0-9A-Fa-f]{1,4} + +IPV4 {DEC_OCT}\.{DEC_OCT}\.{DEC_OCT}\.{DEC_OCT} + +IPV6 ({HEXG}(:{HEXG}){7})|(({HEXG}(:{HEXG})*)?::({HEXG}(:{HEXG})*)?)|({HEXG}(:{HEXG})*::({HEXG}(:{HEXG})*)?\.[0-9.]+)|::ffff:[0-9.]+ + +MAC_COL [0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2}){5} +MAC_HYP [0-9A-Fa-f]{2}(-[0-9A-Fa-f]{2}){5} +MAC_DOT [0-9A-Fa-f]{4}\.[0-9A-Fa-f]{4}\.[0-9A-Fa-f]{4} +MAC ({MAC_COL}|{MAC_HYP}|{MAC_DOT}) + +IDENT [A-Za-z_][A-Za-z0-9_]* + +%% + + /* whitespace and comments */ +"#"[^\n]* ; +[ \t\r\n\v\f]+ ; + + /* punctuation */ +"/" return '/'; +"," return ','; +"{" return '{'; +"}" return '}'; + + /* keywords -- promoted to first-class tokens so the grammar can + * enforce position (e.g. "ingress" cannot appear where a field + * name is expected). + */ +"pattern" return TK_PATTERN; +"actions" return TK_ACTIONS; +"end" return TK_END; +"ingress" return TK_INGRESS; +"egress" return TK_EGRESS; +"transfer" return TK_TRANSFER; +"group" return TK_GROUP; +"priority" return TK_PRIORITY; +"is" return TK_IS; +"spec" return TK_SPEC; +"last" return TK_LAST; +"mask" return TK_MASK; +"prefix" return TK_PREFIX; + + /* + * Structured value tokens. Order matters: rigid shapes first + * (MAC, IPV4) before more permissive forms. Long hex strings + * before plain integers so they don't get truncated. + */ + +{MAC} { + char buf[18]; + struct rte_ether_addr ea; + + if (NULTERM(buf) == NULL || + rte_ether_unformat_addr(buf, &ea) != 0) + FAIL("bad MAC address '%s'", yytext); + memcpy(yylval->mac, ea.addr_bytes, RTE_ETHER_ADDR_LEN); + return TK_MAC; +} + +{IPV4} { + char buf[INET_ADDRSTRLEN]; + + if (NULTERM(buf) == NULL || + inet_pton(AF_INET, buf, yylval->ipv4) != 1) + FAIL("bad IPv4 address '%s'", yytext); + return TK_IPV4; +} + +0[xX][0-9A-Fa-f]{17,} { + /* Long hex -> opaque byte sequence routed via TK_HEXSTR. + * Stash the lexeme; the FK_BYTES setter in setters.c does + * the byte conversion when the destination size is known. + */ + yylval->ident.text = yytext; + yylval->ident.len = (uint16_t)yyleng; + return TK_HEXSTR; +} + +{HEX_PFX}|{DEC} { + char buf[32]; + char *end; + + if (NULTERM(buf) == NULL) + FAIL("integer '%s' out of range", yytext); + errno = 0; + yylval->u = strtoull(buf, &end, 0); + if (errno != 0 || *end != '\0') + FAIL("integer '%s' out of range", yytext); + return TK_UINT; +} + +{IPV6} { + char buf[INET6_ADDRSTRLEN]; + + if (NULTERM(buf) == NULL || + inet_pton(AF_INET6, buf, yylval->ipv6) != 1) + FAIL("bad IPv6 address '%s'", yytext); + return TK_IPV6; +} + + /* string literals */ +\"([^\\\"]|\\.)*\" { + yylval->ident.text = yytext + 1; + yylval->ident.len = (uint16_t)(yyleng - 2); + return TK_STRING; +} + +\" FAIL("unterminated string"); + + /* identifiers (item names, action names, field names, action params) */ +{IDENT} { + yylval->ident.text = yytext; + yylval->ident.len = (uint16_t)yyleng; + return TK_IDENT; +} + +<<EOF>> return 0; + + /* catch-all */ +. FAIL("unexpected character '%c'", (unsigned char)yytext[0]); + +%%
lib/flow_compile/flow_compile.y new file +311 -0
311 lines not on this page · raw message
lib/flow_compile/flow_compile_priv.h new file +127 -0
127 lines not on this page · raw message
lib/flow_compile/flow_compile_setters.c new file +516 -0
516 lines not on this page · raw message
lib/flow_compile/flow_compile_tables.c new file +243 -0
243 lines not on this page · raw message
lib/flow_compile/meson.build new file +22 -0
@@ -0,0 +1,22 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2026 Stephen Hemminger + +if not has_flex_bison + build = false + reason = 'missing dependency, "flex" and/or "bison"' + subdir_done() +endif + +sources += files( + 'flow_compile_setters.c', + 'flow_compile_tables.c', + 'rte_flow_compile_api.c', +) +sources += flex_gen.process('flow_compile.l') +sources += bison_gen.process('flow_compile.y') + +headers += files( + 'rte_flow_compile.h', +) + +deps += ['ethdev', 'net']
lib/flow_compile/rte_flow_compile.h new file +158 -0
158 lines not on this page · raw message
lib/flow_compile/rte_flow_compile_api.c new file +160 -0
160 lines not on this page · raw message
lib/meson.build +1 -0
@@ -40,6 +40,7 @@ libraries = [ 'efd', 'eventdev', 'dispatcher', # dispatcher depends on eventdev + 'flow_compile', 'gpudev', 'gro', 'gso',
Signature · 1 line
2.53.0
RFC v2 3/4 doc: add programmer's guide for flow rule compiler
In reply to Stephen HemmingerAdd a chapter to the programmer's guide describing the new rte_flow_compile library: API summary, BNF grammar, field qualifier semantics (is/spec/last/mask/prefix), diagnostic format, and the table-driven extension model for adding items and actions.
Notes that the grammar is a strict subset of testpmd's, and documents the limitations of the initial implementation (item/action coverage, missing RSS and RAW handling).
--- MAINTAINERS | 6 + doc/guides/prog_guide/flow_compile_lib.rst | 302 +++++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + doc/guides/rel_notes/release_26_07.rst | 6 + 4 files changed, 315 insertions(+) create mode 100644 doc/guides/prog_guide/flow_compile_lib.rst
MAINTAINERS +6 -0
@@ -448,6 +448,12 @@ F: app/test-pmd/cmdline_flow.c F: doc/guides/prog_guide/ethdev/flow_offload.rst F: lib/ethdev/rte_flow* +Flow Compiler API +M: Stephen Hemminger <[email protected]> +T: git://dpdk.org/next/dpdk-next-net +F: lib/flow_compile/ +F: doc/guides/prog_guide/flow_compile_lib.rst + Traffic Management API M: Cristian Dumitrescu <[email protected]> T: git://dpdk.org/next/dpdk-next-net
doc/guides/prog_guide/flow_compile_lib.rst new file +302 -0
302 lines not on this page · raw message
doc/guides/prog_guide/index.rst +1 -0
@@ -121,6 +121,7 @@ Utility Libraries argparse_lib cmdline + flow_compile_lib ptr_compress_lib timer_lib rcu_lib
doc/guides/rel_notes/release_26_07.rst +6 -0
@@ -64,6 +64,12 @@ New Features * ``--auto-probing`` enables the initial bus probing, which is the current default behavior. +* **Added library to compile flow definitions.** + + New library that works like libpcap ``pcap_compile`` function to compile + a text string into flow rules. + + Removed Items -------------
Signature · 1 line
2.53.0
RFC v2 4/4 test/flow_compile: add unit tests for flow rule compiler
In reply to Stephen HemmingerAdd an autotest for the new rte_flow_compile library. The tests exercise the parser end to end without needing a real ethdev port:
each case compiles a textual rule and inspects the resulting attribute, pattern and action arrays directly.
Coverage spans the common happy paths (simple drop, IPv4/IPv6 match with queue and count actions, MAC matching, CIDR-style prefix masks) and a set of error-path cases. The error tests assert a substring of the diagnostic rather than the full message so that wording can evolve without churning the tests.
Registered as flow_compile_autotest in the fast test suite so it runs under the standard meson test invocation.
--- MAINTAINERS | 1 + app/test/meson.build | 1 + app/test/test_flow_compile.c | 255 +++++++++++++++++++++++++++++++++++ 3 files changed, 257 insertions(+) create mode 100644 app/test/test_flow_compile.c
MAINTAINERS +1 -0
@@ -453,6 +453,7 @@ M: Stephen Hemminger <[email protected]> T: git://dpdk.org/next/dpdk-next-net F: lib/flow_compile/ F: doc/guides/prog_guide/flow_compile_lib.rst +F: app/test/test_flow_compile.c Traffic Management API M: Cristian Dumitrescu <[email protected]>
app/test/meson.build +1 -0
@@ -88,6 +88,7 @@ source_file_deps = { 'test_fib6_perf.c': ['fib'], 'test_fib_perf.c': ['net', 'fib'], 'test_flow_classify.c': ['net', 'acl', 'table', 'ethdev', 'flow_classify'], + 'test_flow_compile.c': ['net', 'ethdev', 'flow_compile'], 'test_func_reentrancy.c': ['hash', 'lpm'], 'test_graph.c': ['graph'], 'test_graph_feature_arc.c': ['graph'],
app/test/test_flow_compile.c new file +255 -0
255 lines not on this page · raw message
Signature · 1 line
2.53.0
Re: [RFC v2 0/4] flow_compile: textual flow rule compiler
In reply to Stephen HemmingerQuoted 166 lines · On Wed, 6 May 2026 17:06:47 -0700 Stephen Hemminger…
Background
----------Multiple efforts over the past few cycles have tried to make testpmd's flow rule grammar reusable from outside testpmd. External applications that need
rte_flowwant a documented way to turn human-written rules into the rte_flow_attr/item/action arrays accepted byrte_flow_create().The most recent attempt is Lukas Sismis's series, currently at v12:
http://patches.dpdk.org/project/dpdk/list/?series=37384
That series factors testpmd's existing
cmdline_flow.cinto a library and updates testpmd to consume it. It works, but inherits two properties ofcmdline_flow.cthat I think are worth avoiding in a reusable library:- Coupling to
librte_cmdline. Even after the v12 split into a "simple" part and a "cmdline" part, the parser is still organized around testpmd's command interpreter, and v12 has cmdline depending on ethdev to break a previous circular dependency. A library used by daemons, control planes, or unit tests should not need that.- Ad-hoc grammar.
cmdline_flow.cimplements parsing per-token in long dispatch logic; the grammar emerges from the code rather than being stated, and adding a new flow item requires touching the parser.This RFC explores a different shape and is posted to ask the list which one is preferred before more work goes into either.
I started a new green-field library for parsing flow rules (with AI assistance for the boilerplate). It is young but passes tests and reviews clean under the project's AI review guidelines.
This series
-----------
lib/flow_compile-- a small new library providing the same service via a pcap_compile()-style API:char errbuf[RTE_FLOW_COMPILE_ERRBUF_SIZE]; struct rte_flow_compile *fc = rte_flow_compile(rule, errbuf); if (fc == NULL) fail(errbuf); /* "line:col: message" */ rte_flow_compile_create(port_id, fc, &flow_error); rte_flow_compile_free(fc);Design properties:
- Flex lexer plus bison grammar. Both are reentrant (%option reentrant, %define api.pure full), so multiple compilations may run concurrently and the parser holds no static mutable state. The grammar itself is short (~200 lines) because all per-type knowledge lives in descriptor tables, not in productions.
- Parser is driven entirely by descriptor tables of items and actions. Adding a new flow item is a table edit, not a grammar change. A custom-setter hook on each field is the escape valve for layouts that don't fit a plain byte range (bitfields, indirect arrays).
- Dependencies:
rte_ethdev(forrte_flow.h) andrte_net(for MAC parsing). Nolibrte_cmdline. Flex and bison are required at build time to regenerate the lexer and parser; if either tool is missing the library is silently skipped via meson'shas_flex_bisoncheck, the same pattern other DPDK components use for optional generators.- Per-allocation
rte_zmallocfor spec/mask/last/conf payloads;rte_flow_compile_free()walks the pattern and action arrays and releases every non-NULL slot before freeing the arrays. Parse-error paths use the same walker, so partially constructed rules clean up uniformly. ASan/LSan run clean on the autotest, including the failure cases.The grammar follows testpmd's syntax closely so familiar rules carry over:
ingress pattern eth / ipv4 src is 10.0.0.1 / end actions queue index 3 / count / end
and is documented as a formal BNF in the programmer's guide chapter (patch 2).
Initial coverage: eth, vlan, ipv4, ipv6, tcp, udp, vxlan,
port_id,port_representor,represented_portitems; drop, passthru, queue, mark, jump, count,port_idand representor variants,of_pop_vlan,vxlan_decapactions. Variable-conf items and actions (RSS, RAW) need custom setters and are deferred to a follow-up.What this RFC is *not*
----------------------Not a replacement for
cmdline_flow.cin testpmd. If the shape here is acceptable, the next step is a separate series adding a "flow compile <port> <rule>" command in testpmd alongside the existing parser, so users can adopt the library incrementally without breaking scripts that depend on the current syntax.What I'd like feedback on
-------------------------1. API shape. pcap_compile-style (one string -> opaque object -> arrays) versus the three-call attr/pattern/actions form Sismis's v12 exposes. What does your application actually want?
2. Library placement. Stand-alone at
lib/flow_compile/versus addition to lib/ethdev. This series treats it as a control-path parser layered on top of ethdev rather than part of ethdev itself; v12 places its parser inside ethdev.3. Table-driven extension model. Is "to add a new flow item, add a row to the descriptor table" the right contract? Should the tables live alongside each rte_flow_item_* definition in
rte_flow.h, or in their own file as here?4. Build-tool dependency. Flex and bison are not currently required to build DPDK. Adding a library that needs them (with a clean
has_flex_bisonfallback so the rest of DPDK still builds without them) is the cleanest way I see to get a real grammar. If this gets used by testpmd then what is now an optional dependency would get hardened in.5. Convergence. If this design is preferred, I'm happy to coordinate with Lukas to fold in the testpmd-side changes from his series.
6. Readability. AI generated code like this tends to be either opaque or too verbose for humans. Often have to nudge it into submission.
Stephen Hemminger (4):
config: add support for using flex and bison
flow_compile: introduce textual flow rule compiler
doc: add programmer's guide for flow rule compiler test/flow_compile: add unit tests for flow rule compilerMAINTAINERS | 7 + app/test/meson.build | 1 + app/test/test_flow_compile.c | 255 ++++++++++ config/meson.build | 23 + doc/guides/prog_guide/flow_compile_lib.rst | 302 ++++++++++++ doc/guides/prog_guide/index.rst | 1 + doc/guides/rel_notes/release_26_07.rst | 6 + lib/flow_compile/flow_compile.l | 227 +++++++++ lib/flow_compile/flow_compile.y | 311 +++++++++++++ lib/flow_compile/flow_compile_priv.h | 127 +++++ lib/flow_compile/flow_compile_setters.c | 516 +++++++++++++++++++++ lib/flow_compile/flow_compile_tables.c | 243 ++++++++++ lib/flow_compile/meson.build | 22 + lib/flow_compile/rte_flow_compile.h | 158 +++++++ lib/flow_compile/rte_flow_compile_api.c | 160 +++++++ lib/meson.build | 1 + 16 files changed, 2360 insertions(+) create mode 100644 app/test/test_flow_compile.c create mode 100644 doc/guides/prog_guide/flow_compile_lib.rst
Quoted 9 lines
create mode 100644 lib/flow_compile/flow_compile.l create mode 100644 lib/flow_compile/flow_compile.y create mode 100644 lib/flow_compile/flow_compile_priv.h create mode 100644 lib/flow_compile/flow_compile_setters.c create mode 100644 lib/flow_compile/flow_compile_tables.c create mode 100644 lib/flow_compile/meson.build create mode 100644 lib/flow_compile/rte_flow_compile.h create mode 100644 lib/flow_compile/rte_flow_compile_api.c
Interesting that CI AI review generates lots of false positives on this. Think the CI infrastructure version of AGENTS.md is out of date, or it is using a weak AI model.
Systematically debunked CI review false positives through code analysis
You're right — the entire review is false positives, and several of them violate the explicit rules in AGENTS.md. Walking through each item:
Patch 1/4 — meson flex_gen / bison_gen initialization
Vague speculation phrased as a question ("Does the code need to..."). The variables are only referenced under if has_flex_bison (or equivalent) elsewhere, which is exactly the pattern the snippet establishes. AGENTS.md forbids "vague suggestions like 'should be verified' or 'should be checked'."
Patch 2/4 — nul_terminate with buflen == 0
False positive. If buflen == 0 and srclen == 0, then srclen >= buflen is true (0 >= 0), so the function returns NULL without writing. Also, every call site uses sizeof(_buf) on a non-empty stack buffer, so buflen is never zero in practice. The function is safe both abstractly and in context.
Patch 2/4 — MAC validation before memcpy
False positive. The code already gates the memcpy on rte_ether_unformat_addr(buf, &ea) != 0. The reviewer is speculating that a documented-success return might leave ea undefined, with no basis. AGENTS.md: don't speculate.
Patch 2/4 — hex_nibble validation
False positive. The lexer regex is 0[xX][0-9A-Fa-f]{17,} — only hex digits can ever reach hex_nibble(). The function is correct by construction of its only caller.
Patch 2/4 — cap * sizeof(*p) overflow
Theoretically possible but practically unreachable: the cap doubles per item parsed, so overflow would require parsing a multi-gigabyte rule string with billions of items. Not a real bug. AGENTS.md says report bugs at >=50% confidence — this is well below that.
Patch 2/4 — leak when later rte_zmalloc fails in begin_item
False positive, and the author specifically anticipated this. Note the comment cc->out->npattern++; /* publish so cleanup walker sees it */ — npattern is incremented before the spec/mask/last allocations. On YYABORT, rte_flow_compile_free() walks pattern[0..npattern] and calls rte_free() on each spec/mask/last, and rte_free(NULL) is a no-op. So if spec succeeds and mask fails, spec is freed and mask/last are skipped. The cleanup design is correct.
Patch 2/4 — scanner leak in success path
This is the most egregious one. The reviewer asks the question, then literally writes "Wait, looking more carefully — does the code call flow_compile_yylex_destroy(scanner) in all error paths?" The answer is yes — flow_compile_yylex_destroy(scanner) is called unconditionally after flow_compile_yyparse(), before the if (rc != 0) check, so it runs on both success and failure. AGENTS.md explicitly bans this self-contradicting pattern: "Do NOT report an issue then contradict yourself."
Patch 2/4 — strtoull() overflow check
False positive. The code does errno = 0; ... strtoull(...); if (errno != 0 || *end != '\0') FAIL(...). That is the canonical strtoull overflow check (ERANGE on overflow). The reviewer is asking documented library behavior questions.
Patch 2/4 — partially initialized fc in rte_flow_compile_free
False positive. out is allocated with rte_zmalloc so npattern/nactions start at 0; pattern/actions slots are zeroed by memset in begin_item/begin_action before publication; and rte_free(NULL) is safe. There is no stale-value path.
Patch 3/4 — included with no findings
AGENTS.md: "OMIT patches that have no issues. Do not include a patch in your output just to say 'no issues found' or to summarize what the patch does." The reviewer included it to say it looked good.
Patch 4/4 — alignment of p[1].spec for IPv4
False positive. rte_zmalloc returns at least cache-line aligned memory by default — far stricter than struct rte_flow_item_ipv4 requires. The struct isn't packed in a way that would change this. Pure FUD.
Meta-observation
Almost every item is phrased as "Does this code...?" rather than a concrete claim. AGENTS.md is explicit: "either it's wrong or don't mention it." The Socratic-question framing is the tell — when the reviewer can't commit to "this is wrong," it usually means it isn't, and the question shouldn't be in the output.
Of the eleven items in the review, zero are real bugs. You can safely ignore the entire review.
Re: [RFC v2 0/4] flow_compile: textual flow rule compiler
In reply to Stephen HemmingerQuoted 107 lines · Stephen Hemminger
Background
----------Multiple efforts over the past few cycles have tried to make testpmd's flow rule grammar reusable from outside testpmd. External applications that need
rte_flowwant a documented way to turn human-written rules into the rte_flow_attr/item/action arrays accepted byrte_flow_create().The most recent attempt is Lukas Sismis's series, currently at v12:
http://patches.dpdk.org/project/dpdk/list/?series=37384
That series factors testpmd's existing
cmdline_flow.cinto a library and updates testpmd to consume it. It works, but inherits two properties ofcmdline_flow.cthat I think are worth avoiding in a reusable library:- Coupling to
librte_cmdline. Even after the v12 split into a "simple" part and a "cmdline" part, the parser is still organized around testpmd's command interpreter, and v12 has cmdline depending on ethdev to break a previous circular dependency. A library used by daemons, control planes, or unit tests should not need that.- Ad-hoc grammar.
cmdline_flow.cimplements parsing per-token in long dispatch logic; the grammar emerges from the code rather than being stated, and adding a new flow item requires touching the parser.This RFC explores a different shape and is posted to ask the list which one is preferred before more work goes into either.
I started a new green-field library for parsing flow rules (with AI assistance for the boilerplate). It is young but passes tests and reviews clean under the project's AI review guidelines.
This series
-----------
lib/flow_compile-- a small new library providing the same service via a pcap_compile()-style API:char errbuf[RTE_FLOW_COMPILE_ERRBUF_SIZE]; struct rte_flow_compile *fc = rte_flow_compile(rule, errbuf); if (fc == NULL) fail(errbuf); /* "line:col: message" */ rte_flow_compile_create(port_id, fc, &flow_error); rte_flow_compile_free(fc);Design properties:
- Flex lexer plus bison grammar. Both are reentrant (%option reentrant, %define api.pure full), so multiple compilations may run concurrently and the parser holds no static mutable state. The grammar itself is short (~200 lines) because all per-type knowledge lives in descriptor tables, not in productions.
- Parser is driven entirely by descriptor tables of items and actions. Adding a new flow item is a table edit, not a grammar change. A custom-setter hook on each field is the escape valve for layouts that don't fit a plain byte range (bitfields, indirect arrays).
- Dependencies:
rte_ethdev(forrte_flow.h) andrte_net(for MAC parsing). Nolibrte_cmdline. Flex and bison are required at build time to regenerate the lexer and parser; if either tool is missing the library is silently skipped via meson'shas_flex_bisoncheck, the same pattern other DPDK components use for optional generators.- Per-allocation
rte_zmallocfor spec/mask/last/conf payloads;rte_flow_compile_free()walks the pattern and action arrays and releases every non-NULL slot before freeing the arrays. Parse-error paths use the same walker, so partially constructed rules clean up uniformly. ASan/LSan run clean on the autotest, including the failure cases.The grammar follows testpmd's syntax closely so familiar rules carry over:
ingress pattern eth / ipv4 src is 10.0.0.1 / end actions queue index 3 / count / end
and is documented as a formal BNF in the programmer's guide chapter (patch 2).
Initial coverage: eth, vlan, ipv4, ipv6, tcp, udp, vxlan,
port_id,port_representor,represented_portitems; drop, passthru, queue, mark, jump, count,port_idand representor variants,of_pop_vlan,vxlan_decapactions. Variable-conf items and actions (RSS, RAW) need custom setters and are deferred to a follow-up.What this RFC is *not*
----------------------Not a replacement for
cmdline_flow.cin testpmd. If the shape here is acceptable, the next step is a separate series adding a "flow compile <port> <rule>" command in testpmd alongside the existing parser, so users can adopt the library incrementally without breaking scripts that depend on the current syntax.
Quoted 8 lines
What I'd like feedback on
-------------------------1. API shape. pcap_compile-style (one string -> opaque object -> arrays) versus the three-call attr/pattern/actions form Sismis's v12 exposes. What does your application actually want?
For this, I wonder if we also could do with a second API for the creation which takes a list of tokens rather than just a single string. Thinking about integration with testpmd, or with apps which already have some commandline interface which produces a list of tokens, having to re-stitch the tokens together into one string seems awkward.
Also, have you already investigated how this might be integrated into testpmd? Do we have the capability to pass multi-token strings via cmdline?
Quoted 5 lines
2. Library placement. Stand-alone at
lib/flow_compile/versus addition to lib/ethdev. This series treats it as a control-path parser layered on top of ethdev rather than part of ethdev itself; v12 places its parser inside ethdev.
+1 to external to ethdev
Quoted 5 lines
3. Table-driven extension model. Is "to add a new flow item, add a row to the descriptor table" the right contract? Should the tables live alongside each rte_flow_item_* definition in
rte_flow.h, or in their own file as here?
Quoted 7 lines
4. Build-tool dependency. Flex and bison are not currently required to build DPDK. Adding a library that needs them (with a clean
has_flex_bisonfallback so the rest of DPDK still builds without them) is the cleanest way I see to get a real grammar. If this gets used by testpmd then what is now an optional dependency would get hardened in.
Flex and bison are very common build tools. I don't see an issue with this dependency.
Quoted 8 lines
5. Convergence. If this design is preferred, I'm happy to coordinate with Lukas to fold in the testpmd-side changes from his series.
6. Readability. AI generated code like this tends to be either opaque or too verbose for humans. Often have to nudge it into submission.
For readability, can you (or the AI's working for you :-) ) split the main patch into a couple of patches for easier review and comment. It's a very large single patch to go through in one go.
/Bruce
Re: [RFC v2 0/4] flow_compile: textual flow rule compiler
Quoted 6 lines · On Thu, 7 May 2026 09:10:48 +0100 Bruce Richardson…
Quoted 5 lines
1. API shape. pcap_compile-style (one string -> opaque object -> arrays) versus the three-call attr/pattern/actions form Sismis's v12 exposes. What does your application actually want?
Quoted 8 lines
For this, I wonder if we also could do with a second API for the creation which takes a list of tokens rather than just a single string. Thinking about integration with testpmd, or with apps which already have some commandline interface which produces a list of tokens, having to re-stitch the tokens together into one string seems awkward.
Also, have you already investigated how this might be integrated into testpmd? Do we have the capability to pass multi-token strings via cmdline?
Lex pass does tokenizing in a way that is different than simple string split. Could have a wrapper that takes list of tokens and quotes them back to a string.
For testpmd integration.
- the new compiler may intentionally diverge from existing adhoc parsing. The AI code generation already flagged a couple of these and put note in documentation.
- testpmd (and probably cmdline) will need ability to not pass unparsed string, may need new cmdline type for "rest of line as string"
- AI proposed new syntax:
flow compile <port> "quote rule"
Re: [RFC v2 0/4] flow_compile: textual flow rule compiler
Quoted 22 lines · Stephen Hemminger
Quoted 6 lines · On Thu, 7 May 2026 09:10:48 +0100 Bruce Richardson…
Quoted 5 lines
1. API shape. pcap_compile-style (one string -> opaque object -> arrays) versus the three-call attr/pattern/actions form Sismis's v12 exposes. What does your application actually want?
Quoted 8 lines
For this, I wonder if we also could do with a second API for the creation which takes a list of tokens rather than just a single string. Thinking about integration with testpmd, or with apps which already have some commandline interface which produces a list of tokens, having to re-stitch the tokens together into one string seems awkward.
Also, have you already investigated how this might be integrated into testpmd? Do we have the capability to pass multi-token strings via cmdline?
Lex pass does tokenizing in a way that is different than simple string split. Could have a wrapper that takes list of tokens and quotes them back to a string.
Quoted 8 lines
For testpmd integration.
- the new compiler may intentionally diverge from existing adhoc parsing. The AI code generation already flagged a couple of these and put note in documentation.- testpmd (and probably cmdline) will need ability to not pass unparsed string, may need new cmdline type for "rest of line as string"
Checking with Claude, it seems it's there already:
Multi-string (TOKEN_STRING_MULTI) — reads until cmdline_isendofcommand(), which stops only at \n, \r, \0, or #. This captures the entire remainder of the line including spaces.
Quoted 2 lines
- AI proposed new syntax:
flow compile <port> "quote rule"
I tend to prefer explicit pre-field names in the syntax as a general rule as it makes it clearer what the numeric values in the command are. So I suggest e.g.:
"flow_compile port <N> rule: ...."
In the absense of quoting, I think having a ":" at the end of rule helps to separate the testpmd syntax from the rule syntax.
/Bruce
Re: [RFC v2 0/4] flow_compile: textual flow rule compiler
Quoted 7 lines · On Thu, 7 May 2026 17:26:44 +0100 Bruce Richardson…
Checking with Claude, it seems it's there already:
Multi-string (
TOKEN_STRING_MULTI) — reads untilcmdline_isendofcommand(), which stops only at \n, \r, \0, or #. This captures the entire remainder of the line including spaces.Quoted 2 lines
- AI proposed new syntax:
flow compile <port> "quote rule"
Quoted 8 lines
I tend to prefer explicit pre-field names in the syntax as a general rule as it makes it clearer what the numeric values in the command are. So I suggest e.g.:
"
flow_compileport <N> rule: ...."In the absense of quoting, I think having a ":" at the end of rule helps to separate the testpmd syntax from the rule syntax.
Would be good to have flow_compile as temporary solution and replace the old parser later. I can't see huge requirement for quoting with current syntax, good to have but no fields seem to require it