Skip to content

Flowtable: The Fast Path for Forwarded Flows

How the kernel lets forwarded flows that are already in a flow table skip most of the netfilter hook path

Source links point at Linux v7.4-rc3, the tree this page was checked against. Release numbers are mainline releases. Behaviour that changed recently is marked with the release that introduced it and links to the commit. "The kernel documentation" is nf_flowtable.rst.

What it does

The kernel documentation describes the design: once the first packet of a flow has gone through the IP forwarding path, a rule can add the flow to a table (nf_flowtable.rst:15-19). A packet that finds a matching entry is transmitted without the classic forwarding path, and a packet that doesn't follows the classic path (nf_flowtable.rst:20-26). The lookup runs in a hook at ingress on the devices listed in the flowtable: nf_flow_offload_ip_hook() for IPv4 and nf_flow_offload_ipv6_hook() for IPv6, registered through the flowtable types (nf_flow_table_inet.c:68-96).

                   ingress hook
        ┌───────────────────────────────┐
        │        flowtable lookup       │
        └─┬───────────────────────────┬─┘
          │ hit                       │ miss or fall back
          ▼                           ▼
┌───────────────────┐     ┌───────────────────────┐
│  rewrite headers, │     │     classic path:     │
│    send out the   │     │  prerouting, forward, │
│   egress device   │     │      postrouting      │
└───────────────────┘     └───────────────────────┘

The diagram is simplified from Fig. 1 of the kernel documentation (nf_flowtable.rst:37-70). The figure labels the rule that adds an entry "flow offload"; the example below spells it flow add.

Which hooks a software hit passes, from the source:

The kernel documentation says "you do not see these packets from any of the Netfilter hooks coming after ingress" (nf_flowtable.rst:22-23). The source differs; see Differences.

The tc ct action uses the same infrastructure (act_ct.c:453 calls flow_offload_add()). This page covers the nftables side.

Turning it on

The kernel documentation's example is a flowtable on two devices and one rule in the forward chain (nf_flowtable.rst:87-96):

table inet x {
    flowtable f {
        hook ingress priority 0; devices = { eth0, eth1 };
    }
    chain y {
        type filter hook forward priority 0; policy accept;
        ip protocol tcp flow add @f
        counter packets 0 bytes 0
    }
}
  • The statement. flow add @f is evaluated by nft_flow_offload_eval(). It is accepted only in a chain on the forward hook (nft_flow_offload_validate()). The example rule matches IPv4 TCP.
  • What a hit skips. A hit that is transmitted is consumed with NF_STOLEN (nf_flow_queue_xmit(), nf_flow_xmit_xfrm()), so the later packets of a flow that hit the table don't reach the prerouting and forward chains, and reach postrouting only in a direction with an IPsec transform (above). The kernel documentation says the counter rule stops being updated (nf_flowtable.rst:105-109).
  • Rule evaluation. An earlier rule that accepts or drops the packet ends evaluation of the base chain, including any chain it jumped to (nf_tables_core.c:306-312), so flow add never runs for it in that chain. flow add returns no verdict when it adds the flow. On every other path it sets NFT_BREAK (nft_flow_offload_eval()), which skips the rest of that rule and continues with the next rule (nf_tables_core.c:292-295). So statements after flow add in the same rule run only for the packet that adds the flow.
  • The counter flag. Software hits update conntrack's counters only if the flowtable has the counter flag (nf_flow_table_ip.c:520 for IPv4, nf_flow_table_ip.c:1148 for IPv6; documented in nf_flowtable.rst:165-181). The update reaches only conntrack entries that have the accounting extension (nf_ct_acct_add()), which is added when the entry is created and only if the sysctl net.netfilter.nf_conntrack_acct is set (nf_conntrack_acct.h:36, nf_conntrack_core.c:1789, nf_conntrack_standalone.c:691).
  • Priority. The kernel documentation says to "make sure the flowtable priority is smaller than the nftables ingress chain hence the flowtable runs before in the pipeline" (nf_flowtable.rst:99-103). A hit that is transmitted returns NF_STOLEN, which ends hook traversal (nf_hook_slow()), so an ingress chain that runs after the flowtable doesn't see it.
  • Device list. Path resolution follows VLAN, PPPoE and bridge devices down to the real device (nft_dev_fill_forward_path()) and requires that device to be in the flowtable's list (nf_flow_table_path.c:198). The check runs for both directions and is skipped for IPsec routes (nf_flow_table_path.c:314-320). The kernel documentation says the real device is sufficient and the VLAN and PPPoE devices need not be listed (nf_flowtable.rst:129-130).
  • Failed path discovery. Since v7.2 (871df5007eda), a failed path discovery or a device that isn't in the flowtable makes flow add give up. The commit message says "If forward path discovery fails for any reason or netdevice is not registered for this flowtable, then bail out to classic forwarding path rather than providing incomplete forwarding path."
  • Missing devices. A device name in the flowtable that matches no existing device is accepted (nf_tables_api.c:2456; since v6.16, 6d07a289504a) and registers no hook until a device with that name appears (a331b78a5525).

