Offload: keep flows pf must see on the software path (audit V1-V5)

pf_notify (kernel):
- V1: every event carries a veto mask: route-to/reply-to/dup-to, policy
  routing (rtable), dummynet and ALTQ (shaper, limiters), log all and
  pflow, scrub/set-tos/set-prio/max-mss. Hardware forwarding takes the
  main routing table and skips all of it.
- V3: states are no longer all made sloppy at insert. CMM reports the
  states it puts into hardware (PFN_IOC_OFFLOADED); only those are.
- V5: a DELETE that cannot be queued discards the ring and makes the
  next read a RESYNC; INSERT and READY leave room for DELETEs. Counter
  updates refresh a state's expiry only when packets moved, so an idle
  offloaded flow expires and is removed.

cmm:
- A flow keeps both of its pf states (in, out). It is offloaded only
  with both seen, neither vetoed, and pf's interfaces matching the
  routes the hardware will use, which also catches route-to and policy
  routing structurally. A DELETE of either state removes it (the NAT
  companion's DELETE was ignored when it arrived first). A third state
  for one flow keeps it on the software path.
- RESYNC wipes CDX and forgets every flow; READY rebuilds them.
- V4: bridge flows are refused while pf filters bridged traffic
  (net.link.bridge.pfil_member or pfil_bridge).
- V2: cdx is built without DPA_IPSEC_OFFLOAD and cmm opens no PF_KEY
  socket; a stub answers the SA lookups the conntrack code makes.

Builds clean against the 26.7.9 kernel; not yet tested on hardware.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jeremy Karst 2026-11-27 22:16:06 -05:00
parent fb138079b7
commit 96a812fa5b
8 changed files with 487 additions and 167 deletions

View file

@ -41,7 +41,9 @@ CFLAGS+= -I${FASTPATH_ROOT}/vendor/cdx
CFLAGS+= -DENABLE_EGRESS_QOS
CFLAGS+= -DDPAA_FAST_PATH
CFLAGS+= -DENABLE_FLOW_TIME_STAMPS
CFLAGS+= -DDPA_IPSEC_OFFLOAD
# No IPsec offload (DPA_IPSEC_OFFLOAD): its exception path panics on most
# decrypted packet sizes, hands packets to the stack without a receive
# interface, and skips enc0 filtering (audit V2). cmm opens no PF_KEY socket.
CFLAGS+= -DWIFI_ENABLE
# NCSW build environment defines (replicate dflags_arm64.h without its

View file

@ -188,4 +188,19 @@ dpa_update_timestamp(uint32_t ts)
/* mc4_init, mc6_init, mc4_exit, mc6_exit moved to cdx_mc_freebsd.c */
/* M_ipsec_sa_cache_lookup_by_h — real implementation in control_ipsec.c */
/*
* M_ipsec_sa_cache_lookup_by_h — real implementation in control_ipsec.c,
* which builds only with DPA_IPSEC_OFFLOAD (off, see Makefile). Without it
* no SA is ever programmed, so none is found: conntracks that name an SA
* are refused by their callers.
*/
#ifndef DPA_IPSEC_OFFLOAD
void *M_ipsec_sa_cache_lookup_by_h(U16 handle); /* control_ipsec.h */
void *
M_ipsec_sa_cache_lookup_by_h(U16 handle __unused)
{
return (NULL);
}
#endif

View file

@ -307,11 +307,10 @@ main(int argc, char *argv[])
if (cmm_deny_init(deny_conf) < 0)
goto out;
/* Open PF_KEY socket for IPsec SA events */
g->pfkey_fd = cmm_pfkey_open();
if (g->pfkey_fd < 0)
cmm_print(CMM_LOG_WARN,
"PF_KEY unavailable — IPsec offload disabled");
/*
* No PF_KEY socket: IPsec SAs are not offloaded (cdx is built without
* DPA_IPSEC_OFFLOAD; see fastpath/cdx/Makefile). pfkey_fd stays -1.
*/
/* Open /dev/pfnotify — required for PF state events */
{

View file

@ -18,6 +18,7 @@
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/sysctl.h>
#include <sys/event.h>
#include <sys/socket.h>
#include <net/if.h>
@ -582,6 +583,43 @@ l2flow_flush_all(struct cmm_global *g)
}
}
/*
* Does pf filter bridged traffic? Then no bridge flow may be offloaded: the
* hardware would forward it between the ports without pf. If the sysctls
* cannot be read, assume it does.
*/
static int
bridge_pf_filters(void)
{
static const char *const names[] = {
"net.link.bridge.pfil_member", "net.link.bridge.pfil_bridge",
};
size_t i, len;
int val;
for (i = 0; i < sizeof(names) / sizeof(names[0]); i++) {
len = sizeof(val);
if (sysctlbyname(names[i], &val, &len, NULL, 0) != 0 ||
len != sizeof(val) || val != 0)
return (1);
}
return (0);
}
/* Refuse a bridge flow: drop any hardware entry it has */
static void
flow_deny(struct cmm_global *g, const struct abm_event *ev)
{
struct cmm_l2flow *entry;
entry = l2flow_find(&ev->flow);
if (entry != NULL) {
l2flow_fpp_deregister(g, entry);
l2flow_del(entry);
}
autobridge_respond(&ev->flow, ABM_FLAG_DENIED | ABM_FLAG_ACK);
}
/*
* Handle a FLOW_NEW event from auto_bridge.
*/
@ -591,6 +629,11 @@ handle_flow_new(struct cmm_global *g, const struct abm_event *ev)
struct cmm_l2flow *entry;
struct cmm_interface *iif, *oif;
if (bridge_pf_filters()) {
flow_deny(g, ev);
return;
}
/* Resolve interface indexes to names */
iif = cmm_itf_find_by_index(ev->iif_index);
oif = cmm_itf_find_by_index(ev->oif_index);
@ -657,8 +700,8 @@ handle_flow_update(struct cmm_global *g, const struct abm_event *ev)
struct cmm_interface *iif, *oif;
entry = l2flow_find(&ev->flow);
if (entry == NULL) {
/* Treat as new */
if (entry == NULL || bridge_pf_filters()) {
/* Treat as new (which also refuses it while pf filters) */
handle_flow_new(g, ev);
return;
}

View file

@ -184,9 +184,52 @@ resolve_iif_index(struct cmm_route *opp_route)
*
* 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);
}
/*
* 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)
{
/*
* 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,
@ -258,6 +301,21 @@ conn_try_offload(struct cmm_global *g, struct cmm_conn *conn)
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
* (route-to, 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);
}
/*
* Set input interface for each route: the input for one direction
* is the output of the opposite direction. CDX needs this to
@ -290,8 +348,10 @@ conn_try_offload(struct cmm_global *g, struct cmm_conn *conn)
rc = cmm_fe_ct4_register(g, conn);
else
rc = cmm_fe_ct6_register(g, conn);
if (rc == 0)
if (rc == 0) {
conn_offloaded++;
conn_report_offloaded(g, conn);
}
return (rc);
}
}
@ -443,9 +503,9 @@ cmm_reset_offload_state(struct cmm_global *g)
/* --- Push-based event handling ------------------------------------ */
/*
* Find a connection by PF state ID.
* Find a connection by either of its PF state IDs.
* Linear scan is acceptable because DELETE events fire once per
* connection lifetime.
* PF state lifetime.
*/
static struct cmm_conn *
conn_find_by_pfid(uint64_t id, uint32_t creatorid)
@ -459,8 +519,12 @@ conn_find_by_pfid(uint64_t id, uint32_t creatorid)
pos != &conn_hash[i]; pos = list_next(pos)) {
conn = container_of(pos, struct cmm_conn,
hash_entry);
if (conn->pf_id == id &&
conn->pf_creatorid == creatorid)
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);
}
}
@ -564,15 +628,35 @@ pfn_event_eligible(const struct pfn_event *ev)
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 (state became offload-ready).
* Creates or updates cmm_conn and attempts offload.
* 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;
int sidx, didx, alen, is_nat, slot;
uint8_t osaddr[16], odaddr[16];
uint16_t osport, odport;
sa_family_t af;
@ -588,6 +672,7 @@ handle_pf_ready(struct cmm_global *g, const struct pfn_event *ev)
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));
@ -603,81 +688,68 @@ handle_pf_ready(struct cmm_global *g, const struct pfn_event *ev)
return;
conn = conn_find_5tuple(af, proto, osaddr, odaddr, osport, odport);
if (conn != NULL) {
/* Existing connection — handle NAT upgrade */
if (is_nat && !(conn->flags & CONN_F_HAS_NAT)) {
cmm_print(CMM_LOG_INFO,
"conn: NAT upgrade from push event");
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--;
}
/* Update reply tuples from wire key */
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;
}
/* Save NAT companion PF state ID */
conn->pf_id_nat = ev->id;
conn->pf_creatorid_nat = ev->creatorid;
conn->pf_has_nat_id = 1;
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;
}
if (!(conn->flags & CONN_F_OFFLOADED))
conn_try_offload(g, conn);
return;
}
/* New connection */
if (conn_count >= CMM_CONN_MAX)
return;
conn = calloc(1, sizeof(*conn));
if (conn == NULL)
return;
pfn_extract_tuples(conn, ev);
conn->pf_id = ev->id;
conn->pf_creatorid = ev->creatorid;
conn->pf_direction = ev->direction;
strlcpy(conn->ifname, ev->ifname, sizeof(conn->ifname));
conn->hash_entry.next = NULL;
conn->hash_entry.prev = NULL;
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++;
}
if (conn_try_offload(g, conn) < 0) {
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));
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 (route/neigh pending)");
}
"conn: offload deferred (states/route/neigh pending)");
}
/*
@ -751,6 +823,19 @@ cmm_conn_event(struct cmm_global *g)
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",
@ -869,30 +954,23 @@ cmm_conn_stats_sync(struct cmm_global *g)
if (resp.TotalPackets == 0 && resp.TotalBytes == 0)
continue;
/* Primary PF state */
memset(&batch[n], 0, sizeof(batch[n]));
batch[n].id = conn->pf_id;
batch[n].creatorid = conn->pf_creatorid;
batch[n].packets[0] = resp.TotalPackets;
batch[n].bytes[0] = resp.TotalBytes;
n++;
/* Both of the flow's pf states (offloaded flows have
both) */
{
int k;
/* NAT companion PF state (if present) */
if (conn->pf_has_nat_id) {
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->pf_id_nat;
batch[n].creatorid = conn->pf_creatorid_nat;
batch[n].packets[0] = resp.TotalPackets;
batch[n].bytes[0] = resp.TotalBytes;
n++;
}
if (n >= PFN_COUNTER_BATCH_MAX) {
stats_sync_flush(g, batch, n);
n = 0;
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++;
}
}
}
}

