Compare commits

..

76 commits

Author SHA1 Message Date
20b7c34c64 cmm: remove the unused cmm_neigh_invalidate() and cmm_neigh_flush_ifindex()
Neither had a caller; cmm_neigh_check() now marks neighbors whose MAC
changed or is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 04:27:43 -05:00
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
1f06ea3817 README: how to turn hardware flow offload on and off, and its caveats
Offload stays off by default: it is only needed for multi-gigabit
throughput on the 10 GbE ports. The README says how to turn it on and
off (in /etc/rc.conf.local; onestop, since rc.subr refuses a plain stop
once it is disabled) and lists the caveats: no TCP sequence checks for
offloaded flows, Suricata/Zenarmor/NetFlow/tcpdump see only their first
packets, VLAN and rule counters miss hardware traffic, the MAC address
gap, what is untested, and the reboot after an update. RELEASE.md keeps
the design and points there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 04:16:25 -05:00
64240400dc Docs: hardware flow offload is opt-in and keeps pf's decisions
RELEASE.md: the "offload: off" section becomes "opt-in": how to turn cmm
on (in /etc/rc.conf.local, which overrides rc.conf), which flows go into
hardware and which stay in pf, what offloaded packets still skip
(Suricata, Insight/NetFlow, tcpdump), the reboot after an update, and
what was wrong with the vendor's offload.

ARCHITECTURE.md: pf_notify's RESYNC event, vetoes, route-to target and
orig_kif, the DELETE reserve, sloppy only for offloaded states, and the
flow lifecycle with the offload conditions; the PF_KEY socket is gone
with the IPsec code; cmm only starts with cmm_enable="YES".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 02:08:48 -05:00
e78dba3348 Merge offload-fixes: hardware flow offload that keeps pf's decisions
Tested on a gateway on 2026-11-28 (26.7.9, cmm run by hand): NATed LAN
flows and port forwards were offloaded through OPNsense's automatic
route-to/reply-to rules, only offloaded states were sloppy (502 for 253
flows), no events were lost, pfctl -k stopped an offloaded download at
once with its hardware flows removed, pf saw TCP connections close
(22 TCP state deletions in a minute), and stopping cmm emptied the
hardware tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 02:07:23 -05:00
0130ae74d8 Offload: route-to matching the routing table; the state's own interface
Two problems found while preparing the gateway test.