Two flowtable options appear in the kernel documentation: counter (nf_flowtable.rst:165-181) and flags offload (nf_flowtable.rst:183-196):

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

The kernel options are CONFIG_NF_FLOW_TABLE (Kconfig:711; it depends on NETFILTER_INGRESS, NF_CONNTRACK and NF_TABLES), CONFIG_NF_FLOW_TABLE_INET (Kconfig:703; nf_flow_table_inet.c:68-96 defines the inet, IPv4 and IPv6 flowtable types) and CONFIG_NFT_FLOW_OFFLOAD (Kconfig:504).

How a flow gets in

nft_flow_offload_eval() runs on a packet in the forward path and checks:

If all of that holds:

  1. nft_flow_route() resolves the path. It reuses the route of the packet being processed for one direction and looks up the reverse route (nf_flow_table_path.c:305).
  2. Only the packet's own direction can carry an IPsec transform. Its route is the one the forward path attached to the packet (ip_forward.c:121, ip6_output.c:612). The reverse lookup does no IPsec lookup in IPv4 unless the flow key's protocol is set (route.c:2984), and nft_flow_route() clears the key without setting it (nf_flow_table_path.c:280); IPv6 does none (ipv6/netfilter.c:102). b5964aac51e0 says "the existing basic xfrm offload (which only works in one direction)".
  3. For routes without an IPsec transform the resolution also requires the egress device to be in the flowtable and, on an Ethernet device, a neighbour entry in a valid state (NUD_VALID, nf_flow_table_path.c:61-77).
  4. flow_offload_alloc() allocates the entry with a reference to the conntrack entry and the SNAT and DNAT flags.
  5. flow_offload_add() inserts the entry's two tuples, one per direction, into one resizable hash table. Its comment says garbage collection walks only the original-direction entries, so that one is inserted last.

For TCP, flow_offload_ct_tcp() sets the "be liberal" flag on the conntrack entry; its comment says conntrack will not see all packets any more, so it can "disable tcp window validation". In the flowtable files the flag is set only at nft_flow_offload.c:45-46 and cleared nowhere; the tc ct action sets it too (act_ct.c:441-442).

Transmit modes

Each direction of a flow has a transmit type chosen at add time (nft_xmit_type()):

Each direction caches its route in the entry, except in direct mode without a tunnel, where the route is released (nf_flow_table_core.c:129-136).

What a hit does

nf_flow_offload_ip_hook() looks up the packet's tuple. A miss returns NF_ACCEPT and the packet follows the classic path. On a hit, nf_flow_offload_forward():

  1. Checks the packet against the MTU recorded for the packet's direction. A packet that is too big goes to the classic path (nf_flow_exceeds_mtu()); the kernel documentation gives the reason as the packet-too-big ICMP error (nf_flowtable.rst:78-79).
  2. Checks TCP flags (nf_flow_state_check(); see How a flow leaves).
  3. Checks the cached route of the packet's direction, if that direction keeps one (nf_flow_dst_check() returns true when there is none). A stale route tears the flow down and the packet goes to the classic path. A direction in direct mode without a tunnel keeps no route (nf_flow_table_core.c:129-136), so neither the hook nor the garbage collector notices a route change for it. In the bridge case, the commit that added direct mode, 7a27f6ab4135, says "if peer is moved to different bridge port, the connection will time out".
  4. Refreshes the deadline (flow_offload_refresh()), strips any VLAN, PPPoE or IPIP tunnel header (IPIP since v6.19, ab427db17885), applies the stored NAT rewrite, decrements the TTL, and updates conntrack's counters if the flowtable has counter.