View file

@ -21,6 +21,12 @@
#define CONN_F_ORIG_DIR 0x02 /* offload original direction */
#define CONN_F_REP_DIR 0x04 /* offload reply direction */
#define CONN_F_HAS_NAT 0x08 /* reply tuples from PF_OUT (NAT) */
#define CONN_F_VETO 0x10 /* stays on the software path (pf_notify
veto, or more than two pf states) */
/* conn->st[] slots: the pf state on the way in, and on the way out */
#define CONN_ST_IN 0
#define CONN_ST_OUT 1
struct cmm_conn {
struct list_head hash_entry; /* hash by original 5-tuple */
@ -39,17 +45,19 @@ struct cmm_conn {
uint16_t rep_sport;
uint16_t rep_dport;
/* PF tracking */
uint64_t pf_id;
uint32_t pf_creatorid;
uint8_t pf_direction;
/* NAT companion PF state (PF_OUT state for NAT connections) */
uint64_t pf_id_nat;
uint32_t pf_creatorid_nat;
uint8_t pf_has_nat_id;
char ifname[IFNAMSIZ];
/*
* The flow's pf states: a forwarded flow has one on its way in (on the
* ingress interface) and one on its way out (on the egress interface,
* with the NAT). Offload needs both, neither vetoed, and the egress
* the main routing table gives; a DELETE of either removes it.
*/
struct {
uint64_t id;
uint32_t creatorid;
uint16_t veto; /* PFN_VETO_* */
uint8_t seen;
char ifname[IFNAMSIZ];
} st[2]; /* CONN_ST_IN, CONN_ST_OUT */
/* Offload state */
int flags;

View file

@ -41,6 +41,9 @@
#define PFN_RING_SIZE 131072 /* must be power of 2 (128K entries) */
#define PFN_RING_MASK (PFN_RING_SIZE - 1)
/* INSERT and READY leave this much room, so a burst of them cannot crowd
out the DELETEs that remove hardware flows */
#define PFN_DELETE_RESERVE 4096
struct pfn_ring {
struct pfn_event *events; /* dynamically allocated */
@ -137,6 +140,7 @@ pfn_clear_notified(uint64_t id)
static struct mtx pfn_mtx;
static struct pfn_ring pfn_ring;
static int pfn_overflow; /* a DELETE was lost: RESYNC next */
static struct selinfo pfn_rsel;
static int pfn_open; /* only one client */
static struct cdev *pfn_cdev;
@ -144,6 +148,8 @@ static struct cdev *pfn_cdev;
/* Statistics */
static uint64_t pfn_events_total;
static uint64_t pfn_events_dropped;
static uint64_t pfn_resyncs;
static uint64_t pfn_offloaded;
static uint64_t pfn_counter_updates;
static uint64_t pfn_counter_misses;
@ -151,6 +157,34 @@ static struct sysctl_ctx_list pfn_sysctl_ctx;
/* --- Event construction ------------------------------------------- */
/*
* What in the state's rules keeps its flow on the software path: hardware
* forwarding takes the main routing table and skips everything pf_test()
* does per packet.
*/
static uint16_t
pfn_veto(const struct pf_kstate *s)
{
uint16_t veto = 0;
if (s->act.rt != PF_NOPFROUTE || s->act.rt_kif != NULL)
veto |= PFN_VETO_ROUTE;
if (s->act.rtableid >= 0)
veto |= PFN_VETO_RTABLE;
if (s->act.dnpipe != 0 || s->act.dnrpipe != 0 ||
(s->state_flags & (PFSTATE_DN_IS_PIPE | PFSTATE_DN_IS_QUEUE)))
veto |= PFN_VETO_SHAPER;
if (s->act.qid != 0 || s->act.pqid != 0)
veto |= PFN_VETO_QUEUE;
if ((s->act.log & PF_LOG_ALL) || (s->state_flags & PFSTATE_PFLOW))
veto |= PFN_VETO_LOG;
if ((s->state_flags & (PFSTATE_SCRUBMASK | PFSTATE_SETMASK)) ||
s->act.max_mss != 0 || s->act.min_ttl != 0 ||
s->act.max_pkt_size != 0 || s->act.set_tos != 0)
veto |= PFN_VETO_NORMALIZE;
return (veto);
}
static void
pfn_fill_event(struct pfn_event *ev, uint8_t type, struct pf_kstate *s)
{
@ -163,6 +197,7 @@ pfn_fill_event(struct pfn_event *ev, uint8_t type, struct pf_kstate *s)
ev->id = s->id;
ev->creatorid = s->creatorid;
ev->state_flags = s->state_flags;
ev->veto = pfn_veto(s);
strlcpy(ev->ifname, s->kif->pfik_name, sizeof(ev->ifname));
/* Wire key (PF_SK_WIRE = 0) */
@ -186,19 +221,63 @@ pfn_fill_event(struct pfn_event *ev, uint8_t type, struct pf_kstate *s)
ev->key[1].proto = s->key[PF_SK_STACK]->proto;
}
static void
pfn_wakeup_locked(void)
{
selwakeup(&pfn_rsel);
KNOTE_LOCKED(&pfn_rsel.si_note, 0);
wakeup(&pfn_ring);
}
/* INSERT and READY: dropped when the ring is nearly full (READY is retried
by the next packet, INSERT is informational) */
static int
pfn_ring_put_optional(const struct pfn_event *ev)
{
mtx_assert(&pfn_mtx, MA_OWNED);
if (pfn_overflow ||
ring_count(&pfn_ring) >= PFN_RING_SIZE - PFN_DELETE_RESERVE ||
ring_put(&pfn_ring, ev) != 0) {
pfn_events_dropped++;
return (ENOSPC);
}
pfn_events_total++;
pfn_wakeup_locked();
return (0);
}
static void
pfn_queue_event(struct pfn_event *ev)
{
mtx_lock(&pfn_mtx);
if (ring_put(&pfn_ring, ev) == 0) {
(void)pfn_ring_put_optional(ev);
mtx_unlock(&pfn_mtx);
}
/*
* DELETE must reach CMM, or the hardware keeps forwarding a flow pf has
* removed. If it cannot be queued, everything queued is discarded (a stale
* READY must not re-offload a dead state) and the reader gets RESYNC: CMM
* drops every hardware flow, and READY fires again for each live state.
*/
static void
pfn_queue_delete(struct pfn_event *ev)
{
mtx_lock(&pfn_mtx);
if (!pfn_overflow && ring_put(&pfn_ring, ev) == 0) {
pfn_events_total++;
selwakeup(&pfn_rsel);
KNOTE_LOCKED(&pfn_rsel.si_note, 0);
wakeup(&pfn_ring);
} else {
pfn_events_dropped++;
pfn_resyncs += !pfn_overflow;
pfn_overflow = 1;
pfn_ring.head = pfn_ring.tail = 0;
memset(pfn_notified, 0, PFN_NOTIFIED_SIZE * sizeof(uint64_t));
}
pfn_wakeup_locked();
mtx_unlock(&pfn_mtx);
}
@ -216,13 +295,8 @@ pfn_insert_state(struct pf_kstate *s)
if (!pfn_open)
return;
/* Mark state as sloppy so PF skips strict TCP sequence validation.
* When CDX offloads a flow, PF's seq tracking goes stale. During
* failover, packets return to PF — sloppy mode prevents PF from
* dropping them as "BAD state" due to out-of-window sequence.
* PFSTATE_SLOPPY is 0x0002 (netpfil/pf/pf.h). */
s->state_flags |= 0x0002;
/* Only offloaded states become sloppy (PFN_IOC_OFFLOADED), not every
state: sloppy turns off pf's TCP window checks. */
pfn_fill_event(&ev, PFN_EVENT_INSERT, s);
pfn_queue_event(&ev);
}
@ -281,15 +355,8 @@ pfn_update_state(struct pf_kstate *s)
mtx_unlock(&pfn_mtx);
return;
}
if (ring_put(&pfn_ring, &ev) == 0) {
if (pfn_ring_put_optional(&ev) == 0)
pfn_mark_notified(s->id);
pfn_events_total++;
selwakeup(&pfn_rsel);
KNOTE_LOCKED(&pfn_rsel.si_note, 0);
wakeup(&pfn_ring);
} else {
pfn_events_dropped++;
}
mtx_unlock(&pfn_mtx);
}
@ -310,7 +377,7 @@ pfn_delete_state(struct pf_kstate *s)
{
struct pfn_event ev;
pfn_fill_event(&ev, PFN_EVENT_DELETE, s);
pfn_queue_event(&ev);
pfn_queue_delete(&ev);
}
}
@ -327,9 +394,10 @@ pfn_dev_open(struct cdev *dev __unused, int oflags __unused,
return (EBUSY);
}
pfn_open = 1;
/* Reset ring on new open */
/* Reset ring on new open (CMM resets CDX when it starts) */
pfn_ring.head = 0;
pfn_ring.tail = 0;
pfn_overflow = 0;
memset(pfn_notified, 0, PFN_NOTIFIED_SIZE * sizeof(uint64_t));
mtx_unlock(&pfn_mtx);
return (0);
@ -356,7 +424,7 @@ pfn_dev_read(struct cdev *dev __unused, struct uio *uio, int ioflag)
return (EINVAL);
mtx_lock(&pfn_mtx);
while (ring_empty(&pfn_ring)) {
while (ring_empty(&pfn_ring) && !pfn_overflow) {
if (ioflag & FNONBLOCK) {
mtx_unlock(&pfn_mtx);
return (EAGAIN);
@ -368,6 +436,17 @@ pfn_dev_read(struct cdev *dev __unused, struct uio *uio, int ioflag)
}
}
if (pfn_overflow) {
pfn_overflow = 0;
mtx_unlock(&pfn_mtx);
memset(&ev, 0, sizeof(ev));
ev.type = PFN_EVENT_RESYNC;
error = uiomove(&ev, sizeof(ev), uio);
if (error)
return (error);
mtx_lock(&pfn_mtx);
}
/* Drain as many events as will fit */
while (uio->uio_resid >= (ssize_t)sizeof(ev) &&
ring_get(&pfn_ring, &ev) == 0) {
@ -382,24 +461,15 @@ pfn_dev_read(struct cdev *dev __unused, struct uio *uio, int ioflag)
return (0);
}
/* PFN_IOC_UPDATE_COUNTERS: add CDX's per-flow counters to the pf states */
static int
pfn_dev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data,
int fflag __unused, struct thread *td)
pfn_update_counters(struct pfn_counter_update *upd)
{
struct pfn_counter_update *upd;
struct pfn_counter_entry *entries;
struct pf_kstate *s;
uint32_t i;
int error;
switch (cmd) {
case PFN_IOC_UPDATE_COUNTERS:
break;
default:
return (ENOTTY);
}
upd = (struct pfn_counter_update *)data;
if (upd->count == 0)
return (0);
if (upd->count > PFN_COUNTER_BATCH_MAX)
@ -412,8 +482,6 @@ pfn_dev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data,
return (error);
}
CURVNET_SET(TD_TO_VNET(td));
for (i = 0; i < upd->count; i++) {
s = pf_find_state_byid(entries[i].id, entries[i].creatorid);
if (s == NULL) {
@ -424,22 +492,81 @@ pfn_dev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data,
s->packets[1] += entries[i].packets[1];
s->bytes[0] += entries[i].bytes[0];
s->bytes[1] += entries[i].bytes[1];
/* Keep PF state alive while CDX is offloading the flow.
* Without this, PF purges the state (UDP: 60s, TCP: 24h)
* because offloaded packets bypass pf_test() and never
* update expire. Once PF purges the state, pf_notify
* sends DELETE → CMM removes CDX flow → permanent death. */
s->expire = time_uptime;
/*
* Offloaded packets bypass pf_test(), which would refresh the
* state. Refresh it only for packets that really moved: an
* idle offloaded flow must expire like any other, so its
* DELETE removes it from the hardware.
*/
if (entries[i].packets[0] != 0 || entries[i].packets[1] != 0)
s->expire = time_uptime;
PF_STATE_UNLOCK(s);
pfn_counter_updates++;
}
CURVNET_RESTORE();
free(entries, M_TEMP);
return (0);
}
/* PFN_IOC_OFFLOADED: CMM put these states' flows into hardware */
static int
pfn_mark_offloaded(struct pfn_offloaded *off)
{
struct pfn_state_ref *refs;
struct pf_kstate *s;
uint32_t i;
int error;
if (off->count == 0)
return (0);
if (off->count > PFN_COUNTER_BATCH_MAX)
return (EINVAL);
refs = malloc(off->count * sizeof(*refs), M_TEMP, M_WAITOK);
error = copyin(off->refs, refs, off->count * sizeof(*refs));
if (error) {
free(refs, M_TEMP);
return (error);
}
for (i = 0; i < off->count; i++) {
s = pf_find_state_byid(refs[i].id, refs[i].creatorid);
if (s == NULL)
continue;
/* the hardware forwards without pf's TCP window tracking:
packets coming back to pf must not be dropped as out of
window */
s->state_flags |= PFSTATE_SLOPPY;
PF_STATE_UNLOCK(s);
pfn_offloaded++;
}
free(refs, M_TEMP);
return (0);
}
static int
pfn_dev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data,
int fflag __unused, struct thread *td)
{
int error;
CURVNET_SET(TD_TO_VNET(td));
switch (cmd) {
case PFN_IOC_UPDATE_COUNTERS:
error = pfn_update_counters((struct pfn_counter_update *)data);
break;
case PFN_IOC_OFFLOADED:
error = pfn_mark_offloaded((struct pfn_offloaded *)data);
break;
default:
error = ENOTTY;
break;
}
CURVNET_RESTORE();
return (error);
}
static int
pfn_dev_poll(struct cdev *dev __unused, int events, struct thread *td)
{
@ -447,7 +574,7 @@ pfn_dev_poll(struct cdev *dev __unused, int events, struct thread *td)
mtx_lock(&pfn_mtx);
if (events & (POLLIN | POLLRDNORM)) {
if (!ring_empty(&pfn_ring))
if (!ring_empty(&pfn_ring) || pfn_overflow)
revents |= events & (POLLIN | POLLRDNORM);
else
selrecord(td, &pfn_rsel);
@ -478,8 +605,9 @@ static int
pfn_kqread(struct knote *kn, long hint)
{
kn->kn_data = ring_count(&pfn_ring) * sizeof(struct pfn_event);
return (!ring_empty(&pfn_ring));
kn->kn_data = (ring_count(&pfn_ring) + (pfn_overflow ? 1 : 0)) *
sizeof(struct pfn_event);
return (!ring_empty(&pfn_ring) || pfn_overflow);
}
static void
@ -555,6 +683,16 @@ pfn_sysctl_init(void)
&pfn_events_dropped, 0,
"Events dropped (ring full)");
SYSCTL_ADD_U64(&pfn_sysctl_ctx, SYSCTL_CHILDREN(parent),
OID_AUTO, "resyncs", CTLFLAG_RD,
&pfn_resyncs, 0,
"Lost DELETEs that made CMM drop every hardware flow");
SYSCTL_ADD_U64(&pfn_sysctl_ctx, SYSCTL_CHILDREN(parent),
OID_AUTO, "offloaded", CTLFLAG_RD,
&pfn_offloaded, 0,
"States CMM put into hardware (made sloppy)");
SYSCTL_ADD_U64(&pfn_sysctl_ctx, SYSCTL_CHILDREN(parent),
OID_AUTO, "counter_updates", CTLFLAG_RD,
&pfn_counter_updates, 0,
@ -602,6 +740,9 @@ pfn_load(void)
pfn_open = 0;
pfn_events_total = 0;
pfn_events_dropped = 0;
pfn_resyncs = 0;
pfn_offloaded = 0;
pfn_overflow = 0;
pfn_counter_updates = 0;
pfn_counter_misses = 0;
pfn_ring_hwm = 0;

View file

@ -25,6 +25,20 @@
#define PFN_EVENT_INSERT 1 /* new PF state created */
#define PFN_EVENT_READY 2 /* state is offload-ready */
#define PFN_EVENT_DELETE 3 /* PF state removed */
#define PFN_EVENT_RESYNC 4 /* events were lost: drop every offloaded
flow; READY fires again for live states */
/*
* Offload vetoes (pfn_event.veto): the state's rules ask for something only
* pf_test() does per packet, so its flow must stay on the software path.
*/
#define PFN_VETO_ROUTE 0x0001 /* route-to, reply-to, dup-to */
#define PFN_VETO_RTABLE 0x0002 /* policy routing to another FIB */
#define PFN_VETO_SHAPER 0x0004 /* dummynet pipe/queue (shaper, limiters) */
#define PFN_VETO_QUEUE 0x0008 /* ALTQ queue */
#define PFN_VETO_LOG 0x0010 /* log all, or pflow accounting */
#define PFN_VETO_NORMALIZE 0x0020 /* scrub, set-tos, set-prio, max-mss,
min-ttl, max-pkt-size */
/*
* Compact state key — mirrors pf_state_key fields needed by CMM.
@ -59,7 +73,7 @@ struct pfn_event {
uint64_t id; /* pf_kstate.id */
uint32_t creatorid; /* pf_kstate.creatorid */
uint16_t state_flags; /* pf_kstate.state_flags */
uint16_t _pad1;
uint16_t veto; /* PFN_VETO_* */
char ifname[16]; /* IFNAMSIZ */
struct pfn_state_key key[2]; /* [0]=wire, [1]=stack */
uint8_t _pad2[8]; /* pad to 128 bytes */
@ -92,6 +106,26 @@ struct pfn_counter_update {
#include <sys/ioccom.h>
#endif
/* --- Offloaded states (userspace -> kernel via ioctl) --- */
/*
* CMM reports the states whose flow it put into hardware. Only those are
* made sloppy: their TCP windows go stale while the hardware forwards, and
* pf must not drop the packets that come back to the software path.
*/
struct pfn_state_ref {
uint64_t id;
uint32_t creatorid;
uint32_t pad;
};
struct pfn_offloaded {
uint32_t count; /* number of refs, <= PFN_COUNTER_BATCH_MAX */
uint32_t pad;
const struct pfn_state_ref *refs; /* userspace pointer */
};
#define PFN_IOC_UPDATE_COUNTERS _IOW('N', 1, struct pfn_counter_update)
#define PFN_IOC_OFFLOADED _IOW('N', 2, struct pfn_offloaded)
#endif /* PF_NOTIFY_H */