opnsense-deps/fastpath/cmm/cmm_conn.c
Jeremy Karst ae932c9c46 Offload: follow next-hop MAC changes; veto af-to
cmm put a next hop's MAC into CDX when it programmed the route and then
only watched the next hop's address and interface. A next hop that
changed its MAC (a new ISP modem, an IP reused by another LAN host) kept
receiving its flows at the old MAC, possibly another host's, and new
flows reused the stale route until cmm was restarted. Neighbors no route
used also stayed cached as resolved, so a later route to the same IP got
the old MAC without asking the kernel.

cmm_neigh_check() now re-reads the ARP and NDP tables (one dump per
family) and marks every cached neighbor whose MAC changed or is gone;
cmm_route_check_neighbors() deregisters the routes using it and their
offloaded flows, which re-offload once the next hop resolves again. It
runs every maintenance cycle (30 s) and after route-socket changes, and
cmm_route_handle_change() also treats a different MAC as a change. The
last reference to a neighbor frees it. The link-layer table parser is
shared by both lookups and bounds-checks each entry's length.

pf_notify vetoes af-to (NAT64) states: their two keys are in different
address families, which cmm cannot program.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 04:22:57 -05:00

1136 lines
30 KiB
C

/*
* cmm_conn.c — PF state event handling and connection tracking
*
* Maintains a local connection table driven by push-based events
* from /dev/pfnotify (pf_notify.ko).
*
* New connections are checked for offload eligibility and
* programmed into CDX. Expired connections are removed from CDX.
*
* Copyright 2026 Mono Technologies Inc.
* Copyright (C) 2007 Mindspeed Technologies, Inc.
* Copyright 2014-2016 Freescale Semiconductor, Inc.
* Copyright 2017, 2021 NXP
* SPDX-License-Identifier: GPL-2.0+
*/
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/pfvar.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include "cmm.h"
#include "cmm_conn.h"
#include "cmm_route.h"
#include "cmm_neigh.h"
#include "cmm_itf.h"
#include "cmm_fe.h"
#include "cmm_bridge.h"
#include "cmm_deny.h"
#include "pf_notify.h"
#include "fpp_private.h"
#include "libfci.h"
#include <netinet/tcp_fsm.h>
#ifndef PF_IN
#define PF_IN 1
#endif
#define CMM_CONN_MAX 65536
static struct list_head conn_hash[CONN_HASH_SIZE];
static unsigned int conn_count;
static unsigned int conn_offloaded;
/*
* Hash by original 5-tuple (proto, af, saddr, daddr, sport, dport).
* Uses the STACK key which is identical for both the PF_IN and PF_OUT
* states of a NAT connection, so both map to the same conn entry.
*/
static inline unsigned int
conn_hash_5tuple(sa_family_t af, uint8_t proto,
const void *saddr, const void *daddr,
uint16_t sport, uint16_t dport)
{
uint32_t a, b, c;
if (af == AF_INET) {
uint32_t sa, da;
memcpy(&sa, saddr, 4);
memcpy(&da, daddr, 4);
a = sa ^ ((uint32_t)proto << 16) ^ (uint32_t)sport;
b = da ^ (uint32_t)dport;
c = 0;
} else {
a = jhash(saddr, 16, (uint32_t)proto);
b = jhash(daddr, 16, (uint32_t)sport);
c = (uint32_t)dport;
}
return (jhash_3words(a, b, c, 0) % CONN_HASH_SIZE);
}
static struct cmm_conn *
conn_find_5tuple(sa_family_t af, uint8_t proto,
const void *saddr, const void *daddr,
uint16_t sport, uint16_t dport)
{
struct list_head *bucket, *pos;
struct cmm_conn *conn;
unsigned int h;
int alen;
h = conn_hash_5tuple(af, proto, saddr, daddr, sport, dport);
bucket = &conn_hash[h];
alen = (af == AF_INET) ? 4 : 16;
for (pos = list_first(bucket); pos != bucket; pos = list_next(pos)) {
conn = container_of(pos, struct cmm_conn, hash_entry);
if (conn->af == af &&
conn->proto == proto &&
conn->orig_sport == sport &&
conn->orig_dport == dport &&
memcmp(conn->orig_saddr, saddr, alen) == 0 &&
memcmp(conn->orig_daddr, daddr, alen) == 0)
return (conn);
}
return (NULL);
}
static void
conn_remove(struct cmm_global *g, struct cmm_conn *conn)
{
/* Deregister from CDX if offloaded */
if (conn->flags & CONN_F_OFFLOADED) {
if (conn->af == AF_INET)
cmm_fe_ct4_deregister(g, conn);
else
cmm_fe_ct6_deregister(g, conn);
if (conn_offloaded > 0)
conn_offloaded--;
}
/* Release route references */
if (conn->orig_route != NULL) {
cmm_route_put(conn->orig_route);
conn->orig_route = NULL;
}
if (conn->rep_route != NULL) {
cmm_route_put(conn->rep_route);
conn->rep_route = NULL;
}
list_del(&conn->hash_entry);
free(conn);
if (conn_count > 0)
conn_count--;
}
/*
* Resolve iif_index from the opposite route's output interface.
* If the output goes through a bridge, look up the opposite route's
* neighbor MAC in the bridge FDB to find the physical ingress port.
* For non-bridge interfaces, returns oif_index unchanged.
*/
static int
resolve_iif_index(struct cmm_route *opp_route)
{
struct cmm_interface *itf;
int iif;
iif = opp_route->oif_index;
itf = cmm_itf_find_by_index(iif);
if (itf != NULL && (itf->itf_flags & ITF_F_BRIDGE) &&
opp_route->neigh != NULL) {
char port_name[IFNAMSIZ];
struct cmm_interface *port;
if (cmm_bridge_resolve_port(itf->ifindex,
opp_route->neigh->macaddr, port_name,
sizeof(port_name)) == 0) {
port = cmm_itf_find_by_name(port_name);
if (port != NULL)
iif = port->ifindex;
} else {
cmm_print(CMM_LOG_DEBUG,
"conn: bridge %s FDB miss for "
"mac=%02x:%02x:%02x:%02x:%02x:%02x",
itf->ifname,
opp_route->neigh->macaddr[0],
opp_route->neigh->macaddr[1],
opp_route->neigh->macaddr[2],
opp_route->neigh->macaddr[3],
opp_route->neigh->macaddr[4],
opp_route->neigh->macaddr[5]);
}
}
return (iif);
}
/*
* Try to offload a connection:
* 1. Look up routes for both directions
* 2. Resolve next-hop neighbors (retry-safe)
* 3. Send routes to CDX
* 4. Send conntrack to CDX
*
* Safe to call multiple times — skips steps already completed.
*/
/* Does rt leave through the interface named ifname? */
static int
route_leaves_by(const struct cmm_route *rt, const char *ifname)
{
struct cmm_interface *itf;
itf = cmm_itf_find_by_index(rt->oif_index);
return (itf != NULL && strcmp(itf->ifname, ifname) == 0);
}
/*
* Does rt send its packets where a route-to/reply-to would: out of the
* interface named ifname, to the next hop addr? cmm_route keeps the
* destination itself as the next hop of a directly connected route.
*/
static int
route_sends_to(const struct cmm_route *rt, const char *ifname,
const uint8_t *addr)
{
return (route_leaves_by(rt, ifname) &&
memcmp(rt->gw, addr, rt->family == AF_INET ? 4 : 16) == 0);
}
/*
* Tell pf_notify which states are now forwarded in hardware: it makes them
* sloppy, as their TCP windows stop being tracked.
*/
static void
conn_report_offloaded(struct cmm_global *g, const struct cmm_conn *conn)
{
struct pfn_state_ref refs[2];
struct pfn_offloaded off;
int i;
memset(refs, 0, sizeof(refs));
for (i = 0; i < 2; i++) {
refs[i].id = conn->st[i].id;
refs[i].creatorid = conn->st[i].creatorid;
}
off.count = 2;
off.pad = 0;
off.refs = refs;
if (ioctl(g->pfnotify_fd, PFN_IOC_OFFLOADED, &off) < 0)
cmm_print(CMM_LOG_WARN, "conn: PFN_IOC_OFFLOADED: %s",
strerror(errno));
}
static int
conn_try_offload(struct cmm_global *g, struct cmm_conn *conn)
{
int i;
/*
* Only a flow pf passed in and out, with nothing in its rules that
* only pf_test() can do (pf_notify's veto), goes into hardware.
*/
if (conn->flags & CONN_F_VETO)
return (-1);
if (!conn->st[CONN_ST_IN].seen || !conn->st[CONN_ST_OUT].seen)
return (-1);
/* Look up route for original direction (dst = orig_daddr) */
if (conn->orig_route == NULL)
conn->orig_route = cmm_route_get(g, conn->af,
conn->orig_daddr);
if (conn->orig_route == NULL) {
cmm_print(CMM_LOG_DEBUG,
"conn: no route for original direction");
return (-1);
}
/*
* Look up route for reply direction.
*
* CDX rewrites the reply packet before forwarding: for SNAT,
* it changes the destination from the NAT'd address back to
* the original source. The route must deliver the rewritten
* packet, so look up orig_saddr (the real client address),
* not rep_daddr (the NAT'd address on the external wire).
*
* For non-NAT connections, orig_saddr == rep_daddr anyway.
*/
if (conn->rep_route == NULL)
conn->rep_route = cmm_route_get(g, conn->af,
conn->orig_saddr);
if (conn->rep_route == NULL) {
cmm_print(CMM_LOG_DEBUG,
"conn: no route for reply direction");
return (-1);
}
/* Re-attempt neighbor resolution if needed */
if (conn->orig_route->neigh == NULL)
conn->orig_route->neigh = cmm_neigh_get(g,
conn->orig_route->family,
conn->orig_route->gw,
conn->orig_route->oif_index);
if (conn->rep_route->neigh == NULL)
conn->rep_route->neigh = cmm_neigh_get(g,
conn->rep_route->family,
conn->rep_route->gw,
conn->rep_route->oif_index);
/* Both routes need resolved neighbors */
if (conn->orig_route->neigh == NULL ||
conn->orig_route->neigh->state != NEIGH_RESOLVED) {
cmm_print(CMM_LOG_DEBUG,
"conn: orig neighbor not resolved");
return (-1);
}
if (conn->rep_route->neigh == NULL ||
conn->rep_route->neigh->state != NEIGH_RESOLVED) {
if (conn->af == AF_INET) {
char sb[INET_ADDRSTRLEN], db[INET_ADDRSTRLEN];
inet_ntop(AF_INET, conn->orig_saddr,
sb, sizeof(sb));
inet_ntop(AF_INET, conn->orig_daddr,
db, sizeof(db));
cmm_print(CMM_LOG_DEBUG,
"conn: reply neighbor not resolved "
"proto=%u %s->%s rep_oif=%d",
conn->proto, sb, db,
conn->rep_route->oif_index);
} else {
cmm_print(CMM_LOG_DEBUG,
"conn: reply neighbor not resolved "
"rep_oif=%d",
conn->rep_route->oif_index);
}
return (-1);
}
/*
* The hardware forwards by the main routing table. pf must have sent
* the flow the same way: out where the original direction's route
* leaves, and back in where the reply's route leaves. Anything else
* (policy routing, a bridge member filtered by pf) stays on the
* software path.
*/
if (!route_leaves_by(conn->orig_route, conn->st[CONN_ST_OUT].ifname) ||
!route_leaves_by(conn->rep_route, conn->st[CONN_ST_IN].ifname)) {
cmm_print(CMM_LOG_DEBUG,
"conn: pf states on %s/%s, routes elsewhere: not offloaded",
conn->st[CONN_ST_IN].ifname, conn->st[CONN_ST_OUT].ifname);
return (-1);
}
/*
* A route-to (packets in the state's direction: the original one) or
* reply-to (the reply) is offloaded only while the routing table sends
* those packets to the same interface and next hop. OPNsense puts both
* on its automatic rules (force gateway, reply-to on WAN). When a
* route changes, cmm_route_handle_change() tears the flow down and it
* comes back here.
*/
for (i = 0; i < 2; i++) {
const struct cmm_route *rt;
char nh[INET6_ADDRSTRLEN];
if (conn->st[i].rt == PFN_RT_NONE)
continue;
rt = (conn->st[i].rt == PFN_RT_ROUTETO) ?
conn->orig_route : conn->rep_route;
if (route_sends_to(rt, conn->st[i].rt_ifname,
conn->st[i].rt_addr))
continue;
if (inet_ntop(conn->af, conn->st[i].rt_addr, nh,
sizeof(nh)) == NULL)
strlcpy(nh, "?", sizeof(nh));
cmm_print(CMM_LOG_DEBUG,
"conn: %s (%s %s) differs from the routing table: "
"not offloaded",
conn->st[i].rt == PFN_RT_ROUTETO ? "route-to" : "reply-to",
conn->st[i].rt_ifname, nh);
return (-1);
}
/*
* Set input interface for each route: the input for one direction
* is the output of the opposite direction. CDX needs this to
* install flow classification entries on the correct FMan RX port.
*/
conn->orig_route->iif_index = resolve_iif_index(conn->rep_route);
conn->rep_route->iif_index = resolve_iif_index(conn->orig_route);
/* Send routes to CDX (idempotent if already programmed) */
if (!conn->orig_route->fpp_programmed && !conn->orig_route->fpp_rejected)
cmm_fe_route_register(g, conn->orig_route);
if (!conn->rep_route->fpp_programmed && !conn->rep_route->fpp_rejected)
cmm_fe_route_register(g, conn->rep_route);
if (!conn->orig_route->fpp_programmed ||
!conn->rep_route->fpp_programmed) {
cmm_print(CMM_LOG_DEBUG,
"conn: route FPP registration failed");
return (-1);
}
/* Enable both directions */
conn->flags |= CONN_F_ORIG_DIR | CONN_F_REP_DIR;
/* Send conntrack to CDX */
{
int rc;
if (conn->af == AF_INET)
rc = cmm_fe_ct4_register(g, conn);
else
rc = cmm_fe_ct6_register(g, conn);
if (rc == 0) {
conn_offloaded++;
conn_report_offloaded(g, conn);
}
return (rc);
}
}
int
cmm_conn_init(void)
{
int i;
for (i = 0; i < CONN_HASH_SIZE; i++)
list_head_init(&conn_hash[i]);
return (0);
}
void
cmm_conn_fini(struct cmm_global *g)
{
struct cmm_conn *conn;
struct list_head *pos, *tmp;
int i;
for (i = 0; i < CONN_HASH_SIZE; i++) {
pos = list_first(&conn_hash[i]);
while (pos != &conn_hash[i]) {
tmp = list_next(pos);
conn = container_of(pos, struct cmm_conn, hash_entry);
conn_remove(g, conn);
pos = tmp;
}
}
}
void
cmm_conn_deregister_all(struct cmm_global *g)
{
struct cmm_conn *conn;
struct list_head *pos;
int i;
for (i = 0; i < CONN_HASH_SIZE; i++) {
for (pos = list_first(&conn_hash[i]);
pos != &conn_hash[i]; pos = list_next(pos)) {
conn = container_of(pos, struct cmm_conn, hash_entry);
if (conn->flags & CONN_F_OFFLOADED) {
if (conn->af == AF_INET)
cmm_fe_ct4_deregister(g, conn);
else
cmm_fe_ct6_deregister(g, conn);
}
}
}
}
/*
* Deregister all connections using the given route from CDX, and clear
* their route pointers. Called when a route changes so that affected
* connections will re-resolve and re-offload on the next poll cycle.
*/
void
cmm_route_invalidate_conns(struct cmm_global *g, struct cmm_route *rt)
{
struct cmm_conn *conn;
struct list_head *pos;
int i;
for (i = 0; i < CONN_HASH_SIZE; i++) {
for (pos = list_first(&conn_hash[i]);
pos != &conn_hash[i]; pos = list_next(pos)) {
conn = container_of(pos, struct cmm_conn, hash_entry);
if (conn->orig_route != rt && conn->rep_route != rt)
continue;
/* Deregister from CDX */
if (conn->flags & CONN_F_OFFLOADED) {
if (conn->af == AF_INET)
cmm_fe_ct4_deregister(g, conn);
else
cmm_fe_ct6_deregister(g, conn);
conn->flags &= ~CONN_F_OFFLOADED;
if (conn_offloaded > 0)
conn_offloaded--;
}
/* Clear route pointers — next poll re-resolves */
if (conn->orig_route != NULL) {
cmm_route_put(conn->orig_route);
conn->orig_route = NULL;
}
if (conn->rep_route != NULL) {
cmm_route_put(conn->rep_route);
conn->rep_route = NULL;
}
}
}
}
/*
* Full offload state reset: wipe all CDX tables, then clean up local
* state. Connections remain in the hash table — they will re-resolve
* routes and re-offload on the next poll/event cycle.
*
* Uses cmm_fe_reset() (FPP_CMD_IPVx_RESET) for a guaranteed bulk
* wipe of CDX conntracks and routes. Per-connection deregister is
* unreliable when reply tuples have diverged from CDX's stored state
* (e.g. after NAT address change).
*
* Called on interface reassignment (RTM_NEWADDR / RTM_DELADDR) where
* the routing topology has fundamentally changed.
*/
void
cmm_reset_offload_state(struct cmm_global *g)
{
struct cmm_conn *conn;
struct list_head *pos;
int i;
cmm_print(CMM_LOG_INFO,
"conn: full offload reset (interface reassignment)");
/* 1. Wipe all CDX conntracks + routes in one shot */
cmm_fe_reset(g);
/* 2. Clear local offload flags and route references */
for (i = 0; i < CONN_HASH_SIZE; i++) {
for (pos = list_first(&conn_hash[i]);
pos != &conn_hash[i]; pos = list_next(pos)) {
conn = container_of(pos, struct cmm_conn, hash_entry);
conn->flags &= ~CONN_F_OFFLOADED;
if (conn->orig_route != NULL) {
cmm_route_put(conn->orig_route);
conn->orig_route = NULL;
}
if (conn->rep_route != NULL) {
cmm_route_put(conn->rep_route);
conn->rep_route = NULL;
}
}
}
conn_offloaded = 0;
/* 3. Free local route cache (CDX already wiped — skip deregister) */
cmm_route_flush_all_local();
/* 4. Mark all neighbors stale (forces re-resolution) */
cmm_neigh_flush_all();
}
/* --- Push-based event handling ------------------------------------ */
/*
* Find a connection by either of its PF state IDs.
* Linear scan is acceptable because DELETE events fire once per
* PF state lifetime.
*/
static struct cmm_conn *
conn_find_by_pfid(uint64_t id, uint32_t creatorid)
{
struct list_head *pos;
struct cmm_conn *conn;
int i;
for (i = 0; i < CONN_HASH_SIZE; i++) {
for (pos = list_first(&conn_hash[i]);
pos != &conn_hash[i]; pos = list_next(pos)) {
conn = container_of(pos, struct cmm_conn,
hash_entry);
if ((conn->st[CONN_ST_IN].seen &&
conn->st[CONN_ST_IN].id == id &&
conn->st[CONN_ST_IN].creatorid == creatorid) ||
(conn->st[CONN_ST_OUT].seen &&
conn->st[CONN_ST_OUT].id == id &&
conn->st[CONN_ST_OUT].creatorid == creatorid))
return (conn);
}
}
return (NULL);
}
/*
* Extract connection tuples from a pfn_event.
* Same logic as conn_extract_tuples() but reads from pfn_event.
*/
static void
pfn_extract_tuples(struct cmm_conn *conn, const struct pfn_event *ev)
{
int sidx, didx, alen;
conn->af = ev->key[0].af;
conn->proto = ev->key[0].proto;
alen = (conn->af == AF_INET) ? 4 : 16;
sidx = (ev->direction == PF_IN) ? 0 : 1;
didx = (ev->direction == PF_IN) ? 1 : 0;
/* Original direction: STACK key (index 1) */
memcpy(conn->orig_saddr, ev->key[1].addr[sidx], alen);
memcpy(conn->orig_daddr, ev->key[1].addr[didx], alen);
conn->orig_sport = ev->key[1].port[sidx];
conn->orig_dport = ev->key[1].port[didx];
/* Reply direction: WIRE key (index 0), reversed */
memcpy(conn->rep_saddr, ev->key[0].addr[didx], alen);
memcpy(conn->rep_daddr, ev->key[0].addr[sidx], alen);
conn->rep_sport = ev->key[0].port[didx];
conn->rep_dport = ev->key[0].port[sidx];
}
/*
* Check basic offload eligibility from pfn_event fields.
*/
static int
pfn_event_eligible(const struct pfn_event *ev)
{
uint8_t proto;
sa_family_t af;
int didx;
proto = ev->key[0].proto;
af = ev->key[0].af;
if (proto != IPPROTO_TCP && proto != IPPROTO_UDP)
return (0);
if (af != AF_INET && af != AF_INET6)
return (0);
if (strncmp(ev->ifname, "lo", 2) == 0)
return (0);
/* TCP: require ESTABLISHED, not in FIN states */
if (proto == IPPROTO_TCP) {
if (ev->src_state < TCPS_ESTABLISHED ||
ev->dst_state < TCPS_ESTABLISHED)
return (0);
if (ev->src_state >= TCPS_FIN_WAIT_1 ||
ev->dst_state >= TCPS_FIN_WAIT_1)
return (0);
}
/* UDP: require bidirectional traffic */
if (proto == IPPROTO_UDP) {
if (ev->src_state == 0 || ev->dst_state == 0)
return (0);
}
/* Skip multicast destinations (stack key) */
didx = (ev->direction == PF_IN) ? 1 : 0;
if (af == AF_INET) {
uint32_t daddr;
memcpy(&daddr, ev->key[1].addr[didx], 4);
if (IN_MULTICAST(ntohl(daddr)))
return (0);
} else {
if (IN6_IS_ADDR_MULTICAST(
(const struct in6_addr *)ev->key[1].addr[didx]))
return (0);
}
/* Skip local addresses (stack key, both endpoints) */
if (af == AF_INET) {
if (cmm_itf_is_local_addr(AF_INET,
ev->key[1].addr[0]) ||
cmm_itf_is_local_addr(AF_INET,
ev->key[1].addr[1]))
return (0);
} else {
if (cmm_itf_is_local_addr(AF_INET6,
ev->key[1].addr[0]) ||
cmm_itf_is_local_addr(AF_INET6,
ev->key[1].addr[1]))
return (0);
}
return (1);
}
/* Keep conn on the software path: take it out of the hardware if it is in */
static void
conn_veto(struct cmm_global *g, struct cmm_conn *conn, const char *why)
{
if (!(conn->flags & CONN_F_VETO))
cmm_print(CMM_LOG_DEBUG, "conn: proto=%u not offloaded: %s",
conn->proto, why);
if (conn->flags & CONN_F_OFFLOADED) {
if (conn->af == AF_INET)
cmm_fe_ct4_deregister(g, conn);
else
cmm_fe_ct6_deregister(g, conn);
conn->flags &= ~CONN_F_OFFLOADED;
if (conn_offloaded > 0)
conn_offloaded--;
}
conn->flags |= CONN_F_VETO;
}
/*
* Handle a READY event (a pf state became offload-ready). Each of the
* flow's two states reports READY; the flow is offloaded once both have.
*/
static void
handle_pf_ready(struct cmm_global *g, const struct pfn_event *ev)
{
struct cmm_conn *conn;
int sidx, didx, alen, is_nat, slot;
uint8_t osaddr[16], odaddr[16];
uint16_t osport, odport;
sa_family_t af;
uint8_t proto;
if (!pfn_event_eligible(ev))
return;
proto = ev->key[0].proto;
af = ev->key[0].af;
sidx = (ev->direction == PF_IN) ? 0 : 1;
didx = (ev->direction == PF_IN) ? 1 : 0;
alen = (af == AF_INET) ? 4 : 16;
is_nat = memcmp(&ev->key[0], &ev->key[1],
sizeof(struct pfn_state_key)) != 0;
slot = (ev->direction == PF_IN) ? CONN_ST_IN : CONN_ST_OUT;
/* Extract original 5-tuple from STACK key */
memset(osaddr, 0, sizeof(osaddr));
memset(odaddr, 0, sizeof(odaddr));
memcpy(osaddr, ev->key[1].addr[sidx], alen);
memcpy(odaddr, ev->key[1].addr[didx], alen);
osport = ev->key[1].port[sidx];
odport = ev->key[1].port[didx];
/* Check deny rules */
if (cmm_deny_check_tuple(af, proto, osaddr, odaddr,
osport, odport, ev->ifname))
return;
conn = conn_find_5tuple(af, proto, osaddr, odaddr, osport, odport);
if (conn == NULL) {
if (conn_count >= CMM_CONN_MAX)
return;
conn = calloc(1, sizeof(*conn));
if (conn == NULL)
return;
pfn_extract_tuples(conn, ev);
if (is_nat)
conn->flags |= CONN_F_HAS_NAT;
{
unsigned int h;
h = conn_hash_5tuple(conn->af, conn->proto,
conn->orig_saddr, conn->orig_daddr,
conn->orig_sport, conn->orig_dport);
list_add(&conn_hash[h], &conn->hash_entry);
conn_count++;
}
} else if (is_nat && !(conn->flags & CONN_F_HAS_NAT)) {
/* The NAT state arrived second: its wire key gives the
reply tuples the hardware must match */
if (conn->flags & CONN_F_OFFLOADED) {
if (conn->af == AF_INET)
cmm_fe_ct4_deregister(g, conn);
else
cmm_fe_ct6_deregister(g, conn);
conn->flags &= ~CONN_F_OFFLOADED;
if (conn_offloaded > 0)
conn_offloaded--;
}
memcpy(conn->rep_saddr, ev->key[0].addr[didx], alen);
memcpy(conn->rep_daddr, ev->key[0].addr[sidx], alen);
conn->rep_sport = ev->key[0].port[didx];
conn->rep_dport = ev->key[0].port[sidx];
if (conn->rep_route != NULL) {
cmm_route_put(conn->rep_route);
conn->rep_route = NULL;
}
conn->flags |= CONN_F_HAS_NAT;
}
if (conn->st[slot].seen && (conn->st[slot].id != ev->id ||
conn->st[slot].creatorid != ev->creatorid)) {
/* a third pf state for one flow: not a shape we know */
conn_veto(g, conn, "more than one pf state per direction");
return;
}
conn->st[slot].id = ev->id;
conn->st[slot].creatorid = ev->creatorid;
conn->st[slot].veto = ev->veto;
conn->st[slot].seen = 1;
strlcpy(conn->st[slot].ifname, ev->ifname,
sizeof(conn->st[slot].ifname));
conn->st[slot].rt = ev->rt;
strlcpy(conn->st[slot].rt_ifname, ev->rt_ifname,
sizeof(conn->st[slot].rt_ifname));
memcpy(conn->st[slot].rt_addr, ev->rt_addr,
sizeof(conn->st[slot].rt_addr));
if (ev->veto != 0) {
conn_veto(g, conn, "pf rules need the software path");
return;
}
if (!(conn->flags & CONN_F_OFFLOADED) && conn_try_offload(g, conn) < 0)
cmm_print(CMM_LOG_DEBUG,
"conn: offload deferred (states/route/neigh pending)");
}
/*
* Handle a DELETE event (PF state removed).
*/
static void
handle_pf_delete(struct cmm_global *g, const struct pfn_event *ev)
{
struct cmm_conn *conn;
conn = conn_find_by_pfid(ev->id, ev->creatorid);
if (conn == NULL) {
cmm_print(CMM_LOG_TRACE,
"conn: DELETE for unknown id=%016llx",
(unsigned long long)ev->id);
return;
}
cmm_print(CMM_LOG_DEBUG, "conn: DELETE proto=%u%s (push)",
conn->proto,
(conn->flags & CONN_F_HAS_NAT) ? " NAT" : "");
conn_remove(g, conn);
}
/*
* Handle push-based events from /dev/pfnotify.
* Drain loop reads all available events.
*/
void
cmm_conn_event(struct cmm_global *g)
{
struct pfn_event ev;
ssize_t n;
for (;;) {
n = read(g->pfnotify_fd, &ev, sizeof(ev));
if (n != (ssize_t)sizeof(ev)) {
if (n < 0 && (errno == EAGAIN ||
errno == EWOULDBLOCK))
break;
if (n == 0) {
cmm_print(CMM_LOG_WARN,
"conn: /dev/pfnotify closed");
break;
}
cmm_print(CMM_LOG_WARN,
"conn: short pfnotify read: %zd", n);
break;
}
switch (ev.type) {
case PFN_EVENT_INSERT:
/*
* Log only. Most TCP states are SYN_SENT
* at insert time — wait for READY. If the
* state is already ready (pfsync import),
* the kernel will also fire a READY event.
*/
cmm_print(CMM_LOG_TRACE,
"conn: INSERT id=%016llx proto=%u",
(unsigned long long)ev.id,
ev.key[0].proto);
break;
case PFN_EVENT_READY:
handle_pf_ready(g, &ev);
break;
case PFN_EVENT_DELETE:
handle_pf_delete(g, &ev);
break;
case PFN_EVENT_RESYNC:
/*
* pf_notify lost a DELETE: some hardware flow may
* belong to a state pf has removed. Wipe the hardware
* and forget every flow; each live state reports
* READY again on its next packet.
*/
cmm_print(CMM_LOG_WARN,
"conn: pf_notify lost events, resetting offload");
cmm_reset_offload_state(g);
cmm_conn_fini(g);
break;
default:
cmm_print(CMM_LOG_WARN,
"conn: unknown pfnotify event %u",
ev.type);
break;
}
}
}
/*
* Periodic maintenance: retry offload for connections that are
* tracked but not yet offloaded (e.g., after interface reassignment
* or route change), garbage-collect unreferenced routes, and log stats.
*/
void
cmm_conn_maintenance(struct cmm_global *g)
{
struct cmm_conn *conn;
struct list_head *pos;
int i;
unsigned int retried = 0;
/* First drop flows whose next hop moved to another MAC: the retry
below offloads them again with the new one */
cmm_route_check_neighbors(g);
for (i = 0; i < CONN_HASH_SIZE; i++) {
for (pos = list_first(&conn_hash[i]);
pos != &conn_hash[i]; pos = list_next(pos)) {
conn = container_of(pos, struct cmm_conn,
hash_entry);
if (!(conn->flags & CONN_F_OFFLOADED)) {
if (conn_try_offload(g, conn) == 0)
retried++;
}
}
}
if (retried > 0)
cmm_print(CMM_LOG_INFO,
"conn: maintenance re-offloaded %u flows", retried);
/* Free unreferenced routes */
cmm_route_gc(g);
cmm_print(CMM_LOG_INFO, "conn: %u tracked, %u offloaded",
conn_count, conn_offloaded);
}
/* --- CDX flow counter sync to PF state table --------------------- */
/*
* Flush a batch of counter entries to pf_notify via ioctl.
*/
static void
stats_sync_flush(struct cmm_global *g, struct pfn_counter_entry *entries,
uint32_t count)
{
struct pfn_counter_update upd;
if (count == 0)
return;
upd.count = count;
upd.pad = 0;
upd.entries = entries;
if (ioctl(g->pfnotify_fd, PFN_IOC_UPDATE_COUNTERS, &upd) < 0)
cmm_print(CMM_LOG_WARN, "stats_sync: ioctl failed: %s",
strerror(errno));
}
void
cmm_conn_stats_sync(struct cmm_global *g)
{
struct pfn_counter_entry batch[PFN_COUNTER_BATCH_MAX];
fpp_stat_flow_status_cmd_t cmd;
fpp_stat_flow_entry_response_t resp;
unsigned short resp_len;
struct cmm_conn *conn;
struct list_head *pos;
uint32_t n;
int i, rc;
if (g->pfnotify_fd < 0)
return;
n = 0;
for (i = 0; i < CONN_HASH_SIZE; i++) {
for (pos = list_first(&conn_hash[i]);
pos != &conn_hash[i]; pos = list_next(pos)) {
conn = container_of(pos, struct cmm_conn, hash_entry);
if (!(conn->flags & CONN_F_OFFLOADED))
continue;
/* Build stat query for this flow's original 5-tuple */
memset(&cmd, 0, sizeof(cmd));
cmd.action = FPP_CMM_STAT_QUERY_RESET;
cmd.ip_family = (conn->af == AF_INET) ? 4 : 6;
cmd.Protocol = conn->proto;
cmd.Sport = conn->orig_sport;
cmd.Dport = conn->orig_dport;
if (conn->af == AF_INET) {
memcpy(&cmd.Saddr, conn->orig_saddr, 4);
memcpy(&cmd.Daddr, conn->orig_daddr, 4);
} else {
memcpy(cmd.Saddr_v6, conn->orig_saddr, 16);
memcpy(cmd.Daddr_v6, conn->orig_daddr, 16);
}
resp_len = sizeof(resp);
rc = fci_cmd(g->fci_handle, FPP_CMD_STAT_FLOW,
(unsigned short *)&cmd, sizeof(cmd),
(unsigned short *)&resp, &resp_len);
if (rc != 0)
continue;
if (resp.TotalPackets == 0 && resp.TotalBytes == 0)
continue;
/* Both of the flow's pf states (offloaded flows have
both) */
{
int k;
for (k = 0; k < 2; k++) {
if (n >= PFN_COUNTER_BATCH_MAX) {
stats_sync_flush(g, batch, n);
n = 0;
}
memset(&batch[n], 0, sizeof(batch[n]));
batch[n].id = conn->st[k].id;
batch[n].creatorid = conn->st[k].creatorid;
batch[n].packets[0] = resp.TotalPackets;
batch[n].bytes[0] = resp.TotalBytes;
n++;
}
}
}
}
/* Flush remaining */
stats_sync_flush(g, batch, n);
cmm_print(CMM_LOG_TRACE, "stats sync done");
}
/* --- FCI async event handling (CDX conntrack timeout) ------------- */
/*
* Handle CDX conntrack timeout/FIN notifications.
*
* When CDX's timer wheel ages out a flow (idle > timeout) or detects
* TCP FIN, it removes the flow from the FMan hash table and sends
* CMD_IPV4_CONNTRACK_CHANGE or CMD_IPV6_CONNTRACK_CHANGE via FCI.
*
* We clear CONN_F_OFFLOADED so the next poll/event cycle can
* re-offload if the PF state is still alive. We do NOT call
* cmm_fe_ct*_deregister() because CDX already removed the flow.
*/
int
cmm_conn_fci_event(unsigned short fcode, unsigned short len,
unsigned short *payload)
{
struct cmm_conn *conn;
const char *reason;
if (fcode == FPP_CMD_IPV4_CONNTRACK_CHANGE) {
fpp_ct_cmd_t *cmd;
if (len < sizeof(*cmd))
return (FCI_CB_CONTINUE);
cmd = (fpp_ct_cmd_t *)payload;
if (cmd->action != FPP_ACTION_REMOVED &&
cmd->action != FPP_ACTION_TCP_FIN)
return (FCI_CB_CONTINUE);
reason = (cmd->action == FPP_ACTION_TCP_FIN) ?
"tcp_fin" : "timeout";
conn = conn_find_5tuple(AF_INET, cmd->protocol,
&cmd->saddr, &cmd->daddr,
cmd->sport, cmd->dport);
if (conn == NULL) {
cmm_print(CMM_LOG_DEBUG,
"conn: CDX removed unknown IPv4 flow (%s)",
reason);
return (FCI_CB_CONTINUE);
}
if (conn->flags & CONN_F_OFFLOADED) {
conn->flags &= ~CONN_F_OFFLOADED;
if (conn_offloaded > 0)
conn_offloaded--;
cmm_print(CMM_LOG_INFO,
"conn: CDX removed IPv4 proto=%u (%s)"
" — will re-offload if PF state alive",
conn->proto, reason);
}
return (FCI_CB_CONTINUE);
}
if (fcode == FPP_CMD_IPV6_CONNTRACK_CHANGE) {
fpp_ct6_cmd_t *cmd;
if (len < sizeof(*cmd))
return (FCI_CB_CONTINUE);
cmd = (fpp_ct6_cmd_t *)payload;
if (cmd->action != FPP_ACTION_REMOVED &&
cmd->action != FPP_ACTION_TCP_FIN)
return (FCI_CB_CONTINUE);
reason = (cmd->action == FPP_ACTION_TCP_FIN) ?
"tcp_fin" : "timeout";
conn = conn_find_5tuple(AF_INET6, cmd->protocol,
cmd->saddr, cmd->daddr,
cmd->sport, cmd->dport);
if (conn == NULL) {
cmm_print(CMM_LOG_DEBUG,
"conn: CDX removed unknown IPv6 flow (%s)",
reason);
return (FCI_CB_CONTINUE);
}
if (conn->flags & CONN_F_OFFLOADED) {
conn->flags &= ~CONN_F_OFFLOADED;
if (conn_offloaded > 0)
conn_offloaded--;
cmm_print(CMM_LOG_INFO,
"conn: CDX removed IPv6 proto=%u (%s)"
" — will re-offload if PF state alive",
conn->proto, reason);
}
return (FCI_CB_CONTINUE);
}
return (FCI_CB_CONTINUE);
}