The hook then transmits as described in Transmit modes: nf_flow_queue_xmit4() pushes any egress VLAN, PPPoE or tunnel header back on, builds the link-layer header with dev_hard_header() and calls dev_queue_xmit(). IPsec hits skip that and go out through dst_output().

nf_flow_offload_ipv6_hook() does the same, with the hop limit in place of the TTL (nf_flow_table_ip.c:1069 checks it, nf_flow_table_ip.c:1145 decrements it). The next header has to be TCP, UDP or GRE, so a packet with any extension header is a miss (nf_flow_table_ip.c:1050-1067). It strips IPv6-in-IPv6 tunnel headers since v7.0 (d98103575dcd). Mixed-family tunnels are not supported: the IPv4 path strips only IPIP headers (nf_flow_table_ip.c:331), the IPv6 path only IPv6-in-IPv6 headers (nf_flow_table_ip.c:356), and d0107f381622 says IPv4 over IPv6 and SIT tunnel offloading "is not enabled yet".

Packets that the hook doesn't take go to the classic path: fragments and packets with IPv4 options (nf_flow_table_ip.c:230), a TTL or hop limit of 1 or less (nf_flow_table_ip.c:253, nf_flow_table_ip.c:1069), and GRE other than version 0 (nf_flow_table_ip.c:270, nf_flow_table_ip.c:1086).

How a flow leaves

The garbage collector, nf_flow_offload_work_gc(), re-queues itself one second after each run (nf_flow_table_core.c:626) and removes entries that have been torn down. Teardown is triggered by:

 flow add
    │
    ▼
 in table ◄── software hits refresh the deadline
    │   │
    │   └── TCP FIN or RST ──► closing (hits continue)
    │                              │
    ├──────────────────────────────┘
    │  timeout, dying conntrack entry, stale route,
    │  missing output device or neighbour error, SYN on a closing flow,
    │  device down, flowtable deleted
    ▼
 torn down: software lookups miss, TCP and UDP conntrack entry fixed up,
            offload bit cleared
    │
    ▼
 removed by the garbage collector: in the same run if it did the teardown,
 otherwise within about a second; hardware flows after the driver
 delete completes; at once for software flows on device down, and for all
 flows on flowtable deletion

TCP FIN and RST don't end the flow at once (since v6.14, fdbaf5163331). nf_flow_state_check() marks the flow NF_FLOW_CLOSING and the packet still takes the fast path; nf_flow_offload_gc_step() deletes the hardware rule early and the flow stays in the software table. Software hits keep pushing the deadline, so the flow leaves when the timeout expires after the last packet, and flow_offload_fixup_ct() then gives conntrack the close state and timeout. A later SYN on a closing flow tears it down at once, sets the conntrack state to close and sends that packet to the classic path (nf_flow_state_check(), flow_offload_fixup_tcp()).

Adding again. flow_offload_teardown() clears the offload bit on the conntrack entry (nf_flow_table_core.c:401), so a later forward-chain packet that matches the flow add rule can add the flow again, if it passes the checks in How a flow gets in again. A closing TCP flow gets the close state at teardown (nf_flow_table_core.c:218-221), so it isn't added again until it is established (nf_conntrack_tcp_established()).

Conntrack timeout. While a flow is in the table, conntrack may see few or none of its packets; the comment in nf_flow_table_extend_ct_timeout() says "nf_conntrack might not see any packets anymore" (nf_flow_table_core.c:506-513). flow_offload_add() first sets the conntrack timeout to a day (nf_flow_table_core.c:358). Afterwards the collector calls nf_flow_table_extend_ct_timeout(), which sets a new timeout when less than five minutes remain. The value depends on the protocol and TCP state (nf_flow_table_tcp_timeout()):

Flow Conntrack timeout is set to
UDP, GRE (GRE since v7.4-rc3, 46ecda278f6e) a day
TCP established a day
TCP FIN_WAIT, CLOSE_WAIT, LAST_ACK, TIME_WAIT five minutes
Other TCP states (SYN_SENT, SYN_RECV, CLOSE, ...) no extension

The comment in nf_flow_table_extend_ct_timeout() calls the value "an arbitrary timeout large enough not to ever expire".