pf_notify reported s->kif as a state's interface. A floating state
(OPNsense's default) has kif "all", so cmm's check that the routes leave
by the states' interfaces failed for every flow and nothing would have
been offloaded. Events now carry orig_kif, the interface the state was
created on.

OPNsense's automatic rules put route-to on the force-gateway rule, which
matches every NATed flow leaving WAN, and reply-to on WAN rules (port
forwards). The blanket route veto kept all of it on the software path.
pf_notify now passes a route-to/reply-to target in the event (which grows
to 160 bytes, the ring to 20 MiB), and cmm offloads such a flow only
while the main routing table sends those packets out of the same
interface to the same next hop: route-to for the original direction,
reply-to for the reply. A route change already tears flows down and
re-runs that check. dup-to, a target without an interface, and one in
another address family still veto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 01:44:38 -05:00
49db816186 gwmirror publish: refuse to delete a series from the share
publish mirrors the staged tree with rsync --delete-after, and the share
holds the only copy of series that are no longer built (26.1). A staging
tree rebuilt after /scratch was lost, holding only the current series,
would have deleted 26.1 from the live mirror. publish now stops, before
verifying, when the destination has a directory in its top two levels
(an ABI, a series, releases/<series>) that the staged tree lacks; names
are printed quoted. Retiring a series means deleting it from the share
by hand.

RELEASE.md documents the guard and how to restore the staged tree from
the share.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 01:32:15 -05:00
f1a16265a8 Remove the IPsec offload code (audit V2)
cdx no longer builds it, so it goes: cdx's dpa_ipsec_freebsd.c and
cdx_dpa_ipsec_freebsd.c, the vendor control_ipsec.c and query_ipsec.c,
and cmm's PF_KEY handling (cmm_ipsec.c). FreeBSD's IPsec stack handles
all IPsec; flows into a tunnel never match the hardware's routes, so
cmm keeps them on the software path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:47:12 -05:00
96a812fa5b 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>
2026-11-27 22:16:06 -05:00
fb138079b7 lock-26.7.9: src at fe7a7425d40 (RX checksum fix, ina2xx relabel)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 21:54:10 -05:00
3277066c5a Release tooling: commit lock per release, escaping symlinks, doc fixes
- K2: config/lock-<version> gives tools, src, ports, plugins and core
  their exact commits; build stops when a checkout differs (a tag moved
  upstream, or src moved on), and fetches tags without --force.
  build.sh lock resolves and writes them. lock-26.7.9 is what 26.7.9 was
  built from, checked against the upstream tags.
- K3: verify --root reports symlinks that lead outside the tree or
  nowhere, which publish (rsync -L) would follow; such a path is now
  reported instead of crashing verify.
- K6: RELEASE.md no longer says core trusts only our key (it also trusts
  upstream's, for changelog and bogons), and names no host or user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 21:30:15 -05:00
98356a2663 Board drivers: audit fixes V6, V8, V9, V11; relabel ported drivers GPL-2.0
Security fixes from the audit:
- V8 caam: the HMAC raw key (up to 128 bytes) was copied into a buffer
  of the split key's size (32 bytes for MD5, 48 for SHA-1), reachable
  through /dev/crypto. The buffer now fits both. caam_dma_free() zeroes
  every buffer itself, which also fixes the QI path clearing twice the
  split key buffer's size at each session teardown.
- V6 mwifiex: the uap_passphrase sysctl, readable by every local user,
  is write-only; mwifiex_uap says to keep the passphrase in a 0600
  /etc/rc.conf.d/mwifiex_uap.
- V9 dpaa_wifi: hardware frame lengths were copied into a 4 KB cluster
  unchecked, and scatter/gather frames read as one buffer. One helper
  now takes only contiguous frames within the buffer, at any length.
- V11: cdx frees IPsec keys and shared descriptors with zfree(); fmc's
  state file moves from /tmp (symlink attack by any local user) to
  /var/run.
- The firmware object pcieuart9098_combo_v1.bin.fwo is a build output
  and no longer tracked.

caam, ina2xx and lp5812 were ported from Linux and relabelled BSD-2 by
the vendor (8f9b3bf, 84e318c, ac81eea). They are GPL-2.0-only again,
with the Linux sources' copyright holders; LICENSING.md lists them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 21:30:15 -05:00
5e215f5997 20-kernel-update: leave kernel.bin where the kernel set put it
The hook deleted /boot/kernel/kernel.bin once it was on the FAT
partition, so the health audit always reported it missing (seen on the
gateway after the 26.7.9 upgrade). It now leaves the kernel set's files
alone and returns early, without a space check or a log line, when the
kernel and device tree on the FAT partition are already the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:54:16 -05:00
aa8c49368d rc.d/cmm: stop waits for cmm to exit, and checks it is cmm
The custom stop killed whatever pid the pid file held, ignored whether
that worked, removed the file and printed "Stopped cmm." On the gateway
cmm was still running right after it. rc.subr's own start, stop and
status (command=) send SIGTERM and wait for the exit, and only act on a
pid file that names a running cmm.

Tested through FreeBSD's rc.subr with a stand-in cmm that takes 2
seconds to exit, and with a stale pid file naming another process.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:48:49 -05:00
2e67937271 gwmirror-verify: check the published 26.7 tree daily as well
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:35:49 -05:00
f34695776d gwmirror: verify pkg 2.8 catalogues and the major upgrade's set
- pkg 2.8 (26.7) writes a package's catalogue checksum as "2$" and its
  BLAKE2b-512 in pkg's base32; accept it next to pkg 2.3's SHA-256 hex
  and check each against its own digest, read once for both. Latest/
  signatures stay over the SHA-256: a BLAKE2b catalogue checks them when
  deep, and only their key when shallow, as for the sets.
- TarSource members share the set's file object, which every read
  seeks, and verify_repo reads them from eight threads: the 26.7.9
  upgrade set failed at random packages. Reads now take turns.
- Report the upgrade set's results under its path, not ".".
- Clean up the trust objects' temporary directories.

Tests: the root and URL verify tests run again with BLAKE2b catalogues,
a pkg 2.8.4 checksum pins the encoding, and the upgrade set gets its
own tests (parallel reads of large packages, a tampered package in a
signed set, a bad .abi_hint).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:33:59 -05:00
a72fc09862 build.sh: fail early on a kernel set without kernel.bin
U-Boot boots boot/kernel/kernel.bin, and the gateway's 20-kernel-update
skips a kernel set without one, leaving the old kernel in place. FreeBSD
15 builds it only with WITH_KERNEL_BIN, which the 26.7.9 image build was
the first to notice; check the kernel set right after it is built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:20:05 -05:00
8716b582b3 build.sh: build the host pkg from opnsense/pkg, as tools checks
Since 26.7 the ports tree builds pkg from opnsense/pkg (2.8.4) and tools
compares the host's pkg with it; ports-mgmt/pkg is FreeBSD's 2.9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 19:38:52 -05:00
87893ded3e Build 26.7 for FreeBSD 15 only; port caam and cdx to its kernel
- caam: the bus activate, deactivate and release resource methods take
  no type and rid in FreeBSD 15.
- cdx: sys/cdefs.h defines __maybe_unused now; define it only if missing.
- 26.1 is end of life and no longer built: remove patches/26.1 and
  make-26.1.conf, default to 26.7 and FreeBSD 15.1 throughout, and move
  the build examples in README.md and RELEASE.md to 26.7.9. The 26.1
  tree on the mirror stays, for gateways that still have to upgrade.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 19:26:41 -05:00
99d56a310d RELEASE.md: FreeBSD 15 dropped GEOM_BDE from the GATEWAY kernel config
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 16:52:50 -05:00
eedcb25199 RELEASE.md: the broken pf commit on Mono's 26.7 branch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 21:17:37 -05:00
67ee1582c9 Turn hardware flow offload off; drop the Mono copyright line
The security audit of the vendor's fastpath found that offloaded flows
ignore pf route-to/reply-to and gateway rules (VPN-as-gateway traffic can
leave on WAN), that pf_notify marks every pf state sloppy while cmm runs,
that bridged traffic is offloaded without pf, that hardware flows can
outlive their pf state, and that the IPsec exception path panics. New
images no longer enable cmm, and RELEASE.md gives the commands for a
gateway that was installed from the vendor's image. The board modules
still load; nothing is offloaded without cmm.

rc.d/20-kernel-update is our rewrite: its Mono copyright line goes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 21:12:19 -05:00
df4b223a15 setup: pin FreeBSD 15's ports repository to the release too
FreeBSD 15 names its ports repository FreeBSD-ports instead of FreeBSD,
so the release_N override created a second repository, which had no
mirror_type "srv" for its pkg+https URL and failed. setup now overrides
the first repository /etc/pkg/FreeBSD.conf defines, with mirror_type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 21:00:09 -05:00
569b1f3b95 26.7.9: core patches and caddy-custom plugin pins
The CMM restart on interface reassignment moves to the MVC assignment
API, which replaced interfaces_assign.php in 26.7. The mirror patch is
unchanged but for the plist, where upstream's trusted key changed. Both
apply to core 26.7.9 with git am. caddy-custom's plugins are pinned at
their versions of 2026-11-11, when 26.7.9 was tagged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 20:45:30 -05:00
e1b9aa77fd Drop the cross-build leftovers, pilot and migrate-device.sh
The build runs natively on arm64 since 2026-11-18: setup no longer installs
qemu-user-static and aarch64-binutils (and refuses a non-aarch64 host),
GATEWAY.conf drops PRODUCT_WANTS_CROSS, build no longer asks tools for an
xtools set, finish no longer moves one aside, and mk-image.sh no longer
sets up xtools or removes qemu. The pilot command, which timed ports
before the first full build, goes too.

Gateways are migrated with the shell commands in RELEASE.md, as
ApolloGuardian was, instead of migrate-device.sh; that includes the
custom mirror for a proxy that is not on 443 inside the LAN, and the
major upgrade's UPGRADE_RELEASE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 20:41:11 -05:00
5f4afd0155 RELEASE.md: setting the custom mirror from the shell
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 20:25:17 -05:00
f1f299920a RELEASE.md: a gateway that reaches the mirror on another port
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 20:21:15 -05:00
bd67c63c2c Untrack the mwifiex build symlinks
drivers/mwifiex/Makefile links the vendor mlan sources and the firmware
from _vendor/ into its directory when building, and removes them on clean.
Those links were committed by accident (absolute /usr/deps/_vendor paths,
dangling everywhere else), and Portainer refuses to clone a repository
that contains symlinks. They are ignored now; the modules build the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 19:45:45 -05:00
0342256eb9 verify: no Latest/ in the aux repo; Go's source tree is cross-platform
Tools makes Latest/ for the main repository only, and upstream's aux
repository has none either, so verify no longer requires it there. The Go
toolchain in aux ships ELF test data and race-detector objects for every
platform under /usr/local/go<N>/src/; that tree is exempt from the aarch64
check, nothing else of the Go packages is.

The first real 26.1.11 mirror now verifies clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:30:09 -05:00
90dd8bb200 finish: sign the aux set's catalogue
Tools signs the aux repository's catalogue only in a packages step run
with the key; its sign-packages re-signs the packages set's catalogue but
not the aux set's. Build runs without the key, so the aux catalogue stayed
unsigned and gwmirror verify rejected it. finish now unpacks the aux set,
signs its catalogue with pkg repo and repacks it before tools signs the set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 17:34:56 -05:00
1d27c40b84 Scan the image dataset by dataset; report silent failures
finish's scan imported the image's pool with every dataset mounted under
an altroot. The pool's own dataset needs a mountpoint inside the read-only
root, so nothing was mounted, find scanned an empty directory, and the
export then failed with "pool is busy". The pool is now imported without
mounting, and each dataset is mounted read-only by itself. The root must
have /bin/sh, so an empty scan cannot pass. The export is retried, since
the pool stays busy for a while after the import and after an unmount.

build.sh now says when set -e stops it, and vm.sh sign returns finish's
exit status, not tee's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:40:09 -05:00
f5fa1360bf Pin caddy-custom's plugins at the versions of the 26.1.11 tag
xcaddy fetches www/caddy-custom's plugins while it builds, at their
newest versions; caddy-l4 v0.1.3 (2026-11-09) needs caddy 2.11.7 and the
ports tree has 2.11.4, so the port failed. config/make-<series>.conf,
added to tools' make.conf by ports_make_conf, pins tools' plugin list at
the versions of 2026-07-01, when 26.1.11 was tagged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 09:29:09 -05:00
097d18f940 Recover Codeberg tag archives; fetch-patch.sh is now fetch-distfile.sh
Codeberg now compresses tag archives with GNU gzip instead of git's own,
so sysutils/sysinfo's 1.0.4 archive is 15546 bytes, not distinfo's 15618,
and FreeBSD's distfile cache serves the new one too. git archive of the
tag with git's gzip at level 6 reproduces the original exactly (SHA256
checked by the port). The FETCH_CMD wrapper does that for Codeberg tag
archives, after checking owner, repository and tag strictly, and is
renamed for the second kind of repair.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 08:45:46 -05:00
1bba2be945 Remove all work directories after each port in tools' ports step
Tools ran make clean after each port, which cleans every dependency with
the port's own flavor: a dependency with another flavor, or none, looks
for the wrong work-<flavor> and keeps its work directory. After a failure
tools removes the dependencies it built, and the stale directory claims
they are installed, so every later port needing them failed at once
(Rust: cmake not found; libxslt.so not found). build now has tools'
ports.sh remove every work directory instead, and stops if ports.sh no
longer has the two cleans it replaces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:11:57 -05:00
01e09eccd2 RELEASE.md: why a failed Rust fails at once for the rest of a step
The ports tree's clean passes a flavored port's FLAVOR on to its
dependencies, so a dependency without flavors looks for work-<flavor> and
keeps its half-built work directory; its build tools are removed, and
every later port that needs it fails at once until the next step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:02:51 -05:00
98b6a457ad Cap Rust's build jobs by memory; no page-wait kills in the VM
The Rust build in the 12 GB VM lost two llvm-tblgen 2.8 hours in:
FreeBSD kills a process that has waited 30 seconds for a page, and the
emulated VM's pageout took that long with the swap unused. setup turns
those kills off (vm.pfault_oom_attempts=-1), and build caps lang/rust,
which builds its own LLVM with a job per CPU, at one job per 768 MB
through tools' make.conf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:46:16 -05:00
fc2481ecac build: the host pkg's distfiles come from the distfiles set
host_pkg fetched pkg's distfiles again for every build of the host
pkg, and GitHub turned one of its patches away four times in a row,
which stopped the build. It now seeds them into the distfiles set
(repair_distfiles, which skips what the set has) and extracts them
from there. port_distfiles names a port's entries in the set, for
both host_pkg and distfiles_in_set (whose awk now reads them from
the environment).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:59:34 -05:00
f31a70765a build: salvage only whole packages with a manifest
FreeBSD's tar lists an empty file as an empty archive, so a package
file cut off at zero bytes passed salvage_ports' check. A salvaged
package must now also hold +MANIFEST.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:52:43 -05:00
1addff9484 build VM: swap disk, small ZFS cache; salvage interrupted ports steps
A 16 GB VM (18 GB in qemu, 7 GB of it ZFS cache) and the HTPC's other
work ran the HTPC out of memory, and its reboot lost 12 hours of the
ports step. The VM now gets a swap disk of its own (swap.qcow2, serial
gwswap, cache=none: off ZFS, where swap can deadlock, and past the
host's page cache), and setup caps the VM's ZFS cache at 2 GB
(vm_memory). The VM itself goes down to 12 GB in vm.conf.

Tools writes the packages set only when a ports step ends. build now
first adds what an interrupted step had finished (salvage_ports): the
runtime packages in the stage's packages directory, when the stage
belongs to the same series, version and ports commit, each checked to
be a whole archive. Build-only dependencies are rebuilt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:50:02 -05:00
d8bba11344 build: skip distfiles the set already has; retry GitHub patches
The restarted build stopped at seeding pkg's distfiles: GitHub
answered "Service Unavailable" for a patch the distfiles set already
held. repair_distfiles now skips a port whose distfiles and patch
files are all in the set (distfiles_in_set), and fetch-patch.sh tries
GitHub's current patch three times, a minute apart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:41:58 -05:00
9eceff0663 build: build the ports in one tools step, not in chunks
Tools caches the build-only dependencies it builds (cmake, autoconf,
the Rust and Go compilers) for the rest of a ports step only, and the
packages set keeps just the listed ports and their runtime
dependencies. Each chunk therefore rebuilt them: the second chunk
started by rebuilding the autotools the first had built.

The step also runs without an argument now: an argument makes tools
stop at the first failed port, while without one it goes on with the
others and fails at the end. ports_list served only the chunks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:35:12 -05:00
52f795704a Fetch distfiles as the ports build, repairing failed fetches per chunk
Tools' distfiles step walks every port's whole dependency tree again,
one make at a time: 70 of 266 ports in 9 hours under emulation. It
also walks the default flavor's tree for flavored ports (QEMU's desktop
dependencies for qemu@guestagent) and fails there on a port the build
never needs (gstreamer1-plugins-bad, missing from its distinfo). The
ports step fetches what it builds anyway, so the step is dropped, and
with it the tools patch that only fixed it.

pkg's distfiles are seeded into the distfiles set (which tools
extracts into the ports chroot) before the first chunk. A chunk whose
log shows "Couldn't fetch it" or "Giving up on fetching files" has
those ports repaired with fetch-patch.sh and runs once more.
fetch_failures accepts only port names, tested against real and
crafted logs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:15:18 -05:00
b59c0e41ed Repair distfiles that tools' chroot cannot fetch, and let tools list them
Natively, the first fetch in tools' distfiles chroot builds pkg, whose
GitHub patches no longer match distinfo, and tools' fetch loop records
a failure in a path outside the chroot, which under sh -e ended the
loop with no port named. patches/tools/0001 records failures inside
the chroot (as tools' ports step does); build.sh applies patches/tools
to every series. pkg's distfiles go into the set before the step, via
fetch-patch.sh; repairs are appended to the set instead of rewriting
a set of many gigabytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 06:45:58 -05:00
23f43f6b6c vm.sh sync: copy the tracked dist/.keep
Excluding all of dist/ (to keep the VM's build output from --delete)
also skipped dist/.keep, so the VM's checkout looked dirty and
build.sh would refuse to build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 00:10:37 -05:00
784173c31a vmhost.sh: boot without the NIC's iPXE option ROM; report qemu start errors
Debian's qemu-system-arm only recommends ipxe-qemu, so the virtio NIC's
efi-virtio.rom is missing from the image and qemu refused to start. The
VM never network-boots: drop the ROM. A qemu that exits at once now
shows its log instead of vm.sh waiting minutes to say it stopped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 23:43:12 -05:00
dcc4d129ab Build natively in an emulated arm64 VM on a remote build host
qemu-user cannot run cargo, so no Rust port (py-cryptography and its
dependents) can be cross-built. The build VM is now FreeBSD arm64 under
full-system emulation (qemu-system-aarch64, TCG), run by the new
release/vmhost.sh in a rootless podman container on the build host
GW_VMHOST. vm.sh drives it over ssh and reaches the VM's loopback-only
ssh port through the host (ProxyJump). Settings may live in
$GW_KEYDIR/vm.conf.

The image download probes its sources, resumes stalled transfers and
falls back to a mirror that keeps old releases; the checksum always comes
from FreeBSD itself.

build.sh builds the ports in chunks of PORTS_CHUNK (20) with timings, so
progress is visible and a failure costs one chunk, then runs the whole
list once more to bundle the set. ports_list evaluates ports.conf like
tools' list_config does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 23:42:04 -05:00
3c3cd5e719 RELEASE.md: publish into a folder of the share
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:44:58 -05:00
c40ca350b6 build.sh: build the host pkg outside the ports tree
Its distfiles stayed in /usr/ports/distfiles, the lower layer of the
unionfs mount tools puts in every chroot, and the ports step's
rm -rf of distfiles/ there failed with "Operation not supported".
Fetch and build it under /var/tmp instead and remove that afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:30:51 -05:00
5665956249 mirror: store the tree under names an SMB share can hold
The mirror share refuses ":" in names, ignores case, and lists device
names such as "aux" under a mangled 8.3 name, which rsync would delete as
an unknown file (the real directory). So FreeBSD:<N>:aarch64 is stored
as FreeBSD_<N>_aarch64 and a series' aux repository as aux-repo, in the
staged tree and on the share alike; nginx rewrites the client URLs onto
them, and gwmirror reads and writes through the same mapping.

verify --root, and therefore publish, now fails on any other name the
share cannot store (reserved characters, device names, trailing dot or
space, names differing only in case).

Checked with the real nginx image in podman: a deep verify --url of a
staged fixture passes, aux included, with the live changelog/bogons proxy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:49:20 -05:00
1ab64f5ba2 Recover GitHub-generated patch distfiles; fix git ownership in the VM
The first pilot stopped building the host pkg: GitHub now abbreviates the
object names on the index lines of its generated commit patches with 10
digits instead of 9, so OPNsense's patches of ports-mgmt/pkg no longer
match distinfo, and nothing caches OPNsense's own distfiles.

- release/fetch-patch.sh: FETCH_CMD that, when fetch(1) fails for a
  GitHub commit/pull/compare patch, shortens the abbreviations until the
  size matches; the port's checksum target verifies the SHA256.
- build.sh: run tools' distfiles step on its own, repair the ports it
  could not fetch on the host into the distfiles set, and rerun it; the
  pilot fetches its ports' distfiles too; host pkg uses the wrapper.
- vm.sh sync: files owned by root in the VM. They kept the workstation's
  uid, git refused the "dubious" repository, and that defeated the dirty
  check silently. build.sh now fails when git cannot read /usr/deps, and
  the package target refuses a version without the commit count.
- migrate-device.sh: FreeBSD grep rejects the empty alternative in the
  fingerprint file check, so it failed on every device. Found by running
  release/tests on the build VM, now part of the documented test run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:43:10 -05:00
f8276aa54a RELEASE.md: the forks must be publicly readable
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:06:57 -05:00
4433e98531 build.sh: never let git prompt for credentials
The hang blamed on Forgejo in the previous commit was git waiting at an
invisible username prompt: the forks are internal to code.karsttech.com
and the build VM has no credentials. Fail at once instead, and correct
the reason for the shallow src fetch (its history is not needed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 01:33:10 -05:00
2c66209351 build.sh: fetch the src fork shallow, time out stalled git transfers
A full clone of opnsense-src from Forgejo hung for 5.5 hours with nothing
transferred. The build never reads src history (tools only describes src
when VERSION is not numeric), so fetch just the ref's commit; core, plugins
and ports keep full history and tags for their version strings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 01:01:28 -05:00
6ddb7ef179 vm.sh: setup runs build.sh setup over ssh, before rsync exists in the VM
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:24:02 -05:00
ac8436a4d6 vm.sh: wait for the first boot's freebsd-update before giving up on ssh
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:13:47 -05:00
0a613871af release: pilot builds only the named ports and leaves no partial packages set
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:58:29 -05:00
ab6b52207f mirror: gwmirror stage/verify/publish, nginx stack, release docs
- gwmirror.py: lay a build into the mirror tree, verify it (signatures,
  catalogues, sizes, hashes, aarch64-only ELF, and over HTTPS also TLS
  expiry, Content-Length, redirects) and publish it with rsync only when
  it verifies; tests cover tampering, untrusted and revoked keys,
  traversal and decompression limits
- server/: unprivileged nginx for a Portainer stack serving the SMB share
  read-only, GET/HEAD only, proxying changelog/bogons from upstream
- monitor/: daily systemd user timer running verify --url
- RELEASE.md: design and runbook; README.md points to it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:56:54 -05:00
fe4aecbb05 release: build VM, full release build and device migration
- vm.sh: FreeBSD amd64 build VM on the Linux workstation (QEMU/KVM,
  no root): verified official image, root SSH key via nuageinit, sync of
  this repository, detached builds, signing with the key in a tmpfs
- build.sh: check out all repositories at the release tag, build base,
  kernel, xtools, ports, plugins, core and the board package unsigned;
  finish signs everything, builds the eMMC image and rejects foreign ELF
  files in it; pilot times selected ports to estimate a build
- migrate-device.sh: repoint a gateway from opnsense.mono.si to our
  mirror (dry run, backups, strict input checks) and offer the 26.7
  major upgrade
- tests for migrate-device.sh and 20-kernel-update

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:56:54 -05:00
ccebd54083 board package: build per series, harden kernel install for U-Boot
- Makefile: read the FreeBSD release from tools' config/<series>/build.conf
  and derive the compiler target and package ABI from it, version the
  package <release>_<commit count>, take libxml2 from our own packages
  set instead of pkg.FreeBSD.org, clone the NXP sources from the Forgejo
  mirrors, and drop the image target (release/build.sh replaces it)
- +MANIFEST: ABI from the series, new maintainer and www
- GATEWAY.conf: annotate mono-gateway as coming from the OPNsense
  repository; fail the image build if the package is missing
- mk-image.sh: remove the amd64 qemu binary setup_xtools leaves behind
- 20-kernel-update: drop the 26.1.3 guard; check room on the FAT
  partition, copy and verify the new kernel before replacing the old
  one, keep kernel.old, restore it on failure, retry at next shutdown
- 01-mono-modules: log modules that fail to load instead of hiding it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:56:54 -05:00
9d6aad2ef7 core patches: sign and serve from opnsense.karsttech.com
The vendor mirror opnsense.mono.si is gone and upstream publishes no
aarch64 builds, so releases are signed with our own key and served from
https://opnsense.karsttech.com.

The core patches move to patches/<series>/ and are applied with git am
onto core's release tag. The new mirror patch replaces the vendor's:
CORE_PACKAGESITE and the mirror list point at the new mirror, its key
opnsense.karsttech.com.20261117 is trusted, the vendor keys are revoked,
and the separate MonoGateway repository is dropped (mono-gateway is now
published in the OPNsense repository). The CMM restart patch is kept.

keys/ holds the public key and the fingerprints release tooling trusts:
ours (trusted/revoked) and upstream's for changelog/bogons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:56:54 -05:00
Maurice Walker
95fd8558bf Add OPNsense 26.7 fingerprint to core patches 2026-07-16 02:09:10 +02:00
Maurice Walker
5e16b997aa Force-add fingerprint and Mono Gateway repo before committing core patches 2026-06-17 04:21:01 +02:00
Maurice Walker
93b3a45ddd Move mirror / repo / fingerprint configuration to core package
This is how our releases have always been built: Patch opnsense/core before building it. This is required for online updates.
Also, update the readme to use opnsense.mono.si for prefetching sets. The packages set available there includes the patched core package.
2026-06-17 03:49:36 +02:00
Maurice Walker
f52da03e64 pkg: add dtb updater to kernel updater 2026-04-09 05:56:46 +02:00
Maurice Walker
e84320e823 image build: move kernel to FAT partition instead of copying it
The existence of /boot/kernel/kernel.bin triggers the kernel updater.
2026-04-09 05:32:55 +02:00
Maurice Walker
fc51b3794b pkg: add kernel updater
mono-gateway package installs an rc.syshook script which moves the U-Boot booti compatible kernel image from /boot/kernel to the FAT partition on reboot / shutdown.
2026-04-09 03:59:52 +02:00
Tomaz Zaman
8c3db242b3 cmm: add configd action for interface reassignment restart
Add actions_cmm.conf so OPNsense configd can restart CMM when
interfaces are reassigned. Include in package build and plist.
2026-04-03 17:07:24 +02:00
Tomaz Zaman
b728bd41f7 cmm: add configd action for interface reassignment restart
Add actions_cmm.conf so OPNsense configd can restart CMM when
interfaces are reassigned. Include in package build and plist.
2026-04-03 16:54:54 +02:00
Maurice Walker
a25df123fa build: remove custom kernel image script
Instead, build the kernel with the LINUX_BOOT_ABI option.
https://github.com/we-are-mono/opnsense-src/pull/1
This is a precursor for enabling online kernel updates.
2026-03-31 01:25:53 +02:00
Tomaz Zaman
632abec0ec add LICENSING.md and LICENSES/ for mixed-license clarity
Document the licensing of all components in the repository:
- BSD-2-Clause: clean-room driver reimplementations
- GPL-2.0+: NXP ASK-derived fastpath stack
- GPL-2.0: mwifiex WiFi (NXP mlan core + FreeBSD moal)
- Permissive: fmlib (BSD-3-Clause), fmc (MIT)

LICENSES/ contains full license texts referenced by per-file SPDX
identifiers.
2026-03-29 17:16:26 +02:00
Tomaz Zaman
ac81eea5d5 lp5812: replace Linux references with datasheet citations in comments
Change "from leds-lp5812.h" to "from LP5812 datasheet" and
"matches Linux driver" to "per LP5812 datasheet" in comments.
No functional changes.
2026-03-29 17:02:18 +02:00
Tomaz Zaman
c3ad5aa81a mwifiex: relicense moal files to GPL-2.0 with NXP copyright
The FreeBSD moal shim layer links directly against NXP's GPL-2.0
mlan core (~127K lines). Relicense the 4 moal files and Makefile
from BSD-2-Clause to GPL-2.0 and add NXP copyright, consistent
with the mlan source they are compiled against.
2026-03-29 17:02:10 +02:00
Tomaz Zaman
e8cb4efca3 fastpath: relicense to GPL-2.0+ with proper NXP copyright attribution
The fastpath stack (CDX, CMM, cmmctl, auto_bridge, FCI, dpa_app)
derives from NXP's ASK SDK which is GPL-2.0+ licensed. Several
components compile NXP vendor source directly, and others include
verbatim GPL headers (list.h, jhash.h, fpp.h).

Change all BSD-2-Clause files in the fastpath stack to GPL-2.0+ and
add original copyright holders (Mindspeed Technologies, Freescale
Semiconductor, NXP) alongside Mono's copyright. Also fix "Ported
from" comment in include/desc.h to "Inspired by".

Components unaffected: pf_notify (100% original BSD), fmlib
(BSD-3-Clause NXP), fmc (MIT NXP).
2026-03-29 17:02:02 +02:00
Tomaz Zaman
8f9b3bf487 caam: rename descriptor constants and remove GPL source references
Add CAAM_ prefix to all 253 descriptor command constants (CMD_* ->
CAAM_CMD_*, HDR_* -> CAAM_HDR_*, KEY_* -> CAAM_KEY_*, OP_ALG_* ->
CAAM_OP_ALG_*, LDST_*, FIFOLD_*, FIFOST_*, JUMP_*, MATH_*, MOVE_*)
to differentiate from Linux drivers/crypto/caam/desc.h naming.

Replace all 30+ Linux references in comments with NXP SEC reference
manual citations. Change "ported from" and "matches exactly" language
to hardware-specification references.

No functional changes — purely mechanical renames and comment rewording
for licensing clarity. Build verified clean with -Werror.
2026-03-29 01:12:41 +01:00
Tomaz Zaman
84e318cb09 ina2xx: rename constants and structs to differentiate from GPL source
Rename register macros (INA2XX_* -> INA_REG_*), config struct
(ina2xx_config -> ina_chip_params with new field names), and LSB
calculation variable to remove 1:1 naming correspondence with the
Linux hwmon/ina2xx.c GPL driver. Change "Based on" to "Inspired by"
and remove explicit Linux function reference from comments.

No functional changes — purely mechanical renames for licensing clarity.
2026-03-29 01:12:31 +01:00
Tomaz Zaman
a6471b16f6 build: use minimal 4-entry GPT to reserve firmware region on eMMC
Replace gpart (which enforces 128 GPT entries = 17KB) with a Python
script that creates a 4-entry GPT table fitting in 1.5KB.  This keeps
the entire partition table below 4KB, leaving the 4KB-32MB region free
for LS1046A boot firmware (BL2, FIP, U-Boot env, FMan microcode, DTB).

The boot partition starts at sector 65536 (32MB), matching the existing
GATEWAY.conf ARM_FAT_SIZE setting.  FreeBSD's kernel reads 4-entry GPTs
without issue — the 128-entry minimum only applies to gpart create.
2026-03-27 23:06:02 +01:00
189 changed files with 9246 additions and 6841 deletions

9
.gitignore vendored
View file

@ -20,3 +20,12 @@ opt_*.h
machine
x86
i386
# Python bytecode from the tests
__pycache__/
# Made by drivers/mwifiex/Makefile from _vendor/ when building (Portainer refuses
# to clone a repository with symlinks)
drivers/mwifiex/mlan_*.c
drivers/mwifiex/pcieuart9098_combo_v1.bin
drivers/mwifiex/pcieuart9098_combo_v1.bin.fwo

View file

@ -51,7 +51,8 @@ bypassing the FreeBSD networking stack.
kernel boot
└─► kldload cdx fci pf_notify auto_bridge
└─► dpa_app /etc/cdx_pcd.xml /etc/cdx_cfg.xml /etc/cdx_sp.xml
└─► service cmm start
└─► service cmm start (only with cmm_enable="YES"; images
ship "NO", see README.md)
```
## Fastpath Modules
@ -86,11 +87,28 @@ Hooks into the PF firewall to push state change events to userspace:
- `PFN_EVENT_INSERT` — new state created
- `PFN_EVENT_READY` — state became offload-eligible (TCP ESTABLISHED)
- `PFN_EVENT_DELETE` — state removed by PF
- `PFN_EVENT_RESYNC` — DELETE events were lost: CMM drops every hardware
flow and starts over (`net.pfnotify.resyncs`)
Each event carries the state's keys, the interface it was created on
(`orig_kif`; a floating state's own interface is `all`), its route-to or
reply-to target, and a veto mask (`PFN_VETO_*`) for rule actions only
pf_test() can carry out per packet: dup-to, another FIB, a dummynet pipe
or queue, ALTQ, `log (all)` or pflow, scrub options, set-tos, max-mss,
min-ttl, max-pkt-size, af-to. CMM never offloads a vetoed flow.
Exposes `/dev/pfnotify` (read-write, non-blocking). Required by CMM —
CMM will not start without this module loaded. Uses a 128K-entry ring
buffer with one-shot READY semantics: dropped events re-fire on the
next packet, eliminating the need for polling fallback.
buffer, of which 4096 entries are kept for DELETEs, with one-shot READY
semantics: dropped events re-fire on the next packet, eliminating the
need for polling fallback. CMM reports the states it put into hardware
(`PFN_IOC_OFFLOADED`); only those are made sloppy, as their TCP windows
stop being tracked. `PFN_IOC_UPDATE_COUNTERS` adds the hardware's packet
counts to the states, which keeps them from expiring while FMan forwards.
The event layout is shared with CMM (`pf_notify.h`). A CMM and a
pf_notify.ko from different builds get only short reads and offload
nothing, so reboot after updating `mono-gateway`.
Source: `fastpath/pf_notify/`
@ -111,18 +129,30 @@ next-hop neighbors, and programs CDX with offload entries.
/dev/pfnotify │ │ FCI commands
PF state poll │ CMM ├──────────────► cdx.ko
route socket │ │
PF_KEY socket │ event loop │◄────────────── FCI events
│ event loop │◄────────────── FCI events
/dev/autobridge│ (kqueue) │ (flow timeout)
ctrl socket │ │
└──────────────┘
```
**Flow lifecycle**:
1. PF creates state → pfnotify READY → CMM resolves route + neighbor
2. CMM sends route + conntrack to CDX via FCI → flow in hardware
3. Packets forwarded at line rate by FMan, bypassing stack
4. CDX timer expires or TCP FIN → FCI event → CMM clears offload flag
5. If PF state still alive → maintenance timer (30s) re-offloads
1. PF creates the flow's states (in on the ingress interface, out on the
egress one) → pfnotify READY for each → CMM pairs them and resolves
route + neighbor
2. CMM offloads only if neither state is vetoed, both were seen, each
direction's route leaves by the interface PF's state for it is on,
and a route-to (original direction) or reply-to (reply) names the
same interface and next hop as that route
3. CMM sends route + conntrack to CDX via FCI → flow in hardware, and
reports the two states to pf_notify (sloppy from then on)
4. Packets forwarded at line rate by FMan, bypassing stack; their
counters are synced back into PF's states
5. PF deletes a state (close, timeout, `pfctl -k`) → DELETE → CMM removes
the flow from hardware
6. CDX timer expires or TCP FIN → FCI event → CMM clears offload flag
7. A route change, or a next hop's MAC changing in the ARP/NDP table
(checked every 30s), tears down the flows using it; while PF's states
are alive, the maintenance timer (30s) re-runs step 2 and re-offloads
Source: `fastpath/cmm/`
@ -220,7 +250,6 @@ Wire ──► FMan RX Port
| PF → CMM | /dev/pfnotify | State insert/ready/delete events |
| CMM ← PF | DIOCGETSTATESV2 ioctl | Periodic state table poll (fallback) |
| CMM ← routing | PF_ROUTE socket | Route/neighbor/interface changes |
| CMM ← IPsec | PF_KEY socket | SA add/delete events |
| CMM ← bridge | /dev/autobridge | L2 flow learning events |
| cmmctl → CMM | Unix socket | Query/control commands |
| dpa_app → FMan | /dev/fman chardev | PCD configuration (XML → hardware) |

22
LICENSES/BSD-2-Clause.txt Normal file
View file

@ -0,0 +1,22 @@
BSD 2-Clause License
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

26
LICENSES/BSD-3-Clause.txt Normal file
View file

@ -0,0 +1,26 @@
BSD 3-Clause License
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

338
LICENSES/GPL-2.0.txt Normal file
View file

@ -0,0 +1,338 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Moe Ghoul>, 1 April 1989
Moe Ghoul, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

19
LICENSES/MIT.txt Normal file
View file

@ -0,0 +1,19 @@
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

63
LICENSING.md Normal file
View file

@ -0,0 +1,63 @@
# Licensing
This repository contains components under multiple open-source licenses. Each source file carries an SPDX-License-Identifier header which is the authoritative license for that file. Full license texts are in the `LICENSES/` directory.
## BSD-2-Clause — FreeBSD Drivers
These drivers were written for FreeBSD from hardware datasheets and vendor reference manuals.
| Component | Path | Notes |
|---|---|---|
| EMC2302 fan controller | `drivers/emc2302/` | Microchip EMC2301-2305 |
| TMP431 temp sensor | `drivers/tmp431/` | TI TMP431 dual-channel |
| PCF2131 RTC | `drivers/pcf2131/` | NXP PCF2131 real-time clock |
| pf_notify | `fastpath/pf_notify/` | PF state change notifications (no Linux counterpart) |
## GPL-2.0-only — Ported from Linux Drivers
These drivers were ported from their Linux counterparts. The vendor had relabelled them BSD-2-Clause after renaming constants and removing the "ported from Linux" notes (commits `8f9b3bf`, `84e318c`, `ac81eea`); they carry their Linux sources' license and copyright holders again. The CAAM sources are GPL-2.0+ except `desc.h`, `regs.h`, `key_gen.c` and `qi.c` (GPL-2.0), which every CAAM file uses, so the driver is GPL-2.0-only.
| Component | Path | Linux source |
|---|---|---|
| CAAM crypto | `drivers/caam/` | `drivers/crypto/caam` (Freescale Semiconductor, NXP) |
| INA2xx power monitor | `drivers/ina2xx/` | `drivers/hwmon/ina2xx.c` (Lothar Felten and contributors) |
| LP5812 LED controller | `drivers/lp5812/` | TI's LP5812 driver; `lp5812.h` is TI's header (Texas Instruments) |
## GPL-2.0+ — NXP Fastpath Stack
The DPAA1 flow offload stack derives from NXP's ASK (Application Solution Kit) SDK, which is GPL-2.0+ licensed. Some components compile unmodified NXP vendor source from `fastpath/vendor/`; others are FreeBSD rewrites that include GPL headers (`fpp.h`, `list.h`) or are derived from GPL originals. The entire stack is licensed as GPL-2.0+ with original copyright holders (Mindspeed Technologies, Freescale Semiconductor, NXP) retained.
| Component | Path | Description |
|---|---|---|
| CDX | `fastpath/cdx/` | Flow offload kernel module (compiles NXP vendor source + FreeBSD ports) |
| CMM | `fastpath/cmm/` | Connection manager daemon (reimplemented for FreeBSD, includes GPL headers) |
| cmmctl | `fastpath/cmmctl/` | CMM command-line control tool |
| auto_bridge | `fastpath/auto_bridge/` | L2 flow detection kernel module |
| FCI | `fastpath/fci/` | Fast control interface kernel module |
| fci_lib | `fastpath/fci_lib/` | FCI userspace library |
| dpa_app | `fastpath/dpa_app/` | DPA initialization tool (compiles NXP vendor source) |
| include/ | `fastpath/include/` | Shared headers (mix of GPL NXP originals + BSD compat shims) |
| vendor/ | `fastpath/vendor/` | Unmodified NXP ASK source (GPL-2.0+) |
## GPL-2.0 — NXP WiFi Driver
The mwifiex WiFi driver links NXP's GPL-2.0 mlan core library (~127K lines, fetched into `_vendor/` at build time) with a FreeBSD OS abstraction layer (~3K lines). The combined module is GPL-2.0.
| Component | Path | Description |
|---|---|---|
| mwifiex | `drivers/mwifiex/` | NXP 88W9098 PCIe WiFi (mlan core + FreeBSD moal shim) |
## Permissive Third-Party — NXP Libraries
These NXP-provided libraries carry permissive licenses and are used unmodified.
| Component | Path | License | Description |
|---|---|---|---|
| fmlib | `fastpath/fmlib/` | BSD-3-Clause | FMan userspace library |
| fmc | `fastpath/fmc/` | MIT | FMan Configuration Compiler |
## Compliance
All source code is publicly available in this repository. GPL compliance is satisfied through source availability alongside any binary distribution.
Per-file SPDX-License-Identifier headers are the authoritative license for each file. When in doubt, check the file header.

156
Makefile
View file

@ -1,16 +1,14 @@
# Top-level build Makefile for opnsense-deps
# Top-level build Makefile for opnsense-deps: the Mono Gateway board package
#
# Build everything:
# make -C /usr/deps all
# Build the mono-gateway package (kernel modules, userspace, configs):
# make -C /usr/deps package OPS_SETTINGS=26.7 OPS_VERSION=26.7.9
#
# Clean all build artifacts:
# make -C /usr/deps clean
#
# Build full image (kernel, modules, userspace, package, image):
# make -C /usr/deps image
# This needs the GATEWAY kernel build tree and a sysroot with the base set
# and libxml2 in it; release/build.sh prepares both and builds the whole
# OPNsense release around this package (see RELEASE.md).
#
# Build subsets:
# make -C /usr/deps modules # kernel modules only
# make -C /usr/deps modules # kernel modules only
# make -C /usr/deps userspace # userspace only
#
# Parallel build (modules build concurrently):
@ -30,18 +28,26 @@ TOOLSDIR?= /usr/tools
SYSROOT?= /usr/obj${SRCDIR}/arm64.aarch64/tmp
KERNBUILDDIR?= /usr/obj${SRCDIR}/arm64.aarch64/sys/GATEWAY
# OPNsense build settings
OPS_SETTINGS?= 26.1
OPS_BRANCH= stable/${OPS_SETTINGS}
IMAGESDIR?= /usr/local/opnsense/build/${OPS_SETTINGS}/aarch64/images
SETSDIR?= /usr/local/opnsense/build/${OPS_SETTINGS}/aarch64/sets
# OPNsense series and release this package is built for. The FreeBSD
# release comes from the tools configuration of that series, so the
# compiler target and the package ABI always match the base system.
OPS_SETTINGS?= 26.7
OPS_VERSION?= # required for "package", e.g. 26.7.9
.if !defined(OSREL)
OSREL!= sed -n 's/^OS?*=[[:space:]]*//p' ${TOOLSDIR}/config/${OPS_SETTINGS}/build.conf 2>/dev/null || true
.endif
.if empty(OSREL)
.error Cannot read OS from ${TOOLSDIR}/config/${OPS_SETTINGS}/build.conf; set OSREL=
.endif
PKG_ABI= FreeBSD:${OSREL:R}:aarch64
CROSS_TARGET= --target=aarch64-unknown-freebsd${OSREL}
# Common args for all kernel module builds
# Explicit --target ensures cross-compilation works from amd64; harmless on native aarch64
# --target pins the FreeBSD release of the series
KMOD_ARGS= SYSDIR=${SRCDIR}/sys \
KERNBUILDDIR=${KERNBUILDDIR} \
MACHINE=arm64 MACHINE_ARCH=aarch64 \
CC="cc --target=aarch64-unknown-freebsd14.3" LD=ld.lld
CC="cc ${CROSS_TARGET}" LD=ld.lld
# Local build directory for userspace components
BUILDDIR?= ${OPSDIR}/_build
@ -49,17 +55,12 @@ BUILDDIR?= ${OPSDIR}/_build
# Output directory for all final artifacts
DISTDIR?= ${OPSDIR}/dist
# libxml2 aarch64 package for cross-compilation sysroot (fmc links against it).
# pkg.FreeBSD.org blocks directory listings, so we fetch by exact filename.
# Update this when the FreeBSD ports tree bumps libxml2.
LIBXML2_PKG?= libxml2-2.15.2.pkg
LIBXML2_URL= https://pkg.FreeBSD.org/FreeBSD:14:aarch64/latest/All/${LIBXML2_PKG}
# Package version: derived from git tags (e.g., tag "26.1.2" + 3 commits = "26.1.2_3")
# Override: make package PKG_VERSION=26.1.2.1
_PKG_TAG!= git -C ${OPSDIR} describe --abbrev=0 --always HEAD 2>/dev/null || echo 0.0.0
_PKG_REV!= git -C ${OPSDIR} rev-list --count ${_PKG_TAG}..HEAD 2>/dev/null || echo 0
PKG_VERSION?= ${_PKG_TAG}${_PKG_REV:N0:S/^/_/}
# Package version: the OPNsense release plus the commit count of this
# repository, e.g. "26.1.11_74". It grows with every commit and every
# release, so it always upgrades the previous package (including the
# vendor's "26.1.5_N" versions). Override: make package PKG_VERSION=...
_PKG_REV!= git -C ${OPSDIR} rev-list --count HEAD 2>/dev/null || true
PKG_VERSION?= ${OPS_VERSION}_${_PKG_REV}
PKG_STAGEDIR= ${BUILDDIR}/pkg-stage
PKG_CONFDIR= ${OPSDIR}/config
PKG_RCDDIR= ${OPSDIR}/rc.d
@ -89,10 +90,11 @@ KMOD_TMP= ${DRIVERS}/tmp431
KMOD_MWIFI= ${DRIVERS}/mwifiex
KMOD_DW= ${DRIVERS}/dpaa_wifi
# NXP vendor repositories (pinned commits for reproducible builds)
MWIFIEX_REPO= https://github.com/nxp-imx/mwifiex.git
# NXP vendor repositories (pinned commits for reproducible builds); Forgejo
# pull mirrors of github.com/nxp-imx/{mwifiex,imx-firmware}
MWIFIEX_REPO?= https://code.karsttech.com/claude/mwifiex.git
MWIFIEX_COMMIT= 84ca65c9ff935d7f2999af100a82531c22c65234
IMX_FW_REPO= https://github.com/nxp-imx/imx-firmware.git
IMX_FW_REPO?= https://code.karsttech.com/claude/imx-firmware.git
IMX_FW_COMMIT= 8c9b278016c97527b285f2fcbe53c2d428eb171d
build-cdx:
@ -172,33 +174,33 @@ modules: build-cdx build-fci build-auto_bridge build-pf_notify \
fmlib:
@mkdir -p ${BUILDDIR}/fmlib
cd ${BUILDDIR}/fmlib && ${MAKE} -f ${FASTPATH}/fmlib/Makefile.cross \
SYSROOT=${SYSROOT} KSRCDIR=${SRCDIR} all
TARGET=${CROSS_TARGET} SYSROOT=${SYSROOT} KSRCDIR=${SRCDIR} all
fmc: fmlib
@mkdir -p ${BUILDDIR}/fmc
cd ${BUILDDIR}/fmc && ${MAKE} -f ${FASTPATH}/fmc/Makefile.cross \
SYSROOT=${SYSROOT} KSRCDIR=${SRCDIR} FMLIB_LIB=${BUILDDIR}/fmlib all
TARGET=${CROSS_TARGET} SYSROOT=${SYSROOT} KSRCDIR=${SRCDIR} FMLIB_LIB=${BUILDDIR}/fmlib all
dpa_app: fmc
@mkdir -p ${BUILDDIR}/dpa_app
cd ${BUILDDIR}/dpa_app && ${MAKE} -f ${FASTPATH}/dpa_app/Makefile.cross \
SYSROOT=${SYSROOT} KSRCDIR=${SRCDIR} \
TARGET=${CROSS_TARGET} SYSROOT=${SYSROOT} KSRCDIR=${SRCDIR} \
FMLIB_LIB=${BUILDDIR}/fmlib FMC_LIB=${BUILDDIR}/fmc all
cmm:
@mkdir -p ${BUILDDIR}/cmm
cd ${BUILDDIR}/cmm && ${MAKE} -f ${FASTPATH}/cmm/Makefile.cross \
SYSROOT=${SYSROOT} KSRCDIR=${SRCDIR} all
TARGET=${CROSS_TARGET} SYSROOT=${SYSROOT} KSRCDIR=${SRCDIR} all
cmmctl:
@mkdir -p ${BUILDDIR}/cmmctl
cd ${BUILDDIR}/cmmctl && ${MAKE} -f ${FASTPATH}/cmmctl/Makefile.cross \
SYSROOT=${SYSROOT} all
TARGET=${CROSS_TARGET} SYSROOT=${SYSROOT} all
fand:
@mkdir -p ${BUILDDIR}/fand
cd ${BUILDDIR}/fand && ${MAKE} -f ${DRIVERS}/fand/Makefile \
SYSROOT=${SYSROOT} all
TARGET=${CROSS_TARGET} SYSROOT=${SYSROOT} all
userspace: fmlib fmc dpa_app cmm cmmctl fand
@mkdir -p ${DISTDIR}
@ -213,6 +215,8 @@ userspace: fmlib fmc dpa_app cmm cmmctl fand
# ============================================================
package: all
@if [ -z "${OPS_VERSION}" ]; then echo "set OPS_VERSION (e.g. 26.7.9)" >&2; exit 1; fi
@case "${PKG_VERSION}" in *_) echo "git cannot count the commits of ${OPSDIR}; set PKG_VERSION" >&2; exit 1;; esac
@rm -f ${DISTDIR}/mono-gateway-*.pkg
@rm -rf ${PKG_STAGEDIR}
@mkdir -p ${PKG_STAGEDIR}/boot/modules
@ -220,6 +224,7 @@ package: all
@mkdir -p ${PKG_STAGEDIR}/etc/fmc/config
@mkdir -p ${PKG_STAGEDIR}/usr/local/etc/rc.d
@mkdir -p ${PKG_STAGEDIR}/usr/local/etc/rc.syshook.d/early
@mkdir -p ${PKG_STAGEDIR}/usr/local/etc/rc.syshook.d/stop
# Kernel modules
install -m 644 ${DISTDIR}/cdx.ko ${PKG_STAGEDIR}/boot/modules/
install -m 644 ${DISTDIR}/fci.ko ${PKG_STAGEDIR}/boot/modules/
@ -251,85 +256,22 @@ package: all
install -m 755 ${PKG_RCDDIR}/mwifiex_uap ${PKG_STAGEDIR}/usr/local/etc/rc.d/
# rc.syshook early scripts
install -m 755 ${PKG_RCDDIR}/01-mono-modules ${PKG_STAGEDIR}/usr/local/etc/rc.syshook.d/early/
# rc.syshook stop scripts
install -m 755 ${PKG_RCDDIR}/20-kernel-update ${PKG_STAGEDIR}/usr/local/etc/rc.syshook.d/stop/
# OPNsense plugin files (hwmon dashboard widget)
cp -R ${OPSDIR}/plugins/hwmon/src/opnsense/ ${PKG_STAGEDIR}/usr/local/opnsense/
chmod 755 ${PKG_STAGEDIR}/usr/local/opnsense/scripts/hwmon/sensors.py
# CMM configd action (restart on interface reassignment)
install -m 644 ${PKG_CONFDIR}/actions_cmm.conf ${PKG_STAGEDIR}/usr/local/opnsense/service/conf/actions.d/
# Generate manifest with version
sed 's/%%VERSION%%/${PKG_VERSION}/' ${PKG_METADIR}/+MANIFEST \
> ${PKG_STAGEDIR}/+MANIFEST
sed -e 's/%%VERSION%%/${PKG_VERSION}/' -e 's/%%ABI%%/${PKG_ABI}/' \
${PKG_METADIR}/+MANIFEST > ${PKG_STAGEDIR}/+MANIFEST
# Build package (ABI override for cross-compilation on amd64 host)
ABI=FreeBSD:14:aarch64 pkg create \
ABI=${PKG_ABI} pkg create \
-M ${PKG_STAGEDIR}/+MANIFEST -p ${PKG_METADIR}/plist \
-r ${PKG_STAGEDIR} -o ${DISTDIR}/
@echo "==> Package: ${DISTDIR}/mono-gateway-${PKG_VERSION}.pkg"
# ============================================================
# Full image build (kernel, modules, userspace, package, image)
# ============================================================
_NCPU!= sysctl -n hw.ncpu 2>/dev/null || echo 4
image:
@echo "NOTE: run as root (sudo make image)"
@rm -rf ${DISTDIR}/*
@touch ${DISTDIR}/.keep
@echo "==> Step 1: Checking repositories"
@test -d ${SRCDIR}/.git || git clone https://github.com/we-are-mono/opnsense-src.git -b ${OPS_BRANCH} ${SRCDIR}
@test -d ${TOOLSDIR}/.git || git clone https://github.com/opnsense/tools.git ${TOOLSDIR}
@cp -n ${OPSDIR}/config/GATEWAY.conf ${TOOLSDIR}/device/ 2>/dev/null || true
cd ${SRCDIR} && git checkout ${OPS_BRANCH} && git pull || echo " git pull skipped (NFS or no remote)"
@echo "==> Step 2: Building kernel (clean)"
rm -f ${SETSDIR}/kernel-*-GATEWAY.txz
chflags -R noschg /usr/obj${SRCDIR}/arm64.aarch64 2>/dev/null || true
rm -rf /usr/obj${SRCDIR}/arm64.aarch64
${MAKE} -C ${TOOLSDIR} kernel \
DEVICE=GATEWAY SETTINGS=${OPS_SETTINGS} \
TOOLSDIR=${TOOLSDIR} SRCDIR=${SRCDIR}
@echo "==> Step 2a: Populating sysroot from base set"
@_base=$$(ls ${SETSDIR}/base-*-aarch64-GATEWAY.txz 2>/dev/null | head -1); \
if [ -z "$$_base" ]; then \
echo "ERROR: no base set found in ${SETSDIR}"; exit 1; \
fi; \
echo " extracting headers and libraries from $$(basename $$_base)"; \
tar xf "$$_base" -C ${SYSROOT} --no-fflags \
--include='./usr/include/*' \
--include='./usr/lib/*.a' \
--include='./usr/lib/*.so' \
--include='./usr/lib/*.o' \
--include='./lib/*.so*'
@echo "==> Step 2b: Installing libxml2 into sysroot"
@if [ ! -f ${SYSROOT}/usr/local/lib/libxml2.so ]; then \
rm -f /tmp/libxml2.pkg; \
fetch -qo /tmp/libxml2.pkg '${LIBXML2_URL}'; \
rm -rf /tmp/libxml2-extract; \
mkdir -p /tmp/libxml2-extract; \
tar xf /tmp/libxml2.pkg -C /tmp/libxml2-extract; \
mkdir -p ${SYSROOT}/usr/local/include ${SYSROOT}/usr/local/lib; \
cp -r /tmp/libxml2-extract/usr/local/include/libxml2 \
${SYSROOT}/usr/local/include/; \
cp -a /tmp/libxml2-extract/usr/local/lib/libxml2* \
${SYSROOT}/usr/local/lib/; \
rm -rf /tmp/libxml2-extract /tmp/libxml2.pkg; \
echo " libxml2 installed into sysroot"; \
else \
echo " libxml2 already in sysroot"; \
fi
@echo "==> Step 3: Building modules, userspace, and package"
${MAKE} -C ${OPSDIR} -j${_NCPU} package
@echo "==> Step 5: Assembling ZFS image"
rm -f ${IMAGESDIR}/OPNsense-*-GATEWAY.img \
${IMAGESDIR}/OPNsense-*-GATEWAY.img.gz
cp ${OPSDIR}/mk-image.sh ${TOOLSDIR}/build/arm.sh
${MAKE} -C ${TOOLSDIR} arm-5G \
DEVICE=GATEWAY SETTINGS=${OPS_SETTINGS} \
TOOLSDIR=${TOOLSDIR} SRCDIR=${SRCDIR}
@echo "==> Step 6: Compressing and copying to dist/"
@mkdir -p ${DISTDIR}
gzip -k ${IMAGESDIR}/OPNsense-*-GATEWAY.img
cp ${IMAGESDIR}/OPNsense-*-GATEWAY.img.gz ${DISTDIR}/
@echo "==> Image ready:"
@ls -lh ${DISTDIR}/OPNsense-*-GATEWAY.img.gz
# ============================================================
# Clean
# ============================================================
@ -355,7 +297,7 @@ clean:
.ORDER: clean modules
.ORDER: clean userspace
.PHONY: all modules userspace package image clean fetch-vendor \
.PHONY: all modules userspace package clean fetch-vendor \
build-cdx build-fci build-auto_bridge build-pf_notify \
build-emc2302 build-ina2xx build-lp5812 build-sfpled build-pcf2131 \
build-caam build-tmp431 build-mwifiex build-dpaa_wifi \

281
README.md
View file

@ -1,5 +1,13 @@
# Mono Gateway custom components for OPNsense
> This is the Karst Tech fork of
> [we-are-mono/opnsense-deps](https://github.com/we-are-mono/opnsense-deps).
> The vendor no longer maintains OPNsense for the gateway and its update
> mirror opnsense.mono.si is gone. This fork builds, signs and publishes the
> complete aarch64 OPNsense release (base, kernel, packages, image) at
> **https://opnsense.karsttech.com**. How that works, and how to build,
> publish and migrate a gateway, is in [RELEASE.md](RELEASE.md).
Out-of-tree kernel modules, userspace daemons, and build tooling for the Mono
Gateway OPNsense image. Contains the DPAA1 fast-path stack (CDX flow offload,
FCI, CMM connection manager, PF notifier, auto-bridge), board-support drivers
@ -33,9 +41,14 @@ opnsense-deps/
│ ├── dpa_app/ # DPAA application (PCD setup)
│ ├── cmm/ # Connection Manager daemon
│ └── cmmctl/ # CMM control utility
├── config/ # FMC/CDX XML configuration files
├── config/ # FMC/CDX XML configuration files, GATEWAY device config
├── rc.d/ # rc.d service scripts and syshook scripts
├── pkg/ # FreeBSD package metadata
├── patches/<series>/ # opnsense/core patches (mirror, signing key, CMM restart)
├── keys/ # mirror public key and trusted/revoked fingerprints
├── release/ # build VM, release build, device migration (+ tests)
├── mirror/ # gwmirror.py stage/verify/publish, nginx container (+ tests)
├── mk-image.sh, tools/ # ZFS eMMC image builder used by the release build
├── _vendor/ # NXP vendor repos (cloned at build time, gitignored)
└── Makefile # top-level build (modules + userspace + package)
```
@ -54,213 +67,91 @@ on performance or functionality.
| Port 4 | dtsec3 | 10 GbE SFP+ |
| Port 5 | dtsec4 | 10 GbE SFP+ |
## Hardware flow offload (off by default)
The fast-path stack can forward established connections in FMan hardware
instead of through pf. It is only worth turning on for throughput pf cannot
reach in software, i.e. multi-gigabit traffic on the 10 GbE ports. Images
ship with it off (`cmm_enable="NO"` in `/etc/rc.conf.local`); the board
modules load either way.
Turn it on (the setting belongs in `/etc/rc.conf.local`, which overrides
`/etc/rc.conf`):
```sh
sh
sysrc -f /etc/rc.conf.local cmm_enable=YES
service cmm start
```
Turn it off:
```sh
sh
sysrc -f /etc/rc.conf.local cmm_enable=NO
service cmm onestop
```
pf still decides every connection: filtering, NAT, port forwards and routing
stay pf's, and killing a state removes its hardware flow. Flows whose rules
need pf for every packet (shaper, policy routing to another gateway, scrub,
MSS clamping, `log (all)`) stay in software. Caveats for offloaded flows:
- pf no longer checks their TCP sequence numbers (their states are sloppy).
- Suricata, Zenarmor, Insight/NetFlow and tcpdump see only their first
packets. Leave offload off if you rely on them.
- VLAN interface counters and per-rule counters miss hardware traffic
(physical port counters and per-state counters include it). Captive
portal accounting probably does too.
- When a next hop's MAC address changes (a new ISP modem, a LAN host with a
new NIC but the same IP), its offloaded flows can go to the old MAC for
up to 30 seconds, until cmm's next check of the ARP/NDP table.
- Not tested: IPv6, links with different MTUs (PPPoE, VPN), CARP/pfsync.
- After updating `mono-gateway`, reboot so the loaded `pf_notify.ko`
matches the new cmm; until then nothing is offloaded.
How cmm decides what to offload: [RELEASE.md](RELEASE.md), "Hardware flow
offload".
## Build instructions
All commands run on the build server (FreeBSD, matching the OPNsense base version).
The whole release, not just this package, has to be built for aarch64:
upstream OPNsense publishes no aarch64 packages at all. `release/build.sh`
drives [opnsense/tools](https://github.com/opnsense/tools) through base,
kernel, ports, plugins and core, builds the `mono-gateway` package from this
repository against the new kernel, signs everything and builds the eMMC image.
It runs on an aarch64 FreeBSD host of the series' release (15.1 for 26.7):
the emulated arm64 VM that `release/vm.sh` runs on a Linux
build host, or a native aarch64 machine. See [RELEASE.md](RELEASE.md).
The build server should run the same FreeBSD version that OPNsense is based on
(e.g., FreeBSD 14.3 for OPNsense 26.1). Mismatched versions can cause ABI
issues in kernel modules. Native aarch64 builds are preferred; cross-compilation
from amd64 also works (see below).
### 1. Prerequisites
**Native aarch64 build server:**
To build only the board package on such a host after a release build:
```
sudo pkg install -y git python3
sudo make -C /usr/deps -j$(sysctl -n hw.ncpu) package OPS_SETTINGS=26.7 OPS_VERSION=26.7.9
```
**Cross-compilation from amd64:**
```
sudo pkg install -y git aarch64-binutils qemu-user-static python3
```
### 2. Directory layout
The build system uses standard OPNsense paths under `/usr/`. Repositories map
to these paths either by cloning directly or via NFS + nullfs mounts:
| Path | Repository | OPNsense variable |
|------|-----------|-------------------|
| `/usr/src` | [we-are-mono/opnsense-src](https://github.com/we-are-mono/opnsense-src) | `SRCDIR` |
| `/usr/tools` | [opnsense/tools](https://github.com/opnsense/tools) | `TOOLSDIR` |
| `/usr/deps` | [we-are-mono/opnsense-deps](https://github.com/we-are-mono/opnsense-deps) | (this repo) |
| `/usr/core` | [opnsense/core](https://github.com/opnsense/core) | `COREDIR` |
All paths are overridable: `sudo make -C /usr/deps image SRCDIR=/my/src TOOLSDIR=/my/tools`
**Option A — Local development** (clone directly):
```
sudo git clone https://github.com/we-are-mono/opnsense-src.git /usr/src
sudo git clone https://github.com/opnsense/tools.git /usr/tools
sudo git clone https://github.com/we-are-mono/opnsense-deps /usr/deps
sudo cp /usr/deps/config/GATEWAY.conf /usr/tools/device/
```
**Option B — Remote source via NFS** (source tree on another machine):
```
# Enable the NFS client
sudo sysrc nfs_client_enable="YES"
sudo service nfsclient start
# Mount the remote NFS export
# Replace [server] and [nfs-export] with your NFS server and export path.
# The exported directory should contain opnsense-src, opnsense-build,
# opnsense-deps, and opnsense-core as subdirectories.
sudo mkdir -p /mnt/opnsense /usr/tools /usr/core /usr/deps
echo '[server]:[nfs-export] /mnt/opnsense nfs rw,late 0 0' | sudo tee -a /etc/fstab
echo '/mnt/opnsense/opnsense-src /usr/src nullfs rw,late 0 0' | sudo tee -a /etc/fstab
echo '/mnt/opnsense/opnsense-build /usr/tools nullfs rw,late 0 0' | sudo tee -a /etc/fstab
echo '/mnt/opnsense/opnsense-deps /usr/deps nullfs rw,late 0 0' | sudo tee -a /etc/fstab
echo '/mnt/opnsense/opnsense-core /usr/core nullfs rw,late 0 0' | sudo tee -a /etc/fstab
sudo mount -a
sudo cp /usr/deps/config/GATEWAY.conf /usr/tools/device/
```
Using nullfs (rather than symlinks) ensures `pwd` reports `/usr/...` in build
output, keeping kernel version strings and module paths clean.
### 3. Prefetch base and packages
Official OPNsense mirrors only publish amd64 sets. For aarch64, use walker.earth.
Check https://opnsense-update.walker.earth/FreeBSD:14:aarch64/26.1/sets/ for available versions.
```
export VERSION=26.1.1 # use latest available on the mirror
sudo make -C /usr/tools prefetch-base DEVICE=GATEWAY SETTINGS=26.1 TOOLSDIR=/usr/tools MIRRORS=https://opnsense-update.walker.earth VERSION=$VERSION
# The build system expects a -GATEWAY suffix on the base set
cd /usr/local/opnsense/build/26.1/aarch64/sets
sudo mv base-${VERSION}-aarch64.txz base-${VERSION}-aarch64-GATEWAY.txz
sudo make -C /usr/tools prefetch-packages DEVICE=GATEWAY SETTINGS=26.1 TOOLSDIR=/usr/tools MIRRORS=https://opnsense-update.walker.earth VERSION=$VERSION
```
This skips `make base`, `make ports`, `make core`, and `make plugins` (no cross-compilation needed).
The build system's `check_packages()` validates the host `pkg` version against the
ports tree before checking whether the prefetched set already has completion markers.
Create a minimal stub so the version check passes:
```
sudo mkdir -p /usr/ports/ports-mgmt/pkg
echo "PORTVERSION=$(pkg -v)" | sudo tee /usr/ports/ports-mgmt/pkg/Makefile
```
**Important:** Do NOT run `make base` or `make xtools` locally. If an `xtools-*-aarch64.txz`
set exists in the sets directory, remove it before building the image. The xtools overlay/restore
mechanism (`setup_xtools`/`setup_xbase`) is broken for cross-builds and will leave amd64 binaries
in the image.
### 4–7. Build everything (single command)
After completing steps 1–3, a single command builds the kernel, modules, userspace,
package, and assembles the final eMMC image:
```
sudo make -C /usr/deps image
```
The individual steps below are documented for development workflows where you
only need to rebuild part of the stack.
### 4. Build kernel
```
sudo make -C /usr/tools kernel DEVICE=GATEWAY SETTINGS=26.1 TOOLSDIR=/usr/tools
```
On a native aarch64 build server, no cross-compilation flags are needed. On an
amd64 host, the kernel is cross-compiled natively (no QEMU). Package
installation during `make arm` uses QEMU user-static emulation.
**Rebuilding:** The build system caches the kernel set in the sets directory and
skips the build if one already exists. When rebuilding after source changes,
remove the stale set and obj tree first:
```
sudo rm -f /usr/local/opnsense/build/26.1/aarch64/sets/kernel-*-GATEWAY.txz
sudo rm -rf /usr/obj/usr/src/arm64.aarch64/sys/GATEWAY
```
### 5. Install libxml2
Required by opnsense-deps (fmc links against libxml2).
**Native aarch64 build server:**
```
sudo pkg install -y libxml2
```
**Cross-compilation from amd64:**
Fetch the aarch64 package from the FreeBSD pkg mirror and extract its headers
and libraries into the sysroot created by `make kernel`. `make image` does this
automatically; the manual steps below are only needed when building without it.
```
fetch -o /tmp/libxml2.pkg 'https://pkg.FreeBSD.org/FreeBSD:14:aarch64/latest/All/libxml2-2.15.2.pkg'
mkdir -p /tmp/libxml2-extract && cd /tmp/libxml2-extract && tar xf /tmp/libxml2.pkg
SYSROOT=/usr/obj/usr/src/arm64.aarch64/tmp
sudo mkdir -p ${SYSROOT}/usr/local/include ${SYSROOT}/usr/local/lib
sudo cp -r /tmp/libxml2-extract/usr/local/include/libxml2 ${SYSROOT}/usr/local/include/
sudo cp -a /tmp/libxml2-extract/usr/local/lib/libxml2* ${SYSROOT}/usr/local/lib/
```
If the package version has changed, override it in the Makefile:
```
make -C /usr/deps image LIBXML2_PKG=libxml2-2.16.0.pkg
```
### 6. Build custom modules and tools (everything in this repo)
```
sudo make -C /usr/deps -j24 all
```
The first build automatically clones NXP vendor repositories (mwifiex driver
source and imx-firmware) into `_vendor/` at pinned commits. Subsequent builds
reuse the cached clones. To force a fresh clone, remove `_vendor/` and rebuild.
### 7. Assemble eMMC image
```
sudo make -C /usr/tools arm-5G DEVICE=GATEWAY SETTINGS=26.1 TOOLSDIR=/usr/tools
```
Output: `/usr/local/opnsense/build/26.1/aarch64/images/OPNsense-*-arm-aarch64-GATEWAY.img`
Optionally, compress the image for faster transfers:
```
sudo gzip /usr/local/opnsense/build/26.1/aarch64/images/OPNsense-*-GATEWAY.img
```
The first build clones the NXP vendor repositories (mwifiex driver source and
imx-firmware, mirrored on code.karsttech.com) into `_vendor/` at pinned
commits. Subsequent builds reuse the cached clones; remove `_vendor/` to
force a fresh clone.
## Development workflow
### Kernel source
The kernel source (`opnsense-src`) is a fork of OPNsense/FreeBSD at
[we-are-mono/opnsense-src](https://github.com/we-are-mono/opnsense-src),
branched from `stable/26.1`. All Mono Gateway changes live as commits on this
branch.
[claude/opnsense-src](https://code.karsttech.com/claude/opnsense-src) (forked
from [we-are-mono/opnsense-src](https://github.com/we-are-mono/opnsense-src)).
Each `stable/<series>` branch is the upstream release tag plus the Mono
Gateway commits.
**Making a change:**
```bash
cd /usr/src
# See Mono Gateway commits on top of upstream
git log --oneline origin/stable/26.1..HEAD
# See Mono Gateway commits on top of upstream (in a clone with the release tags)
git log --oneline 26.7.9..origin/stable/26.7
# 1. Edit the file
vim sys/contrib/device-tree/src/arm64/freescale/mono-gateway-dk.dts
@ -273,12 +164,12 @@ git commit -m "dts: add PCIe WiFi reset GPIO"
git push
```
To rebase on a newer upstream OPNsense release:
To rebase on a newer upstream OPNsense release (here 26.7.9):
```bash
git remote add upstream https://github.com/opnsense/src.git
git fetch upstream
git rebase upstream/stable/26.7 # or whatever the new branch is
git fetch upstream tag 26.7.9
git rebase --onto 26.7.9 $(git merge-base HEAD upstream/stable/26.7) stable/26.7
git push --force-with-lease
```
@ -324,10 +215,12 @@ ip route add default via 10.0.0.1 dev eth3
### 3. Serve the image from the build server
On the build server, start an HTTP server in the images directory:
Signed images are published at
https://opnsense.karsttech.com/releases/<series>/ (check the `.sha256` file).
Recovery Linux is easiest served over plain HTTP from a machine on the same
network, e.g. in the directory holding the downloaded image:
```
cd /usr/local/opnsense/build/26.1/aarch64/images
python3 -m http.server 8000
```

767
RELEASE.md Normal file
View file

@ -0,0 +1,767 @@
# OPNsense releases and update mirror for the Mono Gateway
The Mono Gateway (NXP LS1046A) runs an OPNsense build by its vendor. Mono
stopped maintaining it, and its update mirror `opnsense.mono.si` went dark in
October 2026: the server still answers, but holds no TLS certificate, so every
update check fails with "SSL alert number 80". Upstream OPNsense publishes no
aarch64 builds at all, so nothing can be mirrored. Every release is therefore
built from source here, signed with our own key, and served from
**https://opnsense.karsttech.com**.
## Overview
```
code.karsttech.com/claude/{opnsense-src,opnsense-deps} github.com/opnsense/{tools,core,ports,plugins}
\ / (release tags)
release/build.sh in the build VM (FreeBSD arm64, emulated on the build host)
| unsigned sets -> sign (key in VM memory only) -> image
release/vm.sh pull-out -> /scratch/mono-opnsense/out/<series>/
|
mirror/gwmirror.py stage -> verify -> publish (rsync onto the SMB share)
|
nginx container (Portainer stack, share mounted read-only) <- Traefik/NPM (TLS) <- gateway
```
| Piece | Where |
|---|---|
| Kernel/base sources: upstream OPNsense src plus the vendor's 27 DPAA/LS1046A commits | `claude/opnsense-src`, branch `stable/<series>` |
| Board package, core patches, keys, all release tooling (this repository) | `claude/opnsense-deps` |
| NXP sources the board package builds from | `claude/mwifiex`, `claude/imx-firmware` (daily pull mirrors) |
| Build framework, core, ports, plugins | upstream GitHub, checked out at the release tag |
The build VM and Portainer clone every repository anonymously, so the four
`claude/` repositories must be public. That requires the `claude` account
itself to be public: Forgejo makes every repository of a limited or private
account "internal", readable by signed-in users only, whatever the
repository's own setting.
## What a gateway fetches
These are the paths opnsense-update and core's firmware scripts request,
under the URL in `/usr/local/etc/pkg/repos/OPNsense.conf`:
```
/FreeBSD:14:aarch64/26.1/latest/ pkg repository (meta.conf, packagesite.*, data.*, All/, Latest/)
/FreeBSD:14:aarch64/26.1/aux/ build-only packages (repository disabled by default)
/FreeBSD:14:aarch64/26.1/MINT/<ver>/latest/ snapshot per release, for opnsense-revert -r
/FreeBSD:14:aarch64/26.1/sets/
base-<ver>-aarch64.txz(.sig) no device suffix: clients fetch it without
kernel-<ver>-aarch64-GATEWAY.txz(.sig) suffix from kern.ident "MONO-GATEWAY"
changelog.txz(.sig), bogons.txz(.sig) proxied by nginx from pkg.opnsense.org (see below)
{packages,base,kernel}-<next>-aarch64* major upgrade sets for the next series
/FreeBSD:15:aarch64/26.7/... the same for 26.7 (FreeBSD 15)
/releases/<series>/OPNsense-<ver>-arm-aarch64-GATEWAY.img.gz(.sig,.sha256) eMMC image
/healthz
```
- The base/kernel release a gateway wants is the version of the
`opnsense-update` package in the repository, so the sets are built with
`VERSION=<release>` and named exactly after it.
- Core reads the changelog and bogons URL from `OPNsense.conf.sample` (the
build-time package site), not from the live file.
- changelog.txz and bogons.txz don't depend on the architecture. Upstream
signs them with the key core already trusts (pkg.opnsense.org.20260120
for 26.1, .20260608 for 26.7). The container therefore proxies them live
from upstream's amd64 tree of the same FreeBSD major and series, which
keeps the bogons current with no scheduled job.
- The board package `mono-gateway` lives in the main OPNsense repository
(the vendor had a separate `MonoGateway` one). During a major upgrade,
`opnsense-update -P` upgrades only the OPNsense repository. The board's
kernel modules must cross the ABI change with it.
### Names on disk
The mirror is stored on an SMB share, which keeps names the Windows way. On
ours (checked 2026-11-18):
- `:` is refused (`NT_STATUS_OBJECT_NAME_INVALID`);
- names are case-insensitive (`case.txt` replaces `Case.txt`);
- device names such as `aux` and `con` are stored but listed under a mangled
8.3 name (`AHY9U3~9`), so rsync would copy them again and then delete the
"unknown" mangled entry, which is the real directory. A file stored that way
cannot even be deleted over SMB.
So two components of the paths above have other names on disk, in the staged
tree and on the share alike:
| URL path | On disk |
|---|---|
| `/FreeBSD:<N>:aarch64/` | `FreeBSD_<N>_aarch64/` |
| `/FreeBSD:<N>:aarch64/<series>/aux/` | `FreeBSD_<N>_aarch64/<series>/aux-repo/` |
The nginx container rewrites the URLs onto them; `gwmirror.py` reads and
writes through the same mapping (`disk_rel`). Every other name is stored as
it is, and `verify --root` (so also `publish`) fails on any name the share
cannot hold: reserved characters, device names, a trailing dot or space, or
two names in a directory that differ only in case.
## Signing keys and trust
- **Private key:** `~/.config/gwmirror/repo.key` on the workstation (RSA
4096, mode 0600). It is never stored in git, in `/scratch`, on the share or
on a VM disk. `vm.sh sign` copies it over ssh, through the build host, into
a memory file system in the build VM and removes it when signing ends.
**Keep an offline backup:** anyone holding it can install code as root on
the gateway.
- **Public key:** `keys/opnsense.karsttech.com.20261117.pub`.
- **Fingerprint:** `sha256(repo.pub)` =
`5fc1e2bf74e0386a2ea1ee60d085d683735a9d7cd8090647be0f476c779c0dc3`, shipped
by our core package as
`/usr/local/etc/pkg/fingerprints/OPNsense/trusted/opnsense.karsttech.com.20261117`.
- **Vendor keys:** `opnsense.mono.si.20260305` and `.20260716` are revoked
by our core.
- **What gets signed:** every `.sig` holds the RSA-SHA256 signature over the
hex sha256 of its file, plus the public key (`SIGNATURE`/`CERT`/`END`). This
covers sets, `Latest/*.pkg` and the image. The repository catalogues carry
the same signature inside `packagesite.pkg` and `data.pkg`.
- **Where trust is configured:** `keys/fingerprints/` (ours: trusted and
revoked) and `keys/upstream/` (for changelog/bogons). `gwmirror.py` and
`build.sh finish` both use them. finish refuses any key that is not trusted
there.
- **Rotating the key:**
1. Add the new fingerprint to `trusted/` in the core patch and in
`keys/fingerprints/`.
2. Publish one release signed with the old key that ships the new
fingerprint.
3. Then switch keys and move the old fingerprint to `revoked/`.
## Building a release
### Build host
Builds run natively in a FreeBSD arm64 VM that QEMU emulates (TCG) inside a
rootless podman container on a build host, named by `GW_VMHOST` (ours: a
16-core Ryzen AI Max+ 395 running Bazzite). The build host needs podman, curl,
sha256sum and xz, and no root. `release/vm.sh` runs `release/vmhost.sh`
there over ssh; that script builds the container image (QEMU and the arm64
UEFI firmware, from Debian) on first use and keeps the VM's files in
`~/gwbuild-vm/<osrel>`. The VM's ssh port listens on the build host's
loopback only, and vm.sh reaches it through the build host (ProxyJump).
Why emulated, not cross-built: on 2026-11-18 an amd64 VM cross-built base,
kernel and xtools in 64 minutes, but tools builds ports in an aarch64 chroot
under qemu's user-mode emulation, and no qemu-user-static available for
FreeBSD 14 can run cargo there (3.1.0 jumps into unmapped memory; 6.2.50
cannot start FreeBSD 14 programs at all). Every Rust port, py-cryptography
included, failed. Full-system emulation runs a real FreeBSD kernel: slow
(roughly a tenth of native speed), but faithful.
The VM's FreeBSD release must match the series: 15.1 for 26.7 (`OS` in
tools' `config/<series>/build.conf`). A native aarch64 FreeBSD
machine works with the same `build.sh` and no changes.
```sh
# ~/.config/gwmirror/vm.conf, sourced by vm.sh
GW_VMHOST=buildhost # ~/.ssh/config alias of the build host
GW_VM_CPUS=24
GW_VM_MEM=12G # the HTPC's other work needs most of its memory; see Memory below
release/vm.sh create 15.1 # on the build host: official image, checksum verified, grown to 100G
release/vm.sh start 15.1 # first boot applies freebsd-update patches: an hour or more emulated
release/vm.sh setup 15.1 # build.sh setup: host packages, ZFS settings, swap
release/vm.sh sync 15.1 # this repository (with .git) -> /usr/deps
```
- **Image:** the checksums come from download.freebsd.org or, for an old
release, archive.freebsd.org; the image itself from the first of those or
a mirror that has it (archive.freebsd.org at times stops sending).
Stalled transfers are resumed.
- **Disk:** ZFS with zstd compression and autotrim, in a qcow2 file with
copy-on-write disabled (the HTPC's home is btrfs).
- **Setup:** `setup` installs git, python3 and rsync from the frozen package
set of exactly that FreeBSD release.
- **Memory:** the build host backs every page of the VM's memory. On
2026-11-20 a 16 GB VM (18 GB in qemu, 7 GB of it ZFS cache) and the
HTPC's other work ran it out of memory, and it had to be rebooted. So
`setup` caps the VM's ZFS cache at 2 GB, and the VM swaps to a disk of
its own (`swap.qcow2`, `GW_VM_SWAP`, default 16G, serial `gwswap`):
not on ZFS, where swap can deadlock when memory runs out, and past the
host's page cache (`cache=none`). Builds that need more than the VM has
(Rust, LLVM) swap inside the VM instead of pressing on the host.
FreeBSD kills a process that has waited 30 seconds for a free page, and
the emulated VM's pageout can take that long: later that day the Rust
build lost two `llvm-tblgen` that way, 2.8 hours in, with the swap
unused. `setup` turns those kills off (`vm.pfault_oom_attempts=-1`).
On every build host, `build` caps `lang/rust`, which builds its own LLVM
with a job per CPU, at one job per 768 MB of memory (15 in the 12 GB VM,
where 24 did not fit), through tools' `make.conf`.
- **Restarts:** the VM does not start with the build host. After a reboot,
`vm.sh start` it and run `build` again: finished sets are reused. The
ports step writes its set only when it ends (below); `build` first adds
the packages an interrupted step had finished.
### Build, sign, collect
Commit your changes first: `build` refuses a dirty `/usr/deps` unless
`ALLOW_DIRTY=1`.
```sh
release/vm.sh sync 15.1
release/vm.sh run 15.1 build 26.7 26.7.9 # detached; vm.sh log 15.1 to follow
release/vm.sh sign 15.1 26.7 26.7.9 # key into a tmpfs in the VM, finish, key unmounted
release/vm.sh pull-out 15.1 26.7 # -> /scratch/mono-opnsense/out/26.7/{sets,images}
```
**`build`:**
1. Checks out each repository at the release tag, on the branch names tools
insists on. Override per repository with `TOOLS_REF`, `CORE_REF`,
`PORTS_REF`, `PLUGINS_REF` or `SRC_REF` when upstream skipped a tag.
Src is fetched shallow (its single commit, no tags): the build never needs
its history, which is most of its 2 GB. Git never prompts for credentials,
and a transfer that moves nothing for 10 minutes fails the build instead
of hanging. Each checkout must then be at the commit
`config/lock-<version>` gives it (`tools`, `src`, `ports`, `plugins`,
`core`, before our patches): a tag that moved upstream, or a src branch
that moved on, stops the build. Tags are fetched without `--force`, so a
moved tag already fails the fetch. `build.sh lock SERIES VERSION`
resolves the refs and writes the commits to `/root/gwlock-<version>` in
the VM; check them against the upstream tags (`git ls-remote`), then
commit them as `config/lock-<version>`.
2. Applies `patches/<series>/*.patch` to core with `git am`. Core's version
becomes `<release>_<patches>`.
3. Builds base and kernel, then this repository's kernel modules, as an
early check against the new kernel. The kernel set must contain
`boot/kernel/kernel.bin`, the image U-Boot boots: the eMMC image needs
it, and on the gateway `20-kernel-update` skips a kernel set without
one, so the old kernel would go on booting.
4. Builds the ports in one tools ports step over the whole list, tools'
`ports.conf`. Tools caches the build-only dependencies it builds (cmake,
autoconf, the Rust and Go compilers) for the rest of a step only, and the
packages set keeps just the listed ports and their runtime dependencies.
Splitting the list into several steps would rebuild those dependencies in
each one. That cost was measured: a second chunk of 20 started by
rebuilding the autotools the first chunk had already built. The set is
written when the step ends. A reboot of the build host during it leaves
the finished packages only in tools' stage, which the next step clears,
so `build` first adds them to the set: the runtime packages tools had
copied to the stage's packages directory, if the stage belongs to the
same build (series, version and ports commit, kept in
`/var/tmp/gwbuild-ports.run`) and each is a whole package archive. The
build-only dependencies are not kept and get rebuilt. A port that
fails is recorded and the step goes on with the others, then fails at the
end. Tools stops at the first failure only when its step is given an
argument, and `build` gives none. Once the failures are fixed, run `build`
again. Finished sets are reused, and the ports step skips every package
it has built. It does rebuild the build-only dependencies of the ports it
still has to build.
- After each port, tools ran `make clean` to remove its work directories
and its dependencies'. That clean runs each dependency's clean with the
port's own flavor, so a dependency with another flavor, or with none,
looks for the wrong `work-<flavor>` and keeps its work directory.
After a failure, tools removes the dependencies it built. A stale
directory then claims they are installed, so every later port that
needs them fails at once. On 2026-11-20 that happened to Rust ("Couldn't
find required command: cmake") and to libxslt ("libxslt.so - not
found").
- So `build` changes tools' `ports.sh` at checkout: after each port it
removes every work directory (`rm -rf /usr/obj/usr/ports`) instead of
cleaning. The build stops if tools' `ports.sh` no longer has the two
cleans it replaces.
- `config/make-<series>.conf` is added to tools' `make.conf`. Some ports
still download code while they build, at its newest version, and
upstream built them when the release was tagged. It pins
`www/caddy-custom`'s plugins, which xcaddy fetches, at their versions
of the release's tag date: on 2026-11-22 the newest `caddy-l4` needed
a newer Caddy than 26.1's ports tree had, and the port failed. For a
new series or release, pin them
at the release's tag date (`proxy.golang.org/<module>/@v/list` and
`.info`; a module without tags takes the pseudo-version of its last
commit before then).
5. The ports fetch their distfiles as they build. Some no longer download as
recorded in the ports tree's distinfo, chiefly patches GitHub generates
on the fly (`github.com/<owner>/<repo>/commit/<hash>.patch`): GitHub
abbreviates the object names on their `index` lines with more digits as
a repository grows, so an old patch now differs by a few bytes. Codeberg
tag archives (`codeberg.org/<owner>/<repo>/archive/<tag>.tar.gz`) changed
too: Codeberg now compresses them with GNU gzip instead of git's own, and
the same tar comes out smaller. FreeBSD's distfile cache does not help
here. It keeps the originals only of FreeBSD's own ports, so it has
nothing for OPNsense's (e.g. the patches of `opnsense/pkg`). For
`sysutils/sysinfo` it served the new archive as well (2026-11-22).
- Such ports are fetched on the build host with
`release/fetch-distfile.sh`. For a GitHub patch, it shortens the
abbreviations until the size matches distinfo. GitHub turns automated
requests away now and then ("Service Unavailable"), so the current
patch is tried three times, a minute apart. For a Codeberg archive, it
clones the tag and makes the archive with `git archive --format=tar.gz
-6`. Either way, the port's `checksum` target then verifies the
SHA256, so only the original bytes are accepted. The results are
appended to the distfiles set, which
tools extracts into every ports step's chroot. A port whose distfiles
the set has already is skipped, so a rerun downloads nothing for it.
- `opnsense/pkg` (tools' `PKG_ORIGIN`, not `ports-mgmt/pkg`) is fetched
this way first: the ports step's chroot builds pkg before anything
else, and tools needs the same pkg version on the build host
(`pkg -v`), so `build` builds it there too when the version differs
(`vm.sh setup` installs FreeBSD's). Both take its
distfiles from the set, not from GitHub, which turned its patches
away for minutes at a time on 2026-11-20.
- Any other port whose distfiles fail to fetch ("Couldn't fetch it" in
the step's output, `/var/tmp/gwbuild-ports.log`) is fetched this way
and the ports step runs once more. It skips the packages it has
already built, but rebuilds the build-only dependencies of the ports
it still has to build. A distfile that still cannot be fetched
stops the build with the port's name.
- Tools' own `distfiles` step, which would fetch every distfile up front
for offline rebuilds, is not run. It walks the whole dependency tree of
every port again, one `make` at a time: 70 of 266 ports in 9 hours
under emulation. For flavored ports it walks the default flavor's tree
(QEMU's desktop dependencies for `qemu@guestagent`) and fails on a port
the build never needs. Also, its fetch loop records failures at a path
outside its chroot, so the first failure ends the loop.
6. Builds plugins, core and the packages set.
7. Builds the board package against the base set's headers and our libxml2,
and puts it into the packages set.
**`finish`:**
1. Checks the key against `keys/fingerprints/trusted`.
2. Signs base, kernel, packages and aux. Signing the packages set regenerates
the catalogue, so it includes `mono-gateway`. Tools does not do the same
for the aux set: it signs the aux catalogue only in a packages step run
with the key. So `finish` first unpacks the aux set, signs its catalogue
with `pkg repo` and repacks it. `gwmirror verify` found the aux catalogue
unsigned on 2026-11-22.
3. Builds the 5 GB ZFS eMMC image (`mk-image.sh`).
4. Imports the image's pool read-only, without mounting it, and mounts each
dataset read-only by itself. Mounting them all at import does not work:
the pool's own dataset needs a mountpoint inside the read-only root, and
the import then leaves nothing mounted (2026-11-22). Fails if any
non-aarch64 ELF file is found (firmware blobs aside), if a dataset cannot
be mounted, or if the root dataset has no `/bin/sh`, so an empty scan
cannot pass.
5. Compresses and signs the image.
### Board package version
`mono-gateway` is versioned `<release>_<commit count of this repository>`,
e.g. `26.1.11_74`. That always upgrades the previous build, and also the
vendor's `26.1.5_N` packages.
### Hardware flow offload (off by default)
With cmm running, FMan forwards established flows in hardware: pf decides a
flow's first packets, then the hardware forwards the rest with pf's
translation, and pf's states and counters follow it. It is only needed for
multi-gigabit throughput on the 10 GbE ports, so images set
`cmm_enable="NO"` (`rc.d/rc.conf.local`): the board modules load, but
nothing is offloaded until cmm is turned on. Turning it on and off, and its
caveats for users, are in README.md ("Hardware flow offload").
A flow goes into hardware only where that does what pf would have done
(`fastpath/pf_notify/`, `fastpath/cmm/cmm_conn.c`, ARCHITECTURE.md):
- pf passed it in and out, and none of its rules asks for something only pf
does per packet: dup-to, another FIB, a shaper pipe or queue, ALTQ,
`log (all)` or pflow, scrub options, set-tos, max-mss, min-ttl, af-to
(NAT64);
- the routing table sends each direction out of the interface pf's state for
it is on. A route-to or reply-to counts only while it names the same
interface and next hop as the routing table, as OPNsense's automatic
force-gateway and WAN reply-to rules do on a single WAN. Policy routing to
another gateway (a VPN, a second WAN) stays in pf, and a route change
tears down the flows that use the route;
- bridged traffic is offloaded only while pf filters neither the members nor
the bridge (`net.link.bridge.pfil_member` and `pfil_bridge` both 0);
- only offloaded states are made sloppy (no TCP window tracking). A state pf
deletes (close, timeout, `pfctl -k`) takes its hardware flow with it, and
if deletion events are ever lost, cmm drops every hardware flow
(`net.pfnotify.resyncs`).
Offloaded packets never reach the host, so software that watches
interfaces (Suricata, Zenarmor, Insight/NetFlow, tcpdump) misses them, and
so do counters kept in software (VLAN interfaces, pf rules); physical ports
count in hardware, and cmm copies the hardware's counts into pf's states.
IPsec is not offloaded (the vendor's IPsec offload was removed); it runs in
FreeBSD's stack, with CAAM through crypto(9).
A next hop's MAC address goes into CDX when its route is programmed. Every
30 seconds, and after route-socket changes, cmm re-reads the ARP and NDP
tables and tears down routes whose next hop moved to another MAC or left
the table (`cmm_neigh_check()`, `cmm_route_check_neighbors()`): its IP may
belong to another host by then. Neighbors no route uses are not cached.
After updating `mono-gateway` with cmm on, reboot: until then the new cmm
and the loaded `pf_notify.ko` differ, and cmm offloads nothing (it logs
"short pfnotify read").
The vendor's offload, which the security audit of 2026-11-22 found unsafe,
ignored route-to and reply-to, made every pf state sloppy, offloaded bridged
traffic past pf, could keep a hardware flow after its pf state was gone, and
panicked on decrypted IPsec packets. The rework was tested on a gateway on
2026-11-28; the results are in the merge commit (`git log --merges`).
## Stage, verify, publish
```sh
M=/scratch/mono-opnsense/mirror
python3 mirror/gwmirror.py stage --sets /scratch/mono-opnsense/out/26.7 --mirror $M --series 26.7 --version 26.7.9 --upgrade-from 26.1
python3 mirror/gwmirror.py verify --root $M # deep: hashes, signatures, ELF architecture
python3 mirror/gwmirror.py publish --mirror $M --dest /mnt/opnsense-mirror # re-verifies first
python3 mirror/gwmirror.py verify --url https://opnsense.karsttech.com --series FreeBSD:14:aarch64/26.1 --series FreeBSD:15:aarch64/26.7
```
**`stage`** lays one build into the tree above:
- renames the base set;
- extracts the packages and aux sets, skipping tools' dotfile build markers;
- hard-links a MINT snapshot;
- copies the image;
- with `--upgrade-from <series>`, also places this build's sets in that
series' `sets/` as its major upgrade.
**`verify --root`** checks, for each `<ABI>/<series>`:
- the catalogue signatures, and that both catalogues agree;
- every package's path, ABI, size and checksum, and in the main repository
its `Latest/` signature (tools makes `Latest/` for the main repository
only; upstream's aux repository has none either). The catalogue's
checksum is the file's SHA-256 in hex up to pkg 2.3 (26.1), and from
pkg 2.8 (26.7) `2$` and its BLAKE2b-512 in pkg's own base32.
`Latest/` signatures are over the SHA-256 either way, so with a BLAKE2b
catalogue a shallow verify (`--url` without `--deep`) checks only that
they come from a trusted key, as it does for the sets;
- the major upgrade's packages set in the previous series' `sets/`, read
in place as the repository `opnsense-update -P` installs from;
- the set and image signatures against `keys/fingerprints`;
- that every ELF inside every package and set is aarch64. Firmware
directories are excepted, and so is the Go toolchain's source tree
(`/usr/local/go<N>/src/`, in the aux repository), which ships test data
and race-detector objects for every platform.
- that every name can be stored on the SMB share (see "Names on disk");
- that no symlink leads outside the tree or nowhere: `publish` copies with
`rsync -L`, which would publish a link's target.
Nothing is extracted to disk while verifying.
**`verify --url`** also checks:
- the TLS certificate (it must have 21+ days left);
- `/healthz`;
- Content-Length on the sets;
- that no redirect leads elsewhere;
- the proxied changelog/bogons signatures against `keys/upstream`.
`--url` is shallow by default (sizes and signatures, no downloads beyond the
catalogues). `--deep` downloads and hashes everything.
**`publish`** first refuses to delete a series. If the destination has a
directory in its top two levels (`FreeBSD_14_aarch64`,
`FreeBSD_14_aarch64/26.1`, `releases/26.1`) that the staged tree lacks, it
stops before verifying. A series is retired by deleting it from the share by
hand. `publish` then refuses to copy a tree that fails verification, and runs
`rsync -rtL --delay-updates --delete-after`: symlinks become plain files
(SMB keeps none), and clients never see a half-written repository.
The share is mounted on the workstation with the kernel CIFS client (as
root, once; `cifs-utils` installed), owned by the workstation user so rsync
needs no privileges:
```
# /etc/fstab
//<server>/<share>/<folder> /mnt/opnsense-mirror cifs credentials=/home/<user>/.config/gwmirror/smb-credentials,uid=<user>,gid=<user>,vers=3.0,nofail,_netdev 0 0
```
`~/.config/gwmirror/smb-credentials` (mode 0600) holds `username=` and
`password=` lines. The tree goes into a folder of the share (ours: `mirror/`),
and nothing else may live in that folder: `--delete-after` removes it. The
container's `SMB_SHARE` names the same folder (`<share>/mirror`).
### Restoring the staged mirror
The staged tree in `/scratch` is a working copy, and the share holds the
only copy of series that are no longer built (26.1 since 2026-11-28). If
`/scratch` is lost, copy the share back, then re-stage the current build so
its symlinks and hard links return (the rest stays as plain copies, which
verify the same way):
```sh
M=/scratch/mono-opnsense/mirror
mkdir -p $M && rsync -rt /mnt/opnsense-mirror/ $M/
release/vm.sh pull-out 15.1 26.7
python3 mirror/gwmirror.py stage --sets /scratch/mono-opnsense/out/26.7 --mirror $M --series 26.7 --version 26.7.9 --upgrade-from 26.1
python3 mirror/gwmirror.py verify --root $M
rsync -rL -n -i -c --delete-after --exclude='.*' $M/ /mnt/opnsense-mirror/ # prints nothing: publish would change no content
```
## Serving the mirror
`mirror/server/` holds the stack:
- an unprivileged nginx on a read-only root;
- the URL-to-disk name rewrites (see "Names on disk");
- GET/HEAD only, dotfiles hidden, autoindex on;
- the changelog/bogons proxy;
- `/healthz`.
Deploy it as a Portainer stack from this repository (compose path
`mirror/server/docker-compose.yml`), with the SMB share settings as stack
variables. The header of the compose file lists the variables, the
reverse-proxy requirements and the DOCKER-USER rule.
The gateway itself must reach the proxy. If `opnsense.karsttech.com`
resolves to the gateway's own WAN address, add an Unbound host override that
points it at the proxy's LAN IP.
To test locally with podman, serving a staged tree:
```sh
podman build -t opnsense-mirror:local mirror/server
podman run -d --rm --name gwmirror -p 127.0.0.1:18080:8080 -v $M:/srv/mirror:ro \
--read-only --tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges opnsense-mirror:local
python3 mirror/gwmirror.py verify --url http://127.0.0.1:18080 --allow-http --series FreeBSD:14:aarch64/26.1
```
## Migrating a gateway from opnsense.mono.si
Shell commands, run on the gateway over ssh as root. Root's shell there is
csh, which does not take `#` comments typed at the prompt: start `sh` first.
ApolloGuardian was migrated this way on 2026-11-23.
**Before you start:**
- Download a configuration backup (System > Configuration > Backups).
- Have the serial console (115200 baud), or Recovery Linux and the image in
`releases/26.1/`, at hand for the first kernel update.
- `opnsense.karsttech.com` resolves to the public address, which is the
gateway's own WAN address: without an Unbound host override to the
proxy's LAN IP, the gateway connects to its own web GUI. With the
override, the URL depends on the proxy's LAN port (step 4).
**1. Checks.** `opnsense-verify -a` must print `FreeBSD:14:aarch64`,
`opnsense-version -a` `26.1`, and the fetches `ok` and `repo-ok` (add the
proxy's port to the URLs if it is not 443 inside the LAN):
```sh
sh
opnsense-verify -a
opnsense-version -a
fetch -qo - https://opnsense.karsttech.com/healthz
fetch -qo /dev/null https://opnsense.karsttech.com/FreeBSD:14:aarch64/26.1/latest/meta.conf && echo repo-ok
```
**2. Backup and boot environment:**
```sh
B=/root/gwmirror-backup-$(date +%Y%m%d%H%M%S)
mkdir -p $B
cp -p /usr/local/etc/pkg/repos/* $B/
bectl create pre-gwmirror
```
**3. Trust the signing key** (keys/fingerprints/trusted):
```sh
printf 'function: "sha256"\nfingerprint: "5fc1e2bf74e0386a2ea1ee60d085d683735a9d7cd8090647be0f476c779c0dc3"\n' > /usr/local/etc/pkg/fingerprints/OPNsense/trusted/opnsense.karsttech.com.20261117
```
**4. Point the repositories at the mirror.** If the proxy answers on 443
inside the LAN, rewrite the URLs in the repository files and their
`.sample` files (`${ABI}` stays literal):
```sh
cd /usr/local/etc/pkg/repos
for f in OPNsense.conf.sample OPNsense-aux.conf.sample OPNsense.conf OPNsense-aux.conf; do
[ -f $f ] && sed -i '' 's|^\([[:space:]]*url:[[:space:]]*"\)[^"]*\(/${ABI}/\)|\1https://opnsense.karsttech.com\2|' $f
done
cd
```
If the gateway reaches the proxy only on another port (at home Traefik
listens on 444 and the router forwards WAN 443 to it; pf cannot redirect
connections the firewall makes itself), set a custom mirror instead. It is
kept in `config.xml`, and core applies it at every firmware reload
(`opnsense-update -sd -m`), so it survives core updates. The GUI (System >
Firmware > Settings, Mirror "(custom)") did not store it on the vendor's
26.1.9; this did, keeping the previous version in System > Configuration >
History:
```sh
/usr/local/bin/php -r 'require_once("config.inc"); require_once("util.inc"); global $config; $config["system"]["firmware"]["mirror"] = "https://opnsense.karsttech.com:444"; write_config("custom mirror opnsense.karsttech.com:444");'
pluginctl -g system.firmware.mirror
```
The changelog and bogons downloads do not follow a custom mirror:
`opnsense-update -X` reads core's `OPNsense.conf.sample`, which names the
mirror without a port. On such a gateway the GUI changelog does not load
and the bogons list keeps the version it has. Serving the proxy on 443
inside the LAN avoids both.
**5. Drop the vendor's MonoGateway repository** and move `mono-gateway` to
the OPNsense repository (`opnsense-update -P` of a major upgrade only
upgrades that one):
```sh
rm -f /usr/local/etc/pkg/repos/MonoGateway.conf
pkg info -e mono-gateway && pkg annotate -qyM mono-gateway repository OPNsense
```
**6. Reload and check.** `opnsense-update -M` must name the new mirror, and
`pkg update -f` must accept the catalogue ("804 packages processed"; it
fails on a key that is not trusted):
```sh
configctl firmware reload
opnsense-update -M
grep -H url: /usr/local/etc/pkg/repos/OPNsense*.conf
pkg update -f
```
To undo before step 7: `cp -p $B/* /usr/local/etc/pkg/repos/`, remove the
fingerprint file (and the custom mirror, in System > Configuration >
History), `configctl firmware reload`. After step 7: `bectl activate
pre-gwmirror` and reboot.
**7. Update** in System > Firmware > Updates: Check for updates, then
update. This installs our core `26.1.11_2`, then the packages, base and
kernel, and reboots. That core names only our mirror and revokes the
vendor's keys. Besides ours it still trusts upstream's key
(`pkg.opnsense.org.20260120`; `.20260608` in 26.7), which signs the
changelog and bogons sets the mirror passes through from upstream.
**8. Reinstall everything once**, so no vendor-built binary remains, then
reboot:
```sh
sh
opnsense-update -pf
opnsense-update -bkf
reboot
```
**9. Check:**
- `opnsense-version` shows the release, `uname -v` our src fork's commit and
`MONO-GATEWAY`;
- `kldstat` lists cdx, fci and the other board modules (`ina2xx` is built
into the kernel: `kldstat -v | grep ina`), and mwifiex and dpaa_wifi when
the Wi-Fi card is fitted;
- System > Firmware > Status > Audit > Health is clean.
**10. Turn off hardware flow offload** (see "Hardware flow offload (off by
default)"; README.md has how to turn it on later). The vendor image's `/etc/rc.conf.local`
enables cmm and no package manages that file:
```sh
sh
sysrc -f /etc/rc.conf.local cmm_enable=NO
service cmm onestop
pgrep -l cmm || echo cmm-stopped
```
## Major upgrade (26.1 to 26.7)
1. **Kernel fork:** rebase `stable/26.7` of the src fork onto the 26.7.x tag
(see README.md). For 26.7.9 (2026-11-23), Mono's 27 commits on 26.7
rebased onto the tag without conflicts; Mono's tip is tagged
`mono/stable/26.7`. One of them was broken on Mono's 26.7 branch:
"pf: add state creation/destruction notification hooks" also replaced
parts of `pf.c` with older 14.x code (`s->rule.ptr`, the former SCTP and
ICMP cases), which does not compile. It was rebuilt from its 26.1
version: the hook call after each pfsync insert, update and delete call
(five in 26.7's single `pf_test`) and the declarations. To spot such a
commit, compare each commit's insertions and deletions with its 26.1
counterpart (`git show --numstat`); the others matched. FreeBSD 15 also
removed `GEOM_BDE`, so a commit on top drops it from the `GATEWAY` kernel
config. Before building, check the config's options against the new tree:
`config -d /tmp/x GATEWAY` in `sys/arm64/conf` stops at the first unknown
one. A second commit fixes three FreeBSD 15 compile errors in Mono's
code: two `machdep.c` lines that 26.7 no longer needs (upstream defines
`socdev_va` itself and dropped `hcr_el2`), the moved `dev/clk/clk.h`, and
`cpu_dcache_wbinv_range()` now taking a pointer. To find every compile
error in one pass rather than one per build, run tools' `buildkernel`
by hand in the VM with `make -k ... KERNFAST=1` after a failure. A third
commit sets `makeoptions WITH_KERNEL_BIN=t`: FreeBSD 15 builds
`kernel.bin` only when asked, and the 26.7.9 image build was the first
to notice. To rebuild just the kernel set after such a change, remove
it from the VM's `sets/` and run tools' `kernel` step, then `sign`
again.
2. **Core patches:** write `patches/26.7/` against core 26.7.x. For 26.7.9:
- the CMM restart moved from `interfaces_assign.php`, which 26.7 no
longer has, to the MVC assignment API
(`Interfaces/Api/AssignmentController::reconfigureAction`, after its
filter reload);
- the mirror patch applied as is, except for the `plist` lines, where
upstream's trusted key changed (`pkg.opnsense.org.20260608`).
- Also pin `www/caddy-custom`'s plugins at the release's tag date in
`config/make-26.7.conf` (build step 4).
3. **Board package:** fix this repository's drivers for the FreeBSD 15 kernel
interfaces. `build` compiles the modules right after the kernel, so this
fails early. For 26.7: caam's bus resource methods lost their `type`
and `rid` arguments, and `sys/cdefs.h` now defines `__maybe_unused`,
which cdx's `linux_compat.h` also did. The repository then stopped
building 26.1 (its patches and `make-26.1.conf` are gone); the 26.1
tree on the mirror stays, for gateways that still have to upgrade.
4. **Build:** run `vm.sh create 15.1`, then `build 26.7 26.7.x`, `sign` and
`pull-out`.
5. **Stage, verify, publish:**
`gwmirror.py stage ... --series 26.7 --version 26.7.x --upgrade-from 26.1`,
then verify and publish.
6. **Back up:** full eMMC backup from Recovery Linux, or at least a
configuration backup, with the 26.1 image at hand.
7. **Offer the upgrade** on the gateway. Core only offers it once
`packages-26.7.x` is on the mirror (checked in core 26.1.11's check.sh);
`opnsense-update -SRp` prints its size once it is:
```sh
sh
sed -i '' '/^UPGRADE_RELEASE=/d' /usr/local/etc/opnsense-update.conf
echo 'UPGRADE_RELEASE="26.7.x"' >> /usr/local/etc/opnsense-update.conf
opnsense-update -SRp
```
8. **Upgrade in the GUI.** It reboots three times: kernel, then base, then
packages.
- Until the packages stage, the 26.1 board modules don't load under the
26.7 kernel. `01-mono-modules` logs them and carries on, and the
in-kernel DPAA driver keeps the network up.
- At that last stage, the FreeBSD 15 `mono-gateway` package arrives.
## Ongoing releases
- **Point release** (e.g. 26.7.10):
1. Rebase the src fork onto the new tag.
2. Run `build.sh lock` in the VM, check the commits and commit
`config/lock-<version>` (build step 1).
3. Run `build` / `sign` / `pull-out`; tools skips unchanged ports.
4. Run `stage`, `verify`, `publish`.
- **Major release** (27.1 is due January 2027): the procedure above.
- **Board fix between releases:** commit here, then rebuild. The package
version rises with the commit count.
- **Kernel-only fix between releases:** push it to the src fork, update `src`
in `config/lock-<version>`, delete the kernel set in the VM and rebuild,
then republish the same-version kernel set; gateways pick it up with
`opnsense-update -fk`.
## Monitoring
`mirror/monitor/` has a systemd user timer that runs
`gwmirror.py verify --url` daily (install steps in the unit file). Its
failures land in the journal. That is the failure that killed the vendor's
mirror: the certificate is due to be renewed by the proxy, and the timer
complains 21 days before expiry if it isn't.
## Recovery
The kernel is booted by U-Boot from the FAT partition, not from
`/boot/kernel`. After a kernel set update, `rc.syshook.d/stop/20-kernel-update`
installs the new kernel there at shutdown. It keeps the previous one as
`kernel.old`, never leaves `kernel.img` missing, and retries at the next
shutdown if it can't finish. `/boot/kernel/kernel.bin` stays where the kernel
set put it, so the health audit finds the set complete; a shutdown whose
kernel and device tree are on the FAT partition already does nothing. (Up to
`mono-gateway` 26.7.9_116 the hook deleted it, and the audit reported it
missing; `opnsense-update -fk` puts it back.)
If a new kernel doesn't boot, interrupt U-Boot on the serial console:
```
=> load mmc 0:1 ${kernel_addr_r} kernel.old; load mmc 0:1 ${fdt_addr_r} dtb/mono-gateway-dk.old; booti 0x82000000 - 0x88000000
```
Then roll back the boot environment (`bectl activate pre-gwmirror-...`), or
reflash from Recovery Linux with the signed image from `/releases/` (README.md,
"Local / Test Deployment") and restore the configuration backup.
## Tests
```sh
python3 -m unittest discover -s mirror/tests # gwmirror stage/verify/publish, incl. HTTPS
python3 -m unittest discover -s release/tests # build.sh, 20-kernel-update, fetch-distfile.sh
release/vm.sh ssh 15.1 'cd /usr/deps && python3 -m unittest discover -s release/tests'
```
Run `release/tests` on the build VM as well (after `vm.sh sync`): those
scripts run on FreeBSD, whose `grep`, `sed` and `sh` reject things the GNU
tools accept (an empty alternative in a `grep -E` pattern, for one).

View file

@ -1,5 +1,5 @@
# Mono Gateway Development Kit (NXP LS1046A)
# https://mono.vision
# https://mono.si
#
# Boot: U-Boot booti (NOT EFI -- loader.efi broken on this SoC)
# Console: serial 115200 (headless, no video output)
@ -8,7 +8,6 @@
export PRODUCT_KERNEL=GATEWAY
export PRODUCT_TARGET=arm64
export PRODUCT_ARCH=aarch64
export PRODUCT_WANTS_CROSS="aarch64-binutils qemu-user-static"
export PRODUCT_COMSPEED=115200
export HOSTNAME=mono-gateway
export ARM_FAT_SIZE="80m -b 32m"
@ -20,14 +19,12 @@ MONO_GW_DEPS="${MONO_GW_DEPS:-${DEPSDIR}/dist}"
arm_install_uboot()
{
# U-Boot is on QSPI NOR, not SD card. We just need kernel.img
# and DTB on the FAT boot partition for U-Boot to load via booti.
# We need kernel.img and DTB on the FAT boot partition for U-Boot to
# load via booti.
local KERNEL_ELF="${STAGEDIR}/boot/kernel/kernel"
# Convert ELF kernel to ARM64 Image format for U-Boot booti
sh "${DEPSDIR}/mk-kernel-img.sh" \
"${KERNEL_ELF}" "${STAGEDIR}/boot/msdos/kernel.img"
# Move kernel
mv ${STAGEDIR}/boot/kernel/kernel.bin \
${STAGEDIR}/boot/msdos/kernel.img
# Copy device tree binary
mkdir -p ${STAGEDIR}/boot/msdos/dtb
@ -65,48 +62,19 @@ arm_hook()
# rc.d scripts) are delivered via the mono-gateway FreeBSD package.
# Install using the host's pkg via chroot, same mechanism as
# setup_packages() in common.sh. /dev must be mounted for pkg -c.
# The package is also published in the OPNsense repository, so it is
# annotated as coming from there and later updates follow that repo.
local MONO_GW_PKG=$(ls ${MONO_GW_DEPS}/mono-gateway-*.pkg 2>/dev/null | head -1)
if [ -n "${MONO_GW_PKG}" ]; then
cp "${MONO_GW_PKG}" "${STAGEDIR}/tmp/"
mount -t devfs devfs "${STAGEDIR}/dev"
pkg -c "${STAGEDIR}" add "/tmp/$(basename ${MONO_GW_PKG})"
pkg -c "${STAGEDIR}" annotate -qyA mono-gateway repository MonoGateway
pkg -c "${STAGEDIR}" annotate -qyA mono-gateway repository OPNsense
umount "${STAGEDIR}/dev"
rm "${STAGEDIR}/tmp/$(basename ${MONO_GW_PKG})"
else
echo ">>> WARNING: mono-gateway package not found in ${MONO_GW_DEPS}"
echo ">>> Run: make -C opnsense-deps -j24 package"
echo ">>> ERROR: mono-gateway package not found in ${MONO_GW_DEPS}" >&2
echo ">>> Run: make -C /usr/deps package OPS_VERSION=<release>" >&2
return 1
fi
# --- Firmware mirror ---
# Point the update client at our self-hosted mirror which carries
# our custom kernel set and the mono-gateway package.
cat > ${STAGEDIR}/tmp/mirror.xml << 'EOF'
<firmware>
<mirror>https://opnsense.mono.si</mirror>
</firmware>
EOF
sed -i '' -e "/<system>/r ${STAGEDIR}/tmp/mirror.xml" ${STAGEDIR}${CONFIG_XML}
rm ${STAGEDIR}/tmp/mirror.xml
# --- Package repository for mono-gateway ---
# Separate pkg repo so our board-support package is discoverable
# by pkg(8) alongside Walker's OPNsense packages.
local FPDIR="${STAGEDIR}/usr/local/etc/pkg/fingerprints/MonoGateway/trusted"
mkdir -p "${FPDIR}"
cat > "${FPDIR}/opnsense.mono.si.20260227" << 'FPEOF'
function: "sha256"
fingerprint: "81d68eff75025aac679786db4ce9cfe91092adb7e3da3996ab383d9eb8c22e09"
FPEOF
mkdir -p "${STAGEDIR}/usr/local/etc/pkg/repos"
cat > "${STAGEDIR}/usr/local/etc/pkg/repos/MonoGateway.conf" << 'REPOEOF'
MonoGateway: {
fingerprints: "/usr/local/etc/pkg/fingerprints/MonoGateway",
url: "pkg+https://opnsense.mono.si/${ABI}/26.1/MINT/26.1.2/latest",
signature_type: "fingerprints",
priority: 20,
enabled: yes
}
REPOEOF
}

4
config/actions_cmm.conf Normal file
View file

@ -0,0 +1,4 @@
[restart]
command:/usr/local/etc/rc.d/cmm restart
type:script
message:Restarting CMM after interface change

5
config/lock-26.7.9 Normal file
View file

@ -0,0 +1,5 @@
tools 877ba55e86d20c4e66fb56770cb2bfd8538a4c9e
src fe7a7425d403e066146715930a8f191c50b8f9f4
ports 725e9093601820fc4e7e11d6c2e0edf1375f3ea8
plugins a01a2e8cef738b3762830a7bbfc6e857384328f1
core 228ab68d54513046f79bc36d7f583936922d1951

11
config/make-26.7.conf Normal file
View file

@ -0,0 +1,11 @@
# Added to tools' make.conf for the 26.7 ports builds (release/build.sh, ports_make_conf).
#
# xcaddy fetches www/caddy-custom's plugins while it builds, at their newest versions
# unless a version is given. So tools' list, pinned at the
# versions of 2026-11-11, when 26.7.9 was tagged (proxy.golang.org); each one's go.mod
# requires at most the ports tree's caddy 2.11.9. caddy-dynamicdns has no tags: the
# pseudo-version of its last commit before then.
CADDY_CUSTOM_PLUGINS= github.com/mholt/caddy-dynamicdns@v0.0.0-20260805195708-67d107a42c02 \
github.com/mholt/caddy-l4@v0.1.3 \
github.com/mholt/caddy-ratelimit@v0.1.0 \
github.com/caddy-dns/cloudflare@v0.2.4

View file

@ -1,8 +1,11 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* NXP CAAM (Cryptographic Acceleration and Assurance Module) controller driver.
*
* The CAAM controller (SEC v4.0+) acts as a simplebus parent that enumerates
@ -69,7 +72,7 @@ caam_probe(device_t dev)
*
* Used for RNG state handle instantiation during controller attach,
* before any Job Ring child devices are available. Follows the same
* protocol as Linux's run_descriptor_deco0() in ctrl.c.
* protocol described in the NXP SEC reference manual (DECO direct mode).
*
* Returns 0 on success; *status receives the DECO operation status.
*/
@ -171,7 +174,7 @@ caam_run_deco0(struct caam_softc *sc, uint32_t *desc, int nwords,
* Configure the TRNG (True Random Number Generator).
*
* Programs entropy sampling delay, frequency count limits, and
* statistical self-test parameters. Matches Linux's kick_trng().
* statistical self-test parameters per the NXP SEC TRNG specification.
*/
static void
caam_kick_trng(struct caam_softc *sc, uint32_t ent_delay)
@ -244,37 +247,37 @@ caam_build_rng_inst_desc(uint32_t *desc, int handle, int gen_sk)
if (handle == 0 && gen_sk) {
/* SH0 with secure key generation — 7 words */
desc[idx++] = CMD_DESC_HDR | HDR_ONE | 7;
desc[idx++] = CAAM_CMD_DESC_HDR | CAAM_HDR_ONE | 7;
/* Instantiate RNG SH0 with prediction resistance */
desc[idx++] = OP_TYPE_CLASS1_ALG | OP_ALG_ALGSEL_RNG |
OP_ALG_AS_INIT | OP_ALG_PR_ON;
desc[idx++] = CAAM_OP_TYPE_CLASS1_ALG | CAAM_OP_ALG_ALGSEL_RNG |
CAAM_OP_ALG_AS_INIT | CAAM_OP_ALG_PR_ON;
/* JUMP: wait for Class 1 done (skip 1 word) */
desc[idx++] = CMD_JUMP | JUMP_CLASS_CLASS1 | 1;
desc[idx++] = CAAM_CMD_JUMP | CAAM_JUMP_CLASS_CLASS1 | 1;
/* LOAD IMM: write 1 to CLRW to reset done interrupt */
desc[idx++] = CMD_LOAD | LDST_CLASS_DECO | LDST_IMM |
LDST_SRCDST_WORD_CLRW | sizeof(uint32_t);
desc[idx++] = CAAM_CMD_LOAD | CAAM_LDST_CLASS_DECO | CAAM_LDST_IMM |
CAAM_LDST_SRCDST_WORD_CLRW | sizeof(uint32_t);
desc[idx++] = 1;
/* Generate secure keys (JDKEK, TDKEK, TDSK) */
desc[idx++] = OP_TYPE_CLASS1_ALG | OP_ALG_ALGSEL_RNG |
OP_ALG_AAI_RNG4_SK;
desc[idx++] = CAAM_OP_TYPE_CLASS1_ALG | CAAM_OP_ALG_ALGSEL_RNG |
CAAM_OP_ALG_AAI_RNG4_SK;
/* Halt */
desc[idx++] = CMD_JUMP | JUMP_CLASS_CLASS1 | JUMP_TYPE_HALT;
desc[idx++] = CAAM_CMD_JUMP | CAAM_JUMP_CLASS_CLASS1 | CAAM_JUMP_TYPE_HALT;
} else {
/* SH0 without gen_sk or SH1 — 3 words */
desc[idx++] = CMD_DESC_HDR | HDR_ONE | 3;
desc[idx++] = CAAM_CMD_DESC_HDR | CAAM_HDR_ONE | 3;
/* Instantiate RNG with prediction resistance */
desc[idx++] = OP_TYPE_CLASS1_ALG | OP_ALG_ALGSEL_RNG |
((uint32_t)handle << OP_ALG_AAI_SHIFT) |
OP_ALG_AS_INIT | OP_ALG_PR_ON;
desc[idx++] = CAAM_OP_TYPE_CLASS1_ALG | CAAM_OP_ALG_ALGSEL_RNG |
((uint32_t)handle << CAAM_OP_ALG_AAI_SHIFT) |
CAAM_OP_ALG_AS_INIT | CAAM_OP_ALG_PR_ON;
/* Halt */
desc[idx++] = CMD_JUMP | JUMP_CLASS_CLASS1 | JUMP_TYPE_HALT;
desc[idx++] = CAAM_CMD_JUMP | CAAM_JUMP_CLASS_CLASS1 | CAAM_JUMP_TYPE_HALT;
}
return (idx);
@ -294,18 +297,18 @@ caam_build_rng_deinst_desc(uint32_t *desc, uint32_t sh_mask)
{
int idx = 0;
desc[idx++] = CMD_DESC_HDR | HDR_ONE | 3;
desc[idx++] = CAAM_CMD_DESC_HDR | CAAM_HDR_ONE | 3;
/*
* OPERATION: Algorithm RNG, AS=INITFINAL (deinstantiate).
* The sh_mask selects which handles to deinstantiate via AAI bits.
* No prediction resistance flag for deinstantiation.
*/
desc[idx++] = OP_TYPE_CLASS1_ALG | OP_ALG_ALGSEL_RNG |
((uint32_t)sh_mask << OP_ALG_AAI_SHIFT) |
OP_ALG_AS_INITFINAL;
desc[idx++] = CAAM_OP_TYPE_CLASS1_ALG | CAAM_OP_ALG_ALGSEL_RNG |
((uint32_t)sh_mask << CAAM_OP_ALG_AAI_SHIFT) |
CAAM_OP_ALG_AS_INITFINAL;
desc[idx++] = CMD_JUMP | JUMP_CLASS_CLASS1 | JUMP_TYPE_HALT;
desc[idx++] = CAAM_CMD_JUMP | CAAM_JUMP_CLASS_CLASS1 | CAAM_JUMP_TYPE_HALT;
return (idx);
}
@ -337,7 +340,7 @@ caam_rng_init(struct caam_softc *sc)
/*
* Check for handles instantiated WITHOUT prediction resistance.
* U-Boot typically instantiates SH0/SH1 without PR. We need PR
* for OP_ALG_PR_ON in generate descriptors, so deinstantiate
* for CAAM_OP_ALG_PR_ON in generate descriptors, so deinstantiate
* any handle that has IF set but PR clear.
*/
rdsta_if = rdsta & (RDSTA_IF0 | RDSTA_IF1);
@ -508,7 +511,7 @@ caam_attach(device_t dev)
* CAAM registers are ALWAYS big-endian (legacy from PowerPC era),
* regardless of the CPU's byte order.
*
* The detection matches Linux's approach:
* The detection approach:
* 1. Read CSTA with a BE read (safe default for QorIQ)
* 2. If PLEND is set → platform is LE → registers need BE swap
* 3. If PLEND not set → platform is BE → native access works
@ -585,8 +588,7 @@ caam_attach(device_t dev)
* Enable Job Ring processing.
*
* The JRSTART register must be written to start each JR before
* child drivers can submit descriptors. Linux does this in
* caam_ctrl_init (drivers/crypto/caam/ctrl.c).
* child drivers can submit descriptors.
*/
CAAM_WRITE(sc, CAAM_JRSTART,
JRSTART_JR0 | JRSTART_JR1 | JRSTART_JR2 | JRSTART_JR3);
@ -731,8 +733,7 @@ caam_alloc_resource(device_t bus, device_t child, int type, int *rid,
rman_set_type(res, type);
if ((flags & RF_ACTIVE) != 0 &&
bus_activate_resource(child, type, *rid,
res) != 0) {
bus_activate_resource(child, res) != 0) {
rman_release_resource(res);
return (NULL);
}
@ -752,7 +753,7 @@ caam_alloc_resource(device_t bus, device_t child, int type, int *rid,
* The child gets its own bus handle pointing into our VA space.
*/
static int
caam_activate_resource(device_t bus, device_t child, int type, int rid, struct resource *res)
caam_activate_resource(device_t bus, device_t child, struct resource *res)
{
struct caam_softc *sc;
bus_space_handle_t bh;
@ -762,11 +763,11 @@ caam_activate_resource(device_t bus, device_t child, int type, int rid, struct r
sc = device_get_softc(bus);
if (rman_get_type(res) != SYS_RES_MEMORY)
return (bus_generic_activate_resource(bus, child, type, rid, res));
return (bus_generic_activate_resource(bus, child, res));
/* Verify the resource belongs to our rman */
if (rman_is_region_manager(res, &sc->sc_mem_rman) == 0)
return (bus_generic_activate_resource(bus, child, type, rid, res));
return (bus_generic_activate_resource(bus, child, res));
bt = rman_get_bustag(sc->sc_rres);
rv = bus_space_subregion(bt, rman_get_bushandle(sc->sc_rres),
@ -789,7 +790,7 @@ caam_activate_resource(device_t bus, device_t child, int type, int rid, struct r
* Just clear the RF_ACTIVE flag.
*/
static int
caam_deactivate_resource(device_t bus, device_t child, int type, int rid, struct resource *res)
caam_deactivate_resource(device_t bus, device_t child, struct resource *res)
{
struct caam_softc *sc;
@ -797,7 +798,7 @@ caam_deactivate_resource(device_t bus, device_t child, int type, int rid, struct
if (rman_get_type(res) != SYS_RES_MEMORY ||
rman_is_region_manager(res, &sc->sc_mem_rman) == 0)
return (bus_generic_deactivate_resource(bus, child, type, rid, res));
return (bus_generic_deactivate_resource(bus, child, res));
return (rman_deactivate_resource(res));
}
@ -806,7 +807,7 @@ caam_deactivate_resource(device_t bus, device_t child, int type, int rid, struct
* Bus method: release a child's resource.
*/
static int
caam_release_resource(device_t bus, device_t child, int type, int rid, struct resource *res)
caam_release_resource(device_t bus, device_t child, struct resource *res)
{
struct caam_softc *sc;
struct resource_list_entry *rle;
@ -816,10 +817,10 @@ caam_release_resource(device_t bus, device_t child, int type, int rid, struct re
if (rman_get_type(res) != SYS_RES_MEMORY ||
rman_is_region_manager(res, &sc->sc_mem_rman) == 0)
return (bus_generic_rl_release_resource(bus, child, type, rid, res));
return (bus_generic_rl_release_resource(bus, child, res));
if ((rman_get_flags(res) & RF_ACTIVE) != 0) {
rv = bus_deactivate_resource(child, type, rid, res);
rv = bus_deactivate_resource(child, res);
if (rv != 0)
return (rv);
}

View file

@ -1,8 +1,11 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* NXP CAAM (SEC v4.0+) crypto controller — shared types and accessors.
*/

File diff suppressed because it is too large Load diff

View file

@ -1,8 +1,11 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* CAAM opencrypto integration — connects CAAM Job Ring hardware to
* FreeBSD's opencrypto framework for IPsec and kernel crypto.
*
@ -332,15 +335,15 @@ caam_cipher_algtype(int cipher_alg)
switch (cipher_alg) {
case CRYPTO_AES_CBC:
return (OP_ALG_ALGSEL_AES | OP_ALG_AAI_CBC);
return (CAAM_OP_ALG_ALGSEL_AES | CAAM_OP_ALG_AAI_CBC);
case CRYPTO_AES_ICM:
return (OP_ALG_ALGSEL_AES | OP_ALG_AAI_CTR_MOD128);
return (CAAM_OP_ALG_ALGSEL_AES | CAAM_OP_ALG_AAI_CTR_MOD128);
case CRYPTO_AES_XTS:
return (OP_ALG_ALGSEL_AES | OP_ALG_AAI_XTS);
return (CAAM_OP_ALG_ALGSEL_AES | CAAM_OP_ALG_AAI_XTS);
case CRYPTO_DES_CBC:
return (OP_ALG_ALGSEL_DES | OP_ALG_AAI_CBC);
return (CAAM_OP_ALG_ALGSEL_DES | CAAM_OP_ALG_AAI_CBC);
case CRYPTO_3DES_CBC:
return (OP_ALG_ALGSEL_3DES | OP_ALG_AAI_CBC);
return (CAAM_OP_ALG_ALGSEL_3DES | CAAM_OP_ALG_AAI_CBC);
case CRYPTO_NULL_CBC:
return (0); /* No cipher operation */
default:
@ -379,22 +382,22 @@ caam_auth_algsel(int auth_alg)
switch (auth_alg) {
case CRYPTO_SHA1:
case CRYPTO_SHA1_HMAC:
return (OP_ALG_ALGSEL_SHA1);
return (CAAM_OP_ALG_ALGSEL_SHA1);
case CRYPTO_SHA2_224:
case CRYPTO_SHA2_224_HMAC:
return (OP_ALG_ALGSEL_SHA224);
return (CAAM_OP_ALG_ALGSEL_SHA224);
case CRYPTO_SHA2_256:
case CRYPTO_SHA2_256_HMAC:
return (OP_ALG_ALGSEL_SHA256);
return (CAAM_OP_ALG_ALGSEL_SHA256);
case CRYPTO_SHA2_384:
case CRYPTO_SHA2_384_HMAC:
return (OP_ALG_ALGSEL_SHA384);
return (CAAM_OP_ALG_ALGSEL_SHA384);
case CRYPTO_SHA2_512:
case CRYPTO_SHA2_512_HMAC:
return (OP_ALG_ALGSEL_SHA512);
return (CAAM_OP_ALG_ALGSEL_SHA512);
case CRYPTO_MD5:
case CRYPTO_MD5_HMAC:
return (OP_ALG_ALGSEL_MD5);
return (CAAM_OP_ALG_ALGSEL_MD5);
default:
return (0);
}
@ -434,7 +437,10 @@ caam_auth_digest_len(int auth_alg)
/*
* Allocate DMA buffer for pre-computed split key.
* Buffer will be filled by caam_gen_split_key() after allocation.
* Must be called after sess->split_key_pad_len is set.
* Must be called after sess->split_key_pad_len and auth_klen are set:
* caam_gen_split_key() first copies the raw key (up to
* CAAM_MAX_SPLIT_KEY_LEN bytes) into it, which can be longer than the
* split key (32 bytes for MD5, 48 for SHA-1).
*/
int
caam_session_alloc_auth_key_dma(device_t dev, struct caam_session *sess)
@ -442,7 +448,7 @@ caam_session_alloc_auth_key_dma(device_t dev, struct caam_session *sess)
int error;
error = caam_dma_alloc(dev, &sess->auth_key_dma,
sess->split_key_pad_len);
MAX(sess->split_key_pad_len, sess->auth_klen));
if (error != 0)
return (error);
@ -459,8 +465,8 @@ caam_session_alloc_auth_key_dma(device_t dev, struct caam_session *sess)
* 3. Stores the split key to auth_key_dma (FIFO STORE SPLIT_KEK)
*
* This replaces DKP pointer mode which causes DECO watchdog timeouts
* on LS1046A ERA 8. Matches Linux's gen_split_key() approach used
* for ERA < 6 and as a fallback.
* on LS1046A ERA 8. Uses the KEY→HMAC INIT→FIFO STORE sequence
* described in the NXP SEC reference manual for split key derivation.
*
* Must be called after caam_session_alloc_auth_key_dma().
* dev must be a JR device (caam_jr_softc).
@ -514,7 +520,7 @@ caam_gen_split_key(device_t dev, struct caam_session *sess)
/*
* Derive HMAC split key (ipad || opad partial hashes).
* Matches Linux key_gen.c gen_split_key() exactly:
* Hardware-mandated sequence per NXP SEC reference manual:
*
* KEY CLASS2 keylen PTR(auth_key_dma)
* OPERATION CLASS2_ALG algsel HMAC INIT DECRYPT
@ -531,24 +537,24 @@ caam_gen_split_key(device_t dev, struct caam_session *sess)
/* KEY: load raw key into Class 2 key register via DMA pointer */
caam_desc_add_word(desc,
CMD_KEY | KEY_CLASS2 | sess->auth_klen);
CAAM_CMD_KEY | CAAM_KEY_CLASS2 | sess->auth_klen);
caam_desc_add_ptr(desc, sess->auth_key_dma.paddr);
/* OPERATION: HMAC INIT DECRYPT — triggers ipad/opad expansion */
caam_desc_add_word(desc,
CMD_OPERATION | OP_TYPE_CLASS2_ALG |
(sess->auth_algtype & OP_ALG_ALGSEL_MASK) |
OP_ALG_AAI_HMAC | OP_ALG_AS_INIT | OP_ALG_DECRYPT);
CAAM_CMD_OPERATION | CAAM_OP_TYPE_CLASS2_ALG |
(sess->auth_algtype & CAAM_OP_ALG_ALGSEL_MASK) |
CAAM_OP_ALG_AAI_HMAC | CAAM_OP_ALG_AS_INIT | CAAM_OP_ALG_DECRYPT);
/* FIFO LOAD: 0 bytes, CLASS2, MSG, LAST2, IMM — finalize */
caam_desc_add_word(desc,
CMD_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | FIFOLD_IMM |
FIFOLD_TYPE_MSG | FIFOLD_TYPE_LAST2);
CAAM_CMD_FIFO_LOAD | CAAM_FIFOLD_CLASS_CLASS2 | CAAM_FIFOLD_IMM |
CAAM_FIFOLD_TYPE_MSG | CAAM_FIFOLD_TYPE_LAST2);
/* FIFO STORE: extract split key to DMA buffer */
caam_desc_add_word(desc,
CMD_FIFO_STORE | FIFOST_CLASS_CLASS2KEY |
FIFOST_TYPE_SPLIT_KEK | sess->split_key_len);
CAAM_CMD_FIFO_STORE | CAAM_FIFOST_CLASS_CLASS2KEY |
CAAM_FIFOST_TYPE_SPLIT_KEK | sess->split_key_len);
caam_desc_add_ptr(desc, sess->auth_key_dma.paddr);
result.done = 0;
@ -605,7 +611,7 @@ caam_newsession(device_t dev, crypto_session_t cses,
sess->ivlen = AES_GCM_IV_LEN;
sess->icvlen = (csp->csp_auth_mlen != 0) ?
csp->csp_auth_mlen : AES_GCM_TAG_LEN;
sess->cipher_algtype = OP_ALG_ALGSEL_AES | OP_ALG_AAI_GCM;
sess->cipher_algtype = CAAM_OP_ALG_ALGSEL_AES | CAAM_OP_ALG_AAI_GCM;
error = caam_gcm_build_enc_shdesc(sess, dev);
if (error != 0)
@ -643,9 +649,9 @@ caam_newsession(device_t dev, crypto_session_t cses,
sess->auth_klen = csp->csp_auth_klen;
memcpy(sess->auth_key, csp->csp_auth_key, sess->auth_klen);
sess->split_key_len = caam_split_key_len(
sess->auth_algtype & OP_ALG_ALGSEL_MASK);
sess->auth_algtype & CAAM_OP_ALG_ALGSEL_MASK);
sess->split_key_pad_len = caam_split_key_pad_len(
sess->auth_algtype & OP_ALG_ALGSEL_MASK);
sess->auth_algtype & CAAM_OP_ALG_ALGSEL_MASK);
/* Allocate DMA buffer and derive split key via JR */
error = caam_session_alloc_auth_key_dma(dev, sess);
@ -691,9 +697,9 @@ caam_newsession(device_t dev, crypto_session_t cses,
sess->alg_type = CAAM_ALG_HMAC;
sess->auth_klen = csp->csp_auth_klen;
sess->split_key_len = caam_split_key_len(
sess->auth_algtype & OP_ALG_ALGSEL_MASK);
sess->auth_algtype & CAAM_OP_ALG_ALGSEL_MASK);
sess->split_key_pad_len = caam_split_key_pad_len(
sess->auth_algtype & OP_ALG_ALGSEL_MASK);
sess->auth_algtype & CAAM_OP_ALG_ALGSEL_MASK);
memcpy(sess->auth_key, csp->csp_auth_key,
sess->auth_klen);
@ -757,14 +763,9 @@ caam_freesession(device_t dev, crypto_session_t cses)
/* Zero key material before freeing DMA descriptors */
explicit_bzero(sess->enc_key, sizeof(sess->enc_key));
explicit_bzero(sess->auth_key, sizeof(sess->auth_key));
if (sess->auth_key_dma.vaddr != NULL)
explicit_bzero(sess->auth_key_dma.vaddr,
sess->split_key_pad_len);
if (sess->enc_shdesc.vaddr != NULL)
explicit_bzero(sess->enc_shdesc.vaddr, CAAM_DESC_MAX_BYTES);
if (sess->dec_shdesc.vaddr != NULL)
explicit_bzero(sess->dec_shdesc.vaddr, CAAM_DESC_MAX_BYTES);
/* caam_dma_free() zeroes each buffer: the split key, and the shared
descriptors that carry the cipher key inline */
caam_dma_free(&sess->auth_key_dma);
caam_dma_free(&sess->enc_shdesc);
caam_dma_free(&sess->dec_shdesc);

View file

@ -1,8 +1,11 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* CAAM opencrypto integration — per-session and per-request structures.
*/

View file

@ -1,11 +1,14 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* CAAM descriptor command word definitions and construction helpers.
* Based on the NXP SEC v4.x/v5.x descriptor format specification.
* Field encodings match Linux drivers/crypto/caam/desc.h for LS1046A.
* Field encodings from the NXP SEC v5.x descriptor format specification
* (document SECMCRM, LS1046A variant).
*
* Descriptors are arrays of uint32_t words in DMA memory, accessed by
* CAAM directly. All words are stored in CAAM byte order (BE on LS1046A).
@ -23,64 +26,64 @@
/*
* Descriptor Command Types (bits 31:27)
*/
#define CMD_SHIFT 27
#define CMD_MASK (0x1fU << CMD_SHIFT)
#define CAAM_CMD_SHIFT 27
#define CAAM_CMD_MASK (0x1fU << CAAM_CMD_SHIFT)
#define CMD_KEY (0x00U << CMD_SHIFT) /* KEY command */
#define CMD_SEQ_KEY (0x01U << CMD_SHIFT) /* SEQ KEY */
#define CMD_LOAD (0x02U << CMD_SHIFT) /* LOAD command */
#define CMD_SEQ_LOAD (0x03U << CMD_SHIFT)
#define CMD_FIFO_LOAD (0x04U << CMD_SHIFT) /* FIFO LOAD */
#define CMD_SEQ_FIFO_LOAD (0x05U << CMD_SHIFT)
#define CMD_STORE (0x0aU << CMD_SHIFT) /* STORE command */
#define CMD_SEQ_STORE (0x0bU << CMD_SHIFT)
#define CMD_FIFO_STORE (0x0cU << CMD_SHIFT) /* FIFO STORE */
#define CMD_SEQ_FIFO_STORE (0x0dU << CMD_SHIFT)
#define CMD_MOVE (0x0fU << CMD_SHIFT)
#define CMD_OPERATION (0x10U << CMD_SHIFT) /* OPERATION command */
#define CMD_SIGNATURE (0x12U << CMD_SHIFT)
#define CMD_JUMP (0x14U << CMD_SHIFT)
#define CMD_MATH (0x15U << CMD_SHIFT)
#define CMD_DESC_HDR (0x16U << CMD_SHIFT) /* Job Descriptor Header */
#define CMD_SH_DESC_HDR (0x17U << CMD_SHIFT) /* Shared Descriptor Hdr */
#define CMD_SEQ_IN_PTR (0x1eU << CMD_SHIFT) /* Seq Input Pointer */
#define CMD_SEQ_OUT_PTR (0x1fU << CMD_SHIFT) /* Seq Output Pointer */
#define CAAM_CMD_KEY (0x00U << CAAM_CMD_SHIFT) /* KEY command */
#define CAAM_CMD_SEQ_KEY (0x01U << CAAM_CMD_SHIFT) /* SEQ KEY */
#define CAAM_CMD_LOAD (0x02U << CAAM_CMD_SHIFT) /* LOAD command */
#define CAAM_CMD_SEQ_LOAD (0x03U << CAAM_CMD_SHIFT)
#define CAAM_CMD_FIFO_LOAD (0x04U << CAAM_CMD_SHIFT) /* FIFO LOAD */
#define CAAM_CMD_SEQ_FIFO_LOAD (0x05U << CAAM_CMD_SHIFT)
#define CAAM_CMD_STORE (0x0aU << CAAM_CMD_SHIFT) /* STORE command */
#define CAAM_CMD_SEQ_STORE (0x0bU << CAAM_CMD_SHIFT)
#define CAAM_CMD_FIFO_STORE (0x0cU << CAAM_CMD_SHIFT) /* FIFO STORE */
#define CAAM_CMD_SEQ_FIFO_STORE (0x0dU << CAAM_CMD_SHIFT)
#define CAAM_CMD_MOVE (0x0fU << CAAM_CMD_SHIFT)
#define CAAM_CMD_OPERATION (0x10U << CAAM_CMD_SHIFT) /* OPERATION command */
#define CAAM_CMD_SIGNATURE (0x12U << CAAM_CMD_SHIFT)
#define CAAM_CMD_JUMP (0x14U << CAAM_CMD_SHIFT)
#define CAAM_CMD_MATH (0x15U << CAAM_CMD_SHIFT)
#define CAAM_CMD_DESC_HDR (0x16U << CAAM_CMD_SHIFT) /* Job Descriptor Header */
#define CAAM_CMD_SH_DESC_HDR (0x17U << CAAM_CMD_SHIFT) /* Shared Descriptor Hdr */
#define CAAM_CMD_SEQ_IN_PTR (0x1eU << CAAM_CMD_SHIFT) /* Seq Input Pointer */
#define CAAM_CMD_SEQ_OUT_PTR (0x1fU << CAAM_CMD_SHIFT) /* Seq Output Pointer */
/*
* Job Descriptor Header (word 0)
*
* Bits 31:27 = 0x16 (CMD_DESC_HDR)
* Bits 31:27 = 0x16 (CAAM_CMD_DESC_HDR)
* Bit 23 = ONE (must be set)
* Bits 21:16 = Start Index
* Bit 12 = SHARED (next item is shared desc pointer)
* Bits 11:8 = SHARE type
* Bits 6:0 = Descriptor length in words
*/
#define HDR_ONE (1U << 23)
#define HDR_START_IDX_SHIFT 16
#define HDR_START_IDX_MASK (0x3fU << HDR_START_IDX_SHIFT)
#define HDR_DESCLEN_MASK 0x0000007f
#define HDR_JD_LENGTH_MASK HDR_DESCLEN_MASK
#define HDR_SHARED (1U << 12) /* JD: shared desc ptr follows */
#define HDR_SAVECTX HDR_SHARED /* SH_DESC: save context */
#define HDR_REVERSE (1U << 11)
#define CAAM_HDR_ONE (1U << 23)
#define CAAM_HDR_START_IDX_SHIFT 16
#define CAAM_HDR_START_IDX_MASK (0x3fU << CAAM_HDR_START_IDX_SHIFT)
#define CAAM_HDR_DESCLEN_MASK 0x0000007f
#define CAAM_HDR_JD_LENGTH_MASK CAAM_HDR_DESCLEN_MASK
#define CAAM_HDR_SHARED (1U << 12) /* JD: shared desc ptr follows */
#define CAAM_HDR_SAVECTX CAAM_HDR_SHARED /* SH_DESC: save context */
#define CAAM_HDR_REVERSE (1U << 11)
/*
* SHR (Sharing domain) field — bits 10:8 (JD) / 9:8 (shared desc).
* Controls how the DECO caches the shared descriptor across invocations.
* Matches Linux drivers/crypto/caam/desc.h HDR_SD_SHARE_SHIFT = 8.
* Share field starts at bit 8 per SEC descriptor format spec.
*/
#define HDR_SHARE_SHIFT 8
#define HDR_SHARE_MASK (0x07U << HDR_SHARE_SHIFT)
#define HDR_SHARE_NEVER (0x00U << HDR_SHARE_SHIFT)
#define HDR_SHARE_WAIT (0x01U << HDR_SHARE_SHIFT)
#define HDR_SHARE_SERIAL (0x02U << HDR_SHARE_SHIFT)
#define HDR_SHARE_ALWAYS (0x03U << HDR_SHARE_SHIFT)
#define HDR_SHARE_DEFER (0x04U << HDR_SHARE_SHIFT)
#define CAAM_HDR_SHARE_SHIFT 8
#define CAAM_HDR_SHARE_MASK (0x07U << CAAM_HDR_SHARE_SHIFT)
#define CAAM_HDR_SHARE_NEVER (0x00U << CAAM_HDR_SHARE_SHIFT)
#define CAAM_HDR_SHARE_WAIT (0x01U << CAAM_HDR_SHARE_SHIFT)
#define CAAM_HDR_SHARE_SERIAL (0x02U << CAAM_HDR_SHARE_SHIFT)
#define CAAM_HDR_SHARE_ALWAYS (0x03U << CAAM_HDR_SHARE_SHIFT)
#define CAAM_HDR_SHARE_DEFER (0x04U << CAAM_HDR_SHARE_SHIFT)
/* Shared Descriptor Header */
#define SHR_HDR_DESCLEN_MASK 0x0000003f
#define SHR_HDR_START_IDX_SHIFT 16
#define CAAM_SHR_HDR_DESCLEN_MASK 0x0000003f
#define CAAM_SHR_HDR_START_IDX_SHIFT 16
/*
* KEY Command (bits 31:27 = 0x00)
@ -93,17 +96,17 @@
* Bits 17:16 = KDEST (00=class reg, 01=PKHA_E, 10=AFHA_SBOX, 11=MDHA split)
* Bits 9:0 = Key length
*/
#define KEY_CLASS_SHIFT 25
#define KEY_CLASS1 (0x01U << KEY_CLASS_SHIFT) /* 0x02000000 */
#define KEY_CLASS2 (0x02U << KEY_CLASS_SHIFT) /* 0x04000000 */
#define KEY_IMM (1U << 23)
#define KEY_ENC (1U << 22)
#define KEY_DEST_SHIFT 16
#define KEY_DEST_CLASS_REG (0x00U << KEY_DEST_SHIFT) /* Class key register */
#define KEY_DEST_PKHA_E (0x01U << KEY_DEST_SHIFT) /* PKHA E register */
#define KEY_DEST_AFHA_SBOX (0x02U << KEY_DEST_SHIFT) /* AFHA S-box */
#define KEY_DEST_MDHA_SPLIT (0x03U << KEY_DEST_SHIFT) /* MDHA split key */
#define KEY_LENGTH_MASK 0x000003ff
#define CAAM_KEY_CLASS_SHIFT 25
#define CAAM_KEY_CLASS1 (0x01U << CAAM_KEY_CLASS_SHIFT) /* 0x02000000 */
#define CAAM_KEY_CLASS2 (0x02U << CAAM_KEY_CLASS_SHIFT) /* 0x04000000 */
#define CAAM_KEY_IMM (1U << 23)
#define CAAM_KEY_ENC (1U << 22)
#define CAAM_KEY_DEST_SHIFT 16
#define CAAM_KEY_DEST_CLASS_REG (0x00U << CAAM_KEY_DEST_SHIFT) /* Class key register */
#define CAAM_KEY_DEST_PKHA_E (0x01U << CAAM_KEY_DEST_SHIFT) /* PKHA E register */
#define CAAM_KEY_DEST_AFHA_SBOX (0x02U << CAAM_KEY_DEST_SHIFT) /* AFHA S-box */
#define CAAM_KEY_DEST_MDHA_SPLIT (0x03U << CAAM_KEY_DEST_SHIFT) /* MDHA split key */
#define CAAM_KEY_LENGTH_MASK 0x000003ff
/*
* LOAD / SEQ LOAD / STORE / SEQ STORE commands
@ -114,94 +117,94 @@
* Bits 15:8 = OFFSET (byte offset within register)
* Bits 7:0 = LENGTH (byte count)
*/
#define LDST_CLASS_SHIFT 25
#define LDST_CLASS_IND_CCB (0x00U << LDST_CLASS_SHIFT)
#define LDST_CLASS_1_CCB (0x01U << LDST_CLASS_SHIFT)
#define LDST_CLASS_2_CCB (0x02U << LDST_CLASS_SHIFT)
#define LDST_CLASS_DECO (0x03U << LDST_CLASS_SHIFT)
#define CAAM_LDST_CLASS_SHIFT 25
#define CAAM_LDST_CLASS_IND_CCB (0x00U << CAAM_LDST_CLASS_SHIFT)
#define CAAM_LDST_CLASS_1_CCB (0x01U << CAAM_LDST_CLASS_SHIFT)
#define CAAM_LDST_CLASS_2_CCB (0x02U << CAAM_LDST_CLASS_SHIFT)
#define CAAM_LDST_CLASS_DECO (0x03U << CAAM_LDST_CLASS_SHIFT)
#define LDST_IMM (1U << 23)
#define CAAM_LDST_IMM (1U << 23)
#define LDST_SRCDST_SHIFT 16
#define LDST_SRCDST_BYTE_CONTEXT (0x20U << LDST_SRCDST_SHIFT) /* Context reg */
#define LDST_SRCDST_BYTE_KEY (0x40U << LDST_SRCDST_SHIFT) /* Key reg */
#define CAAM_LDST_SRCDST_SHIFT 16
#define CAAM_LDST_SRCDST_BYTE_CONTEXT (0x20U << CAAM_LDST_SRCDST_SHIFT) /* Context reg */
#define CAAM_LDST_SRCDST_BYTE_KEY (0x40U << CAAM_LDST_SRCDST_SHIFT) /* Key reg */
/* DECO register destinations (used with LDST_CLASS_DECO) */
#define LDST_SRCDST_WORD_CLRW (0x08U << LDST_SRCDST_SHIFT)
#define LDST_SRCDST_WORD_DECO_MATH0 (0x08U << LDST_SRCDST_SHIFT)
#define LDST_SRCDST_WORD_DECO_MATH1 (0x09U << LDST_SRCDST_SHIFT)
#define LDST_SRCDST_WORD_DECO_MATH2 (0x0aU << LDST_SRCDST_SHIFT)
#define LDST_SRCDST_WORD_DECO_MATH3 (0x0bU << LDST_SRCDST_SHIFT)
#define LDST_SRCDST_WORD_DECO_AAD_SZ LDST_SRCDST_WORD_DECO_MATH3
/* DECO register destinations (used with CAAM_LDST_CLASS_DECO) */
#define CAAM_LDST_SRCDST_WORD_CLRW (0x08U << CAAM_LDST_SRCDST_SHIFT)
#define CAAM_LDST_SRCDST_WORD_DECO_MATH0 (0x08U << CAAM_LDST_SRCDST_SHIFT)
#define CAAM_LDST_SRCDST_WORD_DECO_MATH1 (0x09U << CAAM_LDST_SRCDST_SHIFT)
#define CAAM_LDST_SRCDST_WORD_DECO_MATH2 (0x0aU << CAAM_LDST_SRCDST_SHIFT)
#define CAAM_LDST_SRCDST_WORD_DECO_MATH3 (0x0bU << CAAM_LDST_SRCDST_SHIFT)
#define CAAM_LDST_SRCDST_WORD_DECO_AAD_SZ CAAM_LDST_SRCDST_WORD_DECO_MATH3
#define LDST_OFFSET_SHIFT 8
#define LDST_OFFSET_MASK (0xffU << LDST_OFFSET_SHIFT)
#define CAAM_LDST_OFFSET_SHIFT 8
#define CAAM_LDST_OFFSET_MASK (0xffU << CAAM_LDST_OFFSET_SHIFT)
#define LDST_LEN_SHIFT 0
#define LDST_LEN_MASK 0x000000ff
#define CAAM_LDST_LEN_SHIFT 0
#define CAAM_LDST_LEN_MASK 0x000000ff
/*
* OPERATION Command (bits 31:27 = 0x10)
*/
#define OP_TYPE_SHIFT 24
#define OP_TYPE_MASK (0x07U << OP_TYPE_SHIFT)
#define OP_TYPE_CLASS1 (0x02U << OP_TYPE_SHIFT)
#define OP_TYPE_CLASS2 (0x04U << OP_TYPE_SHIFT)
#define OP_TYPE_UNI_PROTOCOL (0x00U << OP_TYPE_SHIFT)
#define OP_TYPE_CLASS1_ALG OP_TYPE_CLASS1
#define OP_TYPE_CLASS2_ALG OP_TYPE_CLASS2
#define CAAM_OP_TYPE_SHIFT 24
#define CAAM_OP_TYPE_MASK (0x07U << CAAM_OP_TYPE_SHIFT)
#define CAAM_OP_TYPE_CLASS1 (0x02U << CAAM_OP_TYPE_SHIFT)
#define CAAM_OP_TYPE_CLASS2 (0x04U << CAAM_OP_TYPE_SHIFT)
#define CAAM_OP_TYPE_UNI_PROTOCOL (0x00U << CAAM_OP_TYPE_SHIFT)
#define CAAM_OP_TYPE_CLASS1_ALG CAAM_OP_TYPE_CLASS1
#define CAAM_OP_TYPE_CLASS2_ALG CAAM_OP_TYPE_CLASS2
/* Algorithm selectors (bits 23:16) */
#define OP_ALG_ALGSEL_SHIFT 16
#define OP_ALG_ALGSEL_MASK (0xffU << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_SUBMASK (0x0fU << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_AES (0x10U << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_DES (0x20U << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_3DES (0x21U << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_MD5 (0x40U << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_SHA1 (0x41U << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_SHA224 (0x42U << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_SHA256 (0x43U << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_SHA384 (0x44U << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_SHA512 (0x45U << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_RNG (0x50U << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_CHACHA20 (0xd0U << OP_ALG_ALGSEL_SHIFT)
#define OP_ALG_ALGSEL_POLY1305 (0xe0U << OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_SHIFT 16
#define CAAM_OP_ALG_ALGSEL_MASK (0xffU << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_SUBMASK (0x0fU << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_AES (0x10U << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_DES (0x20U << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_3DES (0x21U << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_MD5 (0x40U << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_SHA1 (0x41U << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_SHA224 (0x42U << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_SHA256 (0x43U << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_SHA384 (0x44U << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_SHA512 (0x45U << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_RNG (0x50U << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_CHACHA20 (0xd0U << CAAM_OP_ALG_ALGSEL_SHIFT)
#define CAAM_OP_ALG_ALGSEL_POLY1305 (0xe0U << CAAM_OP_ALG_ALGSEL_SHIFT)
/* Additional Algorithm Info (AAI) — bits 12:4 */
#define OP_ALG_AAI_SHIFT 4
#define OP_ALG_AAI_MASK (0x1ffU << OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_SHIFT 4
#define CAAM_OP_ALG_AAI_MASK (0x1ffU << CAAM_OP_ALG_AAI_SHIFT)
/* AES modes */
#define OP_ALG_AAI_CTR_MOD128 (0x00U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_CBC (0x10U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_ECB (0x20U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_CFB (0x30U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_OFB (0x40U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_XTS (0x50U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_CMAC (0x60U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_CCM (0x80U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_GCM (0x90U << OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_CTR_MOD128 (0x00U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_CBC (0x10U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_ECB (0x20U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_CFB (0x30U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_OFB (0x40U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_XTS (0x50U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_CMAC (0x60U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_CCM (0x80U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_GCM (0x90U << CAAM_OP_ALG_AAI_SHIFT)
/* Hash modes */
#define OP_ALG_AAI_HASH (0x00U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_HMAC (0x01U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_SMAC (0x02U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_HMAC_PRECOMP (0x04U << OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_HASH (0x00U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_HMAC (0x01U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_SMAC (0x02U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_HMAC_PRECOMP (0x04U << CAAM_OP_ALG_AAI_SHIFT)
/* Decrypt key derivation */
#define OP_ALG_AAI_DK (0x100U << OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_DK (0x100U << CAAM_OP_ALG_AAI_SHIFT)
/* RNG modes */
#define OP_ALG_AAI_RNG (0x00U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_RNG4_SH_0 (0x00U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_RNG4_SH_1 (0x01U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_RNG4_PS (0x40U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_RNG4_AI (0x80U << OP_ALG_AAI_SHIFT)
#define OP_ALG_AAI_RNG4_SK (0x100U << OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_RNG (0x00U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_RNG4_SH_0 (0x00U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_RNG4_SH_1 (0x01U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_RNG4_PS (0x40U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_RNG4_AI (0x80U << CAAM_OP_ALG_AAI_SHIFT)
#define CAAM_OP_ALG_AAI_RNG4_SK (0x100U << CAAM_OP_ALG_AAI_SHIFT)
/*
* Derived Key Protocol (DKP) — protocol info for OP_TYPE_UNI_PROTOCOL.
* Derived Key Protocol (DKP) — protocol info for CAAM_OP_TYPE_UNI_PROTOCOL.
* Used on ERA >= 6 to compute HMAC split keys inline in the descriptor.
*/
#define OP_PCL_DKP_SRC_IMM (0U << 14) /* Source key inline */
@ -210,21 +213,21 @@
#define OP_PCL_DKP_DST_PTR (1U << 12) /* Derived key via DMA pointer */
/* Algorithm State (bits 3:2) */
#define OP_ALG_AS_SHIFT 2
#define OP_ALG_AS_MASK (0x03U << OP_ALG_AS_SHIFT)
#define OP_ALG_AS_UPDATE (0x00U << OP_ALG_AS_SHIFT)
#define OP_ALG_AS_INIT (0x01U << OP_ALG_AS_SHIFT)
#define OP_ALG_AS_FINALIZE (0x02U << OP_ALG_AS_SHIFT)
#define OP_ALG_AS_INITFINAL (0x03U << OP_ALG_AS_SHIFT)
#define CAAM_OP_ALG_AS_SHIFT 2
#define CAAM_OP_ALG_AS_MASK (0x03U << CAAM_OP_ALG_AS_SHIFT)
#define CAAM_OP_ALG_AS_UPDATE (0x00U << CAAM_OP_ALG_AS_SHIFT)
#define CAAM_OP_ALG_AS_INIT (0x01U << CAAM_OP_ALG_AS_SHIFT)
#define CAAM_OP_ALG_AS_FINALIZE (0x02U << CAAM_OP_ALG_AS_SHIFT)
#define CAAM_OP_ALG_AS_INITFINAL (0x03U << CAAM_OP_ALG_AS_SHIFT)
/* ICV check / Prediction Resistance (bit 1 — context-dependent) */
#define OP_ALG_ICV_OFF (0U << 1)
#define OP_ALG_ICV_ON (1U << 1)
#define OP_ALG_PR_ON (1U << 1) /* RNG: prediction resistance */
#define CAAM_OP_ALG_ICV_OFF (0U << 1)
#define CAAM_OP_ALG_ICV_ON (1U << 1)
#define CAAM_OP_ALG_PR_ON (1U << 1) /* RNG: prediction resistance */
/* Direction (bit 0) */
#define OP_ALG_DECRYPT 0
#define OP_ALG_ENCRYPT 1
#define CAAM_OP_ALG_DECRYPT 0
#define CAAM_OP_ALG_ENCRYPT 1
/*
* SEQ IN PTR / SEQ OUT PTR Commands
@ -256,39 +259,39 @@
* Data types: MSG=010, IV=100, AAD=110, ICV=111
* Actions: FLUSH1=001, LAST1=010, LAST2=100, etc.
*/
#define FIFOLD_CLASS_SHIFT 25
#define FIFOLD_CLASS_SKIP (0x00U << FIFOLD_CLASS_SHIFT)
#define FIFOLD_CLASS_CLASS1 (0x01U << FIFOLD_CLASS_SHIFT)
#define FIFOLD_CLASS_CLASS2 (0x02U << FIFOLD_CLASS_SHIFT)
#define FIFOLD_CLASS_BOTH (0x03U << FIFOLD_CLASS_SHIFT)
#define CAAM_FIFOLD_CLASS_SHIFT 25
#define CAAM_FIFOLD_CLASS_SKIP (0x00U << CAAM_FIFOLD_CLASS_SHIFT)
#define CAAM_FIFOLD_CLASS_CLASS1 (0x01U << CAAM_FIFOLD_CLASS_SHIFT)
#define CAAM_FIFOLD_CLASS_CLASS2 (0x02U << CAAM_FIFOLD_CLASS_SHIFT)
#define CAAM_FIFOLD_CLASS_BOTH (0x03U << CAAM_FIFOLD_CLASS_SHIFT)
#define FIFOLDST_VLF (1U << 24) /* Variable length (SEQ FIFO) */
#define FIFOLDST_SGF FIFOLDST_VLF /* Alias */
#define FIFOLD_IMM (1U << 23)
#define FIFOLDST_EXT (1U << 22)
#define CAAM_FIFOLDST_VLF (1U << 24) /* Variable length (SEQ FIFO) */
#define CAAM_FIFOLDST_SGF CAAM_FIFOLDST_VLF /* Alias */
#define CAAM_FIFOLD_IMM (1U << 23)
#define CAAM_FIFOLDST_EXT (1U << 22)
#define FIFOLD_TYPE_SHIFT 16
#define FIFOLD_TYPE_MASK (0x3fU << FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_SHIFT 16
#define CAAM_FIFOLD_TYPE_MASK (0x3fU << CAAM_FIFOLD_TYPE_SHIFT)
/* Data types (upper 3 bits of TYPE) */
#define FIFOLD_TYPE_MSG (0x10U << FIFOLD_TYPE_SHIFT)
#define FIFOLD_TYPE_MSG1OUT2 (0x18U << FIFOLD_TYPE_SHIFT)
#define FIFOLD_TYPE_IV (0x20U << FIFOLD_TYPE_SHIFT)
#define FIFOLD_TYPE_BITDATA (0x28U << FIFOLD_TYPE_SHIFT)
#define FIFOLD_TYPE_AAD (0x30U << FIFOLD_TYPE_SHIFT)
#define FIFOLD_TYPE_ICV (0x38U << FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_MSG (0x10U << CAAM_FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_MSG1OUT2 (0x18U << CAAM_FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_IV (0x20U << CAAM_FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_BITDATA (0x28U << CAAM_FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_AAD (0x30U << CAAM_FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_ICV (0x38U << CAAM_FIFOLD_TYPE_SHIFT)
/* Action bits (lower 3 bits of TYPE, OR'd with data type) */
#define FIFOLD_TYPE_NOACTION (0x00U << FIFOLD_TYPE_SHIFT)
#define FIFOLD_TYPE_FLUSH1 (0x01U << FIFOLD_TYPE_SHIFT)
#define FIFOLD_TYPE_LAST1 (0x02U << FIFOLD_TYPE_SHIFT)
#define FIFOLD_TYPE_LAST2FLUSH (0x03U << FIFOLD_TYPE_SHIFT)
#define FIFOLD_TYPE_LAST2 (0x04U << FIFOLD_TYPE_SHIFT)
#define FIFOLD_TYPE_LAST2FLUSH1 (0x05U << FIFOLD_TYPE_SHIFT)
#define FIFOLD_TYPE_LASTBOTH (0x06U << FIFOLD_TYPE_SHIFT)
#define FIFOLD_TYPE_LASTBOTHFL (0x07U << FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_NOACTION (0x00U << CAAM_FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_FLUSH1 (0x01U << CAAM_FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_LAST1 (0x02U << CAAM_FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_LAST2FLUSH (0x03U << CAAM_FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_LAST2 (0x04U << CAAM_FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_LAST2FLUSH1 (0x05U << CAAM_FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_LASTBOTH (0x06U << CAAM_FIFOLD_TYPE_SHIFT)
#define CAAM_FIFOLD_TYPE_LASTBOTHFL (0x07U << CAAM_FIFOLD_TYPE_SHIFT)
#define FIFOLDST_LEN_MASK 0x0000ffff
#define CAAM_FIFOLDST_LEN_MASK 0x0000ffff
/*
* FIFO STORE / SEQ FIFO STORE commands
@ -299,18 +302,18 @@
* Bits 21:16 = TYPE
* Bits 15:0 = LENGTH
*/
#define FIFOST_CLASS_SHIFT 25
#define FIFOST_CLASS_NORMAL (0x00U << FIFOST_CLASS_SHIFT)
#define FIFOST_CLASS_CLASS1KEY (0x01U << FIFOST_CLASS_SHIFT)
#define FIFOST_CLASS_CLASS2KEY (0x02U << FIFOST_CLASS_SHIFT)
#define CAAM_FIFOST_CLASS_SHIFT 25
#define CAAM_FIFOST_CLASS_NORMAL (0x00U << CAAM_FIFOST_CLASS_SHIFT)
#define CAAM_FIFOST_CLASS_CLASS1KEY (0x01U << CAAM_FIFOST_CLASS_SHIFT)
#define CAAM_FIFOST_CLASS_CLASS2KEY (0x02U << CAAM_FIFOST_CLASS_SHIFT)
#define FIFOST_TYPE_SHIFT 16
#define FIFOST_TYPE_MASK (0x3fU << FIFOST_TYPE_SHIFT)
#define FIFOST_TYPE_MESSAGE_DATA (0x30U << FIFOST_TYPE_SHIFT)
#define FIFOST_TYPE_RNGSTORE (0x34U << FIFOST_TYPE_SHIFT)
#define FIFOST_TYPE_RNGFIFO (0x35U << FIFOST_TYPE_SHIFT)
#define FIFOST_TYPE_SPLIT_KEK (0x26U << FIFOST_TYPE_SHIFT)
#define FIFOST_TYPE_SKIP (0x3fU << FIFOST_TYPE_SHIFT)
#define CAAM_FIFOST_TYPE_SHIFT 16
#define CAAM_FIFOST_TYPE_MASK (0x3fU << CAAM_FIFOST_TYPE_SHIFT)
#define CAAM_FIFOST_TYPE_MESSAGE_DATA (0x30U << CAAM_FIFOST_TYPE_SHIFT)
#define CAAM_FIFOST_TYPE_RNGSTORE (0x34U << CAAM_FIFOST_TYPE_SHIFT)
#define CAAM_FIFOST_TYPE_RNGFIFO (0x35U << CAAM_FIFOST_TYPE_SHIFT)
#define CAAM_FIFOST_TYPE_SPLIT_KEK (0x26U << CAAM_FIFOST_TYPE_SHIFT)
#define CAAM_FIFOST_TYPE_SKIP (0x3fU << CAAM_FIFOST_TYPE_SHIFT)
/*
* JUMP Command
@ -322,45 +325,45 @@
* Bits 15:8 = COND (condition flags)
* Bits 7:0 = OFFSET (signed)
*/
#define JUMP_CLASS_SHIFT 25
#define JUMP_CLASS_NONE 0
#define JUMP_CLASS_CLASS1 (1U << JUMP_CLASS_SHIFT)
#define JUMP_CLASS_CLASS2 (2U << JUMP_CLASS_SHIFT)
#define JUMP_CLASS_BOTH (3U << JUMP_CLASS_SHIFT)
#define CAAM_JUMP_CLASS_SHIFT 25
#define CAAM_JUMP_CLASS_NONE 0
#define CAAM_JUMP_CLASS_CLASS1 (1U << CAAM_JUMP_CLASS_SHIFT)
#define CAAM_JUMP_CLASS_CLASS2 (2U << CAAM_JUMP_CLASS_SHIFT)
#define CAAM_JUMP_CLASS_BOTH (3U << CAAM_JUMP_CLASS_SHIFT)
#define JUMP_JSL (1U << 24)
#define CAAM_JUMP_JSL (1U << 24)
#define JUMP_TYPE_SHIFT 22
#define JUMP_TYPE_LOCAL (0x00U << JUMP_TYPE_SHIFT)
#define JUMP_TYPE_NONLOCAL (0x01U << JUMP_TYPE_SHIFT)
#define JUMP_TYPE_HALT (0x02U << JUMP_TYPE_SHIFT)
#define JUMP_TYPE_HALT_USER (0x03U << JUMP_TYPE_SHIFT)
#define CAAM_JUMP_TYPE_SHIFT 22
#define CAAM_JUMP_TYPE_LOCAL (0x00U << CAAM_JUMP_TYPE_SHIFT)
#define CAAM_JUMP_TYPE_NONLOCAL (0x01U << CAAM_JUMP_TYPE_SHIFT)
#define CAAM_JUMP_TYPE_HALT (0x02U << CAAM_JUMP_TYPE_SHIFT)
#define CAAM_JUMP_TYPE_HALT_USER (0x03U << CAAM_JUMP_TYPE_SHIFT)
#define JUMP_TEST_SHIFT 16
#define JUMP_TEST_ALL (0x00U << JUMP_TEST_SHIFT)
#define JUMP_TEST_INVALL (0x01U << JUMP_TEST_SHIFT)
#define JUMP_TEST_ANY (0x02U << JUMP_TEST_SHIFT)
#define JUMP_TEST_INVANY (0x03U << JUMP_TEST_SHIFT)
#define CAAM_JUMP_TEST_SHIFT 16
#define CAAM_JUMP_TEST_ALL (0x00U << CAAM_JUMP_TEST_SHIFT)
#define CAAM_JUMP_TEST_INVALL (0x01U << CAAM_JUMP_TEST_SHIFT)
#define CAAM_JUMP_TEST_ANY (0x02U << CAAM_JUMP_TEST_SHIFT)
#define CAAM_JUMP_TEST_INVANY (0x03U << CAAM_JUMP_TEST_SHIFT)
/* Condition codes (bits 15:8) — plain conditions (without JSL) */
#define JUMP_COND_SHIFT 8
#define JUMP_COND_MATH_N (0x08U << JUMP_COND_SHIFT)
#define JUMP_COND_MATH_Z (0x04U << JUMP_COND_SHIFT)
#define JUMP_COND_MATH_C (0x02U << JUMP_COND_SHIFT)
#define JUMP_COND_MATH_NV (0x01U << JUMP_COND_SHIFT)
#define CAAM_JUMP_COND_SHIFT 8
#define CAAM_JUMP_COND_MATH_N (0x08U << CAAM_JUMP_COND_SHIFT)
#define CAAM_JUMP_COND_MATH_Z (0x04U << CAAM_JUMP_COND_SHIFT)
#define CAAM_JUMP_COND_MATH_C (0x02U << CAAM_JUMP_COND_SHIFT)
#define CAAM_JUMP_COND_MATH_NV (0x01U << CAAM_JUMP_COND_SHIFT)
/* Condition codes that include JSL (per Linux desc.h encoding) */
#define JUMP_COND_JRP ((0x80U << JUMP_COND_SHIFT) | JUMP_JSL)
#define JUMP_COND_SHRD ((0x40U << JUMP_COND_SHIFT) | JUMP_JSL)
#define JUMP_COND_SELF ((0x20U << JUMP_COND_SHIFT) | JUMP_JSL)
#define JUMP_COND_CALM ((0x10U << JUMP_COND_SHIFT) | JUMP_JSL)
#define JUMP_COND_NIP ((0x08U << JUMP_COND_SHIFT) | JUMP_JSL)
#define JUMP_COND_NIFP ((0x04U << JUMP_COND_SHIFT) | JUMP_JSL)
#define JUMP_COND_NOP ((0x02U << JUMP_COND_SHIFT) | JUMP_JSL)
#define JUMP_COND_NCP ((0x01U << JUMP_COND_SHIFT) | JUMP_JSL)
/* Condition codes that include JSL (per SEC descriptor format spec) */
#define CAAM_JUMP_COND_JRP ((0x80U << CAAM_JUMP_COND_SHIFT) | CAAM_JUMP_JSL)
#define CAAM_JUMP_COND_SHRD ((0x40U << CAAM_JUMP_COND_SHIFT) | CAAM_JUMP_JSL)
#define CAAM_JUMP_COND_SELF ((0x20U << CAAM_JUMP_COND_SHIFT) | CAAM_JUMP_JSL)
#define CAAM_JUMP_COND_CALM ((0x10U << CAAM_JUMP_COND_SHIFT) | CAAM_JUMP_JSL)
#define CAAM_JUMP_COND_NIP ((0x08U << CAAM_JUMP_COND_SHIFT) | CAAM_JUMP_JSL)
#define CAAM_JUMP_COND_NIFP ((0x04U << CAAM_JUMP_COND_SHIFT) | CAAM_JUMP_JSL)
#define CAAM_JUMP_COND_NOP ((0x02U << CAAM_JUMP_COND_SHIFT) | CAAM_JUMP_JSL)
#define CAAM_JUMP_COND_NCP ((0x01U << CAAM_JUMP_COND_SHIFT) | CAAM_JUMP_JSL)
#define JUMP_OFFSET_SHIFT 0
#define JUMP_OFFSET_MASK 0x000000ff
#define CAAM_JUMP_OFFSET_SHIFT 0
#define CAAM_JUMP_OFFSET_MASK 0x000000ff
/*
* MATH Command
@ -374,78 +377,78 @@
* Bits 11:8 = DEST
* Bits 3:0 = LEN (1, 2, 4, or 8 bytes)
*/
#define MATH_IFB (1U << 26)
#define CAAM_MATH_IFB (1U << 26)
#define MATH_FUN_SHIFT 20
#define MATH_FUN_ADD (0x00U << MATH_FUN_SHIFT)
#define MATH_FUN_ADDC (0x01U << MATH_FUN_SHIFT)
#define MATH_FUN_SUB (0x02U << MATH_FUN_SHIFT)
#define MATH_FUN_SUBB (0x03U << MATH_FUN_SHIFT)
#define MATH_FUN_OR (0x04U << MATH_FUN_SHIFT)
#define MATH_FUN_AND (0x05U << MATH_FUN_SHIFT)
#define MATH_FUN_XOR (0x06U << MATH_FUN_SHIFT)
#define MATH_FUN_LSHIFT (0x07U << MATH_FUN_SHIFT)
#define MATH_FUN_RSHIFT (0x08U << MATH_FUN_SHIFT)
#define MATH_FUN_ZBYT (0x0aU << MATH_FUN_SHIFT)
#define CAAM_MATH_FUN_SHIFT 20
#define CAAM_MATH_FUN_ADD (0x00U << CAAM_MATH_FUN_SHIFT)
#define CAAM_MATH_FUN_ADDC (0x01U << CAAM_MATH_FUN_SHIFT)
#define CAAM_MATH_FUN_SUB (0x02U << CAAM_MATH_FUN_SHIFT)
#define CAAM_MATH_FUN_SUBB (0x03U << CAAM_MATH_FUN_SHIFT)
#define CAAM_MATH_FUN_OR (0x04U << CAAM_MATH_FUN_SHIFT)
#define CAAM_MATH_FUN_AND (0x05U << CAAM_MATH_FUN_SHIFT)
#define CAAM_MATH_FUN_XOR (0x06U << CAAM_MATH_FUN_SHIFT)
#define CAAM_MATH_FUN_LSHIFT (0x07U << CAAM_MATH_FUN_SHIFT)
#define CAAM_MATH_FUN_RSHIFT (0x08U << CAAM_MATH_FUN_SHIFT)
#define CAAM_MATH_FUN_ZBYT (0x0aU << CAAM_MATH_FUN_SHIFT)
#define MATH_SRC0_SHIFT 16
#define MATH_SRC0_REG0 (0x00U << MATH_SRC0_SHIFT)
#define MATH_SRC0_REG1 (0x01U << MATH_SRC0_SHIFT)
#define MATH_SRC0_REG2 (0x02U << MATH_SRC0_SHIFT)
#define MATH_SRC0_REG3 (0x03U << MATH_SRC0_SHIFT)
#define MATH_SRC0_IMM (0x04U << MATH_SRC0_SHIFT)
#define MATH_SRC0_DPOVRD (0x07U << MATH_SRC0_SHIFT)
#define MATH_SRC0_SEQINLEN (0x08U << MATH_SRC0_SHIFT)
#define MATH_SRC0_SEQOUTLEN (0x09U << MATH_SRC0_SHIFT)
#define MATH_SRC0_VARSEQINLEN (0x0aU << MATH_SRC0_SHIFT)
#define MATH_SRC0_VARSEQOUTLEN (0x0bU << MATH_SRC0_SHIFT)
#define MATH_SRC0_ZERO (0x0cU << MATH_SRC0_SHIFT)
#define CAAM_MATH_SRC0_SHIFT 16
#define CAAM_MATH_SRC0_REG0 (0x00U << CAAM_MATH_SRC0_SHIFT)
#define CAAM_MATH_SRC0_REG1 (0x01U << CAAM_MATH_SRC0_SHIFT)
#define CAAM_MATH_SRC0_REG2 (0x02U << CAAM_MATH_SRC0_SHIFT)
#define CAAM_MATH_SRC0_REG3 (0x03U << CAAM_MATH_SRC0_SHIFT)
#define CAAM_MATH_SRC0_IMM (0x04U << CAAM_MATH_SRC0_SHIFT)
#define CAAM_MATH_SRC0_DPOVRD (0x07U << CAAM_MATH_SRC0_SHIFT)
#define CAAM_MATH_SRC0_SEQINLEN (0x08U << CAAM_MATH_SRC0_SHIFT)
#define CAAM_MATH_SRC0_SEQOUTLEN (0x09U << CAAM_MATH_SRC0_SHIFT)
#define CAAM_MATH_SRC0_VARSEQINLEN (0x0aU << CAAM_MATH_SRC0_SHIFT)
#define CAAM_MATH_SRC0_VARSEQOUTLEN (0x0bU << CAAM_MATH_SRC0_SHIFT)
#define CAAM_MATH_SRC0_ZERO (0x0cU << CAAM_MATH_SRC0_SHIFT)
#define MATH_SRC1_SHIFT 12
#define MATH_SRC1_REG0 (0x00U << MATH_SRC1_SHIFT)
#define MATH_SRC1_REG1 (0x01U << MATH_SRC1_SHIFT)
#define MATH_SRC1_REG2 (0x02U << MATH_SRC1_SHIFT)
#define MATH_SRC1_REG3 (0x03U << MATH_SRC1_SHIFT)
#define MATH_SRC1_IMM (0x04U << MATH_SRC1_SHIFT)
#define MATH_SRC1_DPOVRD (0x07U << MATH_SRC1_SHIFT)
#define MATH_SRC1_INFIFO (0x0aU << MATH_SRC1_SHIFT)
#define MATH_SRC1_OUTFIFO (0x0bU << MATH_SRC1_SHIFT)
#define MATH_SRC1_ONE (0x0cU << MATH_SRC1_SHIFT)
#define MATH_SRC1_ZERO (0x0fU << MATH_SRC1_SHIFT)
#define CAAM_MATH_SRC1_SHIFT 12
#define CAAM_MATH_SRC1_REG0 (0x00U << CAAM_MATH_SRC1_SHIFT)
#define CAAM_MATH_SRC1_REG1 (0x01U << CAAM_MATH_SRC1_SHIFT)
#define CAAM_MATH_SRC1_REG2 (0x02U << CAAM_MATH_SRC1_SHIFT)
#define CAAM_MATH_SRC1_REG3 (0x03U << CAAM_MATH_SRC1_SHIFT)
#define CAAM_MATH_SRC1_IMM (0x04U << CAAM_MATH_SRC1_SHIFT)
#define CAAM_MATH_SRC1_DPOVRD (0x07U << CAAM_MATH_SRC1_SHIFT)
#define CAAM_MATH_SRC1_INFIFO (0x0aU << CAAM_MATH_SRC1_SHIFT)
#define CAAM_MATH_SRC1_OUTFIFO (0x0bU << CAAM_MATH_SRC1_SHIFT)
#define CAAM_MATH_SRC1_ONE (0x0cU << CAAM_MATH_SRC1_SHIFT)
#define CAAM_MATH_SRC1_ZERO (0x0fU << CAAM_MATH_SRC1_SHIFT)
#define MATH_DEST_SHIFT 8
#define MATH_DEST_REG0 (0x00U << MATH_DEST_SHIFT)
#define MATH_DEST_REG1 (0x01U << MATH_DEST_SHIFT)
#define MATH_DEST_REG2 (0x02U << MATH_DEST_SHIFT)
#define MATH_DEST_REG3 (0x03U << MATH_DEST_SHIFT)
#define MATH_DEST_DPOVRD (0x07U << MATH_DEST_SHIFT)
#define MATH_DEST_SEQINLEN (0x08U << MATH_DEST_SHIFT)
#define MATH_DEST_SEQOUTLEN (0x09U << MATH_DEST_SHIFT)
#define MATH_DEST_VARSEQINLEN (0x0aU << MATH_DEST_SHIFT)
#define MATH_DEST_VARSEQOUTLEN (0x0bU << MATH_DEST_SHIFT)
#define MATH_DEST_NONE (0x0fU << MATH_DEST_SHIFT)
#define CAAM_MATH_DEST_SHIFT 8
#define CAAM_MATH_DEST_REG0 (0x00U << CAAM_MATH_DEST_SHIFT)
#define CAAM_MATH_DEST_REG1 (0x01U << CAAM_MATH_DEST_SHIFT)
#define CAAM_MATH_DEST_REG2 (0x02U << CAAM_MATH_DEST_SHIFT)
#define CAAM_MATH_DEST_REG3 (0x03U << CAAM_MATH_DEST_SHIFT)
#define CAAM_MATH_DEST_DPOVRD (0x07U << CAAM_MATH_DEST_SHIFT)
#define CAAM_MATH_DEST_SEQINLEN (0x08U << CAAM_MATH_DEST_SHIFT)
#define CAAM_MATH_DEST_SEQOUTLEN (0x09U << CAAM_MATH_DEST_SHIFT)
#define CAAM_MATH_DEST_VARSEQINLEN (0x0aU << CAAM_MATH_DEST_SHIFT)
#define CAAM_MATH_DEST_VARSEQOUTLEN (0x0bU << CAAM_MATH_DEST_SHIFT)
#define CAAM_MATH_DEST_NONE (0x0fU << CAAM_MATH_DEST_SHIFT)
#define MATH_LEN_SHIFT 0
#define MATH_LEN_1BYTE 0x01
#define MATH_LEN_2BYTE 0x02
#define MATH_LEN_4BYTE 0x04
#define MATH_LEN_8BYTE 0x08
#define CAAM_MATH_LEN_SHIFT 0
#define CAAM_MATH_LEN_1BYTE 0x01
#define CAAM_MATH_LEN_2BYTE 0x02
#define CAAM_MATH_LEN_4BYTE 0x04
#define CAAM_MATH_LEN_8BYTE 0x08
/*
* MOVE Command
*/
#define MOVE_SRC_SHIFT 20
#define MOVE_SRC_CLASS1CTX (0x04U << MOVE_SRC_SHIFT)
#define MOVE_SRC_CLASS2CTX (0x05U << MOVE_SRC_SHIFT)
#define MOVE_SRC_OUTFIFO (0x06U << MOVE_SRC_SHIFT)
#define CAAM_MOVE_SRC_SHIFT 20
#define CAAM_MOVE_SRC_CLASS1CTX (0x04U << CAAM_MOVE_SRC_SHIFT)
#define CAAM_MOVE_SRC_CLASS2CTX (0x05U << CAAM_MOVE_SRC_SHIFT)
#define CAAM_MOVE_SRC_OUTFIFO (0x06U << CAAM_MOVE_SRC_SHIFT)
#define MOVE_DEST_SHIFT 16
#define MOVE_DEST_CLASS1CTX (0x04U << MOVE_DEST_SHIFT)
#define MOVE_DEST_CLASS2CTX (0x05U << MOVE_DEST_SHIFT)
#define MOVE_DEST_CLASS2INFIFO (0x07U << MOVE_DEST_SHIFT)
#define CAAM_MOVE_DEST_SHIFT 16
#define CAAM_MOVE_DEST_CLASS1CTX (0x04U << CAAM_MOVE_DEST_SHIFT)
#define CAAM_MOVE_DEST_CLASS2CTX (0x05U << CAAM_MOVE_DEST_SHIFT)
#define CAAM_MOVE_DEST_CLASS2INFIFO (0x07U << CAAM_MOVE_DEST_SHIFT)
#define MOVE_OFFSET_SHIFT 8
#define MOVE_LEN_SHIFT 0
#define CAAM_MOVE_OFFSET_SHIFT 8
#define CAAM_MOVE_LEN_SHIFT 0
/*
* SEC4 Scatter-Gather Table Entry
@ -483,7 +486,7 @@ static __inline int
caam_desc_len(const uint32_t *desc)
{
return (caam_to_cpu32(desc[0]) & HDR_DESCLEN_MASK);
return (caam_to_cpu32(desc[0]) & CAAM_HDR_DESCLEN_MASK);
}
/* Get shared descriptor length in words */
@ -491,35 +494,34 @@ static __inline int
caam_shdesc_len(const uint32_t *desc)
{
return (caam_to_cpu32(desc[0]) & SHR_HDR_DESCLEN_MASK);
return (caam_to_cpu32(desc[0]) & CAAM_SHR_HDR_DESCLEN_MASK);
}
/*
* Initialize a job descriptor header.
* Sets CMD_DESC_HDR + HDR_ONE + length=1 (the header word itself).
* Sets CAAM_CMD_DESC_HDR + CAAM_HDR_ONE + length=1 (the header word itself).
*/
static __inline void
caam_desc_init(uint32_t *desc)
{
desc[0] = cpu_to_caam32(CMD_DESC_HDR | HDR_ONE | 1);
desc[0] = cpu_to_caam32(CAAM_CMD_DESC_HDR | CAAM_HDR_ONE | 1);
}
/*
* Initialize a shared descriptor header.
* Sets CMD_SH_DESC_HDR + HDR_ONE + options + length=1.
* Sets CAAM_CMD_SH_DESC_HDR + CAAM_HDR_ONE + options + length=1.
*/
static __inline void
caam_shdesc_init(uint32_t *desc, uint32_t options)
{
/*
* Shared descriptor header: CMD_SH_DESC_HDR + HDR_ONE + options + 1.
* HDR_ONE (bit 23) is set in both JD and SD headers per the SEC
* reference manual. Matches Linux init_sh_desc → init_desc which
* always ORs HDR_ONE.
* Shared descriptor header: CAAM_CMD_SH_DESC_HDR + CAAM_HDR_ONE + options + 1.
* CAAM_HDR_ONE (bit 23) is set in both JD and SD headers per the SEC
* reference manual; always ORed into descriptor headers.
*/
desc[0] = cpu_to_caam32(CMD_SH_DESC_HDR | HDR_ONE | options | 1);
desc[0] = cpu_to_caam32(CAAM_CMD_SH_DESC_HDR | CAAM_HDR_ONE | options | 1);
}
/* Append a command/data word to the descriptor (with byte-swap) */
@ -530,11 +532,11 @@ caam_desc_add_word(uint32_t *desc, uint32_t word)
int len;
hdr = caam_to_cpu32(desc[0]);
len = hdr & HDR_DESCLEN_MASK;
len = hdr & CAAM_HDR_DESCLEN_MASK;
KASSERT(len < CAAM_DESC_MAX_WORDS,
("caam_desc_add_word: descriptor overflow (%d words)", len));
desc[len] = cpu_to_caam32(word);
desc[0] = cpu_to_caam32((hdr & ~HDR_DESCLEN_MASK) | (len + 1));
desc[0] = cpu_to_caam32((hdr & ~CAAM_HDR_DESCLEN_MASK) | (len + 1));
}
/*
@ -548,11 +550,11 @@ caam_desc_add_raw(uint32_t *desc, uint32_t raw)
int len;
hdr = caam_to_cpu32(desc[0]);
len = hdr & HDR_DESCLEN_MASK;
len = hdr & CAAM_HDR_DESCLEN_MASK;
KASSERT(len < CAAM_DESC_MAX_WORDS,
("caam_desc_add_raw: descriptor overflow (%d words)", len));
desc[len] = raw;
desc[0] = cpu_to_caam32((hdr & ~HDR_DESCLEN_MASK) | (len + 1));
desc[0] = cpu_to_caam32((hdr & ~CAAM_HDR_DESCLEN_MASK) | (len + 1));
}
/*
@ -568,7 +570,7 @@ caam_desc_add_ptr(uint32_t *desc, uint64_t ptr)
int len;
hdr = caam_to_cpu32(desc[0]);
len = hdr & HDR_DESCLEN_MASK;
len = hdr & CAAM_HDR_DESCLEN_MASK;
KASSERT(len + 1 < CAAM_DESC_MAX_WORDS,
("caam_desc_add_ptr: descriptor overflow (%d words)", len));
if (caam_big_endian) {
@ -578,7 +580,7 @@ caam_desc_add_ptr(uint32_t *desc, uint64_t ptr)
desc[len] = (uint32_t)ptr;
desc[len + 1] = (uint32_t)(ptr >> 32);
}
desc[0] = cpu_to_caam32((hdr & ~HDR_DESCLEN_MASK) | (len + 2));
desc[0] = cpu_to_caam32((hdr & ~CAAM_HDR_DESCLEN_MASK) | (len + 2));
}
/*
@ -594,10 +596,10 @@ caam_desc_add_jump(uint32_t *desc, uint32_t options)
uint32_t *jump_word;
hdr = caam_to_cpu32(desc[0]);
len = hdr & HDR_DESCLEN_MASK;
len = hdr & CAAM_HDR_DESCLEN_MASK;
jump_word = &desc[len];
desc[len] = cpu_to_caam32(CMD_JUMP | options);
desc[0] = cpu_to_caam32((hdr & ~HDR_DESCLEN_MASK) | (len + 1));
desc[len] = cpu_to_caam32(CAAM_CMD_JUMP | options);
desc[0] = cpu_to_caam32((hdr & ~CAAM_HDR_DESCLEN_MASK) | (len + 1));
return (jump_word);
}
@ -616,7 +618,7 @@ caam_desc_set_jump_target(uint32_t *desc, uint32_t *jump_cmd)
cur_len = caam_desc_len(desc);
/* Offset is relative: how many words to skip from the jump command */
jcmd = caam_to_cpu32(*jump_cmd);
jcmd = (jcmd & ~JUMP_OFFSET_MASK) | (cur_len - jump_idx);
jcmd = (jcmd & ~CAAM_JUMP_OFFSET_MASK) | (cur_len - jump_idx);
*jump_cmd = cpu_to_caam32(jcmd);
}
@ -626,7 +628,7 @@ caam_desc_set_jump_target(uint32_t *desc, uint32_t *jump_cmd)
* Data bytes are copied verbatim into the descriptor buffer without
* byte-swapping. CAAM reads the inline data as raw bytes from the
* descriptor in DMA memory, regardless of register endianness.
* This matches Linux's append_data() which uses memcpy.
* Uses memcpy to append raw bytes into the descriptor buffer.
*
* key_len is rounded up to 4 for word alignment; callers must ensure
* the key command's length field reflects the actual byte count.
@ -646,27 +648,27 @@ caam_desc_add_key_imm(uint32_t *desc, const uint8_t *key, int key_len)
/*
* Append a Derived Key Protocol (DKP) OPERATION for HMAC split key.
* Used on ERA >= 6 instead of KEY + KEY_ENC for split key loading.
* Used on ERA >= 6 instead of KEY + CAAM_KEY_ENC for split key loading.
*
* The DKP computes the HMAC split key from the raw HMAC key at DECO
* runtime and loads it into the Class 2 key register. This replaces
* the pre-computed split key + KEY_DEST_MDHA_SPLIT approach used on
* the pre-computed split key + CAAM_KEY_DEST_MDHA_SPLIT approach used on
* earlier ERAs.
*
* algtype: algorithm selector (e.g. OP_ALG_ALGSEL_SHA256)
* algtype: algorithm selector (e.g. CAAM_OP_ALG_ALGSEL_SHA256)
* key: raw HMAC key bytes
* keylen: raw HMAC key length in bytes
* split_key_len: split key length = 2 * MDHA_pad (determines DECO IP
* advancement and inline reservation). Must be the
* UNPADDED split_key_len, NOT split_key_pad_len.
* Matches Linux adata->keylen_pad = split_key_len().
* KEY length field = unpadded split_key_len per SEC RM.
*
* When keylen > split_key_len, inline source would cause the DECO to
* skip fewer words than the key occupies, executing key data as
* instructions. In that case we MUST NOT inline both. This
* implementation rejects keylen > split_key_len; callers must limit
* auth_klen in probesession. (Linux uses SRC_PTR mode with a DMA
* pointer for large keys.)
* auth_klen in probesession. (SRC_PTR mode with a DMA pointer
* could be used for large keys but is not implemented here.)
*/
static __inline void
caam_desc_add_proto_dkp(uint32_t *desc, uint32_t algtype,
@ -676,11 +678,11 @@ caam_desc_add_proto_dkp(uint32_t *desc, uint32_t algtype,
int words, len;
/*
* Translate OP_ALG_ALGSEL_SHA* to OP_PCLID_DKP_SHA*.
* Translate CAAM_OP_ALG_ALGSEL_SHA* to OP_PCLID_DKP_SHA*.
* DKP protocol IDs are 0x2n where n = low nibble of ALGSEL.
*/
protid = (algtype & OP_ALG_ALGSEL_SUBMASK) |
(0x20U << OP_ALG_ALGSEL_SHIFT);
protid = (algtype & CAAM_OP_ALG_ALGSEL_SUBMASK) |
(0x20U << CAAM_OP_ALG_ALGSEL_SHIFT);
KASSERT(keylen <= split_key_len,
("caam DKP: keylen %d > split_key_len %d, need SRC_PTR mode",
@ -688,7 +690,7 @@ caam_desc_add_proto_dkp(uint32_t *desc, uint32_t algtype,
/* OPERATION: DKP with inline source and inline destination */
caam_desc_add_word(desc,
CMD_OPERATION | OP_TYPE_UNI_PROTOCOL | protid |
CAAM_CMD_OPERATION | CAAM_OP_TYPE_UNI_PROTOCOL | protid |
OP_PCL_DKP_SRC_IMM | OP_PCL_DKP_DST_IMM | keylen);
/* Append raw key inline */
@ -704,8 +706,8 @@ caam_desc_add_proto_dkp(uint32_t *desc, uint32_t algtype,
words = (roundup2(split_key_len, 4) - roundup2(keylen, 4)) / 4;
if (words > 0) {
hdr = caam_to_cpu32(desc[0]);
len = hdr & HDR_DESCLEN_MASK;
desc[0] = cpu_to_caam32((hdr & ~HDR_DESCLEN_MASK) |
len = hdr & CAAM_HDR_DESCLEN_MASK;
desc[0] = cpu_to_caam32((hdr & ~CAAM_HDR_DESCLEN_MASK) |
(len + words));
}
}
@ -729,7 +731,7 @@ caam_desc_add_split_key_ptr(uint32_t *desc, int split_key_pad_len,
{
caam_desc_add_word(desc,
CMD_KEY | KEY_CLASS2 | KEY_DEST_MDHA_SPLIT | KEY_ENC |
CAAM_CMD_KEY | CAAM_KEY_CLASS2 | CAAM_KEY_DEST_MDHA_SPLIT | CAAM_KEY_ENC |
split_key_pad_len);
caam_desc_add_ptr(desc, key_pa);
}
@ -738,8 +740,7 @@ caam_desc_add_split_key_ptr(uint32_t *desc, int split_key_pad_len,
* Append a SEQ IN PTR command. Always uses EXT mode (extended 32-bit
* length in a separate word after the pointer).
*
* Linux's append_seq_in_ptr() also always uses EXT mode — the compile-
* time sizeof(u32) > sizeof(u16) check in APPEND_CMD_PTR_LEN selects
* EXT mode is always used for SEQ IN/OUT PTR on 64-bit platforms — the
* the extlen variant unconditionally. We match this behavior to ensure
* the JD body word count is constant regardless of data size, which
* avoids DECO descriptor caching issues when the same shared descriptor
@ -751,7 +752,7 @@ static __inline void
caam_desc_add_seq_in_ptr(uint32_t *desc, bus_addr_t pa, uint32_t len)
{
caam_desc_add_word(desc, CMD_SEQ_IN_PTR | SQIN_EXT);
caam_desc_add_word(desc, CAAM_CMD_SEQ_IN_PTR | SQIN_EXT);
caam_desc_add_ptr(desc, pa);
caam_desc_add_word(desc, len);
}
@ -764,7 +765,7 @@ static __inline void
caam_desc_add_seq_out_ptr(uint32_t *desc, bus_addr_t pa, uint32_t len)
{
caam_desc_add_word(desc, CMD_SEQ_OUT_PTR | SQOUT_EXT);
caam_desc_add_word(desc, CAAM_CMD_SEQ_OUT_PTR | SQOUT_EXT);
caam_desc_add_ptr(desc, pa);
caam_desc_add_word(desc, len);
}
@ -788,7 +789,7 @@ caam_desc_build_nop(uint32_t *desc)
{
caam_desc_init(desc);
caam_desc_add_word(desc, CMD_JUMP | JUMP_TYPE_HALT);
caam_desc_add_word(desc, CAAM_CMD_JUMP | CAAM_JUMP_TYPE_HALT);
}
#endif /* _CAAM_DESC_H */

View file

@ -1,8 +1,11 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* CAAM hash/HMAC descriptor builders for CSP_MODE_DIGEST.
*
* Standalone hash (SHA, MD5) and HMAC use Class 2 (MDHA) only.
@ -65,12 +68,12 @@ caam_hash_build_shdesc(struct caam_session *sess, device_t dev)
return (error);
desc = sess->enc_shdesc.vaddr;
caam_shdesc_init(desc, HDR_SHARE_SERIAL);
caam_shdesc_init(desc, CAAM_HDR_SHARE_SERIAL);
if (is_hmac) {
/* Skip key loading if already shared */
key_jump = caam_desc_add_jump(desc,
JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD);
CAAM_JUMP_JSL | CAAM_JUMP_TEST_ALL | CAAM_JUMP_COND_SHRD);
/* Load pre-derived HMAC split key (pointer mode, 3 words) */
caam_desc_add_split_key_ptr(desc, sess->split_key_pad_len,
@ -81,31 +84,31 @@ caam_hash_build_shdesc(struct caam_session *sess, device_t dev)
/* OPERATION: hash/HMAC init+final, always "encrypt" (compute) */
caam_desc_add_word(desc,
CMD_OPERATION | OP_TYPE_CLASS2_ALG |
CAAM_CMD_OPERATION | CAAM_OP_TYPE_CLASS2_ALG |
sess->auth_algtype |
(is_hmac ? OP_ALG_AAI_HMAC_PRECOMP : 0) |
OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT);
(is_hmac ? CAAM_OP_ALG_AAI_HMAC_PRECOMP : 0) |
CAAM_OP_ALG_AS_INITFINAL | CAAM_OP_ALG_ENCRYPT);
/*
* VARSEQINLEN = SEQINLEN + 0.
* SEQINLEN is set by the SEQ IN PTR command in the JD body
* (which runs first due to HDR_REVERSE). REG0 is always zero
* at descriptor start. Matches Linux cnstr_shdsc_ahash().
* (which runs first due to CAAM_HDR_REVERSE). REG0 is always zero
* at descriptor start.
*/
caam_desc_add_word(desc,
CMD_MATH | MATH_FUN_ADD |
MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 |
MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE);
CAAM_CMD_MATH | CAAM_MATH_FUN_ADD |
CAAM_MATH_SRC0_SEQINLEN | CAAM_MATH_SRC1_REG0 |
CAAM_MATH_DEST_VARSEQINLEN | CAAM_MATH_LEN_4BYTE);
/* Feed all data to Class 2 (LAST2 for finalization) */
caam_desc_add_word(desc,
CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | FIFOLDST_VLF |
FIFOLD_TYPE_MSG | FIFOLD_TYPE_LAST2);
CAAM_CMD_SEQ_FIFO_LOAD | CAAM_FIFOLD_CLASS_CLASS2 | CAAM_FIFOLDST_VLF |
CAAM_FIFOLD_TYPE_MSG | CAAM_FIFOLD_TYPE_LAST2);
/* Store digest from Class 2 context register */
caam_desc_add_word(desc,
CMD_SEQ_STORE | LDST_CLASS_2_CCB |
LDST_SRCDST_BYTE_CONTEXT | sess->icvlen);
CAAM_CMD_SEQ_STORE | CAAM_LDST_CLASS_2_CCB |
CAAM_LDST_SRCDST_BYTE_CONTEXT | sess->icvlen);
sess->enc_shdesc_len = caam_shdesc_len(desc);
return (0);
@ -114,7 +117,7 @@ caam_hash_build_shdesc(struct caam_session *sess, device_t dev)
/* ================================================================
* Hash/HMAC Job Descriptor
*
* Layout (always-EXT, matching Linux):
* Layout (always-EXT mode on 64-bit):
* [0] JD header (SHARED | SHARE_DEFER | REVERSE)
* [1-2] Shared descriptor pointer (64-bit)
* [3] SEQ IN PTR | EXT (payload data)
@ -150,15 +153,15 @@ caam_hash_build_job(struct caam_jr_softc *sc, struct caam_request *req,
{
uint32_t hdr = caam_to_cpu32(desc[0]);
hdr |= HDR_SHARED | HDR_SHARE_DEFER | HDR_REVERSE;
hdr |= (shdesc_len << HDR_START_IDX_SHIFT);
hdr |= CAAM_HDR_SHARED | CAAM_HDR_SHARE_DEFER | CAAM_HDR_REVERSE;
hdr |= (shdesc_len << CAAM_HDR_START_IDX_SHIFT);
desc[0] = cpu_to_caam32(hdr);
}
/* Shared descriptor pointer */
caam_desc_add_ptr(desc, sess->enc_shdesc.paddr);
/* === JD body (runs FIRST with HDR_REVERSE) === */
/* === JD body (runs FIRST with CAAM_HDR_REVERSE) === */
/* SEQ IN PTR: data to hash (always EXT mode) */
caam_desc_add_seq_in_ptr(desc, buf_pa, data_len);

View file

@ -1,8 +1,11 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* NXP CAAM Job Ring driver.
*
* Each Job Ring is a child device of the CAAM controller. It manages
@ -118,6 +121,7 @@ caam_dma_alloc(device_t dev, struct caam_dma_mem *mem, bus_size_t size)
mem->vaddr = NULL;
return (error);
}
mem->size = size;
return (0);
}
@ -128,12 +132,15 @@ caam_dma_free(struct caam_dma_mem *mem)
if (mem->tag == NULL)
return;
/* key material, split keys and descriptors that embed keys */
explicit_bzero(mem->vaddr, mem->size);
bus_dmamap_unload(mem->tag, mem->map);
bus_dmamem_free(mem->tag, mem->vaddr, mem->map);
bus_dma_tag_destroy(mem->tag);
mem->tag = NULL;
mem->vaddr = NULL;
mem->paddr = 0;
mem->size = 0;
}
/*

View file

@ -1,8 +1,11 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* NXP CAAM Job Ring driver — softc and ring structures.
*/
@ -21,7 +24,7 @@ struct caam_request;
/*
* Ring depth — must be a power of 2, max 1024 per hardware.
* Linux default is 512 (CONFIG_CRYPTO_DEV_FSL_CAAM_RINGSIZE = 9, 1<<9).
* Default 512 entries (1<<9).
*/
#define CAAM_JR_DEPTH 512
#define CAAM_JR_DEPTH_MASK (CAAM_JR_DEPTH - 1)
@ -53,6 +56,7 @@ struct caam_dma_mem {
bus_dmamap_t map;
void *vaddr;
bus_addr_t paddr;
bus_size_t size; /* caam_dma_free() zeroes all of it */
};
/*

View file

@ -1,8 +1,11 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* CAAM QI (Queue Interface) crypto backend.
*
* Submits crypto operations through QMan frame queues instead of Job Rings.
@ -448,7 +451,6 @@ caam_qi_drv_ctx_create(struct caam_qi_softc *qi, struct caam_session *sess,
* RSLS (bit 31) = Route SEQ LOAD/STORE to FD — tells the QI
* hardware to route compound FD S/G data to the DECO's sequential
* input/output. Without RSLS, SEQ commands have no data source.
* Linux always sets RSLS (see drivers/crypto/caam/qi.c).
* Word 1: ABS — absolute addressing mode
*/
prehdr = ctx->prehdr_shdesc.vaddr;
@ -514,10 +516,7 @@ caam_qi_drv_ctx_destroy(struct caam_qi_drv_ctx *ctx)
qman_fqr_free(ctx->req_fqr[cpu]);
}
/* Zero inline key material in shared descriptor before freeing */
if (ctx->prehdr_shdesc.vaddr != NULL)
explicit_bzero(ctx->prehdr_shdesc.vaddr, CAAM_QI_PREHDR_SZ);
caam_dma_free(&ctx->prehdr_shdesc);
caam_dma_free(&ctx->prehdr_shdesc); /* zeroes the inline key */
free(ctx, M_CAAM_QI);
}
@ -543,7 +542,7 @@ caam_qi_newsession(device_t dev, crypto_session_t cses,
sess->ivlen = AES_GCM_IV_LEN;
sess->icvlen = (csp->csp_auth_mlen != 0) ?
csp->csp_auth_mlen : AES_GCM_TAG_LEN;
sess->cipher_algtype = OP_ALG_ALGSEL_AES | OP_ALG_AAI_GCM;
sess->cipher_algtype = CAAM_OP_ALG_ALGSEL_AES | CAAM_OP_ALG_AAI_GCM;
error = caam_qi_drv_ctx_create(qi, sess, &sess->qi_enc_ctx,
caam_qi_gcm_build_enc_shdesc);
@ -577,9 +576,9 @@ caam_qi_newsession(device_t dev, crypto_session_t cses,
sess->auth_klen = csp->csp_auth_klen;
memcpy(sess->auth_key, csp->csp_auth_key, sess->auth_klen);
sess->split_key_len = caam_split_key_len(
sess->auth_algtype & OP_ALG_ALGSEL_MASK);
sess->auth_algtype & CAAM_OP_ALG_ALGSEL_MASK);
sess->split_key_pad_len = caam_split_key_pad_len(
sess->auth_algtype & OP_ALG_ALGSEL_MASK);
sess->auth_algtype & CAAM_OP_ALG_ALGSEL_MASK);
/* Allocate DMA buffer and derive split key via JR */
error = caam_session_alloc_auth_key_dma(qi->dev, sess);
@ -633,9 +632,9 @@ caam_qi_newsession(device_t dev, crypto_session_t cses,
sess->alg_type = CAAM_ALG_HMAC;
sess->auth_klen = csp->csp_auth_klen;
sess->split_key_len = caam_split_key_len(
sess->auth_algtype & OP_ALG_ALGSEL_MASK);
sess->auth_algtype & CAAM_OP_ALG_ALGSEL_MASK);
sess->split_key_pad_len = caam_split_key_pad_len(
sess->auth_algtype & OP_ALG_ALGSEL_MASK);
sess->auth_algtype & CAAM_OP_ALG_ALGSEL_MASK);
memcpy(sess->auth_key, csp->csp_auth_key,
sess->auth_klen);
@ -703,10 +702,8 @@ caam_qi_freesession(device_t dev, crypto_session_t cses)
/* Zero key material before freeing contexts */
explicit_bzero(sess->enc_key, sizeof(sess->enc_key));
explicit_bzero(sess->auth_key, sizeof(sess->auth_key));
if (sess->auth_key_dma.vaddr != NULL)
explicit_bzero(sess->auth_key_dma.vaddr,
sess->split_key_pad_len * 2);
/* zeroed by caam_dma_free(); this used to clear twice its size */
caam_dma_free(&sess->auth_key_dma);
caam_qi_drv_ctx_destroy(sess->qi_enc_ctx);
caam_qi_drv_ctx_destroy(sess->qi_dec_ctx);

View file

@ -1,8 +1,11 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* CAAM QI (Queue Interface) backend — data structures.
*
* QI submits crypto operations through QMan frame queues instead of Job

File diff suppressed because it is too large Load diff

View file

@ -1,8 +1,11 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* Hardware register definitions for NXP CAAM (SEC v4.0+) crypto engine.
* Derived from the NXP Layerscape LS1046A Security Engine Reference Manual.
*/

View file

@ -1,8 +1,11 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* CAAM hardware entropy source for FreeBSD's kernel random subsystem.
*
* Submits RNG descriptors to a Job Ring to generate random data from the
@ -102,10 +105,10 @@ caam_rng_generate(void)
out_pa = caam_rng.out_mem.paddr;
/* Build RNG descriptor */
desc[0] = cpu_to_caam32(CMD_DESC_HDR | HDR_ONE | 5);
desc[1] = cpu_to_caam32(CMD_OPERATION | OP_TYPE_CLASS1_ALG |
OP_ALG_ALGSEL_RNG | OP_ALG_PR_ON);
desc[2] = cpu_to_caam32(CMD_FIFO_STORE | FIFOST_TYPE_RNGSTORE |
desc[0] = cpu_to_caam32(CAAM_CMD_DESC_HDR | CAAM_HDR_ONE | 5);
desc[1] = cpu_to_caam32(CAAM_CMD_OPERATION | CAAM_OP_TYPE_CLASS1_ALG |
CAAM_OP_ALG_ALGSEL_RNG | CAAM_OP_ALG_PR_ON);
desc[2] = cpu_to_caam32(CAAM_CMD_FIFO_STORE | CAAM_FIFOST_TYPE_RNGSTORE |
CAAM_RNG_OUTSIZE);
desc[3] = cpu_to_caam32((uint32_t)(out_pa >> 32));
desc[4] = cpu_to_caam32((uint32_t)out_pa);

View file

@ -1,8 +1,11 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
* Ported from the Linux CAAM driver (drivers/crypto/caam: GPL-2.0 and
* GPL-2.0+), Copyright Freescale Semiconductor, Inc. and NXP.
*
* CAAM hardware entropy source — interface.
*/

View file

@ -272,6 +272,29 @@ dpaa_wifi_find_vap_for_rx(const void *frame_data)
* The VAP is known from the callback context (no MAC lookup).
* Same logic as the CDX→WiFi path in dpaa_wifi_rx_cb().
*/
/*
* Copy a contiguous frame out of an FMan buffer into a new mbuf chain.
* Offset and length come from the hardware frame descriptor: only a
* single-buffer frame lying within the buffer (FM_PORT_BUFFER_SIZE, as
* WIFI_BUF_SIZE) is copied, at any length up to that. NULL when the frame
* is malformed or no mbuf is free; the caller drops it.
*/
static struct mbuf *
dpaa_wifi_copy_frame(void *buf, t_DpaaFD *frame, struct ifnet *ifp)
{
uint32_t off, len;
if (__predict_false(DPAA_FD_GET_FORMAT(frame) !=
e_DPAA_FD_FORMAT_TYPE_SHORT_SBSF))
return (NULL);
off = DPAA_FD_GET_OFFSET(frame);
len = DPAA_FD_GET_LENGTH(frame);
if (__predict_false(len == 0 || off >= WIFI_BUF_SIZE ||
len > WIFI_BUF_SIZE - off))
return (NULL);
return (m_devget((char *)buf + off, len, 0, ifp, NULL));
}
static e_RxStoreResponse
dpaa_wifi_fwd_rx_cb(t_Handle app, t_Handle fqr, t_Handle portal,
uint32_t fqid_off, t_DpaaFD *frame)
@ -280,7 +303,7 @@ dpaa_wifi_fwd_rx_cb(t_Handle app, t_Handle fqr, t_Handle portal,
struct dpaa_wifi_vap *vap = ctx->vap;
void *buf;
struct mbuf *m;
uint32_t fd_status, frame_len;
uint32_t fd_status;
uint8_t bpid;
buf = DPAA_FD_GET_ADDR(frame);
@ -305,9 +328,7 @@ dpaa_wifi_fwd_rx_cb(t_Handle app, t_Handle fqr, t_Handle portal,
return (e_RX_STORE_RESPONSE_CONTINUE);
}
frame_len = DPAA_FD_GET_LENGTH(frame);
m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR,
frame_len > MCLBYTES ? MJUMPAGESIZE : MCLBYTES);
m = dpaa_wifi_copy_frame(buf, frame, vap->ifp);
if (__predict_false(m == NULL)) {
atomic_add_64(&wifi_rx_drop, 1);
dtsec_rm_buf_free_external(bpid, buf);
@ -316,12 +337,6 @@ dpaa_wifi_fwd_rx_cb(t_Handle app, t_Handle fqr, t_Handle portal,
return (e_RX_STORE_RESPONSE_CONTINUE);
}
memcpy(mtod(m, void *),
(char *)buf + DPAA_FD_GET_OFFSET(frame), frame_len);
m->m_len = frame_len;
m->m_pkthdr.len = frame_len;
m->m_pkthdr.rcvif = vap->ifp;
/* Release dtsec buffer and refill BMan pool */
dtsec_rm_buf_free_external(bpid, buf);
dtsec_rm_pool_rx_refill_bpid(bpid);
@ -722,7 +737,6 @@ dpaa_wifi_deliver_to_stack(void *buf, t_DpaaFD *frame)
struct mbuf *m;
struct dpaa_wifi_vap *vap;
uint8_t vap_idx;
uint32_t frame_len;
vap_idx = *(uint8_t *)((char *)buf + PRIVDATA_VAP_OFF);
if (__predict_false(vap_idx >= DPAA_WIFI_MAX_VAPS ||
@ -733,22 +747,13 @@ dpaa_wifi_deliver_to_stack(void *buf, t_DpaaFD *frame)
}
vap = &wifi_vaps[vap_idx];
frame_len = DPAA_FD_GET_LENGTH(frame);
m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR,
frame_len > MCLBYTES ? MJUMPAGESIZE : MCLBYTES);
m = dpaa_wifi_copy_frame(buf, frame, vap->ifp);
if (__predict_false(m == NULL)) {
atomic_add_64(&wifi_rx_drop, 1);
wifi_buf_return(buf);
return (e_RX_STORE_RESPONSE_CONTINUE);
}
memcpy(mtod(m, void *),
(char *)buf + DPAA_FD_GET_OFFSET(frame), frame_len);
m->m_len = frame_len;
m->m_pkthdr.len = frame_len;
m->m_pkthdr.rcvif = vap->ifp;
/* Return BMan buffer to pool immediately */
wifi_buf_return(buf);
@ -850,7 +855,7 @@ dpaa_wifi_rx_cb(t_Handle app, t_Handle fqr, t_Handle portal,
struct mbuf *m;
struct dpaa_wifi_vap *vap;
uint8_t bpid;
uint32_t fd_status, frame_len;
uint32_t fd_status;
buf = DPAA_FD_GET_ADDR(frame);
if (__predict_false(buf == NULL))
@ -913,20 +918,12 @@ dpaa_wifi_rx_cb(t_Handle app, t_Handle fqr, t_Handle portal,
goto drop;
}
frame_len = DPAA_FD_GET_LENGTH(frame);
m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR,
frame_len > MCLBYTES ? MJUMPAGESIZE : MCLBYTES);
m = dpaa_wifi_copy_frame(buf, frame, vap->ifp);
if (__predict_false(m == NULL)) {
atomic_add_64(&wifi_rx_drop, 1);
goto drop;
}
memcpy(mtod(m, void *),
(char *)buf + DPAA_FD_GET_OFFSET(frame), frame_len);
m->m_len = frame_len;
m->m_pkthdr.len = frame_len;
m->m_pkthdr.rcvif = vap->ifp;
/* Release dtsec buffer and refill BMan pool */
dtsec_rm_buf_free_external(bpid, buf);
dtsec_rm_pool_rx_refill_bpid(bpid);

View file

@ -9,7 +9,7 @@
SYSROOT?= /usr/obj/usr/src/arm64.aarch64/tmp
CC?= cc
TARGET?= --target=aarch64-unknown-freebsd14.3
TARGET?= --target=aarch64-unknown-freebsd15.1
CFLAGS= -O2 -pipe -Wall --sysroot=${SYSROOT} ${TARGET}
LDFLAGS= ${TARGET} --sysroot=${SYSROOT}

View file

@ -1,5 +1,5 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright (c) 2026 Mono Technologies Inc.
*
@ -7,7 +7,8 @@
* Reads bus voltage, shunt voltage, current, and power from
* INA2xx-family digital power monitors over I2C.
*
* Based on Linux hwmon/ina2xx.c by Lothar Felten.
* Ported from Linux drivers/hwmon/ina2xx.c (GPL-2.0-only),
* Copyright Lothar Felten and the Linux INA2xx driver's contributors.
*/
#include <sys/cdefs.h>
@ -24,60 +25,60 @@
#include <dev/ofw/ofw_bus_subr.h>
/* INA2xx register addresses */
#define INA2XX_CONFIG 0x00
#define INA2XX_SHUNT_VOLTAGE 0x01
#define INA2XX_BUS_VOLTAGE 0x02
#define INA2XX_POWER 0x03
#define INA2XX_CURRENT 0x04
#define INA2XX_CALIBRATION 0x05
#define INA_REG_CONFIG 0x00
#define INA_REG_SHUNT 0x01
#define INA_REG_BUS 0x02
#define INA_REG_POWER 0x03
#define INA_REG_CURRENT 0x04
#define INA_REG_CAL 0x05
/* Default shunt resistance: 10 mOhm = 10000 uOhm */
#define INA2XX_RSHUNT_DEFAULT 10000
#define INA_RSHUNT_DEFAULT 10000
/* Chip type enumeration */
enum ina2xx_chip { INA219, INA226, INA234 };
/* Per-chip-type configuration constants */
struct ina2xx_config {
uint16_t config_default;
uint16_t calibration_value;
int shunt_div; /* shunt voltage divider (LSB factor) */
int bus_voltage_shift;
int bus_voltage_lsb; /* uV per LSB */
int power_lsb_factor;
struct ina_chip_params {
uint16_t cfg_default;
uint16_t cal_value;
int shunt_lsb_div; /* shunt voltage divider (LSB factor) */
int bus_shift;
int bus_lsb_uv; /* uV per LSB */
int power_lsb_mult;
};
static const struct ina2xx_config ina2xx_configs[] = {
static const struct ina_chip_params ina_chip_params[] = {
[INA219] = {
.config_default = 0x399F, /* PGA /8 */
.calibration_value = 4096,
.shunt_div = 100,
.bus_voltage_shift = 3,
.bus_voltage_lsb = 4000, /* 4 mV */
.power_lsb_factor = 20,
.cfg_default = 0x399F, /* PGA /8 */
.cal_value = 4096,
.shunt_lsb_div = 100,
.bus_shift = 3,
.bus_lsb_uv = 4000, /* 4 mV */
.power_lsb_mult = 20,
},
[INA226] = {
.config_default = 0x4527, /* avg=16 */
.calibration_value = 2048,
.shunt_div = 400,
.bus_voltage_shift = 0,
.bus_voltage_lsb = 1250, /* 1.25 mV */
.power_lsb_factor = 25,
.cfg_default = 0x4527, /* avg=16 */
.cal_value = 2048,
.shunt_lsb_div = 400,
.bus_shift = 0,
.bus_lsb_uv = 1250, /* 1.25 mV */
.power_lsb_mult = 25,
},
[INA234] = {
.config_default = 0x4527, /* same as INA226 */
.calibration_value = 2048,
.shunt_div = 400,
.bus_voltage_shift = 4,
.bus_voltage_lsb = 25600, /* 25.6 mV */
.power_lsb_factor = 32,
.cfg_default = 0x4527, /* same as INA226 */
.cal_value = 2048,
.shunt_lsb_div = 400,
.bus_shift = 4,
.bus_lsb_uv = 25600, /* 25.6 mV */
.power_lsb_mult = 32,
},
};
struct ina2xx_softc {
device_t dev;
enum ina2xx_chip chip;
const struct ina2xx_config *config;
const struct ina_chip_params *config;
uint32_t rshunt; /* shunt resistance, uOhm */
long current_lsb_uA;
long power_lsb_uW;
@ -113,7 +114,7 @@ ina2xx_write_reg(device_t dev, uint8_t reg, uint16_t val)
}
/* ================================================================
* Measurement value conversion (matches Linux ina2xx_get_value)
* Measurement value conversion
* ================================================================ */
static int
@ -122,11 +123,11 @@ ina2xx_read_bus_voltage(struct ina2xx_softc *sc, int *millivolts)
uint16_t raw;
int error;
error = ina2xx_read_reg(sc->dev, INA2XX_BUS_VOLTAGE, &raw);
error = ina2xx_read_reg(sc->dev, INA_REG_BUS, &raw);
if (error != 0)
return (error);
*millivolts = ((raw >> sc->config->bus_voltage_shift) *
sc->config->bus_voltage_lsb) / 1000;
*millivolts = ((raw >> sc->config->bus_shift) *
sc->config->bus_lsb_uv) / 1000;
return (0);
}
@ -136,11 +137,11 @@ ina2xx_read_shunt_voltage(struct ina2xx_softc *sc, int *microvolts)
uint16_t raw;
int error;
error = ina2xx_read_reg(sc->dev, INA2XX_SHUNT_VOLTAGE, &raw);
error = ina2xx_read_reg(sc->dev, INA_REG_SHUNT, &raw);
if (error != 0)
return (error);
/* Shunt voltage register is signed */
*microvolts = (int16_t)raw * 1000 / sc->config->shunt_div;
*microvolts = (int16_t)raw * 1000 / sc->config->shunt_lsb_div;
return (0);
}
@ -150,7 +151,7 @@ ina2xx_read_current(struct ina2xx_softc *sc, int *milliamps)
uint16_t raw;
int error;
error = ina2xx_read_reg(sc->dev, INA2XX_CURRENT, &raw);
error = ina2xx_read_reg(sc->dev, INA_REG_CURRENT, &raw);
if (error != 0)
return (error);
/* Current register is signed */
@ -164,7 +165,7 @@ ina2xx_read_power(struct ina2xx_softc *sc, int *milliwatts)
uint16_t raw;
int error;
error = ina2xx_read_reg(sc->dev, INA2XX_POWER, &raw);
error = ina2xx_read_reg(sc->dev, INA_REG_POWER, &raw);
if (error != 0)
return (error);
/* Power register is unsigned */
@ -280,7 +281,7 @@ ina2xx_attach(device_t dev)
phandle_t node;
struct sysctl_oid *oid;
uint32_t shunt;
long dividend;
long shunt_lsb_nv;
int error;
sc = device_get_softc(dev);
@ -288,13 +289,13 @@ ina2xx_attach(device_t dev)
cd = ofw_bus_search_compatible(dev, compat_data);
sc->chip = (enum ina2xx_chip)cd->ocd_data;
sc->config = &ina2xx_configs[sc->chip];
sc->config = &ina_chip_params[sc->chip];
node = ofw_bus_get_node(dev);
/* Read shunt resistance from DT (micro-ohms), default 10 mOhm */
if (OF_getencprop(node, "shunt-resistor", &shunt, sizeof(shunt)) <= 0)
shunt = INA2XX_RSHUNT_DEFAULT;
shunt = INA_RSHUNT_DEFAULT;
sc->rshunt = shunt;
/* Read label from DT */
@ -303,21 +304,21 @@ ina2xx_attach(device_t dev)
sc->label[sizeof(sc->label) - 1] = '\0';
/* Compute current and power LSBs */
dividend = 1000000000L / sc->config->shunt_div;
sc->current_lsb_uA = dividend / (long)sc->rshunt;
sc->power_lsb_uW = sc->config->power_lsb_factor * sc->current_lsb_uA;
shunt_lsb_nv = 1000000000L / sc->config->shunt_lsb_div;
sc->current_lsb_uA = shunt_lsb_nv / (long)sc->rshunt;
sc->power_lsb_uW = sc->config->power_lsb_mult * sc->current_lsb_uA;
/* Program configuration register */
error = ina2xx_write_reg(dev, INA2XX_CONFIG,
sc->config->config_default);
error = ina2xx_write_reg(dev, INA_REG_CONFIG,
sc->config->cfg_default);
if (error != 0) {
device_printf(dev, "failed to write config register\n");
return (ENXIO);
}
/* Program calibration register */
error = ina2xx_write_reg(dev, INA2XX_CALIBRATION,
sc->config->calibration_value);
error = ina2xx_write_reg(dev, INA_REG_CAL,
sc->config->cal_value);
if (error != 0) {
device_printf(dev, "failed to write calibration register\n");
return (ENXIO);

View file

@ -1,9 +1,12 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0-only
*
* Copyright 2026 Mono Technologies Inc.
* Author: Tomaz Zaman <tomaz@mono.si>
*
* Uses lp5812.h from TI's Linux LP5812 driver (GPL-2.0-only),
* Copyright (C) 2025 Texas Instruments.
*
* TI LP5812 I2C LED Driver for FreeBSD
*
* Controls up to 12 LED channels via I2C in direct (non-multiplexed) mode.
@ -54,7 +57,7 @@
#include "iicbus_if.h"
/* ----------------------------------------------------------------
* LP5812 Register definitions (from leds-lp5812.h)
* LP5812 Register definitions (from LP5812 datasheet)
* ---------------------------------------------------------------- */
#define LP5812_REG_ENABLE 0x0000
@ -177,7 +180,7 @@ lp5812_init_device(struct lp5812_softc *sc)
{
int err;
/* Stabilization delay (1ms, matches Linux driver) */
/* Stabilization delay (1ms per LP5812 datasheet) */
DELAY(1100);
/* Enable chip */

View file

@ -7,7 +7,7 @@
# Makefile's fetch-vendor target into _vendor/.
#
# Copyright 2026 Mono Technologies Inc.
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0
VENDORDIR?= ${.CURDIR}/../../_vendor
MLANDIR= ${VENDORDIR}/mwifiex/mlan

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_11ac.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_11ax.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_11d.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_11h.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_11n.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_11n_aggr.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_11n_rxreorder.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_cfp.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_cmdevt.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_init.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_join.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_meas.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_misc.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_pcie.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_scan.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_shim.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_sta_cmd.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_sta_cmdresp.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_sta_event.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_sta_ioctl.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_sta_rx.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_sta_tx.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_txrx.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_uap_cmdevent.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_uap_ioctl.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_uap_txrx.c

View file

@ -1 +0,0 @@
/usr/deps/_vendor/mwifiex/mlan/mlan_wmm.c

View file

@ -1,7 +1,8 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0
*
* Copyright 2026 Mono Technologies Inc.
* Copyright 2008-2025 NXP
*
* NXP 88W9098 PCIe WiFi driver — FreeBSD OS abstraction header.
* This replaces mlinux/moal_main.h for the FreeBSD port.

View file

@ -1,7 +1,8 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0
*
* Copyright 2026 Mono Technologies Inc.
* Copyright 2008-2025 NXP
*
* NXP 88W9098 PCIe WiFi driver — FreeBSD OS abstraction (moal_shim).
* Implements the moal_callbacks function pointer table that mlan calls.

View file

@ -1,7 +1,8 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0
*
* Copyright 2026 Mono Technologies Inc.
* Copyright 2008-2025 NXP
*
* NXP 88W9098 PCIe WiFi driver — PCI probe/attach with mlan integration.
*/
@ -956,6 +957,10 @@ mwifiex_sysctl_uap_ssid(SYSCTL_HANDLER_ARGS)
return (0);
}
/*
* Write-only: sysctl reads are open to every local user, so a read
* returns an empty string, never the passphrase.
*/
static int
mwifiex_sysctl_uap_passphrase(SYSCTL_HANDLER_ARGS)
{
@ -963,12 +968,15 @@ mwifiex_sysctl_uap_passphrase(SYSCTL_HANDLER_ARGS)
char buf[65];
int error;
strlcpy(buf, handle->uap_passphrase, sizeof(buf));
buf[0] = '\0';
error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
if (error || req->newptr == NULL)
if (error || req->newptr == NULL) {
explicit_bzero(buf, sizeof(buf));
return (error);
}
strlcpy(handle->uap_passphrase, buf,
sizeof(handle->uap_passphrase));
explicit_bzero(buf, sizeof(buf));
return (0);
}
@ -1545,7 +1553,7 @@ mwifiex_attach(device_t dev)
CTLFLAG_MPSAFE,
handle, 0,
mwifiex_sysctl_uap_passphrase, "A",
"UAP WPA2 passphrase");
"UAP WPA2 passphrase (write-only)");
SYSCTL_ADD_PROC(ctx,
SYSCTL_CHILDREN(tree), OID_AUTO,
"uap_channel",

View file

@ -1,7 +1,8 @@
/*-
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0
*
* Copyright 2026 Mono Technologies Inc.
* Copyright 2008-2025 NXP
*
* NXP 88W9098 PCIe WiFi driver — register definitions and softc.
*/

View file

@ -1 +0,0 @@
/usr/deps/_vendor/imx-firmware/FwImage_9098_PCIE/pcieuart9098_combo_v1.bin

View file

@ -6,7 +6,7 @@
# MACHINE=arm64 MACHINE_ARCH=aarch64 CC=cc LD=ld.lld
#
# Copyright 2026 Mono Technologies Inc.
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0+
KMOD= auto_bridge

View file

@ -8,7 +8,10 @@
* FreeBSD port of the Linux auto_bridge kernel module.
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* Copyright (C) 2007 Mindspeed Technologies, Inc.
* Copyright 2015-2016 Freescale Semiconductor, Inc.
* Copyright 2017, 2021 NXP
* SPDX-License-Identifier: GPL-2.0+
*/
#include <sys/param.h>

View file

@ -6,7 +6,10 @@
* /dev/autobridge character device.
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* Copyright (C) 2007 Mindspeed Technologies, Inc.
* Copyright 2015-2016 Freescale Semiconductor, Inc.
* Copyright 2017, 2021 NXP
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef AUTO_BRIDGE_H

View file

@ -2,7 +2,10 @@
* auto_bridge_private.h — Kernel-private structures
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* Copyright (C) 2007 Mindspeed Technologies, Inc.
* Copyright 2015-2016 Freescale Semiconductor, Inc.
* Copyright 2017, 2021 NXP
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef AUTO_BRIDGE_PRIVATE_H

View file

@ -1,7 +1,7 @@
# CDX (Conntrack Data-plane eXpress) kernel module for FreeBSD
#
# Copyright 2026 Mono Technologies Inc.
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0+
.include "../Makefile.inc"
@ -16,17 +16,16 @@ SRCS= cdx_main_freebsd.c cdx_timer_freebsd.c cdx_cmdhandler_freebsd.c \
cdx_ifstats_freebsd.c cdx_debug_freebsd.c \
cdx_qos_freebsd.c cdx_mc_freebsd.c \
cdx_devoh_freebsd.c cdx_reassm_freebsd.c \
cdx_ceetm_freebsd.c \
dpa_ipsec_freebsd.c cdx_dpa_ipsec_freebsd.c
cdx_ceetm_freebsd.c
# Tier 1 CDX sources (from original CDX tree, mostly unchanged)
SRCS+= cdx_hal.c \
layer2.c control_ipv4.c control_ipv6.c control_tx.c control_rx.c \
control_vlan.c control_lagg.c control_pppoe.c control_bridge.c control_tunnel.c \
control_socket.c control_stat.c control_natpt.c control_qm.c \
control_wifi.c control_ipsec.c control_rtp_relay.c \
control_wifi.c control_rtp_relay.c \
control_pktcap.c \
query_Rx.c query_ipsec.c
query_Rx.c
SRCS+= opt_platform.h opt_dpaa.h device_if.h bus_if.h ofw_bus_if.h
@ -41,7 +40,10 @@ 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, and its sources are gone): its
# exception path panicked on most decrypted packet sizes, handed packets to
# the stack without a receive interface and skipped enc0 filtering (audit
# V2). FreeBSD's IPsec stack handles all IPsec.
CFLAGS+= -DWIFI_ENABLE
# NCSW build environment defines (replicate dflags_arm64.h without its
@ -84,11 +86,9 @@ CFLAGS.control_stat.c+= ${VENDOR_WARN}
CFLAGS.control_natpt.c+= ${VENDOR_WARN}
CFLAGS.control_qm.c+= ${VENDOR_WARN}
CFLAGS.control_wifi.c+= ${VENDOR_WARN}
CFLAGS.control_ipsec.c+= ${VENDOR_WARN}
CFLAGS.control_rtp_relay.c+= ${VENDOR_WARN}
CFLAGS.control_pktcap.c+= ${VENDOR_WARN}
CFLAGS.query_Rx.c+= ${VENDOR_WARN}
CFLAGS.query_ipsec.c+= ${VENDOR_WARN}
# cdx_ehash.c is ported vendor code (originally cdx-5.03.1/cdx_ehash.c)
CFLAGS.cdx_ehash.c+= ${VENDOR_WARN}
@ -96,8 +96,4 @@ CFLAGS.cdx_ehash.c+= ${VENDOR_WARN}
# cdx_mc_freebsd.c is ported vendor code (originally dpa_control_mc.c + cdx_mc_query.c)
CFLAGS.cdx_mc_freebsd.c+= ${VENDOR_WARN}
# IPsec offload — ported from cdx-5.03.1/dpa_ipsec.c + cdx_dpa_ipsec.c
CFLAGS.dpa_ipsec_freebsd.c+= ${VENDOR_WARN}
CFLAGS.cdx_dpa_ipsec_freebsd.c+= ${VENDOR_WARN}
.include <bsd.kmod.mk>

View file

@ -9,7 +9,7 @@
* Copyright 2017-2018,2021 NXP
* Copyright 2026 Mono Technologies Inc.
*
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0+
*/
#include <sys/param.h>

View file

@ -15,7 +15,7 @@
* Copyright 2017-2018,2021-2022 NXP
* Copyright 2026 Mono Technologies Inc.
*
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0+
*/
#include <sys/param.h>

View file

@ -8,8 +8,10 @@
* fman_info for use by the CDX runtime.
*
* Copyright (c) 2026 Mono Technologies Inc.
* Copyright 2014-2016 Freescale Semiconductor, Inc.
* Copyright 2017-2022 NXP
*
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0+
*/
#include <sys/param.h>

View file

@ -1,7 +1,9 @@
/*
* Copyright (c) 2026 Mono Technologies Inc.
* Copyright 2014-2016 Freescale Semiconductor, Inc.
* Copyright 2017-2022 NXP
*
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef CDX_DPA_BRIDGE_H

View file

@ -13,7 +13,7 @@
* Copyright 2017-2018,2021-2022 NXP
* Copyright 2026 Mono Technologies Inc.
*
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0+
*/
#include <sys/param.h>

View file

@ -9,8 +9,10 @@
* cdx_dpa_bridge_destroy() to safely tear down state.
*
* Copyright (c) 2026 Mono Technologies Inc.
* Copyright 2014-2016 Freescale Semiconductor, Inc.
* Copyright 2017-2022 NXP
*
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0+
*/
#include <sys/param.h>

View file

@ -1,7 +1,9 @@
/*
* Copyright (c) 2026 Mono Technologies Inc.
* Copyright 2014-2016 Freescale Semiconductor, Inc.
* Copyright 2017-2022 NXP
*
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef CDX_DPA_INIT_H

File diff suppressed because it is too large Load diff

View file

@ -16,7 +16,6 @@
* - cdx_qos_freebsd.c (QoS / policer)
* - cdx_mc_freebsd.c (multicast)
* - cdx_debug_freebsd.c (debug display)
* - dpa_ipsec_freebsd.c (IPsec SA management)
* - cdx_reassm_freebsd.c (IP reassembly)
* - cdx_ceetm_freebsd.c (CEETM QoS)
*
@ -188,4 +187,18 @@ 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: IPsec offload is gone (see Makefile), so no
* SA is ever programmed and none is found; the conntrack code that asks
* refuses conntracks naming an SA.
*/
#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

@ -17,7 +17,7 @@
* Copyright 2017-2018,2021-2022 NXP
* Copyright 2026 Mono Technologies Inc.
*
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0+
*/
#include <sys/param.h>

View file

@ -13,7 +13,7 @@
* Copyright 2017,2021 NXP
* Copyright 2026 Mono Technologies Inc.
*
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0+
*/
#include <sys/param.h>

View file

@ -292,7 +292,7 @@ cdx_module_init(void)
}
register_cdx_deinit_func(cdx_deinit_ip_reassembly);
/* IPsec SA management done via FCI/CMM path (dpa_ipsec_freebsd.c) */
/* No IPsec offload: FreeBSD's IPsec stack handles all IPsec */
exit:
if (rc) {

View file

@ -20,7 +20,7 @@
* Copyright 2017-2018,2021 NXP
* Copyright 2026 Mono Technologies Inc.
*
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0+
*/
#include <sys/param.h>

View file

@ -9,9 +9,11 @@
* start_init), adapted for use from loadable kernel modules.
*
* Copyright (c) 2026 Mono Technologies Inc.
* Copyright 2014-2016 Freescale Semiconductor, Inc.
* Copyright 2017-2022 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0+
*/
#include <sys/param.h>

View file

@ -1,723 +0,0 @@
/*
* DPAA IPsec plumbing layer — FreeBSD port.
*
* Ported from ASK/cdx-5.03.1/dpa_ipsec.c. Provides the DPAA
* infrastructure for CDX inline IPsec offload:
* - Per-SA frame queue creation/teardown (FQ_TO_SEC, FQ_FROM_SEC, FQ_TO_CP)
* - IPsec OH port discovery and channel setup
* - Slow-path exception handler for FQ_TO_CP (decrypted miss packets)
* - Buffer pool info for CAAM preheader (BPID/BSIZE)
* - sec_descriptor allocation (64-byte aligned)
*
* Uses FreeBSD NCSW QMan API (qman_fqr_create_ctx, qman_fqr_create,
* qman_fqr_register_cb, qman_fqr_free) instead of Linux SDK QMan API.
*
* Copyright 2014-2016 Freescale Semiconductor, Inc.
* Copyright 2017,2021 NXP
* Copyright 2026 Mono Technologies Inc.
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include "portdefs.h"
#include "cdx.h"
#include "cdx_ioctl.h"
#include "misc.h"
#include "dpa_ipsec.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <net/if.h>
#include <net/if_var.h>
#include <net/netisr.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <vm/vm.h>
#include <vm/pmap.h>
#include <vm/uma.h>
/* DPAA kernel headers */
#include <dev/dpaa/qman.h>
#include <dev/dpaa/bman.h>
#include <dev/dpaa/dpaa_oh.h>
/* NCSW types */
#include <contrib/ncsw/inc/ncsw_ext.h>
#include <contrib/ncsw/inc/integrations/dpaa_integration_ext.h>
MALLOC_DECLARE(M_CDX);
#define DPAIPSEC_CELL_INDEX 3 /* OH port cell-index for IPsec */
#define IPSEC_WQ_ID 2 /* Work queue for per-SA FQs */
/* Buffer size for IPsec BMan pool — same as FM_PORT_BUFFER_SIZE (9600+64) */
#define IPSEC_BUFFER_SIZE (9600 + 64)
#define DPAIPSEC_ERROR(fmt, ...) \
printf("cdx_ipsec: " fmt, ## __VA_ARGS__)
#define DPAIPSEC_INFO(fmt, ...) \
printf("cdx_ipsec: " fmt, ## __VA_ARGS__)
/* ================================================================
* Per-SA info — holds sec_descriptor + 3 FQR handles
* ================================================================ */
struct dpa_ipsec_sainfo {
void *shdesc_mem; /* raw allocation (for free) */
struct sec_descriptor *shared_desc; /* 64-byte aligned */
t_Handle fqr[NUM_FQS_PER_SA]; /* NCSW FQR handles */
uint32_t fqid[NUM_FQS_PER_SA]; /* resolved FQIDs */
};
/* ================================================================
* IPsec instance singleton — one per CDX module lifetime
* ================================================================ */
struct ipsec_info {
uint32_t crypto_channel_id; /* CAAM DCP channel */
device_t oh_dev; /* OH port device_t */
uint32_t ofport_channel; /* OH port QMan channel */
uint32_t ipsec_bpid; /* buffer pool ID for CAAM output */
uint32_t ipsec_buf_size; /* buffer size in that pool */
t_Handle ipsec_pool; /* BMan pool handle */
uma_zone_t ipsec_zone; /* UMA zone for pool buffers */
int initialized;
};
static struct ipsec_info ipsecinfo;
/* Interface list from cdx_devman_freebsd.c / cdx_dpa_stub.c */
extern struct dpa_iface_info *dpa_interface_info;
/* ================================================================
* Accessor functions — called by Tier 1 control_ipsec.c
* ================================================================ */
void *
dpa_get_ipsec_instance(void)
{
return (&ipsecinfo);
}
struct sec_descriptor *
get_shared_desc(void *handle)
{
struct dpa_ipsec_sainfo *sa = (struct dpa_ipsec_sainfo *)handle;
return (sa->shared_desc);
}
uint32_t
get_fqid_to_sec(void *handle)
{
struct dpa_ipsec_sainfo *sa = (struct dpa_ipsec_sainfo *)handle;
return (sa->fqid[FQ_TO_SEC]);
}
uint32_t
get_fqid_from_sec(void *handle)
{
struct dpa_ipsec_sainfo *sa = (struct dpa_ipsec_sainfo *)handle;
return (sa->fqid[FQ_FROM_SEC]);
}
#ifdef UNIQUE_IPSEC_CP_FQID
uint32_t
ipsec_get_to_cp_fqid(void *handle)
{
struct dpa_ipsec_sainfo *sa = (struct dpa_ipsec_sainfo *)handle;
return (sa->fqid[FQ_TO_CP]);
}
#endif
/* ================================================================
* OH port table descriptor — used for classification table lookups
* ================================================================ */
/* From cdx_devoh_freebsd.c */
extern void *get_oh_port_td(uint32_t fm_index, uint32_t port_idx,
uint32_t type);
int
dpa_ipsec_ofport_td(struct ipsec_info *info __unused, uint32_t table_type,
void **td, uint32_t *portid)
{
struct dpa_iface_info *p;
if (table_type >= MAX_MATCH_TABLES) {
DPAIPSEC_ERROR("invalid table type %u\n", table_type);
return (-1);
}
/*
* Walk interface list to find the IPsec OH port.
* Table descriptors are stored in cdx_devoh_freebsd.c's
* offline_port_info[][] — use get_oh_port_td() accessor.
*/
for (p = dpa_interface_info; p != NULL; p = p->next) {
if ((p->if_flags & (1 << 8)) == 0) /* IF_TYPE_OFPORT */
continue;
if (p->oh_info.port_idx != DPAIPSEC_CELL_INDEX)
continue;
*td = get_oh_port_td(p->oh_info.fman_idx,
p->oh_info.port_idx, table_type);
*portid = p->oh_info.portid;
return (0);
}
DPAIPSEC_ERROR("IPsec OH port not found in interface list\n");
return (-1);
}
/* ================================================================
* Buffer pool info — used by preheader for CAAM output buffers
* ================================================================ */
int
cdx_dpa_get_ipsec_pool_info(uint32_t *bpid, uint32_t *buf_size)
{
if (!ipsecinfo.initialized) {
DPAIPSEC_ERROR("ipsec not initialized\n");
return (-1);
}
*bpid = ipsecinfo.ipsec_bpid;
*buf_size = ipsecinfo.ipsec_buf_size;
return (0);
}
/*
* Dedicated IPsec BMan buffer pool.
*
* CAAM QI acquires output buffers from BMan using the BPID in the
* preheader. Using a dedicated pool avoids competing with FMan RX
* for buffers from the dtsec pool — the same starvation pattern
* that caused the dtsec 256→2048 buffer fix.
*/
static t_Error
ipsec_pool_put_buffer(t_Handle h_BufferPool, uint8_t *buffer,
t_Handle context __unused)
{
uma_zfree(ipsecinfo.ipsec_zone, buffer);
return (E_OK);
}
static uint8_t *
ipsec_pool_get_buffer(t_Handle h_BufferPool, t_Handle *context)
{
return (uma_zalloc(ipsecinfo.ipsec_zone, M_NOWAIT));
}
static void
ipsec_pool_depleted(t_Handle h_App, bool in)
{
if (!in)
return;
while (bman_count(ipsecinfo.ipsec_pool) < IPSEC_BUFCOUNT)
bman_pool_fill(ipsecinfo.ipsec_pool, IPSEC_BUFCOUNT);
}
static int
ipsec_pool_create(struct ipsec_info *info)
{
uint8_t bpid;
info->ipsec_buf_size = IPSEC_BUFFER_SIZE;
info->ipsec_zone = uma_zcreate("cdx_ipsec_bufs", IPSEC_BUFFER_SIZE,
NULL, NULL, NULL, NULL, 255 /* 256-byte align for DMA */, 0);
if (info->ipsec_zone == NULL) {
DPAIPSEC_ERROR("failed to create UMA zone\n");
return (-1);
}
info->ipsec_pool = bman_pool_create(&bpid,
IPSEC_BUFFER_SIZE,
0, 0, /* no software stockpile */
IPSEC_BUFCOUNT, /* pre-seed 512 buffers */
ipsec_pool_get_buffer,
ipsec_pool_put_buffer,
IPSEC_BUFCOUNT / 4, /* depletion entry threshold */
IPSEC_BUFCOUNT / 2, /* depletion exit threshold */
0, 0, /* no HW depletion */
ipsec_pool_depleted, info, NULL, NULL);
if (info->ipsec_pool == NULL) {
DPAIPSEC_ERROR("failed to create BMan pool\n");
uma_zdestroy(info->ipsec_zone);
info->ipsec_zone = NULL;
return (-1);
}
info->ipsec_bpid = bpid;
DPAIPSEC_INFO("IPsec pool: bpid %u, buf_size %u, count %u\n",
info->ipsec_bpid, info->ipsec_buf_size,
bman_count(info->ipsec_pool));
return (0);
}
static void
ipsec_pool_destroy(struct ipsec_info *info)
{
if (info->ipsec_pool != NULL) {
bman_pool_destroy(info->ipsec_pool);
info->ipsec_pool = NULL;
}
if (info->ipsec_zone != NULL) {
uma_zdestroy(info->ipsec_zone);
info->ipsec_zone = NULL;
}
}
/* ================================================================
* Slow-path exception handler — FQ_TO_CP callback
*
* Decrypted packets that don't match any fast-path flow entry
* arrive here via the OH port's miss path. Convert the BMan
* buffer to an mbuf and deliver to the FreeBSD network stack.
* ================================================================ */
static uint32_t ipsec_exception_pkt_cnt;
static e_RxStoreResponse
ipsec_exception_pkt_handler(t_Handle app __unused, t_Handle qm_fqr __unused,
t_Handle qm_portal __unused, uint32_t fqid_offset __unused,
t_DpaaFD *fd)
{
struct mbuf *m;
void *frame_va;
uint32_t fd_status, fd_length, fd_offset;
uint8_t fd_format;
ipsec_exception_pkt_cnt++;
/*
* Only handle short single-buffer (SBSF) frames for now.
* Format is in elion bits [7:5] (NCSW t_DpaaFD).
*/
fd_format = (fd->elion >> 5) & 0x3;
if (fd_format != 0) {
DPAIPSEC_ERROR("exception: unsupported FD format %u\n",
fd_format);
goto release;
}
fd_status = fd->status;
/* Short SBSF: length[28:20] = offset (9 bits), length[19:0] = len */
fd_length = fd->length & 0xFFFFF;
fd_offset = (fd->length >> 20) & 0x1FF;
/* Check for SEC errors */
if (fd_status & 0xFF000000) {
DPAIPSEC_ERROR("exception: SEC error status 0x%08x\n",
fd_status);
goto release;
}
/* Get virtual address from physical */
frame_va = (void *)PHYS_TO_DMAP(
((uint64_t)fd->addrh << 32) | fd->addrl);
if (frame_va == NULL)
goto release;
/*
* Build an mbuf wrapping the frame data.
* The decrypted frame starts at frame_va + fd_offset.
*/
m = m_gethdr(M_NOWAIT, MT_DATA);
if (m == NULL)
goto release;
/*
* Copy frame data into the mbuf. For the exception path (slow
* path), a copy is acceptable. The BMan buffer is released
* immediately after.
*/
if (fd_length > MHLEN) {
if (m_cljget(m, M_NOWAIT, fd_length) == NULL) {
m_freem(m);
goto release;
}
}
m_copyback(m, 0, fd_length, (char *)frame_va + fd_offset);
m->m_pkthdr.len = fd_length;
m->m_len = fd_length;
/*
* Deliver the decrypted packet to the IP input path.
* The frame should be a raw IP packet (ESP headers stripped).
*/
{
struct ip *ip;
if (m->m_len < (int)sizeof(struct ip)) {
m_freem(m);
goto release;
}
ip = mtod(m, struct ip *);
if (ip->ip_v == IPVERSION) {
m->m_pkthdr.rcvif = NULL;
netisr_dispatch(NETISR_IP, m);
} else if (ip->ip_v == 6) {
m->m_pkthdr.rcvif = NULL;
netisr_dispatch(NETISR_IPV6, m);
} else {
DPAIPSEC_ERROR("exception: unknown IP version %u\n",
ip->ip_v);
m_freem(m);
}
}
release:
/* Release BMan buffer back to the IPsec pool */
if (ipsecinfo.ipsec_pool != NULL) {
void *buf_va;
buf_va = (void *)PHYS_TO_DMAP(
((uint64_t)fd->addrh << 32) | fd->addrl);
if (buf_va != NULL)
bman_put_buffer(ipsecinfo.ipsec_pool, buf_va);
}
return (e_RX_STORE_RESPONSE_CONTINUE);
}
/* ================================================================
* Per-SA allocation / teardown
* ================================================================ */
/*
* Allocate per-SA resources: sec_descriptor + 3 FQs.
*
* FQ creation order (to resolve FQID dependencies):
* 1. FQ_TO_CP — SW portal channel, DQRR callback
* 2. FQ_FROM_SEC — OH port channel, context_b = FQ_TO_CP FQID
* 3. FQ_TO_SEC — CAAM DCP channel, context_a = sec_desc phys,
* context_b = FQ_FROM_SEC FQID
*/
void *
cdx_dpa_ipsecsa_alloc(struct ipsec_info *info, uint32_t handle __unused)
{
struct dpa_ipsec_sainfo *sainfo;
t_QmContextA context_a;
t_QmContextB context_b;
uint64_t desc_pa;
if (!info || !ipsecinfo.initialized) {
DPAIPSEC_ERROR("ipsec not initialized in sa_alloc\n");
return (NULL);
}
sainfo = malloc(sizeof(*sainfo), M_CDX, M_WAITOK | M_ZERO);
/*
* Allocate sec_descriptor with 64-byte alignment.
* Raw allocation stored for free; aligned pointer for use.
*/
sainfo->shdesc_mem = malloc(sizeof(struct sec_descriptor) +
PRE_HDR_ALIGN, M_CDX, M_WAITOK | M_ZERO);
sainfo->shared_desc = (struct sec_descriptor *)
roundup2((uintptr_t)sainfo->shdesc_mem, PRE_HDR_ALIGN);
/*
* Step 1: Create FQ_TO_CP — scheduled to CPU 0's SW portal.
* This FQ receives decrypted slow-path packets from the OH port.
*/
sainfo->fqr[FQ_TO_CP] = qman_fqr_create(1,
(e_QmFQChannel)e_QM_FQ_CHANNEL_SWPORTAL0,
IPSEC_WQ_ID,
FALSE, /* don't force FQID */
0, /* alignment */
FALSE, /* not parked */
TRUE, /* holdActive — keep portal affinity */
TRUE, /* preferInCache */
FALSE, /* no congestion avoidance */
NULL, /* no CG handle */
0, /* no overhead accounting */
0); /* no tail drop */
if (sainfo->fqr[FQ_TO_CP] == NULL) {
DPAIPSEC_ERROR("failed to create FQ_TO_CP\n");
goto err_cp;
}
sainfo->fqid[FQ_TO_CP] = qman_fqr_get_base_fqid(sainfo->fqr[FQ_TO_CP]);
/* Register DQRR callback for exception packets */
if (qman_fqr_register_cb(sainfo->fqr[FQ_TO_CP],
ipsec_exception_pkt_handler, NULL) != E_OK) {
DPAIPSEC_ERROR("failed to register FQ_TO_CP callback\n");
goto err_from;
}
/*
* Step 2: Create FQ_FROM_SEC — OH port channel.
*
* Context-A flags:
* OVERRIDE_FQ — override destination FQ with context_b FQID
* A1_FIELD_VALID — enable A1 field (SEC error check)
* A1 value = 2 — check SEC error status
*
* Context-B = FQ_TO_CP FQID (miss destination)
*/
memset(&context_a, 0, sizeof(context_a));
context_a.res[0] =
(((CDX_FQD_CTX_A_OVERRIDE_FQ | CDX_FQD_CTX_A_A1_FIELD_VALID)
<< CDX_FQD_CTX_A_SHIFT_BITS) |
CDX_FQD_CTX_A_A1_VAL_TO_CHECK_SECERR);
context_b = sainfo->fqid[FQ_TO_CP];
sainfo->fqr[FQ_FROM_SEC] = qman_fqr_create_ctx(1,
(e_QmFQChannel)ipsecinfo.ofport_channel,
IPSEC_WQ_ID,
FALSE, /* don't force FQID */
0, /* alignment */
TRUE, /* preferInCache */
&context_a,
&context_b);
if (sainfo->fqr[FQ_FROM_SEC] == NULL) {
DPAIPSEC_ERROR("failed to create FQ_FROM_SEC\n");
goto err_from;
}
sainfo->fqid[FQ_FROM_SEC] = qman_fqr_get_base_fqid(
sainfo->fqr[FQ_FROM_SEC]);
/*
* Step 3: Create FQ_TO_SEC — CAAM DCP channel.
*
* Context-A = physical address of sec_descriptor (preheader + shdesc).
* CAAM QI reads the shared descriptor from this address.
*
* Context-B = FQ_FROM_SEC FQID (CAAM response destination).
*/
desc_pa = vtophys(sainfo->shared_desc);
memset(&context_a, 0, sizeof(context_a));
context_a.res[0] = (uint32_t)(desc_pa >> 32);
context_a.res[1] = (uint32_t)(desc_pa);
context_b = sainfo->fqid[FQ_FROM_SEC];
sainfo->fqr[FQ_TO_SEC] = qman_fqr_create_ctx(1,
e_QM_FQ_CHANNEL_CAAM,
IPSEC_WQ_ID,
FALSE, /* don't force FQID */
0, /* alignment */
TRUE, /* preferInCache */
&context_a,
&context_b);
if (sainfo->fqr[FQ_TO_SEC] == NULL) {
DPAIPSEC_ERROR("failed to create FQ_TO_SEC\n");
goto err_to;
}
sainfo->fqid[FQ_TO_SEC] = qman_fqr_get_base_fqid(
sainfo->fqr[FQ_TO_SEC]);
DPAIPSEC_INFO("SA alloc: to_sec=%u from_sec=%u to_cp=%u desc_pa=0x%lx\n",
sainfo->fqid[FQ_TO_SEC], sainfo->fqid[FQ_FROM_SEC],
sainfo->fqid[FQ_TO_CP], (unsigned long)desc_pa);
return (sainfo);
err_to:
qman_fqr_free(sainfo->fqr[FQ_FROM_SEC]);
err_from:
if (sainfo->fqr[FQ_TO_CP] != NULL)
qman_fqr_free(sainfo->fqr[FQ_TO_CP]);
err_cp:
free(sainfo->shdesc_mem, M_CDX);
free(sainfo, M_CDX);
return (NULL);
}
/*
* Retire a single per-SA FQ.
*
* On Linux, this calls qman_retire_fq() which transitions the FQ to
* "retiring" state asynchronously. On FreeBSD, NCSW qman_fqr_free()
* does full retire+OOS synchronously. We just free the FQ here and
* NULL it out so cdx_dpa_ipsecsa_release() skips it.
*
* Returns: 0 = FQ already retired/freed, 1 = still retiring (never on NCSW).
*/
int
cdx_dpa_ipsec_retire_fq(void *handle, int fq_num)
{
struct dpa_ipsec_sainfo *sainfo;
if (handle == NULL)
return (0);
sainfo = (struct dpa_ipsec_sainfo *)handle;
if (fq_num < 0 || fq_num >= NUM_FQS_PER_SA)
return (0);
if (sainfo->fqr[fq_num] != NULL) {
qman_fqr_free(sainfo->fqr[fq_num]);
sainfo->fqr[fq_num] = NULL;
}
return (0); /* synchronous — always immediately retired */
}
/*
* Check if a per-SA FQ is in retired state.
*
* On FreeBSD, qman_fqr_free() is synchronous so the FQ is always
* fully retired (and freed) after cdx_dpa_ipsec_retire_fq().
*
* Returns: 0 = retired (OK to proceed), nonzero = still not retired.
*/
int
cdx_ipsec_sa_fq_check_if_retired_state(void *handle, int fq_num)
{
struct dpa_ipsec_sainfo *sainfo;
if (handle == NULL)
return (0); /* treat NULL as "already retired" */
sainfo = (struct dpa_ipsec_sainfo *)handle;
if (fq_num < 0 || fq_num >= NUM_FQS_PER_SA)
return (0);
/* If FQR is NULL, it's already freed (retired). Return 0 = OK. */
return (sainfo->fqr[fq_num] != NULL ? 1 : 0);
}
/*
* Release all per-SA resources: tear down FQs, free descriptor memory.
*/
int
cdx_dpa_ipsecsa_release(void *handle)
{
struct dpa_ipsec_sainfo *sainfo;
int ii;
if (handle == NULL)
return (-1);
sainfo = (struct dpa_ipsec_sainfo *)handle;
/* Free FQRs in reverse order */
for (ii = NUM_FQS_PER_SA - 1; ii >= 0; ii--) {
if (sainfo->fqr[ii] != NULL) {
qman_fqr_free(sainfo->fqr[ii]);
sainfo->fqr[ii] = NULL;
}
}
free(sainfo->shdesc_mem, M_CDX);
free(sainfo, M_CDX);
return (0);
}
/* ================================================================
* XFRM state stubs
*
* On Linux, these hold/release a reference to the kernel's xfrm_state
* to keep it alive while CDX offloads the SA. On FreeBSD there is no
* XFRM framework — CDX manages SA lifecycle independently via FCI
* commands from CMM. Return a non-NULL sentinel so the Tier 1 NULL
* check in control_ipsec.c passes.
* ================================================================ */
#define CDX_XFRM_SENTINEL ((void *)(uintptr_t)0x1)
void *
cdx_get_xfrm_state_of_sa(void *dev __unused, uint16_t handle __unused)
{
return (CDX_XFRM_SENTINEL);
}
void
cdx_dpa_ipsec_xfrm_state_dec_ref_cnt(void *xfrm_state __unused)
{
}
/* ================================================================
* SG / skb-free buffer pool stubs
*
* On Linux, these create dedicated BMan pools for scatter-gather
* and skb recycling. On FreeBSD, mbuf allocation handles this
* natively. Provide stub implementations that succeed.
* ================================================================ */
int
cdx_init_scatter_gather_bpool(void)
{
return (0);
}
int
cdx_init_skb_2bfreed_bpool(void)
{
return (0);
}
/* ================================================================
* Module init / exit
* ================================================================ */
int
cdx_dpa_ipsec_init(void)
{
device_t oh_dev;
DPAIPSEC_INFO("initializing IPsec DPAA plumbing\n");
memset(&ipsecinfo, 0, sizeof(ipsecinfo));
/* CAAM DCP channel for QI submissions */
ipsecinfo.crypto_channel_id = (uint32_t)e_QM_FQ_CHANNEL_CAAM;
/* Discover IPsec OH port (cell-index 3) */
oh_dev = dpaa_oh_find_port(DPAIPSEC_CELL_INDEX);
if (oh_dev == NULL) {
DPAIPSEC_ERROR("IPsec OH port (cell-index %d) not found\n",
DPAIPSEC_CELL_INDEX);
return (-1);
}
ipsecinfo.oh_dev = oh_dev;
ipsecinfo.ofport_channel = dpaa_oh_get_qman_channel(oh_dev);
DPAIPSEC_INFO("OH port: cell-index %d, channel 0x%x\n",
DPAIPSEC_CELL_INDEX, ipsecinfo.ofport_channel);
/* Create dedicated IPsec BMan buffer pool */
if (ipsec_pool_create(&ipsecinfo) != 0) {
DPAIPSEC_ERROR("failed to create IPsec buffer pool\n");
return (-1);
}
ipsecinfo.initialized = 1;
DPAIPSEC_INFO("IPsec DPAA plumbing initialized: "
"CAAM channel 0x%x, OH channel 0x%x, bpid %u, buf_size %u\n",
ipsecinfo.crypto_channel_id, ipsecinfo.ofport_channel,
ipsecinfo.ipsec_bpid, ipsecinfo.ipsec_buf_size);
return (0);
}
void
cdx_dpa_ipsec_exit(void)
{
DPAIPSEC_INFO("IPsec DPAA plumbing exiting\n");
ipsecinfo.initialized = 0;
ipsec_pool_destroy(&ipsecinfo);
}

View file

@ -11,7 +11,7 @@
# ssh target "cd /tmp/cmm && make && make install"
#
# Copyright 2026 Mono Technologies Inc.
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0+
PROG= cmm
NO_MAN= yes
@ -25,7 +25,6 @@ SRCS= cmm.c \
cmm_fe.c \
cmm_lagg.c \
cmm_vlan.c \
cmm_ipsec.c \
cmm_tunnel.c \
cmm_ctrl.c \
cmm_deny.c \

View file

@ -5,14 +5,14 @@
#
# Builds in the current directory (use /tmp/cmm-build or similar).
# Requires OPNsense base build first:
# sudo make -C /usr/tools base DEVICE=GATEWAY SETTINGS=26.1 TOOLSDIR=/usr/tools
# sudo make -C /usr/tools base DEVICE=GATEWAY SETTINGS=26.7 TOOLSDIR=/usr/tools
#
# Copyright 2026 Mono Technologies Inc.
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0+
SYSROOT?= /usr/obj/usr/src/arm64.aarch64/tmp
CC?= cc
TARGET?= --target=aarch64-unknown-freebsd14.3
TARGET?= --target=aarch64-unknown-freebsd15.1
SRCDIR= ${MAKEFILE:H}/..
CMM_DIR= ${SRCDIR}/cmm
@ -21,7 +21,7 @@ FCI_HDR= ${SRCDIR}/fci
CMM_SRCS= cmm.c cmm_conn.c cmm_route.c cmm_neigh.c \
cmm_itf.c cmm_rtsock.c cmm_fe.c \
cmm_lagg.c cmm_vlan.c cmm_ipsec.c cmm_tunnel.c cmm_deny.c \
cmm_lagg.c cmm_vlan.c cmm_tunnel.c cmm_deny.c \
cmm_socket.c cmm_bridge.c cmm_ctrl.c cmm_l2tp.c \
cmm_wifi.c cmm_pppoe.c cmm_mcast.c
CMM_OBJS= ${CMM_SRCS:.c=.o}

View file

@ -6,7 +6,7 @@
* hardware flow offload on the NXP LS1046A.
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* SPDX-License-Identifier: GPL-2.0+
*/
#include <sys/types.h>
@ -34,7 +34,6 @@
#include "cmm_fe.h"
#include "cmm_lagg.h"
#include "cmm_vlan.h"
#include "cmm_ipsec.h"
#include "cmm_tunnel.h"
#include "cmm_l2tp.h"
#include "cmm_deny.h"
@ -104,7 +103,6 @@ main(int argc, char *argv[])
g->rtsock_fd = -1;
g->rtsock_query_fd = -1;
g->kq = -1;
g->pfkey_fd = -1;
g->ctrl_listen_fd = -1;
g->autobridge_fd = -1;
g->pfnotify_fd = -1;
@ -300,18 +298,11 @@ main(int argc, char *argv[])
cmm_pppoe_init(g);
cmm_mcast_init();
if (cmm_ipsec_init() < 0)
goto out;
/* Load deny rules (optional — missing file means offload everything) */
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");
/* IPsec is never offloaded: FreeBSD's IPsec stack handles it all */
/* Open /dev/pfnotify — required for PF state events */
{
@ -358,13 +349,6 @@ main(int argc, char *argv[])
}
}
/* PF_KEY socket: IPsec SA events */
if (g->pfkey_fd >= 0) {
EV_SET(&kev[nev], g->pfkey_fd, EVFILT_READ,
EV_ADD, 0, 0, NULL);
nev++;
}
/* Control socket: external tool commands (cmmctl) */
if (cmm_ctrl_init(g) == 0) {
EV_SET(&kev[nev], g->ctrl_listen_fd, EVFILT_READ,
@ -395,10 +379,10 @@ main(int argc, char *argv[])
nev++;
cmm_print(CMM_LOG_DEBUG,
"fds: rtsock=%d fci=%d pfkey=%d ctrl=%d autobridge=%d pfnotify=%d",
"fds: rtsock=%d fci=%d ctrl=%d autobridge=%d pfnotify=%d",
g->rtsock_fd,
g->fci_catch ? fci_fd(g->fci_catch) : -1,
g->pfkey_fd, g->ctrl_listen_fd,
g->ctrl_listen_fd,
g->autobridge_fd, g->pfnotify_fd);
/* Validate: drop any EVFILT_READ with invalid fd */
@ -459,9 +443,6 @@ main(int argc, char *argv[])
} else if ((int)events[i].ident ==
g->rtsock_fd) {
cmm_rtsock_dispatch(g);
} else if (g->pfkey_fd >= 0 &&
(int)events[i].ident == g->pfkey_fd) {
cmm_pfkey_dispatch(g);
} else if (events[i].udata ==
(void *)(uintptr_t)3) {
/* auto_bridge: L2 flow event */
@ -483,7 +464,6 @@ main(int argc, char *argv[])
out:
/* Clean shutdown */
cmm_ctrl_fini(g);
cmm_sa_flush_all(g);
cmm_conn_deregister_all(g);
cmm_mcast_fini();
cmm_wifi_fini(g);
@ -496,7 +476,6 @@ out:
cmm_fe_reset(g);
cmm_deny_fini();
cmm_ipsec_fini(g);
cmm_conn_fini(g);
cmm_route_fini();
cmm_neigh_fini();
@ -504,8 +483,6 @@ out:
if (g->kq >= 0)
close(g->kq);
if (g->pfkey_fd >= 0)
close(g->pfkey_fd);
if (g->rtsock_fd >= 0)
close(g->rtsock_fd);
if (g->rtsock_query_fd >= 0)

View file

@ -6,7 +6,10 @@
* via FCI/CDX for hardware flow offload.
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* Copyright (C) 2007 Mindspeed Technologies, Inc.
* Copyright 2014-2016 Freescale Semiconductor, Inc.
* Copyright 2017, 2021 NXP
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef CMM_H
@ -51,7 +54,6 @@ struct cmm_global {
int rtsock_fd; /* PF_ROUTE socket (monitoring) */
int rtsock_query_fd;/* PF_ROUTE socket (RTM_GET queries) */
int kq; /* kqueue fd */
int pfkey_fd; /* PF_KEY socket */
int ctrl_listen_fd; /* control socket (listen) */
int ctrl_clients[4];/* control socket clients */
int autobridge_fd; /* /dev/autobridge (L2 bridge) */

View file

@ -10,11 +10,15 @@
* and ffbridge.c (bridge port resolution).
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* 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/sysctl.h>
#include <sys/event.h>
#include <sys/socket.h>
#include <net/if.h>
@ -579,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.
*/
@ -588,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);
@ -654,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

@ -7,7 +7,10 @@
* is a bridge, CDX needs the physical member port name).
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* Copyright (C) 2007 Mindspeed Technologies, Inc.
* Copyright 2014-2016 Freescale Semiconductor, Inc.
* Copyright 2017, 2021 NXP
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef CMM_BRIDGE_H

View file

@ -8,7 +8,10 @@
* programmed into CDX. Expired connections are removed from CDX.
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* 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>
@ -181,9 +184,68 @@ 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);
}
/*
* 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,
@ -255,6 +317,51 @@ 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
* (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
@ -287,8 +394,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);
}
}
@ -440,9 +549,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)
@ -456,8 +565,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);
}
}
@ -561,15 +674,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;
@ -585,6 +718,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));
@ -600,81 +734,73 @@ 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));
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 (route/neigh pending)");
}
"conn: offload deferred (states/route/neigh pending)");
}
/*
@ -748,6 +874,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",
@ -770,6 +909,10 @@ cmm_conn_maintenance(struct cmm_global *g)
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)) {
@ -866,30 +1009,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

@ -2,7 +2,10 @@
* cmm_conn.h — PF state table polling and connection tracking
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* Copyright (C) 2007 Mindspeed Technologies, Inc.
* Copyright 2014-2016 Freescale Semiconductor, Inc.
* Copyright 2017, 2021 NXP
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef CMM_CONN_H
@ -18,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 */
@ -36,17 +45,23 @@ 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, also for a route-to/reply-to; a
* DELETE of either removes it.
*/
struct {
uint64_t id;
uint32_t creatorid;
uint16_t veto; /* PFN_VETO_* */
uint8_t seen;
uint8_t rt; /* PFN_RT_* */
char ifname[IFNAMSIZ];
char rt_ifname[IFNAMSIZ];
uint8_t rt_addr[16]; /* route-to/reply-to next hop */
} st[2]; /* CONN_ST_IN, CONN_ST_OUT */
/* Offload state */
int flags;

View file

@ -5,7 +5,10 @@
* FPP commands to CDX via FCI. Used by cmmctl and other tools.
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* 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>

View file

@ -5,7 +5,10 @@
* (e.g., cmmctl) to send FPP commands through CMM to CDX.
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* Copyright (C) 2007 Mindspeed Technologies, Inc.
* Copyright 2014-2016 Freescale Semiconductor, Inc.
* Copyright 2017, 2021 NXP
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef CMM_CTRL_H

View file

@ -19,7 +19,10 @@
* iface=<name>
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* 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>

View file

@ -7,7 +7,10 @@
* interface name.
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* Copyright (C) 2007 Mindspeed Technologies, Inc.
* Copyright 2014-2016 Freescale Semiconductor, Inc.
* Copyright 2017, 2021 NXP
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef CMM_DENY_H

View file

@ -5,7 +5,10 @@
* already-ported libfci library.
*
* Copyright 2026 Mono Technologies Inc.
* SPDX-License-Identifier: BSD-2-Clause
* 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>

Some files were not shown because too many files have changed in this diff Show more