Hand-back to conntrack. flow_offload_fixup_ct() runs at teardown.

  • TCP state. It keeps the last conntrack state, or sets close if the flow was closing, and clears the recorded maximum window and the max-ack flag; the code comment says that otherwise conntrack's TCP reset validation would fail (flow_offload_fixup_tcp()).
  • Timeout. TCP and UDP flows have the conntrack timeout lowered to the normal value for their state, less the flowtable timeout if the flow expired; a closing TCP flow gets the close timeout unconditionally (nf_flow_table_core.c:250-252).
  • Established TCP. Except for a closing TCP flow, the timeout is only lowered, so an established TCP entry, whose default timeout is five days (nf_conntrack_proto_tcp.c:64), keeps the timeout it has left (a day or less, unless a packet of the flow went through conntrack while it was in the table) until a packet goes through conntrack again.
  • Next conntrack packet. When conntrack processes another packet of a TCP flow, its TCP tracker can set the timeout again, for example with the refresh at nf_conntrack_proto_tcp.c:1381. That refresh does not change the timeout of entries with a fixed timeout (__nf_ct_refresh_acct(), nf_conntrack_core.c:2094-2096).
  • GRE. GRE flows return before any timeout change (nf_flow_table_core.c:240-241).

Hardware offload

The kernel documentation says a flowtable can offload flows to a device that supports it, enabled with flags offload, and that a workqueue adds the flows, so a few packets can still take the software path first (nf_flowtable.rst:183-201).

The driver interface is the tc flow-block interface:

XDP lookup. XDP programs can look a flowtable up with bpf_xdp_flow_lookup (391bb6594fd3, v6.11). It sees only flowtables without flags offload (89cc8f1c5f22, v6.11), returns the first flowtable bound to the device (nf_flow_table_xdp.c:36-42), and nf_flow_table_bpf.c is built with CONFIG_DEBUG_INFO_BTF when the flowtable is built in and CONFIG_DEBUG_INFO_BTF_MODULES when it is a module (Makefile:147-150).

Behaviour with flags offload, from the source:

Inspecting

Limits

  • Rule changes. Removing a rule runs the expression's deactivate and destroy callbacks, which release the expression's use of the flowtable and its conntrack hook registration for the netns, and don't touch flow entries (nft_flow_offload.c:185-206). The ways a flow leaves are in How a flow leaves.
  • Rules a hit doesn't reach. A hit never reaches the prerouting and forward chains, and a software hit pushes the deadline out (flow_offload_refresh()). The stored NAT rewrite is applied to a hit (nf_flow_offload_forward()). Packets the hook passes to the classic path, such as fragments and over-MTU packets, still reach those chains.
  • Consequence. A flow already in the table keeps being forwarded after the flow add rule is removed or a drop rule is added to the prerouting or forward chains, or to postrouting for a direction without an IPsec transform, as long as packets keep arriving; hardware flows get their deadline from driver statistics instead (flow_offload_work_stats()).
  • Cache. The kernel documentation says the table behaves like a cache and that entries might get stale if the destination MAC address or the egress device changes, which "might be a problem" with software mode combined with bridging and IP forwarding, and with hardware offload (nf_flowtable.rst:214-222).
  • IPsec. A packet that carries a security path never triggers an add (nft_flow_offload_skip()). In the direction whose route has an IPsec transform the device-list and neighbour checks are skipped (nf_flow_table_path.c:314-320); the other direction gets them like any other flow.
  • ip6gre. The commit that extended the GRE timeout, 46ecda278f6e, says ip6gre tunnels with the default encapsulation limit carry a Destination Options header before GRE, which the flowtable doesn't parse, so every packet of the flow takes the classic path.

Where it came from

The design was posted to netfilter-devel by Pablo Neira Ayuso. LWN reproduces two of the postings, and the kernel documentation cites them (nf_flowtable.rst:224-235).

  • 3 November 2017, [PATCH RFC,WIP 0/5] Flow offload infrastructure (Message-ID <20171103152636.9967-1-pablo@netfilter.org>). The cover letter describes a module with a hook at ingress, populated by an nftables action once a flow is established. It gives the hardware motivation: "Switches and NICs come with built-in flow table, I've been observing out of tree patches in OpenWRT/LEDE to integrate this into Netfilter for a little while." It reports a measurement: "I'm measuring here that the software flow table forwarding path is 2.5 faster than the classic forwarding path in my testbed." Its TODO list included IPv4 only, IPv4 SNAT only, no netns support and no flow counters, and the last patch added ndo hooks to populate a hardware flow table.
  • 22 December 2017, [PATCH nf-next,v3 0/7] Flow offload infrastructure (Message-ID <20171222192732.13188-1-pablo@netfilter.org>). The cover letter lists IPv6 and mixed IPv4/IPv6 support, hardware offload in a separate nf_flow_table_hw module, port translation and netns support. The hardware patch was tagged RFC, and the cover letter says "I will keep this one back until there's an initial driver that introduces flow table offload support".

The software flow table was committed on 8 January 2018 (ac2a66665e23 adds the generic infrastructure and a3c90f7a2323 the nftables expression) and first appeared in v4.16. Felix Fietkau reorganised the code in a series written in February 2018 and merged for v4.18, for example in 1a999d899bc2, which renamed nf_flow_table.c to nf_flow_table_core.c.

Hardware offload reached the tree in v5.5 through the tc flow-block interface rather than through the dedicated ndo hooks proposed in the RFC. Pablo Neira Ayuso added it in c29f74e0df7a, which called ndo_setup_tc with TC_SETUP_BLOCK and the callbacks with TC_SETUP_FT. The arrangement described above came from two fixes by wenxu in the same release, ee1bcfe01251 and e052901991ae. wenxu added the indirect path in b5140a36da78 (v5.7).

GRE timeout history.

  • 03428ca5cee9 (v6.14) reworked the conntrack timeout extension. For GRE it fell into the default branch, which left new_timeout at its initial value true (one jiffy) and hit WARN_ON_ONCE() once a GRE entry's timeout fell below five minutes.
  • The extension never took effect until 53b3e60edb67 (v7.2): it compared a relative value with the absolute ct->timeout, so the update never succeeded. Once it did, the default branch's one-jiffy timeout applied to GRE.
  • 46ecda278f6e (v7.4-rc3) says "the default branch sets the new timeout to 1 jiffy, so the conntrack entry expires right away" and extends GRE like UDP. The packets that bring a GRE entry's timeout down are those that still go through conntrack; the commit message gives packets with a TTL of 1 or less as an example.
  • Both fixes carry Cc: stable@vger.kernel.org.

Differences from nf_flowtable.rst

The kernel documentation was last updated with new content in March 2021 (v5.13, 143490cde566); a build-warning fix followed the next day (794d9b25817a). As of v7.4-rc3, at least these statements in it no longer match the source:

  • It says TCP RST and FIN packets are passed up to the classic path (nf_flowtable.rst:77-78). Since fdbaf5163331 ("netfilter: flowtable: add CLOSING state", v6.14), they stay on the fast path and the flow enters the closing state. The commit message explains that the old behaviour "leads to packet races when restoring the conntrack state as well as late flow re-offload situations".
  • It says hits are sent with neigh_xmit() (nf_flowtable.rst:21, nf_flowtable.rst:74). Direct mode has called dev_queue_xmit() since 7a27f6ab4135 (v5.13, the same day as the documentation update), and b5964aac51e0 ("netfilter: flowtable: consolidate xmit path", v6.19) moved neighbour mode to it too.
  • It says packets are not seen "from any of the Netfilter hooks coming after ingress" (nf_flowtable.rst:22-23). The netfilter egress hook, added in 42df6e1d221d (v5.16, after the documentation was written), does see software hits in a direction without an IPsec transform, because they end in dev_queue_xmit(). An IPsec hit also runs postrouting, because it goes out through dst_output(), which it has done since 589b474a4b7c (v5.3), before the documentation was last updated.
  • It says the rule adds the flow on "the TCP syn-ack packet" (nf_flowtable.rst:105-106). The code requires an established and assured conntrack entry (nf_conntrack_tcp_established()). e5eaac2beb54 (v5.18) added that check, and its message says the patch makes nft_flow_offload "skip packets in SYN_RECV state" and "postpones offload up to the next packet".
  • It lists TCP and UDP as the supported layer 4 protocols (nf_flowtable.rst:10). GRE has also been accepted since 4e8d9584d154 (v5.18).

Further reading