commit 5514d65ac564651c2b3a2fb59c28c11f440a389f Author: Tomaz Zaman Date: Wed Feb 25 00:58:56 2026 +0100 Hello world. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..eb3279d --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ +# Build output directories +dist/* +!dist/.keep +_build/ + +# Object files and libraries +*.o +*.ko +*.kld +*.a + +# Dependency tracking +.depend* + +# Kernel module build artifacts +export_syms +*_if.h +opt_*.h +machine diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..42c4ad9 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,220 @@ +# Architecture Overview + +Hardware flow offload stack for the Mono Gateway (NXP LS1046A / DPAA1). +Packets matching offloaded flows are forwarded entirely in FMan hardware, +bypassing the FreeBSD networking stack. + +## System Diagram + +``` + ┌────────────────────────────────────────────────────────────────┐ + │ USERSPACE │ + │ │ + │ ┌─────────┐ ┌─────────┐ ┌──────────┐ ┌────────────┐ │ + │ │ cmm │ │ dpa_app │ │ fand │ │ cmmctl │ │ + │ │ │ │ │ │ │ │ │ │ + │ │ offload │ │ PCD │ │ fan │ │ query/ctrl │ │ + │ │ manager │ │ setup │ │ control │ │ tool │ │ + │ └────┬────┘ └────┬────┘ └──────────┘ └─────┬──────┘ │ + │ │FCI │chardev │socket │ + │ ══════╪══════════════╪═══════════════════════════════╪═══════ │ + │ KERNEL │ │ │ + │ │ ┌────┴────┐ │ │ + │ ┌────┴────┐ │ fmc │ ┌────┴────┐ │ + │ │ fci.ko │ │ chardev │ │ cmm │ │ + │ │ │ │ (fman) │ │ ctrl │ │ + │ │ cmd/evt │ └────┬────┘ │ socket │ │ + │ │ channel │ │FM ioctl └─────────┘ │ + │ └────┬────┘ ┌────┴────────────────────────┐ │ + │ │ │ FreeBSD DPAA1 kernel │ │ + │ ┌────┴────┐ │ (dtsec, QMan, BMan, FMan) │ │ + │ │ cdx.ko │ └────┬────────────────────────┘ │ + │ │ │ │ │ + │ │ flow │ ┌────┴────┐ ┌────────────┐ ┌─────────────┐ │ + │ │ engine │ │pf_notify│ │auto_bridge │ │ caam.ko │ │ + │ └────┬────┘ │ .ko │ │ .ko │ │ (crypto) │ │ + │ │ └────┬────┘ └─────┬──────┘ └─────────────┘ │ + │ │ │ │ │ + │ ┌────┴──────────────┴─────────────┴──────────────────────┐ │ + │ │ FMan Hardware │ │ + │ │ Parser -> KeyGen -> CC/Hash Tables --> Policer/EN. │ │ + │ └────────────────────────────────────────────────────────┘ │ + └────────────────────────────────────────────────────────────────┘ +``` + +## Boot Sequence + +``` +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 +``` + +## Fastpath Modules + +### cdx.ko — Flow Offload Engine (kernel module) + +The core datapath acceleration module. Receives conntrack and route +registrations from CMM via FCI, installs flow entries in FMan's +enhanced hash tables, and executes packet transformations (NAT, +TTL decrement, MAC rewrite) in hardware. + +- **Timer wheel**: Ages out idle flows (TCP ~12h, UDP unidir ~5min) +- **Miss path**: Unmatched packets enqueue to dtsec default RX FQID (software path) +- **Notifications**: Sends `CONNTRACK_CHANGE` events back to CMM via FCI when flows expire + +Source: `fastpath/cdx/` + `fastpath/vendor/cdx/` + +### fci.ko — Fast Control Interface (kernel module) + +IPC channel between userspace (CMM) and kernel (CDX). Provides: + +- **Command path** (CMM → CDX): register/deregister routes, conntrack entries, L2 flows +- **Event path** (CDX → CMM): flow timeout notifications, TCP FIN events +- **Mechanism**: chardev with ioctl for commands, ring buffer + kqueue for async events + +Source: `fastpath/fci/` + +### pf_notify.ko — PF State Event Bridge (kernel module) + +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 + +Exposes `/dev/pfnotify` (read-only, non-blocking). Without this module, +CMM falls back to polling the PF state table every 1s. + +Source: `fastpath/pf_notify/` + +### auto_bridge.ko — L2 Bridge Flow Offload (kernel module) + +Captures L2 forwarding decisions from the FreeBSD bridge and +exposes them to CMM for hardware offload. Exposes `/dev/autobridge`. + +Source: `fastpath/auto_bridge/` + +### cmm — Connection Management Module (userspace daemon) + +The orchestrator. Monitors PF state and routing tables, resolves +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 + /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 → next poll re-offloads automatically + +Source: `fastpath/cmm/` + +### cmmctl — CMM Control Tool (userspace) + +CLI tool to query CMM state (offloaded connections, routes, stats) +via a unix domain socket. + +Source: `fastpath/cmmctl/` + +### dpa_app — PCD Configuration Tool (userspace) + +Loads FMan Parser/Classification/Distribution configuration from +XML files via the FMan chardev. Sets up the KeyGen hash schemes +and CC tree that CDX later patches with per-flow entries. + +Depends on: fmlib (FMan API), fmc (XML parser/compiler) + +Source: `fastpath/dpa_app/`, `fastpath/fmc/`, `fastpath/fmlib/` + +## Hardware Drivers + +### emc2302.ko — Fan Controller + +I2C driver for EMC2302 fan controller. Exposes sysctl interface +for fan RPM reading and PWM duty cycle control. + +Source: `drivers/emc2302/` + +### ina2xx.ko — Power Monitor + +I2C driver for INA226/INA219 current/voltage/power monitors. +Exposes sysctl interface for voltage, current, and power readings. + +Source: `drivers/ina2xx/` + +### lp5812.ko — RGB LED Controller + +I2C driver for TI LP5812 LED controller. Drives the board's +RGB status LEDs. + +Source: `drivers/lp5812/` + +### sfpled.ko — SFP+ Link LEDs + +GPIO-based LED driver that reflects SFP+ link state on +front-panel LEDs by polling dtsec link status. + +Source: `drivers/sfp-led/` + +### fand — Fan Control Daemon (userspace) + +Reads temperature sensors and adjusts fan speed via emc2302 +sysctl interface. Runs as a daemon. + +Source: `drivers/fand/` + +## Data Flow: Packet Through Hardware Offload + +``` +Wire ──► FMan RX Port + │ + ▼ + Parser (extract L3/L4 headers) + │ + ▼ + KeyGen (hash IP src/dst + L4 ports) + │ + ▼ + CC Hash Table lookup + ╱ ╲ + HIT MISS + │ │ + ▼ ▼ + CDX opcodes Default RX FQID + (NAT rewrite, (FreeBSD stack) + TTL dec, │ + MAC rewrite) ▼ + │ PF firewall + ▼ routing + FMan TX Port if_output + │ │ + ▼ ▼ + Wire Wire + (line rate) (software path) +``` + +## IPC Summary + +| Path | Mechanism | Purpose | +|------|-----------|---------| +| CMM → CDX | FCI ioctl | Register/deregister routes, conntrack, L2 flows | +| CDX → CMM | FCI ring + kqueue | Flow timeout, TCP FIN notifications | +| 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) | diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..faecb34 --- /dev/null +++ b/Makefile @@ -0,0 +1,156 @@ +# Top-level build Makefile for opnsense-deps +# +# Build everything: +# make -C /build/opnsense-deps all +# +# Clean all build artifacts: +# make -C /build/opnsense-deps clean +# +# Build subsets: +# make -C /build/opnsense-deps modules # kernel modules only +# make -C /build/opnsense-deps userspace # userspace only +# +# Parallel build (modules build concurrently): +# make -C /build/opnsense-deps -j24 all +# +# Copyright 2026 Mono Technologies Inc. +# SPDX-License-Identifier: BSD-2-Clause + +OPSDIR= ${.CURDIR} +FASTPATH= ${OPSDIR}/fastpath +DRIVERS= ${OPSDIR}/drivers + +# Cross-compilation settings (all ?= for easy override) +SRCTOP?= /build +SYSROOT?= /usr/obj${SRCTOP}/opnsense-src/arm64.aarch64/tmp +KERNBUILDDIR?= /usr/obj${SRCTOP}/opnsense-src/arm64.aarch64/sys/GATEWAY + +# Common args for all kernel module builds +# Host clang cross-compiles with explicit --target (bsd.kmod.mk does NOT add it) +KMOD_ARGS= KERNBUILDDIR=${KERNBUILDDIR} \ + MACHINE=arm64 MACHINE_ARCH=aarch64 \ + CC="cc --target=aarch64-unknown-freebsd14.3" LD=ld.lld + +# Local build directory for userspace components +BUILDDIR?= ${OPSDIR}/_build + +# Output directory for all final artifacts +DISTDIR?= ${OPSDIR}/dist + +# ============================================================ +# Top-level targets +# ============================================================ + +all: dist + +# ============================================================ +# Kernel modules (all independent — safe for -j) +# ============================================================ + +KMOD_CDX= ${FASTPATH}/cdx +KMOD_FCI= ${FASTPATH}/fci +KMOD_AB= ${FASTPATH}/auto_bridge +KMOD_PN= ${FASTPATH}/pf_notify +KMOD_EMC= ${DRIVERS}/emc2302 +KMOD_INA= ${DRIVERS}/ina2xx +KMOD_LP= ${DRIVERS}/lp5812 +KMOD_SFP= ${DRIVERS}/sfp-led + +build-cdx: + ${MAKE} -C ${KMOD_CDX} ${KMOD_ARGS} + +build-fci: + ${MAKE} -C ${KMOD_FCI} ${KMOD_ARGS} + +build-auto_bridge: + ${MAKE} -C ${KMOD_AB} ${KMOD_ARGS} + +build-pf_notify: + ${MAKE} -C ${KMOD_PN} ${KMOD_ARGS} + +build-emc2302: + ${MAKE} -C ${KMOD_EMC} ${KMOD_ARGS} + +build-ina2xx: + ${MAKE} -C ${KMOD_INA} ${KMOD_ARGS} + +build-lp5812: + ${MAKE} -C ${KMOD_LP} ${KMOD_ARGS} + +build-sfpled: + ${MAKE} -C ${KMOD_SFP} ${KMOD_ARGS} + +modules: build-cdx build-fci build-auto_bridge build-pf_notify \ + build-emc2302 build-ina2xx build-lp5812 build-sfpled + +# ============================================================ +# Userspace components (dependency order: fmlib -> fmc -> dpa_app) +# ============================================================ + +fmlib: + @mkdir -p ${BUILDDIR}/fmlib + cd ${BUILDDIR}/fmlib && ${MAKE} -f ${FASTPATH}/fmlib/Makefile.cross all + +fmc: fmlib + @mkdir -p ${BUILDDIR}/fmc + cd ${BUILDDIR}/fmc && ${MAKE} -f ${FASTPATH}/fmc/Makefile.cross \ + FMLIB_LIB=${BUILDDIR}/fmlib all + +dpa_app: fmc + @mkdir -p ${BUILDDIR}/dpa_app + cd ${BUILDDIR}/dpa_app && ${MAKE} -f ${FASTPATH}/dpa_app/Makefile.cross \ + FMLIB_LIB=${BUILDDIR}/fmlib FMC_LIB=${BUILDDIR}/fmc all + +cmm: + @mkdir -p ${BUILDDIR}/cmm + cd ${BUILDDIR}/cmm && ${MAKE} -f ${FASTPATH}/cmm/Makefile.cross all + +cmmctl: + @mkdir -p ${BUILDDIR}/cmmctl + cd ${BUILDDIR}/cmmctl && ${MAKE} -f ${FASTPATH}/cmmctl/Makefile.cross all + +fand: + @mkdir -p ${BUILDDIR}/fand + cd ${BUILDDIR}/fand && ${MAKE} -f ${DRIVERS}/fand/Makefile all + +userspace: fmlib fmc dpa_app cmm cmmctl fand + +# ============================================================ +# Collect outputs into dist/ +# ============================================================ + +dist: modules userspace + @mkdir -p ${DISTDIR} + cp ${KMOD_CDX}/cdx.ko ${DISTDIR}/ + cp ${KMOD_FCI}/fci.ko ${DISTDIR}/ + cp ${KMOD_AB}/auto_bridge.ko ${DISTDIR}/ + cp ${KMOD_PN}/pf_notify.ko ${DISTDIR}/ + cp ${KMOD_EMC}/emc2302.ko ${DISTDIR}/ + cp ${KMOD_INA}/ina2xx.ko ${DISTDIR}/ + cp ${KMOD_LP}/lp5812.ko ${DISTDIR}/ + cp ${KMOD_SFP}/sfpled.ko ${DISTDIR}/ + cp ${BUILDDIR}/fmc/fmc ${DISTDIR}/ + cp ${BUILDDIR}/dpa_app/dpa_app ${DISTDIR}/ + cp ${BUILDDIR}/cmm/cmm ${DISTDIR}/ + cp ${BUILDDIR}/cmmctl/cmmctl ${DISTDIR}/ + cp ${BUILDDIR}/fand/fand ${DISTDIR}/ + +# ============================================================ +# Clean +# ============================================================ + +clean: + ${MAKE} -C ${KMOD_CDX} ${KMOD_ARGS} clean + ${MAKE} -C ${KMOD_FCI} ${KMOD_ARGS} clean + ${MAKE} -C ${KMOD_AB} ${KMOD_ARGS} clean + ${MAKE} -C ${KMOD_PN} ${KMOD_ARGS} clean + ${MAKE} -C ${KMOD_EMC} ${KMOD_ARGS} clean + ${MAKE} -C ${KMOD_INA} ${KMOD_ARGS} clean + ${MAKE} -C ${KMOD_LP} ${KMOD_ARGS} clean + ${MAKE} -C ${KMOD_SFP} ${KMOD_ARGS} clean + rm -rf ${BUILDDIR} + +.PHONY: all modules userspace dist clean \ + build-cdx build-fci build-auto_bridge build-pf_notify \ + build-emc2302 build-ina2xx build-lp5812 build-sfpled \ + fmlib fmc dpa_app cmm cmmctl fand diff --git a/OPNsense-26.1-aarch64-GATEWAY.patch b/OPNsense-26.1-aarch64-GATEWAY.patch new file mode 100644 index 0000000..d1e3ce3 --- /dev/null +++ b/OPNsense-26.1-aarch64-GATEWAY.patch @@ -0,0 +1,26956 @@ +From 7f7033d3ae437fa667a2044b5a82c8499e85800a Mon Sep 17 00:00:00 2001 +From: Tomaz Zaman +Date: Wed, 25 Feb 2026 14:41:14 +0100 +Subject: [PATCH] Port Mono Gateway (NXP LS1046A) to OPNsense's FreeBSD 14.3 + +--- + sys/arm64/arm64/machdep.c | 1 + + sys/arm64/conf/GATEWAY | 88 + + sys/arm64/conf/caam/config.caam | 6 + + sys/arm64/conf/caam/files.caam | 12 + + sys/arm64/conf/dpaa/config.dpaa_arm64 | 29 + + sys/arm64/conf/dpaa/files.dpaa_arm64 | 131 ++ + sys/arm64/include/pio.h | 237 +++ + sys/conf/files | 3 + + sys/conf/files.arm64 | 4 +- + sys/conf/options | 1 + + .../src/arm64/freescale/mono-gateway-dk.dts | 434 ++++ + sys/contrib/ncsw/Peripherals/BM/bm.c | 48 +- + sys/contrib/ncsw/Peripherals/BM/bm.h | 3 + + sys/contrib/ncsw/Peripherals/BM/bm_pool.c | 2 + + sys/contrib/ncsw/Peripherals/BM/bm_portal.c | 19 +- + sys/contrib/ncsw/Peripherals/BM/bman_low.c | 36 +- + .../ncsw/Peripherals/BM/bman_private.h | 35 + + sys/contrib/ncsw/Peripherals/FM/HC/hc.c | 5 + + sys/contrib/ncsw/Peripherals/FM/Pcd/fm_cc.c | 201 ++ + sys/contrib/ncsw/Peripherals/FM/Pcd/fm_cc.h | 5 + + .../ncsw/Peripherals/FM/Pcd/fm_ehash.c | 1530 ++++++++++++++ + sys/contrib/ncsw/Peripherals/FM/Pcd/fm_kg.c | 25 +- + sys/contrib/ncsw/Peripherals/FM/Pcd/fm_plcr.c | 8 + + .../ncsw/Peripherals/FM/Pcd/fm_replic.c | 2 +- + .../ncsw/Peripherals/FM/Port/fm_port.c | 4 + + sys/contrib/ncsw/Peripherals/FM/fm_ncsw.c | 98 +- + .../ncsw/Peripherals/FM/inc/fm_common.h | 9 +- + sys/contrib/ncsw/Peripherals/QM/qm.c | 118 +- + sys/contrib/ncsw/Peripherals/QM/qm.h | 12 +- + .../ncsw/Peripherals/QM/qm_portal_fqr.c | 482 ++++- + sys/contrib/ncsw/Peripherals/QM/qman_low.h | 53 +- + .../ncsw/Peripherals/QM/qman_private.h | 35 + + sys/contrib/ncsw/build/dflags_arm64.h | 86 + + sys/contrib/ncsw/etc/ncsw_memcpy.c | 6 + + sys/contrib/ncsw/inc/Peripherals/bm_ext.h | 3 + + sys/contrib/ncsw/inc/Peripherals/dpaa_ext.h | 45 +- + sys/contrib/ncsw/inc/Peripherals/fm_ehash.h | 724 +++++++ + sys/contrib/ncsw/inc/Peripherals/fm_ext.h | 5 + + sys/contrib/ncsw/inc/Peripherals/fm_pcd_ext.h | 34 + + sys/contrib/ncsw/inc/Peripherals/qm_ext.h | 41 + + sys/contrib/ncsw/inc/core_ext.h | 8 +- + sys/contrib/ncsw/inc/cores/arm_ext.h | 29 +- + .../inc/integrations/dpaa_integration_ext.h | 138 +- + sys/contrib/ncsw/inc/integrations/part_ext.h | 6 + + sys/contrib/ncsw/inc/types_freebsd.h | 23 +- + sys/contrib/ncsw/user/env/core_arm64.c | 60 + + sys/contrib/ncsw/user/env/xx_arm64.c | 891 ++++++++ + sys/dev/caam/caam.c | 858 ++++++++ + sys/dev/caam/caam.h | 128 ++ + sys/dev/caam/caam_alg.c | 1183 +++++++++++ + sys/dev/caam/caam_crypto.c | 864 ++++++++ + sys/dev/caam/caam_crypto.h | 149 ++ + sys/dev/caam/caam_desc.h | 714 +++++++ + sys/dev/caam/caam_hash.c | 164 ++ + sys/dev/caam/caam_jr.c | 730 +++++++ + sys/dev/caam/caam_jr.h | 131 ++ + sys/dev/caam/caam_qi.c | 1042 +++++++++ + sys/dev/caam/caam_qi.h | 129 ++ + sys/dev/caam/caam_qi_alg.c | 905 ++++++++ + sys/dev/caam/caam_regs.h | 298 +++ + sys/dev/caam/caam_rng.c | 302 +++ + sys/dev/caam/caam_rng.h | 17 + + sys/dev/dpaa/bman.c | 76 +- + sys/dev/dpaa/bman.h | 9 +- + sys/dev/dpaa/bman_fdt.c | 21 +- + sys/dev/dpaa/bman_portals.c | 71 +- + sys/dev/dpaa/dpaa_oh.c | 566 +++++ + sys/dev/dpaa/dpaa_oh.h | 90 + + sys/dev/dpaa/fman.c | 480 ++++- + sys/dev/dpaa/fman.h | 17 + + sys/dev/dpaa/fman_chardev.c | 1777 ++++++++++++++++ + sys/dev/dpaa/fman_chardev.h | 155 ++ + sys/dev/dpaa/fman_fdt.c | 29 +- + sys/dev/dpaa/if_dtsec.c | 375 +++- + sys/dev/dpaa/if_dtsec.h | 36 +- + sys/dev/dpaa/if_dtsec_fdt.c | 123 +- + sys/dev/dpaa/if_dtsec_im.c | 3 +- + sys/dev/dpaa/if_dtsec_rm.c | 1268 +++++++++-- + sys/dev/dpaa/if_dtsec_rm.h | 6 +- + sys/dev/dpaa/memac_mdio.c | 328 +++ + sys/dev/dpaa/portals.h | 5 + + sys/dev/dpaa/portals_common.c | 93 + + sys/dev/dpaa/qman.c | 355 +++- + sys/dev/dpaa/qman.h | 37 +- + sys/dev/dpaa/qman_ceetm.c | 1874 +++++++++++++++++ + sys/dev/dpaa/qman_ceetm.h | 719 +++++++ + sys/dev/dpaa/qman_fdt.c | 19 +- + sys/dev/dpaa/qman_portals.c | 256 ++- + sys/dev/gpio/qoriq_gpio.c | 59 +- + sys/dev/iicbus/mux/iicmux.c | 3 +- + sys/dev/iicbus/mux/pca954x.c | 1 + + sys/dev/iicbus/ofw_iicbus.c | 2 +- + sys/dev/iicbus/rtc/pcf2131.c | 480 +++++ + sys/dev/iicbus/sensor/ina2xx.c | 399 ++++ + sys/dev/mii/gpyphy.c | 371 ++++ + sys/dev/mii/miidevs | 13 + + sys/dev/random/random_harvestq.c | 1 + + sys/dev/uart/uart_dev_ns8250.c | 24 + + sys/modules/dtb/freescale/Makefile | 40 +- + sys/net/if_bridge.c | 17 +- + sys/net/if_bridgevar.h | 12 + + sys/net/pfvar.h | 22 + + sys/netpfil/pf/pf.c | 24 + + sys/netpfil/pf/pf_ioctl.c | 5 + + sys/sys/random.h | 1 + + sys/sys/systm.h | 11 + + 106 files changed, 23172 insertions(+), 490 deletions(-) + create mode 100644 sys/arm64/conf/GATEWAY + create mode 100644 sys/arm64/conf/caam/config.caam + create mode 100644 sys/arm64/conf/caam/files.caam + create mode 100644 sys/arm64/conf/dpaa/config.dpaa_arm64 + create mode 100644 sys/arm64/conf/dpaa/files.dpaa_arm64 + create mode 100644 sys/arm64/include/pio.h + create mode 100644 sys/contrib/device-tree/src/arm64/freescale/mono-gateway-dk.dts + create mode 100644 sys/contrib/ncsw/Peripherals/FM/Pcd/fm_ehash.c + create mode 100644 sys/contrib/ncsw/build/dflags_arm64.h + create mode 100644 sys/contrib/ncsw/etc/ncsw_memcpy.c + create mode 100644 sys/contrib/ncsw/inc/Peripherals/fm_ehash.h + create mode 100644 sys/contrib/ncsw/user/env/core_arm64.c + create mode 100644 sys/contrib/ncsw/user/env/xx_arm64.c + create mode 100644 sys/dev/caam/caam.c + create mode 100644 sys/dev/caam/caam.h + create mode 100644 sys/dev/caam/caam_alg.c + create mode 100644 sys/dev/caam/caam_crypto.c + create mode 100644 sys/dev/caam/caam_crypto.h + create mode 100644 sys/dev/caam/caam_desc.h + create mode 100644 sys/dev/caam/caam_hash.c + create mode 100644 sys/dev/caam/caam_jr.c + create mode 100644 sys/dev/caam/caam_jr.h + create mode 100644 sys/dev/caam/caam_qi.c + create mode 100644 sys/dev/caam/caam_qi.h + create mode 100644 sys/dev/caam/caam_qi_alg.c + create mode 100644 sys/dev/caam/caam_regs.h + create mode 100644 sys/dev/caam/caam_rng.c + create mode 100644 sys/dev/caam/caam_rng.h + create mode 100644 sys/dev/dpaa/dpaa_oh.c + create mode 100644 sys/dev/dpaa/dpaa_oh.h + create mode 100644 sys/dev/dpaa/fman_chardev.c + create mode 100644 sys/dev/dpaa/fman_chardev.h + create mode 100644 sys/dev/dpaa/memac_mdio.c + create mode 100644 sys/dev/dpaa/qman_ceetm.c + create mode 100644 sys/dev/dpaa/qman_ceetm.h + create mode 100644 sys/dev/iicbus/rtc/pcf2131.c + create mode 100644 sys/dev/iicbus/sensor/ina2xx.c + create mode 100644 sys/dev/mii/gpyphy.c + +diff --git a/sys/arm64/arm64/machdep.c b/sys/arm64/arm64/machdep.c +index cdc81226954..2c2fc14dd10 100644 +--- a/sys/arm64/arm64/machdep.c ++++ b/sys/arm64/arm64/machdep.c +@@ -131,6 +131,7 @@ static struct trapframe proc0_tf; + int early_boot = 1; + int cold = 1; + static int boot_el; ++uintptr_t socdev_va; + static uint64_t hcr_el2; + + struct kva_md_info kmi; +diff --git a/sys/arm64/conf/GATEWAY b/sys/arm64/conf/GATEWAY +new file mode 100644 +index 00000000000..129de3def8f +--- /dev/null ++++ b/sys/arm64/conf/GATEWAY +@@ -0,0 +1,88 @@ ++# ++# MONO-GATEWAY -- NXP LS1046A with DPAA1 + CAAM for OPNsense ++# ++# Based on GENERIC (like SMP-ARM) with hardware-specific additions: ++# - DPAA1 packet acceleration (FMan/QMan/BMan) ++# - CAAM crypto accelerator (JR + QI paths) ++# - GPY115 PHY, SFP+, I2C sensors ++# - Early printf via QorIQ ns16550 ++# ++ ++include GENERIC ++ ++ident MONO-GATEWAY ++ ++# Disable debug for production ++nooptions INVARIANTS ++nooptions INVARIANT_SUPPORT ++nooptions WITNESS ++nooptions WITNESS_SKIPSPIN ++nooptions LOCK_PROFILING ++ ++# OPNsense standard features (from SMP-ARM) ++options DDB ++options GEOM_BDE ++options GEOM_ELI ++options GEOM_MIRROR ++options IPFIREWALL_DEFAULT_TO_ACCEPT ++options IPFIREWALL_VERBOSE ++options IPSTEALTH ++options MROUTING ++options PPS_SYNC ++options TCP_SIGNATURE ++ ++# Platform ++options SOC_NXP_LS ++ ++# Root filesystem (label set by opnsense-build arm.sh) ++options ROOTDEVNAME=\"ufs:/dev/ufs/OPNsense_ARM\" ++ ++# Early printf for debugging ++options SOCDEV_PA=0x2000000 ++options EARLY_PRINTF=qoriq ++ ++# eMMC (QorIQ ESDHC) ++device sdhci ++ ++# I2C (board-specific) ++device vf_i2c # Freescale Vybrid / QorIQ I2C controller ++device pca954x # NXP PCA9545/9546/9548 I2C mux/switch ++device ina2xx # TI INA219/INA226/INA234 power monitor ++device pcf2131 # NXP PCF2131 RTC ++ ++# DPAA1 (FMan/QMan/BMan) -- NXP LS1046A packet acceleration ++include "dpaa/config.dpaa_arm64" ++device dpaa ++options QMAN_CEETM_SUPPORT # QMan CEETM egress QoS traffic shaping ++device sff # Small Form Factor Transceivers (SFP+) ++ ++# NXP CAAM (SEC v5.4) crypto accelerator ++include "caam/config.caam" ++device caam ++ ++# Packet filter ++device pf ++device pflog ++device pfsync ++device carp ++ ++# Networking ++device lagg # Link aggregation ++device if_bridge # Bridge interface ++device enc # IPsec enc(4) interface ++device gif # IPv6/IPv4 tunneling ++device gre # GRE tunneling ++device tuntap # Tunnel/TAP ++ ++# OPNsense extras ++device wlan_acl ++device wlan_xauth ++device u3g ++device uftdi ++device umodem ++device uplcom ++device uvisor ++device uvscom ++ ++# DTBs ++makeoptions MODULES_EXTRA+="dtb/freescale" +diff --git a/sys/arm64/conf/caam/config.caam b/sys/arm64/conf/caam/config.caam +new file mode 100644 +index 00000000000..83dea588ab3 +--- /dev/null ++++ b/sys/arm64/conf/caam/config.caam +@@ -0,0 +1,6 @@ ++ ++files "caam/files.caam" ++ ++# QI files need NCSW include paths for DPAA FD/SGTE types and QMan API. ++# Uses DPAA_COMPILE_CMD which provides the full NCSW include environment ++# (defined in dpaa/config.dpaa_arm64, included before this file). +diff --git a/sys/arm64/conf/caam/files.caam b/sys/arm64/conf/caam/files.caam +new file mode 100644 +index 00000000000..17cd5e85b4e +--- /dev/null ++++ b/sys/arm64/conf/caam/files.caam +@@ -0,0 +1,12 @@ ++ ++# NXP CAAM (SEC v4.0+) crypto accelerator driver ++dev/caam/caam.c optional caam fdt ++dev/caam/caam_jr.c optional caam fdt ++dev/caam/caam_crypto.c optional caam fdt ++dev/caam/caam_alg.c optional caam fdt ++dev/caam/caam_hash.c optional caam fdt ++dev/caam/caam_rng.c optional caam fdt ++dev/caam/caam_qi.c optional caam fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++dev/caam/caam_qi_alg.c optional caam fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" +diff --git a/sys/arm64/conf/dpaa/config.dpaa_arm64 b/sys/arm64/conf/dpaa/config.dpaa_arm64 +new file mode 100644 +index 00000000000..4b4756753b5 +--- /dev/null ++++ b/sys/arm64/conf/dpaa/config.dpaa_arm64 +@@ -0,0 +1,29 @@ ++ ++files "dpaa/files.dpaa_arm64" ++ ++makeoptions DPAA_COMPILE_CMD="${LINUXKPI_C} ${DPAAWARNFLAGS} \ ++ -Wno-cast-qual -Wno-unused-function -Wno-init-self -fms-extensions \ ++ -include $S/contrib/ncsw/build/dflags_arm64.h \ ++ -Wno-error=missing-prototypes \ ++ -I$S/contrib/ncsw/build/ \ ++ -I$S/contrib/ncsw/inc \ ++ -I$S/contrib/ncsw/inc/cores \ ++ -I$S/contrib/ncsw/inc/etc \ ++ -I$S/contrib/ncsw/inc/Peripherals \ ++ -I$S/contrib/ncsw/etc \ ++ -I$S/contrib/ncsw/Peripherals/BM \ ++ -I$S/contrib/ncsw/Peripherals/FM \ ++ -I$S/contrib/ncsw/Peripherals/FM/HC \ ++ -I$S/contrib/ncsw/Peripherals/FM/inc \ ++ -I$S/contrib/ncsw/Peripherals/FM/MAC \ ++ -I$S/contrib/ncsw/Peripherals/FM/Pcd \ ++ -I$S/contrib/ncsw/Peripherals/FM/Port \ ++ -I$S/contrib/ncsw/Peripherals/FM/Rtc \ ++ -I$S/contrib/ncsw/Peripherals/QM \ ++ -I$S/contrib/ncsw/inc/flib \ ++ -I$S/contrib/ncsw/inc/integrations" ++ ++makeoptions FMCD_COMPILE_CMD="${DPAA_COMPILE_CMD} \ ++ -I$S/../../ASK/freebsd/fmlib/include/fmd \ ++ -I$S/../../ASK/freebsd/fmlib/include/fmd/Peripherals \ ++ -I$S/../../ASK/freebsd/fmlib/include/fmd/integrations" +diff --git a/sys/arm64/conf/dpaa/files.dpaa_arm64 b/sys/arm64/conf/dpaa/files.dpaa_arm64 +new file mode 100644 +index 00000000000..7ed4809d11c +--- /dev/null ++++ b/sys/arm64/conf/dpaa/files.dpaa_arm64 +@@ -0,0 +1,131 @@ ++ ++# NetCommSW drivers — ARM64 variant ++# Identical source list to powerpc/conf/dpaa/files.dpaa except: ++# - core.c -> core_arm64.c (ARM64 CORE_GetId etc.) ++# - xx.c -> xx_arm64.c (no PowerPC ccsrbar/LAW/TLB deps) ++# - if_dtsec* excluded (LS1046A uses mEMAC, not dTSEC) ++ ++contrib/ncsw/etc/error.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/etc/ncsw_list.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/etc/ncsw_memcpy.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/etc/mm.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/etc/ncsw_mem.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/etc/sprint.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/BM/bm.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/BM/bman_low.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/BM/bm_pool.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/BM/bm_portal.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/SP/fm_sp.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD} -Wno-enum-conversion" ++contrib/ncsw/Peripherals/FM/SP/fman_sp.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Rtc/fm_rtc.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Rtc/fman_rtc.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Port/fman_port.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Port/fm_port.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Port/fm_port_im.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Pcd/fm_cc.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Pcd/fm_ehash.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Pcd/fm_kg.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Pcd/fman_kg.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Pcd/fm_manip.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Pcd/fm_pcd.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Pcd/fm_plcr.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Pcd/fm_prs.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Pcd/fman_prs.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/Pcd/fm_replic.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++# mEMAC — the MAC type used by LS1046A FManv3 (DPAA_VERSION >= 11) ++contrib/ncsw/Peripherals/FM/MAC/memac.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/MAC/memac_mii_acc.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/MAC/fman_memac.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/MAC/fman_memac_mii_acc.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/MAC/fm_mac.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/HC/hc.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/fm_muram.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/FM/fm_ncsw.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD} -Wno-unused-but-set-variable" ++contrib/ncsw/Peripherals/FM/fman_ncsw.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD} ${NO_WMISLEADING_INDENTATION}" ++contrib/ncsw/Peripherals/QM/qm.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/Peripherals/QM/qm_portal_fqr.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/user/env/stdlib.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++# ARM64 replacements for xx.c and core.c (no PowerPC deps) ++contrib/ncsw/user/env/xx_arm64.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++contrib/ncsw/user/env/core_arm64.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++ ++# FreeBSD Wrappers ++dev/dpaa/portals_common.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++dev/dpaa/bman_portals.c optional dpaa fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++dev/dpaa/bman.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++dev/dpaa/bman_fdt.c optional dpaa fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++dev/dpaa/qman_portals.c optional dpaa fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++dev/dpaa/qman.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++dev/dpaa/qman_fdt.c optional dpaa fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++dev/dpaa/fman.c optional dpaa fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++dev/dpaa/fman_chardev.c optional dpaa fdt \ ++ no-depend compile-with "${FMCD_COMPILE_CMD}" ++dev/dpaa/fman_fdt.c optional dpaa fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++# mEMAC external MDIO controller (fsl,fman-memac-mdio) ++dev/dpaa/memac_mdio.c optional dpaa fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++# Ethernet driver (reuses dTSEC wrapper with mEMAC via NCSW FM_MAC API) ++dev/dpaa/if_dtsec.c optional dpaa fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++dev/dpaa/if_dtsec_fdt.c optional dpaa fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++dev/dpaa/if_dtsec_im.c optional dpaa fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++dev/dpaa/if_dtsec_rm.c optional dpaa fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++# Offline / Header Manipulation ports ++dev/dpaa/dpaa_oh.c optional dpaa fdt \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" ++# CEETM (Channel Egress Enhancement and Traffic Management) ++dev/dpaa/qman_ceetm.c optional dpaa \ ++ no-depend compile-with "${DPAA_COMPILE_CMD}" +diff --git a/sys/arm64/include/pio.h b/sys/arm64/include/pio.h +new file mode 100644 +index 00000000000..b33dc78bfdf +--- /dev/null ++++ b/sys/arm64/include/pio.h +@@ -0,0 +1,237 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * I/O macros for ARM64 — equivalent to powerpc/include/pio.h. ++ * Provides in8/out8/../in64/out64 used by the NetCommSW (ncsw) DPAA1 driver. ++ * All accesses are memory-mapped volatile loads/stores with a DSB barrier ++ * to match the ordering semantics of the PowerPC "sync" in the original. ++ */ ++ ++#ifndef _MACHINE_PIO_H_ ++#define _MACHINE_PIO_H_ ++ ++#include ++ ++/* ++ * Full system data synchronisation barrier. ++ * Ensures completion of all preceding memory accesses before any ++ * subsequent access can begin. Equivalent to PowerPC "sync". ++ */ ++#define arm64_iomb() __asm __volatile("dsb sy" : : : "memory") ++ ++static __inline void ++__outb(volatile u_int8_t *a, u_int8_t v) ++{ ++ *a = v; ++ arm64_iomb(); ++} ++ ++static __inline void ++__outw(volatile u_int16_t *a, u_int16_t v) ++{ ++ *a = v; ++ arm64_iomb(); ++} ++ ++static __inline void ++__outl(volatile u_int32_t *a, u_int32_t v) ++{ ++ *a = v; ++ arm64_iomb(); ++} ++ ++static __inline void ++__outll(volatile u_int64_t *a, u_int64_t v) ++{ ++ *a = v; ++ arm64_iomb(); ++} ++ ++static __inline u_int8_t ++__inb(volatile u_int8_t *a) ++{ ++ u_int8_t v; ++ ++ v = *a; ++ arm64_iomb(); ++ return (v); ++} ++ ++static __inline u_int16_t ++__inw(volatile u_int16_t *a) ++{ ++ u_int16_t v; ++ ++ v = *a; ++ arm64_iomb(); ++ return (v); ++} ++ ++static __inline u_int32_t ++__inl(volatile u_int32_t *a) ++{ ++ u_int32_t v; ++ ++ v = *a; ++ arm64_iomb(); ++ return (v); ++} ++ ++static __inline u_int64_t ++__inll(volatile u_int64_t *a) ++{ ++ u_int64_t v; ++ ++ v = *a; ++ arm64_iomb(); ++ return (v); ++} ++ ++#define outb(a,v) (__outb((volatile u_int8_t *)(a), v)) ++#define out8(a,v) outb(a,v) ++#define outw(a,v) (__outw((volatile u_int16_t *)(a), v)) ++#define out16(a,v) outw(a,v) ++#define outl(a,v) (__outl((volatile u_int32_t *)(a), v)) ++#define out32(a,v) outl(a,v) ++#define outll(a,v) (__outll((volatile u_int64_t *)(a), v)) ++#define out64(a,v) outll(a,v) ++#define inb(a) (__inb((volatile u_int8_t *)(a))) ++#define in8(a) inb(a) ++#define inw(a) (__inw((volatile u_int16_t *)(a))) ++#define in16(a) inw(a) ++#define inl(a) (__inl((volatile u_int32_t *)(a))) ++#define in32(a) inl(a) ++#define inll(a) (__inll((volatile u_int64_t *)(a))) ++#define in64(a) inll(a) ++ ++/* Reverse-byte variants — ARM64 is LE, so these byte-swap for BE regs */ ++static __inline void ++__outwrb(volatile u_int16_t *a, u_int16_t v) ++{ ++ *a = __builtin_bswap16(v); ++ arm64_iomb(); ++} ++ ++static __inline void ++__outlrb(volatile u_int32_t *a, u_int32_t v) ++{ ++ *a = __builtin_bswap32(v); ++ arm64_iomb(); ++} ++ ++static __inline u_int16_t ++__inwrb(volatile u_int16_t *a) ++{ ++ u_int16_t v; ++ ++ v = *a; ++ arm64_iomb(); ++ return (__builtin_bswap16(v)); ++} ++ ++static __inline u_int32_t ++__inlrb(volatile u_int32_t *a) ++{ ++ u_int32_t v; ++ ++ v = *a; ++ arm64_iomb(); ++ return (__builtin_bswap32(v)); ++} ++ ++#define out8rb(a,v) outb(a,v) ++#define outwrb(a,v) (__outwrb((volatile u_int16_t *)(a), v)) ++#define out16rb(a,v) outwrb(a,v) ++#define outlrb(a,v) (__outlrb((volatile u_int32_t *)(a), v)) ++#define out32rb(a,v) outlrb(a,v) ++#define in8rb(a) inb(a) ++#define inwrb(a) (__inwrb((volatile u_int16_t *)(a))) ++#define in16rb(a) inwrb(a) ++#define inlrb(a) (__inlrb((volatile u_int32_t *)(a))) ++#define in32rb(a) inlrb(a) ++ ++/* Bulk accessors */ ++static __inline void ++__outsb(volatile u_int8_t *a, const u_int8_t *s, size_t c) ++{ ++ while (c--) ++ *a = *s++; ++ arm64_iomb(); ++} ++ ++static __inline void ++__outsw(volatile u_int16_t *a, const u_int16_t *s, size_t c) ++{ ++ while (c--) ++ *a = *s++; ++ arm64_iomb(); ++} ++ ++static __inline void ++__outsl(volatile u_int32_t *a, const u_int32_t *s, size_t c) ++{ ++ while (c--) ++ *a = *s++; ++ arm64_iomb(); ++} ++ ++static __inline void ++__outsll(volatile u_int64_t *a, const u_int64_t *s, size_t c) ++{ ++ while (c--) ++ *a = *s++; ++ arm64_iomb(); ++} ++ ++static __inline void ++__insb(volatile u_int8_t *a, u_int8_t *d, size_t c) ++{ ++ while (c--) ++ *d++ = *a; ++ arm64_iomb(); ++} ++ ++static __inline void ++__insw(volatile u_int16_t *a, u_int16_t *d, size_t c) ++{ ++ while (c--) ++ *d++ = *a; ++ arm64_iomb(); ++} ++ ++static __inline void ++__insl(volatile u_int32_t *a, u_int32_t *d, size_t c) ++{ ++ while (c--) ++ *d++ = *a; ++ arm64_iomb(); ++} ++ ++static __inline void ++__insll(volatile u_int64_t *a, u_int64_t *d, size_t c) ++{ ++ while (c--) ++ *d++ = *a; ++ arm64_iomb(); ++} ++ ++#define outsb(a,s,c) (__outsb((volatile u_int8_t *)(a), s, c)) ++#define outs8(a,s,c) outsb(a,s,c) ++#define outsw(a,s,c) (__outsw((volatile u_int16_t *)(a), s, c)) ++#define outs16(a,s,c) outsw(a,s,c) ++#define outsl(a,s,c) (__outsl((volatile u_int32_t *)(a), s, c)) ++#define outs32(a,s,c) outsl(a,s,c) ++#define outsll(a,s,c) (__outsll((volatile u_int64_t *)(a), s, c)) ++#define outs64(a,s,c) outsll(a,s,c) ++#define insb(a,d,c) (__insb((volatile u_int8_t *)(a), d, c)) ++#define ins8(a,d,c) insb(a,d,c) ++#define insw(a,d,c) (__insw((volatile u_int16_t *)(a), d, c)) ++#define ins16(a,d,c) insw(a,d,c) ++#define insl(a,d,c) (__insl((volatile u_int32_t *)(a), d, c)) ++#define ins32(a,d,c) insl(a,d,c) ++#define insll(a,d,c) (__insll((volatile u_int64_t *)(a), d, c)) ++#define ins64(a,d,c) insll(a,d,c) ++ ++#endif /* _MACHINE_PIO_H_ */ +diff --git a/sys/conf/files b/sys/conf/files +index 00816d17c70..b8c33cc8bcf 100644 +--- a/sys/conf/files ++++ b/sys/conf/files +@@ -1832,12 +1832,14 @@ dev/iicbus/rtc/ds1672.c optional ds1672 + dev/iicbus/rtc/ds3231.c optional ds3231 + dev/iicbus/rtc/isl12xx.c optional isl12xx + dev/iicbus/rtc/nxprtc.c optional nxprtc | pcf8563 ++dev/iicbus/rtc/pcf2131.c optional pcf2131 + dev/iicbus/rtc/pcf85063.c optional pcf85063 iicbus fdt + dev/iicbus/rtc/rtc8583.c optional rtc8583 + dev/iicbus/rtc/rv3032.c optional rv3032 iicbus fdt + dev/iicbus/rtc/rx8803.c optional rx8803 iicbus fdt + dev/iicbus/rtc/s35390a.c optional s35390a + dev/iicbus/sensor/htu21.c optional htu21 ++dev/iicbus/sensor/ina2xx.c optional ina2xx + dev/iicbus/sensor/lm75.c optional lm75 + dev/iicbus/sensor/max44009.c optional max44009 + dev/iicbus/gpio/pcf8574.c optional pcf8574 +@@ -2401,6 +2403,7 @@ dev/mii/dp83822phy.c optional miibus | dp83822phy + dev/mii/dp83867phy.c optional miibus | dp83867phy + dev/mii/e1000phy.c optional miibus | e1000phy + dev/mii/gentbi.c optional miibus | gentbi ++dev/mii/gpyphy.c optional miibus | gpyphy + dev/mii/icsphy.c optional miibus | icsphy + dev/mii/ip1000phy.c optional miibus | ip1000phy + dev/mii/jmphy.c optional miibus | jmphy +diff --git a/sys/conf/files.arm64 b/sys/conf/files.arm64 +index cf2e1d22da8..b22a047f8f5 100644 +--- a/sys/conf/files.arm64 ++++ b/sys/conf/files.arm64 +@@ -636,8 +636,8 @@ dev/iicbus/controller/vybrid/vf_i2c_acpi.c optional vf_i2c iicbus acpi soc_nxp_l + dev/iicbus/controller/vybrid/vf_i2c_fdt.c optional vf_i2c iicbus fdt soc_nxp_ls + arm64/qoriq/qoriq_dw_pci.c optional pci fdt soc_nxp_ls + arm64/qoriq/qoriq_gpio_pic.c optional gpio fdt soc_nxp_ls +-arm64/qoriq/qoriq_therm.c optional pci fdt soc_nxp_ls +-arm64/qoriq/qoriq_therm_if.m optional pci fdt soc_nxp_ls ++arm64/qoriq/qoriq_therm.c optional fdt soc_nxp_ls ++arm64/qoriq/qoriq_therm_if.m optional fdt soc_nxp_ls + arm64/qoriq/clk/ls1028a_clkgen.c optional clk soc_nxp_ls fdt + arm64/qoriq/clk/ls1028a_flexspi_clk.c optional clk soc_nxp_ls fdt + arm64/qoriq/clk/ls1046a_clkgen.c optional clk soc_nxp_ls fdt +diff --git a/sys/conf/options b/sys/conf/options +index e201f8a4bdb..42045dd1141 100644 +--- a/sys/conf/options ++++ b/sys/conf/options +@@ -52,6 +52,7 @@ DDB_CAPTURE_DEFAULTBUFSIZE opt_ddb.h + DDB_CAPTURE_MAXBUFSIZE opt_ddb.h + DDB_CTF opt_ddb.h + DDB_NUMSYM opt_ddb.h ++QMAN_CEETM_SUPPORT opt_dpaa.h + EARLY_PRINTF opt_global.h + FULL_BUF_TRACKING opt_global.h + GDB +diff --git a/sys/contrib/device-tree/src/arm64/freescale/mono-gateway-dk.dts b/sys/contrib/device-tree/src/arm64/freescale/mono-gateway-dk.dts +new file mode 100644 +index 00000000000..3058f5e9d02 +--- /dev/null ++++ b/sys/contrib/device-tree/src/arm64/freescale/mono-gateway-dk.dts +@@ -0,0 +1,434 @@ ++// SPDX-License-Identifier: (GPL-2.0+ OR MIT) ++/* ++ * Device Tree for Mono Gateway DK (NXP LS1046A) ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * Author: Tomaz Zaman ++ */ ++ ++/dts-v1/; ++ ++#include "fsl-ls1046a.dtsi" ++ ++/ { ++ model = "Mono Gateway Development Kit"; ++ compatible = "mono,gateway-dk", "fsl,ls1046a"; ++ freebsd,dts-version = "6.4"; ++ ++ aliases { ++ serial0 = &duart0; ++ }; ++ ++ chosen { ++ stdout-path = "serial0:115200n8"; ++ }; ++ ++ /* ++ * SFP LED GPIO definitions — referenced by sfp-led-controller via ++ * the "leds" property on each SFP node. These are NOT children of ++ * gpio-leds so the gpioled driver won't claim the pins (sfp-led ++ * module owns them). ++ */ ++ led_sfp0_link: sfp0_link { ++ gpios = <&gpio2 17 GPIO_ACTIVE_HIGH>; ++ }; ++ ++ led_sfp0_activity: sfp0_activity { ++ gpios = <&gpio2 18 GPIO_ACTIVE_HIGH>; ++ }; ++ ++ led_sfp1_link: sfp1_link { ++ gpios = <&gpio2 15 GPIO_ACTIVE_HIGH>; ++ }; ++ ++ led_sfp1_activity: sfp1_activity { ++ gpios = <&gpio2 16 GPIO_ACTIVE_HIGH>; ++ }; ++ ++ sfp_xfi0: sfp-xfi0 { ++ compatible = "sff,sfp"; ++ i2c-bus = <&sfp0_i2c>; ++ tx-disable-gpios = <&gpio2 14 GPIO_ACTIVE_HIGH>; ++ mod-def0-gpios = <&gpio2 12 GPIO_ACTIVE_LOW>; ++ los-gpios = <&gpio2 11 GPIO_ACTIVE_HIGH>; ++ maximum-power-milliwatt = <3000>; ++ leds = <&led_sfp0_link>, <&led_sfp0_activity>; ++ }; ++ ++ sfp_xfi1: sfp-xfi1 { ++ compatible = "sff,sfp"; ++ i2c-bus = <&sfp1_i2c>; ++ tx-disable-gpios = <&gpio2 13 GPIO_ACTIVE_HIGH>; ++ mod-def0-gpios = <&gpio2 10 GPIO_ACTIVE_LOW>; ++ los-gpios = <&gpio2 9 GPIO_ACTIVE_HIGH>; ++ maximum-power-milliwatt = <3000>; ++ leds = <&led_sfp1_link>, <&led_sfp1_activity>; ++ }; ++ ++ sfp_led_controller: sfp-led-controller { ++ compatible = "mono,sfp-led"; ++ sfp-ports = <&sfp_xfi0>, <&sfp_xfi1>; ++ }; ++}; ++ ++&duart0 { ++ status = "okay"; ++}; ++ ++&esdhc { ++ status = "okay"; ++ mmc-hs200-1_8v; ++ bus-width = <4>; ++}; ++ ++&i2c0 { ++ status = "okay"; ++ ++ /* Thermal sensors, retimer, clock generator, PWM fan */ ++ i2c-mux@70 { ++ compatible = "nxp,pca9545"; ++ reg = <0x70>; ++ #address-cells = <1>; ++ #size-cells = <0>; ++ ++ i2c@0 { ++ #address-cells = <1>; ++ #size-cells = <0>; ++ reg = <0>; ++ ++ retimer: retimer@18 { ++ compatible = "ti,ds100df410"; ++ reg = <0x18>; ++ status = "okay"; ++ }; ++ }; ++ ++ i2c@1 { ++ #address-cells = <1>; ++ #size-cells = <0>; ++ reg = <1>; ++ ++ temp-sensor@4c { ++ compatible = "ti,tmp431"; ++ reg = <0x4c>; ++ }; ++ }; ++ ++ i2c@2 { ++ #address-cells = <1>; ++ #size-cells = <0>; ++ reg = <2>; ++ ++ temp-sensor@4c { ++ compatible = "ti,tmp431"; ++ reg = <0x4c>; ++ }; ++ }; ++ ++ i2c@3 { ++ #address-cells = <1>; ++ #size-cells = <0>; ++ reg = <3>; ++ ++ fan_controller: fan-controller@2e { ++ compatible = "microchip,emc2305"; ++ reg = <0x2e>; ++ #address-cells = <1>; ++ #size-cells = <0>; ++ #pwm-cells = <3>; ++ ++ fan0: fan@0 { ++ reg = <0>; ++ label = "System Fan 1"; ++ pwms = <&fan_controller 26000 1 1>; ++ #cooling-cells = <2>; ++ }; ++ ++ fan1: fan@1 { ++ reg = <1>; ++ label = "System Fan 2"; ++ pwms = <&fan_controller 26000 1 1>; ++ #cooling-cells = <2>; ++ }; ++ }; ++ }; ++ }; ++}; ++ ++&i2c1 { ++ status = "okay"; ++ ++ /* SFP+ I2C mux */ ++ sfpmux: i2c-mux@70 { ++ compatible = "nxp,pca9545"; ++ reg = <0x70>; ++ #address-cells = <1>; ++ #size-cells = <0>; ++ ++ sfp0_i2c: i2c@0 { ++ #address-cells = <1>; ++ #size-cells = <0>; ++ reg = <0>; ++ }; ++ ++ sfp1_i2c: i2c@1 { ++ #address-cells = <1>; ++ #size-cells = <0>; ++ reg = <1>; ++ }; ++ }; ++}; ++ ++&i2c2 { ++ status = "okay"; ++ ++ i2c-mux@70 { ++ compatible = "nxp,pca9545"; ++ reg = <0x70>; ++ #address-cells = <1>; ++ #size-cells = <0>; ++ ++ i2c@0 { ++ #address-cells = <1>; ++ #size-cells = <0>; ++ reg = <0>; ++ ++ power_sensor@40 { ++ compatible = "ti,ina234"; ++ reg = <0x40>; ++ label = "USB Power Delivery"; ++ #io-channel-cells = <1>; ++ shunt-resistor = <1000>; ++ }; ++ power_sensor@41 { ++ compatible = "ti,ina234"; ++ reg = <0x41>; ++ label = "5V PSU"; ++ #io-channel-cells = <1>; ++ shunt-resistor = <1000>; ++ }; ++ power_sensor@42 { ++ compatible = "ti,ina234"; ++ reg = <0x42>; ++ label = "1V Core PSU"; ++ #io-channel-cells = <1>; ++ shunt-resistor = <1000>; ++ }; ++ power_sensor@43 { ++ compatible = "ti,ina234"; ++ reg = <0x43>; ++ label = "1.2V DDR PSU"; ++ #io-channel-cells = <1>; ++ shunt-resistor = <5000>; ++ }; ++ }; ++ ++ i2c@1 { ++ #address-cells = <1>; ++ #size-cells = <0>; ++ reg = <1>; ++ ++ power_sensor@40 { ++ compatible = "ti,ina234"; ++ reg = <0x40>; ++ label = "1.35V SerDes PSU"; ++ #io-channel-cells = <1>; ++ shunt-resistor = <5000>; ++ }; ++ power_sensor@41 { ++ compatible = "ti,ina234"; ++ reg = <0x41>; ++ label = "1.8V PSU"; ++ #io-channel-cells = <1>; ++ shunt-resistor = <5000>; ++ }; ++ power_sensor@42 { ++ compatible = "ti,ina234"; ++ reg = <0x42>; ++ label = "2.5V DDR PSU"; ++ #io-channel-cells = <1>; ++ shunt-resistor = <5000>; ++ }; ++ power_sensor@43 { ++ compatible = "ti,ina234"; ++ reg = <0x43>; ++ label = "3.3V PSU"; ++ #io-channel-cells = <1>; ++ shunt-resistor = <1000>; ++ }; ++ }; ++ ++ i2c@2 { ++ #address-cells = <1>; ++ #size-cells = <0>; ++ reg = <2>; ++ ++ rtc@53 { ++ compatible = "nxp,pcf2131"; ++ reg = <0x53>; ++ status = "okay"; ++ }; ++ }; ++ ++ i2c@3 { ++ #address-cells = <1>; ++ #size-cells = <0>; ++ reg = <3>; ++ ++ lp5810@6c { ++ compatible = "ti,lp5812"; ++ reg = <0x6c>; ++ #address-cells = <1>; ++ #size-cells = <0>; ++ ++ led@0 { ++ reg = <0>; ++ label = "status:white"; ++ led-max-microamp = <25500>; ++ }; ++ ++ led@1 { ++ reg = <1>; ++ label = "status:blue"; ++ led-max-microamp = <25500>; ++ }; ++ ++ led@2 { ++ reg = <2>; ++ label = "status:green"; ++ led-max-microamp = <25500>; ++ }; ++ ++ led@3 { ++ reg = <3>; ++ label = "status:red"; ++ led-max-microamp = <25500>; ++ }; ++ }; ++ }; ++ }; ++}; ++ ++&i2c3 { ++ status = "okay"; ++}; ++ ++#include "fsl-ls1046-post.dtsi" ++ ++/* Override portal bus compatible from "simple-bus" to prevent simplebus ++ * from claiming these nodes before the DPAA portal drivers attach. ++ * The portal drivers match on these specific compatible strings. */ ++&qportals { ++ compatible = "fsl,qman-portals"; ++}; ++ ++&bportals { ++ compatible = "fsl,bman-portals"; ++}; ++ ++/* CEETM: Channel Egress Enhancement and Traffic Management ++ * QMan hardware egress QoS — hierarchical traffic shaping with ++ * sub-portals, LNIs, channels, and class queues. ++ * LFQID range extracted from Linux SDK DTS for LS1046A. */ ++&qman { ++ qman-ceetm@0 { ++ compatible = "fsl,qman-ceetm"; ++ fsl,ceetm-lfqid-range = <0xf00000 0x1000>; ++ fsl,ceetm-sp-range = <0 16>; ++ fsl,ceetm-lni-range = <0 8>; ++ fsl,ceetm-channel-range = <0 32>; ++ }; ++}; ++ ++/* port@82000 (cell-index 2) is reserved for Host Command — disable for OP use. ++ * Keep 0x3 (IPsec) and 0x4 (WiFi), matching Linux SDK port assignment. */ ++&fman0_oh_0x2 { status = "disabled"; }; ++&fman0_oh_0x5 { status = "disabled"; }; ++&fman0_oh_0x6 { status = "disabled"; }; ++&fman0_oh_0x7 { status = "disabled"; }; ++ ++&fman0 { ++ /* Unused 1G ports */ ++ ethernet@e0000 { ++ status = "disabled"; ++ }; ++ ++ ethernet@e4000 { ++ status = "disabled"; ++ }; ++ ++ ethernet@e6000 { ++ status = "disabled"; ++ }; ++ ++ /* SGMII 1GbE ports */ ++ ethernet@e8000 { ++ phy-handle = <&sgmii_phy0>; ++ phy-connection-type = "sgmii"; ++ status = "okay"; ++ }; ++ ++ ethernet@ea000 { ++ phy-handle = <&sgmii_phy1>; ++ phy-connection-type = "sgmii"; ++ status = "okay"; ++ }; ++ ++ ethernet@e2000 { ++ phy-handle = <&sgmii_phy2>; ++ phy-connection-type = "sgmii"; ++ status = "okay"; ++ }; ++ ++ /* 10GbE XFI ports */ ++ ethernet@f0000 { ++ sfp = <&sfp_xfi0>; ++ phy-connection-type = "10gbase-r"; ++ managed = "in-band-status"; ++ }; ++ ++ ethernet@f2000 { ++ sfp = <&sfp_xfi1>; ++ phy-connection-type = "10gbase-r"; ++ managed = "in-band-status"; ++ }; ++ ++ /* Internal MDIO disabled (no PHYs on this bus) */ ++ mdio@fc000 { ++ status = "disabled"; ++ }; ++ ++ /* External MDIO — SGMII PHYs */ ++ mdio@fd000 { ++ sgmii_phy0: ethernet-phy@0 { ++ reg = <0x0>; ++ }; ++ ++ sgmii_phy1: ethernet-phy@1 { ++ reg = <0x1>; ++ }; ++ ++ sgmii_phy2: ethernet-phy@2 { ++ reg = <0x2>; ++ }; ++ }; ++}; ++ ++/* ++ * Override reserved-memory nodes with fixed physical addresses. ++ * FreeBSD excludes no-map + reg regions from phys_avail[] at early boot, ++ * giving QBMan dedicated memory that the VM system never touches. ++ * Addresses are in DDR range (0x80000000-0xFFFFFFFF), naturally aligned. ++ */ ++&qman_pfdr { ++ reg = <0 0xc0000000 0 0x2000000>; /* 32MB at 0xC0000000 */ ++}; ++ ++&bman_fbpr { ++ reg = <0 0xc2000000 0 0x1000000>; /* 16MB at 0xC2000000 */ ++}; ++ ++&qman_fqd { ++ reg = <0 0xc3000000 0 0x800000>; /* 8MB at 0xC3000000 */ ++}; ++ +diff --git a/sys/contrib/ncsw/Peripherals/BM/bm.c b/sys/contrib/ncsw/Peripherals/BM/bm.c +index 646e38fb969..09bd8ade79e 100644 +--- a/sys/contrib/ncsw/Peripherals/BM/bm.c ++++ b/sys/contrib/ncsw/Peripherals/BM/bm.c +@@ -441,7 +441,7 @@ t_Error BmGetRevision(t_Handle h_Bm, t_BmRevisionInfo *p_BmRevisionInfo) + + static void FreeInitResources(t_Bm *p_Bm) + { +- if (p_Bm->p_FbprBase) ++ if (p_Bm->p_FbprBase && !p_Bm->fbprExternal) + XX_FreeSmart(p_Bm->p_FbprBase); + if (p_Bm->h_Session) + XX_IpcFreeSession(p_Bm->h_Session); +@@ -491,6 +491,8 @@ t_Handle BM_Config(t_BmParam *p_BmParam) + p_Bm->p_BmDriverParams->fbprMemPartitionId = p_BmParam->fbprMemPartitionId; + p_Bm->p_BmDriverParams->fbprThreshold = DEFAULT_fbprThreshold; + p_Bm->p_BmDriverParams->liodn = p_BmParam->liodn; ++ p_Bm->p_BmDriverParams->p_FbprBaseExt = p_BmParam->p_FbprBase; ++ p_Bm->p_BmDriverParams->fbprSizeExt = p_BmParam->fbprSize; + + } + /* build the BM partition IPC address */ +@@ -534,26 +536,50 @@ t_Error BM_Init(t_Handle h_Bm) + WRITE_UINT32(p_Bm->p_BmRegs->liodnr, (uint16_t)p_Bm->p_BmDriverParams->liodn); + + /* FBPR memory */ +- dsSize = (uint32_t)(p_Bm->p_BmDriverParams->totalNumOfBuffers * (FBPR_ENTRY_SIZE / 8)); +- LOG2(dsSize, exp); +- if (!POWER_OF_2(dsSize)) (exp++); +- dsSize = (uint32_t)(1 << exp); +- if (dsSize < (4*KILOBYTE)) ++ if (p_Bm->p_BmDriverParams->p_FbprBaseExt) + { +- dsSize = (4*KILOBYTE); ++ /* Use pre-allocated FBPR memory from caller */ ++ p_Bm->p_FbprBase = p_Bm->p_BmDriverParams->p_FbprBaseExt; ++ p_Bm->fbprExternal = TRUE; ++ dsSize = p_Bm->p_BmDriverParams->fbprSizeExt; + LOG2(dsSize, exp); ++ if (!POWER_OF_2(dsSize)) (exp++); ++ dsSize = (uint32_t)(1 << exp); + } +- p_Bm->p_FbprBase = XX_MallocSmart(dsSize, (int)p_Bm->p_BmDriverParams->fbprMemPartitionId, dsSize); +- if (!p_Bm->p_FbprBase) ++ else + { +- FreeInitResources(p_Bm); +- RETURN_ERROR(MAJOR, E_NO_MEMORY, ("FBPR obj!!!")); ++ dsSize = (uint32_t)(p_Bm->p_BmDriverParams->totalNumOfBuffers * (FBPR_ENTRY_SIZE / 8)); ++ LOG2(dsSize, exp); ++ if (!POWER_OF_2(dsSize)) (exp++); ++ dsSize = (uint32_t)(1 << exp); ++ if (dsSize < (4*KILOBYTE)) ++ { ++ dsSize = (4*KILOBYTE); ++ LOG2(dsSize, exp); ++ } ++ p_Bm->p_FbprBase = XX_MallocSmart(dsSize, (int)p_Bm->p_BmDriverParams->fbprMemPartitionId, dsSize); ++ if (!p_Bm->p_FbprBase) ++ { ++ FreeInitResources(p_Bm); ++ RETURN_ERROR(MAJOR, E_NO_MEMORY, ("FBPR obj!!!")); ++ } + } + phyAddr = XX_VirtToPhys(p_Bm->p_FbprBase); + WRITE_UINT32(p_Bm->p_BmRegs->fbpr_bare, ((uint32_t)(phyAddr >> 32) & 0xffff)); + WRITE_UINT32(p_Bm->p_BmRegs->fbpr_bar, (uint32_t)phyAddr); + WRITE_UINT32(p_Bm->p_BmRegs->fbpr_ar, (exp - 1)); + ++ /* Readback and verify FBPR BAR programming */ ++ { ++ uint32_t rb_bare = GET_UINT32(p_Bm->p_BmRegs->fbpr_bare); ++ uint32_t rb_bar = GET_UINT32(p_Bm->p_BmRegs->fbpr_bar); ++ uint32_t rb_ar = GET_UINT32(p_Bm->p_BmRegs->fbpr_ar); ++ XX_Print("BM FBPR: va=%p phys=0x%08x%08x bare=0x%08x bar=0x%08x ar=0x%08x (exp=%d, size=0x%x)\n", ++ p_Bm->p_FbprBase, ++ (uint32_t)(phyAddr >> 32), (uint32_t)phyAddr, ++ rb_bare, rb_bar, rb_ar, exp, dsSize); ++ } ++ + WRITE_UINT32(p_Bm->p_BmRegs->fbpr_fp_lwit, p_Bm->p_BmDriverParams->fbprThreshold); + WRITE_UINT32(p_Bm->p_BmRegs->err_isr, p_Bm->exceptions); + WRITE_UINT32(p_Bm->p_BmRegs->err_ier, p_Bm->exceptions); +diff --git a/sys/contrib/ncsw/Peripherals/BM/bm.h b/sys/contrib/ncsw/Peripherals/BM/bm.h +index 09870cb0715..7fbd30417b4 100644 +--- a/sys/contrib/ncsw/Peripherals/BM/bm.h ++++ b/sys/contrib/ncsw/Peripherals/BM/bm.h +@@ -290,6 +290,8 @@ typedef struct { + uint32_t fbprMemPartitionId; + uint32_t fbprThreshold; + uint16_t liodn; ++ void *p_FbprBaseExt; /* Pre-allocated FBPR, or NULL */ ++ uint32_t fbprSizeExt; + } t_BmDriverParams; + + typedef struct { +@@ -301,6 +303,7 @@ typedef struct { + char moduleName[MODULE_NAME_SIZE]; + t_BmRegs *p_BmRegs; + void *p_FbprBase; ++ bool fbprExternal; /* FBPR memory externally allocated */ + uint32_t exceptions; + t_BmExceptionsCallback *f_Exception; + t_Handle h_App; +diff --git a/sys/contrib/ncsw/Peripherals/BM/bm_pool.c b/sys/contrib/ncsw/Peripherals/BM/bm_pool.c +index c908846760a..83c0c4b337d 100644 +--- a/sys/contrib/ncsw/Peripherals/BM/bm_pool.c ++++ b/sys/contrib/ncsw/Peripherals/BM/bm_pool.c +@@ -61,6 +61,7 @@ static void depletion_link(t_BmPool *p_BmPool) + + NCSW_PLOCK(p_Portal); + p_Portal->depletionPoolsTable[p_BmPool->bpid] = p_BmPool; ++ bman_depletion_set(&p_Portal->pools[0], (uint8_t)p_BmPool->bpid); + bm_isr_bscn_mask(p_Portal->p_BmPortalLow, (uint8_t)p_BmPool->bpid, 1); + PUNLOCK(p_Portal); + } +@@ -71,6 +72,7 @@ static void depletion_unlink(t_BmPool *p_BmPool) + + NCSW_PLOCK(p_Portal); + p_Portal->depletionPoolsTable[p_BmPool->bpid] = NULL; ++ bman_depletion_unset(&p_Portal->pools[0], (uint8_t)p_BmPool->bpid); + bm_isr_bscn_mask(p_Portal->p_BmPortalLow, (uint8_t)p_BmPool->bpid, 0); + PUNLOCK(p_Portal); + } +diff --git a/sys/contrib/ncsw/Peripherals/BM/bm_portal.c b/sys/contrib/ncsw/Peripherals/BM/bm_portal.c +index 34b48e38b4d..ff42e31fc20 100644 +--- a/sys/contrib/ncsw/Peripherals/BM/bm_portal.c ++++ b/sys/contrib/ncsw/Peripherals/BM/bm_portal.c +@@ -381,16 +381,23 @@ t_Error BmPortalRelease(t_Handle h_BmPortal, + if (!r) { + if (flags & BMAN_RELEASE_FLAG_WAIT) { + t_Error ret = wait_rel_start(p_BmPortal, &r, flags); +- if (ret) ++ if (ret) { ++ printf("BmPortalRelease: wait_rel_start FAILED E_BUSY, avail=%u, " ++ "rcr.ci=%u, rcr.cursor=%p, rcr.vbit=%u\n", ++ bm_rcr_get_avail(p_BmPortal->p_BmPortalLow), ++ p_BmPortal->p_BmPortalLow->rcr.ci, ++ p_BmPortal->p_BmPortalLow->rcr.cursor, ++ p_BmPortal->p_BmPortalLow->rcr.vbit); + return ret; ++ } + } else + return ERROR_CODE(E_BUSY); + ASSERT_COND(r != NULL); + } + r->bpid = bpid; + for (i = 0; i < num; i++) { +- r->bufs[i].hi = bufs[i].hi; +- r->bufs[i].lo = bufs[i].lo; ++ WRITE_UINT16(r->bufs[i].hi, bufs[i].hi); ++ WRITE_UINT32(r->bufs[i].lo, bufs[i].lo); + } + /* Issue the release command and wait for sync if requested. NB: the + * commit can't fail, only waiting can. Don't propagate any failure if a +@@ -423,8 +430,8 @@ uint8_t BmPortalAcquire(t_Handle h_BmPortal, + ASSERT_COND(num <= 8); + while (num--) { + bufs[num].bpid = bpid; +- bufs[num].hi = mcr->acquire.bufs[num].hi; +- bufs[num].lo = mcr->acquire.bufs[num].lo; ++ bufs[num].hi = GET_UINT16(mcr->acquire.bufs[num].hi); ++ bufs[num].lo = GET_UINT32(mcr->acquire.bufs[num].lo); + } + PUNLOCK(p_BmPortal); + return ret; +@@ -495,7 +502,7 @@ t_Handle BM_PORTAL_Config(t_BmPortalParam *p_BmPortalParam) + p_BmPortal->h_Bm = p_BmPortalParam->h_Bm; + + p_BmPortal->p_BmPortalDriverParams->hwExtStructsMemAttr = DEFAULT_memAttr; +- bman_depletion_fill(&p_BmPortal->p_BmPortalDriverParams->mask); ++ bman_depletion_init(&p_BmPortal->p_BmPortalDriverParams->mask); + + return p_BmPortal; + } +diff --git a/sys/contrib/ncsw/Peripherals/BM/bman_low.c b/sys/contrib/ncsw/Peripherals/BM/bman_low.c +index 818e62df31c..fb48dc1df3b 100644 +--- a/sys/contrib/ncsw/Peripherals/BM/bman_low.c ++++ b/sys/contrib/ncsw/Peripherals/BM/bman_low.c +@@ -40,6 +40,7 @@ + *//***************************************************************************/ + #include + #include ++#include + #include + + #include "std_ext.h" +@@ -55,15 +56,28 @@ + /***************************/ + + /* Cache-inhibited register offsets */ ++#if defined(__aarch64__) ++/* ++ * ARM64 Layerscape (LS1046A etc.): CI space is 16KB per portal. ++ * Register offsets are spread out compared to PowerPC. ++ * See Linux drivers/soc/fsl/qbman/bman.c for reference. ++ */ ++#define REG_RCR_PI_CINH 0x3000 ++#define REG_RCR_CI_CINH 0x3100 ++#define REG_RCR_ITR 0x3200 ++#define REG_CFG 0x3300 ++#define REG_SCN(n) (0x3400 + ((n) << 6)) ++#define REG_ISR 0x3e00 ++#define BM_ISR_SHIFT 6 /* ISR/IER/ISDR/IIR stride: 64 bytes */ ++#else /* PowerPC */ + #define REG_RCR_PI_CINH 0x0000 + #define REG_RCR_CI_CINH 0x0004 + #define REG_RCR_ITR 0x0008 + #define REG_CFG 0x0100 + #define REG_SCN(n) (0x0200 + ((n) << 2)) + #define REG_ISR 0x0e00 +-#define REG_IER 0x0e04 +-#define REG_ISDR 0x0e08 +-#define REG_IIR 0x0e0c ++#define BM_ISR_SHIFT 2 /* ISR/IER/ISDR/IIR stride: 4 bytes */ ++#endif + + /* Cache-enabled register offsets */ + #define CL_CR 0x0000 +@@ -258,9 +272,17 @@ struct bm_rcr_entry *bm_rcr_pend_and_next(struct bm_portal *portal, uint8_t myve + void bm_rcr_pci_commit(struct bm_portal *portal, uint8_t myverb) + { + register struct bm_rcr *rcr = &portal->rcr; ++ struct bm_rcr_entry *rcursor; + ASSERT_COND(rcr->busy); + ASSERT_COND(rcr->pmode == e_BmPortalPCI); +- rcr->cursor->__dont_write_directly__verb = (uint8_t)(myverb | rcr->vbit); ++ rcursor = rcr->cursor; ++ rcursor->__dont_write_directly__verb = (uint8_t)(myverb | rcr->vbit); ++ /* ++ * ARM64: The portal hardware cannot snoop the CPU cache via CCI-400. ++ * Explicitly flush the entry from cache to portal CE memory before ++ * writing PI. On PowerPC the CCF provides hardware coherency. ++ */ ++ dcbf_64(rcursor); + RCR_INC(rcr); + rcr->available--; + mb(); +@@ -298,7 +320,7 @@ void bm_rcr_pvb_commit(struct bm_portal *portal, uint8_t myverb) + struct bm_rcr_entry *rcursor; + ASSERT_COND(rcr->busy); + ASSERT_COND(rcr->pmode == e_BmPortalPVB); +- rmb(); ++ wmb(); + rcursor = rcr->cursor; + rcursor->__dont_write_directly__verb = (uint8_t)(myverb | rcr->vbit); + dcbf_64(rcursor); +@@ -487,12 +509,12 @@ void bm_isr_bscn_mask(struct bm_portal *portal, uint8_t bpid, int enable) + + uint32_t __bm_isr_read(struct bm_portal *portal, enum bm_isr_reg n) + { +- return __bm_in(&portal->addr, REG_ISR + (n << 2)); ++ return __bm_in(&portal->addr, REG_ISR + (n << BM_ISR_SHIFT)); + } + + + void __bm_isr_write(struct bm_portal *portal, enum bm_isr_reg n, uint32_t val) + { +- __bm_out(&portal->addr, REG_ISR + (n << 2), val); ++ __bm_out(&portal->addr, REG_ISR + (n << BM_ISR_SHIFT), val); + } + +diff --git a/sys/contrib/ncsw/Peripherals/BM/bman_private.h b/sys/contrib/ncsw/Peripherals/BM/bman_private.h +index 972c57cecb0..2641792e2e6 100644 +--- a/sys/contrib/ncsw/Peripherals/BM/bman_private.h ++++ b/sys/contrib/ncsw/Peripherals/BM/bman_private.h +@@ -55,6 +55,39 @@ + * execution reordering with respect to other code/instructions that manipulate + * the same cacheline. */ + ++#if defined(__aarch64__) ++/* ++ * ARM64 cache operations. ++ * ++ * Portal CE region is mapped Normal Non-Cacheable (matching Linux's ++ * MEMREMAP_WC), so stores go directly to hardware. However, dcbf is ++ * also used on cacheable DMA memory (buffer pools) — there we need ++ * real cache clean to make CPU writes visible to BMan hardware. ++ * ++ * dc cvac (clean by VA to PoC) is the ARM64 equivalent of PPC dcbf. ++ * On NC addresses it's a harmless no-op; on cached addresses it writes ++ * dirty lines back to memory. ++ * ++ * dc zva MUST NOT be used on portal NC memory — it generates a special ++ * bus transaction that can hang the interconnect. Use memset instead. ++ */ ++#define lwsync() __asm__ __volatile__ ("dmb ish" : : : "memory") ++#define dcbf(addr) do { \ ++ __asm__ __volatile__ ("dc cvac, %0" : : "r"(addr) : "memory"); \ ++ __asm__ __volatile__ ("dsb st" : : : "memory"); \ ++} while(0) ++#define dcbi(p) __asm__ __volatile__ ("dsb sy" : : : "memory") ++#define dcbt_ro(addr) do { } while(0) ++#define dcbt_rw(addr) do { } while(0) ++#define dcbz_64(p) do { memset((p), 0, 64); } while(0) ++#define dcbf_64(p) do { \ ++ __asm__ __volatile__ ("dc cvac, %0" : : "r"(p) : "memory"); \ ++ __asm__ __volatile__ ("dsb st" : : : "memory"); \ ++} while(0) ++#define dcbit_ro(p) do { } while(0) ++ ++#else /* PowerPC */ ++ + #define dcbf(addr) \ + do { \ + __asm__ __volatile__ ("dcbf 0, %0" : : "r" (addr)); \ +@@ -127,6 +160,8 @@ + + #define dcbi(p) dcbf(p) + ++#endif /* __aarch64__ */ ++ + struct bm_addr { + void *addr_ce; /* cache-enabled */ + void *addr_ci; /* cache-inhibited */ +diff --git a/sys/contrib/ncsw/Peripherals/FM/HC/hc.c b/sys/contrib/ncsw/Peripherals/FM/HC/hc.c +index 903d55e4b7e..0470bbbb777 100644 +--- a/sys/contrib/ncsw/Peripherals/FM/HC/hc.c ++++ b/sys/contrib/ncsw/Peripherals/FM/HC/hc.c +@@ -228,7 +228,12 @@ static __inline__ t_Error EnQFrm(t_FmHc *p_FmHc, t_DpaaFD *p_FmFd, uint32_t seqN + XX_UDelay(100); + + if (!timeout) ++ { ++ intFlags = FmPcdLock(p_FmHc->h_FmPcd); ++ p_FmHc->enqueued[seqNum] = FALSE; ++ FmPcdUnlock(p_FmHc->h_FmPcd, intFlags); + RETURN_ERROR(MINOR, E_TIMEOUT, ("HC Callback, timeout exceeded")); ++ } + + return err; + } +diff --git a/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_cc.c b/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_cc.c +index a9fd2c1d036..ba734f9956b 100644 +--- a/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_cc.c ++++ b/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_cc.c +@@ -38,6 +38,7 @@ + *//***************************************************************************/ + #include + #include ++ + #include "std_ext.h" + #include "error_ext.h" + #include "string_ext.h" +@@ -51,6 +52,15 @@ + #include "fm_cc.h" + #include "crc64.h" + ++#ifdef USE_ENHANCED_EHASH ++#include "fm_ehash.h" ++extern t_Handle ExternalHashTableSet(t_Handle h_FmPcd, ++ t_FmPcdHashTableParams *p_Param); ++extern t_Error ExternalHashTableModifyMissNextEngine(t_Handle h_HashTbl, ++ t_FmPcdCcNextEngineParams *p_FmPcdCcNextEngineParams); ++extern void copy_td_to_ccbase(void *handle, t_Handle p_CcTreeTmp); ++#endif /* USE_ENHANCED_EHASH */ ++ + /****************************************/ + /* static functions */ + /****************************************/ +@@ -344,6 +354,24 @@ static void FillAdOfTypeContLookup(t_Handle h_Ad, + /* if (p_AdNewPtr = NULL) --> Done. (case (3)) */ + if (p_AdNewPtr) + { ++#if (DPAA_VERSION >= 11) ++ if (p_Node->externalHash) ++ { ++ /* ++ * External hash table (CDX): write a zeroed placeholder AD. ++ * CDX will overwrite this AD with its opcode-format entries ++ * when it takes over the hash table. Until then, the zero ++ * AD acts as a "result" type with FQID=0 / NIA=0, which ++ * causes FMan to enqueue to the default queue. ++ */ ++ WRITE_UINT32(p_AdContLookup->ccAdBase, 0); ++ WRITE_UINT32(p_AdContLookup->matchTblPtr, 0); ++ WRITE_UINT32(p_AdContLookup->pcAndOffsets, 0); ++ WRITE_UINT32(p_AdContLookup->gmask, 0); ++ } ++ else ++#endif /* (DPAA_VERSION >= 11) */ ++ { + /* cases (1) & (2) */ + tmpReg32 = 0; + tmpReg32 |= FM_PCD_AD_CONT_LOOKUP_TYPE; +@@ -371,6 +399,7 @@ static void FillAdOfTypeContLookup(t_Handle h_Ad, + + MemCpy8((void*)&p_AdContLookup->gmask, p_Node->p_GlblMask, + CC_GLBL_MASK_SIZE); ++ } + } + } + +@@ -1071,6 +1100,7 @@ static bool IsCapwapApplSpecific(t_Handle h_Node) + } + #endif /* FM_CAPWAP_SUPPORT */ + ++#ifndef USE_ENHANCED_EHASH + static t_Error CcUpdateParam( + t_Handle h_FmPcd, t_Handle h_PcdParams, t_Handle h_FmPort, + t_FmPcdCcKeyAndNextEngineParams *p_CcKeyAndNextEngineParams, +@@ -1165,6 +1195,34 @@ static t_Error CcUpdateParam( + + return E_OK; + } ++#else /* USE_ENHANCED_EHASH */ ++/* ++ * With enhanced ehash, CC tree entries contain CDX enhanced AD content ++ * written by copy_td_to_ccbase(). No NCSW internal parameter update ++ * or recursive tree walking needed — h_CcNode handles are en_exthash_info* ++ * not t_FmPcdCcNode*, so the internal code would crash. ++ * Matching Linux SDK fm_cc.c:1209-1221. ++ */ ++static t_Error CcUpdateParam( ++ t_Handle h_FmPcd, t_Handle h_PcdParams, t_Handle h_FmPort, ++ t_FmPcdCcKeyAndNextEngineParams *p_CcKeyAndNextEngineParams, ++ uint16_t numOfEntries, t_Handle h_Ad, bool validate, uint16_t level, ++ t_Handle h_FmTree, bool modify) ++{ ++ UNUSED(h_FmPcd); ++ UNUSED(h_PcdParams); ++ UNUSED(h_FmPort); ++ UNUSED(p_CcKeyAndNextEngineParams); ++ UNUSED(numOfEntries); ++ UNUSED(h_Ad); ++ UNUSED(validate); ++ UNUSED(level); ++ UNUSED(h_FmTree); ++ UNUSED(modify); ++ ++ return E_OK; ++} ++#endif /* USE_ENHANCED_EHASH */ + + static ccPrivateInfo_t IcDefineCode(t_FmPcdCcNodeParams *p_CcNodeParam) + { +@@ -6005,8 +6063,10 @@ t_Handle FM_PCD_CcRootBuild(t_Handle h_FmPcd, + t_NetEnvParams netEnvParams; + uint8_t lastOne = 0; + uint32_t requiredAction = 0; ++#ifndef USE_ENHANCED_EHASH + t_FmPcdCcNode *p_FmPcdCcNextNode; + t_CcNodeInformation ccNodeInfo, *p_CcInformation; ++#endif + + SANITY_CHECK_RETURN_VALUE(h_FmPcd, E_INVALID_HANDLE, NULL); + SANITY_CHECK_RETURN_VALUE(p_PcdGroupsParam, E_INVALID_HANDLE, NULL); +@@ -6190,6 +6250,7 @@ t_Handle FM_PCD_CcRootBuild(t_Handle h_FmPcd, + + p_CcTreeTmp = UINT_TO_PTR(p_FmPcdCcTree->ccTreeBaseAddr); + ++#ifndef USE_ENHANCED_EHASH + for (i = 0; i < numOfEntries; i++) + { + p_KeyAndNextEngineParams = p_Params + i; +@@ -6225,10 +6286,59 @@ t_Handle FM_PCD_CcRootBuild(t_Handle h_FmPcd, + p_CcInformation->index++; + } + } ++#else /* USE_ENHANCED_EHASH */ ++ for (i = 0; i < numOfEntries; i++) ++ { ++ t_FmPcdCcNextEngineParams *nexteng; ++ ++ p_KeyAndNextEngineParams = p_Params + i; ++ nexteng = &p_KeyAndNextEngineParams->nextEngineParams; ++ ++ if (nexteng->nextEngine == e_FM_PCD_CC && ++ nexteng->params.ccParams.h_CcNode) ++ { ++ /* Enhanced external hash table: copy AD into CC tree MURAM slot */ ++ copy_td_to_ccbase(nexteng->params.ccParams.h_CcNode, p_CcTreeTmp); ++ } ++ else ++ { ++ /* Non-CC entry (KG/PLCR/DONE): use standard result AD */ ++ NextStepAd(p_CcTreeTmp, NULL, nexteng, p_FmPcd); ++ } ++ ++ p_CcTreeTmp = PTR_MOVE(p_CcTreeTmp, FM_PCD_CC_AD_ENTRY_SIZE); ++ ++ memcpy(&p_FmPcdCcTree->keyAndNextEngineParams[i], ++ p_KeyAndNextEngineParams, ++ sizeof(t_FmPcdCcKeyAndNextEngineParams)); ++ } ++ ++ /* ++ * Fill unused CC tree entries (numOfEntries..15) with a copy of ++ * entry 0. A zeroed EHASH AD has table_base=0x0 — FMan DMA to ++ * physical address 0 (not DDR) hangs the task permanently. ++ * Copying entry 0 gives a valid table_base, int_buf_pool, and ++ * global_mem_offset. The miss_action starts as DONE (0); ++ * ExternalHashTableModifyMissNextEngine propagates the correct ++ * miss action to all copies by scanning for matching table_base_lo. ++ */ ++ if (numOfEntries > 0 && numOfEntries < FM_PCD_MAX_NUM_OF_CC_GROUPS) ++ { ++ uint8_t *base = (uint8_t *) ++ UINT_TO_PTR(p_FmPcdCcTree->ccTreeBaseAddr); ++ for (i = numOfEntries; i < FM_PCD_MAX_NUM_OF_CC_GROUPS; i++) ++ { ++ memcpy(base + i * FM_PCD_CC_AD_ENTRY_SIZE, ++ base, ++ FM_PCD_CC_AD_ENTRY_SIZE); ++ } ++ } ++#endif /* USE_ENHANCED_EHASH */ + + FmPcdIncNetEnvOwners(h_FmPcd, p_FmPcdCcTree->netEnvId); + p_CcTreeTmp = UINT_TO_PTR(p_FmPcdCcTree->ccTreeBaseAddr); + ++#ifndef USE_ENHANCED_EHASH + if (!FmPcdLockTryLockAll(p_FmPcd)) + { + FM_PCD_CcRootDelete(p_FmPcdCcTree); +@@ -6259,6 +6369,7 @@ t_Handle FM_PCD_CcRootBuild(t_Handle h_FmPcd, + } + + FmPcdLockUnlockAll(p_FmPcd); ++#endif /* USE_ENHANCED_EHASH */ + p_FmPcdCcTree->p_Lock = FmPcdAcquireLock(p_FmPcd); + if (!p_FmPcdCcTree->p_Lock) + { +@@ -7112,6 +7223,9 @@ t_Error FM_PCD_MatchTableGetIndexedHashBucket(t_Handle h_CcNode, + + t_Handle FM_PCD_HashTableSet(t_Handle h_FmPcd, t_FmPcdHashTableParams *p_Param) + { ++#ifdef USE_ENHANCED_EHASH ++ return ExternalHashTableSet(h_FmPcd, p_Param); ++#else /* !USE_ENHANCED_EHASH */ + t_FmPcdCcNode *p_CcNodeHashTbl; + t_FmPcdCcNodeParams *p_IndxHashCcNodeParam, *p_ExactMatchCcNodeParam; + t_FmPcdCcNode *p_CcNode; +@@ -7151,6 +7265,57 @@ t_Handle FM_PCD_HashTableSet(t_Handle h_FmPcd, t_FmPcdHashTableParams *p_Param) + ("RMON statistics mode is not supported for hash table")); + return NULL; + } ++ ++ if (p_Param->externalHash) ++ { ++ /* ++ * External hash table: CDX manages the hash buckets in DDR. ++ * NCSW only allocates a minimal t_FmPcdCcNode with a MURAM AD ++ * placeholder. CDX will take over the AD and rewrite it with ++ * CDX opcode entries. ++ * ++ * The AD is initially zeroed (safe: result type, enqueue to ++ * default FQ). Packets reaching this node before CDX takes ++ * over will be enqueued to the default queue harmlessly. ++ */ ++ t_FmPcdCcNode *p_ExtNode; ++ t_FmPcd *p_FmPcd = (t_FmPcd *)h_FmPcd; ++ ++ p_ExtNode = (t_FmPcdCcNode *)XX_Malloc(sizeof(t_FmPcdCcNode)); ++ if (!p_ExtNode) ++ { ++ REPORT_ERROR(MAJOR, E_NO_MEMORY, ("external hash CC node")); ++ return NULL; ++ } ++ memset(p_ExtNode, 0, sizeof(t_FmPcdCcNode)); ++ ++ p_ExtNode->externalHash = TRUE; ++ p_ExtNode->h_FmPcd = h_FmPcd; ++ p_ExtNode->kgHashShift = p_Param->kgHashShift; ++ p_ExtNode->statisticsMode = p_Param->statisticsMode; ++ ++ /* Allocate MURAM AD for this node */ ++ p_ExtNode->h_Ad = (t_Handle)FM_MURAM_AllocMem( ++ p_FmPcd->h_FmMuram, ++ FM_PCD_CC_AD_ENTRY_SIZE, FM_PCD_CC_AD_TABLE_ALIGN); ++ if (!p_ExtNode->h_Ad) ++ { ++ XX_Free(p_ExtNode); ++ REPORT_ERROR(MAJOR, E_NO_MEMORY, ++ ("MURAM allocation for external hash AD")); ++ return NULL; ++ } ++ MemSet8(p_ExtNode->h_Ad, 0, FM_PCD_CC_AD_ENTRY_SIZE); ++ ++ p_ExtNode->h_Spinlock = XX_InitSpinlock(); ++ ++ INIT_LIST(&p_ExtNode->ccPrevNodesLst); ++ INIT_LIST(&p_ExtNode->ccTreeIdLst); ++ INIT_LIST(&p_ExtNode->ccTreesLst); ++ INIT_LIST(&p_ExtNode->availableStatsLst); ++ ++ return (t_Handle)p_ExtNode; ++ } + #endif /* (DPAA_VERSION >= 11) */ + + p_ExactMatchCcNodeParam = (t_FmPcdCcNodeParams*)XX_Malloc( +@@ -7305,10 +7470,14 @@ t_Handle FM_PCD_HashTableSet(t_Handle h_FmPcd, t_FmPcdHashTableParams *p_Param) + XX_Free(p_ExactMatchCcNodeParam); + + return p_CcNodeHashTbl; ++#endif /* !USE_ENHANCED_EHASH */ + } + + t_Error FM_PCD_HashTableDelete(t_Handle h_HashTbl) + { ++#ifdef USE_ENHANCED_EHASH ++ return (t_Error)-1; /* delete not implemented for enhanced ehash */ ++#else + t_FmPcdCcNode *p_HashTbl = (t_FmPcdCcNode *)h_HashTbl; + t_Handle h_FmPcd; + t_Handle *p_HashBuckets, h_MissStatsCounters; +@@ -7317,6 +7486,19 @@ t_Error FM_PCD_HashTableDelete(t_Handle h_HashTbl) + + SANITY_CHECK_RETURN_ERROR(p_HashTbl, E_INVALID_HANDLE); + ++#if (DPAA_VERSION >= 11) ++ if (p_HashTbl->externalHash) ++ { ++ if (p_HashTbl->h_Ad) ++ FM_MURAM_FreeMem(FmPcdGetMuramHandle(p_HashTbl->h_FmPcd), ++ p_HashTbl->h_Ad); ++ if (p_HashTbl->h_Spinlock) ++ XX_FreeSpinlock(p_HashTbl->h_Spinlock); ++ XX_Free(p_HashTbl); ++ return E_OK; ++ } ++#endif /* (DPAA_VERSION >= 11) */ ++ + /* Store all hash buckets before the hash is freed */ + numOfBuckets = p_HashTbl->numOfKeys; + +@@ -7348,11 +7530,20 @@ t_Error FM_PCD_HashTableDelete(t_Handle h_HashTbl) + RETURN_ERROR(MAJOR, err, NO_MSG); + + return E_OK; ++#endif /* !USE_ENHANCED_EHASH */ + } + + t_Error FM_PCD_HashTableAddKey(t_Handle h_HashTbl, uint8_t keySize, + t_FmPcdCcKeyParams *p_KeyParams) + { ++#ifdef USE_ENHANCED_EHASH ++ /* CDX adds keys directly via ExternalHashTableAddKey (different ++ * signature). This NCSW dispatch path is not used. */ ++ UNUSED(h_HashTbl); ++ UNUSED(keySize); ++ UNUSED(p_KeyParams); ++ return E_NOT_SUPPORTED; ++#else + t_FmPcdCcNode *p_HashTbl = (t_FmPcdCcNode *)h_HashTbl; + t_Handle h_HashBucket; + uint8_t bucketIndex; +@@ -7377,8 +7568,10 @@ t_Error FM_PCD_HashTableAddKey(t_Handle h_HashTbl, uint8_t keySize, + + return FM_PCD_MatchTableAddKey(h_HashBucket, FM_PCD_LAST_KEY_INDEX, keySize, + p_KeyParams); ++#endif /* !USE_ENHANCED_EHASH */ + } + ++#ifndef USE_ENHANCED_EHASH + t_Error FM_PCD_HashTableRemoveKey(t_Handle h_HashTbl, uint8_t keySize, + uint8_t *p_Key) + { +@@ -7426,11 +7619,16 @@ t_Error FM_PCD_HashTableModifyNextEngine( + NULL, + p_FmPcdCcNextEngineParams); + } ++#endif /* !USE_ENHANCED_EHASH */ + + t_Error FM_PCD_HashTableModifyMissNextEngine( + t_Handle h_HashTbl, + t_FmPcdCcNextEngineParams *p_FmPcdCcNextEngineParams) + { ++#ifdef USE_ENHANCED_EHASH ++ return ExternalHashTableModifyMissNextEngine(h_HashTbl, ++ p_FmPcdCcNextEngineParams); ++#else + t_FmPcdCcNode *p_HashTbl = (t_FmPcdCcNode *)h_HashTbl; + t_Handle h_HashBucket; + uint8_t i; +@@ -7483,9 +7681,11 @@ t_Error FM_PCD_HashTableModifyMissNextEngine( + } + + return E_OK; ++#endif /* !USE_ENHANCED_EHASH */ + } + + ++#ifndef USE_ENHANCED_EHASH + t_Error FM_PCD_HashTableGetMissNextEngine( + t_Handle h_HashTbl, + t_FmPcdCcNextEngineParams *p_FmPcdCcNextEngineParams) +@@ -7549,3 +7749,4 @@ t_Error FM_PCD_HashTableGetMissStatistics( + + return FM_PCD_MatchTableGetMissStatistics(h_HashBucket, p_MissStatistics); + } ++#endif /* !USE_ENHANCED_EHASH */ +diff --git a/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_cc.h b/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_cc.h +index 3456bb565fd..30bed7c5c44 100644 +--- a/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_cc.h ++++ b/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_cc.h +@@ -348,6 +348,11 @@ typedef struct + uint32_t shadowAction; + uint8_t userSizeOfExtraction; + uint8_t userOffset; ++ ++#if (DPAA_VERSION >= 11) ++ bool externalHash; /* CDX external hash table */ ++#endif /* (DPAA_VERSION >= 11) */ ++ + uint8_t kgHashShift; /* used in hash-table */ + + t_Handle h_Spinlock; +diff --git a/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_ehash.c b/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_ehash.c +new file mode 100644 +index 00000000000..09926af104e +--- /dev/null ++++ b/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_ehash.c +@@ -0,0 +1,1530 @@ ++/* ++ * fm_ehash.c — FMan enhanced external hash table (kernel-side) ++ * ++ * Ported from: ++ * linux/drivers/net/ethernet/freescale/sdk_fman/Peripherals/FM/Pcd/fm_ehash.c ++ * ++ * Implements the ExternalHashTable* API used by CDX for hardware flow ++ * offload. Manages DDR-based hash tables with CRC64-indexed buckets ++ * and per-bucket spinlocks. ++ * ++ * With USE_ENHANCED_EHASH, FM_PCD_HashTableSet (in fm_cc.c) redirects ++ * to ExternalHashTableSet here. The returned handle (en_exthash_info*) ++ * is opaque to all callers (fmlib, FMC, dpa_app, CDX). ++ * ++ * The MURAM Action Descriptor is NOT allocated here. copy_td_to_ccbase() ++ * writes the AD content from info->node into the CC tree's MURAM slot ++ * during FM_PCD_CcRootBuild, and saves the MURAM address to info->h_Ad. ++ * ExternalHashTableModifyMissNextEngine then uses info->h_Ad to patch ++ * the miss action in-place. ++ * ++ * Simplifications for initial port: ++ * - NO_CUMULATIVE_ENTRY: simple linked-list buckets, no compaction ++ * - No IP reassembly table support (table_type REASSM is accepted ++ * but reassembly-specific params are ignored) ++ * ++ * Copyright 2018 NXP (original Linux SDK code) ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * SPDX-License-Identifier: BSD-2-Clause ++ */ ++ ++#include "opt_dpaa.h" ++ ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++ ++/* NCSW public headers (resolved via -I paths in DPAA_COMPILE_CMD) */ ++#include "ncsw_ext.h" ++#include "error_ext.h" ++#include "endian_ext.h" ++#include "xx_ext.h" ++#include "fm_pcd_ext.h" ++#include "fm_muram_ext.h" ++ ++/* NCSW internal headers — needed for t_FmPcd, FmPcdGetMuramHandle, etc. */ ++#include "fm_pcd.h" ++#include "fm_cc.h" ++#include "fm_common.h" ++ ++/* CRC64 from NCSW PCD */ ++#include "crc64.h" ++ ++/* CDX fm_ehash.h — entry/bucket structs and opcode constants */ ++#include "fm_ehash.h" ++ ++/* Linux endian compat — guarded against LinuxKPI which defines them too */ ++#ifndef cpu_to_be16 ++#define cpu_to_be16(x) htobe16(x) ++#endif ++#ifndef cpu_to_be32 ++#define cpu_to_be32(x) htobe32(x) ++#endif ++#ifndef be64_to_cpu ++#define be64_to_cpu(x) be64toh(x) ++#endif ++ ++/* ---------------------------------------------------------------- ++ * Direct MURAM accessors — batch-safe volatile stores/loads ++ * ++ * MURAM on LS1046A ARM64 requires that multiple stores to the same ++ * 16-byte region are batched WITHOUT a dsb sy between each store. ++ * A dsb sy after each store causes all but the last to be lost ++ * (confirmed empirically: raw batch stores + single dsb work, ++ * per-store dsb does not). ++ * ++ * muram_wr32 does a raw volatile store with bswap, NO barrier. ++ * muram_rd32 does a raw volatile load with bswap + read barrier. ++ * muram_barrier() issues a single dsb sy — call ONCE after all ++ * stores in a batch are complete. ++ * ---------------------------------------------------------------- */ ++#define muram_barrier() __asm __volatile("dsb sy" ::: "memory") ++ ++static __inline void ++muram_wr32(volatile uint32_t *addr, uint32_t native_val) ++{ ++ ++ *addr = __builtin_bswap32(native_val); ++ /* NO barrier here — caller must call muram_barrier() after batch */ ++} ++ ++/* ++ * muram_wr64 — write two native uint32_t values as a single 64-bit store. ++ * ++ * A 64-bit store is a single AXI bus transaction, which the MURAM ++ * controller handles atomically. This avoids the partial-write ++ * corruption seen with two separate 32-bit stores when FMan microcode ++ * concurrently reads the same 16-byte AD region. ++ * ++ * On LE ARM64, a 64-bit store writes: ++ * bits[31:0] → bytes at addr+0 (native_lo, byte-swapped) ++ * bits[63:32] → bytes at addr+4 (native_hi, byte-swapped) ++ */ ++static __inline void ++muram_wr64(volatile uint64_t *addr, uint32_t native_lo, uint32_t native_hi) ++{ ++ ++ *addr = ((uint64_t)__builtin_bswap32(native_hi) << 32) | ++ (uint64_t)__builtin_bswap32(native_lo); ++ /* NO barrier here — caller must call muram_barrier() after batch */ ++} ++ ++static __inline uint32_t ++muram_rd32(volatile uint32_t *addr) ++{ ++ uint32_t v; ++ ++ v = *addr; ++ __asm __volatile("dsb sy" ::: "memory"); ++ return (__builtin_bswap32(v)); ++} ++ ++/* ---------------------------------------------------------------- ++ * Internal definitions (supplements fm_ehash.h) ++ * ---------------------------------------------------------------- */ ++ ++/* Miss action types for en_exthash_node */ ++#define EN_EHASH_MISS_ACTION_DROP 3 ++#define EN_EHASH_MISS_ACTION_NIA 1 ++#define EN_EHASH_MISS_ACTION_ENQUE 2 ++#define EN_EHASH_MISS_ACTION_DONE 0 ++ ++/* Internal buffer pool size and table alignment */ ++#define EN_INTERNAL_BUFF_POOL_SIZE (256 * 128) ++#define EN_EXTHASH_TBL_ALIGNMENT 256 ++ ++/* ++ * Hardware table_type constants for en_exthash_node word_0 bits [23:20] ++ * (LE ARM64 C bitfield position). ++ * The CDX microcode uses table_type to identify the hash table's ++ * protocol layer. Without a valid table_type, the microcode does ++ * not recognize the AD as an enhanced hash table entry. ++ */ ++#define EHASH_HW_TABLE_TYPE_L2 (1 << 0) /* 0x1 */ ++#define EHASH_HW_TABLE_TYPE_L3 (1 << 1) /* 0x2 */ ++#define EHASH_HW_TABLE_TYPE_L4 (1 << 2) /* 0x4 */ ++#define EHASH_HW_TABLE_TYPE_REASSM (1 << 3) /* 0x8 */ ++ ++/* ++ * Convert user-facing table_type enum (from dpa_app/fmlib) to ++ * hardware table_type constant. Enum values match fm_eh_types.h. ++ */ ++static uint32_t ++ehash_hw_table_type(uint32_t user_type) ++{ ++ ++ switch (user_type & 0xf) { ++ case 0: /* IPV4_UDP_TABLE */ ++ case 1: /* IPV4_TCP_TABLE */ ++ case 2: /* IPV6_UDP_TABLE */ ++ case 3: /* IPV6_TCP_TABLE */ ++ case 4: /* ESP_IPV4_TABLE */ ++ case 5: /* ESP_IPV6_TABLE */ ++ case 10: /* IPV4_3TUPLE_UDP_TABLE */ ++ case 11: /* IPV4_3TUPLE_TCP_TABLE */ ++ case 12: /* IPV6_3TUPLE_UDP_TABLE */ ++ case 13: /* IPV6_3TUPLE_TCP_TABLE */ ++ return (EHASH_HW_TABLE_TYPE_L4); ++ case 6: /* IPV4_MULTICAST_TABLE */ ++ case 7: /* IPV6_MULTICAST_TABLE */ ++ return (EHASH_HW_TABLE_TYPE_L3); ++ case 14: /* IPV4_REASSM_TABLE */ ++ case 15: /* IPV6_REASSM_TABLE */ ++ return (EHASH_HW_TABLE_TYPE_REASSM); ++ default: /* PPPOE_RELAY_TABLE, ETHERNET_TABLE, etc. */ ++ return (EHASH_HW_TABLE_TYPE_L2); ++ } ++} ++ ++/* Flags for en_exthash_info.flags */ ++#define TIMESTAMP_EN (1 << 0) ++#define STATS_EN (1 << 1) ++ ++/* ++ * en_exthash_node — Action Descriptor for enhanced external hash table. ++ * Written to MURAM (via copy_td_to_ccbase); read by FMan CDX microcode. ++ * ++ * The Linux SDK (fm_ehash.h line 563) defines this with C bitfield unions ++ * "assuming a LE GPP core". On LE ARM64, the first declared struct field ++ * occupies the LSB. muram_wr32/muram_wr64 byte-swap the native value ++ * so FMan (always BE) reads the correct numeric value. ++ * ++ * CONFIRMED: LE ARM64 C bitfield positions are correct. Attempting ++ * PPC/BE positions (build #194) causes FMan exception 5 (crash). ++ * ++ * Non-EXCLUDE_FMAN_IPR_OFFLOAD layout (active on LS1046A): ++ * ++ * word_0 — LE ARM64 C bitfield positions (first field at LSB): ++ * bits 7:0 = table_base_hi (8) — upper bits of 40-bit table addr ++ * bits 15:8 = ipv4_ad_offset (8) — IPR reassembly AD offset (0) ++ * bits 18:16 = hash_bytes_offset (3) — CRC64 shift parameter ++ * bit 19 = reserved (1) ++ * bits 23:20 = table_type (4) — L2/L3/L4/REASSM identifier ++ * bits 29:24 = key_size (6) ++ * bits 31:30 = miss_action_type (2) ++ * ++ * word_1 — LE ARM64 C bitfield positions: ++ * bits 3:0 = hash_mask_bits (4) ++ * bits 15:4 = global_mem_offset (12) ++ * bits 31:16 = int_buf_pool_addr (16) ++ * ++ * word_2: nia or fqid depending on miss_action_type ++ */ ++struct en_exthash_node { ++ uint32_t word_0; ++ uint32_t table_base_lo; ++ uint32_t word_1; ++ uint32_t word_2; /* nia or fqid */ ++} __attribute__((packed)); ++ ++/* word_0 field construction — LE ARM64 C bitfield positions. ++ * ++ * On LE ARM64, C bitfields place the first declared field at bit 0 (LSB). ++ * muram_wr32/muram_wr64 byte-swap the native value for MURAM storage. ++ * ++ * Non-EXCLUDE_FMAN_IPR_OFFLOAD variant (LS1046A). */ ++#define EHASH_W0_TABLE_BASE_HI(v) ((uint32_t)(v) & 0xFF) /* bits 7:0 */ ++#define EHASH_W0_IPV4_AD_OFF(v) (((uint32_t)(v) & 0xFF) << 8) /* bits 15:8 */ ++#define EHASH_W0_HASH_BYTES_OFF(v) (((uint32_t)(v) & 0x7) << 16) /* bits 18:16 */ ++#define EHASH_W0_TABLE_TYPE(v) (((uint32_t)(v) & 0xF) << 20) /* bits 23:20 */ ++#define EHASH_W0_KEY_SIZE(v) (((uint32_t)(v) & 0x3F) << 24) /* bits 29:24 */ ++#define EHASH_W0_MISS_ACTION(v) (((uint32_t)(v) & 0x3) << 30) /* bits 31:30 */ ++#define EHASH_W0_MISS_ACTION_MASK (0x3U << 30) /* bits 31:30 */ ++ ++/* word_1 field construction — LE ARM64 C bitfield positions. ++ * Non-EXCLUDE variant: hash_mask_bits at LSB, then ++ * global_mem_offset, then int_buf_pool_addr at MSB. */ ++#define EHASH_W1_HASH_MASK_BITS(v) ((uint32_t)(v) & 0xF) /* bits 3:0 */ ++#define EHASH_W1_GLOBAL_MEM_OFF(v) (((uint32_t)(v) & 0xFFF) << 4) /* bits 15:4 */ ++#define EHASH_W1_INT_BUF_POOL(v) (((uint32_t)(v) & 0xFFFF) << 16) /* bits 31:16 */ ++ ++/* ++ * en_exthash_info — Per-table software state. ++ * Returned as opaque t_Handle to callers. ++ */ ++struct en_exthash_info { ++ uint32_t flags; ++ void *table_base; /* DDR bucket array */ ++ void **pSpinlock; /* per-bucket spinlock array */ ++ void *h_Ad; /* MURAM AD pointer (set by copy_td_to_ccbase) */ ++ struct en_exthash_node node; /* local copy of table descriptor */ ++ uint32_t tablesize; ++ uint32_t hashmask; ++ uint32_t keysize; ++ uint32_t hashshift; ++ uint32_t dataMemId; ++ uint32_t dataLiodnOffset; ++ uint32_t num_keys; ++ uint32_t max_collisions; ++ void *pcd; /* PCD handle */ ++ uint32_t table_type; /* user-facing type (L2/L3/L4/REASSM) */ ++ struct ip_reassembly_params *ip_reassem_info; /* MURAM VA, REASSM only */ ++}; ++ ++MALLOC_DEFINE(M_EHASH, "ehash", "CDX external hash table"); ++ ++/* ---------------------------------------------------------------- ++ * Internal buffer pool management — allocated once in MURAM ++ * ---------------------------------------------------------------- */ ++ ++static void *ehash_int_muram_ptr; /* virtual address */ ++static uint32_t ehash_int_muram_area; /* MURAM offset >> 8 */ ++static void *ehash_first_table_base;/* DDR base of first table */ ++ ++/* Global MURAM data area — dscp_vlanpcp_map + SEC_failure_stats. ++ * Points to pool + EN_INTERNAL_BUFF_POOL_SIZE. Initialized in ++ * ehash_init_muram_pool(). */ ++static en_exthash_global_mem *ehash_global_mem; ++ ++/* Reassembly table tracking — set during ExternalHashTableSet() ++ * for IPV4_REASSM_TABLE (14) and IPV6_REASSM_TABLE (15). */ ++#define EHASH_IPV4_REASSM_TABLE 14 ++#define EHASH_IPV6_REASSM_TABLE 15 ++ ++static struct en_exthash_info *ehash_ipv4_reassly_tbl; ++static struct en_exthash_info *ehash_ipv6_reassly_tbl; ++ ++/* ---------------------------------------------------------------- ++ * External timestamp slots — separate MURAM allocation ++ * ++ * Timestamps MUST be in their own MURAM region, NOT in the global ++ * data area. The global data area (at int_buf_pool + POOL_SIZE) ++ * contains en_exthash_global_mem (dscp_vlanpcp_map + SEC_failure_stats) ++ * which the CDX microcode reads/writes at runtime. ++ * ++ * Linux SDK allocates timestamps separately in FM_PCD_Init() ++ * (fm_pcd.c: FM_MURAM_AllocMem for MAX_EXT_TS_TIMERS * EXT_TS_SIZE). ++ * ---------------------------------------------------------------- */ ++ ++#define MAX_EXT_TS_TIMERS 4 ++ ++static uint32_t *ehash_ts_virt; /* virtual ptr to slot[0] */ ++static uint64_t ehash_ts_phys; /* physical addr of slot[0] */ ++static uint64_t ehash_muram_phys_base; /* MURAM physical base */ ++ ++/* ++ * Allocate the internal buffer pool + global data area in MURAM, ++ * plus a SEPARATE timestamp region. ++ * Called once on first ExternalHashTableSet. ++ */ ++static int ++ehash_init_muram_pool(t_Handle h_FmPcd) ++{ ++ t_FmPcd *p_FmPcd = (t_FmPcd *)h_FmPcd; ++ t_Handle h_FmMuram; ++ uint32_t total_size; ++ uint32_t muram_offset; ++ uint32_t ts_size; ++ ++ if (ehash_int_muram_ptr != NULL) ++ return (0); ++ ++ h_FmMuram = FmPcdGetMuramHandle(h_FmPcd); ++ if (h_FmMuram == NULL) ++ return (-1); ++ ++ /* ++ * Layout of the pool+global allocation: ++ * [0 .. EN_INTERNAL_BUFF_POOL_SIZE-1] internal buffer pool ++ * [EN_INTERNAL_BUFF_POOL_SIZE .. +256] global data area ++ * (en_exthash_global_mem: dscp_vlanpcp_map + SEC_failure_stats) ++ * ++ * Timestamps are allocated SEPARATELY below. ++ */ ++ total_size = EN_INTERNAL_BUFF_POOL_SIZE + 256; ++ ++ ehash_int_muram_ptr = FM_MURAM_AllocMem(h_FmMuram, ++ total_size, EN_EXTHASH_TBL_ALIGNMENT); ++ if (ehash_int_muram_ptr == NULL) { ++ printf("fm_ehash: MURAM alloc failed (%u bytes)\n", ++ total_size); ++ return (-1); ++ } ++ IOMemSet32(ehash_int_muram_ptr, 0, total_size); ++ ++ /* Compute compressed MURAM offset (physical offset / 256) */ ++ muram_offset = (uint32_t)(XX_VirtToPhys(ehash_int_muram_ptr) - ++ p_FmPcd->physicalMuramBase); ++ if (muram_offset & 0xff) { ++ printf("fm_ehash: MURAM pool not 256-aligned (0x%x)\n", ++ muram_offset); ++ FM_MURAM_FreeMem(h_FmMuram, ehash_int_muram_ptr); ++ ehash_int_muram_ptr = NULL; ++ return (-1); ++ } ++ ++ ehash_int_muram_area = muram_offset >> 8; ++ ++ ehash_muram_phys_base = p_FmPcd->physicalMuramBase; ++ ++ printf("fm_ehash: MURAM pool at %p, offset 0x%x (compressed 0x%x)\n", ++ ehash_int_muram_ptr, muram_offset, ehash_int_muram_area); ++ ehash_global_mem = (en_exthash_global_mem *)((uint8_t *)ehash_int_muram_ptr + ++ EN_INTERNAL_BUFF_POOL_SIZE); ++ ++ printf("fm_ehash: global data at pool+0x%x (en_exthash_global_mem)\n", ++ EN_INTERNAL_BUFF_POOL_SIZE); ++ ++ /* ++ * Allocate timestamp slots as a SEPARATE MURAM region. ++ * Linux SDK does this in FM_PCD_Init() via FM_MURAM_AllocMem. ++ * These must NOT overlap the global data area. ++ */ ++ ts_size = MAX_EXT_TS_TIMERS * sizeof(uint32_t); ++ ehash_ts_virt = FM_MURAM_AllocMem(h_FmMuram, ++ ts_size, sizeof(uint32_t)); ++ if (ehash_ts_virt == NULL) { ++ printf("fm_ehash: MURAM timestamp alloc failed (%u bytes)\n", ++ ts_size); ++ FM_MURAM_FreeMem(h_FmMuram, ehash_int_muram_ptr); ++ ehash_int_muram_ptr = NULL; ++ return (-1); ++ } ++ IOMemSet32(ehash_ts_virt, 0, ts_size); ++ ehash_ts_phys = XX_VirtToPhys(ehash_ts_virt); ++ ++ printf("fm_ehash: timestamp slots at %p, phys 0x%jx " ++ "(MURAM offset 0x%jx)\n", ++ ehash_ts_virt, (uintmax_t)ehash_ts_phys, ++ (uintmax_t)(ehash_ts_phys - ehash_muram_phys_base)); ++ ++ return (0); ++} ++ ++/* ---------------------------------------------------------------- ++ * CRC64-based hash bucket indexing ++ * ++ * Ported from sdk_fman fm_cc.c:get_indexed_hash_bucket() ++ * ---------------------------------------------------------------- */ ++ ++static void ++get_indexed_hash_bucket(uint8_t key_size, uint8_t *key_ptr, ++ uint8_t crc_shift, uint16_t mask, uint16_t *bucket_index) ++{ ++ uint64_t crc64; ++ ++ crc64 = crc64_init(); ++ crc64 = crc64_compute(key_ptr, key_size, crc64); ++ crc64 >>= ((6 - crc_shift) << 3); ++ *bucket_index = (uint16_t)crc64 & mask; ++} ++ ++/* ---------------------------------------------------------------- ++ * Bucket chain search (NO_CUMULATIVE_ENTRY path) ++ * ---------------------------------------------------------------- */ ++ ++static struct en_exthash_tbl_entry * ++find_entry_in_bucket(struct en_exthash_tbl_entry *entry, ++ uint8_t *key, uint32_t size) ++{ ++ ++ while (entry != NULL) { ++ if (memcmp(key, &entry->hashentry.key[0], size) == 0) ++ return (entry); ++ entry = entry->next; ++ } ++ return (NULL); ++} ++ ++/* ---------------------------------------------------------------- ++ * Cleanup helper ++ * ---------------------------------------------------------------- */ ++ ++static void ++delete_ehash_info(struct en_exthash_info *info) ++{ ++ uint32_t ii; ++ ++ if (info == NULL) ++ return; ++ ++ if (info->pSpinlock != NULL) { ++ for (ii = 0; ii <= info->hashmask; ii++) { ++ if (*(info->pSpinlock + ii) != NULL) ++ XX_FreeSpinlock(*(info->pSpinlock + ii)); ++ else ++ break; ++ } ++ free(info->pSpinlock, M_EHASH); ++ } ++ ++ if (info->table_base != NULL) ++ contigfree(info->table_base, info->tablesize, M_EHASH); ++ ++ /* ++ * Do NOT free h_Ad — it points into the CC tree's MURAM slot ++ * (set by copy_td_to_ccbase). The CC tree owns that MURAM. ++ */ ++ ++ free(info, M_EHASH); ++} ++ ++ ++/* ================================================================ ++ * Public API ++ * ================================================================ */ ++ ++/* ++ * ExternalHashTableSet — Create an enhanced external hash table. ++ * ++ * Called from FM_PCD_HashTableSet (via USE_ENHANCED_EHASH redirect). ++ * Allocates DDR bucket array and per-bucket spinlocks. Builds the ++ * AD node data in info->node but does NOT write it to MURAM. ++ * copy_td_to_ccbase() (called during FM_PCD_CcRootBuild) writes ++ * the AD into the CC tree's MURAM entry and sets info->h_Ad. ++ * ++ * Returns opaque handle on success, NULL on failure. ++ */ ++t_Handle ++ExternalHashTableSet(t_Handle h_FmPcd, t_FmPcdHashTableParams *p_Param) ++{ ++ struct en_exthash_info *info; ++ uint32_t ii; ++ struct en_exthash_node *node; ++ uint64_t tblphysaddr; ++ uint32_t num_bits; ++ ++ if (ehash_init_muram_pool(h_FmPcd) != 0) ++ return (NULL); ++ ++ info = malloc(sizeof(*info), M_EHASH, M_WAITOK | M_ZERO); ++ if (info == NULL) { ++ REPORT_ERROR(MAJOR, E_NO_MEMORY, ++ ("en_exthash_info allocation")); ++ return (NULL); ++ } ++ ++ info->hashmask = p_Param->hashResMask; ++ info->pcd = h_FmPcd; ++ ++ /* ++ * Validate hash mask: must be (2^N - 1) where N <= 15. ++ */ ++ if (info->hashmask > 0x7fff) { ++ REPORT_ERROR(MAJOR, E_INVALID_VALUE, ++ ("unsupported hash mask value")); ++ goto err_ret; ++ } ++ ++ num_bits = 0; ++ for (ii = 0; ii < 15; ii++) { ++ if ((info->hashmask + 1) & (1U << ii)) ++ break; ++ } ++ num_bits = ii; ++ ++ if ((1U << num_bits) != (info->hashmask + 1)) { ++ REPORT_ERROR(MAJOR, E_INVALID_VALUE, ++ ("hash mask not power-of-2 minus 1")); ++ goto err_ret; ++ } ++ ++ /* Allocate per-bucket spinlocks (CPU-only, no DMA) */ ++ info->pSpinlock = malloc( ++ sizeof(t_Handle) * (info->hashmask + 1), ++ M_EHASH, M_WAITOK | M_ZERO); ++ if (info->pSpinlock == NULL) { ++ REPORT_ERROR(MAJOR, E_NO_MEMORY, ("spinlock array")); ++ goto err_ret; ++ } ++ ++ for (ii = 0; ii <= info->hashmask; ii++) { ++ *(info->pSpinlock + ii) = XX_InitSpinlock(); ++ if (*(info->pSpinlock + ii) == NULL) { ++ REPORT_ERROR(MAJOR, E_NO_MEMORY, ++ ("bucket spinlock")); ++ goto err_ret; ++ } ++ } ++ ++ /* ++ * Allocate DDR hash table (bucket array). ++ * Must be physically contiguous — FMan microcode accesses ++ * buckets via table_base_phys + index * sizeof(bucket). ++ * Use contigmalloc directly instead of the shared NCSW ++ * MallocSmart pool, which is sized for dTSEC buffers only. ++ */ ++ info->tablesize = (uint32_t)(sizeof(struct en_exthash_bucket) * ++ (info->hashmask + 1)); ++ info->table_base = contigmalloc(info->tablesize, M_EHASH, ++ M_WAITOK | M_ZERO, 0, (vm_paddr_t)0xFFFFFFFF, ++ EN_EXTHASH_TBL_ALIGNMENT, 0); ++ if (info->table_base == NULL) { ++ REPORT_ERROR(MAJOR, E_NO_MEMORY, ++ ("hash table buckets")); ++ goto err_ret; ++ } ++ ++ /* Save first table base for diagnostic DDR bucket verification */ ++ if (ehash_first_table_base == NULL) ++ ehash_first_table_base = info->table_base; ++ ++ /* Fill table parameters */ ++ info->keysize = p_Param->matchKeySize; ++ info->hashshift = p_Param->hashShift; ++ info->flags |= TIMESTAMP_EN; ++ if (p_Param->statisticsMode) ++ info->flags |= STATS_EN; ++ ++ /* Build AD node in local copy — NOT written to MURAM yet. ++ * copy_td_to_ccbase() writes this into the CC tree MURAM slot. */ ++ node = &info->node; ++ memset(node, 0, sizeof(*node)); ++ ++ tblphysaddr = XX_VirtToPhys(info->table_base); ++ ++ { ++ uint32_t miss_action; ++ uint32_t hw_table_type; ++ ++ /* Convert user-facing table_type enum to hardware constant. ++ * p_Param->table_type is populated by dpa_app via fmlib. */ ++ hw_table_type = ehash_hw_table_type(p_Param->table_type); ++ ++ switch (p_Param->ccNextEngineParamsForMiss.nextEngine) { ++ case e_FM_PCD_KG: { ++ t_FmPcdCcNextKgParams *kgparams = ++ &p_Param->ccNextEngineParamsForMiss.params.kgParams; ++ ++ node->word_2 = NIA_ENG_KG | NIA_KG_DIRECT; ++ if (kgparams->overrideFqid) ++ node->word_2 |= kgparams->newFqid | ++ NIA_KG_CC_EN; ++ node->word_2 |= ++ FmPcdKgGetSchemeId(kgparams->h_DirectScheme); ++ miss_action = EN_EHASH_MISS_ACTION_NIA; ++ break; ++ } ++ case e_FM_PCD_DONE: { ++ t_FmPcdCcNextEnqueueParams *enqparams = ++ &p_Param->ccNextEngineParamsForMiss.params ++ .enqueueParams; ++ ++ if (enqparams->overrideFqid) { ++ node->word_2 = enqparams->newFqid; ++ miss_action = EN_EHASH_MISS_ACTION_ENQUE; ++ } else { ++ miss_action = EN_EHASH_MISS_ACTION_DONE; ++ } ++ break; ++ } ++ default: ++ miss_action = EN_EHASH_MISS_ACTION_DROP; ++ break; ++ } ++ ++ /* Build word_0 — non-EXCLUDE layout matching CDX microcode. ++ * ipv4_ad_offset = 0 (no IPR reassembly support). */ ++ node->word_0 = ++ EHASH_W0_TABLE_BASE_HI((tblphysaddr >> 32) & 0xff) | ++ EHASH_W0_IPV4_AD_OFF(0) | ++ EHASH_W0_HASH_BYTES_OFF(info->hashshift) | ++ EHASH_W0_TABLE_TYPE(hw_table_type) | ++ EHASH_W0_KEY_SIZE(info->keysize) | ++ EHASH_W0_MISS_ACTION(miss_action); ++ node->table_base_lo = tblphysaddr & 0xffffffff; ++ node->word_1 = ++ EHASH_W1_HASH_MASK_BITS(num_bits) | ++ EHASH_W1_GLOBAL_MEM_OFF(EN_INTERNAL_BUFF_POOL_SIZE >> 8) | ++ EHASH_W1_INT_BUF_POOL(ehash_int_muram_area); ++ } ++ ++ /* ++ * No MURAM AD allocation here. info->h_Ad stays NULL until ++ * copy_td_to_ccbase() writes the AD into the CC tree's MURAM ++ * slot during FM_PCD_CcRootBuild. ++ */ ++ info->h_Ad = NULL; ++ info->table_type = p_Param->table_type; ++ ++ /* ++ * Track reassembly tables for ExternalHashSetReasslyPool(). ++ * For REASSM tables, word_2 holds the MURAM offset (>>8) of ++ * ip_reassembly_params. Compute the VA so we can write pool ++ * configuration fields later. ++ */ ++ if (p_Param->table_type == EHASH_IPV4_REASSM_TABLE || ++ p_Param->table_type == EHASH_IPV6_REASSM_TABLE) { ++ t_FmPcd *p_FmPcd = (t_FmPcd *)h_FmPcd; ++ uint64_t reassm_phys; ++ ++ if (node->word_2 != 0) { ++ reassm_phys = p_FmPcd->physicalMuramBase + ++ ((uint64_t)node->word_2 << 8); ++ info->ip_reassem_info = ++ (struct ip_reassembly_params *)XX_PhysToVirt( ++ reassm_phys); ++ printf("fm_ehash: REASSM table type %u, " ++ "ip_reassem_info at %p (MURAM off 0x%x)\n", ++ p_Param->table_type, info->ip_reassem_info, ++ node->word_2 << 8); ++ } ++ ++ if (p_Param->table_type == EHASH_IPV4_REASSM_TABLE) ++ ehash_ipv4_reassly_tbl = info; ++ else ++ ehash_ipv6_reassly_tbl = info; ++ } ++ ++ return ((t_Handle)info); ++ ++err_ret: ++ delete_ehash_info(info); ++ return (NULL); ++} ++ ++/* ++ * copy_td_to_ccbase — Write enhanced hash AD into CC tree MURAM entry. ++ * ++ * Called from FM_PCD_CcRootBuild (USE_ENHANCED_EHASH path) for each ++ * CC tree entry that points to a hash table. Copies the 16-byte AD ++ * from info->node to the CC tree's MURAM slot using big-endian ++ * accessors, and saves the MURAM address to info->h_Ad. ++ * ++ * After this call, FMan reads the CC tree entry and finds CDX enhanced ++ * hash format. ExternalHashTableModifyMissNextEngine can later patch ++ * the miss action via info->h_Ad. ++ * ++ * No IPR reassembly support (void return). ++ */ ++void ++copy_td_to_ccbase(void *handle, t_Handle p_CcTreeTmp) ++{ ++ struct en_exthash_info *info = (struct en_exthash_info *)handle; ++ volatile uint32_t *p = (volatile uint32_t *)p_CcTreeTmp; ++ ++ struct en_exthash_node *ptr = &info->node; ++ ++ /* ++ * Write enhanced hash AD into CC tree MURAM slot. ++ * ++ * Enhanced hash node layout (16 bytes, all BE in MURAM): ++ * p[0] = word_0: flags, miss_action, int_buf_pool, etc. ++ * p[1] = table_base_lo: DDR hash table physical address (low 32) ++ * p[2] = word_1: global_mem_offset, hash_mask, key_size ++ * p[3] = word_2: miss FQID (set to 0 here, patched by ModifyMiss) ++ * ++ * The CDX microcode reads this format for CC lookup. ++ * Standard Result ADs do NOT work — CDX microcode ignores ++ * the standard FQID field and uses KG baseFqid instead ++ * (confirmed build #207: all frames discarded with QMan ++ * Invalid Enqueue State for FQID 65882). ++ */ ++ { ++ uint32_t v0, v1, v2, v3; ++ int retry; ++ ++ for (retry = 0; retry < 4; retry++) { ++ muram_wr32(&p[2], ptr->word_1); /* offset 8 */ ++ muram_wr32(&p[1], ptr->table_base_lo); /* offset 4 */ ++ muram_wr32(&p[3], ptr->word_2); /* offset 12 */ ++ muram_wr32(&p[0], ptr->word_0); /* offset 0 */ ++ muram_barrier(); ++ ++ v0 = muram_rd32(&p[0]); ++ v1 = muram_rd32(&p[1]); ++ v2 = muram_rd32(&p[2]); ++ v3 = muram_rd32(&p[3]); ++ if (v0 == ptr->word_0 && ++ v1 == ptr->table_base_lo && ++ v2 == ptr->word_1 && ++ v3 == ptr->word_2) ++ break; ++ ++ printf("fm_ehash: copy_td VERIFY FAIL attempt %d " ++ "AD=%p [%08x %08x %08x %08x] != " ++ "[%08x %08x %08x %08x]\n", ++ retry + 1, p, v0, v1, v2, v3, ++ ptr->word_0, ptr->table_base_lo, ++ ptr->word_1, ptr->word_2); ++ } ++ } ++ ++ /* Save MURAM address for AD — used by ModifyMissNextEngine later */ ++ info->h_Ad = (void *)p; ++} ++ ++/* ++ * ExternalHashTableAllocEntry — Allocate a new hash table entry. ++ */ ++void * ++ExternalHashTableAllocEntry(void *h_HashTbl) ++{ ++ struct en_exthash_info *info; ++ void *entry; ++ ++ info = (struct en_exthash_info *)h_HashTbl; ++ if (info == NULL) ++ return (NULL); ++ ++ entry = XX_MallocSmart(sizeof(struct en_exthash_tbl_entry), ++ 0, EN_EHASH_ENTRY_ALIGN); ++ if (entry != NULL) ++ memset(entry, 0, sizeof(struct en_exthash_tbl_entry)); ++ else ++ REPORT_ERROR(MAJOR, E_NO_MEMORY, ("hash table entry")); ++ ++ return (entry); ++} ++ ++/* ++ * ExternalHashTableEntryFree — Free a hash table entry. ++ */ ++void ++ExternalHashTableEntryFree(void *entry) ++{ ++ ++ if (entry != NULL) ++ XX_FreeSmart(entry); ++} ++ ++/* ++ * ExternalHashTableAddKey — Add an entry to the hash table. ++ * ++ * Returns the bucket index on success, -1 on failure. ++ */ ++int ++ExternalHashTableAddKey(void *h_HashTbl, uint8_t keySize, void *tbl_entry) ++{ ++ struct en_exthash_info *info; ++ struct en_exthash_tbl_entry *first_entry; ++ struct en_exthash_tbl_entry *new_entry; ++ uint16_t index; ++ struct en_exthash_bucket *bucket; ++ t_Handle *h_Spinlock; ++ uint32_t intFlags; ++ int retval; ++ uint64_t phyaddr; ++ ++ SANITY_CHECK_RETURN_ERROR(h_HashTbl, E_INVALID_HANDLE); ++ SANITY_CHECK_RETURN_ERROR(tbl_entry, E_NULL_POINTER); ++ ++ new_entry = (struct en_exthash_tbl_entry *)tbl_entry; ++ info = (struct en_exthash_info *)h_HashTbl; ++ ++ if (info->table_base == NULL || info->pSpinlock == NULL) { ++ REPORT_ERROR(MAJOR, E_INVALID_HANDLE, ++ ("hash table not initialized (table_base=%p pSpinlock=%p)", ++ info->table_base, info->pSpinlock)); ++ return (-1); ++ } ++ ++ get_indexed_hash_bucket(keySize, &new_entry->hashentry.key[0], ++ info->hashshift, (uint16_t)info->hashmask, &index); ++ ++ bucket = (struct en_exthash_bucket *)info->table_base + index; ++ ++ h_Spinlock = *(info->pSpinlock + index); ++ intFlags = XX_LockIntrSpinlock(h_Spinlock); ++ ++ retval = index; ++ phyaddr = bucket->h; ++ ++ if (phyaddr) { ++ first_entry = XX_PhysToVirt(SwapUint64(phyaddr)); ++ if (find_entry_in_bucket(first_entry, ++ &new_entry->hashentry.key[0], keySize)) { ++ REPORT_ERROR(MAJOR, E_ALREADY_EXISTS, ++ ("hash table entry")); ++ retval = -1; ++ goto func_ret; ++ } ++ first_entry->prev = new_entry; ++ } else { ++ first_entry = NULL; ++ } ++ ++ /* Link new entry at head of bucket chain */ ++ new_entry->next = first_entry; ++ ++ /* Fill hardware next-entry pointer (byte-swapped physical addr) */ ++ phyaddr = SwapUint64(phyaddr); ++ new_entry->hashentry.next_entry_hi = ++ cpu_to_be16((phyaddr >> 32) & 0xffff); ++ new_entry->hashentry.next_entry_lo = ++ cpu_to_be32(phyaddr & 0xffffffff); ++ ++ /* Update bucket head to point to new entry */ ++ phyaddr = XX_VirtToPhys(new_entry); ++ bucket->h = SwapUint64(phyaddr); ++ ++func_ret: ++ XX_UnlockIntrSpinlock(h_Spinlock, intFlags); ++ return (retval); ++} ++ ++/* ++ * ExternalHashTableDeleteKey — Remove an entry from the hash table. ++ * ++ * Returns 0 on success, -1 on failure. ++ */ ++int ++ExternalHashTableDeleteKey(void *h_HashTbl, uint16_t index, void *tbl_entry) ++{ ++ struct en_exthash_info *info; ++ struct en_exthash_bucket *bucket; ++ struct en_exthash_tbl_entry *entry; ++ struct en_exthash_tbl_entry *temp_entry; ++ t_Handle *h_Spinlock; ++ uint32_t intFlags; ++ uint64_t phyaddr; ++ uint64_t update_entry; ++ ++ if (h_HashTbl == NULL || tbl_entry == NULL) ++ return (-1); ++ ++ info = (struct en_exthash_info *)h_HashTbl; ++ ++ if (info->table_base == NULL || info->pSpinlock == NULL) { ++ REPORT_ERROR(MAJOR, E_INVALID_HANDLE, ++ ("hash table not initialized in DeleteKey")); ++ return (-1); ++ } ++ ++ if (index > info->hashmask) { ++ REPORT_ERROR(MAJOR, E_INVALID_VALUE, ++ ("DeleteKey index %u exceeds hashmask %u", ++ (unsigned)index, (unsigned)info->hashmask)); ++ return (-1); ++ } ++ ++ bucket = (struct en_exthash_bucket *)info->table_base + index; ++ entry = (struct en_exthash_tbl_entry *)tbl_entry; ++ ++ h_Spinlock = *(info->pSpinlock + index); ++ intFlags = XX_LockIntrSpinlock(h_Spinlock); ++ ++ /* Mark entry as invalid for microcode */ ++ update_entry = SwapUint64(entry->hashentry.next_entry); ++ SET_INVALID_ENTRY_64BIT(update_entry); ++ entry->hashentry.next_entry = SwapUint64(update_entry); ++ ++ if (entry->prev != NULL) { ++ /* Not at head — unlink from middle/end */ ++ temp_entry = entry->prev; ++ temp_entry->next = entry->next; ++ if (entry->next != NULL) ++ entry->next->prev = temp_entry; ++ /* Update hardware next-entry pointer */ ++ update_entry = entry->hashentry.next_entry & ~0xffffULL; ++ temp_entry->hashentry.next_entry = ++ update_entry | temp_entry->hashentry.flags; ++ } else { ++ /* At head — update bucket pointer */ ++ if (entry->next != NULL) { ++ phyaddr = XX_VirtToPhys(entry->next); ++ bucket->h = SwapUint64(phyaddr); ++ entry->next->prev = NULL; ++ } else { ++ /* Last entry in bucket — clear to zero (empty) */ ++ bucket->h = 0; ++ } ++ } ++ ++ XX_UnlockIntrSpinlock(h_Spinlock, intFlags); ++ ++ if (FmPcdHcSync(info->pcd)) { ++ printf("fm_ehash: FmPcdHcSync failed in DeleteKey\n"); ++ return (-1); ++ } ++ ++ return (0); ++} ++ ++/* ++ * ExternalHashTableEntryGetStatsAndTS — Read entry stats and timestamp. ++ */ ++int ++ExternalHashTableEntryGetStatsAndTS(void *tbl_entry, ++ struct en_tbl_entry_stats *stats) ++{ ++ struct en_exthash_tbl_entry *hash_node; ++ struct en_ehash_entry *entry; ++ uint16_t flags; ++ ++ hash_node = (struct en_exthash_tbl_entry *)tbl_entry; ++ if (hash_node == NULL) ++ return (-1); ++ ++ entry = &hash_node->hashentry; ++ flags = cpu_to_be16(entry->flags); ++ stats->flags = 0; ++ ++ if (GET_TIMESTAMP_ENABLE(flags)) { ++ stats->flags |= TIMESTAMP_VALID; ++ stats->timestamp = cpu_to_be32(entry->timestamp); ++ } ++ ++ if (GET_STATS_ENABLE(flags)) { ++ stats->flags |= STATS_VALID; ++ stats->pkts = be64_to_cpu(entry->packet_count); ++ stats->bytes = be64_to_cpu(entry->packet_bytes); ++ } ++ ++ return (0); ++} ++ ++/* ++ * ExternalHashTableModifyMissNextEngine — Change the miss action. ++ * ++ * Modifies the MURAM AD node directly (via info->h_Ad, set by ++ * copy_td_to_ccbase). ALL 4 words of the AD must be written in ++ * a single batch — partial writes corrupt the unwritten words ++ * (LS1046A MURAM / Normal-NC ARM64 store behavior). ++ * ++ * Uses info->node as the base (unchanged table_base_lo, word_1) ++ * and modifies word_0 (miss action) and word_2 (FQID/NIA). ++ * Also updates info->node so it stays in sync for future calls. ++ */ ++t_Error ++ExternalHashTableModifyMissNextEngine(t_Handle h_HashTbl, ++ t_FmPcdCcNextEngineParams *p_FmPcdCcNextEngineParams) ++{ ++ struct en_exthash_info *info; ++ volatile uint32_t *p; ++ struct en_exthash_node *ptr; ++ ++ info = (struct en_exthash_info *)h_HashTbl; ++ if (info->h_Ad == NULL) { ++ printf("fm_ehash: ModifyMissNextEngine: h_Ad is NULL " ++ "(copy_td_to_ccbase not called?)\n"); ++ return (E_INVALID_STATE); ++ } ++ ++ ptr = &info->node; ++ ++ /* ++ * Enhanced hash AD miss action patching. ++ * ++ * Modify word_0 (miss_action bits [31:30]) and word_2 (FQID/NIA) ++ * while preserving table_base_lo and word_1 (hash table params). ++ * ++ * Build #208: reverted from standard Result AD format which the ++ * CDX microcode cannot interpret (build #207 showed all frames ++ * discarded with QMan Invalid Enqueue State for KG baseFqid). ++ */ ++ { ++ uint32_t fqid = 0; ++ ++ switch (p_FmPcdCcNextEngineParams->nextEngine) { ++ case e_FM_PCD_DONE: { ++ t_FmPcdCcNextEnqueueParams *enqparams = ++ &p_FmPcdCcNextEngineParams->params.enqueueParams; ++ if (enqparams->overrideFqid) ++ fqid = enqparams->newFqid & 0x00FFFFFF; ++ ++ /* Set miss_action to ENQUE, preserve other word_0 fields */ ++ ptr->word_0 = (ptr->word_0 & ~EHASH_W0_MISS_ACTION_MASK) | ++ EHASH_W0_MISS_ACTION(EN_EHASH_MISS_ACTION_ENQUE); ++ ptr->word_2 = fqid; ++ break; ++ } ++ default: ++ printf("fm_ehash: ModifyMiss: unhandled engine %d\n", ++ p_FmPcdCcNextEngineParams->nextEngine); ++ break; ++ } ++ ++ } ++ ++ /* ++ * Write the 16-byte AD to MURAM. ++ * Verify + retry in case of CCI-400/AXI flush timing. ++ */ ++ p = (volatile uint32_t *)info->h_Ad; ++ { ++ uint32_t v0, v1, v2, v3; ++ int retry; ++ ++ for (retry = 0; retry < 4; retry++) { ++ muram_wr32(&p[2], ptr->word_1); /* offset 8 */ ++ muram_wr32(&p[1], ptr->table_base_lo); /* offset 4 */ ++ muram_wr32(&p[3], ptr->word_2); /* offset 12 */ ++ muram_wr32(&p[0], ptr->word_0); /* offset 0 */ ++ muram_barrier(); ++ ++ v0 = muram_rd32(&p[0]); ++ v1 = muram_rd32(&p[1]); ++ v2 = muram_rd32(&p[2]); ++ v3 = muram_rd32(&p[3]); ++ if (v0 == ptr->word_0 && ++ v1 == ptr->table_base_lo && ++ v2 == ptr->word_1 && ++ v3 == ptr->word_2) ++ break; ++ ++ printf("fm_ehash: ModifyMiss AD=%p attempt %d " ++ "VERIFY FAIL [%08x %08x %08x %08x] != " ++ "[%08x %08x %08x %08x]\n", ++ info->h_Ad, retry + 1, ++ v0, v1, v2, v3, ++ ptr->word_0, ptr->table_base_lo, ++ ptr->word_1, ptr->word_2); ++ } ++ } ++ ++ /* ++ * Propagate miss action to CC tree copy entries. ++ * ++ * The CC tree fill logic (fm_cc.c CcRootBuild) copies entry 0 ++ * to unused slots (indices numOfEntries..15) via raw memcpy. ++ * These copies have the pre-ModifyMiss state because ++ * copy_td_to_ccbase only tracks a single h_Ad per hash table. ++ * ++ * Scan all 16 CC tree entries: any entry (other than h_Ad ++ * itself) that is a copy and needs its miss action updated. ++ * ++ * CC tree is 256-byte aligned (FM_PCD_CC_TREE_ADDR_ALIGN). ++ */ ++ { ++ uintptr_t tree_base = ++ (uintptr_t)info->h_Ad & ~(uintptr_t)0xFF; ++ int j; ++ ++ for (j = 0; j < FM_PCD_MAX_NUM_OF_CC_GROUPS; j++) { ++ volatile uint32_t *ep = (volatile uint32_t *) ++ (tree_base + j * FM_PCD_CC_AD_ENTRY_SIZE); ++ if (ep == (volatile uint32_t *)info->h_Ad) ++ continue; /* skip the entry we just wrote */ ++ if (muram_rd32(&ep[1]) == ptr->table_base_lo) { ++ /* Copy with same table — update all 4 words */ ++ muram_wr32(&ep[2], ptr->word_1); ++ muram_wr32(&ep[1], ptr->table_base_lo); ++ muram_wr32(&ep[3], ptr->word_2); ++ muram_wr32(&ep[0], ptr->word_0); ++ muram_barrier(); ++ } ++ } ++ } ++ ++ return (E_OK); ++} ++ ++/* ++ * ExternalHashTableFmPcdHcSync — Flush PCD Host Command channel. ++ */ ++int ++ExternalHashTableFmPcdHcSync(void *h_HashTbl) ++{ ++ struct en_exthash_info *info; ++ ++ info = (struct en_exthash_info *)h_HashTbl; ++ if (FmPcdHcSync(info->pcd)) { ++ printf("fm_ehash: FmPcdHcSync failed\n"); ++ return (-1); ++ } ++ return (0); ++} ++ ++/* ++ * ExternalHashTableDelete — Destroy a table and free all resources. ++ */ ++void ++ExternalHashTableDelete(t_Handle h_HashTbl) ++{ ++ ++ if (h_HashTbl != NULL) ++ delete_ehash_info((struct en_exthash_info *)h_HashTbl); ++} ++ ++/* ++ * ExternalHashTableGetMuramAd — Return MURAM AD pointer for a table. ++ */ ++void * ++ExternalHashTableGetMuramAd(t_Handle h_HashTbl) ++{ ++ struct en_exthash_info *info; ++ ++ info = (struct en_exthash_info *)h_HashTbl; ++ if (info == NULL) ++ return (NULL); ++ return (info->h_Ad); ++} ++ ++/* ================================================================ ++ * Global MURAM features — read/write the global data area at ++ * pool + EN_INTERNAL_BUFF_POOL_SIZE (en_exthash_global_mem). ++ * ++ * All fields are big-endian in MURAM. Use GET_UINT32/WRITE_UINT32 ++ * for 32-bit fields, GET_UINT8/WRITE_UINT8 for byte fields. ++ * ================================================================ */ ++ ++int32_t ++ExternalHashGetSECfailureStats(en_SEC_failure_stats *stats) ++{ ++ volatile en_SEC_failure_stats *src; ++ ++ if (stats == NULL) ++ return (-1); ++ if (ehash_global_mem == NULL) { ++ memset(stats, 0, sizeof(*stats)); ++ return (-1); ++ } ++ ++ src = &ehash_global_mem->SEC_failure_stats; ++ ++ stats->icv_failures = GET_UINT32(src->icv_failures); ++ stats->hw_errs = GET_UINT32(src->hw_errs); ++ stats->CCM_AAD_size_errs = GET_UINT32(src->CCM_AAD_size_errs); ++ stats->anti_replay_late_errs = GET_UINT32(src->anti_replay_late_errs); ++ stats->anti_replay_replay_errs = GET_UINT32(src->anti_replay_replay_errs); ++ stats->seq_num_overflows = GET_UINT32(src->seq_num_overflows); ++ stats->DMA_errs = GET_UINT32(src->DMA_errs); ++ stats->DECO_watchdog_timer_timedout_errs = GET_UINT32(src->DECO_watchdog_timer_timedout_errs); ++ stats->input_frame_read_errs = GET_UINT32(src->input_frame_read_errs); ++ stats->protocol_format_errs = GET_UINT32(src->protocol_format_errs); ++ stats->ipsec_ttl_zero_errs = GET_UINT32(src->ipsec_ttl_zero_errs); ++ stats->ipsec_pad_chk_failures = GET_UINT32(src->ipsec_pad_chk_failures); ++ stats->output_frame_length_rollover_errs = GET_UINT32(src->output_frame_length_rollover_errs); ++ stats->tbl_buff_too_small_errs = GET_UINT32(src->tbl_buff_too_small_errs); ++ stats->tbl_buff_pool_depletion_errs = GET_UINT32(src->tbl_buff_pool_depletion_errs); ++ stats->output_frame_too_large_errs = GET_UINT32(src->output_frame_too_large_errs); ++ stats->cmpnd_frame_write_errs = GET_UINT32(src->cmpnd_frame_write_errs); ++ stats->buff_too_small_errs = GET_UINT32(src->buff_too_small_errs); ++ stats->buff_pool_depletion_errs = GET_UINT32(src->buff_pool_depletion_errs); ++ stats->output_frame_write_errs = GET_UINT32(src->output_frame_write_errs); ++ stats->cmpnd_frame_read_errs = GET_UINT32(src->cmpnd_frame_read_errs); ++ stats->prehdr_read_errs = GET_UINT32(src->prehdr_read_errs); ++ stats->other_errs = GET_UINT32(src->other_errs); ++ ++ return (0); ++} ++ ++int32_t ++ExternalHashResetSECfailureStats(void) ++{ ++ volatile en_SEC_failure_stats *dst; ++ ++ if (ehash_global_mem == NULL) ++ return (-1); ++ ++ dst = &ehash_global_mem->SEC_failure_stats; ++ ++ WRITE_UINT32(dst->icv_failures, 0); ++ WRITE_UINT32(dst->hw_errs, 0); ++ WRITE_UINT32(dst->CCM_AAD_size_errs, 0); ++ WRITE_UINT32(dst->anti_replay_late_errs, 0); ++ WRITE_UINT32(dst->anti_replay_replay_errs, 0); ++ WRITE_UINT32(dst->seq_num_overflows, 0); ++ WRITE_UINT32(dst->DMA_errs, 0); ++ WRITE_UINT32(dst->DECO_watchdog_timer_timedout_errs, 0); ++ WRITE_UINT32(dst->input_frame_read_errs, 0); ++ WRITE_UINT32(dst->protocol_format_errs, 0); ++ WRITE_UINT32(dst->ipsec_ttl_zero_errs, 0); ++ WRITE_UINT32(dst->ipsec_pad_chk_failures, 0); ++ WRITE_UINT32(dst->output_frame_length_rollover_errs, 0); ++ WRITE_UINT32(dst->tbl_buff_too_small_errs, 0); ++ WRITE_UINT32(dst->tbl_buff_pool_depletion_errs, 0); ++ WRITE_UINT32(dst->output_frame_too_large_errs, 0); ++ WRITE_UINT32(dst->cmpnd_frame_write_errs, 0); ++ WRITE_UINT32(dst->buff_too_small_errs, 0); ++ WRITE_UINT32(dst->buff_pool_depletion_errs, 0); ++ WRITE_UINT32(dst->output_frame_write_errs, 0); ++ WRITE_UINT32(dst->cmpnd_frame_read_errs, 0); ++ WRITE_UINT32(dst->prehdr_read_errs, 0); ++ WRITE_UINT32(dst->other_errs, 0); ++ ++ return (0); ++} ++ ++int32_t ++ExternalHashSetDscpVlanpcpMapCfg(en_dscp_vlanpcp_map_cfg *map) ++{ ++ volatile uint8_t *dst; ++ int ii; ++ ++ if (map == NULL) ++ return (-1); ++ if (ehash_global_mem == NULL) ++ return (-1); ++ ++ dst = ehash_global_mem->dscp_vlanpcp_map.dscp_vlanpcp; ++ for (ii = 0; ii <= MAX_VLAN_PCP; ii++) ++ WRITE_UINT8(dst[ii], map->dscp_vlanpcp[ii]); ++ ++ return (0); ++} ++ ++int32_t ++ExternalHashGetDscpVlanpcpMapCfg(en_dscp_vlanpcp_map_cfg *map) ++{ ++ volatile uint8_t *src; ++ int ii; ++ ++ if (map == NULL) ++ return (-1); ++ if (ehash_global_mem == NULL) { ++ memset(map, 0, sizeof(*map)); ++ return (-1); ++ } ++ ++ src = ehash_global_mem->dscp_vlanpcp_map.dscp_vlanpcp; ++ for (ii = 0; ii <= MAX_VLAN_PCP; ii++) ++ map->dscp_vlanpcp[ii] = GET_UINT8(src[ii]); ++ ++ return (0); ++} ++ ++/* ++ * ExternalHashReasslyTableExists — Check if a reassembly table exists. ++ * ++ * Returns 1 if the specified reassembly table (IPv4 or IPv6) was ++ * created during PCD setup, 0 otherwise. Used by the CDX module ++ * to skip resource allocation when reassembly is not configured. ++ */ ++int ++ExternalHashReasslyTableExists(uint32_t type) ++{ ++ struct en_exthash_info *tbl_info; ++ ++ switch (type) { ++ case EHASH_IPV4_REASSM_TABLE: ++ tbl_info = ehash_ipv4_reassly_tbl; ++ break; ++ case EHASH_IPV6_REASSM_TABLE: ++ tbl_info = ehash_ipv6_reassly_tbl; ++ break; ++ default: ++ return (0); ++ } ++ ++ return (tbl_info != NULL && tbl_info->ip_reassem_info != NULL); ++} ++ ++/* ++ * ExternalHashSetReasslyPool — Configure reassembly buffer pools. ++ * ++ * Called from CDX module (cdx_reassm_freebsd.c) to program BMan pool ++ * IDs, buffer sizes, timeout, and TX-confirm FQIDs into the MURAM ++ * ip_reassembly_params structure for IPv4/IPv6 reassembly tables. ++ * ++ * The ip_reassem_info pointer is set during ExternalHashTableSet() ++ * when a REASSM table is created. If no REASSM table exists (e.g. ++ * dpa_app PCD XML doesn't include reassembly), this returns -1. ++ */ ++int ++ExternalHashSetReasslyPool(uint32_t type, uint32_t ctx_bpid, ++ uint32_t ctx_bpsize, uint32_t frag_bpid, uint32_t frag_size, ++ uint32_t txc_fqid, uint32_t ipr_timer_freq) ++{ ++ struct en_exthash_info *tbl_info; ++ volatile struct ip_reassembly_params *params; ++ uint32_t timeout; ++ ++ switch (type) { ++ case EHASH_IPV4_REASSM_TABLE: ++ tbl_info = ehash_ipv4_reassly_tbl; ++ break; ++ case EHASH_IPV6_REASSM_TABLE: ++ tbl_info = ehash_ipv6_reassly_tbl; ++ break; ++ default: ++ printf("fm_ehash: SetReasslyPool: invalid type %u\n", type); ++ return (-1); ++ } ++ ++ if (tbl_info == NULL || tbl_info->ip_reassem_info == NULL) ++ return (-1); ++ ++ params = (volatile struct ip_reassembly_params *)tbl_info->ip_reassem_info; ++ ++ printf("fm_ehash: SetReasslyPool type %u: ctx_bpid=%u frag_bpid=%u " ++ "timer_freq=%u txc_fqid=%u\n", ++ type, ctx_bpid, frag_bpid, ipr_timer_freq, txc_fqid); ++ ++ WRITE_UINT32(params->reassem_bpid, ctx_bpid); ++ WRITE_UINT32(params->reassem_bsize, ctx_bpsize); ++ WRITE_UINT32(params->frag_bpid, frag_bpid); ++ WRITE_UINT32(params->frag_bsize, frag_size); ++ WRITE_UINT32(params->txc_fqid, txc_fqid); ++ ++ /* Convert timeout from absolute to timer-frequency-relative. ++ * The existing timeout_val was set by the PCD configuration ++ * in absolute units; divide by timer frequency. */ ++ if (ipr_timer_freq != 0) { ++ timeout = GET_UINT32(params->timeout_val); ++ WRITE_UINT32(params->timeout_val, timeout / ipr_timer_freq); ++ } ++ ++ return (0); ++} ++ ++void ++ipr_update_timestamp(void) ++{ ++ ++ /* Timestamp updates handled by cdx_ehash_update_timestamp() */ ++} ++ ++/* ++ * cdx_ehash_update_timestamp — Write current time to MURAM timestamp slot. ++ * ++ * Called from the CDX timer thread (via dpa_update_timestamp) on every ++ * tick. FMan microcode reads these slots and copies the raw value into ++ * each hash entry's timestamp field on packet match (MURAM-to-MURAM). ++ * ++ * NO byte-swap: Linux SDK's FM_PCD_UpdateExtTimeStamp does a raw store. ++ * CDX software reads the timestamp back with the same raw access, so ++ * both sides see the same byte pattern. ++ */ ++void ++cdx_ehash_update_timestamp(uint32_t id, uint32_t value) ++{ ++ ++ if (ehash_ts_virt == NULL || id >= MAX_EXT_TS_TIMERS) ++ return; ++ *(volatile uint32_t *)&ehash_ts_virt[id] = value; ++ __asm __volatile("dsb sy" ::: "memory"); ++} ++ ++/* ++ * cdx_ehash_get_timestamp_addr — Return MURAM physical offset for a ++ * timestamp slot. ++ */ ++uint32_t ++cdx_ehash_get_timestamp_addr(uint32_t id) ++{ ++ ++ if (ehash_ts_virt == NULL || id >= MAX_EXT_TS_TIMERS) ++ return (0); ++ return ((uint32_t)(ehash_ts_phys + id * sizeof(uint32_t) - ++ ehash_muram_phys_base)); ++} ++ ++/* ++ * ehash_dump_muram_diag — Dump MURAM state for stall diagnosis. ++ * ++ * Prints global data area, timestamp slots, and first internal ++ * buffer pool slot. Safe to call from callout context. ++ */ ++void ++ehash_dump_muram_diag(void) ++{ ++ uint8_t *global_data; ++ volatile uint32_t *pool32; ++ ++ if (ehash_int_muram_ptr == NULL) { ++ printf("fm_ehash: diag: pool not initialized\n"); ++ return; ++ } ++ ++ /* Global data area: at pool + EN_INTERNAL_BUFF_POOL_SIZE */ ++ global_data = (uint8_t *)ehash_int_muram_ptr + ++ EN_INTERNAL_BUFF_POOL_SIZE; ++ printf("fm_ehash: global_data (dscp_vlanpcp_map): " ++ "%02x %02x %02x %02x %02x %02x %02x %02x\n", ++ global_data[0], global_data[1], global_data[2], global_data[3], ++ global_data[4], global_data[5], global_data[6], global_data[7]); ++ /* SEC failure stats — 23 × uint32_t starting at global_data+8. ++ * CDX microcode writes these in BE (via WRITE_UINT32), so read ++ * with GET_UINT32 for correct byte order. */ ++ { ++ static const char *stat_names[] = { ++ "icv_fail", "hw_err", "ccm_aad", "ar_late", ++ "ar_replay", "seq_ovfl", "dma_err", "deco_wdt", ++ "in_rd_err", "proto_fmt", "ttl_zero", "pad_chk", ++ "out_len_roll", "tbl_buf_small", "tbl_pool_depl", ++ "out_too_large", "cmpnd_wr", "buf_small", ++ "pool_depl", "out_wr", "cmpnd_rd", ++ "prehdr_rd", "other" ++ }; ++ volatile uint32_t *sp = ++ (volatile uint32_t *)(global_data + 8); ++ int si, any = 0; ++ for (si = 0; si < 23; si++) { ++ uint32_t v = GET_UINT32(sp[si]); ++ if (v != 0) { ++ printf("fm_ehash: SEC stat[%d] %s = %u\n", ++ si, stat_names[si], v); ++ any = 1; ++ } ++ } ++ if (!any) ++ printf("fm_ehash: SEC stats: all zero\n"); ++ } ++ ++ /* Timestamp slots (separate allocation) */ ++ if (ehash_ts_virt != NULL) ++ printf("fm_ehash: ts[0..3]: %08x %08x %08x %08x " ++ "(raw, no swap)\n", ++ *(volatile uint32_t *)&ehash_ts_virt[0], ++ *(volatile uint32_t *)&ehash_ts_virt[1], ++ *(volatile uint32_t *)&ehash_ts_virt[2], ++ *(volatile uint32_t *)&ehash_ts_virt[3]); ++ else ++ printf("fm_ehash: ts: not allocated\n"); ++ ++ /* Internal buffer pool — first 4 slots (each 256 bytes). ++ * Read with GET_UINT32 since microcode writes in BE. */ ++ pool32 = (volatile uint32_t *)ehash_int_muram_ptr; ++ { ++ int slot; ++ for (slot = 0; slot < 4; slot++) { ++ int base = slot * 64; /* 256B / 4B per word */ ++ printf("fm_ehash: pool[%d]: %08x %08x %08x %08x\n", ++ slot, ++ GET_UINT32(pool32[base + 0]), ++ GET_UINT32(pool32[base + 1]), ++ GET_UINT32(pool32[base + 2]), ++ GET_UINT32(pool32[base + 3])); ++ } ++ } ++ ++ /* DDR hash table bucket[0] verification */ ++ if (ehash_first_table_base != NULL) { ++ volatile uint64_t *bkt = ++ (volatile uint64_t *)ehash_first_table_base; ++ printf("fm_ehash: DDR bucket[0] (cached): " ++ "%016lx %016lx\n", bkt[0], bkt[1]); ++ /* Writeback + invalidate to force re-read from DDR */ ++ cpu_dcache_wbinv_range((vm_offset_t)ehash_first_table_base, 64); ++ printf("fm_ehash: DDR bucket[0] (after wbinv): " ++ "%016lx %016lx\n", bkt[0], bkt[1]); ++ } ++} ++ ++/* ================================================================ ++ * Debug ++ * ================================================================ */ ++ ++void ++EhashTableWalk(void *h_HashTbl) ++{ ++ struct en_exthash_info *info; ++ struct en_exthash_tbl_entry *entry; ++ struct en_exthash_bucket *bucket; ++ uint32_t ii; ++ uint32_t num_entries = 0; ++ uint32_t max_collisions = 0; ++ ++ info = (struct en_exthash_info *)h_HashTbl; ++ if (info == NULL) ++ return; ++ ++ bucket = (struct en_exthash_bucket *)info->table_base; ++ for (ii = 0; ii <= info->hashmask; ii++) { ++ if (bucket->h != 0) { ++ uint32_t bucket_entries = 0; ++ ++ entry = XX_PhysToVirt(SwapUint64(bucket->h)); ++ while (entry != NULL) { ++ bucket_entries++; ++ entry = entry->next; ++ } ++ num_entries += bucket_entries; ++ if (bucket_entries > max_collisions) ++ max_collisions = bucket_entries; ++ } ++ bucket++; ++ } ++ ++ printf("fm_ehash: table %p — %u entries, max collisions %u, " ++ "%u buckets\n", info, num_entries, max_collisions, ++ info->hashmask + 1); ++} +diff --git a/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_kg.c b/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_kg.c +index f183d2f9ee0..08ffdc821b3 100644 +--- a/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_kg.c ++++ b/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_kg.c +@@ -1035,6 +1035,12 @@ static t_Error BuildSchemeRegs(t_FmPcdKgScheme *p_Scheme, + memset(swDefaults, 0, NUM_OF_SW_DEFAULTS*sizeof(t_FmPcdKgExtractDflt)); + memset(p_SchemeRegs, 0, sizeof(struct fman_kg_scheme_regs)); + ++ /* Default: disable policer profile generation. PLCR and ++ * CC-with-plcrNext cases below overwrite kgse_ppc when PGEN ++ * is actually needed. Without this, kgse_ppc=0 leaves ++ * PP_NO_GEN clear → implicit PGEN with profile 0. */ ++ p_SchemeRegs->kgse_ppc = KG_SCH_PP_NO_GEN; ++ + if (p_SchemeParams->netEnvParams.numOfDistinctionUnits > FM_PCD_MAX_NUM_OF_DISTINCTION_UNITS) + RETURN_ERROR(MAJOR, E_INVALID_VALUE, + ("numOfDistinctionUnits should not exceed %d", FM_PCD_MAX_NUM_OF_DISTINCTION_UNITS)); +@@ -1250,7 +1256,13 @@ static t_Error BuildSchemeRegs(t_FmPcdKgScheme *p_Scheme, + } + p_SchemeRegs->kgse_mode = tmpReg; + +- p_SchemeRegs->kgse_mv = p_Scheme->matchVector; ++ /* SCHEME_ALWAYS_DIRECT (0xFFFFFFFF) means "match all frames" in NCSW ++ * software, but FMan KG hardware interprets the MV register literally: ++ * (classification_vector & kgse_mv) == kgse_mv. With 0xFFFFFFFF, all ++ * 32 classification bits must be set — no frame can ever match. ++ * Write 0 instead: the hardware treats MV=0 as "always match." */ ++ p_SchemeRegs->kgse_mv = (p_Scheme->matchVector == SCHEME_ALWAYS_DIRECT) ++ ? 0 : p_Scheme->matchVector; + + #if (DPAA_VERSION >= 11) + if (p_SchemeParams->overrideStorageProfile) +@@ -1569,6 +1581,17 @@ static t_Error BuildSchemeRegs(t_FmPcdKgScheme *p_Scheme, + generic = FALSE; + } + } ++ /* ++ * CDX/ASK flow offload requires the port ID to always be ++ * present as the first byte of every KG key output. The ++ * PCD XML only adds it to ++ * extractedOrs (for FQID modification), but the CDX hash ++ * table key (union dpa_key) expects portid at byte 0. ++ * Force KG_SCH_KN_PORT_ID into the known-fields set so ++ * the hardware extracts it as known-field ID 0 (bit 31, ++ * highest priority → first in key output). ++ */ ++ knownTmp |= KG_SCH_KN_PORT_ID; + p_SchemeRegs->kgse_ekfc = knownTmp; + + selectTmp = 0; +diff --git a/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_plcr.c b/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_plcr.c +index f23d8b8168b..db687ad8220 100644 +--- a/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_plcr.c ++++ b/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_plcr.c +@@ -158,6 +158,14 @@ static t_Error SetProfileNia(t_FmPcd *p_FmPcd, e_FmPcdEngine nextEngine, u_FmPcd + RETURN_ERROR(MAJOR, E_INVALID_STATE, ("Invalid profile ")); + nia |= NIA_ENG_PLCR | NIA_PLCR_ABSOLUTE | absoluteProfileId; + break; ++ case e_FM_PCD_PRS: ++ /* Post-policer: re-enter PCD pipeline via KG engine */ ++ nia |= 0x00480200; ++ break; ++ case e_FM_PCD_CC: ++ /* Post-policer: coarse classifier engine */ ++ nia |= 0x26; ++ break; + default: + RETURN_ERROR(MAJOR, E_INVALID_SELECTION, NO_MSG); + } +diff --git a/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_replic.c b/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_replic.c +index ee82f73014b..7cfadba5c09 100644 +--- a/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_replic.c ++++ b/sys/contrib/ncsw/Peripherals/FM/Pcd/fm_replic.c +@@ -144,7 +144,7 @@ static t_FmPcdFrmReplicMember *GetAvailableMember(t_FmPcdFrmReplicGroup *p_Repli + + if (!LIST_IsEmpty(&p_ReplicGroup->availableMembersList)) + { +- p_Next = LIST_FIRST(&p_ReplicGroup->availableMembersList); ++ p_Next = NCSW_LIST_FIRST(&p_ReplicGroup->availableMembersList); + p_ReplicMember = LIST_OBJECT(p_Next, t_FmPcdFrmReplicMember, node); + ASSERT_COND(p_ReplicMember); + LIST_DelAndInit(p_Next); +diff --git a/sys/contrib/ncsw/Peripherals/FM/Port/fm_port.c b/sys/contrib/ncsw/Peripherals/FM/Port/fm_port.c +index 79419eab453..6faf7fa6b4c 100644 +--- a/sys/contrib/ncsw/Peripherals/FM/Port/fm_port.c ++++ b/sys/contrib/ncsw/Peripherals/FM/Port/fm_port.c +@@ -36,6 +36,9 @@ + + @Description FM driver routines implementation. + *//***************************************************************************/ ++#ifdef __FreeBSD__ ++#endif ++ + #include "error_ext.h" + #include "std_ext.h" + #include "string_ext.h" +@@ -5271,6 +5274,7 @@ t_Error FM_PORT_SetPCD(t_Handle h_FmPort, t_FmPortPcdParams *p_PcdParam) + RETURN_ERROR(MAJOR, err, NO_MSG); + } + ++ /* Diagnostic: dump all BMI NIA registers after SetPCD */ + RELEASE_LOCK(p_FmPort->lock); + + return err; +diff --git a/sys/contrib/ncsw/Peripherals/FM/fm_ncsw.c b/sys/contrib/ncsw/Peripherals/FM/fm_ncsw.c +index 884bc45edd3..0bc43c79bcf 100644 +--- a/sys/contrib/ncsw/Peripherals/FM/fm_ncsw.c ++++ b/sys/contrib/ncsw/Peripherals/FM/fm_ncsw.c +@@ -88,8 +88,11 @@ static bool IsFmanCtrlCodeLoaded(t_Fm *p_Fm) + + static t_Error CheckFmParameters(t_Fm *p_Fm) + { ++#ifndef __aarch64__ ++ /* On ARM64, U-Boot preloads FMan microcode into IRAM; reuse it */ + if (IsFmanCtrlCodeLoaded(p_Fm) && !p_Fm->resetOnInit) + RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("Old FMan CTRL code is loaded; FM must be reset!")); ++#endif + #if (DPAA_VERSION < 11) + if (!p_Fm->p_FmDriverParam->dma_axi_dbg_num_of_beats || + (p_Fm->p_FmDriverParam->dma_axi_dbg_num_of_beats > DMA_MODE_MAX_AXI_DBG_NUM_OF_BEATS)) +@@ -3434,7 +3437,7 @@ t_Handle FM_Config(t_FmParams *p_FmParam) + + #ifdef FM_AID_MODE_NO_TNUM_SW005 + if (p_Fm->p_FmStateStruct->revInfo.majorRev >= 6) +- p_Fm->p_FmDriverParam->dma_aid_mode = e_FM_DMA_AID_OUT_PORT_ID; ++ p_Fm->p_FmDriverParam->dma_aid_mode = E_FMAN_DMA_AID_OUT_PORT_ID; + #endif /* FM_AID_MODE_NO_TNUM_SW005 */ + #ifndef FM_QMI_NO_DEQ_OPTIONS_SUPPORT + if (p_Fm->p_FmStateStruct->revInfo.majorRev != 4) +@@ -3568,12 +3571,15 @@ t_Error FM_Init(t_Handle h_Fm) + if (!p_Fm->resetOnInit) /* Skip operations done in errata workaround */ + { + #endif /* FM_UCODE_NOT_RESET_ERRATA_BUGZILLA6173 */ +- /* Load FMan-Controller code to IRAM */ +- +- ClearIRam(p_Fm); ++ /* Load FMan-Controller code to IRAM (skip if no firmware provided, ++ e.g. when U-Boot has already loaded microcode) */ ++ if (p_Fm->firmware.p_Code) ++ { ++ ClearIRam(p_Fm); + +- if (p_Fm->firmware.p_Code && (LoadFmanCtrlCode(p_Fm) != E_OK)) +- RETURN_ERROR(MAJOR, E_INVALID_STATE, NO_MSG); ++ if (LoadFmanCtrlCode(p_Fm) != E_OK) ++ RETURN_ERROR(MAJOR, E_INVALID_STATE, NO_MSG); ++ } + #ifdef FM_UCODE_NOT_RESET_ERRATA_BUGZILLA6173 + } + #endif /* FM_UCODE_NOT_RESET_ERRATA_BUGZILLA6173 */ +@@ -4825,6 +4831,86 @@ uint32_t FM_GetCounter(t_Handle h_Fm, e_FmCounters counter) + return fman_get_counter(&fman_rg, fsl_counter); + } + ++#ifdef __aarch64__ ++void FM_ErrorDiag(t_Handle h_Fm, uint8_t hwPortId) ++{ ++ t_Fm *p = (t_Fm *)h_Fm; ++ uint32_t ps, epi, cld, npi, gs, ts, eie, dmsr, ievr; ++ uint32_t dmtah, dmtal; ++ ++ /* FPM: port stall status + error pending */ ++ ps = ioread32be(&p->p_FmFpmRegs->fmfp_ps[hwPortId]); ++ epi = ioread32be(&p->p_FmFpmRegs->fm_epi); ++ cld = ioread32be(&p->p_FmFpmRegs->fm_cld); ++ npi = ioread32be(&p->p_FmFpmRegs->fm_npi); ++ ++ /* QMI: global status + task status + error */ ++ gs = ioread32be(&p->p_FmQmiRegs->fmqm_gs); ++ ts = ioread32be(&p->p_FmQmiRegs->fmqm_ts); ++ eie = ioread32be(&p->p_FmQmiRegs->fmqm_eie); ++ ++ /* DMA: status + last transfer address */ ++ dmsr = ioread32be(&p->p_FmDmaRegs->fmdmsr); ++ dmtah = ioread32be(&p->p_FmDmaRegs->fmdmtah); ++ dmtal = ioread32be(&p->p_FmDmaRegs->fmdmtal); ++ ++ /* BMI: interrupt event */ ++ ievr = ioread32be(&p->p_FmBmiRegs->fmbm_ievr); ++ ++ printf("fman: FPM port[%u] ps=0x%08x %s\n", ++ hwPortId, ps, (ps & 0x00800000) ? "STALLED" : "ok"); ++ printf("fman: FPM epi=0x%08x npi=0x%08x cld=0x%08x\n", epi, npi, cld); ++ printf("fman: QMI gs=0x%08x ts=0x%08x eie=0x%08x\n", gs, ts, eie); ++ printf("fman: DMA sr=0x%08x addr=0x%08x%08x\n", dmsr, dmtah, dmtal); ++ printf("fman: BMI ievr=0x%08x\n", ievr); ++} ++ ++void FM_TaskStatusDiag(t_Handle h_Fm, uint8_t hwPortId) ++{ ++ t_Fm *p = (t_Fm *)h_Fm; ++ uint32_t pp, ts; ++ int t, port_tasks = 0, total_active = 0; ++ uint8_t port_count[256]; ++ int i, dumped = 0; ++ ++ if (hwPortId == 0 || hwPortId > 63) ++ return; ++ ++ memset(port_count, 0, sizeof(port_count)); ++ ++ /* Read configured tasks from BMI Port Parameters */ ++ pp = ioread32be(&p->p_FmBmiRegs->fmbm_pp[hwPortId - 1]); ++ printf("fman: BMI pp[%u]=0x%08x (tasks=%u, extra=%u)\n", ++ hwPortId, pp, ++ ((pp >> 24) & 0x3f) + 1, ++ (pp >> 16) & 0xf); ++ ++ /* Scan FPM task status registers — dump first 8 non-zero raw values */ ++ for (t = 0; t < 128; t++) { ++ ts = ioread32be(&p->p_FmFpmRegs->fmfp_ts[t]); ++ if (ts != 0) { ++ uint8_t owner = (ts >> 24) & 0xff; ++ total_active++; ++ port_count[owner]++; ++ if (owner == hwPortId) ++ port_tasks++; ++ if (dumped < 8) { ++ printf("fman: ts[%d]=0x%08x (owner=%u)\n", t, ts, owner); ++ dumped++; ++ } ++ } ++ } ++ ++ /* Print per-port task breakdown for all ports with active tasks */ ++ printf("fman: task breakdown:"); ++ for (i = 0; i < 256; i++) { ++ if (port_count[i] > 0) ++ printf(" port%d=%d", i, port_count[i]); ++ } ++ printf(" (total=%d, port%u=%d)\n", total_active, hwPortId, port_tasks); ++} ++#endif ++ + t_Error FM_ModifyCounter(t_Handle h_Fm, e_FmCounters counter, uint32_t val) + { + t_Fm *p_Fm = (t_Fm*)h_Fm; +diff --git a/sys/contrib/ncsw/Peripherals/FM/inc/fm_common.h b/sys/contrib/ncsw/Peripherals/FM/inc/fm_common.h +index 81a25e976b6..354e7277389 100644 +--- a/sys/contrib/ncsw/Peripherals/FM/inc/fm_common.h ++++ b/sys/contrib/ncsw/Peripherals/FM/inc/fm_common.h +@@ -52,7 +52,8 @@ + + #define IP_OFFLOAD_PACKAGE_NUMBER 106 + #define CAPWAP_OFFLOAD_PACKAGE_NUMBER 108 +-#define IS_OFFLOAD_PACKAGE(num) ((num == IP_OFFLOAD_PACKAGE_NUMBER) || (num == CAPWAP_OFFLOAD_PACKAGE_NUMBER)) ++#define ASK_UCODE_PACKAGE_NUMBER 209 ++#define IS_OFFLOAD_PACKAGE(num) ((num == IP_OFFLOAD_PACKAGE_NUMBER) || (num == CAPWAP_OFFLOAD_PACKAGE_NUMBER) || (num >= ASK_UCODE_PACKAGE_NUMBER)) + + + +@@ -189,7 +190,13 @@ typedef _Packed struct t_FmPcdCtrlParamsPage { + volatile uint32_t discardMask; + volatile uint8_t reserved3[4]; + volatile uint32_t postBmiFetchNia; ++#if (DPAA_VERSION >= 11) ++ volatile uint32_t internalFEBufferManagementIndexAddr; ++ volatile uint32_t internalFEBufferDepletionCounter; ++ volatile uint8_t reserved4[164]; ++#else + volatile uint8_t reserved4[172]; ++#endif + } _PackedType t_FmPcdCtrlParamsPage; + + +diff --git a/sys/contrib/ncsw/Peripherals/QM/qm.c b/sys/contrib/ncsw/Peripherals/QM/qm.c +index ed3049f0a31..dbe25ccb364 100644 +--- a/sys/contrib/ncsw/Peripherals/QM/qm.c ++++ b/sys/contrib/ncsw/Peripherals/QM/qm.c +@@ -295,9 +295,9 @@ static uint32_t ReserveFqids(t_Qm *p_Qm, uint32_t size, uint32_t alignment, bool + + static void FreeInitResources(t_Qm *p_Qm) + { +- if (p_Qm->p_FqdBase) ++ if (p_Qm->p_FqdBase && !p_Qm->fqdExternal) + XX_FreeSmart(p_Qm->p_FqdBase); +- if (p_Qm->p_PfdrBase) ++ if (p_Qm->p_PfdrBase && !p_Qm->pfdrExternal) + XX_FreeSmart(p_Qm->p_PfdrBase); + if (p_Qm->h_Session) + XX_IpcFreeSession(p_Qm->h_Session); +@@ -705,6 +705,10 @@ t_Handle QM_Config(t_QmParam *p_QmParam) + p_Qm->p_QmDriverParams->pfdrThreshold = DEFAULT_pfdrThreshold; + p_Qm->p_QmDriverParams->sfdrThreshold = DEFAULT_sfdrThreshold; + p_Qm->p_QmDriverParams->pfdrBaseConstant = DEFAULT_pfdrBaseConstant; ++ p_Qm->p_QmDriverParams->p_FqdBaseExt = p_QmParam->p_FqdBase; ++ p_Qm->p_QmDriverParams->fqdSizeExt = p_QmParam->fqdSize; ++ p_Qm->p_QmDriverParams->p_PfdrBaseExt = p_QmParam->p_PfdrBase; ++ p_Qm->p_QmDriverParams->pfdrSizeExt = p_QmParam->pfdrSize; + for(i= 0;ip_QmDriverParams->dcPortalsParams[i].sendToSw = + (bool)((i < e_DPAA_DCPORTAL2) ? FALSE : TRUE); +@@ -774,19 +778,32 @@ t_Error QM_Init(t_Handle h_Qm) + WRITE_UINT32(p_Qm->p_QmRegs->liodnr, (uint16_t)p_QmDriverParams->liodn); + + /* FQD memory */ +- dsSize = (uint32_t)(p_QmDriverParams->totalNumOfFqids * FQD_ENTRY_SIZE); +- LOG2(dsSize, exp); +- if (!POWER_OF_2(dsSize)) (exp++); +- dsSize = (uint32_t)(1 << exp); +- if (dsSize < (4*KILOBYTE)) ++ if (p_QmDriverParams->p_FqdBaseExt) + { +- dsSize = (4*KILOBYTE); ++ /* Use pre-allocated FQD memory from caller (e.g. DT reserved-memory) */ ++ p_Qm->p_FqdBase = p_QmDriverParams->p_FqdBaseExt; ++ p_Qm->fqdExternal = TRUE; ++ dsSize = p_QmDriverParams->fqdSizeExt; + LOG2(dsSize, exp); ++ if (!POWER_OF_2(dsSize)) (exp++); ++ dsSize = (uint32_t)(1 << exp); + } +- p_Qm->p_FqdBase = XX_MallocSmart(dsSize, (int)p_QmDriverParams->fqdMemPartitionId, dsSize); +- if (!p_Qm->p_FqdBase) ++ else + { +- RETURN_ERROR(MAJOR, E_NO_MEMORY, ("FQD obj!!!")); ++ dsSize = (uint32_t)(p_QmDriverParams->totalNumOfFqids * FQD_ENTRY_SIZE); ++ LOG2(dsSize, exp); ++ if (!POWER_OF_2(dsSize)) (exp++); ++ dsSize = (uint32_t)(1 << exp); ++ if (dsSize < (4*KILOBYTE)) ++ { ++ dsSize = (4*KILOBYTE); ++ LOG2(dsSize, exp); ++ } ++ p_Qm->p_FqdBase = XX_MallocSmart(dsSize, (int)p_QmDriverParams->fqdMemPartitionId, dsSize); ++ if (!p_Qm->p_FqdBase) ++ { ++ RETURN_ERROR(MAJOR, E_NO_MEMORY, ("FQD obj!!!")); ++ } + } + memset(p_Qm->p_FqdBase, 0, dsSize); + mb(); +@@ -799,29 +816,67 @@ t_Error QM_Init(t_Handle h_Qm) + WRITE_UINT32(p_Qm->p_QmRegs->fqd_bar, (uint32_t)phyAddr); + WRITE_UINT32(p_Qm->p_QmRegs->fqd_ar, AR_ENABLE | (exp - 1)); + ++ /* Readback and verify FQD BAR programming */ ++ { ++ uint32_t rb_bare = GET_UINT32(p_Qm->p_QmRegs->fqd_bare); ++ uint32_t rb_bar = GET_UINT32(p_Qm->p_QmRegs->fqd_bar); ++ uint32_t rb_ar = GET_UINT32(p_Qm->p_QmRegs->fqd_ar); ++ XX_Print("QM FQD: va=%p phys=0x%08x%08x bare=0x%08x bar=0x%08x ar=0x%08x (exp=%d, size=0x%x)\n", ++ p_Qm->p_FqdBase, ++ (uint32_t)(phyAddr >> 32), (uint32_t)phyAddr, ++ rb_bare, rb_bar, rb_ar, exp, dsSize); ++ } ++ + /* PFDR memory */ +- dsSize = (uint32_t)(p_QmDriverParams->rtFramesDepth * (PFDR_ENTRY_SIZE/3)); +- LOG2(dsSize, exp); +- if (!POWER_OF_2(dsSize)) (exp++); +- dsSize = (uint32_t)(1 << exp); +- if (dsSize < (4*KILOBYTE)) ++ if (p_QmDriverParams->p_PfdrBaseExt) + { +- dsSize = (4*KILOBYTE); ++ /* Use pre-allocated PFDR memory from caller */ ++ p_Qm->p_PfdrBase = p_QmDriverParams->p_PfdrBaseExt; ++ p_Qm->pfdrExternal = TRUE; ++ dsSize = p_QmDriverParams->pfdrSizeExt; + LOG2(dsSize, exp); ++ if (!POWER_OF_2(dsSize)) (exp++); ++ dsSize = (uint32_t)(1 << exp); ++ } ++ else ++ { ++ dsSize = (uint32_t)(p_QmDriverParams->rtFramesDepth * (PFDR_ENTRY_SIZE/3)); ++ LOG2(dsSize, exp); ++ if (!POWER_OF_2(dsSize)) (exp++); ++ dsSize = (uint32_t)(1 << exp); ++ if (dsSize < (4*KILOBYTE)) ++ { ++ dsSize = (4*KILOBYTE); ++ LOG2(dsSize, exp); ++ } ++ p_Qm->p_PfdrBase = XX_MallocSmart(dsSize, (int)p_QmDriverParams->pfdrMemPartitionId, dsSize); ++ if (!p_Qm->p_PfdrBase) ++ RETURN_ERROR(MAJOR, E_NO_MEMORY, ("PFDR obj!!!")); + } +- +- p_Qm->p_PfdrBase = XX_MallocSmart(dsSize, (int)p_QmDriverParams->pfdrMemPartitionId, dsSize); +- if (!p_Qm->p_PfdrBase) +- RETURN_ERROR(MAJOR, E_NO_MEMORY, ("PFDR obj!!!")); + + phyAddr = XX_VirtToPhys(p_Qm->p_PfdrBase); + WRITE_UINT32(p_Qm->p_QmRegs->pfdr_bare, ((uint32_t)(phyAddr >> 32) & 0x000000ff)); + WRITE_UINT32(p_Qm->p_QmRegs->pfdr_bar, (uint32_t)phyAddr); + WRITE_UINT32(p_Qm->p_QmRegs->pfdr_ar, AR_ENABLE | (exp - 1)); + ++ /* Readback and verify PFDR BAR programming */ ++ { ++ uint32_t rb_bare = GET_UINT32(p_Qm->p_QmRegs->pfdr_bare); ++ uint32_t rb_bar = GET_UINT32(p_Qm->p_QmRegs->pfdr_bar); ++ uint32_t rb_ar = GET_UINT32(p_Qm->p_QmRegs->pfdr_ar); ++ XX_Print("QM PFDR: va=%p phys=0x%08x%08x bare=0x%08x bar=0x%08x ar=0x%08x (exp=%d, size=0x%x)\n", ++ p_Qm->p_PfdrBase, ++ (uint32_t)(phyAddr >> 32), (uint32_t)phyAddr, ++ rb_bare, rb_bar, rb_ar, exp, dsSize); ++ XX_Print("QM PFDR init: pfdr_start=8, num=%d\n", dsSize / 64 - 8); ++ } ++ + if (QmInitPfdr(p_Qm, 8, dsSize / 64 - 8) != E_OK) + RETURN_ERROR(MAJOR, E_INVALID_STATE, ("PFDR init failed!!!")); + ++ XX_Print("QM PFDR init: SUCCESS, pfdr_fpc=%d\n", ++ GET_UINT32(p_Qm->p_QmRegs->pfdr_fpc)); ++ + /* thresholds */ + WRITE_UINT32(p_Qm->p_QmRegs->pfdr_fp_lwit, (p_Qm->p_QmDriverParams->pfdrThreshold & 0xffffff)); + WRITE_UINT32(p_Qm->p_QmRegs->pfdr_cfg, p_Qm->p_QmDriverParams->pfdrBaseConstant); +@@ -1037,6 +1092,27 @@ uint32_t QM_GetCounter(t_Handle h_Qm, e_QmCounters counter) + return 0; + } + ++#ifdef __aarch64__ ++void QM_ErrorDiag(t_Handle h_Qm, uint32_t *err_isr, uint32_t *ecsr, ++ uint32_t *ecir, uint32_t *pfdr_fpc, uint32_t *sfdr_in_use, ++ uint32_t *idle_stat, uint32_t *dcp0_cfg, uint32_t *dcp0_dlm_avg, ++ uint32_t *dcp_dd_ihrsr, uint32_t *dcp_dd_hasr) ++{ ++ t_Qm *p_Qm = (t_Qm *)h_Qm; ++ ++ *err_isr = GET_UINT32(p_Qm->p_QmRegs->err_isr); ++ *ecsr = GET_UINT32(p_Qm->p_QmRegs->ecsr); ++ *ecir = GET_UINT32(p_Qm->p_QmRegs->ecir); ++ *pfdr_fpc = GET_UINT32(p_Qm->p_QmRegs->pfdr_fpc); ++ *sfdr_in_use = GET_UINT32(p_Qm->p_QmRegs->sfdr_in_use); ++ *idle_stat = GET_UINT32(p_Qm->p_QmRegs->idle_stat); ++ *dcp0_cfg = GET_UINT32(p_Qm->p_QmRegs->dcpConfRegs[0].cfg); ++ *dcp0_dlm_avg = GET_UINT32(p_Qm->p_QmRegs->dcpConfRegs[0].dlm_avg); ++ *dcp_dd_ihrsr = GET_UINT32(p_Qm->p_QmRegs->dcp_dd_ihrsr); ++ *dcp_dd_hasr = GET_UINT32(p_Qm->p_QmRegs->dcp_dd_hasr); ++} ++#endif ++ + void QM_ErrorIsr(t_Handle h_Qm) + { + t_Qm *p_Qm = (t_Qm *)h_Qm; +diff --git a/sys/contrib/ncsw/Peripherals/QM/qm.h b/sys/contrib/ncsw/Peripherals/QM/qm.h +index a004dc55a67..a18ada7c719 100644 +--- a/sys/contrib/ncsw/Peripherals/QM/qm.h ++++ b/sys/contrib/ncsw/Peripherals/QM/qm.h +@@ -373,7 +373,11 @@ typedef _Packed struct + #define QM_CGR_TARGET_DCP(portlaId) (QM_CGR_TARG_FIRST_DCPORTAL >> portlaId) + + +-#define QM_DCP_CFG_ED 0x00000100 ++#ifdef __aarch64__ ++#define QM_DCP_CFG_ED 0x00001000 /* QMan v3 (LS1046A) */ ++#else ++#define QM_DCP_CFG_ED 0x00000100 /* QMan v1/v2 (P5020) */ ++#endif + /* + #define CGR_VALID 0x80 + #define CGR_VERB_INIT 0x50 +@@ -467,6 +471,10 @@ typedef struct { + uint32_t pfdrBaseConstant; + uint16_t liodn; + t_QmDcPortalParams dcPortalsParams[DPAA_MAX_NUM_OF_DC_PORTALS]; ++ void *p_FqdBaseExt; /* Pre-allocated FQD, or NULL */ ++ uint32_t fqdSizeExt; ++ void *p_PfdrBaseExt; /* Pre-allocated PFDR, or NULL */ ++ uint32_t pfdrSizeExt; + } t_QmDriverParams; + + typedef struct { +@@ -479,6 +487,8 @@ typedef struct { + t_QmRegs *p_QmRegs; + uint32_t *p_FqdBase; + uint32_t *p_PfdrBase; ++ bool fqdExternal; /* FQD memory externally allocated */ ++ bool pfdrExternal; /* PFDR memory externally allocated */ + uint32_t exceptions; + t_QmExceptionsCallback *f_Exception; + t_Handle h_App; +diff --git a/sys/contrib/ncsw/Peripherals/QM/qm_portal_fqr.c b/sys/contrib/ncsw/Peripherals/QM/qm_portal_fqr.c +index 31313d37f97..11456d2d9dc 100644 +--- a/sys/contrib/ncsw/Peripherals/QM/qm_portal_fqr.c ++++ b/sys/contrib/ncsw/Peripherals/QM/qm_portal_fqr.c +@@ -1,6 +1,6 @@ + /****************************************************************************** + +- © 1995-2003, 2004, 2005-2011 Freescale Semiconductor, Inc. ++ � 1995-2003, 2004, 2005-2011 Freescale Semiconductor, Inc. + All rights reserved. + + This is proprietary source code of Freescale Semiconductor Inc., +@@ -64,22 +64,44 @@ + * call. Take advantage of this fact to shove a 64-bit kernel pointer into a + * 32-bit context integer, and back. + * +- * XXX: This depends on the fact that VM_MAX_KERNEL_ADDRESS is less than 38-bit +- * count from VM_MIN_KERNEL_ADDRESS. If this ever changes, this needs to be +- * updated. ++ * On ARM64, XX_MallocSmart allocates from contigmalloc which returns kernel ++ * VA addresses (0xffff0000...), NOT DMAP addresses. We encode kernel-VA- ++ * relative offsets (shifted by 7 for 128-byte alignment) into the 32-bit ++ * contextB field. Max encodable range: 512GB from VM_MIN_KERNEL_ADDRESS. ++ * contigmalloc returns page-aligned (4096-byte) memory, so 128-byte ++ * alignment is always satisfied. ++ * ++ * On PowerPC, shift by 3 (8-byte alignment) relative to VM_MIN_KERNEL_ADDRESS. + */ ++#if defined(__aarch64__) ++CTASSERT((VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS) <= (1ULL << (32 + 7))); ++#define QMAN_CTX_SHIFT 7 ++#define QMAN_CTX_BASE VM_MIN_KERNEL_ADDRESS ++#else + CTASSERT((VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS) < (1ULL << 35)); ++#define QMAN_CTX_SHIFT 3 ++#define QMAN_CTX_BASE VM_MIN_KERNEL_ADDRESS ++#endif + static inline uint32_t + aligned_int_from_ptr(const void *p) + { + uintptr_t ctx; ++ uint32_t result; + + ctx = (uintptr_t)p; +- KASSERT(ctx >= VM_MIN_KERNEL_ADDRESS, ("%p is too low!\n", p)); +- ctx -= VM_MIN_KERNEL_ADDRESS; +- KASSERT((ctx & 0x07) == 0, ("Pointer %p is not 8-byte aligned!\n", p)); +- +- return (ctx >> 3); ++ KASSERT(ctx >= QMAN_CTX_BASE, ++ ("%s: %p is below base %#lx\n", __func__, p, ++ (unsigned long)QMAN_CTX_BASE)); ++ ctx -= QMAN_CTX_BASE; ++ KASSERT((ctx & ((1 << QMAN_CTX_SHIFT) - 1)) == 0, ++ ("Pointer %p is not %d-byte aligned!\n", p, 1 << QMAN_CTX_SHIFT)); ++ ++ result = (ctx >> QMAN_CTX_SHIFT); ++ KASSERT((uintptr_t)result == (ctx >> QMAN_CTX_SHIFT), ++ ("%s: %p overflows 32-bit context (shifted %#lx)\n", ++ __func__, p, (unsigned long)(ctx >> QMAN_CTX_SHIFT))); ++ ++ return (result); + } + + static inline void * +@@ -88,11 +110,59 @@ ptr_from_aligned_int(uint32_t ctx) + uintptr_t p; + + p = ctx; +- p = VM_MIN_KERNEL_ADDRESS + (p << 3); ++ p = QMAN_CTX_BASE + (p << QMAN_CTX_SHIFT); + + return ((void *)p); + } + ++/* ++ * Copy a frame descriptor from CE portal memory (big-endian) to a native ++ * t_DpaaFD struct with proper byte-swapping. On big-endian (PowerPC), ++ * GET_UINT32 is a plain load so this is equivalent to a raw copy. ++ * ++ * On LE (ARM64), t_DpaaFD swaps the word order of the first 8 bytes: ++ * HW (BE): [liodn,bpid,elion,addrh][addrl_BE] ++ * t_DpaaFD LE: [addrl_LE][addrh,elion,bpid,liodn] ++ * So we swap word positions AND byte-swap each word (equivalent to bswap64). ++ */ ++static inline void ++qm_fd_read(t_DpaaFD *dst, const volatile struct qm_fd *src) ++{ ++ const volatile uint32_t *s = (const volatile uint32_t *)src; ++ uint32_t *d = (uint32_t *)dst; ++ ++#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ ++ d[0] = s[0]; ++ d[1] = s[1]; ++#else ++ d[0] = GET_UINT32(s[1]); ++ d[1] = GET_UINT32(s[0]); ++#endif ++ d[2] = GET_UINT32(s[2]); ++ d[3] = GET_UINT32(s[3]); ++} ++ ++/* ++ * Copy a native t_DpaaFD to CE portal memory (big-endian) with proper ++ * byte-swapping. Reverse of qm_fd_read(). ++ */ ++static inline void ++qm_fd_write(volatile struct qm_fd *dst, const t_DpaaFD *src) ++{ ++ volatile uint32_t *d = (volatile uint32_t *)dst; ++ const uint32_t *s = (const uint32_t *)src; ++ ++#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ ++ d[0] = s[0]; ++ d[1] = s[1]; ++#else ++ WRITE_UINT32(d[0], s[1]); ++ WRITE_UINT32(d[1], s[0]); ++#endif ++ WRITE_UINT32(d[2], s[2]); ++ WRITE_UINT32(d[3], s[3]); ++} ++ + static t_Error qman_volatile_dequeue(t_QmPortal *p_QmPortal, + struct qman_fq *p_Fq, + uint32_t vdqcr) +@@ -152,7 +222,7 @@ static t_Error qman_create_fq(t_QmPortal *p_QmPortal, + /* Everything else is RECOVER support */ + NCSW_PLOCK(p_QmPortal); + p_Mcc = qm_mc_start(p_QmPortal->p_LowQmPortal); +- p_Mcc->queryfq.fqid = fqid; ++ WRITE_UINT32(p_Mcc->queryfq.fqid, fqid); + qm_mc_commit(p_QmPortal->p_LowQmPortal, QM_MCC_VERB_QUERYFQ); + while (!(p_Mcr = qm_mc_result(p_QmPortal->p_LowQmPortal))) ; + ASSERT_COND((p_Mcr->verb & QM_MCR_VERB_MASK) == QM_MCC_VERB_QUERYFQ); +@@ -162,7 +232,7 @@ static t_Error qman_create_fq(t_QmPortal *p_QmPortal, + } + fqd = p_Mcr->queryfq.fqd; + p_Mcc = qm_mc_start(p_QmPortal->p_LowQmPortal); +- p_Mcc->queryfq_np.fqid = fqid; ++ WRITE_UINT32(p_Mcc->queryfq_np.fqid, fqid); + qm_mc_commit(p_QmPortal->p_LowQmPortal, QM_MCC_VERB_QUERYFQ_NP); + while (!(p_Mcr = qm_mc_result(p_QmPortal->p_LowQmPortal))) ; + ASSERT_COND((p_Mcr->verb & QM_MCR_VERB_MASK) == QM_MCC_VERB_QUERYFQ_NP); +@@ -245,7 +315,56 @@ static t_Error qman_init_fq(t_QmPortal *p_QmPortal, + return ERROR_CODE(E_BUSY); + } + p_Mcc = qm_mc_start(p_QmPortal->p_LowQmPortal); ++#ifdef __aarch64__ ++ /* ++ * Portal CE memory is big-endian on QorIQ ARM64 (LS1046A). ++ * Mem2IOCpy32 doesn't handle LE→BE conversion correctly for packed ++ * structs whose fields span 32-bit word boundaries — the byte-by-byte ++ * prefix and the unaligned shift-merge were designed for big-endian ++ * PowerPC only. Write each field individually using WRITE_UINTxx ++ * (out{8,16,32}rb) which byte-swap LE values to BE portal bytes. ++ * ++ * Bitfield-containing sub-fields (dest_wq, td_thresh) must be manually ++ * reconstructed in BE bit layout because GCC allocates bitfields from ++ * LSB on LE vs MSB on BE. ++ */ ++ WRITE_UINT8(p_Mcc->initfq.reserved1, 0); ++ WRITE_UINT16(p_Mcc->initfq.we_mask, p_Opts->we_mask); ++ WRITE_UINT32(p_Mcc->initfq.fqid, p_Opts->fqid); ++ WRITE_UINT16(p_Mcc->initfq.count, p_Opts->count); ++ /* FQD sub-struct */ ++ WRITE_UINT8(p_Mcc->initfq.fqd.orpc, p_Opts->fqd.orpc); ++ WRITE_UINT8(p_Mcc->initfq.fqd.cgid, p_Opts->fqd.cgid); ++ WRITE_UINT16(p_Mcc->initfq.fqd.fq_ctrl, p_Opts->fqd.fq_ctrl); ++ { ++ /* dest_wq has bitfields channel:13 wq:3. ++ * BE bit layout: channel(bits15-3) wq(bits2-0). */ ++ uint16_t dest_wq_be = ((uint16_t)(p_Opts->fqd.dest.channel & 0x1FFF) << 3) | ++ (p_Opts->fqd.dest.wq & 0x7); ++ WRITE_UINT16(p_Mcc->initfq.fqd.dest_wq, dest_wq_be); ++ } ++ { ++ /* reserved2:1 + ics_cred:15 are bare bitfields with no union accessor. ++ * Address the 16-bit word via the preceding dest_wq union. */ ++ volatile uint16_t *p_ics = (volatile uint16_t *)&p_Mcc->initfq.fqd.dest_wq + 1; ++ /* BE bit layout: reserved2(bit15) ics_cred(bits14-0). reserved2=0. */ ++ uint16_t ics_be = (uint16_t)(p_Opts->fqd.ics_cred & 0x7FFF); ++ WRITE_UINT16(*p_ics, ics_be); ++ } ++ { ++ /* td_thresh has bitfields reserved1:3 mant:8 exp:5. ++ * BE bit layout: reserved(bits15-13) mant(bits12-5) exp(bits4-0). */ ++ uint16_t td_be = ((uint16_t)(p_Opts->fqd.td.mant & 0xFF) << 5) | ++ (p_Opts->fqd.td.exp & 0x1F); ++ WRITE_UINT16(p_Mcc->initfq.fqd.td_thresh, td_be); ++ } ++ WRITE_UINT32(p_Mcc->initfq.fqd.context_b, p_Opts->fqd.context_b); ++ WRITE_UINT32(p_Mcc->initfq.fqd.context_a.hi, p_Opts->fqd.context_a.hi); ++ WRITE_UINT32(p_Mcc->initfq.fqd.context_a.lo, p_Opts->fqd.context_a.lo); ++ /* reserved3[32] already zeroed by dcbz_64 in qm_mc_start */ ++#else + Mem2IOCpy32((void*)&p_Mcc->initfq, p_Opts, sizeof(struct qm_mcc_initfq)); ++#endif + qm_mc_commit(p_QmPortal->p_LowQmPortal, myverb); + while (!(p_Mcr = qm_mc_result(p_QmPortal->p_LowQmPortal))) ; + ASSERT_COND((p_Mcr->verb & QM_MCR_VERB_MASK) == myverb); +@@ -253,17 +372,19 @@ static t_Error qman_init_fq(t_QmPortal *p_QmPortal, + if (res != QM_MCR_RESULT_OK) { + FQUNLOCK(p_Fq); + PUNLOCK(p_QmPortal); +- RETURN_ERROR(MINOR, E_INVALID_STATE,("INITFQ failed: %s", mcr_result_str(res))); ++ RETURN_ERROR(MINOR, E_INVALID_STATE,("INITFQ failed: fqid=%d %s", ++ p_Fq->fqid, mcr_result_str(res))); + } + +- if (p_Mcc->initfq.we_mask & QM_INITFQ_WE_FQCTRL) { +- if (p_Mcc->initfq.fqd.fq_ctrl & QM_FQCTRL_CGE) ++ /* Read flags back from the source struct, not portal CE (which is BE) */ ++ if (p_Opts->we_mask & QM_INITFQ_WE_FQCTRL) { ++ if (p_Opts->fqd.fq_ctrl & QM_FQCTRL_CGE) + p_Fq->flags |= QMAN_FQ_STATE_CGR_EN; + else + p_Fq->flags &= ~QMAN_FQ_STATE_CGR_EN; + } +- if (p_Mcc->initfq.we_mask & QM_INITFQ_WE_CGID) +- p_Fq->cgr_groupid = p_Mcc->initfq.fqd.cgid; ++ if (p_Opts->we_mask & QM_INITFQ_WE_CGID) ++ p_Fq->cgr_groupid = p_Opts->fqd.cgid; + p_Fq->state = (flags & QMAN_INITFQ_FLAG_SCHED) ? + qman_fq_state_sched : qman_fq_state_parked; + FQUNLOCK(p_Fq); +@@ -296,9 +417,9 @@ static t_Error qman_retire_fq(t_QmPortal *p_QmPortal, + goto out; + } + p_Mcc = qm_mc_start(p_QmPortal->p_LowQmPortal); +- p_Mcc->alterfq.fqid = p_Fq->fqid; ++ WRITE_UINT32(p_Mcc->alterfq.fqid, p_Fq->fqid); + if (drain) +- p_Mcc->alterfq.context_b = aligned_int_from_ptr(p_Fq); ++ WRITE_UINT32(p_Mcc->alterfq.context_b, aligned_int_from_ptr(p_Fq)); + qm_mc_commit(p_QmPortal->p_LowQmPortal, + (uint8_t)((drain)?QM_MCC_VERB_ALTER_RETIRE_CTXB:QM_MCC_VERB_ALTER_RETIRE)); + while (!(p_Mcr = qm_mc_result(p_QmPortal->p_LowQmPortal))) ; +@@ -347,7 +468,7 @@ static t_Error qman_oos_fq(t_QmPortal *p_QmPortal, struct qman_fq *p_Fq) + return ERROR_CODE(E_BUSY); + } + p_Mcc = qm_mc_start(p_QmPortal->p_LowQmPortal); +- p_Mcc->alterfq.fqid = p_Fq->fqid; ++ WRITE_UINT32(p_Mcc->alterfq.fqid, p_Fq->fqid); + qm_mc_commit(p_QmPortal->p_LowQmPortal, QM_MCC_VERB_ALTER_OOS); + while (!(p_Mcr = qm_mc_result(p_QmPortal->p_LowQmPortal))) ; + ASSERT_COND((p_Mcr->verb & QM_MCR_VERB_MASK) == QM_MCR_VERB_ALTER_OOS); +@@ -383,7 +504,7 @@ static t_Error qman_schedule_fq(t_QmPortal *p_QmPortal, struct qman_fq *p_Fq) + return ERROR_CODE(E_BUSY); + } + p_Mcc = qm_mc_start(p_QmPortal->p_LowQmPortal); +- p_Mcc->alterfq.fqid = p_Fq->fqid; ++ WRITE_UINT32(p_Mcc->alterfq.fqid, p_Fq->fqid); + qm_mc_commit(p_QmPortal->p_LowQmPortal, QM_MCC_VERB_ALTER_SCHED); + while (!(p_Mcr = qm_mc_result(p_QmPortal->p_LowQmPortal))) ; + ASSERT_COND((p_Mcr->verb & QM_MCR_VERB_MASK) == QM_MCR_VERB_ALTER_SCHED); +@@ -607,14 +728,30 @@ static uint32_t LoopMessageRing(t_QmPortal *p_QmPortal, uint32_t is) + qmPortalMrPvbUpdate(p_QmPortal->p_LowQmPortal); + p_Msg = qm_mr_current(p_QmPortal->p_LowQmPortal); + if (p_Msg) { +- struct qman_fq *p_FqFqs = ptr_from_aligned_int(p_Msg->fq.contextB); +- struct qman_fq *p_FqErn = ptr_from_aligned_int(p_Msg->ern.tag); ++ struct qman_fq *p_FqFqs = ptr_from_aligned_int(GET_UINT32(p_Msg->fq.contextB)); ++ struct qman_fq *p_FqErn = ptr_from_aligned_int(GET_UINT32(p_Msg->ern.tag)); + uint8_t verb =(uint8_t)(p_Msg->verb & QM_MR_VERB_TYPE_MASK); + t_QmRejectedFrameInfo rejectedFrameInfo; ++ t_DpaaFD mr_fd; + + memset(&rejectedFrameInfo, 0, sizeof(t_QmRejectedFrameInfo)); + if (!(verb & QM_MR_VERB_DC_ERN)) + { ++ qm_fd_read(&mr_fd, &p_Msg->ern.fd); ++ { ++ static int ern_print_count; ++ if (ern_print_count++ < 20) ++ XX_Print("QM ERN: verb=0x%02x rc=0x%02x fqid=%u " ++ "fd_addr=0x%08x%08x fd_status=0x%x\n", ++ verb, p_Msg->ern.rc, ++ p_FqErn ? p_FqErn->fqid : 0, ++ DPAA_FD_GET_ADDRH(&mr_fd), ++ DPAA_FD_GET_ADDRL(&mr_fd), ++ DPAA_FD_GET_STATUS(&mr_fd)); ++ } ++ if (DPAA_FD_GET_PHYS_ADDR(&mr_fd) == 0) ++ XX_Print("LoopMessageRing: ERN FD.addr=0 verb=0x%02x rc=0x%02x\n", ++ verb, p_Msg->ern.rc); + switch(p_Msg->ern.rc) + { + case(QM_MR_RC_CGR_TAILDROP): +@@ -635,11 +772,17 @@ static uint32_t LoopMessageRing(t_QmPortal *p_QmPortal, uint32_t is) + REPORT_ERROR(MINOR, E_NOT_SUPPORTED, ("Unknown rejection code")); + } + if (!p_FqErn) +- p_QmPortal->p_NullCB->ern(p_QmPortal->h_App, NULL, p_QmPortal, 0, (t_DpaaFD*)&p_Msg->ern.fd, &rejectedFrameInfo); ++ p_QmPortal->p_NullCB->ern(p_QmPortal->h_App, NULL, p_QmPortal, 0, &mr_fd, &rejectedFrameInfo); + else +- p_FqErn->cb.ern(p_FqErn->h_App, p_FqErn->h_QmFqr, p_QmPortal, p_FqErn->fqidOffset, (t_DpaaFD*)&p_Msg->ern.fd, &rejectedFrameInfo); ++ p_FqErn->cb.ern(p_FqErn->h_App, p_FqErn->h_QmFqr, p_QmPortal, p_FqErn->fqidOffset, &mr_fd, &rejectedFrameInfo); + } else if (verb == QM_MR_VERB_DC_ERN) + { ++ { ++ static int dc_ern_count; ++ if (dc_ern_count++ < 20) ++ XX_Print("QM DC_ERN: fqid=%u\n", ++ p_FqErn ? p_FqErn->fqid : 0); ++ } + if (!p_FqErn) + p_QmPortal->p_NullCB->dc_ern(NULL, p_QmPortal, NULL, p_Msg); + else +@@ -676,6 +819,7 @@ static void LoopDequeueRing(t_Handle h_QmPortal) + e_RxStoreResponse tmpRes; + t_QmPortal *p_QmPortal = (t_QmPortal *)h_QmPortal; + int prefetch = !(p_QmPortal->options & QMAN_PORTAL_FLAG_RSTASH); ++ t_DpaaFD fd; + + while (res != qman_cb_dqrr_pause) + { +@@ -685,12 +829,13 @@ static void LoopDequeueRing(t_Handle h_QmPortal) + p_Dq = qm_dqrr_current(p_QmPortal->p_LowQmPortal); + if (!p_Dq) + break; +- p_Fq = ptr_from_aligned_int(p_Dq->contextB); ++ p_Fq = ptr_from_aligned_int(GET_UINT32(p_Dq->contextB)); ++ qm_fd_read(&fd, &p_Dq->fd); + if (p_Dq->stat & QM_DQRR_STAT_UNSCHEDULED) { + /* We only set QMAN_FQ_STATE_NE when retiring, so we only need + * to check for clearing it when doing volatile dequeues. It's + * one less thing to check in the critical path (SDQCR). */ +- tmpRes = p_Fq->cb.dqrr(p_Fq->h_App, p_Fq->h_QmFqr, p_QmPortal, p_Fq->fqidOffset, (t_DpaaFD*)&p_Dq->fd); ++ tmpRes = p_Fq->cb.dqrr(p_Fq->h_App, p_Fq->h_QmFqr, p_QmPortal, p_Fq->fqidOffset, &fd); + if (tmpRes == e_RX_STORE_RESPONSE_PAUSE) + res = qman_cb_dqrr_pause; + /* Check for VDQCR completion */ +@@ -706,14 +851,14 @@ static void LoopDequeueRing(t_Handle h_QmPortal) + { + /* Interpret 'dq' from the owner's perspective. */ + /* use portal default handlers */ +- ASSERT_COND(p_Dq->fqid); ++ ASSERT_COND(GET_UINT32(p_Dq->fqid)); + if (p_Fq) + { + tmpRes = p_Fq->cb.dqrr(p_Fq->h_App, + p_Fq->h_QmFqr, + p_QmPortal, + p_Fq->fqidOffset, +- (t_DpaaFD*)&p_Dq->fd); ++ &fd); + if (tmpRes == e_RX_STORE_RESPONSE_PAUSE) + res = qman_cb_dqrr_pause; + else if (p_Fq->state == qman_fq_state_waiting_parked) +@@ -724,8 +869,8 @@ static void LoopDequeueRing(t_Handle h_QmPortal) + tmpRes = p_QmPortal->p_NullCB->dqrr(p_QmPortal->h_App, + NULL, + p_QmPortal, +- p_Dq->fqid, +- (t_DpaaFD*)&p_Dq->fd); ++ GET_UINT32(p_Dq->fqid), ++ &fd); + if (tmpRes == e_RX_STORE_RESPONSE_PAUSE) + res = qman_cb_dqrr_pause; + } +@@ -760,6 +905,7 @@ static void LoopDequeueRingDcaOptimized(t_Handle h_QmPortal) + enum qman_cb_dqrr_result res = qman_cb_dqrr_consume; + e_RxStoreResponse tmpRes; + t_QmPortal *p_QmPortal = (t_QmPortal *)h_QmPortal; ++ t_DpaaFD fd; + + while (res != qman_cb_dqrr_pause) + { +@@ -767,12 +913,13 @@ static void LoopDequeueRingDcaOptimized(t_Handle h_QmPortal) + p_Dq = qm_dqrr_current(p_QmPortal->p_LowQmPortal); + if (!p_Dq) + break; +- p_Fq = ptr_from_aligned_int(p_Dq->contextB); ++ p_Fq = ptr_from_aligned_int(GET_UINT32(p_Dq->contextB)); ++ qm_fd_read(&fd, &p_Dq->fd); + if (p_Dq->stat & QM_DQRR_STAT_UNSCHEDULED) { + /* We only set QMAN_FQ_STATE_NE when retiring, so we only need + * to check for clearing it when doing volatile dequeues. It's + * one less thing to check in the critical path (SDQCR). */ +- tmpRes = p_Fq->cb.dqrr(p_Fq->h_App, p_Fq->h_QmFqr, p_QmPortal, p_Fq->fqidOffset, (t_DpaaFD*)&p_Dq->fd); ++ tmpRes = p_Fq->cb.dqrr(p_Fq->h_App, p_Fq->h_QmFqr, p_QmPortal, p_Fq->fqidOffset, &fd); + if (tmpRes == e_RX_STORE_RESPONSE_PAUSE) + res = qman_cb_dqrr_pause; + /* Check for VDQCR completion */ +@@ -788,14 +935,14 @@ static void LoopDequeueRingDcaOptimized(t_Handle h_QmPortal) + { + /* Interpret 'dq' from the owner's perspective. */ + /* use portal default handlers */ +- ASSERT_COND(p_Dq->fqid); ++ ASSERT_COND(GET_UINT32(p_Dq->fqid)); + if (p_Fq) + { + tmpRes = p_Fq->cb.dqrr(p_Fq->h_App, + p_Fq->h_QmFqr, + p_QmPortal, + p_Fq->fqidOffset, +- (t_DpaaFD*)&p_Dq->fd); ++ &fd); + if (tmpRes == e_RX_STORE_RESPONSE_PAUSE) + res = qman_cb_dqrr_pause; + else if (p_Fq->state == qman_fq_state_waiting_parked) +@@ -806,8 +953,8 @@ static void LoopDequeueRingDcaOptimized(t_Handle h_QmPortal) + tmpRes = p_QmPortal->p_NullCB->dqrr(p_QmPortal->h_App, + NULL, + p_QmPortal, +- p_Dq->fqid, +- (t_DpaaFD*)&p_Dq->fd); ++ GET_UINT32(p_Dq->fqid), ++ &fd); + if (tmpRes == e_RX_STORE_RESPONSE_PAUSE) + res = qman_cb_dqrr_pause; + } +@@ -834,6 +981,7 @@ static void LoopDequeueRingOptimized(t_Handle h_QmPortal) + enum qman_cb_dqrr_result res = qman_cb_dqrr_consume; + e_RxStoreResponse tmpRes; + t_QmPortal *p_QmPortal = (t_QmPortal *)h_QmPortal; ++ t_DpaaFD fd; + + while (res != qman_cb_dqrr_pause) + { +@@ -841,12 +989,13 @@ static void LoopDequeueRingOptimized(t_Handle h_QmPortal) + p_Dq = qm_dqrr_current(p_QmPortal->p_LowQmPortal); + if (!p_Dq) + break; +- p_Fq = ptr_from_aligned_int(p_Dq->contextB); ++ p_Fq = ptr_from_aligned_int(GET_UINT32(p_Dq->contextB)); ++ qm_fd_read(&fd, &p_Dq->fd); + if (p_Dq->stat & QM_DQRR_STAT_UNSCHEDULED) { + /* We only set QMAN_FQ_STATE_NE when retiring, so we only need + * to check for clearing it when doing volatile dequeues. It's + * one less thing to check in the critical path (SDQCR). */ +- tmpRes = p_Fq->cb.dqrr(p_Fq->h_App, p_Fq->h_QmFqr, p_QmPortal, p_Fq->fqidOffset, (t_DpaaFD*)&p_Dq->fd); ++ tmpRes = p_Fq->cb.dqrr(p_Fq->h_App, p_Fq->h_QmFqr, p_QmPortal, p_Fq->fqidOffset, &fd); + if (tmpRes == e_RX_STORE_RESPONSE_PAUSE) + res = qman_cb_dqrr_pause; + /* Check for VDQCR completion */ +@@ -862,14 +1011,14 @@ static void LoopDequeueRingOptimized(t_Handle h_QmPortal) + { + /* Interpret 'dq' from the owner's perspective. */ + /* use portal default handlers */ +- ASSERT_COND(p_Dq->fqid); ++ ASSERT_COND(GET_UINT32(p_Dq->fqid)); + if (p_Fq) + { + tmpRes = p_Fq->cb.dqrr(p_Fq->h_App, + p_Fq->h_QmFqr, + p_QmPortal, + p_Fq->fqidOffset, +- (t_DpaaFD*)&p_Dq->fd); ++ &fd); + if (tmpRes == e_RX_STORE_RESPONSE_PAUSE) + res = qman_cb_dqrr_pause; + else if (p_Fq->state == qman_fq_state_waiting_parked) +@@ -880,8 +1029,8 @@ static void LoopDequeueRingOptimized(t_Handle h_QmPortal) + tmpRes = p_QmPortal->p_NullCB->dqrr(p_QmPortal->h_App, + NULL, + p_QmPortal, +- p_Dq->fqid, +- (t_DpaaFD*)&p_Dq->fd); ++ GET_UINT32(p_Dq->fqid), ++ &fd); + if (tmpRes == e_RX_STORE_RESPONSE_PAUSE) + res = qman_cb_dqrr_pause; + } +@@ -909,6 +1058,26 @@ static void portal_isr(void *ptr) + + DBG(TRACE, ("software-portal %d got interrupt", p_QmPortal->p_LowQmPortal->config.cpu)); + ++#ifdef __aarch64__ ++ { ++ /* Per-portal ISR invocation counters (max 16 portals) */ ++ static volatile uint32_t portal_isr_cnt[16]; ++ int cpu = p_QmPortal->p_LowQmPortal->config.cpu; ++ uint32_t cnt; ++ if (cpu >= 0 && cpu < 16) ++ cnt = ++portal_isr_cnt[cpu]; ++ else ++ cnt = 0; ++ if (cnt <= 10 || (cnt % 1000 == 0)) ++ printf("qman: portal_isr cpu=%d count=%u ISR=0x%x IER=0x%x " ++ "dqrr_fill=%u\n", ++ cpu, cnt, ++ qm_isr_status_read(p_QmPortal->p_LowQmPortal), ++ enableEvents, ++ (unsigned)p_QmPortal->p_LowQmPortal->dqrr.fill); ++ } ++#endif ++ + event |= (qm_isr_status_read(p_QmPortal->p_LowQmPortal) & + enableEvents); + +@@ -930,7 +1099,7 @@ static t_Error qman_query_fq_np(t_QmPortal *p_QmPortal, struct qman_fq *p_Fq, st + + NCSW_PLOCK(p_QmPortal); + p_Mcc = qm_mc_start(p_QmPortal->p_LowQmPortal); +- p_Mcc->queryfq_np.fqid = p_Fq->fqid; ++ WRITE_UINT32(p_Mcc->queryfq_np.fqid, p_Fq->fqid); + qm_mc_commit(p_QmPortal->p_LowQmPortal, QM_MCC_VERB_QUERYFQ_NP); + while (!(p_Mcr = qm_mc_result(p_QmPortal->p_LowQmPortal))) ; + ASSERT_COND((p_Mcr->verb & QM_MCR_VERB_MASK) == QM_MCR_VERB_QUERYFQ_NP); +@@ -1198,6 +1367,105 @@ static void clean_dqrr_mr(t_QmPortal *p_QmPortal) + } + } + ++/* ++ * Clean up stale frame queues left by a previous boot (e.g. U-Boot). ++ * The QMan hardware's FQD cache may retain FQs in SCHED/ACTIVE state ++ * across a soft reboot. If not retired, these stale FQs will produce ++ * DQRR entries with invalid contextB pointers, causing a page fault. ++ * ++ * Called during portal creation after DQRR, MR, and MC are initialized ++ * but before ISR setup and SDQCR enable. ++ */ ++#define CLEANUP_MAX_FQID 256 ++ ++static void qman_cleanup_stale_fqs(struct qm_portal *portal) ++{ ++ static volatile int cleanup_done = 0; ++ struct qm_mc_command *mcc; ++ struct qm_mc_result *mcr; ++ uint32_t fqid; ++ int cleaned = 0; ++ uint8_t state, res; ++ ++ /* All portals see the same global FQ state — only clean up once. ++ * Running on subsequent portals would retire FQs that drivers ++ * legitimately created after the first portal's cleanup. */ ++ if (atomic_cmpset_int(&cleanup_done, 0, 1) == 0) ++ return; ++ ++ /* Drain any stale DQRR entries from previous boot */ ++ while (qmPortalDqrrPvbUpdate(portal), ++ qm_dqrr_current(portal) != NULL) { ++ qm_dqrr_next(portal); ++ qmPortalDqrrCciConsume(portal, 1); ++ } ++ /* Drain any stale MR entries from previous boot */ ++ while (qmPortalMrPvbUpdate(portal), ++ qm_mr_current(portal) != NULL) { ++ qm_mr_next(portal); ++ qmPortalMrCciConsume(portal, 1); ++ } ++ /* Retire stale FQs via MC commands */ ++ for (fqid = 0; fqid < CLEANUP_MAX_FQID; fqid++) { ++ /* QUERYFQ_NP */ ++ mcc = qm_mc_start(portal); ++ WRITE_UINT32(mcc->queryfq_np.fqid, fqid); ++ qm_mc_commit(portal, QM_MCC_VERB_QUERYFQ_NP); ++ while (!(mcr = qm_mc_result(portal))) ++ ; ++ res = mcr->result; ++ if (res != QM_MCR_RESULT_OK) ++ continue; ++ state = mcr->queryfq_np.state & QM_MCR_NP_STATE_MASK; ++ if (state == QM_MCR_NP_STATE_OOS) ++ continue; ++ if (state == QM_MCR_NP_STATE_RETIRED) ++ goto do_oos; ++ ++ /* ALTER_RETIRE */ ++ mcc = qm_mc_start(portal); ++ WRITE_UINT32(mcc->alterfq.fqid, fqid); ++ qm_mc_commit(portal, QM_MCC_VERB_ALTER_RETIRE); ++ while (!(mcr = qm_mc_result(portal))) ++ ; ++ res = mcr->result; ++ if (res == QM_MCR_RESULT_PENDING) { ++ /* Wait for FQRNI on MR */ ++ int timeout = 10000; ++ while (timeout--) { ++ qmPortalMrPvbUpdate(portal); ++ if (qm_mr_current(portal) != NULL) { ++ qm_mr_next(portal); ++ qmPortalMrCciConsume(portal, 1); ++ break; ++ } ++ } ++ } else if (res != QM_MCR_RESULT_OK) { ++ XX_Print("qman_cleanup: fqid %u retire failed 0x%02x\n", ++ fqid, res); ++ continue; ++ } ++ ++do_oos: ++ /* ALTER_OOS */ ++ mcc = qm_mc_start(portal); ++ WRITE_UINT32(mcc->alterfq.fqid, fqid); ++ qm_mc_commit(portal, QM_MCC_VERB_ALTER_OOS); ++ while (!(mcr = qm_mc_result(portal))) ++ ; ++ res = mcr->result; ++ if (res != QM_MCR_RESULT_OK) { ++ /* OOS may fail if FQ has pending frames. ++ * RETIRED state is safe — FQ won't be scheduled. */ ++ XX_Print("qman_cleanup: fqid %u OOS failed 0x%02x " ++ "(left retired)\n", fqid, res); ++ } ++ cleaned++; ++ } ++ if (cleaned) ++ printf("qman: retired %d stale FQs\n", cleaned); ++} ++ + static t_Error qman_create_portal(t_QmPortal *p_QmPortal, + uint32_t flags, + uint32_t sdqcrFlags, +@@ -1230,6 +1498,8 @@ static t_Error qman_create_portal(t_QmPortal *p_QmPortal, + REPORT_ERROR(MAJOR, E_INVALID_STATE, ("MC initialization failed")); + goto fail_mc; + } ++ /* Clean up stale FQs from previous boot before enabling SDQCR */ ++ qman_cleanup_stale_fqs(p_QmPortal->p_LowQmPortal); + if (qm_isr_init(p_QmPortal->p_LowQmPortal)) { + REPORT_ERROR(MAJOR, E_INVALID_STATE, ("ISR initialization failed")); + goto fail_isr; +@@ -1272,7 +1542,37 @@ goto fail_dqrr_mr_empty; + goto fail_dqrr_mr_empty; + } + qm_isr_disable_write(p_QmPortal->p_LowQmPortal, 0); ++ /* ++ * Inhibit ISR before enabling SDQCR — stale FQs from a previous boot ++ * (e.g. Linux) may still be in SCHED state. Enabling SDQCR causes ++ * the hardware to push their DQRR entries immediately. Drain them ++ * here before the ISR can see them (their contextB pointers are ++ * garbage in this kernel's address space). ++ */ ++ qm_isr_inhibit(p_QmPortal->p_LowQmPortal); + qm_dqrr_sdqcr_set(p_QmPortal->p_LowQmPortal, sdqcrFlags); ++ { ++ int idle = 0; ++ while (idle < 1000) { ++ qmPortalDqrrPvbUpdate(p_QmPortal->p_LowQmPortal); ++ if (qm_dqrr_current(p_QmPortal->p_LowQmPortal) != NULL) { ++ qm_dqrr_next(p_QmPortal->p_LowQmPortal); ++ qmPortalDqrrCciConsume(p_QmPortal->p_LowQmPortal, 1); ++ idle = 0; ++ } else { ++ XX_UDelay(10); ++ idle++; ++ } ++ } ++ /* Also drain any MR entries that appeared */ ++ while (qmPortalMrPvbUpdate(p_QmPortal->p_LowQmPortal), ++ qm_mr_current(p_QmPortal->p_LowQmPortal) != NULL) { ++ qm_mr_next(p_QmPortal->p_LowQmPortal); ++ qmPortalMrCciConsume(p_QmPortal->p_LowQmPortal, 1); ++ } ++ } ++ qm_isr_status_clear(p_QmPortal->p_LowQmPortal, 0xffffffff); ++ qm_isr_uninhibit(p_QmPortal->p_LowQmPortal); + return E_OK; + fail_dqrr_mr_empty: + fail_eqcr_empty: +@@ -1341,8 +1641,8 @@ static t_Error qman_orp_update(t_QmPortal *p_QmPortal, + else + /* No need to check 4 QMAN_ENQUEUE_FLAG_HOLE */ + orpSeqnum &= ~QM_EQCR_SEQNUM_NESN; +- p_Eq->seqnum = orpSeqnum; +- p_Eq->orp = orpId; ++ WRITE_UINT16(p_Eq->seqnum, orpSeqnum); ++ WRITE_UINT32(p_Eq->orp, orpId); + qmPortalEqcrPvbCommit(p_QmPortal->p_LowQmPortal, (uint8_t)QM_EQCR_VERB_ORP); + + PUNLOCK(p_QmPortal); +@@ -1394,7 +1694,7 @@ static t_Error QmPortalUnregisterCg(t_Handle h_QmPortal, uint8_t cgId) + if(!(p_QmPortal->cgrs[0].q.__state[cgId/32] & (0x80000000 >> (cgId % 32)))) + RETURN_ERROR(MINOR, E_BUSY, ("CG is not in use")); + +- p_QmPortal->cgrs[0].q.__state[cgId/32] &= ~0x80000000 >> (cgId % 32); ++ p_QmPortal->cgrs[0].q.__state[cgId/32] &= ~(0x80000000 >> (cgId % 32)); + p_QmPortal->cgsHandles[cgId] = NULL; + + return E_OK; +@@ -1494,7 +1794,6 @@ static t_Error QmPortalPullFrame(t_Handle h_QmPortal, uint32_t pdqcr, t_DpaaFD * + t_QmPortal *p_QmPortal = (t_QmPortal *)h_QmPortal; + struct qm_dqrr_entry *p_Dq; + int prefetch; +- uint32_t *p_Dst, *p_Src; + + ASSERT_COND(p_QmPortal); + ASSERT_COND(p_Frame); +@@ -1515,13 +1814,8 @@ static t_Error QmPortalPullFrame(t_Handle h_QmPortal, uint32_t pdqcr, t_DpaaFD * + p_Dq = qm_dqrr_current(p_QmPortal->p_LowQmPortal); + if (!p_Dq) + continue; +- ASSERT_COND(p_Dq->fqid); +- p_Dst = (uint32_t *)p_Frame; +- p_Src = (uint32_t *)&p_Dq->fd; +- p_Dst[0] = p_Src[0]; +- p_Dst[1] = p_Src[1]; +- p_Dst[2] = p_Src[2]; +- p_Dst[3] = p_Src[3]; ++ ASSERT_COND(GET_UINT32(p_Dq->fqid)); ++ qm_fd_read(p_Frame, &p_Dq->fd); + if (p_QmPortal->options & QMAN_PORTAL_FLAG_DCA) + { + qmPortalDqrrDcaConsume1ptr(p_QmPortal->p_LowQmPortal, +@@ -1792,6 +2086,12 @@ t_Error QM_PORTAL_AddPoolChannel(t_Handle h_QmPortal, uint8_t poolChannelId) + sdqcrFlags |= QM_SDQCR_CHANNELS_POOL(poolChannelId+1); + qm_dqrr_sdqcr_set(p_QmPortal->p_LowQmPortal, sdqcrFlags); + ++#ifdef __aarch64__ ++ XX_Print("QM_PORTAL_AddPoolChannel: cpu=%d poolCh=%u SDQCR=0x%08x\n", ++ p_QmPortal->p_LowQmPortal->config.cpu, ++ (unsigned)poolChannelId, sdqcrFlags); ++#endif ++ + return E_OK; + } + +@@ -1820,6 +2120,51 @@ t_Error QM_PORTAL_Poll(t_Handle h_QmPortal, e_QmPortalPollSource source) + return E_OK; + } + ++#ifdef __aarch64__ ++/* ++ * Read DQRR state from hardware for diagnostics. ++ * Returns software PI/CI/fill and hardware PI/CI registers. ++ */ ++void QM_PORTAL_DqrrDiag(t_Handle h_QmPortal, uint8_t *sw_pi, uint8_t *sw_ci, ++ uint8_t *sw_fill, uint8_t *hw_pi, uint8_t *hw_ci) ++{ ++ t_QmPortal *p_QmPortal = (t_QmPortal *)h_QmPortal; ++ struct qm_portal *portal = p_QmPortal->p_LowQmPortal; ++ struct qm_dqrr *dqrr = &portal->dqrr; ++ ++ *sw_pi = dqrr->pi; ++ *sw_ci = dqrr->ci; ++ *sw_fill = dqrr->fill; ++ *hw_pi = (uint8_t)(qm_in(DQRR_PI_CINH) & (QM_DQRR_SIZE - 1)); ++ *hw_ci = (uint8_t)(qm_in(DQRR_CI_CINH) & (QM_DQRR_SIZE - 1)); ++} ++ ++void QM_PORTAL_IsrDiag(t_Handle h_QmPortal, uint32_t *isr, uint32_t *ier, ++ uint32_t *iir) ++{ ++ t_QmPortal *p = (t_QmPortal *)h_QmPortal; ++ ++ *isr = qm_isr_status_read(p->p_LowQmPortal); ++ *ier = qm_isr_enable_read(p->p_LowQmPortal); ++ *iir = __qm_isr_read(p->p_LowQmPortal, qm_isr_inhibit); ++} ++ ++void QM_PORTAL_Inhibit(t_Handle h_QmPortal) ++{ ++ t_QmPortal *p = (t_QmPortal *)h_QmPortal; ++ ++ qm_isr_inhibit(p->p_LowQmPortal); ++} ++ ++void QM_PORTAL_Uninhibit(t_Handle h_QmPortal) ++{ ++ t_QmPortal *p = (t_QmPortal *)h_QmPortal; ++ ++ qm_isr_status_clear(p->p_LowQmPortal, 0xffffffff); ++ qm_isr_uninhibit(p->p_LowQmPortal); ++} ++#endif ++ + t_Error QM_PORTAL_PollFrame(t_Handle h_QmPortal, t_QmPortalFrameInfo *p_frameInfo) + { + t_QmPortal *p_QmPortal = (t_QmPortal *)h_QmPortal; +@@ -1842,21 +2187,21 @@ t_Error QM_PORTAL_PollFrame(t_Handle h_QmPortal, t_QmPortalFrameInfo *p_frameInf + PUNLOCK(p_QmPortal); + return ERROR_CODE(E_EMPTY); + } +- p_Fq = ptr_from_aligned_int(p_Dq->contextB); +- ASSERT_COND(p_Dq->fqid); ++ p_Fq = ptr_from_aligned_int(GET_UINT32(p_Dq->contextB)); ++ ASSERT_COND(GET_UINT32(p_Dq->fqid)); + if (p_Fq) + { + p_frameInfo->h_App = p_Fq->h_App; + p_frameInfo->h_QmFqr = p_Fq->h_QmFqr; + p_frameInfo->fqidOffset = p_Fq->fqidOffset; +- memcpy((void*)&p_frameInfo->frame, (void*)&p_Dq->fd, sizeof(t_DpaaFD)); ++ qm_fd_read(&p_frameInfo->frame, &p_Dq->fd); + } + else + { + p_frameInfo->h_App = p_QmPortal->h_App; + p_frameInfo->h_QmFqr = NULL; +- p_frameInfo->fqidOffset = p_Dq->fqid; +- memcpy((void*)&p_frameInfo->frame, (void*)&p_Dq->fd, sizeof(t_DpaaFD)); ++ p_frameInfo->fqidOffset = GET_UINT32(p_Dq->fqid); ++ qm_fd_read(&p_frameInfo->frame, &p_Dq->fd); + } + if (p_QmPortal->options & QMAN_PORTAL_FLAG_DCA) { + qmPortalDqrrDcaConsume1ptr(p_QmPortal->p_LowQmPortal, +@@ -2138,7 +2483,6 @@ t_Error QM_FQR_Enqueue(t_Handle h_QmFqr, t_Handle h_QmPortal, uint32_t fqidOffse + t_QmFqr *p_QmFqr = (t_QmFqr *)h_QmFqr; + t_QmPortal *p_QmPortal; + struct qm_eqcr_entry *p_Eq; +- uint32_t *p_Dst, *p_Src; + const struct qman_fq *p_Fq; + + SANITY_CHECK_RETURN_ERROR(p_QmFqr, E_INVALID_HANDLE); +@@ -2171,19 +2515,9 @@ t_Error QM_FQR_Enqueue(t_Handle h_QmFqr, t_Handle h_QmPortal, uint32_t fqidOffse + return ERROR_CODE(E_BUSY); + } + +- p_Eq->fqid = p_Fq->fqid; +- p_Eq->tag = aligned_int_from_ptr(p_Fq); +- /* gcc does a dreadful job of the following; +- * eq->fd = *fd; +- * It causes the entire function to save/restore a wider range of +- * registers, and comes up with instruction-waste galore. This will do +- * until we can rework the function for better code-generation. */ +- p_Dst = (uint32_t *)&p_Eq->fd; +- p_Src = (uint32_t *)p_Frame; +- p_Dst[0] = p_Src[0]; +- p_Dst[1] = p_Src[1]; +- p_Dst[2] = p_Src[2]; +- p_Dst[3] = p_Src[3]; ++ WRITE_UINT32(p_Eq->fqid, p_Fq->fqid); ++ WRITE_UINT32(p_Eq->tag, aligned_int_from_ptr(p_Fq)); ++ qm_fd_write(&p_Eq->fd, p_Frame); + + qmPortalEqcrPvbCommit(p_QmPortal->p_LowQmPortal, + (uint8_t)(QM_EQCR_VERB_CMD_ENQUEUE/* | +diff --git a/sys/contrib/ncsw/Peripherals/QM/qman_low.h b/sys/contrib/ncsw/Peripherals/QM/qman_low.h +index 1becfc15554..687d58f210a 100644 +--- a/sys/contrib/ncsw/Peripherals/QM/qman_low.h ++++ b/sys/contrib/ncsw/Peripherals/QM/qman_low.h +@@ -51,6 +51,30 @@ + /***************************/ + + /* Cache-inhibited register offsets */ ++#if defined(__aarch64__) ++/* ++ * ARM64 Layerscape (LS1046A etc.): CI space is 16KB per portal. ++ * Register offsets differ from PowerPC. ++ * See Linux drivers/soc/fsl/qbman/qman.c for reference. ++ */ ++#define REG_EQCR_PI_CINH 0x3000 ++#define REG_EQCR_CI_CINH 0x3040 ++#define REG_EQCR_ITR 0x3080 ++#define REG_DQRR_PI_CINH 0x3100 ++#define REG_DQRR_CI_CINH 0x3140 ++#define REG_DQRR_ITR 0x3180 ++#define REG_DQRR_DCAP 0x31C0 ++#define REG_DQRR_SDQCR 0x3200 ++#define REG_DQRR_VDQCR 0x3240 ++#define REG_DQRR_PDQCR 0x3280 ++#define REG_MR_PI_CINH 0x3300 ++#define REG_MR_CI_CINH 0x3340 ++#define REG_MR_ITR 0x3380 ++#define REG_CFG 0x3500 ++#define REG_ISR 0x3600 ++#define REG_ITPR 0x3740 ++#define QM_ISR_SHIFT 6 /* ISR/IER/ISDR/IIR stride: 64 bytes */ ++#else /* PowerPC */ + #define REG_EQCR_PI_CINH 0x0000 + #define REG_EQCR_CI_CINH 0x0004 + #define REG_EQCR_ITR 0x0008 +@@ -66,22 +90,29 @@ + #define REG_MR_ITR 0x0088 + #define REG_CFG 0x0100 + #define REG_ISR 0x0e00 +-#define REG_IER 0x0e04 +-#define REG_ISDR 0x0e08 +-#define REG_IIR 0x0e0c + #define REG_ITPR 0x0e14 ++#define QM_ISR_SHIFT 2 /* ISR/IER/ISDR/IIR stride: 4 bytes */ ++#endif + + /* Cache-enabled register offsets */ + #define CL_EQCR 0x0000 + #define CL_DQRR 0x1000 + #define CL_MR 0x2000 + #define CL_EQCR_PI_CENA 0x3000 ++#if defined(__aarch64__) ++#define CL_EQCR_CI_CENA 0x3040 ++#define CL_DQRR_PI_CENA 0x3100 ++#define CL_DQRR_CI_CENA 0x3140 ++#define CL_MR_PI_CENA 0x3300 ++#define CL_MR_CI_CENA 0x3340 ++#else /* PowerPC */ + #define CL_EQCR_CI_CENA 0x3100 + #define CL_DQRR_PI_CENA 0x3200 + #define CL_DQRR_CI_CENA 0x3300 + #define CL_MR_PI_CENA 0x3400 + #define CL_MR_CI_CENA 0x3500 + #define CL_RORI_CENA 0x3600 ++#endif + #define CL_CR 0x3800 + #define CL_RR0 0x3900 + #define CL_RR1 0x3940 +@@ -300,11 +331,18 @@ static __inline__ struct qm_eqcr_entry *qm_eqcr_pend_and_next(struct qm_portal * + } + + #ifdef QM_CHECKING ++/* ++ * EQCR entries live in CE portal memory (big-endian on hardware). ++ * On ARM64, WRITE_UINT32 byte-swaps values for the hardware, so we ++ * must use GET_UINT32 to read them back in host order for validation. ++ */ + #define EQCR_COMMIT_CHECKS(eqcr) \ + do { \ + ASSERT_COND(eqcr->busy); \ +- ASSERT_COND(eqcr->cursor->orp == (eqcr->cursor->orp & 0x00ffffff)); \ +- ASSERT_COND(eqcr->cursor->fqid == (eqcr->cursor->fqid & 0x00ffffff)); \ ++ ASSERT_COND(GET_UINT32(eqcr->cursor->orp) == \ ++ (GET_UINT32(eqcr->cursor->orp) & 0x00ffffff)); \ ++ ASSERT_COND(GET_UINT32(eqcr->cursor->fqid) == \ ++ (GET_UINT32(eqcr->cursor->fqid) & 0x00ffffff)); \ + } while(0) + + #else +@@ -878,6 +916,7 @@ static __inline__ void qm_mr_current_prefetch(struct qm_portal *portal) + { + register struct qm_mr *mr = &portal->mr; + dcbt_ro(mr->cursor); ++ (void)mr; + } + + static __inline__ struct qm_mr_entry *qm_mr_current(struct qm_portal *portal) +@@ -1139,10 +1178,10 @@ static __inline__ void qm_isr_set_iperiod(struct qm_portal *portal, uint16_t ipe + + static __inline__ uint32_t __qm_isr_read(struct qm_portal *portal, enum qm_isr_reg n) + { +- return __qm_in(&portal->addr, REG_ISR + (n << 2)); ++ return __qm_in(&portal->addr, REG_ISR + (n << QM_ISR_SHIFT)); + } + + static __inline__ void __qm_isr_write(struct qm_portal *portal, enum qm_isr_reg n, uint32_t val) + { +- __qm_out(&portal->addr, REG_ISR + (n << 2), val); ++ __qm_out(&portal->addr, REG_ISR + (n << QM_ISR_SHIFT), val); + } +diff --git a/sys/contrib/ncsw/Peripherals/QM/qman_private.h b/sys/contrib/ncsw/Peripherals/QM/qman_private.h +index 0b172879099..3b5dc9fa745 100644 +--- a/sys/contrib/ncsw/Peripherals/QM/qman_private.h ++++ b/sys/contrib/ncsw/Peripherals/QM/qman_private.h +@@ -56,6 +56,39 @@ + * execution reordering with respect to other code/instructions that manipulate + * the same cacheline. */ + ++#if defined(__aarch64__) ++/* ++ * ARM64 cache operations. ++ * ++ * Portal CE region is mapped Normal Non-Cacheable (matching Linux's ++ * MEMREMAP_WC), so stores go directly to hardware. However, dcbf is ++ * also used on cacheable DMA memory (FQD, PFDR) in qm.c — there we ++ * need real cache clean to make CPU writes visible to QMan hardware. ++ * ++ * dc cvac (clean by VA to PoC) is the ARM64 equivalent of PPC dcbf. ++ * On NC addresses it's a harmless no-op; on cached addresses it writes ++ * dirty lines back to memory. ++ * ++ * dc zva MUST NOT be used on portal NC memory — it generates a special ++ * bus transaction that can hang the interconnect. Use memset instead. ++ */ ++#define lwsync() __asm__ __volatile__ ("dmb ish" : : : "memory") ++#define dcbf(addr) do { \ ++ __asm__ __volatile__ ("dc cvac, %0" : : "r"(addr) : "memory"); \ ++ __asm__ __volatile__ ("dsb st" : : : "memory"); \ ++} while(0) ++#define dcbi(p) __asm__ __volatile__ ("dsb sy" : : : "memory") ++#define dcbt_ro(addr) do { } while(0) ++#define dcbt_rw(addr) do { } while(0) ++#define dcbz_64(p) do { memset((p), 0, 64); } while(0) ++#define dcbf_64(p) do { \ ++ __asm__ __volatile__ ("dc cvac, %0" : : "r"(p) : "memory"); \ ++ __asm__ __volatile__ ("dsb st" : : : "memory"); \ ++} while(0) ++#define dcbit_ro(p) do { } while(0) ++ ++#else /* PowerPC */ ++ + #define dcbf(addr) \ + do { \ + __asm__ __volatile__ ("dcbf 0, %0" : : "r" (addr)); \ +@@ -132,6 +165,8 @@ + + #define dcbi(p) dcbf(p) + ++#endif /* __aarch64__ */ ++ + struct qm_addr { + void *addr_ce; /* cache-enabled */ + void *addr_ci; /* cache-inhibited */ +diff --git a/sys/contrib/ncsw/build/dflags_arm64.h b/sys/contrib/ncsw/build/dflags_arm64.h +new file mode 100644 +index 00000000000..4a5eec8e0e8 +--- /dev/null ++++ b/sys/contrib/ncsw/build/dflags_arm64.h +@@ -0,0 +1,86 @@ ++/*- ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * All rights reserved. ++ * ++ * 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 AUTHOR 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 AUTHOR 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. ++ */ ++ ++/* ++ * DPAA1 / NetCommSW build flags for ARM64 (LS1046A). ++ * ++ * Equivalent to dflags.h (which targets PowerPC e500mc/P5020). ++ * Force-included before every ncsw source file via config.dpaa_arm64. ++ */ ++#ifndef DFLAGS_ARM64_H_ ++#define DFLAGS_ARM64_H_ ++ ++#include "opt_platform.h" ++#include "events_mapping.h" ++ ++/* ++ * Core selection: ARM64 (Cortex-A72). ++ * The PPC path uses NCSW_PPC_CORE which pulls in ppc_ext.h and e500v2_ext.h. ++ * Our ARM path uses NCSW_ARM_CORE which pulls in arm_ext.h with FreeBSD ++ * ARM64 implementations. ++ */ ++#define NCSW_ARM_CORE ++#define NCSW_FREEBSD ++ ++/* Cortex-A72 cache line size (LS1046A) */ ++#define CORE_CACHELINE_SIZE 64 ++ ++/* Linux-ism helpers needed by mEMAC flib code */ ++#include ++#include ++ ++/* ++ * LIST_ compatibility macros — FreeBSD's list_ext.h prefixes everything ++ * with NCSW_ to avoid conflicts with . The mEMAC code ++ * uses the unprefixed original names from the NXP SDK. ++ * ++ * Note: LIST_FIRST/NEXT/PREV/LAST conflict with and ++ * are intentionally omitted here. ++ */ ++#define LIST_Add NCSW_LIST_Add ++#define LIST_AddToTail NCSW_LIST_AddToTail ++#define LIST_DelAndInit NCSW_LIST_DelAndInit ++#define LIST_IsEmpty NCSW_LIST_IsEmpty ++#define LIST_OBJECT NCSW_LIST_OBJECT ++#define LIST_FOR_EACH NCSW_LIST_FOR_EACH ++#define LIST_FOR_EACH_SAFE NCSW_LIST_FOR_EACH_SAFE ++#define LIST_FOR_EACH_OBJECT NCSW_LIST_FOR_EACH_OBJECT ++#define LIST_FOR_EACH_OBJECT_SAFE NCSW_LIST_FOR_EACH_OBJECT_SAFE ++ ++/* Debugging */ ++#define DEBUG_ERRORS 1 ++#define DPAA_DEBUG 1 ++#if defined(DPAA_DEBUG) ++#define DEBUG_GLOBAL_LEVEL REPORT_LEVEL_INFO ++#else ++#define DEBUG_GLOBAL_LEVEL REPORT_LEVEL_WARNING ++#endif ++ ++/* Events */ ++#define REPORT_EVENTS 1 ++#define EVENT_GLOBAL_LEVEL REPORT_LEVEL_MINOR ++ ++#endif /* DFLAGS_ARM64_H_ */ +diff --git a/sys/contrib/ncsw/etc/ncsw_memcpy.c b/sys/contrib/ncsw/etc/ncsw_memcpy.c +new file mode 100644 +index 00000000000..6793a2ebf84 +--- /dev/null ++++ b/sys/contrib/ncsw/etc/ncsw_memcpy.c +@@ -0,0 +1,6 @@ ++/* ++ * Wrapper to compile ncsw memcpy.c as ncsw_memcpy.o, avoiding ++ * a name collision with arm64/arm64/memcpy.S (which also produces ++ * memcpy.o and defines memcpy/memmove). ++ */ ++#include "memcpy.c" +diff --git a/sys/contrib/ncsw/inc/Peripherals/bm_ext.h b/sys/contrib/ncsw/inc/Peripherals/bm_ext.h +index 952e95f62e4..79a1bff7264 100644 +--- a/sys/contrib/ncsw/inc/Peripherals/bm_ext.h ++++ b/sys/contrib/ncsw/inc/Peripherals/bm_ext.h +@@ -131,6 +131,9 @@ typedef struct { + NOTE: this parameter relevant only when working with multiple partitions. */ + uint8_t partNumOfPools; /**< Number of Pools dedicated to this partition. + NOTE: this parameter relevant only when working with multiple partitions. */ ++ void *p_FbprBase; /**< Pre-allocated FBPR memory (virtual), or NULL for internal allocation. ++ Must be physically contiguous, naturally aligned, and non-cacheable. */ ++ uint32_t fbprSize; /**< Size of pre-allocated FBPR memory in bytes. */ + } t_BmParam; + + +diff --git a/sys/contrib/ncsw/inc/Peripherals/dpaa_ext.h b/sys/contrib/ncsw/inc/Peripherals/dpaa_ext.h +index e7c0c131fda..fae846e2b8c 100644 +--- a/sys/contrib/ncsw/inc/Peripherals/dpaa_ext.h ++++ b/sys/contrib/ncsw/inc/Peripherals/dpaa_ext.h +@@ -182,29 +182,42 @@ typedef _Packed struct t_DpaaCompTbl { + #define DPAA_SGTE_BPID_MASK 0x00ff0000 /**< SGTE BPID field mask */ + #define DPAA_SGTE_OFFSET_MASK 0x00001fff /**< SGTE OFFSET field mask */ + +-#define DPAA_SGTE_GET_ADDRH(sgte) (((t_DpaaSGTE *)sgte)->addrh & DPAA_SGTE_ADDRH_MASK) /**< Macro to get SGTE ADDRH field */ +-#define DPAA_SGTE_GET_ADDRL(sgte) ((t_DpaaSGTE *)sgte)->addrl /**< Macro to get SGTE ADDRL field */ +-#define DPAA_SGTE_GET_PHYS_ADDR(sgte) ((physAddress_t)(((uint64_t)DPAA_SGTE_GET_ADDRH(sgte) << 32) | (uint64_t)DPAA_SGTE_GET_ADDRL(sgte))) /**< Macro to get FD ADDR field */ +-#define DPAA_SGTE_GET_EXTENSION(sgte) ((((t_DpaaSGTE *)sgte)->length & DPAA_SGTE_E_MASK) >> (31-0)) /**< Macro to get SGTE EXTENSION field */ +-#define DPAA_SGTE_GET_FINAL(sgte) ((((t_DpaaSGTE *)sgte)->length & DPAA_SGTE_F_MASK) >> (31-1)) /**< Macro to get SGTE FINAL field */ +-#define DPAA_SGTE_GET_LENGTH(sgte) (((t_DpaaSGTE *)sgte)->length & DPAA_SGTE_LENGTH_MASK) /**< Macro to get SGTE LENGTH field */ +-#define DPAA_SGTE_GET_BPID(sgte) ((((t_DpaaSGTE *)sgte)->offset & DPAA_SGTE_BPID_MASK) >> (31-15)) /**< Macro to get SGTE BPID field */ +-#define DPAA_SGTE_GET_OFFSET(sgte) (((t_DpaaSGTE *)sgte)->offset & DPAA_SGTE_OFFSET_MASK) /**< Macro to get SGTE OFFSET field */ ++/* ++ * SGT entries live in host DMA memory and are read/written by FMan in ++ * big-endian byte order. On big-endian hosts (PowerPC) no swap is needed. ++ * On little-endian hosts (ARM64) each 32-bit field must be byte-swapped. ++ */ ++#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ ++#define _DPAA_SGTE_R32(field) (field) ++#define _DPAA_SGTE_W32(field, val) ((field) = (val)) ++#else ++#define _DPAA_SGTE_R32(field) __builtin_bswap32(field) ++#define _DPAA_SGTE_W32(field, val) ((field) = __builtin_bswap32(val)) ++#endif ++ ++#define DPAA_SGTE_GET_ADDRH(sgte) (_DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->addrh) & DPAA_SGTE_ADDRH_MASK) ++#define DPAA_SGTE_GET_ADDRL(sgte) _DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->addrl) ++#define DPAA_SGTE_GET_PHYS_ADDR(sgte) ((physAddress_t)(((uint64_t)DPAA_SGTE_GET_ADDRH(sgte) << 32) | (uint64_t)DPAA_SGTE_GET_ADDRL(sgte))) ++#define DPAA_SGTE_GET_EXTENSION(sgte) ((_DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->length) & DPAA_SGTE_E_MASK) >> (31-0)) ++#define DPAA_SGTE_GET_FINAL(sgte) ((_DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->length) & DPAA_SGTE_F_MASK) >> (31-1)) ++#define DPAA_SGTE_GET_LENGTH(sgte) (_DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->length) & DPAA_SGTE_LENGTH_MASK) ++#define DPAA_SGTE_GET_BPID(sgte) ((_DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->offset) & DPAA_SGTE_BPID_MASK) >> (31-15)) ++#define DPAA_SGTE_GET_OFFSET(sgte) (_DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->offset) & DPAA_SGTE_OFFSET_MASK) + #define DPAA_SGTE_GET_ADDR(sgte) XX_PhysToVirt(DPAA_SGTE_GET_PHYS_ADDR(sgte)) + +-#define DPAA_SGTE_SET_ADDRH(sgte,val) (((t_DpaaSGTE *)sgte)->addrh = ((((t_DpaaSGTE *)sgte)->addrh & ~DPAA_SGTE_ADDRH_MASK) | ((val) & DPAA_SGTE_ADDRH_MASK))) /**< Macro to set SGTE ADDRH field */ +-#define DPAA_SGTE_SET_ADDRL(sgte,val) ((t_DpaaSGTE *)sgte)->addrl = (val) /**< Macro to set SGTE ADDRL field */ ++#define DPAA_SGTE_SET_ADDRH(sgte,val) _DPAA_SGTE_W32(((t_DpaaSGTE *)sgte)->addrh, (_DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->addrh) & ~DPAA_SGTE_ADDRH_MASK) | ((val) & DPAA_SGTE_ADDRH_MASK)) ++#define DPAA_SGTE_SET_ADDRL(sgte,val) _DPAA_SGTE_W32(((t_DpaaSGTE *)sgte)->addrl, (val)) + #define DPAA_SGTE_SET_ADDR(sgte,val) \ + do { \ + uint64_t physAddr = (uint64_t)(XX_VirtToPhys(val)); \ + DPAA_SGTE_SET_ADDRH(sgte, ((uint32_t)(physAddr >> 32))); \ + DPAA_SGTE_SET_ADDRL(sgte, (uint32_t)physAddr); \ +-} while (0) /**< Macro to set SGTE ADDR field */ +-#define DPAA_SGTE_SET_EXTENSION(sgte,val) (((t_DpaaSGTE *)sgte)->length = ((((t_DpaaSGTE *)sgte)->length & ~DPAA_SGTE_E_MASK) | (((val) << (31-0))& DPAA_SGTE_E_MASK))) /**< Macro to set SGTE EXTENSION field */ +-#define DPAA_SGTE_SET_FINAL(sgte,val) (((t_DpaaSGTE *)sgte)->length = ((((t_DpaaSGTE *)sgte)->length & ~DPAA_SGTE_F_MASK) | (((val) << (31-1))& DPAA_SGTE_F_MASK))) /**< Macro to set SGTE FINAL field */ +-#define DPAA_SGTE_SET_LENGTH(sgte,val) (((t_DpaaSGTE *)sgte)->length = (((t_DpaaSGTE *)sgte)->length & ~DPAA_SGTE_LENGTH_MASK) | ((val) & DPAA_SGTE_LENGTH_MASK)) /**< Macro to set SGTE LENGTH field */ +-#define DPAA_SGTE_SET_BPID(sgte,val) (((t_DpaaSGTE *)sgte)->offset = ((((t_DpaaSGTE *)sgte)->offset & ~DPAA_SGTE_BPID_MASK) | (((val) << (31-15))& DPAA_SGTE_BPID_MASK))) /**< Macro to set SGTE BPID field */ +-#define DPAA_SGTE_SET_OFFSET(sgte,val) (((t_DpaaSGTE *)sgte)->offset = ((((t_DpaaSGTE *)sgte)->offset & ~DPAA_SGTE_OFFSET_MASK) | (((val) << (31-31))& DPAA_SGTE_OFFSET_MASK) )) /**< Macro to set SGTE OFFSET field */ ++} while (0) ++#define DPAA_SGTE_SET_EXTENSION(sgte,val) _DPAA_SGTE_W32(((t_DpaaSGTE *)sgte)->length, (_DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->length) & ~DPAA_SGTE_E_MASK) | (((val) << (31-0)) & DPAA_SGTE_E_MASK)) ++#define DPAA_SGTE_SET_FINAL(sgte,val) _DPAA_SGTE_W32(((t_DpaaSGTE *)sgte)->length, (_DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->length) & ~DPAA_SGTE_F_MASK) | (((val) << (31-1)) & DPAA_SGTE_F_MASK)) ++#define DPAA_SGTE_SET_LENGTH(sgte,val) _DPAA_SGTE_W32(((t_DpaaSGTE *)sgte)->length, (_DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->length) & ~DPAA_SGTE_LENGTH_MASK) | ((val) & DPAA_SGTE_LENGTH_MASK)) ++#define DPAA_SGTE_SET_BPID(sgte,val) _DPAA_SGTE_W32(((t_DpaaSGTE *)sgte)->offset, (_DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->offset) & ~DPAA_SGTE_BPID_MASK) | (((val) << (31-15)) & DPAA_SGTE_BPID_MASK)) ++#define DPAA_SGTE_SET_OFFSET(sgte,val) _DPAA_SGTE_W32(((t_DpaaSGTE *)sgte)->offset, (_DPAA_SGTE_R32(((t_DpaaSGTE *)sgte)->offset) & ~DPAA_SGTE_OFFSET_MASK) | (((val) << (31-31)) & DPAA_SGTE_OFFSET_MASK)) + /* @} */ + + #if defined(__MWERKS__) && !defined(__GNUC__) +diff --git a/sys/contrib/ncsw/inc/Peripherals/fm_ehash.h b/sys/contrib/ncsw/inc/Peripherals/fm_ehash.h +new file mode 100644 +index 00000000000..d09b7d4f18f +--- /dev/null ++++ b/sys/contrib/ncsw/inc/Peripherals/fm_ehash.h +@@ -0,0 +1,724 @@ ++/* ++ * Shadow fm_ehash.h — FMan External Hash Table API ++ * ++ * Replaces the SDK header (which contains Linux-specific inline functions). ++ * Struct layouts match the NXP SDK exactly: ++ * sdk_fman/inc/Peripherals/fm_ehash.h ++ * ++ * NOTE: en_exthash_info and en_exthash_node are NOT defined here — they ++ * are defined locally in fm_ehash_freebsd.c (EXCLUDE_FMAN_IPR_OFFLOAD ++ * variant). CDX code treats table handles as opaque void*. ++ * ++ * Copyright 2011, 2014 Freescale Semiconductor, Inc. ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * SPDX-License-Identifier: BSD-2-Clause ++ */ ++#ifndef FM_EHASH_H ++#define FM_EHASH_H 1 ++ ++#include ++ ++/* ---------------------------------------------------------------- ++ * Constants ++ * ---------------------------------------------------------------- */ ++#define MAX_KEY_LEN 56 ++#define MAX_EN_EHASH_EXT_ENTRY_SIZE 320 ++#define MAX_EN_EHASH_ENTRY_SIZE 256 ++#define EN_EHASH_ENTRY_ALIGN 256 ++#define TBLENTRY_OPC_ALIGN sizeof(uint32_t) ++#define MAX_OPCODES 16 ++ ++/* ---------------------------------------------------------------- ++ * Entry flag accessors ++ * ---------------------------------------------------------------- */ ++#define SET_INVALID_ENTRY_64BIT(entry) (entry |= (((uint64_t)1) << 63)) ++#define SET_INVALID_ENTRY(flags) (flags |= (1 << 15)) ++#define SET_TIMESTAMP_ENABLE(flags) (flags |= (1 << 13)) ++#define SET_STATS_ENABLE(flags) (flags |= (1 << 12)) ++#define SET_OPC_OFFSET(flags, offset) (flags |= ((offset >> 2) << 6)) ++#define SET_PARAM_OFFSET(flags, offset) (flags |= (offset >> 2)) ++ ++#define GET_INVALID_ENTRY_64BIT(entry) (entry & (((uint64_t)1) << 63)) ++#define GET_INVALID_ENTRY(flags) (flags & (1 << 15)) ++#define GET_TIMESTAMP_ENABLE(flags) ((flags >> 13) & 1) ++#define GET_STATS_ENABLE(flags) (flags & (1 << 12)) ++#define GET_OPC_OFFSET(x) (((x >> 6) & 0x1f) << 2) ++#define GET_PARAM_OFFSET(x) ((x & 0x3f) << 2) ++ ++/* ---------------------------------------------------------------- ++ * Hash table entry — on-hardware representation ++ * ---------------------------------------------------------------- */ ++struct en_ehash_entry { ++ union { ++ struct { ++ union { ++ struct { ++ uint16_t flags; ++ uint16_t next_entry_hi; ++ uint32_t next_entry_lo; ++ }; ++ uint64_t next_entry; ++ }; ++ uint8_t key[0]; ++ } __attribute__((packed)); ++ struct { ++ uint8_t hash_entry[MAX_EN_EHASH_ENTRY_SIZE]; ++ uint64_t packet_count; ++ uint64_t packet_bytes; ++ uint32_t timestamp; ++ uint32_t reserved; ++ uint32_t timestamp_counter; ++ } __attribute__((packed)); ++ uint8_t hash_ext_entry[MAX_EN_EHASH_EXT_ENTRY_SIZE]; ++ } __attribute__((packed)); ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * DPA Classifier table entry statistics ++ * ---------------------------------------------------------------- */ ++#define STATS_VALID (1 << 0) ++#define TIMESTAMP_VALID (1 << 1) ++ ++struct en_tbl_entry_stats { ++ uint64_t pkts; ++ uint64_t bytes; ++ uint32_t timestamp; ++ uint32_t flags; ++}; ++ ++/* ---------------------------------------------------------------- ++ * Opcodes ++ * ---------------------------------------------------------------- */ ++#define ENQUEUE_PKT 0x01 ++#define REPLICATE_PKT 0x02 ++#define ENQUEUE_ONLY 0x03 ++#define UPDATE_ETH_RX_STATS 0x04 ++#define PREEMPTIVE_CHECKS_ON_PKT 0x05 ++#define PREEMPTIVE_CHECKS_ON_IPSEC_PKT 0x06 ++#define STRIP_ETH_HDR 0x11 ++#define STRIP_ALL_VLAN_HDRS 0x12 ++#define STRIP_PPPoE_HDR 0x14 ++#define STRIP_L2_HDR 0x17 ++#define STRIP_FIRST_VLAN_HDR 0x18 ++#define REMOVE_FIRST_IP_HDR 0x19 ++#define VALIDATE_IPSEC_ID 0x1a ++#define UPDATE_TTL 0x21 ++#define UPDATE_SIP_V4 0x22 ++#define UPDATE_DIP_V4 0x24 ++#define UPDATE_HOPLIMIT 0x29 ++#define UPDATE_SIP_V6 0x2A ++#define UPDATE_DIP_V6 0x2C ++#define UPDATE_SPORT 0x31 ++#define UPDATE_DPORT 0x32 ++#define INSERT_L2_HDR 0x41 ++#define INSERT_VLAN_HDR 0x42 ++#define INSERT_PPPoE_HDR 0x43 ++#define INSERT_L3_HDR 0x44 ++#define REPLACE_PPPOE_HDR 0x45 ++#define NATPT_4to6 0x51 ++#define NATPT_6to4 0x52 ++#define PROCESS_RTP_PAYLOAD 0x61 ++#define PROCESS_RTCP_PAYLOAD 0x62 ++#define UPDATE_GLOBAL_STATS 0x80 ++ ++/* ---------------------------------------------------------------- ++ * Preemptive check parameters ++ * ---------------------------------------------------------------- */ ++#define PREEMPT_TX_VALIDATE (1 << 0) ++#define PREEMPT_DFBIT_HONOR (1 << 1) ++#define PREEMPT_POLICE_PKT (1 << 2) ++#define PREEMPT_MATCH_DSCP (1 << 3) ++#define PREEMPT_REPLACE_DSCP (1 << 4) ++ ++struct en_ehash_preempt_op { ++ uint8_t mtu_offset; ++ uint8_t OpMask; ++ uint8_t dscp_match_value; ++ uint8_t pp_no; ++ uint8_t new_dscp_val; ++ uint8_t pad; ++ uint16_t pad1; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * IPSec preemptive check parameters ++ * ---------------------------------------------------------------- */ ++#define MAX_VLAN_PER_FLOW 2 ++#define MAX_SPI_PER_FLOW 16 ++#define VALIDATE_SPI (0x1 << 0) ++ ++struct spi_info { ++ uint32_t spi; ++ uint32_t fqid; ++} __attribute__((packed)); ++ ++struct en_ehash_ipsec_preempt_op { ++ uint8_t op_flags; ++ uint8_t unused; ++ uint16_t natt_arr_mask; ++ uint16_t pppoe_session_id; ++ uint16_t pad; ++ struct spi_info spi_param[MAX_SPI_PER_FLOW]; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Enqueue parameters ++ * ---------------------------------------------------------------- */ ++#define EN_EHASH_DISABLE_FRAG 0xffff ++ ++struct en_ehash_enqueue_param { ++ uint16_t mtu; ++ uint8_t hdr_xpnd_sz; ++ uint8_t bpid; ++ uint32_t fqid; ++ union { ++ struct { ++ uint32_t rspid:8; ++ uint32_t stats_ptr:24; ++ }; ++ uint32_t word; ++ }; ++ union { ++ struct { ++ uint32_t dscp_fq_enable:8; ++ uint32_t muram_frag_param_addr:24; ++ }; ++ uint32_t word2; ++ }; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * RTP relay parameters ++ * ---------------------------------------------------------------- */ ++#define EEH_RTP_SEND_FIRST_PACKET_TO_CP 0x0001 ++#define EEH_RTP_DUPLICATE_PKT_SEND_TO_CP 0x0002 ++#define EEH_RTP_ENABLE_VLAN_P_BIT_LEARN 0x0004 ++ ++struct en_ehash_rtprelay_param { ++ uint32_t rtpinfo_ptr; ++ uint32_t in_sock_stats_ptr; ++ uint32_t out_sock_stats_ptr; ++ union { ++ uint32_t src_ipv4_val; ++ uint32_t src_ipv6_val[4]; ++ } __attribute__((packed)); ++ uint32_t TimeStampIncr; ++ uint32_t SSRC_1; ++ uint16_t seq_base; ++ uint16_t egress_socketID; ++ uint8_t DTMF_PT[2]; ++ uint16_t rtp_flags; ++ uint16_t seq_incr; ++ uint32_t chksum_ptr; ++ uint32_t rtp_hdr; ++ uint32_t ts_incr; ++ uint32_t cur_ts_msec; ++ int32_t rtp_check; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Replicate parameters (multicast) ++ * ---------------------------------------------------------------- */ ++struct en_ehash_replicate_param { ++ union { ++ struct { ++ uint16_t rsvd; ++ uint16_t first_member_flow_addr_hi; ++ uint32_t first_member_flow_addr_lo; ++ }; ++ uint64_t first_member_flow_addr; ++ }; ++ void *first_listener_entry; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Update ethernet RX stats ++ * ---------------------------------------------------------------- */ ++struct en_ehash_update_ether_rx_stats { ++ uint32_t stats_ptr; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Strip first VLAN header ++ * ---------------------------------------------------------------- */ ++struct en_ehash_strip_first_vlan_hdr { ++ uint32_t stats_ptr; ++ uint16_t vlan_id; ++ uint16_t pad; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Strip all VLAN headers ++ * ---------------------------------------------------------------- */ ++#define OP_SKIP_VLAN_VALIDATE (1 << 0) ++#define OP_VLAN_FILTER_EN (1 << 1) ++#define OP_VLAN_FILTER_PVID_SET (1 << 2) ++ ++struct en_ehash_strip_all_vlan_hdrs { ++ uint16_t vlan_id[MAX_VLAN_PER_FLOW]; ++ union { ++ struct { ++ uint32_t padding:2; ++ uint32_t num_entries:6; ++ uint32_t stats_ptr:24; ++ }; ++ uint32_t word; ++ }; ++ uint8_t op_flags; ++ uint8_t pad; ++ uint16_t pad1; ++ uint8_t stats_offsets[0]; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Strip PPPoE header ++ * ---------------------------------------------------------------- */ ++struct en_ehash_strip_pppoe_hdr { ++ uint32_t stats_ptr; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Strip all L2 headers ++ * ---------------------------------------------------------------- */ ++struct en_ehash_strip_l2_hdrs { ++ uint16_t vlan_id[MAX_VLAN_PER_FLOW]; ++ union { ++ struct { ++ uint32_t padding:2; ++ uint32_t num_entries:6; ++ uint32_t stats_ptr:24; ++ }; ++ uint32_t word; ++ }; ++ uint8_t stats_offsets[0]; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Validate IPSec ID ++ * ---------------------------------------------------------------- */ ++struct en_ehash_validate_ipsec { ++ uint32_t reserved:16; ++ uint32_t identifier:16; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Update IP addresses ++ * ---------------------------------------------------------------- */ ++struct en_ehash_update_ipv4_ip { ++ uint32_t ip_v4; ++} __attribute__((packed)); ++ ++struct en_ehash_update_ipv6_ip { ++ uint8_t ip_v6[16]; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Update DSCP ++ * ---------------------------------------------------------------- */ ++struct en_ehash_update_dscp { ++ union { ++ struct { ++ uint32_t rsvd:24; ++ uint32_t dscp_mark_value:6; ++ uint32_t dscp_mark_flag:1; ++ uint32_t padding:1; ++ }; ++ uint32_t dscp; ++ }; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Update ports ++ * ---------------------------------------------------------------- */ ++struct en_ehash_update_port { ++ uint16_t dport; ++ uint16_t sport; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Insert L2 header ++ * ---------------------------------------------------------------- */ ++struct en_ehash_insert_l2_hdr { ++ union { ++ struct { ++ uint8_t replace:1; ++ uint8_t header_padding:2; ++ uint8_t reserved:5; ++ uint8_t stats_count; ++ uint8_t reserved_1; ++ uint8_t hdr_len; ++ }; ++ uint32_t word; ++ }; ++ uint8_t l2hdr[0]; ++} __attribute__((packed)); ++ ++struct en_ehash_insert_l2_hdr_stats { ++ union { ++ struct { ++ uint32_t padding:2; ++ uint32_t reserved:6; ++ uint32_t stats_ptr:24; ++ }; ++ uint32_t word; ++ }; ++ uint8_t stats_offsets[0]; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Insert VLAN header ++ * ---------------------------------------------------------------- */ ++struct en_ehash_insert_vlan_hdr { ++ union { ++ struct { ++ uint32_t reserved:1; ++ uint32_t dscp_vlanpcp_map_enable:1; ++ uint32_t num_hdrs:6; ++ uint32_t statptr:24; ++ } __attribute__((packed)); ++ uint32_t word; ++ } __attribute__((packed)); ++ uint32_t vlanhdr[0]; ++} __attribute__((packed)); ++ ++struct en_ehash_insert_vlan_hdr_stats { ++ uint8_t stats_offsets[1]; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Insert/replace PPPoE header ++ * ---------------------------------------------------------------- */ ++#define PPPoE_VERSION 1 ++#define PPPoE_TYPE 1 ++#define PPPoE_CODE 0 ++ ++struct en_ehash_insert_pppoe_hdr { ++ uint32_t stats_ptr; ++ union { ++ struct { ++ uint32_t version:4; ++ uint32_t type:4; ++ uint32_t code:8; ++ uint32_t session_id:16; ++ }; ++ uint32_t word; ++ }; ++} __attribute__((packed)); ++ ++struct en_ehash_replace_pppoe_hdr_params { ++ uint8_t destination_mac[6]; ++ uint8_t source_mac[6]; ++ uint16_t session_id; ++ uint16_t pad; ++ uint32_t fqid; ++ uint32_t stats_ptr; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Insert L3 header (tunnels) ++ * ---------------------------------------------------------------- */ ++#define TYPE_CUSTOM 0 ++#define TYPE_4o6 1 ++#define TYPE_6o4 2 ++ ++#define IPID_STARTVAL 1 ++ ++struct en_ehash_insert_l3_hdr { ++ union { ++ struct { ++ uint8_t reserved:3; ++ uint8_t calc_cksum:1; ++ uint8_t qos:1; ++ uint8_t df:1; ++ uint8_t type:2; ++ uint8_t hdr_len; ++ uint16_t ipident; ++ }; ++ uint32_t word; ++ }; ++ union { ++ struct { ++ uint32_t route_dest_offset:8; ++ uint32_t stats_ptr:24; ++ }; ++ uint32_t word_1; ++ }; ++ uint8_t l3hdr[0]; ++} __attribute__((packed)); ++ ++#define COPY_DSCP_OUTER_INNER (1 << 24) ++ ++/* ---------------------------------------------------------------- ++ * Remove first IP header (tunnel decap) ++ * ---------------------------------------------------------------- */ ++struct en_ehash_remove_first_ip_hdr { ++ uint32_t flags:8; ++ uint32_t stats_ptr:24; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * Port info / interface stats structures ++ * ---------------------------------------------------------------- */ ++struct en_ehash_portinfo { ++ uint32_t reserved[3]; ++ uint32_t port_info; ++} __attribute__((packed)); ++ ++struct en_ehash_ifportinfo { ++ struct en_ehash_portinfo rxpinfo; ++ struct en_ehash_portinfo txpinfo; ++} __attribute__((packed)); ++ ++struct en_ehash_stats { ++ uint64_t bytes; ++ uint32_t pkts; ++ uint32_t reserved; ++} __attribute__((packed)); ++ ++struct en_ehash_stats_with_ts { ++ uint64_t bytes; ++ uint32_t pkts; ++ uint32_t pad; ++ uint64_t timestamp; ++} __attribute__((packed)); ++ ++struct en_ehash_ifstats { ++ struct en_ehash_stats rxstats; ++ struct en_ehash_stats txstats; ++} __attribute__((packed)); ++ ++#define STATS_WITH_TS (1 << 7) ++ ++struct en_ehash_ifstats_with_ts { ++ struct en_ehash_stats_with_ts rxstats; ++ struct en_ehash_stats_with_ts txstats; ++} __attribute__((packed)); ++ ++/* Statistics table */ ++struct en_ehash_stats_tbl { ++ uint32_t table_indicator:1; ++ uint32_t num_entries:7; ++ uint32_t stats_ptr:24; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * NATPT structures ++ * ---------------------------------------------------------------- */ ++struct en_ehash_natpt_hdr { ++ union { ++ struct { ++ uint32_t reserved:6; ++ uint32_t tcu:1; ++ uint32_t hlu:1; ++ uint32_t hdrlen:8; ++ uint32_t reserved1:16; ++ } ip4to6; ++ struct { ++ uint16_t reserved:5; ++ uint16_t ipu:1; ++ uint16_t tou:1; ++ uint16_t tlu:1; ++ uint16_t hdrlen:8; ++ uint16_t ipident; ++ } ip6to4; ++ uint32_t word; ++ }; ++ uint8_t l3hdr[0]; ++} __attribute__((packed)); ++ ++/* NATPT 4-to-6 flags */ ++#define NATPT_TCU (1 << 25) ++#define NATPT_HLU (1 << 24) ++/* NATPT 6-to-4 flags */ ++#define NATPT_IPU (1 << 26) ++#define NATPT_TOU (1 << 25) ++#define NATPT_TLU (1 << 24) ++ ++/* ---------------------------------------------------------------- ++ * SEC failure statistics ++ * ---------------------------------------------------------------- */ ++typedef struct en_SEC_failure_stats_s { ++ uint32_t icv_failures; ++ uint32_t hw_errs; ++ uint32_t CCM_AAD_size_errs; ++ uint32_t anti_replay_late_errs; ++ uint32_t anti_replay_replay_errs; ++ uint32_t seq_num_overflows; ++ uint32_t DMA_errs; ++ uint32_t DECO_watchdog_timer_timedout_errs; ++ uint32_t input_frame_read_errs; ++ uint32_t protocol_format_errs; ++ uint32_t ipsec_ttl_zero_errs; ++ uint32_t ipsec_pad_chk_failures; ++ uint32_t output_frame_length_rollover_errs; ++ uint32_t tbl_buff_too_small_errs; ++ uint32_t tbl_buff_pool_depletion_errs; ++ uint32_t output_frame_too_large_errs; ++ uint32_t cmpnd_frame_write_errs; ++ uint32_t buff_too_small_errs; ++ uint32_t buff_pool_depletion_errs; ++ uint32_t output_frame_write_errs; ++ uint32_t cmpnd_frame_read_errs; ++ uint32_t prehdr_read_errs; ++ uint32_t other_errs; ++} __attribute__((packed)) en_SEC_failure_stats; ++ ++/* ---------------------------------------------------------------- ++ * DSCP-to-VLAN PCP mapping ++ * ---------------------------------------------------------------- */ ++#define MAX_VLAN_PCP 7 ++ ++typedef struct en_dscp_vlanpcp_map_cfg_s { ++ uint8_t dscp_vlanpcp[MAX_VLAN_PCP + 1]; ++} __attribute__((packed)) en_dscp_vlanpcp_map_cfg; ++ ++/* ---------------------------------------------------------------- ++ * Global MURAM data area — at pool + EN_INTERNAL_BUFF_POOL_SIZE ++ * ++ * Contains DSCP-to-VLAN PCP mapping (8 bytes) followed by SEC ++ * failure statistics (92 bytes). Total: 100 bytes within a ++ * 256-byte MURAM slot. CDX microcode reads/writes these at runtime. ++ * ---------------------------------------------------------------- */ ++typedef struct en_exthash_global_mem_s { ++ en_dscp_vlanpcp_map_cfg dscp_vlanpcp_map; /* +0, 8B */ ++ en_SEC_failure_stats SEC_failure_stats; /* +8, 92B */ ++} __attribute__((packed)) en_exthash_global_mem; ++ ++/* ---------------------------------------------------------------- ++ * IP reassembly MURAM parameters — written by FMan microcode, ++ * fields configured by ExternalHashSetReasslyPool(). ++ * ++ * This is the hardware layout in MURAM, pointed to by ++ * en_exthash_node.word_2 (reassm_param << 8) for REASSM tables. ++ * All multi-byte fields are stored big-endian. ++ * ---------------------------------------------------------------- */ ++#define MAX_REASSM_BUCKETS 16 ++ ++struct ip_reassembly_stats { ++ uint64_t num_frag_pkts; ++ uint64_t num_reassemblies; ++ uint64_t num_completed_reassly; ++ uint64_t num_sess_matches; ++ uint64_t num_frags_too_small; ++ uint64_t num_reassm_timeouts; ++ uint64_t num_overlapping_frags; ++ uint64_t num_too_many_frags; ++ uint64_t num_failed_bufallocs; ++ uint64_t num_failed_ctxallocs; ++ uint64_t num_fatal_errors; ++ uint64_t num_failed_ctxdeallocs; ++ uint32_t reassm_count; ++ uint32_t pad; ++} __attribute__((packed)); ++ ++struct ip_reassembly_params { ++ uint32_t table_base_hi; ++ uint32_t table_base_lo; ++ struct ip_reassembly_stats stats; ++ uint32_t table_mask; ++ uint32_t type; ++ uint32_t ipr_timer; ++ uint32_t timeout_val; ++ uint32_t timeout_fqid; ++ uint32_t min_frag_size; ++ uint32_t reassem_bpid; ++ uint32_t reassem_bsize; ++ uint32_t frag_bpid; ++ uint32_t frag_bsize; ++ uint32_t reassly_dbg; ++ uint32_t context_info; ++ uint32_t curr_sessions; ++ uint32_t txc_fqid; ++ uint32_t timer_tnum; ++ uint32_t max_frags; ++ uint32_t max_con_reassm; ++ uint32_t bucket_base; ++ uint32_t bucket_lock[MAX_REASSM_BUCKETS]; ++ uint32_t bucket_head[MAX_REASSM_BUCKETS]; ++} __attribute__((packed)); ++ ++/* ---------------------------------------------------------------- ++ * IP reassembly info (for devman.h forward reference) ++ * ---------------------------------------------------------------- */ ++struct ip_reassembly_info { ++ uint64_t num_frag_pkts; ++ uint64_t num_reassemblies; ++ uint64_t num_completed_reassly; ++ uint64_t num_sess_matches; ++ uint64_t num_frags_too_small; ++ uint64_t num_reassm_timeouts; ++ uint64_t num_overlapping_frags; ++ uint64_t num_too_many_frags; ++ uint64_t num_failed_bufallocs; ++ uint64_t num_failed_ctxallocs; ++ uint64_t num_fatal_errors; ++ uint64_t num_failed_ctxdeallocs; ++ uint32_t table_mask; ++ uint32_t ipr_timer; ++ uint32_t timeout_val; ++ uint32_t timeout_fqid; ++ uint32_t max_frags; ++ uint32_t min_frag_size; ++ uint32_t max_con_reassm; ++ uint32_t reassem_bpid; ++ uint32_t reassem_bsize; ++ uint32_t frag_bpid; ++ uint32_t frag_bsize; ++ uint32_t timer_tnum; ++ uint32_t reassly_dbg; ++ uint32_t curr_sessions; ++ uint32_t txc_fqid; ++}; ++ ++/* ---------------------------------------------------------------- ++ * Software table entry wrapping the hardware entry ++ * ---------------------------------------------------------------- */ ++struct en_exthash_tbl_entry { ++ struct en_ehash_entry hashentry; ++ struct en_exthash_tbl_entry *prev; ++ struct en_exthash_tbl_entry *next; ++ uint8_t *replicate_params; ++ union { ++ uint8_t *enqueue_params; ++ uint8_t *ipsec_preempt_params; ++ }; ++}; ++ ++/* Hash table bucket */ ++struct en_exthash_bucket { ++ uint64_t h; ++ uint64_t pad; ++}; ++ ++/* ---------------------------------------------------------------- ++ * Debug display — no-op stubs replacing SDK inline functions ++ * that use printk/phys_to_virt/etc. Tier 1 code calls these ++ * but they're debug-only and not needed for correct operation. ++ * ---------------------------------------------------------------- */ ++static inline void ++display_ehash_tbl_entry(struct en_ehash_entry *entry __attribute__((unused)), ++ uint32_t keysize __attribute__((unused))) ++{ ++} ++ ++/* ---------------------------------------------------------------- ++ * ExternalHash API ++ * ---------------------------------------------------------------- */ ++extern void *ExternalHashTableAllocEntry(void *h_HashTbl); ++extern void ExternalHashTableEntryFree(void *entry); ++extern int ExternalHashTableFmPcdHcSync(void *h_HashTbl); ++extern int ExternalHashTableAddKey(void *h_HashTbl, uint8_t keySize, ++ void *tbl_entry); ++extern int ExternalHashTableDeleteKey(void *h_HashTbl, uint16_t index, ++ void *tbl_entry); ++extern int ExternalHashTableEntryGetStatsAndTS(void *tbl_entry, ++ struct en_tbl_entry_stats *stats); ++extern int32_t ExternalHashGetSECfailureStats(en_SEC_failure_stats *stats); ++extern int32_t ExternalHashResetSECfailureStats(void); ++extern int32_t ExternalHashSetDscpVlanpcpMapCfg(en_dscp_vlanpcp_map_cfg *map); ++extern int32_t ExternalHashGetDscpVlanpcpMapCfg(en_dscp_vlanpcp_map_cfg *map); ++extern int ExternalHashSetReasslyPool(uint32_t type, uint32_t ctx_bpid, ++ uint32_t ctx_bpsize, uint32_t frag_bpid, uint32_t frag_size, ++ uint32_t txc_fqid, uint32_t ipr_timer_freq); ++ ++#endif /* FM_EHASH_H */ +diff --git a/sys/contrib/ncsw/inc/Peripherals/fm_ext.h b/sys/contrib/ncsw/inc/Peripherals/fm_ext.h +index c3633592694..d12600c89bf 100644 +--- a/sys/contrib/ncsw/inc/Peripherals/fm_ext.h ++++ b/sys/contrib/ncsw/inc/Peripherals/fm_ext.h +@@ -1462,6 +1462,11 @@ t_Error FM_GetFmanCtrlCodeRevision(t_Handle h_Fm, t_FmCtrlCodeRevisionInfo *p_Re + *//***************************************************************************/ + uint32_t FM_GetCounter(t_Handle h_Fm, e_FmCounters counter); + ++#ifdef __aarch64__ ++void FM_ErrorDiag(t_Handle h_Fm, uint8_t hwPortId); ++void FM_TaskStatusDiag(t_Handle h_Fm, uint8_t hwPortId); ++#endif ++ + /**************************************************************************//** + @Function FM_ModifyCounter + +diff --git a/sys/contrib/ncsw/inc/Peripherals/fm_pcd_ext.h b/sys/contrib/ncsw/inc/Peripherals/fm_pcd_ext.h +index 8d1c3d88945..488b4c81d79 100644 +--- a/sys/contrib/ncsw/inc/Peripherals/fm_pcd_ext.h ++++ b/sys/contrib/ncsw/inc/Peripherals/fm_pcd_ext.h +@@ -39,6 +39,10 @@ + #ifndef __FM_PCD_EXT + #define __FM_PCD_EXT + ++/* CDX enhanced external hash tables — redirect FM_PCD_HashTable* APIs ++ * to ExternalHashTable* implementations (matching Linux SDK). */ ++#define USE_ENHANCED_EHASH 1 ++ + #include "std_ext.h" + #include "net_ext.h" + #include "list_ext.h" +@@ -1718,6 +1722,8 @@ typedef struct t_FmPcdKgSchemeParams { + uint8_t relativeSchemeId; /**< if modify=FALSE:Partition relative scheme id */ + t_Handle h_Scheme; /**< if modify=TRUE: a handle of the existing scheme */ + } id; ++ bool shared; /**< This scheme is shared between ports ++ (must match ioc_fm_pcd_kg_scheme_params_t layout) */ + bool alwaysDirect; /**< This scheme is reached only directly, i.e. no need + for match vector; KeyGen will ignore it when matching */ + struct { /**< HL Relevant only if alwaysDirect = FALSE */ +@@ -1991,6 +1997,34 @@ typedef struct t_FmPcdHashTableParams { + + t_FmPcdCcNextEngineParams ccNextEngineParamsForMiss; /**< Parameters for defining the next engine when a key is not matched */ + ++ bool agingSupport; /**< TRUE to enable aging support for all keys of this ++ hash table; allows monitoring whether a key was ++ accessed during a given period. */ ++ ++#if (DPAA_VERSION >= 11) ++ bool externalHash; /**< TRUE to use external hash table (CDX manages ++ the hash buckets in DDR; NCSW only allocates the ++ MURAM AD placeholder). */ ++ ++#ifndef EXCLUDE_FMAN_IPR_OFFLOAD ++ uint32_t table_type; /**< IP reassembly table type ++ (must match ioc_fm_pcd_hash_table_params_t layout) */ ++ struct { ++ uint32_t timeout_val; /**< reassembly timeout */ ++ uint32_t timeout_fqid; /**< fqid for reassembly failures */ ++ uint32_t max_frags; /**< max allowed fragments */ ++ uint32_t min_frag_size; /**< min allowed frag size except last frag */ ++ uint32_t max_sessions; /**< max conn reassembly sessions */ ++ }; ++#endif /* EXCLUDE_FMAN_IPR_OFFLOAD */ ++ ++ struct { ++ uint8_t dataMemId; /**< Memory partition ID for external hash table ++ buckets and contexts; must not cross 4GB boundary */ ++ uint16_t dataLiodnOffs; /**< LIODN offset for external hash table access */ ++ uintptr_t missMonitorAddr; /**< User-allocated miss monitor address */ ++ } externalHashParams; ++#endif /* (DPAA_VERSION >= 11) */ + } t_FmPcdHashTableParams; + + /**************************************************************************//** +diff --git a/sys/contrib/ncsw/inc/Peripherals/qm_ext.h b/sys/contrib/ncsw/inc/Peripherals/qm_ext.h +index 6a4bc9fcfe6..2c0bbe320b4 100644 +--- a/sys/contrib/ncsw/inc/Peripherals/qm_ext.h ++++ b/sys/contrib/ncsw/inc/Peripherals/qm_ext.h +@@ -258,6 +258,13 @@ typedef struct { + NOTE: this parameter relevant only when working with multiple partitions. */ + uint16_t partNumOfCgs; /**< Number of cgr's dedicated to this partition. + NOTE: this parameter relevant only when working with multiple partitions. */ ++ void *p_FqdBase; /**< Pre-allocated FQD memory (virtual), or NULL for internal allocation. ++ Must be physically contiguous, naturally aligned, and non-cacheable. ++ When set, totalNumOfFqids is computed from fqdSize / 64. */ ++ uint32_t fqdSize; /**< Size of pre-allocated FQD memory in bytes. */ ++ void *p_PfdrBase; /**< Pre-allocated PFDR memory (virtual), or NULL for internal allocation. ++ Must be physically contiguous, naturally aligned, and non-cacheable. */ ++ uint32_t pfdrSize; /**< Size of pre-allocated PFDR memory in bytes. */ + } t_QmParam; + + +@@ -791,6 +798,40 @@ typedef struct t_QmPortalFrameInfo { + *//***************************************************************************/ + t_Error QM_PORTAL_Poll(t_Handle h_QmPortal, e_QmPortalPollSource source); + ++#ifdef __aarch64__ ++void QM_PORTAL_DqrrDiag(t_Handle h_QmPortal, uint8_t *sw_pi, uint8_t *sw_ci, ++ uint8_t *sw_fill, uint8_t *hw_pi, uint8_t *hw_ci); ++void QM_PORTAL_IsrDiag(t_Handle h_QmPortal, uint32_t *isr, uint32_t *ier, ++ uint32_t *iir); ++ ++void QM_ErrorDiag(t_Handle h_Qm, uint32_t *err_isr, uint32_t *ecsr, ++ uint32_t *ecir, uint32_t *pfdr_fpc, uint32_t *sfdr_in_use, ++ uint32_t *idle_stat, uint32_t *dcp0_cfg, uint32_t *dcp0_dlm_avg, ++ uint32_t *dcp_dd_ihrsr, uint32_t *dcp_dd_hasr); ++ ++/**************************************************************************//** ++ @Function QM_PORTAL_Inhibit ++ ++ @Description Inhibit all interrupts for this portal (IIR=1). ++ Used by NAPI-style FILTER handler to mask interrupts ++ at the source before scheduling deferred processing. ++ ++ @Param[in] h_QmPortal - A handle to a QM-Portal module ++*//***************************************************************************/ ++void QM_PORTAL_Inhibit(t_Handle h_QmPortal); ++ ++/**************************************************************************//** ++ @Function QM_PORTAL_Uninhibit ++ ++ @Description Clear all pending ISR status and uninhibit portal ++ interrupts (IIR=0). Called after draining DQRR/MR ++ to re-enable interrupt delivery. ++ ++ @Param[in] h_QmPortal - A handle to a QM-Portal module ++*//***************************************************************************/ ++void QM_PORTAL_Uninhibit(t_Handle h_QmPortal); ++#endif ++ + /**************************************************************************//** + @Function QM_PORTAL_PollFrame + +diff --git a/sys/contrib/ncsw/inc/core_ext.h b/sys/contrib/ncsw/inc/core_ext.h +index ec89a6dde4c..8b4779672cc 100644 +--- a/sys/contrib/ncsw/inc/core_ext.h ++++ b/sys/contrib/ncsw/inc/core_ext.h +@@ -43,7 +43,11 @@ + #ifndef __CORE_EXT_H + #define __CORE_EXT_H + +-#ifdef CONFIG_FMAN_ARM ++#if defined(NCSW_ARM_CORE) ++/* FreeBSD ARM64 path — CORE_CACHELINE_SIZE set in dflags_arm64.h */ ++#include "arm_ext.h" ++#elif defined(CONFIG_FMAN_ARM) ++/* Linux ARM path */ + #include "arm_ext.h" + #include + #else +@@ -63,7 +67,7 @@ + #error "Must define the core cache-line size!" + #endif /* !CORE_CACHELINE_SIZE */ + +-#endif /* CONFIG_FMAN_ARM */ ++#endif /* NCSW_ARM_CORE / CONFIG_FMAN_ARM */ + + + /**************************************************************************//** +diff --git a/sys/contrib/ncsw/inc/cores/arm_ext.h b/sys/contrib/ncsw/inc/cores/arm_ext.h +index e63444a7d67..5ab333d1efd 100644 +--- a/sys/contrib/ncsw/inc/cores/arm_ext.h ++++ b/sys/contrib/ncsw/inc/cores/arm_ext.h +@@ -35,9 +35,6 @@ + @File arm_ext.h + + @Description Core API for ARM cores +- +- These routines must be implemented by each specific PowerPC +- core driver. + *//***************************************************************************/ + #ifndef __ARM_EXT_H + #define __ARM_EXT_H +@@ -52,4 +49,28 @@ static __inline__ void CORE_MemoryBarrier(void) + mb(); + } + +-#endif /* __PPC_EXT_H */ ++#if defined(NCSW_ARM_CORE) && defined(NCSW_FREEBSD) ++/* ++ * FreeBSD ARM64 core function bindings. ++ * Implementations are in core_arm64.c. ++ * ++ * Follow the same pattern as PPC: e500v2_ext.h defines ++ * CORE_GetId -> E500_GetId, etc. We map to ARM64_* equivalents. ++ */ ++ ++uint32_t ARM64_GetId(void); ++int ARM64_TestAndSet(volatile int *p); ++void ARM64_InstructionSync(void); ++ ++#define CORE_GetId ARM64_GetId ++#define CORE_TestAndSet ARM64_TestAndSet ++#define CORE_InstructionSync ARM64_InstructionSync ++ ++/* Cache management — handled by the kernel on ARM64, no-ops here */ ++#define CORE_DCacheEnable() do { } while (0) ++#define CORE_ICacheEnable() do { } while (0) ++#define CORE_DCacheDisable() do { } while (0) ++#define CORE_ICacheDisable() do { } while (0) ++#endif /* NCSW_ARM_CORE && NCSW_FREEBSD */ ++ ++#endif /* __ARM_EXT_H */ +diff --git a/sys/contrib/ncsw/inc/integrations/dpaa_integration_ext.h b/sys/contrib/ncsw/inc/integrations/dpaa_integration_ext.h +index 27bb5d40237..7003e027971 100644 +--- a/sys/contrib/ncsw/inc/integrations/dpaa_integration_ext.h ++++ b/sys/contrib/ncsw/inc/integrations/dpaa_integration_ext.h +@@ -103,6 +103,45 @@ typedef enum + e_QM_FQ_CHANNEL_SWPORTAL8, + e_QM_FQ_CHANNEL_SWPORTAL9, + ++#ifdef __aarch64__ ++ /* QMan v3 (LS1046A): pool channels at 0x401-0x40F, FMan DC at 0x800+, ++ * CAAM at 0x840. SW portal channels (0-9) are unchanged. */ ++ e_QM_FQ_CHANNEL_POOL1 = 0x401, ++ e_QM_FQ_CHANNEL_POOL2, ++ e_QM_FQ_CHANNEL_POOL3, ++ e_QM_FQ_CHANNEL_POOL4, ++ e_QM_FQ_CHANNEL_POOL5, ++ e_QM_FQ_CHANNEL_POOL6, ++ e_QM_FQ_CHANNEL_POOL7, ++ e_QM_FQ_CHANNEL_POOL8, ++ e_QM_FQ_CHANNEL_POOL9, ++ e_QM_FQ_CHANNEL_POOL10, ++ e_QM_FQ_CHANNEL_POOL11, ++ e_QM_FQ_CHANNEL_POOL12, ++ e_QM_FQ_CHANNEL_POOL13, ++ e_QM_FQ_CHANNEL_POOL14, ++ e_QM_FQ_CHANNEL_POOL15, ++ ++ e_QM_FQ_CHANNEL_FMAN0_SP0 = 0x800, ++ e_QM_FQ_CHANNEL_FMAN0_SP1, ++ e_QM_FQ_CHANNEL_FMAN0_SP2, ++ e_QM_FQ_CHANNEL_FMAN0_SP3, ++ e_QM_FQ_CHANNEL_FMAN0_SP4, ++ e_QM_FQ_CHANNEL_FMAN0_SP5, ++ e_QM_FQ_CHANNEL_FMAN0_SP6, ++ e_QM_FQ_CHANNEL_FMAN0_SP7, ++ e_QM_FQ_CHANNEL_FMAN0_SP8, ++ e_QM_FQ_CHANNEL_FMAN0_SP9, ++ e_QM_FQ_CHANNEL_FMAN0_SP10, ++ e_QM_FQ_CHANNEL_FMAN0_SP11, ++ e_QM_FQ_CHANNEL_FMAN0_SP12, ++ e_QM_FQ_CHANNEL_FMAN0_SP13, ++ e_QM_FQ_CHANNEL_FMAN0_SP14, ++ e_QM_FQ_CHANNEL_FMAN0_SP15, ++ ++ e_QM_FQ_CHANNEL_CAAM = 0x840 ++#else ++ /* QMan v1/v2 (P5020): pool channels at 0x21-0x2F, FMan DC at 0x40+ */ + e_QM_FQ_CHANNEL_POOL1 = 0x21, /**< Pool channels that can be serviced by any of the software portals */ + e_QM_FQ_CHANNEL_POOL2, + e_QM_FQ_CHANNEL_POOL3, +@@ -144,6 +183,7 @@ typedef enum + connected to PME */ + e_QM_FQ_CHANNEL_RAID = 0xC0 /**< Dedicated channel serviced by Direct Connect Portal 4: + connected to RAID */ ++#endif + } e_QmFQChannel; + + /***************************************************************************** +@@ -156,11 +196,31 @@ typedef enum + ******************************************************************************/ + #define INTG_MAX_NUM_OF_FM 1 + ++/* ++ * ---------- Architecture-dependent integration parameters ---------- ++ * ++ * ARM64 (LS1046A / FManv3, DPAA 1.1) ++ * Values from NXP Linux SDK LS1043 dpaa_integration_ext.h ++ * PowerPC (P5020 / FManv2, DPAA 1.0) ++ * Original FreeBSD values ++ */ ++#ifdef __aarch64__ ++#define DPAA_VERSION 11 ++#else ++#define DPAA_VERSION 10 ++#endif ++ + /* Ports defines */ ++#ifdef __aarch64__ ++#define FM_MAX_NUM_OF_1G_MACS 6 ++#define FM_MAX_NUM_OF_10G_MACS 2 ++#define FM_MAX_NUM_OF_OH_PORTS 6 ++#else + #define FM_MAX_NUM_OF_1G_MACS 5 + #define FM_MAX_NUM_OF_10G_MACS 1 +-#define FM_MAX_NUM_OF_MACS (FM_MAX_NUM_OF_1G_MACS + FM_MAX_NUM_OF_10G_MACS) + #define FM_MAX_NUM_OF_OH_PORTS 7 ++#endif ++#define FM_MAX_NUM_OF_MACS (FM_MAX_NUM_OF_1G_MACS + FM_MAX_NUM_OF_10G_MACS) + + #define FM_MAX_NUM_OF_1G_RX_PORTS FM_MAX_NUM_OF_1G_MACS + #define FM_MAX_NUM_OF_10G_RX_PORTS FM_MAX_NUM_OF_10G_MACS +@@ -170,46 +230,85 @@ typedef enum + #define FM_MAX_NUM_OF_10G_TX_PORTS FM_MAX_NUM_OF_10G_MACS + #define FM_MAX_NUM_OF_TX_PORTS (FM_MAX_NUM_OF_10G_TX_PORTS + FM_MAX_NUM_OF_1G_TX_PORTS) + ++#ifdef __aarch64__ ++#define FM_PORT_MAX_NUM_OF_EXT_POOLS 4 /**< Number of external BM pools per Rx port */ ++#define FM_MAX_NUM_OF_SUB_PORTALS 16 ++#else + #define FM_PORT_MAX_NUM_OF_EXT_POOLS 8 /**< Number of external BM pools per Rx port */ +-#define FM_PORT_NUM_OF_CONGESTION_GRPS 256 /**< Total number of congestion groups in QM */ + #define FM_MAX_NUM_OF_SUB_PORTALS 12 ++#endif ++#define FM_PORT_NUM_OF_CONGESTION_GRPS 256 /**< Total number of congestion groups in QM */ + #define FM_PORT_MAX_NUM_OF_OBSERVED_EXT_POOLS 0 + ++#if (DPAA_VERSION >= 11) ++#define FM_VSP_MAX_NUM_OF_ENTRIES 64 ++#define FM_MAX_NUM_OF_PFC_PRIORITIES 8 ++#endif ++ + /* RAMs defines */ +-#define FM_MURAM_SIZE (160 * KILOBYTE) ++#ifdef __aarch64__ ++#define FM_MURAM_SIZE (384 * KILOBYTE) /**< LS1046A FManv3: 384KB MURAM */ ++#else ++#define FM_MURAM_SIZE (160 * KILOBYTE) /**< P5020 FManv2: 160KB MURAM */ ++#endif + #define FM_IRAM_SIZE(a,b) ( 64 * KILOBYTE) + + /* PCD defines */ + #define FM_PCD_PLCR_NUM_ENTRIES 256 /**< Total number of policer profiles */ + #define FM_PCD_KG_NUM_OF_SCHEMES 32 /**< Total number of KG schemes */ + #define FM_PCD_MAX_NUM_OF_CLS_PLANS 256 /**< Number of classification plan entries. */ ++#define FM_PCD_SW_PRS_SIZE 0x00000800 ++#ifdef __aarch64__ ++#define FM_PCD_PRS_SW_PATCHES_SIZE 0x00000600 ++#else ++#define FM_PCD_PRS_SW_PATCHES_SIZE 0x00000200 ++#endif + + /* RTC defines */ + #define FM_RTC_NUM_OF_ALARMS 2 /**< RTC number of alarms */ ++#ifdef __aarch64__ ++#define FM_RTC_NUM_OF_PERIODIC_PULSES 3 /**< RTC number of periodic pulses */ ++#else + #define FM_RTC_NUM_OF_PERIODIC_PULSES 2 /**< RTC number of periodic pulses */ ++#endif + #define FM_RTC_NUM_OF_EXT_TRIGGERS 2 /**< RTC number of external triggers */ + + /* QMI defines */ + #define QMI_MAX_NUM_OF_TNUMS 64 ++#ifdef __aarch64__ ++#define QMI_DEF_TNUMS_THRESH 32 ++#else + #define MAX_QMI_DEQ_SUBPORTAL 12 + #define QMI_DEF_TNUMS_THRESH 48 ++#endif + + /* FPM defines */ + #define FM_NUM_OF_FMAN_CTRL_EVENT_REGS 4 + + /* DMA defines */ ++#ifdef __aarch64__ ++#define DMA_THRESH_MAX_COMMQ 83 ++#else + #define DMA_THRESH_MAX_COMMQ 31 ++#endif + #define DMA_THRESH_MAX_BUF 127 + + /* BMI defines */ + #define BMI_MAX_NUM_OF_TASKS 128 ++#ifdef __aarch64__ ++#define BMI_MAX_NUM_OF_DMAS 84 ++#define FM_NUM_OF_CTRL 4 ++#else + #define BMI_MAX_NUM_OF_DMAS 32 ++#define FM_NUM_OF_CTRL 2 ++#endif + #define BMI_MAX_FIFO_SIZE (FM_MURAM_SIZE) + #define PORT_MAX_WEIGHT 16 + + + #define FM_CHECK_PORT_RESTRICTIONS(__validPorts, __newPortIndx) TRUE + ++#ifndef __aarch64__ + /* P5020 unique features */ + #define FM_QMI_DEQ_OPTIONS_SUPPORT + #define FM_NO_DISPATCH_RAM_ECC +@@ -250,8 +349,6 @@ typedef enum + #define FM_IM_LARGE_MRBLR_ERRATA_FMAN15 /* Implemented by ucode */ + #define FM_BMI_TO_RISC_ENQ_ERRATA_FMANc /* No implementation, Out of LLD scope */ + #define FM_INVALID_SWPRS_DATA_ERRATA_FMANd +-//#define FM_PRS_MPLS_SSA_ERRATA_FMANj /* No implementation, No patch yet */ +-//#define FM_PRS_INITIAL_PLANID_ERRATA_FMANk /* No implementation, No patch yet */ + + #define FM_NO_COPY_CTXA_CTXB_ERRATA_FMAN_SW001 + +@@ -260,16 +357,35 @@ typedef enum + /* P2041 */ + #define FM_BAD_VLAN_DETECT_ERRATA_10GMAC_A010 + +-/* Common to all */ ++/* Common to P5020 */ + #define FM_RX_PREAM_4_ERRATA_DTSEC_A001 FM_NO_RX_PREAM_ERRATA_DTSECx1 + #define FM_UCODE_NOT_RESET_ERRATA_BUGZILLA6173 + #define FM_MAGIC_PACKET_UNRECOGNIZED_ERRATA_DTSEC2 /* No implementation, Out of LLD scope */ + #define FM_PRS_MEM_ERRATA_FMAN_SW003 +-#define FM_LEN_CHECK_ERRATA_FMAN_SW002 + +-#define DPAA_VERSION 10 +-#define FM_PCD_SW_PRS_SIZE 0x00000800 +-#define FM_PCD_PRS_SW_PATCHES_SIZE 0x00000200 +-#define FM_NUM_OF_CTRL 2 ++#else /* __aarch64__ — LS1046A / FManv3 errata and features */ ++ ++#define FM_OP_OPEN_DMA_MIN_LIMIT ++#define FM_NO_RESTRICT_ON_ACCESS_RSRC ++#define FM_NO_OP_OBSERVED_POOLS ++#define FM_FRAME_END_PARAMS_FOR_OP ++#define FM_DEQ_PIPELINE_PARAMS_FOR_OP ++#define FM_QMI_NO_SINGLE_ECC_EXCEPTION ++#define FM_NO_GUARANTEED_RESET_VALUES ++ ++/* LS1046A / FManv3 errata */ ++#define FM_HEAVY_TRAFFIC_HANG_ERRATA_FMAN_A005669 ++#define FM_WRONG_RESET_VALUES_ERRATA_FMAN_A005127 ++#define FM_RX_FIFO_CORRUPT_ERRATA_10GMAC_A006320 ++#define FM_OP_NO_VSP_NO_RELEASE_ERRATA_FMAN_A006675 ++#define FM_HEAVY_TRAFFIC_SEQUENCER_HANG_ERRATA_FMAN_A006981 ++#define FM_BCB_ERRATA_BMI_SW001 ++#define FM_AID_MODE_NO_TNUM_SW005 ++#define FM_ERROR_VSP_NO_MATCH_SW006 ++ ++#endif /* __aarch64__ */ ++ ++/* Common to all platforms */ ++#define FM_LEN_CHECK_ERRATA_FMAN_SW002 + + #endif /* __DPAA_INTEGRATION_EXT_H */ +diff --git a/sys/contrib/ncsw/inc/integrations/part_ext.h b/sys/contrib/ncsw/inc/integrations/part_ext.h +index 0fa70299389..614fc499a37 100644 +--- a/sys/contrib/ncsw/inc/integrations/part_ext.h ++++ b/sys/contrib/ncsw/inc/integrations/part_ext.h +@@ -44,8 +44,14 @@ + #include "enet_ext.h" + #include "dpaa_integration_ext.h" + ++#if defined(NCSW_ARM_CORE) ++/* ARM64 — LS1046A has 4x Cortex-A72; no PPC core type */ ++#define INTG_MAX_NUM_OF_CORES 4 ++#else ++/* PowerPC — P5020/P3041/P5040 */ + #define CORE_E500MC + #define INTG_MAX_NUM_OF_CORES 24 ++#endif + + /**************************************************************************//* + @Description Part data structure - must be contained in any integration +diff --git a/sys/contrib/ncsw/inc/types_freebsd.h b/sys/contrib/ncsw/inc/types_freebsd.h +index 031da08e0f7..e37fb2502c2 100644 +--- a/sys/contrib/ncsw/inc/types_freebsd.h ++++ b/sys/contrib/ncsw/inc/types_freebsd.h +@@ -36,7 +36,7 @@ + #include + + #if !defined(__bool_true_false_are_defined) +-typedef boolean_t bool; ++typedef _Bool bool; + #endif + #define TRUE 1 + #define FALSE 0 +@@ -48,22 +48,39 @@ typedef vm_paddr_t physAddress_t; + + /** + * Accessor defines. +- * TODO: These are only stubs and have to be redefined (use bus_space +- * facilities). ++ * DPAA1 registers are big-endian. On PowerPC (big-endian), native ++ * in32/out32 match. On ARM64 (little-endian), use the reverse-byte ++ * variants (in32rb/out32rb) to byte-swap. + */ ++#ifdef __aarch64__ ++#define GET_UINT32(arg) in32rb(&(arg)) ++#define GET_UINT64(arg) in64(&(arg)) ++ ++#define _WRITE_UINT32(arg, data) out32rb(&(arg), (data)) ++#define _WRITE_UINT64(arg, data) out64(&(arg), (data)) ++#else + #define GET_UINT32(arg) in32(&(arg)) + #define GET_UINT64(arg) in64(&(arg)) + + #define _WRITE_UINT32(arg, data) out32(&(arg), (data)) + #define _WRITE_UINT64(arg, data) out64(&(arg), (data)) ++#endif + + #ifndef QE_32_BIT_ACCESS_RESTRICTION + ++#ifdef __aarch64__ ++#define GET_UINT8(arg) in8(&(arg)) ++#define GET_UINT16(arg) in16rb(&(arg)) ++ ++#define _WRITE_UINT8(arg, data) out8(&(arg), (data)) ++#define _WRITE_UINT16(arg, data) out16rb(&(arg), (data)) ++#else + #define GET_UINT8(arg) in8(&(arg)) + #define GET_UINT16(arg) in16(&(arg)) + + #define _WRITE_UINT8(arg, data) out8(&(arg), (data)) + #define _WRITE_UINT16(arg, data) out16(&(arg), (data)) ++#endif + + #else /* QE_32_BIT_ACCESS_RESTRICTION */ + +diff --git a/sys/contrib/ncsw/user/env/core_arm64.c b/sys/contrib/ncsw/user/env/core_arm64.c +new file mode 100644 +index 00000000000..552d6be43ca +--- /dev/null ++++ b/sys/contrib/ncsw/user/env/core_arm64.c +@@ -0,0 +1,60 @@ ++/*- ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * All rights reserved. ++ * ++ * 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 AUTHOR 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 AUTHOR 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. ++ */ ++ ++/* ++ * ARM64 core functions for NetCommSW (DPAA1). ++ * Equivalent to core.c (which provides E500_GetId for PowerPC). ++ */ ++#include ++#include ++#include ++#include ++ ++#include ++ ++#include "types_ext.h" ++#include "core_ext.h" ++ ++uint32_t ++ARM64_GetId(void) ++{ ++ ++ return (PCPU_GET(cpuid)); ++} ++ ++int ++ARM64_TestAndSet(volatile int *p) ++{ ++ ++ return (!atomic_cmpset_int((volatile u_int *)p, 0, 1)); ++} ++ ++void ++ARM64_InstructionSync(void) ++{ ++ ++ __asm __volatile("isb" ::: "memory"); ++} +diff --git a/sys/contrib/ncsw/user/env/xx_arm64.c b/sys/contrib/ncsw/user/env/xx_arm64.c +new file mode 100644 +index 00000000000..a41b0da1897 +--- /dev/null ++++ b/sys/contrib/ncsw/user/env/xx_arm64.c +@@ -0,0 +1,891 @@ ++/*- ++ * Copyright (c) 2011 Semihalf. ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * All rights reserved. ++ * ++ * 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 AUTHOR 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 AUTHOR 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. ++ */ ++ ++/* ++ * NetCommSW (ncsw) environment layer for FreeBSD ARM64. ++ * ++ * Adapted from xx.c (PowerPC version) by Semihalf. Key differences: ++ * ++ * 1. No ccsrbar_va/pa (ARM64 uses FDT-based bus_space mappings) ++ * 2. No law_enable (ARM64 doesn't have Local Access Windows) ++ * 3. No powerpc_intr_mask/unmask (GIC handles interrupt masking) ++ * 4. No TLB1 management (ARM64 uses page tables) ++ * 5. XX_VirtToPhys/XX_PhysToVirt use DMAP exclusively ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include ++#include ++#include ++ ++#include "error_ext.h" ++#include "std_ext.h" ++#include "list_ext.h" ++#include "mm_ext.h" ++ ++/* Configuration */ ++ ++/* Define the number of dTSEC ports active in system */ ++#define MALLOCSMART_DTSEC_IN_USE 4 ++ ++/* ++ * Calculate malloc's pool size for dTSEC's buffers. ++ * We reserve 1MB pool for each dTSEC port. ++ */ ++#define MALLOCSMART_POOL_SIZE \ ++ (MALLOCSMART_DTSEC_IN_USE * 1024 * 1024) ++ ++#define MALLOCSMART_SLICE_SIZE (PAGE_SIZE / 2) /* 2kB */ ++ ++/* Defines */ ++#define MALLOCSMART_SIZE_TO_SLICE(x) \ ++ (((x) + MALLOCSMART_SLICE_SIZE - 1) / MALLOCSMART_SLICE_SIZE) ++#define MALLOCSMART_SLICES \ ++ MALLOCSMART_SIZE_TO_SLICE(MALLOCSMART_POOL_SIZE) ++ ++/* Malloc Pool for NetCommSW */ ++MALLOC_DEFINE(M_NETCOMMSW, "NetCommSW", "NetCommSW software stack"); ++MALLOC_DEFINE(M_NETCOMMSW_MT, "NetCommSWTrack", ++ "NetCommSW software allocation tracker"); ++ ++/* MallocSmart data structures */ ++static void *XX_MallocSmartPool; ++static int XX_MallocSmartMap[MALLOCSMART_SLICES]; ++ ++static struct mtx XX_MallocSmartLock; ++static struct mtx XX_MallocTrackLock; ++MTX_SYSINIT(XX_MallocSmartLockInit, &XX_MallocSmartLock, ++ "NetCommSW MallocSmart Lock", MTX_DEF); ++MTX_SYSINIT(XX_MallocTrackLockInit, &XX_MallocTrackLock, ++ "NetCommSW MallocTrack Lock", MTX_DEF); ++ ++/* Interrupt info */ ++#define XX_INTR_FLAG_PREALLOCATED (1 << 0) ++ ++/* ++ * ARM64 GIC can have many more interrupts than PowerPC (INTR_VECTORS=256). ++ * DPAA1 only uses a handful; 512 is plenty. ++ */ ++#define XX_MAX_INTR 512 ++ ++struct XX_IntrInfo { ++ driver_intr_t *handler; ++ void *arg; ++ int cpu; ++ int flags; ++ void *cookie; ++ /* NAPI mode: non-NULL napi_tq enables FILTER handler */ ++ struct taskqueue *napi_tq; ++ struct task *napi_task; ++ t_Handle napi_portal; ++}; ++ ++static struct XX_IntrInfo XX_IntrInfo[XX_MAX_INTR]; ++ ++/* Portal type identifiers */ ++enum XX_PortalIdent{ ++ BM_PORTAL = 0, ++ QM_PORTAL, ++}; ++ ++/* Structure to store portals' properties */ ++struct XX_PortalInfo { ++ vm_paddr_t portal_ce_pa[2][MAXCPU]; ++ vm_paddr_t portal_ci_pa[2][MAXCPU]; ++ uint32_t portal_ce_size[2][MAXCPU]; ++ uint32_t portal_ci_size[2][MAXCPU]; ++ vm_offset_t portal_ce_va[2]; ++ vm_offset_t portal_ci_va[2]; ++ uintptr_t portal_intr[2][MAXCPU]; ++}; ++ ++static struct XX_PortalInfo XX_PInfo; ++ ++void ++XX_Exit(int status) ++{ ++ ++ panic("NetCommSW: Exit called with status %i", status); ++} ++ ++void ++XX_Print(char *str, ...) ++{ ++ va_list ap; ++ ++ va_start(ap, str); ++ vprintf(str, ap); ++ va_end(ap); ++} ++ ++void * ++XX_Malloc(uint32_t size) ++{ ++ void *p = (malloc(size, M_NETCOMMSW, M_NOWAIT)); ++ ++ return (p); ++} ++ ++static int ++XX_MallocSmartMapCheck(unsigned int start, unsigned int slices) ++{ ++ unsigned int i; ++ ++ mtx_assert(&XX_MallocSmartLock, MA_OWNED); ++ for (i = start; i < start + slices; i++) ++ if (XX_MallocSmartMap[i]) ++ return (FALSE); ++ return (TRUE); ++} ++ ++static void ++XX_MallocSmartMapSet(unsigned int start, unsigned int slices) ++{ ++ unsigned int i; ++ ++ mtx_assert(&XX_MallocSmartLock, MA_OWNED); ++ ++ for (i = start; i < start + slices; i++) ++ XX_MallocSmartMap[i] = ((i == start) ? slices : -1); ++} ++ ++static void ++XX_MallocSmartMapClear(unsigned int start, unsigned int slices) ++{ ++ unsigned int i; ++ ++ mtx_assert(&XX_MallocSmartLock, MA_OWNED); ++ ++ for (i = start; i < start + slices; i++) ++ XX_MallocSmartMap[i] = 0; ++} ++ ++int ++XX_MallocSmartInit(void) ++{ ++ int error; ++ ++ error = E_OK; ++ mtx_lock(&XX_MallocSmartLock); ++ ++ if (XX_MallocSmartPool) ++ goto out; ++ ++ /* Allocate MallocSmart pool */ ++ XX_MallocSmartPool = contigmalloc(MALLOCSMART_POOL_SIZE, M_NETCOMMSW, ++ M_NOWAIT, 0, 0xFFFFFFFFFull, MALLOCSMART_POOL_SIZE, 0); ++ if (!XX_MallocSmartPool) { ++ error = E_NO_MEMORY; ++ goto out; ++ } ++ ++out: ++ mtx_unlock(&XX_MallocSmartLock); ++ return (error); ++} ++ ++void * ++XX_MallocSmart(uint32_t size, int memPartitionId, uint32_t alignment) ++{ ++ unsigned int i; ++ vm_offset_t addr; ++ ++ addr = 0; ++ ++ /* Convert alignment and size to number of slices */ ++ alignment = MALLOCSMART_SIZE_TO_SLICE(alignment); ++ size = MALLOCSMART_SIZE_TO_SLICE(size); ++ ++ /* Lock resources */ ++ mtx_lock(&XX_MallocSmartLock); ++ ++ /* Allocate region */ ++ for (i = 0; i + size <= MALLOCSMART_SLICES; i += alignment) { ++ if (XX_MallocSmartMapCheck(i, size)) { ++ XX_MallocSmartMapSet(i, size); ++ addr = (vm_offset_t)XX_MallocSmartPool + ++ (i * MALLOCSMART_SLICE_SIZE); ++ break; ++ } ++ } ++ ++ /* Unlock resources */ ++ mtx_unlock(&XX_MallocSmartLock); ++ ++ return ((void *)addr); ++} ++ ++void ++XX_FreeSmart(void *p) ++{ ++ unsigned int start, slices; ++ ++ /* Calculate first slice of region */ ++ start = MALLOCSMART_SIZE_TO_SLICE((vm_offset_t)(p) - ++ (vm_offset_t)XX_MallocSmartPool); ++ ++ if (__predict_false(start >= MALLOCSMART_SLICES)) { ++ printf("XX_FreeSmart: %p outside pool (start=%u max=%u)\n", ++ p, start, (unsigned)MALLOCSMART_SLICES); ++ return; ++ } ++ ++ /* Lock resources */ ++ mtx_lock(&XX_MallocSmartLock); ++ ++ KASSERT(XX_MallocSmartMap[start] > 0, ++ ("XX_FreeSmart: Double or mid-block free!\n")); ++ ++ /* Free region */ ++ slices = XX_MallocSmartMap[start]; ++ XX_MallocSmartMapClear(start, slices); ++ ++ /* Unlock resources */ ++ mtx_unlock(&XX_MallocSmartLock); ++} ++ ++void ++XX_Free(void *p) ++{ ++ ++ free(p, M_NETCOMMSW); ++} ++ ++uint32_t ++XX_DisableAllIntr(void) ++{ ++ ++ return (intr_disable()); ++} ++ ++void ++XX_RestoreAllIntr(uint32_t flags) ++{ ++ ++ intr_restore(flags); ++} ++ ++static bool ++XX_IsPortalIntr(uintptr_t irq) ++{ ++ int cpu, type; ++ /* Check interrupt numbers of all available portals */ ++ for (type = 0; type < 2; type++) ++ for (cpu = 0; cpu < MAXCPU; cpu++) ++ if (irq == XX_PInfo.portal_intr[type][cpu]) ++ return (1); ++ ++ return (0); ++} ++ ++static void ++XX_Dispatch(void *arg) ++{ ++ struct XX_IntrInfo *info; ++ ++ info = arg; ++ ++ if (info->handler == NULL) { ++ printf("%s(): IRQ handler is NULL!\n", __func__); ++ return; ++ } ++ ++ info->handler(info->arg); ++} ++ ++/* ++ * FILTER interrupt handler for NAPI-style portal processing. ++ * Runs in hard IRQ context — inhibits portal interrupts at the ++ * source (IIR=1) and schedules a taskqueue task for deferred ++ * DQRR/MR drain. Matches Linux's portal_isr → napi_schedule pattern. ++ */ ++static int ++XX_PortalFilter(void *arg) ++{ ++ struct XX_IntrInfo *info = arg; ++ ++ if (__predict_false(info->napi_portal == NULL)) ++ return (FILTER_STRAY); ++ ++ QM_PORTAL_Inhibit(info->napi_portal); ++ taskqueue_enqueue(info->napi_tq, info->napi_task); ++ ++ return (FILTER_HANDLED); ++} ++ ++/* ++ * Configure NAPI mode for a portal interrupt. Must be called ++ * before QM_PORTAL_Init (which calls XX_SetIntr internally). ++ */ ++void ++XX_ConfigPortalNapi(uintptr_t irq, struct taskqueue *tq, struct task *task) ++{ ++ struct resource *r; ++ unsigned int inum; ++ ++ r = (struct resource *)irq; ++ inum = rman_get_start(r); ++ ++ if (inum >= XX_MAX_INTR) ++ return; ++ ++ XX_IntrInfo[inum].napi_tq = tq; ++ XX_IntrInfo[inum].napi_task = task; ++ XX_IntrInfo[inum].napi_portal = NULL; ++} ++ ++/* ++ * Set the portal handle for a NAPI-configured interrupt. ++ * Called after QM_PORTAL_Init returns the portal handle. ++ */ ++void ++XX_SetPortalNapiHandle(uintptr_t irq, t_Handle portal) ++{ ++ struct resource *r; ++ unsigned int inum; ++ ++ r = (struct resource *)irq; ++ inum = rman_get_start(r); ++ ++ if (inum >= XX_MAX_INTR) ++ return; ++ ++ XX_IntrInfo[inum].napi_portal = portal; ++} ++ ++t_Error ++XX_PreallocAndBindIntr(device_t dev, uintptr_t irq, unsigned int cpu) ++{ ++ struct resource *r; ++ unsigned int inum; ++ ++ r = (struct resource *)irq; ++ inum = rman_get_start(r); ++ ++ if (inum >= XX_MAX_INTR) { ++ printf("NetCommSW: IRQ %u exceeds XX_MAX_INTR (%d)\n", ++ inum, XX_MAX_INTR); ++ return (E_FULL); ++ } ++ ++ /* ++ * Don't call bus_setup_intr here — just record the CPU binding. ++ * The OS interrupt handler will be registered later when the ++ * portal driver calls XX_SetIntr with a real handler. This ++ * prevents interrupt storms from stale portal state on warm ++ * reboot (portal hardware may assert IRQ before the driver ++ * is ready to clear it). ++ */ ++ XX_IntrInfo[inum].flags = XX_INTR_FLAG_PREALLOCATED; ++ XX_IntrInfo[inum].cpu = cpu; ++ ++ return (E_OK); ++} ++ ++t_Error ++XX_DeallocIntr(uintptr_t irq) ++{ ++ struct resource *r; ++ unsigned int inum; ++ ++ r = (struct resource *)irq; ++ inum = rman_get_start(r); ++ ++ if (inum >= XX_MAX_INTR) ++ return (E_INVALID_STATE); ++ ++ if ((XX_IntrInfo[inum].flags & XX_INTR_FLAG_PREALLOCATED) == 0) ++ return (E_INVALID_STATE); ++ ++ XX_IntrInfo[inum].flags = 0; ++ XX_IntrInfo[inum].handler = NULL; ++ XX_IntrInfo[inum].arg = NULL; ++ ++ /* Tear down OS handler only if it was registered */ ++ if (XX_IntrInfo[inum].cookie != NULL) ++ return (XX_FreeIntr(irq)); ++ ++ return (E_OK); ++} ++ ++t_Error ++XX_SetIntr(uintptr_t irq, t_Isr *f_Isr, t_Handle handle) ++{ ++ device_t dev; ++ struct resource *r; ++ unsigned int flags; ++ int err; ++ ++ r = (struct resource *)irq; ++ dev = rman_get_device(r); ++ irq = rman_get_start(r); ++ ++ if (irq >= XX_MAX_INTR) ++ return (E_FULL); ++ ++ /* Handle preallocated interrupts */ ++ if (XX_IntrInfo[irq].flags & XX_INTR_FLAG_PREALLOCATED) { ++ if (XX_IntrInfo[irq].handler != NULL) ++ return (E_BUSY); ++ ++ XX_IntrInfo[irq].handler = f_Isr; ++ XX_IntrInfo[irq].arg = handle; ++ ++ /* Register OS handler now that portal driver is ready */ ++ if (XX_IntrInfo[irq].cookie == NULL) { ++ unsigned int iflags; ++ int err; ++ ++ iflags = INTR_TYPE_NET | INTR_MPSAFE; ++ if (XX_IsPortalIntr(irq)) ++ iflags |= INTR_EXCL; ++ ++ if (XX_IntrInfo[irq].napi_tq != NULL) { ++ /* NAPI mode: FILTER-only, no ithread */ ++ err = bus_setup_intr(dev, r, iflags, ++ XX_PortalFilter, NULL, ++ &XX_IntrInfo[irq], ++ &XX_IntrInfo[irq].cookie); ++ } else { ++ /* Legacy ithread mode */ ++ err = bus_setup_intr(dev, r, iflags, NULL, ++ XX_Dispatch, &XX_IntrInfo[irq], ++ &XX_IntrInfo[irq].cookie); ++ } ++ if (err) ++ return (E_NOT_AVAILABLE); ++ ++ bus_bind_intr(dev, r, XX_IntrInfo[irq].cpu); ++ } ++ ++ return (E_OK); ++ } ++ ++ flags = INTR_TYPE_NET | INTR_MPSAFE; ++ ++ /* BMAN/QMAN Portal interrupts must be exclusive */ ++ if (XX_IsPortalIntr(irq)) ++ flags |= INTR_EXCL; ++ ++ err = bus_setup_intr(dev, r, flags, NULL, f_Isr, handle, ++ &XX_IntrInfo[irq].cookie); ++ ++ return (err); ++} ++ ++t_Error ++XX_FreeIntr(uintptr_t irq) ++{ ++ device_t dev; ++ struct resource *r; ++ ++ r = (struct resource *)irq; ++ dev = rman_get_device(r); ++ irq = rman_get_start(r); ++ ++ if (irq >= XX_MAX_INTR) ++ return (E_INVALID_STATE); ++ ++ /* Handle preallocated interrupts */ ++ if (XX_IntrInfo[irq].flags & XX_INTR_FLAG_PREALLOCATED) { ++ if (XX_IntrInfo[irq].handler == NULL) ++ return (E_INVALID_STATE); ++ ++ XX_IntrInfo[irq].handler = NULL; ++ XX_IntrInfo[irq].arg = NULL; ++ ++ return (E_OK); ++ } ++ ++ return (bus_teardown_intr(dev, r, XX_IntrInfo[irq].cookie)); ++} ++ ++t_Error ++XX_EnableIntr(uintptr_t irq) ++{ ++ /* ++ * On ARM64 with GIC, interrupt masking/unmasking is handled ++ * by the interrupt framework. Portal interrupts are set up ++ * with INTR_EXCL; the GIC re-enables them after handler return. ++ */ ++ (void)irq; ++ return (E_OK); ++} ++ ++t_Error ++XX_DisableIntr(uintptr_t irq) ++{ ++ /* ++ * See XX_EnableIntr — no explicit mask needed on ARM64. ++ */ ++ (void)irq; ++ return (E_OK); ++} ++ ++t_TaskletHandle ++XX_InitTasklet (void (*routine)(void *), void *data) ++{ ++ /* Not referenced */ ++ printf("NetCommSW: Unimplemented function %s() called!\n", __func__); ++ return (NULL); ++} ++ ++ ++void ++XX_FreeTasklet (t_TaskletHandle h_Tasklet) ++{ ++ /* Not referenced */ ++ printf("NetCommSW: Unimplemented function %s() called!\n", __func__); ++} ++ ++int ++XX_ScheduleTask(t_TaskletHandle h_Tasklet, int immediate) ++{ ++ /* Not referenced */ ++ printf("NetCommSW: Unimplemented function %s() called!\n", __func__); ++ return (0); ++} ++ ++void ++XX_FlushScheduledTasks(void) ++{ ++ /* Not referenced */ ++ printf("NetCommSW: Unimplemented function %s() called!\n", __func__); ++} ++ ++int ++XX_TaskletIsQueued(t_TaskletHandle h_Tasklet) ++{ ++ /* Not referenced */ ++ printf("NetCommSW: Unimplemented function %s() called!\n", __func__); ++ return (0); ++} ++ ++void ++XX_SetTaskletData(t_TaskletHandle h_Tasklet, t_Handle data) ++{ ++ /* Not referenced */ ++ printf("NetCommSW: Unimplemented function %s() called!\n", __func__); ++} ++ ++t_Handle ++XX_GetTaskletData(t_TaskletHandle h_Tasklet) ++{ ++ /* Not referenced */ ++ printf("NetCommSW: Unimplemented function %s() called!\n", __func__); ++ return (NULL); ++} ++ ++t_Handle ++XX_InitSpinlock(void) ++{ ++ struct mtx *m; ++ ++ m = malloc(sizeof(*m), M_NETCOMMSW, M_NOWAIT | M_ZERO); ++ if (!m) ++ return (0); ++ ++ mtx_init(m, "NetCommSW Lock", NULL, MTX_DEF | MTX_DUPOK); ++ ++ return (m); ++} ++ ++void ++XX_FreeSpinlock(t_Handle h_Spinlock) ++{ ++ struct mtx *m; ++ ++ m = h_Spinlock; ++ ++ mtx_destroy(m); ++ free(m, M_NETCOMMSW); ++} ++ ++void ++XX_LockSpinlock(t_Handle h_Spinlock) ++{ ++ struct mtx *m; ++ ++ m = h_Spinlock; ++ mtx_lock(m); ++} ++ ++void ++XX_UnlockSpinlock(t_Handle h_Spinlock) ++{ ++ struct mtx *m; ++ ++ m = h_Spinlock; ++ mtx_unlock(m); ++} ++ ++uint32_t ++XX_LockIntrSpinlock(t_Handle h_Spinlock) ++{ ++ ++ XX_LockSpinlock(h_Spinlock); ++ return (0); ++} ++ ++void ++XX_UnlockIntrSpinlock(t_Handle h_Spinlock, uint32_t intrFlags) ++{ ++ ++ XX_UnlockSpinlock(h_Spinlock); ++} ++ ++uint32_t ++XX_Sleep(uint32_t msecs) ++{ ++ ++ XX_UDelay(1000 * msecs); ++ return (0); ++} ++ ++void ++XX_UDelay(uint32_t usecs) ++{ ++ DELAY(usecs); ++} ++ ++t_Error ++XX_IpcRegisterMsgHandler(char addr[XX_IPC_MAX_ADDR_NAME_LENGTH], ++ t_IpcMsgHandler *f_MsgHandler, t_Handle h_Module, uint32_t replyLength) ++{ ++ ++ /* ++ * This function returns fake E_OK status and does nothing ++ * as NetCommSW IPC is not used by FreeBSD drivers. ++ */ ++ return (E_OK); ++} ++ ++t_Error ++XX_IpcUnregisterMsgHandler(char addr[XX_IPC_MAX_ADDR_NAME_LENGTH]) ++{ ++ /* ++ * This function returns fake E_OK status and does nothing ++ * as NetCommSW IPC is not used by FreeBSD drivers. ++ */ ++ return (E_OK); ++} ++ ++ ++t_Error ++XX_IpcSendMessage(t_Handle h_Session, ++ uint8_t *p_Msg, uint32_t msgLength, uint8_t *p_Reply, ++ uint32_t *p_ReplyLength, t_IpcMsgCompletion *f_Completion, t_Handle h_Arg) ++{ ++ ++ /* Should not be called */ ++ printf("NetCommSW: Unimplemented function %s() called!\n", __func__); ++ return (E_OK); ++} ++ ++t_Handle ++XX_IpcInitSession(char destAddr[XX_IPC_MAX_ADDR_NAME_LENGTH], ++ char srcAddr[XX_IPC_MAX_ADDR_NAME_LENGTH]) ++{ ++ ++ /* Should not be called */ ++ printf("NetCommSW: Unimplemented function %s() called!\n", __func__); ++ return (NULL); ++} ++ ++t_Error ++XX_IpcFreeSession(t_Handle h_Session) ++{ ++ ++ /* Should not be called */ ++ printf("NetCommSW: Unimplemented function %s() called!\n", __func__); ++ return (E_OK); ++} ++ ++physAddress_t ++XX_VirtToPhys(void *addr) ++{ ++ vm_paddr_t paddr; ++ int cpu; ++ ++ cpu = PCPU_GET(cpuid); ++ ++ /* Handle NULL address */ ++ if (addr == NULL) ++ return (-1); ++ ++ /* ++ * No CCSR check needed on ARM64 — registers are mapped via ++ * bus_space, not through a global ccsrbar mapping. ++ */ ++ ++ /* Handle BMAN mappings */ ++ if (((vm_offset_t)addr >= XX_PInfo.portal_ce_va[BM_PORTAL]) && ++ ((vm_offset_t)addr < XX_PInfo.portal_ce_va[BM_PORTAL] + ++ XX_PInfo.portal_ce_size[BM_PORTAL][cpu])) ++ return (XX_PInfo.portal_ce_pa[BM_PORTAL][cpu] + ++ (vm_offset_t)addr - XX_PInfo.portal_ce_va[BM_PORTAL]); ++ ++ if (((vm_offset_t)addr >= XX_PInfo.portal_ci_va[BM_PORTAL]) && ++ ((vm_offset_t)addr < XX_PInfo.portal_ci_va[BM_PORTAL] + ++ XX_PInfo.portal_ci_size[BM_PORTAL][cpu])) ++ return (XX_PInfo.portal_ci_pa[BM_PORTAL][cpu] + ++ (vm_offset_t)addr - XX_PInfo.portal_ci_va[BM_PORTAL]); ++ ++ /* Handle QMAN mappings */ ++ if (((vm_offset_t)addr >= XX_PInfo.portal_ce_va[QM_PORTAL]) && ++ ((vm_offset_t)addr < XX_PInfo.portal_ce_va[QM_PORTAL] + ++ XX_PInfo.portal_ce_size[QM_PORTAL][cpu])) ++ return (XX_PInfo.portal_ce_pa[QM_PORTAL][cpu] + ++ (vm_offset_t)addr - XX_PInfo.portal_ce_va[QM_PORTAL]); ++ ++ if (((vm_offset_t)addr >= XX_PInfo.portal_ci_va[QM_PORTAL]) && ++ ((vm_offset_t)addr < XX_PInfo.portal_ci_va[QM_PORTAL] + ++ XX_PInfo.portal_ci_size[QM_PORTAL][cpu])) ++ return (XX_PInfo.portal_ci_pa[QM_PORTAL][cpu] + ++ (vm_offset_t)addr - XX_PInfo.portal_ci_va[QM_PORTAL]); ++ ++ /* ARM64 always has DMAP */ ++ if ((vm_offset_t)addr >= DMAP_MIN_ADDRESS && ++ (vm_offset_t)addr < DMAP_MAX_ADDRESS) ++ return (DMAP_TO_PHYS((vm_offset_t)addr)); ++ ++ paddr = pmap_kextract((vm_offset_t)addr); ++ ++ if (paddr == 0) ++ printf("NetCommSW: " ++ "Unable to translate virtual address %p!\n", addr); ++ ++ return (paddr); ++} ++ ++void * ++XX_PhysToVirt(physAddress_t addr) ++{ ++ int cpu; ++ ++ cpu = PCPU_GET(cpuid); ++ ++ /* ++ * No CCSR check needed on ARM64 — see XX_VirtToPhys comment. ++ */ ++ ++ /* Handle BMAN mappings */ ++ if ((addr >= XX_PInfo.portal_ce_pa[BM_PORTAL][cpu]) && ++ (addr < XX_PInfo.portal_ce_pa[BM_PORTAL][cpu] + ++ XX_PInfo.portal_ce_size[BM_PORTAL][cpu])) ++ return ((void *)(XX_PInfo.portal_ce_va[BM_PORTAL] + ++ (vm_offset_t)(addr - XX_PInfo.portal_ce_pa[BM_PORTAL][cpu]))); ++ ++ if ((addr >= XX_PInfo.portal_ci_pa[BM_PORTAL][cpu]) && ++ (addr < XX_PInfo.portal_ci_pa[BM_PORTAL][cpu] + ++ XX_PInfo.portal_ci_size[BM_PORTAL][cpu])) ++ return ((void *)(XX_PInfo.portal_ci_va[BM_PORTAL] + ++ (vm_offset_t)(addr - XX_PInfo.portal_ci_pa[BM_PORTAL][cpu]))); ++ ++ /* Handle QMAN mappings */ ++ if ((addr >= XX_PInfo.portal_ce_pa[QM_PORTAL][cpu]) && ++ (addr < XX_PInfo.portal_ce_pa[QM_PORTAL][cpu] + ++ XX_PInfo.portal_ce_size[QM_PORTAL][cpu])) ++ return ((void *)(XX_PInfo.portal_ce_va[QM_PORTAL] + ++ (vm_offset_t)(addr - XX_PInfo.portal_ce_pa[QM_PORTAL][cpu]))); ++ ++ if ((addr >= XX_PInfo.portal_ci_pa[QM_PORTAL][cpu]) && ++ (addr < XX_PInfo.portal_ci_pa[QM_PORTAL][cpu] + ++ XX_PInfo.portal_ci_size[QM_PORTAL][cpu])) ++ return ((void *)(XX_PInfo.portal_ci_va[QM_PORTAL] + ++ (vm_offset_t)(addr - XX_PInfo.portal_ci_pa[QM_PORTAL][cpu]))); ++ ++ /* ++ * Reject PA outside DRAM range (catches stale FD addresses from ++ * a previous boot and PA=0 which maps below dmap_phys_base). ++ */ ++ if (__predict_false(!PHYS_IN_DMAP_RANGE(addr))) ++ return (NULL); ++ return ((void *)(uintptr_t)PHYS_TO_DMAP(addr)); ++} ++ ++void ++XX_PortalSetInfo(device_t dev) ++{ ++ struct dpaa_portals_softc *sc; ++ const char *dev_name; ++ int i, type; ++ ++ dev_name = device_get_name(dev); ++ ++ if (strcmp(dev_name, "bman-portals") == 0) ++ type = BM_PORTAL; ++ else if (strcmp(dev_name, "qman-portals") == 0) ++ type = QM_PORTAL; ++ else ++ return; ++ ++ sc = device_get_softc(dev); ++ ++ for (i = 0; i < MAXCPU && sc->sc_dp[i].dp_ce_pa != 0; i++) { ++ XX_PInfo.portal_ce_pa[type][i] = sc->sc_dp[i].dp_ce_pa; ++ XX_PInfo.portal_ci_pa[type][i] = sc->sc_dp[i].dp_ci_pa; ++ XX_PInfo.portal_ce_size[type][i] = sc->sc_dp[i].dp_ce_size; ++ XX_PInfo.portal_ci_size[type][i] = sc->sc_dp[i].dp_ci_size; ++ XX_PInfo.portal_intr[type][i] = sc->sc_dp[i].dp_intr_num; ++ } ++ ++ XX_PInfo.portal_ce_va[type] = rman_get_bushandle(sc->sc_rres[0]); ++ XX_PInfo.portal_ci_va[type] = rman_get_bushandle(sc->sc_rres[1]); ++} ++ ++/* ++ * Stub for dead FManv3 clock-change code in fm_ncsw.c (FM_ChangeClock). ++ * fm_clk_down() is referenced but defined under #ifdef TODO_SOC_SUSPEND ++ * in fm_port.c — never compiled. g_MemacRegs is provided by memac.c. ++ */ ++void ++fm_clk_down(void) ++{ ++ printf("NetCommSW: fm_clk_down() stub called — not implemented\n"); ++} +diff --git a/sys/dev/caam/caam.c b/sys/dev/caam/caam.c +new file mode 100644 +index 00000000000..a0a554ddb3b +--- /dev/null ++++ b/sys/dev/caam/caam.c +@@ -0,0 +1,858 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * NXP CAAM (Cryptographic Acceleration and Assurance Module) controller driver. ++ * ++ * The CAAM controller (SEC v4.0+) acts as a simplebus parent that enumerates ++ * Job Ring child devices from the device tree. It also detects hardware ++ * version, register endianness, and DMA pointer size. ++ * ++ * Child Job Ring devices need to map sub-ranges of the controller's 1MB ++ * register space. Since the controller allocates the full region from the ++ * parent bus, we use a local resource manager (rman) to subdivide it for ++ * children — the same pattern used by FMan (sys/dev/dpaa/fman.c). ++ * ++ * Matches: "fsl,sec-v4.0" (broadest compatible for SEC v4.0/v5.0/v5.4) ++ * DT node: crypto@1700000 with #address-cells=1, #size-cells=1, ranges ++ * ++ * This is a clean-room implementation based on the NXP SEC reference manual. ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include "caam.h" ++#include "caam_regs.h" ++#include "caam_desc.h" ++ ++/* ++ * Global endianness flag — set once during controller attach. ++ * Used by all CAAM byte-order conversion helpers. ++ */ ++bool caam_big_endian; ++ ++static struct ofw_compat_data caam_compat[] = { ++ { "fsl,sec-v4.0", 1 }, ++ { NULL, 0 } ++}; ++ ++static int ++caam_probe(device_t dev) ++{ ++ ++ if (!ofw_bus_status_okay(dev)) ++ return (ENXIO); ++ ++ if (ofw_bus_search_compatible(dev, caam_compat)->ocd_data == 0) ++ return (ENXIO); ++ ++ device_set_desc(dev, "NXP CAAM crypto accelerator"); ++ return (BUS_PROBE_SPECIFIC); ++} ++ ++/* ++ * Run a descriptor on DECO0 directly (without a Job Ring). ++ * ++ * 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. ++ * ++ * Returns 0 on success; *status receives the DECO operation status. ++ */ ++static int ++caam_run_deco0(struct caam_softc *sc, uint32_t *desc, int nwords, ++ uint32_t *status) ++{ ++ bus_size_t deco = sc->sc_deco0_off; ++ uint32_t val; ++ int i, timeout; ++ ++ *status = 0; ++ ++ /* ++ * Step 1: Acquire DECO0. ++ * Write JR0 as request source, poll for VALID. ++ */ ++ CAAM_WRITE(sc, CAAM_DECORSR, DECORSR_JR0); ++ for (timeout = 10000; timeout > 0; timeout--) { ++ val = CAAM_READ(sc, CAAM_DECORSR); ++ if (val & DECORSR_VALID) ++ break; ++ DELAY(10); ++ } ++ if (timeout <= 0) { ++ device_printf(sc->sc_base.dev, ++ "DECO0: timeout waiting for DECORSR VALID\n"); ++ return (ETIMEDOUT); ++ } ++ ++ /* ++ * Step 2: Request DECO0 for direct access. ++ * Set RQD0ENABLE, poll for DEN0. ++ */ ++ CAAM_WRITE(sc, CAAM_DECORR, DECORR_RQD0ENABLE); ++ for (timeout = 10000; timeout > 0; timeout--) { ++ val = CAAM_READ(sc, CAAM_DECORR); ++ if (val & DECORR_DEN0) ++ break; ++ DELAY(10); ++ } ++ if (timeout <= 0) { ++ device_printf(sc->sc_base.dev, ++ "DECO0: timeout waiting for DECORR DEN0\n"); ++ /* Release DECORSR */ ++ CAAM_WRITE(sc, CAAM_DECORSR, 0); ++ return (ETIMEDOUT); ++ } ++ ++ /* ++ * Step 3: Load descriptor into DECO0 descriptor buffer. ++ */ ++ for (i = 0; i < nwords; i++) ++ CAAM_WRITE(sc, deco + DECO_DESCBUF(i), desc[i]); ++ ++ /* ++ * Step 4: Trigger execution. ++ * WHL = whole descriptor (not a link), FOUR = descriptor >= 4 words. ++ */ ++ val = DECO_JQCR_WHL; ++ if (nwords >= 4) ++ val |= DECO_JQCR_FOUR; ++ CAAM_WRITE(sc, deco + DECO_JR_CTL_HI, val); ++ ++ /* ++ * Step 5: Poll for completion. ++ * The DESC_DBG register's VALID bit (31) clears when done, or ++ * the status field shows HOST_ERR (0xD) on error. ++ */ ++ for (timeout = 100000; timeout > 0; timeout--) { ++ val = CAAM_READ(sc, deco + DECO_DESC_DBG); ++ if (!(val & DESC_DBG_DECO_STAT_VALID)) ++ break; ++ if (((val & DESC_DBG_DECO_STAT_MASK) >> ++ DESC_DBG_DECO_STAT_SHIFT) == DECO_STAT_HOST_ERR) ++ break; ++ DELAY(10); ++ } ++ if (timeout <= 0) { ++ device_printf(sc->sc_base.dev, ++ "DECO0: timeout waiting for descriptor completion\n"); ++ } ++ ++ /* ++ * Step 6: Read operation status. ++ */ ++ *status = CAAM_READ(sc, deco + DECO_OP_STATUS_HI); ++ ++ /* ++ * Step 7: Release DECO0. ++ */ ++ val = CAAM_READ(sc, CAAM_DECORR); ++ CAAM_WRITE(sc, CAAM_DECORR, val & ~DECORR_RQD0ENABLE); ++ ++ return (0); ++} ++ ++/* ++ * Configure the TRNG (True Random Number Generator). ++ * ++ * Programs entropy sampling delay, frequency count limits, and ++ * statistical self-test parameters. Matches Linux's kick_trng(). ++ */ ++static void ++caam_kick_trng(struct caam_softc *sc, uint32_t ent_delay) ++{ ++ uint32_t rtsdctl, cur_delay; ++ ++ /* ++ * Enter program mode: set PRGM and ACC bits in RTMCTL. ++ * This invalidates current entropy and forces re-generation. ++ */ ++ CAAM_WRITE(sc, CAAM_RTMCTL, ++ CAAM_READ(sc, CAAM_RTMCTL) | RTMCTL_PRGM | RTMCTL_ACC); ++ ++ /* ++ * Only increase the entropy delay — never decrease it, ++ * as the current value may have been raised for good reason. ++ */ ++ rtsdctl = CAAM_READ(sc, CAAM_RTSDCTL); ++ cur_delay = (rtsdctl & RTSDCTL_ENT_DLY_MASK) >> RTSDCTL_ENT_DLY_SHIFT; ++ if (ent_delay > cur_delay) { ++ cur_delay = ent_delay; ++ /* Minimum frequency count = 1/4 of entropy sample length */ ++ CAAM_WRITE(sc, CAAM_RTFRQMIN, cur_delay >> 2); ++ /* Disable maximum frequency count */ ++ CAAM_WRITE(sc, CAAM_RTFRQMAX, RTFRQMAX_DISABLE); ++ } ++ ++ CAAM_WRITE(sc, CAAM_RTSDCTL, ++ (cur_delay << RTSDCTL_ENT_DLY_SHIFT) | RTSDCTL_SAMP_SIZE_VAL); ++ ++ /* ++ * Program self-test parameters on first call. ++ * Use SAMP_SIZE as indicator: if it hasn't been set to our ++ * value yet, this is the first configuration. ++ */ ++ if ((rtsdctl & RTSDCTL_SAMP_SIZE_MASK) != RTSDCTL_SAMP_SIZE_VAL) { ++ CAAM_WRITE(sc, CAAM_RTSCMISC, (2 << 16) | 32); ++ CAAM_WRITE(sc, CAAM_RTPKRRNG, 570); ++ CAAM_WRITE(sc, CAAM_RTPKRMAX, 1600); ++ CAAM_WRITE(sc, CAAM_RTSCML, (122 << 16) | 317); ++ CAAM_WRITE(sc, CAAM_RTSCRL(0), (80 << 16) | 107); ++ CAAM_WRITE(sc, CAAM_RTSCRL(1), (57 << 16) | 62); ++ CAAM_WRITE(sc, CAAM_RTSCRL(2), (39 << 16) | 39); ++ CAAM_WRITE(sc, CAAM_RTSCRL(3), (27 << 16) | 26); ++ CAAM_WRITE(sc, CAAM_RTSCRL(4), (19 << 16) | 18); ++ CAAM_WRITE(sc, CAAM_RTSCRL(5), (18 << 16) | 17); ++ } ++ ++ /* ++ * Exit program mode: clear PRGM and ACC, enable raw sampling ++ * in both entropy shifter and statistical checker. ++ */ ++ CAAM_WRITE(sc, CAAM_RTMCTL, ++ (CAAM_READ(sc, CAAM_RTMCTL) & ~(RTMCTL_PRGM | RTMCTL_ACC)) | ++ RTMCTL_SAMP_MODE_RAW); ++} ++ ++/* ++ * Build an RNG state handle instantiation descriptor. ++ * ++ * For SH0 with gen_sk=1: 7 words (also generates secure keys JDKEK/TDKEK/TDSK). ++ * For SH1 (or SH0 without gen_sk): 3 words. ++ * ++ * Returns the number of descriptor words. ++ */ ++static int ++caam_build_rng_inst_desc(uint32_t *desc, int handle, int gen_sk) ++{ ++ int idx = 0; ++ ++ if (handle == 0 && gen_sk) { ++ /* SH0 with secure key generation — 7 words */ ++ desc[idx++] = CMD_DESC_HDR | 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; ++ ++ /* JUMP: wait for Class 1 done (skip 1 word) */ ++ desc[idx++] = CMD_JUMP | 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++] = 1; ++ ++ /* Generate secure keys (JDKEK, TDKEK, TDSK) */ ++ desc[idx++] = OP_TYPE_CLASS1_ALG | OP_ALG_ALGSEL_RNG | ++ OP_ALG_AAI_RNG4_SK; ++ ++ /* Halt */ ++ desc[idx++] = CMD_JUMP | JUMP_CLASS_CLASS1 | JUMP_TYPE_HALT; ++ } else { ++ /* SH0 without gen_sk or SH1 — 3 words */ ++ desc[idx++] = CMD_DESC_HDR | 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; ++ ++ /* Halt */ ++ desc[idx++] = CMD_JUMP | JUMP_CLASS_CLASS1 | JUMP_TYPE_HALT; ++ } ++ ++ return (idx); ++} ++ ++/* ++ * Build an RNG state handle deinstantiation descriptor. ++ * ++ * Deinstantiates all state handles indicated by the mask bits. ++ * Used when U-Boot instantiated handles without prediction resistance ++ * and we need to re-instantiate with PR enabled. ++ * ++ * Returns the number of descriptor words. ++ */ ++static int ++caam_build_rng_deinst_desc(uint32_t *desc, uint32_t sh_mask) ++{ ++ int idx = 0; ++ ++ desc[idx++] = CMD_DESC_HDR | 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++] = CMD_JUMP | JUMP_CLASS_CLASS1 | JUMP_TYPE_HALT; ++ ++ return (idx); ++} ++ ++/* ++ * Initialize the RNG: configure TRNG, instantiate state handles. ++ * ++ * Called from caam_attach() after JRSTART. Retry with increasing ++ * entropy delay if instantiation fails (3200 -> 6400 -> 12800). ++ * ++ * If U-Boot already instantiated state handles without prediction ++ * resistance, deinstantiate them first, then re-instantiate with PR. ++ */ ++static int ++caam_rng_init(struct caam_softc *sc) ++{ ++ uint32_t rdsta, desc[8], status; ++ uint32_t ent_delay = RTSDCTL_ENT_DLY_MIN; ++ uint32_t rdsta_if, rdsta_pr, deinst_mask; ++ int gen_sk, ret, nwords; ++ ++ /* Check which state handles are already instantiated */ ++ rdsta = CAAM_READ(sc, CAAM_RDSTA); ++ device_printf(sc->sc_base.dev, "RNG: initial RDSTA = 0x%08x\n", rdsta); ++ ++ /* If secure keys not yet valid, first SH0 instantiation must gen them */ ++ gen_sk = (rdsta & RDSTA_SKVN) ? 0 : 1; ++ ++ /* ++ * 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 ++ * any handle that has IF set but PR clear. ++ */ ++ rdsta_if = rdsta & (RDSTA_IF0 | RDSTA_IF1); ++ rdsta_pr = rdsta & (RDSTA_PR0 | RDSTA_PR1); ++ ++ /* Build mask of handles that need deinstantiation (IF set, PR clear) */ ++ deinst_mask = 0; ++ if ((rdsta_if & RDSTA_IF0) && !(rdsta_pr & RDSTA_PR0)) ++ deinst_mask |= RDSTA_IF0; /* SH0 bit = AAI bit 0 */ ++ if ((rdsta_if & RDSTA_IF1) && !(rdsta_pr & RDSTA_PR1)) ++ deinst_mask |= RDSTA_IF1; /* SH1 bit = AAI bit 1 */ ++ ++ if (deinst_mask != 0) { ++ device_printf(sc->sc_base.dev, ++ "RNG: deinstantiating handles without PR (mask 0x%x)\n", ++ deinst_mask); ++ ++ nwords = caam_build_rng_deinst_desc(desc, deinst_mask); ++ ret = caam_run_deco0(sc, desc, nwords, &status); ++ if (ret != 0) { ++ device_printf(sc->sc_base.dev, ++ "RNG: DECO0 error during deinstantiation\n"); ++ return (ret); ++ } ++ ++ if (status != 0 && status != JRSTA_SSRC_JUMP_HALT_CC) { ++ device_printf(sc->sc_base.dev, ++ "RNG: deinstantiation failed, status 0x%08x\n", ++ status); ++ return (EIO); ++ } ++ ++ rdsta = CAAM_READ(sc, CAAM_RDSTA); ++ device_printf(sc->sc_base.dev, ++ "RNG: RDSTA after deinstantiation = 0x%08x\n", rdsta); ++ } ++ ++ do { ++ uint32_t inst_handles; ++ ++ inst_handles = CAAM_READ(sc, CAAM_RDSTA); ++ rdsta_if = inst_handles & (RDSTA_IF0 | RDSTA_IF1); ++ rdsta_pr = inst_handles & (RDSTA_PR0 | RDSTA_PR1); ++ inst_handles &= RDSTA_MASK; ++ ++ /* Configure TRNG if no handles instantiated yet */ ++ if (rdsta_if == 0) { ++ device_printf(sc->sc_base.dev, ++ "RNG: entropy delay = %u\n", ent_delay); ++ caam_kick_trng(sc, ent_delay); ++ ent_delay *= 2; ++ } ++ ++ ret = 0; ++ ++ /* ++ * Instantiate SH0 if not fully done (need both IF0 and PR0). ++ */ ++ if (!((rdsta_if & RDSTA_IF0) && (rdsta_pr & RDSTA_PR0))) { ++ nwords = caam_build_rng_inst_desc(desc, 0, gen_sk); ++ ret = caam_run_deco0(sc, desc, nwords, &status); ++ if (ret != 0) ++ break; ++ ++ if (status != 0 && ++ status != JRSTA_SSRC_JUMP_HALT_CC) { ++ device_printf(sc->sc_base.dev, ++ "RNG: SH0 instantiation failed, " ++ "status 0x%08x\n", status); ++ ret = EAGAIN; ++ continue; ++ } ++ ++ /* Verify SH0 instantiated with PR */ ++ rdsta = CAAM_READ(sc, CAAM_RDSTA); ++ if ((rdsta & (RDSTA_IF0 | RDSTA_PR0)) != ++ (RDSTA_IF0 | RDSTA_PR0)) { ++ device_printf(sc->sc_base.dev, ++ "RNG: SH0 not confirmed, RDSTA=0x%08x\n", ++ rdsta); ++ ret = EAGAIN; ++ continue; ++ } ++ device_printf(sc->sc_base.dev, ++ "RNG: state handle 0 instantiated (PR)\n"); ++ } ++ ++ /* ++ * Instantiate SH1 if not fully done (need both IF1 and PR1). ++ */ ++ if (!((rdsta_if & RDSTA_IF1) && (rdsta_pr & RDSTA_PR1))) { ++ nwords = caam_build_rng_inst_desc(desc, 1, 0); ++ ret = caam_run_deco0(sc, desc, nwords, &status); ++ if (ret != 0) ++ break; ++ ++ if (status != 0 && ++ status != JRSTA_SSRC_JUMP_HALT_CC) { ++ device_printf(sc->sc_base.dev, ++ "RNG: SH1 instantiation failed, " ++ "status 0x%08x\n", status); ++ ret = EAGAIN; ++ continue; ++ } ++ ++ /* Verify SH1 instantiated with PR */ ++ rdsta = CAAM_READ(sc, CAAM_RDSTA); ++ if ((rdsta & (RDSTA_IF1 | RDSTA_PR1)) != ++ (RDSTA_IF1 | RDSTA_PR1)) { ++ device_printf(sc->sc_base.dev, ++ "RNG: SH1 not confirmed, RDSTA=0x%08x\n", ++ rdsta); ++ ret = EAGAIN; ++ continue; ++ } ++ device_printf(sc->sc_base.dev, ++ "RNG: state handle 1 instantiated (PR)\n"); ++ } ++ ++ break; /* Both handles fully instantiated with PR */ ++ ++ } while (ret == EAGAIN && ent_delay <= RTSDCTL_ENT_DLY_MAX); ++ ++ if (ret != 0) { ++ device_printf(sc->sc_base.dev, ++ "RNG: failed to instantiate state handles\n"); ++ return (ret); ++ } ++ ++ rdsta = CAAM_READ(sc, CAAM_RDSTA); ++ device_printf(sc->sc_base.dev, ++ "RNG: initialized, RDSTA = 0x%08x\n", rdsta); ++ ++ /* Enable RDB for faster RNG operation */ ++ CAAM_WRITE(sc, CAAM_SCFGR, ++ CAAM_READ(sc, CAAM_SCFGR) | SCFGR_RDBENABLE); ++ ++ sc->sc_rng_inited = true; ++ return (0); ++} ++ ++int ++caam_attach(device_t dev) ++{ ++ struct caam_softc *sc; ++ phandle_t node; ++ uint32_t csta, ctpr, ccbvid, chanum_ls; ++ pcell_t era; ++ int error, maj, min; ++ ++ sc = device_get_softc(dev); ++ sc->sc_base.dev = dev; ++ ++ /* Map CCSR register space (1MB) */ ++ sc->sc_rrid = 0; ++ sc->sc_rres = bus_alloc_resource_any(dev, SYS_RES_MEMORY, ++ &sc->sc_rrid, RF_ACTIVE | RF_SHAREABLE); ++ if (sc->sc_rres == NULL) { ++ device_printf(dev, "cannot map register space\n"); ++ return (ENXIO); ++ } ++ ++ /* ++ * Detect register endianness. ++ * ++ * CAAM's CSTA register contains PLEND/ALT_PLEND bits that indicate ++ * whether the platform is little-endian. On QorIQ Layerscape SoCs, ++ * CAAM registers are ALWAYS big-endian (legacy from PowerPC era), ++ * regardless of the CPU's byte order. ++ * ++ * The detection matches Linux's 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 ++ * ++ * On LS1046A ARM64 (LE CPU): PLEND=1, caam_big_endian=true → swap ++ * On PowerPC (BE CPU): PLEND=0, caam_big_endian=false → no swap ++ */ ++ csta = be32toh(bus_read_4(sc->sc_rres, CAAM_CSTA)); ++ caam_big_endian = (csta & (CSTA_PLEND | CSTA_ALT_PLEND)) != 0; ++ ++ /* Read compile-time parameters */ ++ ctpr = CAAM_READ(sc, CAAM_CTPR_MS); ++ if (ctpr & CTPR_MS_PS) ++ device_printf(dev, "64-bit DMA pointer mode\n"); ++ ++ /* Read ERA from DT (preferred) or from hardware */ ++ node = ofw_bus_get_node(dev); ++ if (OF_getencprop(node, "fsl,sec-era", &era, sizeof(era)) > 0) { ++ sc->sc_era = era; ++ } else { ++ ccbvid = CAAM_READ(sc, CAAM_CCBVID); ++ sc->sc_era = (ccbvid & CCBVID_ERA_MASK) >> CCBVID_ERA_SHIFT; ++ } ++ ++ /* Read version info */ ++ chanum_ls = CAAM_READ(sc, CAAM_CHANUM_LS); ++ ccbvid = CAAM_READ(sc, CAAM_CCBVID); ++ maj = (CAAM_READ(sc, CAAM_CAAMVID_MS) & SECVID_MS_MAJ_REV_MASK) ++ >> SECVID_MS_MAJ_REV_SHIFT; ++ min = CAAM_READ(sc, CAAM_CAAMVID_MS) & 0xff; ++ ++ device_printf(dev, "SEC era %d, version %d.%d, " ++ "CHAs: AES=%u DES=%u MD=%u RNG=%u PK=%u\n", ++ sc->sc_era, maj, min, ++ (chanum_ls >> 0) & 0xf, /* AES */ ++ (chanum_ls >> 4) & 0xf, /* DES */ ++ (chanum_ls >> 12) & 0xf, /* MDHA */ ++ (chanum_ls >> 16) & 0xf, /* RNG */ ++ (chanum_ls >> 24) & 0xf); /* PKHA */ ++ ++ /* ++ * Initialize local resource manager (rman) for child devices. ++ * ++ * The controller owns the full 1MB register region. Child Job ++ * Rings need sub-ranges (e.g. 0x10000-0x1ffff). A local rman ++ * allows children to allocate from our resource without conflicting ++ * with the parent bus's resource pool. ++ */ ++ sc->sc_mem_rman.rm_type = RMAN_ARRAY; ++ sc->sc_mem_rman.rm_descr = "CAAM memory"; ++ error = rman_init_from_resource(&sc->sc_mem_rman, sc->sc_rres); ++ if (error != 0) { ++ device_printf(dev, "rman_init_from_resource failed: %d\n", ++ error); ++ bus_release_resource(dev, SYS_RES_MEMORY, ++ sc->sc_rrid, sc->sc_rres); ++ return (error); ++ } ++ ++ /* ++ * Configure Master Config Register for optimal DMA behavior. ++ * Set AXI write cache attributes (cacheable + bufferable), ++ * enable watchdog, and allow large bursts. ++ */ ++ { ++ uint32_t mcr = CAAM_READ(sc, CAAM_MCFGR); ++ mcr = (mcr & ~MCFGR_AWCACHE_MASK) | ++ MCFGR_AWCACHE_CACH | MCFGR_AWCACHE_BUFF | ++ MCFGR_WDENABLE | MCFGR_LARGE_BURST; ++ CAAM_WRITE(sc, CAAM_MCFGR, mcr); ++ } ++ ++ /* ++ * 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). ++ */ ++ CAAM_WRITE(sc, CAAM_JRSTART, ++ JRSTART_JR0 | JRSTART_JR1 | JRSTART_JR2 | JRSTART_JR3); ++ ++ /* ++ * Compute page-size-dependent block offsets. ++ * Page size is 4K or 64K, read from CTPR_MS. ++ * DECO block = page 8, QI block = page 7. ++ * LS1046A uses 64K pages: QI at 0x70000, DECO0 at 0x80000. ++ */ ++ { ++ uint32_t pg_size; ++ ++ pg_size = (ctpr & CTPR_MS_PG_SZ_MASK) >> CTPR_MS_PG_SZ_SHIFT; ++ pg_size = pg_size ? PG_SIZE_64K : PG_SIZE_4K; ++ sc->sc_deco0_off = DECO_BLOCK_NUMBER * pg_size; ++ sc->sc_qi_off = QI_BLOCK_NUMBER * pg_size; ++ /* No debug print needed — page size used internally */ ++ } ++ ++ /* ++ * Initialize RNG: configure TRNG and instantiate state handles. ++ * Must happen before child enumeration since JR crypto operations ++ * that use RNG (e.g. key generation) need instantiated state handles. ++ */ ++ error = caam_rng_init(sc); ++ if (error != 0) ++ device_printf(dev, "WARNING: RNG initialization failed: %d\n", ++ error); ++ ++ /* ++ * Enable QI (Queue Interface) if hardware supports it. ++ * ++ * QI allows crypto submission via QMan frame queues instead of ++ * Job Rings, eliminating the JR spinlock bottleneck for high ++ * packet-rate workloads. The child JR driver checks sc_qi_present ++ * to optionally register a QI-based opencrypto backend. ++ */ ++ if (ctpr & CTPR_MS_QI_MASK) { ++ CAAM_WRITE(sc, sc->sc_qi_off + CAAM_QI_CONTROL_LO, ++ QICTL_DQEN); ++ sc->sc_qi_present = true; ++ device_printf(dev, "QI enabled\n"); ++ } ++ ++ /* ++ * Initialize simplebus and enumerate Job Ring children from DT. ++ * After that, add a QI pseudo-device if the hardware supports it. ++ * The QI device doesn't need DT resources — it communicates ++ * with CAAM entirely through QMan frame queues. ++ * The crypto@1700000 node has ranges + #address-cells + #size-cells, ++ * making it a valid bus for child enumeration. ++ */ ++ simplebus_init(dev, node); ++ simplebus_fill_ranges(node, &sc->sc_base); ++ ++ bus_identify_children(dev); ++ for (node = OF_child(ofw_bus_get_node(dev)); node > 0; ++ node = OF_peer(node)) { ++ simplebus_add_device(dev, node, 0, NULL, -1, NULL); ++ } ++ ++ /* Add QI pseudo-device alongside JR children */ ++ if (sc->sc_qi_present) ++ device_add_child(dev, "caam_qi", -1); ++ ++ bus_attach_children(dev); ++ ++ return (0); ++} ++ ++int ++caam_detach(device_t dev) ++{ ++ struct caam_softc *sc; ++ ++ sc = device_get_softc(dev); ++ ++ bus_generic_detach(dev); ++ ++ rman_fini(&sc->sc_mem_rman); ++ ++ if (sc->sc_rres != NULL) ++ bus_release_resource(dev, SYS_RES_MEMORY, ++ sc->sc_rrid, sc->sc_rres); ++ ++ return (0); ++} ++ ++/* ++ * Bus method: allocate a resource for a child device. ++ * ++ * For memory resources, allocate from our local rman (backed by the ++ * controller's 1MB register region). For IRQs and other types, pass ++ * through to the default simplebus/parent implementation. ++ */ ++static struct resource * ++caam_alloc_resource(device_t bus, device_t child, int type, int *rid, ++ rman_res_t start, rman_res_t end, rman_res_t count, u_int flags) ++{ ++ struct caam_softc *sc; ++ struct resource_list_entry *rle; ++ struct resource *res; ++ ++ sc = device_get_softc(bus); ++ ++ if (type != SYS_RES_MEMORY) ++ return (bus_generic_rl_alloc_resource(bus, child, type, ++ rid, start, end, count, flags)); ++ ++ /* Look up child's resource list entry (populated from DT) */ ++ rle = resource_list_find(BUS_GET_RESOURCE_LIST(bus, child), ++ type, *rid); ++ if (rle == NULL) ++ return (NULL); ++ ++ if (RMAN_IS_DEFAULT_RANGE(start, end)) { ++ start = rle->start; ++ count = ulmax(count, rle->count); ++ end = ulmax(rle->end, start + count - 1); ++ } ++ ++ /* ++ * Translate child's bus address to physical address through the ++ * DT "ranges" property — same transform as simplebus_alloc_resource. ++ * ++ * Child addresses (e.g. 0x10000) map to parent physical addresses ++ * (e.g. 0x1710000) via: phys = child_addr - ranges.bus + ranges.host ++ */ ++ for (int i = 0; i < sc->sc_base.nranges; i++) { ++ struct simplebus_range *r = &sc->sc_base.ranges[i]; ++ ++ if (start >= r->bus && end < r->bus + r->size) { ++ start = start - r->bus + r->host; ++ end = end - r->bus + r->host; ++ ++ res = rman_reserve_resource(&sc->sc_mem_rman, ++ start, end, count, flags & ~RF_ACTIVE, child); ++ if (res == NULL) ++ return (NULL); ++ ++ rman_set_rid(res, *rid); ++ rman_set_type(res, type); ++ ++ if ((flags & RF_ACTIVE) != 0 && ++ bus_activate_resource(child, type, *rid, ++ res) != 0) { ++ rman_release_resource(res); ++ return (NULL); ++ } ++ ++ rle->res = res; ++ return (res); ++ } ++ } ++ ++ return (NULL); ++} ++ ++/* ++ * Bus method: activate a child's memory resource. ++ * ++ * Create a bus_space subregion of the controller's mapping. ++ * 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) ++{ ++ struct caam_softc *sc; ++ bus_space_handle_t bh; ++ bus_space_tag_t bt; ++ int rv; ++ ++ sc = device_get_softc(bus); ++ ++ if (rman_get_type(res) != SYS_RES_MEMORY) ++ return (bus_generic_activate_resource(bus, child, type, rid, 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)); ++ ++ bt = rman_get_bustag(sc->sc_rres); ++ rv = bus_space_subregion(bt, rman_get_bushandle(sc->sc_rres), ++ rman_get_start(res) - rman_get_start(sc->sc_rres), ++ rman_get_size(res), &bh); ++ if (rv != 0) ++ return (rv); ++ ++ rman_set_bustag(res, bt); ++ rman_set_bushandle(res, bh); ++ ++ return (rman_activate_resource(res)); ++} ++ ++/* ++ * Bus method: deactivate a child's resource. ++ * ++ * Resources from our rman were activated via bus_space_subregion — ++ * they share the parent's mapping and must NOT be pmap_unmapdev'd. ++ * Just clear the RF_ACTIVE flag. ++ */ ++static int ++caam_deactivate_resource(device_t bus, device_t child, int type, int rid, struct resource *res) ++{ ++ struct caam_softc *sc; ++ ++ sc = device_get_softc(bus); ++ ++ 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 (rman_deactivate_resource(res)); ++} ++ ++/* ++ * 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) ++{ ++ struct caam_softc *sc; ++ struct resource_list_entry *rle; ++ int rv; ++ ++ sc = device_get_softc(bus); ++ ++ 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)); ++ ++ if ((rman_get_flags(res) & RF_ACTIVE) != 0) { ++ rv = bus_deactivate_resource(child, type, rid, res); ++ if (rv != 0) ++ return (rv); ++ } ++ ++ rv = rman_release_resource(res); ++ ++ rle = resource_list_find(BUS_GET_RESOURCE_LIST(bus, child), ++ rman_get_type(res), rman_get_rid(res)); ++ if (rle != NULL) ++ rle->res = NULL; ++ ++ return (rv); ++} ++ ++static device_method_t caam_methods[] = { ++ /* Device interface */ ++ DEVMETHOD(device_probe, caam_probe), ++ DEVMETHOD(device_attach, caam_attach), ++ DEVMETHOD(device_detach, caam_detach), ++ ++ /* Bus interface — override simplebus for rman-based allocation */ ++ DEVMETHOD(bus_alloc_resource, caam_alloc_resource), ++ DEVMETHOD(bus_activate_resource, caam_activate_resource), ++ DEVMETHOD(bus_deactivate_resource, caam_deactivate_resource), ++ DEVMETHOD(bus_release_resource, caam_release_resource), ++ ++ DEVMETHOD_END ++}; ++ ++DEFINE_CLASS_1(caam, caam_driver, caam_methods, ++ sizeof(struct caam_softc), simplebus_driver); ++ ++EARLY_DRIVER_MODULE(caam, simplebus, caam_driver, 0, 0, ++ BUS_PASS_DEFAULT); ++MODULE_VERSION(caam, 1); +diff --git a/sys/dev/caam/caam.h b/sys/dev/caam/caam.h +new file mode 100644 +index 00000000000..4395f133ca8 +--- /dev/null ++++ b/sys/dev/caam/caam.h +@@ -0,0 +1,128 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * NXP CAAM (SEC v4.0+) crypto controller — shared types and accessors. ++ */ ++ ++#ifndef _CAAM_H ++#define _CAAM_H ++ ++#include ++#include ++ ++#include ++ ++/* ++ * CAAM register/DMA endianness. ++ * ++ * Detected at runtime via the CSTA register's PLEND bit. On QorIQ ++ * Layerscape ARM64 (LS1046A), CAAM is big-endian — same as DPAA1 ++ * portals. All register accesses and DMA data (ring entries, descriptors) ++ * use CAAM byte order. ++ * ++ * Set once during controller attach; used by all CAAM subsystems. ++ */ ++extern bool caam_big_endian; ++ ++/* ++ * Byte-order conversion between CPU and CAAM. ++ */ ++static __inline uint32_t ++cpu_to_caam32(uint32_t val) ++{ ++ ++ return (caam_big_endian ? htobe32(val) : val); ++} ++ ++static __inline uint32_t ++caam_to_cpu32(uint32_t val) ++{ ++ ++ return (caam_big_endian ? be32toh(val) : val); ++} ++ ++static __inline uint64_t ++cpu_to_caam64(uint64_t val) ++{ ++ ++ return (caam_big_endian ? htobe64(val) : val); ++} ++ ++static __inline uint64_t ++caam_to_cpu64(uint64_t val) ++{ ++ ++ return (caam_big_endian ? be64toh(val) : val); ++} ++ ++/* ++ * Controller softc. ++ */ ++struct caam_softc { ++ struct simplebus_softc sc_base; /* Inherits simplebus */ ++ struct resource *sc_rres; /* CCSR register resource */ ++ int sc_rrid; ++ int sc_era; /* SEC era (8 for LS1046A) */ ++ struct rman sc_mem_rman; /* Resource manager for children */ ++ bus_size_t sc_deco0_off; /* DECO0 base offset */ ++ bus_size_t sc_qi_off; /* QI block base offset */ ++ bool sc_rng_inited; /* RNG state handles instantiated */ ++ bool sc_rng_registered; /* RNG entropy source registered */ ++ bool sc_qi_present; /* QI (Queue Interface) present */ ++}; ++ ++/* ++ * Register access — applies CAAM byte-swap (BE on LS1046A). ++ * ++ * bus_read_4/bus_write_4 do no byte-swap on LE ARM64. Since CAAM ++ * registers are BE, we must swap explicitly. ++ */ ++#define CAAM_READ(sc, off) caam_to_cpu32(bus_read_4((sc)->sc_rres, (off))) ++#define CAAM_WRITE(sc, off, v) \ ++ bus_write_4((sc)->sc_rres, (off), cpu_to_caam32(v)) ++ ++/* ++ * 64-bit register access. ++ * ++ * CAAM 64-bit registers (e.g. ring base addresses) are two 32-bit halves. ++ * - BE CAAM: high 32 bits at offset+0, low 32 bits at offset+4. ++ * - LE CAAM: low 32 bits at offset+0, high 32 bits at offset+4. ++ * Each 32-bit half uses CAAM byte order. ++ */ ++static __inline void ++caam_write_8(struct resource *res, bus_size_t off, uint64_t val) ++{ ++ ++ if (caam_big_endian) { ++ /* BE: MSB at lower address */ ++ bus_write_4(res, off, htobe32((uint32_t)(val >> 32))); ++ bus_write_4(res, off + 4, htobe32((uint32_t)val)); ++ } else { ++ /* LE: LSB at lower address */ ++ bus_write_4(res, off, (uint32_t)val); ++ bus_write_4(res, off + 4, (uint32_t)(val >> 32)); ++ } ++} ++ ++static __inline uint64_t ++caam_read_8(struct resource *res, bus_size_t off) ++{ ++ uint32_t w0, w1; ++ ++ w0 = bus_read_4(res, off); ++ w1 = bus_read_4(res, off + 4); ++ if (caam_big_endian) { ++ /* BE: high 32 at offset+0, low 32 at offset+4 */ ++ return ((uint64_t)be32toh(w0) << 32) | be32toh(w1); ++ } else { ++ /* LE: low 32 at offset+0, high 32 at offset+4 */ ++ return ((uint64_t)w1 << 32) | w0; ++ } ++} ++ ++int caam_attach(device_t dev); ++int caam_detach(device_t dev); ++ ++#endif /* _CAAM_H */ +diff --git a/sys/dev/caam/caam_alg.c b/sys/dev/caam/caam_alg.c +new file mode 100644 +index 00000000000..e13c824e20a +--- /dev/null ++++ b/sys/dev/caam/caam_alg.c +@@ -0,0 +1,1183 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * CAAM algorithm descriptor builders for all supported modes. ++ * ++ * Shared descriptors are built once per session and stored in DMA memory. ++ * Job descriptors are built per-request and reference the shared descriptor. ++ * ++ * Descriptor sequences ported from Linux drivers/crypto/caam/caamalg_desc.c ++ * (cnstr_shdsc_gcm_encap, cnstr_shdsc_gcm_decap, cnstr_shdsc_aead_encap, ++ * cnstr_shdsc_aead_decap) adapted for FreeBSD's opencrypto buffer model. ++ * ++ * Job descriptor layout uses HDR_SHARE_DEFER | HDR_REVERSE so the JD body ++ * (REG3 load, IV load, SEQ IN/OUT PTR) executes BEFORE the shared ++ * descriptor. start_idx = shdesc_len following the combined descriptor ++ * interleaving model. ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++ ++#include ++ ++#include "caam.h" ++#include "caam_regs.h" ++#include "caam_desc.h" ++#include "caam_jr.h" ++#include "caam_crypto.h" ++ ++/* ++ * Split key lengths for HMAC algorithms. ++ * ++ * The split key is the result of HMAC's inner hash init: ipad || opad ++ * partial digests concatenated. For SHA-256 (32-byte digest), the ++ * split key is 2*32 = 64 bytes. ++ */ ++int ++caam_split_key_len(uint32_t algsel) ++{ ++ ++ switch (algsel) { ++ case OP_ALG_ALGSEL_SHA1: ++ return (40); /* 2 * 20 */ ++ case OP_ALG_ALGSEL_SHA224: ++ return (56); /* 2 * 28 */ ++ case OP_ALG_ALGSEL_SHA256: ++ return (64); /* 2 * 32 */ ++ case OP_ALG_ALGSEL_SHA384: ++ return (96); /* 2 * 48 */ ++ case OP_ALG_ALGSEL_SHA512: ++ return (128); /* 2 * 64 */ ++ case OP_ALG_ALGSEL_MD5: ++ return (32); /* 2 * 16 */ ++ default: ++ return (0); ++ } ++} ++ ++int ++caam_split_key_pad_len(uint32_t algsel) ++{ ++ ++ /* Round up to the next multiple of 16 for CAAM DMA alignment */ ++ return ((caam_split_key_len(algsel) + 15) & ~15); ++} ++ ++/* ================================================================ ++ * AES-GCM Shared Descriptors ++ * ++ * GCM uses Class 1 only (AES in GCM mode is a combined cipher+auth). ++ * The shared descriptor loads the key and sets up the OPERATION. ++ * Job descriptors provide: ++ * - REG3 = assoclen (via MATH ADD IMM, runs first with HDR_REVERSE) ++ * - IV via FIFO LOAD IMM (12 bytes, Class 1) ++ * - SEQ IN PTR / SEQ OUT PTR for bounce buffer ++ * ++ * Data layout in bounce buffer: ++ * Encrypt input: [AAD (assoclen bytes)] [plaintext (cryptlen bytes)] ++ * Encrypt output: [AAD (assoclen bytes)] [ciphertext] [ICV (16 bytes)] ++ * Decrypt input: [AAD (assoclen bytes)] [ciphertext] [ICV (16 bytes)] ++ * Decrypt output: [AAD (assoclen bytes)] [plaintext] ++ * ================================================================ */ ++ ++int ++caam_gcm_build_enc_shdesc(struct caam_session *sess, device_t dev) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump, *zero_assoc_jump1, *zero_assoc_jump2, ++ *zero_payload_jump; ++ int error; ++ ++ error = caam_dma_alloc(dev, &sess->enc_shdesc, CAAM_DESC_MAX_BYTES); ++ if (error != 0) ++ return (error); ++ ++ desc = sess->enc_shdesc.vaddr; ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL); ++ ++ /* Skip key loading if already shared */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ /* Load AES key (inline in descriptor) */ ++ caam_desc_add_word(desc, ++ CMD_KEY | KEY_CLASS1 | KEY_DEST_CLASS_REG | ++ KEY_IMM | sess->enc_klen); ++ caam_desc_add_key_imm(desc, sess->enc_key, sess->enc_klen); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* OPERATION: AES-GCM encrypt, init+final */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ OP_ALG_ALGSEL_AES | OP_ALG_AAI_GCM | ++ OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT); ++ ++ /* ++ * VARSEQOUTLEN = SEQINLEN - REG0 ++ * REG0 is zero at job start, so VARSEQOUTLEN = total input length. ++ * If zero, no data to process — skip to ICV write. ++ */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_SUB | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* If total length (assoclen + cryptlen) is zero, skip to ICV write */ ++ zero_assoc_jump2 = caam_desc_add_jump(desc, ++ JUMP_TEST_ALL | JUMP_COND_MATH_Z); ++ ++ /* VARSEQINLEN = REG3 (= assoclen, loaded by job desc) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_REG3 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* If assoclen is zero, skip AAD processing */ ++ zero_assoc_jump1 = caam_desc_add_jump(desc, ++ JUMP_TEST_ALL | JUMP_COND_MATH_Z); ++ ++ /* VARSEQOUTLEN = REG3 (for skipping AAD in output) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_REG3 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Skip AAD bytes in output */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_SKIP | FIFOLDST_VLF); ++ ++ /* cryptlen = SEQINLEN - REG3 (subtract assoclen from remaining) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_SUB | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG3 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* If cryptlen is zero, jump to zero-payload path */ ++ zero_payload_jump = caam_desc_add_jump(desc, ++ JUMP_TEST_ALL | JUMP_COND_MATH_Z); ++ ++ /* Read AAD data (Class 1, AAD type, FLUSH1) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_AAD | FIFOLD_TYPE_FLUSH1); ++ ++ caam_desc_set_jump_target(desc, zero_assoc_jump1); ++ ++ /* VARSEQINLEN = SEQINLEN - REG0 (remaining = cryptlen) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_SUB | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* Write encrypted payload */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_MESSAGE_DATA | FIFOLDST_VLF); ++ ++ /* Read plaintext payload (CLASS1, MSG, LAST1) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG | FIFOLD_TYPE_LAST1); ++ ++ /* Jump past zero-payload path to ICV write */ ++ caam_desc_add_word(desc, CMD_JUMP | JUMP_TEST_ALL | 2); ++ ++ /* Zero-payload: read AAD only (AAD | LAST1) */ ++ caam_desc_set_jump_target(desc, zero_payload_jump); ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_AAD | FIFOLD_TYPE_LAST1); ++ ++ /* Zero-total-length target */ ++ caam_desc_set_jump_target(desc, zero_assoc_jump2); ++ ++ /* Write ICV (tag) from Class 1 context register */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_STORE | LDST_CLASS_1_CCB | ++ LDST_SRCDST_BYTE_CONTEXT | sess->icvlen); ++ ++ sess->enc_shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++int ++caam_gcm_build_dec_shdesc(struct caam_session *sess, device_t dev) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump, *zero_assoc_jump1, *zero_payload_jump; ++ int error; ++ ++ error = caam_dma_alloc(dev, &sess->dec_shdesc, CAAM_DESC_MAX_BYTES); ++ if (error != 0) ++ return (error); ++ ++ desc = sess->dec_shdesc.vaddr; ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL); ++ ++ /* Skip key loading if already shared */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ /* Load AES key */ ++ caam_desc_add_word(desc, ++ CMD_KEY | KEY_CLASS1 | KEY_DEST_CLASS_REG | ++ KEY_IMM | sess->enc_klen); ++ caam_desc_add_key_imm(desc, sess->enc_key, sess->enc_klen); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* OPERATION: AES-GCM decrypt with ICV check */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ OP_ALG_ALGSEL_AES | OP_ALG_AAI_GCM | ++ OP_ALG_AS_INITFINAL | OP_ALG_DECRYPT | OP_ALG_ICV_ON); ++ ++ /* VARSEQINLEN = REG3 (= assoclen) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_REG3 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* If assoclen is zero, skip AAD */ ++ zero_assoc_jump1 = caam_desc_add_jump(desc, ++ JUMP_TEST_ALL | JUMP_COND_MATH_Z); ++ ++ /* VARSEQOUTLEN = REG3 */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_REG3 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Skip AAD in output */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_SKIP | FIFOLDST_VLF); ++ ++ /* Read AAD (CLASS1, AAD, FLUSH1) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_AAD | FIFOLD_TYPE_FLUSH1); ++ ++ caam_desc_set_jump_target(desc, zero_assoc_jump1); ++ ++ /* cryptlen = SEQOUTLEN - REG0 (= remaining output size) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_SUB | ++ MATH_SRC0_SEQOUTLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* If cryptlen is zero, jump to ICV read */ ++ zero_payload_jump = caam_desc_add_jump(desc, ++ JUMP_TEST_ALL | JUMP_COND_MATH_Z); ++ ++ /* VARSEQOUTLEN = SEQOUTLEN - REG0 */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_SUB | ++ MATH_SRC0_SEQOUTLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Write decrypted payload */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_MESSAGE_DATA | FIFOLDST_VLF); ++ ++ /* Read ciphertext (CLASS1, MSG, FLUSH1) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG | FIFOLD_TYPE_FLUSH1); ++ ++ /* Zero-payload target */ ++ caam_desc_set_jump_target(desc, zero_payload_jump); ++ ++ /* Read ICV for verification (CLASS1, ICV | LAST1) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | ++ FIFOLD_TYPE_ICV | FIFOLD_TYPE_LAST1 | sess->icvlen); ++ ++ sess->dec_shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++/* ================================================================ ++ * AES-CBC + HMAC-SHA Shared Descriptors (ETA mode) ++ * ++ * Uses both Class 1 (AES-CBC) and Class 2 (HMAC-SHA). ++ * ================================================================ */ ++ ++int ++caam_eta_build_enc_shdesc(struct caam_session *sess, device_t dev) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ int error; ++ ++ error = caam_dma_alloc(dev, &sess->enc_shdesc, CAAM_DESC_MAX_BYTES); ++ if (error != 0) ++ return (error); ++ ++ desc = sess->enc_shdesc.vaddr; ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL | HDR_SAVECTX); ++ ++ /* Skip key loading if already shared */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ /* ++ * Derive and load HMAC split key via DKP (ERA >= 6). ++ * The DKP OPERATION takes the raw HMAC key inline, computes ++ * the ipad/opad partial digests, and loads them into the ++ * Class 2 key register — all in one DECO step. ++ */ ++ caam_desc_add_proto_dkp(desc, sess->auth_algtype, ++ sess->auth_key, sess->auth_klen, sess->split_key_pad_len); ++ ++ /* Load AES cipher key (Class 1) */ ++ caam_desc_add_word(desc, ++ CMD_KEY | KEY_CLASS1 | KEY_DEST_CLASS_REG | ++ KEY_IMM | sess->enc_klen); ++ caam_desc_add_key_imm(desc, sess->enc_key, sess->enc_klen); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* Class 2 OPERATION: HMAC with pre-computed split key */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS2_ALG | ++ sess->auth_algtype | OP_ALG_AAI_HMAC_PRECOMP | ++ OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT); ++ ++ /* ++ * Read assoclen from DPOVRD (set by job descriptor, era >= 3). ++ * VARSEQINLEN = DPOVRD = assoclen ++ * VARSEQOUTLEN = DPOVRD = assoclen ++ */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_DPOVRD | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_DPOVRD | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Skip assoc data in output */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_SKIP | FIFOLDST_VLF); ++ ++ /* Read assoc data for HMAC (CLASS2, MSG) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | ++ FIFOLD_TYPE_MSG | FIFOLDST_VLF); ++ ++ /* Class 1 OPERATION: AES-CBC encrypt */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ sess->cipher_algtype | OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT); ++ ++ /* ++ * Remaining input = SEQINLEN (live counter after AAD consumed). ++ * VARSEQINLEN = SEQINLEN + REG0(=0) = cryptlen ++ * VARSEQOUTLEN = SEQINLEN + REG0(=0) = cryptlen ++ */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* ++ * Read plaintext (both classes) and write ciphertext. ++ * MSG1OUT2: Class 1 encrypts, Class 2 authenticates the ciphertext. ++ * No explicit LAST flags — VLF exhaustion signals completion. ++ */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_MESSAGE_DATA | FIFOLDST_VLF); ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_BOTH | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG1OUT2); ++ ++ /* Write HMAC ICV from Class 2 context */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_STORE | LDST_CLASS_2_CCB | ++ LDST_SRCDST_BYTE_CONTEXT | sess->icvlen); ++ ++ sess->enc_shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++int ++caam_eta_build_dec_shdesc(struct caam_session *sess, device_t dev) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ int error; ++ ++ error = caam_dma_alloc(dev, &sess->dec_shdesc, CAAM_DESC_MAX_BYTES); ++ if (error != 0) ++ return (error); ++ ++ desc = sess->dec_shdesc.vaddr; ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL | HDR_SAVECTX); ++ ++ /* Skip key loading if already shared */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ /* Derive and load HMAC split key via DKP (ERA >= 6) */ ++ caam_desc_add_proto_dkp(desc, sess->auth_algtype, ++ sess->auth_key, sess->auth_klen, sess->split_key_pad_len); ++ ++ /* Load AES cipher key (Class 1) */ ++ caam_desc_add_word(desc, ++ CMD_KEY | KEY_CLASS1 | KEY_DEST_CLASS_REG | ++ KEY_IMM | sess->enc_klen); ++ caam_desc_add_key_imm(desc, sess->enc_key, sess->enc_klen); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* Class 2 OPERATION: HMAC verify (DECRYPT + ICV_ON) */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS2_ALG | ++ sess->auth_algtype | OP_ALG_AAI_HMAC_PRECOMP | ++ OP_ALG_AS_INITFINAL | OP_ALG_DECRYPT | OP_ALG_ICV_ON); ++ ++ /* VARSEQINLEN = DPOVRD (= assoclen, set by job desc, era >= 3) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_DPOVRD | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* VARSEQOUTLEN = DPOVRD */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_DPOVRD | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Skip assoc data in output */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_SKIP | FIFOLDST_VLF); ++ ++ /* Read assoc data for HMAC (CLASS2, MSG) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | ++ FIFOLD_TYPE_MSG | FIFOLDST_VLF); ++ ++ /* Class 1 OPERATION: AES-CBC decrypt */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ sess->cipher_algtype | OP_ALG_AS_INITFINAL | OP_ALG_DECRYPT); ++ ++ /* ++ * For decrypt, use SEQOUTLEN (output remaining) to determine ++ * cryptlen, matching Linux's approach. ++ * VARSEQINLEN = SEQOUTLEN + REG0(=0) = cryptlen ++ * VARSEQOUTLEN = SEQOUTLEN + REG0(=0) = cryptlen ++ */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQOUTLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQOUTLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Read ciphertext and write plaintext (both classes, MSG) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_MESSAGE_DATA | FIFOLDST_VLF); ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_BOTH | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG); ++ ++ /* Read ICV for verification (CLASS2, ICV | LAST2) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | ++ FIFOLD_TYPE_LAST2 | FIFOLD_TYPE_ICV | sess->icvlen); ++ ++ sess->dec_shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++/* ================================================================ ++ * Job Descriptor Builders ++ * ++ * Job descriptors use HDR_SHARE_DEFER | HDR_REVERSE so the JD body ++ * executes BEFORE the shared descriptor. This allows the JD to ++ * set up REG3 (GCM) or DPOVRD (ETA, era >= 3) for the shared ++ * descriptor to use. ++ * ++ * Combined descriptor model (DECO internal view): ++ * [0] JD header ++ * [1..shlen] Shared descriptor (loaded from DMA) ++ * [shlen+1..end] JD body (from words after shdesc pointer in JD) ++ * ++ * start_idx = shlen + 1: tells DECO where JD body begins. ++ * With HDR_REVERSE: JD body runs first, then shared descriptor. ++ * ++ * JD memory layout: ++ * [0] JD header ++ * [1-2] Shared descriptor DMA pointer (64-bit) ++ * [3..] JD body commands (MATH, LOAD IV, SEQ IN/OUT PTR) ++ * ================================================================ */ ++ ++int ++caam_gcm_build_job(struct caam_jr_softc *sc, struct caam_request *req, ++ struct cryptop *crp) ++{ ++ struct caam_session *sess; ++ uint32_t *desc; ++ bus_addr_t buf_pa; ++ uint32_t assoclen, input_len, output_len; ++ bool encrypt; ++ int shdesc_len; ++ uint8_t iv[AES_GCM_IV_LEN]; ++ ++ sess = req->sess; ++ desc = req->desc.vaddr; ++ encrypt = CRYPTO_OP_IS_ENCRYPT(crp->crp_op); ++ buf_pa = req->using_dyn ? req->dyn_bounce.paddr : req->bounce.paddr; ++ ++ assoclen = crp->crp_aad_length; ++ shdesc_len = encrypt ? sess->enc_shdesc_len : sess->dec_shdesc_len; ++ ++ if (encrypt) { ++ input_len = assoclen + crp->crp_payload_length; ++ output_len = assoclen + crp->crp_payload_length + sess->icvlen; ++ } else { ++ input_len = assoclen + crp->crp_payload_length + sess->icvlen; ++ output_len = assoclen + crp->crp_payload_length; ++ } ++ ++ /* Read IV from the crypto request */ ++ crypto_read_iv(crp, iv); ++ ++ /* Build job descriptor */ ++ caam_desc_init(desc); ++ ++ /* Set start index and share mode */ ++ { ++ uint32_t hdr = caam_to_cpu32(desc[0]); ++ ++ hdr |= HDR_SHARED | HDR_SHARE_DEFER | HDR_REVERSE; ++ hdr |= (shdesc_len << HDR_START_IDX_SHIFT); ++ desc[0] = cpu_to_caam32(hdr); ++ } ++ ++ /* Shared descriptor pointer (64-bit) */ ++ if (encrypt) ++ caam_desc_add_ptr(desc, sess->enc_shdesc.paddr); ++ else ++ caam_desc_add_ptr(desc, sess->dec_shdesc.paddr); ++ ++ /* === JD body (runs FIRST with HDR_REVERSE) === */ ++ ++ /* REG3 = assoclen (MATH ADD: ZERO + IMM → REG3) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_IMM | ++ MATH_DEST_REG3 | MATH_LEN_4BYTE); ++ caam_desc_add_word(desc, assoclen); ++ ++ /* ++ * Load GCM IV (12 bytes, inline) into Class 1 FIFO. ++ * CAAM AES-GCM expects the 12-byte IV; it auto-appends counter=1. ++ */ ++ caam_desc_add_word(desc, ++ CMD_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLD_IMM | ++ FIFOLD_TYPE_IV | FIFOLD_TYPE_FLUSH1 | AES_GCM_IV_LEN); ++ caam_desc_add_key_imm(desc, iv, AES_GCM_IV_LEN); ++ ++ /* SEQ IN PTR: input data */ ++ caam_desc_add_word(desc, CMD_SEQ_IN_PTR | input_len); ++ caam_desc_add_ptr(desc, buf_pa); ++ ++ /* SEQ OUT PTR: output data */ ++ caam_desc_add_word(desc, CMD_SEQ_OUT_PTR | output_len); ++ caam_desc_add_ptr(desc, buf_pa); ++ ++ return (0); ++} ++ ++int ++caam_eta_build_job(struct caam_jr_softc *sc, struct caam_request *req, ++ struct cryptop *crp) ++{ ++ struct caam_session *sess; ++ uint32_t *desc; ++ bus_addr_t buf_pa; ++ uint32_t assoclen, input_len, output_len; ++ bool encrypt; ++ int shdesc_len; ++ uint8_t iv[AES_BLOCK_LEN]; /* Max IV: 16 bytes (AES) */ ++ ++ sess = req->sess; ++ desc = req->desc.vaddr; ++ encrypt = CRYPTO_OP_IS_ENCRYPT(crp->crp_op); ++ buf_pa = req->using_dyn ? req->dyn_bounce.paddr : req->bounce.paddr; ++ ++ assoclen = crp->crp_aad_length; ++ shdesc_len = encrypt ? sess->enc_shdesc_len : sess->dec_shdesc_len; ++ ++ if (encrypt) { ++ input_len = assoclen + crp->crp_payload_length; ++ output_len = assoclen + crp->crp_payload_length + sess->icvlen; ++ } else { ++ input_len = assoclen + crp->crp_payload_length + sess->icvlen; ++ output_len = assoclen + crp->crp_payload_length; ++ } ++ ++ /* Build job descriptor */ ++ caam_desc_init(desc); ++ ++ { ++ uint32_t hdr = caam_to_cpu32(desc[0]); ++ ++ hdr |= HDR_SHARED | HDR_SHARE_DEFER | HDR_REVERSE; ++ hdr |= (shdesc_len << HDR_START_IDX_SHIFT); ++ desc[0] = cpu_to_caam32(hdr); ++ } ++ ++ /* Shared descriptor pointer */ ++ if (encrypt) ++ caam_desc_add_ptr(desc, sess->enc_shdesc.paddr); ++ else ++ caam_desc_add_ptr(desc, sess->dec_shdesc.paddr); ++ ++ /* === JD body (runs FIRST with HDR_REVERSE) === */ ++ ++ /* DPOVRD = assoclen (MATH ADD: ZERO + IMM -> DPOVRD, era >= 3) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_IMM | ++ MATH_DEST_DPOVRD | MATH_LEN_4BYTE); ++ caam_desc_add_word(desc, assoclen); ++ ++ /* ++ * Load cipher IV into Class 1 context register. ++ * AES-CBC/CTR: 16 bytes at CONTEXT1[0]. ++ * DES/3DES-CBC: 8 bytes at CONTEXT1[0]. ++ */ ++ if (sess->ivlen > 0) { ++ crypto_read_iv(crp, iv); ++ caam_desc_add_word(desc, ++ CMD_LOAD | LDST_CLASS_1_CCB | LDST_IMM | ++ LDST_SRCDST_BYTE_CONTEXT | sess->ivlen); ++ caam_desc_add_key_imm(desc, iv, sess->ivlen); ++ } ++ ++ /* SEQ IN PTR */ ++ caam_desc_add_word(desc, CMD_SEQ_IN_PTR | input_len); ++ caam_desc_add_ptr(desc, buf_pa); ++ ++ /* SEQ OUT PTR */ ++ caam_desc_add_word(desc, CMD_SEQ_OUT_PTR | output_len); ++ caam_desc_add_ptr(desc, buf_pa); ++ ++ return (0); ++} ++ ++/* ================================================================ ++ * Standalone Cipher Shared Descriptors ++ * ++ * Class 1 only (no authentication). Supports AES-CBC, AES-CTR, ++ * AES-ECB, AES-XTS, DES-CBC, and 3DES-CBC. ++ * ++ * Key is loaded inline. IV is provided by the job descriptor via ++ * LOAD IMM into CONTEXT1 (runs first with HDR_REVERSE). ++ * ++ * XTS requires special handling: double key, sector size in ++ * CONTEXT1+0x28, and IV (tweak) loaded as two 8-byte halves ++ * at CONTEXT1+0x20 and 0x30. ++ * ================================================================ */ ++ ++static bool ++caam_cipher_is_xts(const struct caam_session *sess) ++{ ++ ++ return ((sess->cipher_algtype & OP_ALG_AAI_MASK) == OP_ALG_AAI_XTS); ++} ++ ++int ++caam_cipher_build_enc_shdesc(struct caam_session *sess, device_t dev) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ int error; ++ ++ error = caam_dma_alloc(dev, &sess->enc_shdesc, CAAM_DESC_MAX_BYTES); ++ if (error != 0) ++ return (error); ++ ++ desc = sess->enc_shdesc.vaddr; ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL); ++ ++ /* Skip key loading if already shared */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ /* Load cipher key (inline, Class 1) */ ++ caam_desc_add_word(desc, ++ CMD_KEY | KEY_CLASS1 | KEY_DEST_CLASS_REG | ++ KEY_IMM | sess->enc_klen); ++ caam_desc_add_key_imm(desc, sess->enc_key, sess->enc_klen); ++ ++ if (caam_cipher_is_xts(sess)) { ++ /* ++ * XTS: load sector size (2^15 = 32768) at CONTEXT1+0x28. ++ * This effectively disables sector-based segmentation, ++ * processing the entire input as one unit. ++ */ ++ static const uint8_t sector_size[8] = { ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00 ++ }; ++ caam_desc_add_word(desc, ++ CMD_LOAD | LDST_CLASS_1_CCB | LDST_IMM | ++ LDST_SRCDST_BYTE_CONTEXT | ++ (0x28 << LDST_OFFSET_SHIFT) | 8); ++ caam_desc_add_key_imm(desc, sector_size, 8); ++ } ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* OPERATION: cipher encrypt, init+final */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ sess->cipher_algtype | OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT); ++ ++ /* VARSEQOUTLEN = SEQINLEN (total input → total output) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* VARSEQINLEN = SEQINLEN */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* Read plaintext and write ciphertext */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG | FIFOLD_TYPE_LAST1); ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_MESSAGE_DATA | FIFOLDST_VLF); ++ ++ sess->enc_shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++int ++caam_cipher_build_dec_shdesc(struct caam_session *sess, device_t dev) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ uint32_t algtype; ++ int error; ++ ++ error = caam_dma_alloc(dev, &sess->dec_shdesc, CAAM_DESC_MAX_BYTES); ++ if (error != 0) ++ return (error); ++ ++ desc = sess->dec_shdesc.vaddr; ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL); ++ ++ /* Skip key loading if already shared */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ /* Load cipher key (inline, Class 1) */ ++ caam_desc_add_word(desc, ++ CMD_KEY | KEY_CLASS1 | KEY_DEST_CLASS_REG | ++ KEY_IMM | sess->enc_klen); ++ caam_desc_add_key_imm(desc, sess->enc_key, sess->enc_klen); ++ ++ if (caam_cipher_is_xts(sess)) { ++ /* XTS: sector size at CONTEXT1+0x28 */ ++ static const uint8_t sector_size[8] = { ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00 ++ }; ++ caam_desc_add_word(desc, ++ CMD_LOAD | LDST_CLASS_1_CCB | LDST_IMM | ++ LDST_SRCDST_BYTE_CONTEXT | ++ (0x28 << LDST_OFFSET_SHIFT) | 8); ++ caam_desc_add_key_imm(desc, sector_size, 8); ++ } ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* ++ * OPERATION: cipher decrypt. ++ * ++ * For AES, use the DK (Derived Key) optimization: ++ * - First run (key not yet shared): plain INITFINAL + DECRYPT ++ * computes the decrypt key schedule from the raw key. ++ * - Subsequent runs (key shared): INITFINAL + DECRYPT + DK ++ * reuses the pre-computed decrypt key schedule. ++ * CTR mode doesn't need DK (same key schedule for enc/dec). ++ * DES/3DES doesn't support DK. ++ */ ++ algtype = sess->cipher_algtype; ++ if ((algtype & OP_ALG_ALGSEL_MASK) == OP_ALG_ALGSEL_AES && ++ (algtype & OP_ALG_AAI_MASK) != OP_ALG_AAI_CTR_MOD128) { ++ uint32_t *dk_jump, *skip_jump; ++ ++ /* If shared, jump to DK path */ ++ dk_jump = caam_desc_add_jump(desc, ++ JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ /* First run: derive decrypt key from raw key */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ algtype | OP_ALG_AS_INITFINAL | OP_ALG_DECRYPT); ++ ++ skip_jump = caam_desc_add_jump(desc, JUMP_TEST_ALL); ++ ++ /* DK path: reuse pre-computed decrypt key */ ++ caam_desc_set_jump_target(desc, dk_jump); ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ algtype | OP_ALG_AS_INITFINAL | ++ OP_ALG_DECRYPT | OP_ALG_AAI_DK); ++ ++ caam_desc_set_jump_target(desc, skip_jump); ++ } else { ++ /* CTR, DES, 3DES: plain decrypt */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ algtype | OP_ALG_AS_INITFINAL | OP_ALG_DECRYPT); ++ } ++ ++ /* VARSEQOUTLEN = SEQINLEN */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* VARSEQINLEN = SEQINLEN */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* Read ciphertext and write plaintext */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG | FIFOLD_TYPE_LAST1); ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_MESSAGE_DATA | FIFOLDST_VLF); ++ ++ sess->dec_shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++/* ================================================================ ++ * NULL cipher + HMAC Shared Descriptors (auth-only ETA) ++ * ++ * Class 2 only — no cipher engine. All data (AAD + payload) is ++ * fed to HMAC as message data. Since our bounce buffer uses the ++ * same address for input and output, the "passthrough" is implicit: ++ * data is already in the output buffer. We just skip the output ++ * sequence, feed data to Class 2, and write/verify the ICV. ++ * ++ * This avoids the complex self-modifying MOVE descriptor pattern ++ * that Linux uses for separate source/destination scatterlists. ++ * ================================================================ */ ++ ++int ++caam_null_hmac_build_enc_shdesc(struct caam_session *sess, device_t dev) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ int error; ++ ++ error = caam_dma_alloc(dev, &sess->enc_shdesc, CAAM_DESC_MAX_BYTES); ++ if (error != 0) ++ return (error); ++ ++ desc = sess->enc_shdesc.vaddr; ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL | HDR_SAVECTX); ++ ++ /* Skip key loading if already shared */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ /* Derive and load HMAC split key via DKP (ERA >= 6) */ ++ caam_desc_add_proto_dkp(desc, sess->auth_algtype, ++ sess->auth_key, sess->auth_klen, sess->split_key_pad_len); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* Class 2 OPERATION: HMAC init+final, encrypt (generate ICV) */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS2_ALG | ++ sess->auth_algtype | OP_ALG_AAI_HMAC_PRECOMP | ++ OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT); ++ ++ /* ++ * VARSEQINLEN = SEQINLEN (= assoclen + cryptlen). ++ * All input data is fed to HMAC — no AAD/payload split needed ++ * since there is no cipher to separate them. ++ */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* VARSEQOUTLEN = SEQINLEN (skip passthrough in output) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Skip passthrough data in output (bounce buffer already has it) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_SKIP | FIFOLDST_VLF); ++ ++ /* Feed all data to Class 2 HMAC (LAST2 for finalization) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG | FIFOLD_TYPE_LAST2); ++ ++ /* Write HMAC ICV from Class 2 context */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_STORE | LDST_CLASS_2_CCB | ++ LDST_SRCDST_BYTE_CONTEXT | sess->icvlen); ++ ++ sess->enc_shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++int ++caam_null_hmac_build_dec_shdesc(struct caam_session *sess, device_t dev) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ int error; ++ ++ error = caam_dma_alloc(dev, &sess->dec_shdesc, CAAM_DESC_MAX_BYTES); ++ if (error != 0) ++ return (error); ++ ++ desc = sess->dec_shdesc.vaddr; ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL | HDR_SAVECTX); ++ ++ /* Skip key loading if already shared */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ /* Derive and load HMAC split key via DKP (ERA >= 6) */ ++ caam_desc_add_proto_dkp(desc, sess->auth_algtype, ++ sess->auth_key, sess->auth_klen, sess->split_key_pad_len); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* Class 2 OPERATION: HMAC verify (decrypt + ICV check) */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS2_ALG | ++ sess->auth_algtype | OP_ALG_AAI_HMAC_PRECOMP | ++ OP_ALG_AS_INITFINAL | OP_ALG_DECRYPT | OP_ALG_ICV_ON); ++ ++ /* ++ * Data length = SEQOUTLEN (= assoclen + cryptlen, excludes ICV). ++ * SEQINLEN includes ICV; SEQOUTLEN does not. ++ */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQOUTLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQOUTLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Skip passthrough data in output (bounce buffer already has it) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_SKIP | FIFOLDST_VLF); ++ ++ /* Feed data to Class 2 HMAC (no LAST2 yet — ICV follows) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG); ++ ++ /* Read ICV for verification (Class 2, ICV | LAST2) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | ++ FIFOLD_TYPE_ICV | FIFOLD_TYPE_LAST2 | sess->icvlen); ++ ++ sess->dec_shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++/* ================================================================ ++ * NULL+HMAC Job Descriptor ++ * ++ * Simpler than regular ETA — no cipher IV, no DPOVRD needed. ++ * The shared descriptor uses SEQINLEN/SEQOUTLEN directly. ++ * ================================================================ */ ++ ++int ++caam_null_hmac_build_job(struct caam_jr_softc *sc, ++ struct caam_request *req, struct cryptop *crp) ++{ ++ struct caam_session *sess; ++ uint32_t *desc; ++ bus_addr_t buf_pa; ++ uint32_t input_len, output_len; ++ bool encrypt; ++ int shdesc_len; ++ ++ sess = req->sess; ++ desc = req->desc.vaddr; ++ encrypt = CRYPTO_OP_IS_ENCRYPT(crp->crp_op); ++ buf_pa = req->using_dyn ? req->dyn_bounce.paddr : req->bounce.paddr; ++ ++ shdesc_len = encrypt ? sess->enc_shdesc_len : sess->dec_shdesc_len; ++ ++ if (encrypt) { ++ input_len = crp->crp_aad_length + crp->crp_payload_length; ++ output_len = crp->crp_aad_length + crp->crp_payload_length + ++ sess->icvlen; ++ } else { ++ input_len = crp->crp_aad_length + crp->crp_payload_length + ++ sess->icvlen; ++ output_len = crp->crp_aad_length + crp->crp_payload_length; ++ } ++ ++ /* Build job descriptor */ ++ caam_desc_init(desc); ++ ++ { ++ uint32_t hdr = caam_to_cpu32(desc[0]); ++ ++ hdr |= HDR_SHARED | HDR_SHARE_DEFER | HDR_REVERSE; ++ hdr |= (shdesc_len << HDR_START_IDX_SHIFT); ++ desc[0] = cpu_to_caam32(hdr); ++ } ++ ++ /* Shared descriptor pointer */ ++ if (encrypt) ++ caam_desc_add_ptr(desc, sess->enc_shdesc.paddr); ++ else ++ caam_desc_add_ptr(desc, sess->dec_shdesc.paddr); ++ ++ /* === JD body (runs FIRST with HDR_REVERSE) === */ ++ ++ /* SEQ IN PTR */ ++ caam_desc_add_word(desc, CMD_SEQ_IN_PTR | input_len); ++ caam_desc_add_ptr(desc, buf_pa); ++ ++ /* SEQ OUT PTR */ ++ caam_desc_add_word(desc, CMD_SEQ_OUT_PTR | output_len); ++ caam_desc_add_ptr(desc, buf_pa); ++ ++ return (0); ++} ++ ++/* ================================================================ ++ * Cipher Job Descriptor ++ * ++ * Layout: ++ * [0] JD header (SHARED | SHARE_DEFER | REVERSE) ++ * [1-2] Shared descriptor pointer (64-bit) ++ * [3..] JD body: LOAD IV (inline), SEQ IN PTR, SEQ OUT PTR ++ * ++ * For XTS: IV loaded as two 8-byte halves at CONTEXT1+0x20 and 0x30. ++ * For CBC/DES: IV loaded at CONTEXT1+0x00. ++ * For CTR: IV (full counter block) loaded at CONTEXT1+0x00. ++ * For ECB: no IV. ++ * ================================================================ */ ++ ++int ++caam_cipher_build_job(struct caam_jr_softc *sc, struct caam_request *req, ++ struct cryptop *crp) ++{ ++ struct caam_session *sess; ++ uint32_t *desc; ++ bus_addr_t buf_pa; ++ uint32_t cryptlen; ++ bool encrypt; ++ int shdesc_len; ++ uint8_t iv[AES_BLOCK_LEN]; ++ ++ sess = req->sess; ++ desc = req->desc.vaddr; ++ encrypt = CRYPTO_OP_IS_ENCRYPT(crp->crp_op); ++ buf_pa = req->using_dyn ? req->dyn_bounce.paddr : req->bounce.paddr; ++ ++ cryptlen = crp->crp_payload_length; ++ shdesc_len = encrypt ? sess->enc_shdesc_len : sess->dec_shdesc_len; ++ ++ /* Build job descriptor */ ++ caam_desc_init(desc); ++ ++ { ++ uint32_t hdr = caam_to_cpu32(desc[0]); ++ ++ hdr |= HDR_SHARED | HDR_SHARE_DEFER | HDR_REVERSE; ++ hdr |= (shdesc_len << HDR_START_IDX_SHIFT); ++ desc[0] = cpu_to_caam32(hdr); ++ } ++ ++ /* Shared descriptor pointer */ ++ if (encrypt) ++ caam_desc_add_ptr(desc, sess->enc_shdesc.paddr); ++ else ++ caam_desc_add_ptr(desc, sess->dec_shdesc.paddr); ++ ++ /* === JD body (runs FIRST with HDR_REVERSE) === */ ++ ++ /* Load IV if applicable */ ++ if (sess->ivlen > 0) { ++ crypto_read_iv(crp, iv); ++ ++ if (caam_cipher_is_xts(sess)) { ++ /* ++ * XTS: load 16-byte tweak as two 8-byte halves ++ * into CONTEXT1 at offsets 0x20 and 0x30. ++ */ ++ caam_desc_add_word(desc, ++ CMD_LOAD | LDST_CLASS_1_CCB | LDST_IMM | ++ LDST_SRCDST_BYTE_CONTEXT | ++ (0x20 << LDST_OFFSET_SHIFT) | 8); ++ caam_desc_add_key_imm(desc, iv, 8); ++ ++ caam_desc_add_word(desc, ++ CMD_LOAD | LDST_CLASS_1_CCB | LDST_IMM | ++ LDST_SRCDST_BYTE_CONTEXT | ++ (0x30 << LDST_OFFSET_SHIFT) | 8); ++ caam_desc_add_key_imm(desc, iv + 8, 8); ++ } else { ++ /* ++ * CBC/CTR/DES: load IV at CONTEXT1+0x00. ++ */ ++ caam_desc_add_word(desc, ++ CMD_LOAD | LDST_CLASS_1_CCB | LDST_IMM | ++ LDST_SRCDST_BYTE_CONTEXT | sess->ivlen); ++ caam_desc_add_key_imm(desc, iv, sess->ivlen); ++ } ++ } ++ ++ /* SEQ IN PTR: input data (cipher-only, no AAD) */ ++ caam_desc_add_word(desc, CMD_SEQ_IN_PTR | cryptlen); ++ caam_desc_add_ptr(desc, buf_pa); ++ ++ /* SEQ OUT PTR: output data (same size, no ICV) */ ++ caam_desc_add_word(desc, CMD_SEQ_OUT_PTR | cryptlen); ++ caam_desc_add_ptr(desc, buf_pa); ++ ++ return (0); ++} +diff --git a/sys/dev/caam/caam_crypto.c b/sys/dev/caam/caam_crypto.c +new file mode 100644 +index 00000000000..31267099dc7 +--- /dev/null ++++ b/sys/dev/caam/caam_crypto.c +@@ -0,0 +1,864 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * CAAM opencrypto integration — connects CAAM Job Ring hardware to ++ * FreeBSD's opencrypto framework for IPsec and kernel crypto. ++ * ++ * Architecture: ++ * opencrypto → caam_process() → bounce buffer copy → caam_jr_enqueue() ++ * caam_jr_task() → caam_crypto_done() → bounce copy-back → crypto_done() ++ * ++ * Supported algorithms: ++ * CSP_MODE_AEAD: AES-GCM (128/192/256) ++ * CSP_MODE_ETA: {AES-CBC,AES-CTR,DES-CBC,3DES-CBC} + HMAC-{SHA1,256,384,512,MD5} ++ * CSP_MODE_ETA: NULL cipher + HMAC (auth-only) ++ * CSP_MODE_CIPHER: AES-{CBC,CTR,XTS}, DES-CBC, 3DES-CBC ++ * CSP_MODE_DIGEST: SHA-{1,224,256,384,512}, MD5, HMAC variants ++ * ++ * Bounce buffer strategy: ++ * Each request has a pre-mapped 2048-byte bounce buffer covering standard ++ * MTU + AAD + ICV. For oversized payloads, a dynamic bounce buffer is ++ * allocated on demand. Data is copied in before submission and copied ++ * back on completion. This avoids per-request DMA mapping of mbufs. ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++ ++#include ++ ++#include "caam.h" ++#include "caam_regs.h" ++#include "caam_desc.h" ++#include "caam_jr.h" ++#include "caam_crypto.h" ++ ++static MALLOC_DEFINE(M_CAAM_CRYPTO, "caam_crypto", "CAAM crypto requests"); ++ ++/* ================================================================ ++ * Request Pool Management ++ * ++ * Pre-allocated pool of CAAM_JR_DEPTH request structures. Descriptor ++ * and bounce buffers are allocated in bulk (two large DMA regions) ++ * and sliced into per-request chunks. This uses ~1.2MB per JR instead ++ * of ~4MB with individual page-aligned allocations. ++ * ++ * Managed as a singly-linked free list indexed by next_free. ++ * ================================================================ */ ++ ++static int ++caam_pool_init(struct caam_jr_softc *sc) ++{ ++ struct caam_request *req; ++ int error, i; ++ ++ sc->sc_requests = malloc(sizeof(struct caam_request) * CAAM_JR_DEPTH, ++ M_CAAM_CRYPTO, M_WAITOK | M_ZERO); ++ ++ /* Bulk DMA: all descriptors (512 * 256 = 128KB) */ ++ error = caam_dma_alloc(sc->sc_dev, &sc->sc_desc_bulk, ++ (bus_size_t)CAAM_JR_DEPTH * CAAM_DESC_MAX_BYTES); ++ if (error != 0) ++ goto fail_requests; ++ ++ /* Bulk DMA: all bounce buffers (512 * 2048 = 1MB) */ ++ error = caam_dma_alloc(sc->sc_dev, &sc->sc_bounce_bulk, ++ (bus_size_t)CAAM_JR_DEPTH * CAAM_BOUNCE_SZ); ++ if (error != 0) ++ goto fail_desc; ++ ++ mtx_init(&sc->sc_pool_lock, "caam_pool", NULL, MTX_DEF); ++ sc->sc_pool_head = 0; ++ sc->sc_blocked = false; ++ ++ for (i = 0; i < CAAM_JR_DEPTH; i++) { ++ req = &sc->sc_requests[i]; ++ req->next_free = i + 1; ++ ++ /* Point to slice of bulk descriptor allocation */ ++ req->desc.tag = NULL; /* Sentinel: sub-allocation */ ++ req->desc.map = NULL; ++ req->desc.vaddr = (uint8_t *)sc->sc_desc_bulk.vaddr + ++ i * CAAM_DESC_MAX_BYTES; ++ req->desc.paddr = sc->sc_desc_bulk.paddr + ++ i * CAAM_DESC_MAX_BYTES; ++ ++ /* Point to slice of bulk bounce allocation */ ++ req->bounce.tag = NULL; ++ req->bounce.map = NULL; ++ req->bounce.vaddr = (uint8_t *)sc->sc_bounce_bulk.vaddr + ++ i * CAAM_BOUNCE_SZ; ++ req->bounce.paddr = sc->sc_bounce_bulk.paddr + ++ i * CAAM_BOUNCE_SZ; ++ ++ req->dyn_bounce.tag = NULL; ++ req->using_dyn = false; ++ } ++ ++ /* Terminate free list */ ++ sc->sc_requests[CAAM_JR_DEPTH - 1].next_free = -1; ++ ++ device_printf(sc->sc_dev, ++ "request pool: %d entries (%zuKB descs + %zuKB bounce)\n", ++ CAAM_JR_DEPTH, ++ (size_t)(CAAM_JR_DEPTH * CAAM_DESC_MAX_BYTES / 1024), ++ (size_t)(CAAM_JR_DEPTH * CAAM_BOUNCE_SZ / 1024)); ++ ++ return (0); ++ ++fail_desc: ++ caam_dma_free(&sc->sc_desc_bulk); ++fail_requests: ++ free(sc->sc_requests, M_CAAM_CRYPTO); ++ sc->sc_requests = NULL; ++ return (error); ++} ++ ++static void ++caam_pool_fini(struct caam_jr_softc *sc) ++{ ++ struct caam_request *req; ++ int i; ++ ++ if (sc->sc_requests == NULL) ++ return; ++ ++ /* Free any outstanding dynamic bounces */ ++ for (i = 0; i < CAAM_JR_DEPTH; i++) { ++ req = &sc->sc_requests[i]; ++ if (req->using_dyn) ++ caam_dma_free(&req->dyn_bounce); ++ } ++ ++ caam_dma_free(&sc->sc_bounce_bulk); ++ caam_dma_free(&sc->sc_desc_bulk); ++ ++ mtx_destroy(&sc->sc_pool_lock); ++ free(sc->sc_requests, M_CAAM_CRYPTO); ++ sc->sc_requests = NULL; ++} ++ ++static struct caam_request * ++caam_pool_alloc(struct caam_jr_softc *sc) ++{ ++ struct caam_request *req; ++ int idx; ++ ++ mtx_lock(&sc->sc_pool_lock); ++ idx = sc->sc_pool_head; ++ if (idx < 0) { ++ mtx_unlock(&sc->sc_pool_lock); ++ return (NULL); ++ } ++ req = &sc->sc_requests[idx]; ++ sc->sc_pool_head = req->next_free; ++ req->next_free = -1; ++ mtx_unlock(&sc->sc_pool_lock); ++ ++ return (req); ++} ++ ++static void ++caam_pool_free(struct caam_jr_softc *sc, struct caam_request *req) ++{ ++ int idx; ++ ++ /* Free dynamic bounce buffer if allocated */ ++ if (req->using_dyn) { ++ caam_dma_free(&req->dyn_bounce); ++ req->using_dyn = false; ++ } ++ ++ req->crp = NULL; ++ req->sess = NULL; ++ req->sc = NULL; ++ ++ idx = req - sc->sc_requests; ++ ++ mtx_lock(&sc->sc_pool_lock); ++ req->next_free = sc->sc_pool_head; ++ sc->sc_pool_head = idx; ++ mtx_unlock(&sc->sc_pool_lock); ++} ++ ++/* ================================================================ ++ * Probesession — validate algorithm support ++ * ================================================================ */ ++ ++static bool ++caam_valid_aes_klen(int klen) ++{ ++ ++ return (klen == 16 || klen == 24 || klen == 32); ++} ++ ++int ++caam_probesession(device_t dev, const struct crypto_session_params *csp) ++{ ++ ++ if (csp->csp_flags != 0) ++ return (EINVAL); ++ ++ switch (csp->csp_mode) { ++ case CSP_MODE_AEAD: ++ /* AES-GCM-16 only */ ++ if (csp->csp_cipher_alg != CRYPTO_AES_NIST_GCM_16) ++ return (EINVAL); ++ if (!caam_valid_aes_klen(csp->csp_cipher_klen)) ++ return (EINVAL); ++ if (csp->csp_ivlen != AES_GCM_IV_LEN) ++ return (EINVAL); ++ if (csp->csp_auth_mlen != 0 && ++ csp->csp_auth_mlen != AES_GCM_TAG_LEN) ++ return (EINVAL); ++ break; ++ ++ case CSP_MODE_ETA: ++ /* Cipher + HMAC (encrypt-then-authenticate) */ ++ switch (csp->csp_cipher_alg) { ++ case CRYPTO_AES_CBC: ++ case CRYPTO_AES_ICM: ++ if (!caam_valid_aes_klen(csp->csp_cipher_klen)) ++ return (EINVAL); ++ break; ++ case CRYPTO_DES_CBC: ++ if (csp->csp_cipher_klen != 8) ++ return (EINVAL); ++ break; ++ case CRYPTO_3DES_CBC: ++ if (csp->csp_cipher_klen != 24) ++ return (EINVAL); ++ break; ++ case CRYPTO_NULL_CBC: ++ break; ++ default: ++ return (EINVAL); ++ } ++ switch (csp->csp_auth_alg) { ++ case CRYPTO_SHA1_HMAC: ++ case CRYPTO_SHA2_256_HMAC: ++ case CRYPTO_SHA2_384_HMAC: ++ case CRYPTO_SHA2_512_HMAC: ++ case CRYPTO_MD5_HMAC: ++ break; ++ default: ++ return (EINVAL); ++ } ++ if (csp->csp_auth_klen > CAAM_MAX_SPLIT_KEY_LEN) ++ return (EINVAL); ++ break; ++ ++ case CSP_MODE_DIGEST: ++ /* Standalone hash or HMAC */ ++ switch (csp->csp_auth_alg) { ++ case CRYPTO_SHA1: ++ case CRYPTO_SHA2_224: ++ case CRYPTO_SHA2_256: ++ case CRYPTO_SHA2_384: ++ case CRYPTO_SHA2_512: ++ case CRYPTO_MD5: ++ /* Plain hash — no key allowed */ ++ if (csp->csp_auth_klen != 0) ++ return (EINVAL); ++ break; ++ case CRYPTO_SHA1_HMAC: ++ case CRYPTO_SHA2_224_HMAC: ++ case CRYPTO_SHA2_256_HMAC: ++ case CRYPTO_SHA2_384_HMAC: ++ case CRYPTO_SHA2_512_HMAC: ++ case CRYPTO_MD5_HMAC: ++ /* HMAC — key required, bounded by auth_key buffer */ ++ if (csp->csp_auth_klen == 0 || ++ csp->csp_auth_klen > CAAM_MAX_SPLIT_KEY_LEN) ++ return (EINVAL); ++ break; ++ default: ++ return (EINVAL); ++ } ++ break; ++ ++ case CSP_MODE_CIPHER: ++ switch (csp->csp_cipher_alg) { ++ case CRYPTO_AES_CBC: ++ case CRYPTO_AES_ICM: ++ if (!caam_valid_aes_klen(csp->csp_cipher_klen)) ++ return (EINVAL); ++ break; ++ case CRYPTO_AES_XTS: ++ /* XTS uses double key: enc_key || tweak_key */ ++ if (csp->csp_cipher_klen != 32 && ++ csp->csp_cipher_klen != 64) ++ return (EINVAL); ++ break; ++ case CRYPTO_DES_CBC: ++ if (csp->csp_cipher_klen != 8) ++ return (EINVAL); ++ break; ++ case CRYPTO_3DES_CBC: ++ if (csp->csp_cipher_klen != 24) ++ return (EINVAL); ++ break; ++ default: ++ return (EINVAL); ++ } ++ break; ++ ++ default: ++ return (EINVAL); ++ } ++ ++ return (CRYPTODEV_PROBE_HARDWARE); ++} ++ ++/* ================================================================ ++ * Newsession / Freesession — session lifecycle ++ * ================================================================ */ ++ ++/* ++ * Map FreeBSD cipher algorithm to CAAM algorithm selector + AAI. ++ */ ++uint32_t ++caam_cipher_algtype(int cipher_alg) ++{ ++ ++ switch (cipher_alg) { ++ case CRYPTO_AES_CBC: ++ return (OP_ALG_ALGSEL_AES | OP_ALG_AAI_CBC); ++ case CRYPTO_AES_ICM: ++ return (OP_ALG_ALGSEL_AES | OP_ALG_AAI_CTR_MOD128); ++ case CRYPTO_AES_XTS: ++ return (OP_ALG_ALGSEL_AES | OP_ALG_AAI_XTS); ++ case CRYPTO_DES_CBC: ++ return (OP_ALG_ALGSEL_DES | OP_ALG_AAI_CBC); ++ case CRYPTO_3DES_CBC: ++ return (OP_ALG_ALGSEL_3DES | OP_ALG_AAI_CBC); ++ case CRYPTO_NULL_CBC: ++ return (0); /* No cipher operation */ ++ default: ++ return (0); ++ } ++} ++ ++/* ++ * IV length for cipher algorithms. ++ */ ++int ++caam_cipher_ivlen(int cipher_alg) ++{ ++ ++ switch (cipher_alg) { ++ case CRYPTO_AES_CBC: ++ case CRYPTO_AES_XTS: ++ return (AES_BLOCK_LEN); /* 16 */ ++ case CRYPTO_AES_ICM: ++ return (AES_BLOCK_LEN); /* 16-byte CTR IV/nonce */ ++ case CRYPTO_DES_CBC: ++ case CRYPTO_3DES_CBC: ++ return (8); /* DES block = 8 */ ++ default: ++ return (0); ++ } ++} ++ ++/* ++ * Map FreeBSD hash/HMAC algorithm ID to CAAM algorithm selector. ++ */ ++uint32_t ++caam_auth_algsel(int auth_alg) ++{ ++ ++ switch (auth_alg) { ++ case CRYPTO_SHA1: ++ case CRYPTO_SHA1_HMAC: ++ return (OP_ALG_ALGSEL_SHA1); ++ case CRYPTO_SHA2_224: ++ case CRYPTO_SHA2_224_HMAC: ++ return (OP_ALG_ALGSEL_SHA224); ++ case CRYPTO_SHA2_256: ++ case CRYPTO_SHA2_256_HMAC: ++ return (OP_ALG_ALGSEL_SHA256); ++ case CRYPTO_SHA2_384: ++ case CRYPTO_SHA2_384_HMAC: ++ return (OP_ALG_ALGSEL_SHA384); ++ case CRYPTO_SHA2_512: ++ case CRYPTO_SHA2_512_HMAC: ++ return (OP_ALG_ALGSEL_SHA512); ++ case CRYPTO_MD5: ++ case CRYPTO_MD5_HMAC: ++ return (OP_ALG_ALGSEL_MD5); ++ default: ++ return (0); ++ } ++} ++ ++/* ++ * Full hash digest length for the given hash/HMAC algorithm. ++ */ ++int ++caam_auth_digest_len(int auth_alg) ++{ ++ ++ switch (auth_alg) { ++ case CRYPTO_MD5: ++ case CRYPTO_MD5_HMAC: ++ return (16); ++ case CRYPTO_SHA1: ++ case CRYPTO_SHA1_HMAC: ++ return (20); ++ case CRYPTO_SHA2_224: ++ case CRYPTO_SHA2_224_HMAC: ++ return (28); ++ case CRYPTO_SHA2_256: ++ case CRYPTO_SHA2_256_HMAC: ++ return (32); ++ case CRYPTO_SHA2_384: ++ case CRYPTO_SHA2_384_HMAC: ++ return (48); ++ case CRYPTO_SHA2_512: ++ case CRYPTO_SHA2_512_HMAC: ++ return (64); ++ default: ++ return (0); ++ } ++} ++ ++int ++caam_newsession(device_t dev, crypto_session_t cses, ++ const struct crypto_session_params *csp) ++{ ++ struct caam_session *sess; ++ int error; ++ ++ sess = crypto_get_driver_session(cses); ++ ++ /* Copy cipher key (if present) */ ++ sess->enc_klen = csp->csp_cipher_klen; ++ if (sess->enc_klen > 0 && csp->csp_cipher_key != NULL) ++ memcpy(sess->enc_key, csp->csp_cipher_key, sess->enc_klen); ++ ++ switch (csp->csp_mode) { ++ case CSP_MODE_AEAD: ++ sess->alg_type = CAAM_ALG_GCM; ++ 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; ++ ++ error = caam_gcm_build_enc_shdesc(sess, dev); ++ if (error != 0) ++ return (error); ++ error = caam_gcm_build_dec_shdesc(sess, dev); ++ if (error != 0) { ++ caam_dma_free(&sess->enc_shdesc); ++ return (error); ++ } ++ break; ++ ++ case CSP_MODE_ETA: ++ if (csp->csp_cipher_alg == CRYPTO_NULL_CBC) { ++ sess->alg_type = CAAM_ALG_NULL_HMAC; ++ } else { ++ sess->alg_type = CAAM_ALG_CBC_HMAC; ++ } ++ sess->cipher_algtype = caam_cipher_algtype( ++ csp->csp_cipher_alg); ++ sess->ivlen = caam_cipher_ivlen(csp->csp_cipher_alg); ++ sess->icvlen = (csp->csp_auth_mlen != 0) ? ++ csp->csp_auth_mlen : ++ caam_auth_digest_len(csp->csp_auth_alg); ++ sess->auth_algtype = caam_auth_algsel(csp->csp_auth_alg); ++ ++ if (sess->auth_algtype == 0) ++ return (EINVAL); ++ ++ /* ++ * Store raw auth key for DKP (Derived Key Protocol). ++ * On ERA >= 6, the shared descriptor uses a DKP OPERATION ++ * to derive the HMAC split key inline at DECO runtime, ++ * instead of pre-computing it via a separate JR submission. ++ */ ++ 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->split_key_pad_len = caam_split_key_pad_len( ++ sess->auth_algtype & OP_ALG_ALGSEL_MASK); ++ ++ if (sess->alg_type == CAAM_ALG_NULL_HMAC) { ++ error = caam_null_hmac_build_enc_shdesc(sess, dev); ++ if (error != 0) ++ return (error); ++ error = caam_null_hmac_build_dec_shdesc(sess, dev); ++ } else { ++ error = caam_eta_build_enc_shdesc(sess, dev); ++ if (error != 0) ++ return (error); ++ error = caam_eta_build_dec_shdesc(sess, dev); ++ } ++ if (error != 0) { ++ caam_dma_free(&sess->enc_shdesc); ++ return (error); ++ } ++ break; ++ ++ case CSP_MODE_DIGEST: ++ sess->auth_algtype = caam_auth_algsel(csp->csp_auth_alg); ++ if (sess->auth_algtype == 0) ++ return (EINVAL); ++ sess->icvlen = (csp->csp_auth_mlen != 0) ? ++ csp->csp_auth_mlen : ++ caam_auth_digest_len(csp->csp_auth_alg); ++ sess->ivlen = 0; ++ sess->enc_klen = 0; ++ ++ if (csp->csp_auth_klen > 0) { ++ /* HMAC */ ++ sess->alg_type = CAAM_ALG_HMAC; ++ 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->split_key_pad_len = caam_split_key_pad_len( ++ sess->auth_algtype & OP_ALG_ALGSEL_MASK); ++ } else { ++ /* Plain hash */ ++ sess->alg_type = CAAM_ALG_HASH; ++ sess->auth_klen = 0; ++ } ++ ++ error = caam_hash_build_shdesc(sess, dev); ++ if (error != 0) ++ return (error); ++ /* No separate dec_shdesc — verify done in software */ ++ break; ++ ++ case CSP_MODE_CIPHER: ++ sess->alg_type = CAAM_ALG_CIPHER; ++ sess->cipher_algtype = caam_cipher_algtype(csp->csp_cipher_alg); ++ sess->ivlen = caam_cipher_ivlen(csp->csp_cipher_alg); ++ sess->icvlen = 0; /* No authentication */ ++ ++ if (sess->cipher_algtype == 0) ++ return (EINVAL); ++ ++ error = caam_cipher_build_enc_shdesc(sess, dev); ++ if (error != 0) ++ return (error); ++ error = caam_cipher_build_dec_shdesc(sess, dev); ++ if (error != 0) { ++ caam_dma_free(&sess->enc_shdesc); ++ return (error); ++ } ++ break; ++ ++ default: ++ return (EINVAL); ++ } ++ ++ return (0); ++} ++ ++void ++caam_freesession(device_t dev, crypto_session_t cses) ++{ ++ struct caam_session *sess; ++ ++ sess = crypto_get_driver_session(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->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(&sess->enc_shdesc); ++ caam_dma_free(&sess->dec_shdesc); ++} ++ ++/* ================================================================ ++ * Completion callback — invoked from caam_jr_task() for each ++ * completed job descriptor. ++ * ++ * Maps CAAM hardware status to crp_etype, copies results back ++ * from the bounce buffer, returns the request to the pool, ++ * unblocks opencrypto if needed, and calls crypto_done(). ++ * ================================================================ */ ++ ++static void ++caam_crypto_done(uint32_t status, void *arg) ++{ ++ struct caam_request *req = arg; ++ struct caam_jr_softc *sc = req->sc; ++ struct cryptop *crp = req->crp; ++ struct caam_session *sess = req->sess; ++ uint8_t *buf; ++ bool encrypt, blocked; ++ uint32_t ssrc; ++ ++ encrypt = CRYPTO_OP_IS_ENCRYPT(crp->crp_op); ++ buf = req->using_dyn ? req->dyn_bounce.vaddr : req->bounce.vaddr; ++ ++ /* Map CAAM status to error code */ ++ if (status == 0) { ++ crp->crp_etype = 0; ++ } else { ++ ssrc = status & JRSTA_SSRC_MASK; ++ if (ssrc == JRSTA_SSRC_JUMP_HALT_USER) { ++ /* Informational condition code, not an error */ ++ crp->crp_etype = 0; ++ } else if (ssrc == JRSTA_SSRC_CCB_ERROR && ++ (status & CCB_ERRID_MASK) == CCB_ERR_ICV_CHECK) { ++ crp->crp_etype = EBADMSG; ++ } else { ++ crp->crp_etype = EIO; ++ device_printf(sc->sc_dev, ++ "crypto error: status 0x%08x\n", status); ++ } ++ } ++ ++ /* Copy results back on success */ ++ if (crp->crp_etype == 0) { ++ if (sess->alg_type == CAAM_ALG_HASH || ++ sess->alg_type == CAAM_ALG_HMAC) { ++ /* ++ * Digest mode: computed hash is at ++ * buf[payload_length..payload_length + icvlen]. ++ */ ++ if (crp->crp_op & CRYPTO_OP_VERIFY_DIGEST) { ++ uint8_t expected[64]; /* max SHA-512 */ ++ ++ crypto_copydata(crp, crp->crp_digest_start, ++ sess->icvlen, expected); ++ if (timingsafe_bcmp( ++ buf + crp->crp_payload_length, ++ expected, sess->icvlen) != 0) ++ crp->crp_etype = EBADMSG; ++ } else { ++ crypto_copyback(crp, crp->crp_digest_start, ++ sess->icvlen, ++ buf + crp->crp_payload_length); ++ } ++ } else if (encrypt) { ++ /* Ciphertext at bounce[aad_length..] */ ++ crypto_copyback(crp, crp->crp_payload_start, ++ crp->crp_payload_length, ++ buf + crp->crp_aad_length); ++ /* ICV/tag at bounce[aad_length + payload_length..] */ ++ crypto_copyback(crp, crp->crp_digest_start, ++ sess->icvlen, ++ buf + crp->crp_aad_length + ++ crp->crp_payload_length); ++ } else { ++ /* Plaintext at bounce[aad_length..] */ ++ crypto_copyback(crp, crp->crp_payload_start, ++ crp->crp_payload_length, ++ buf + crp->crp_aad_length); ++ } ++ } ++ ++ /* Return request to pool */ ++ caam_pool_free(sc, req); ++ ++ /* Unblock opencrypto if we were resource-constrained */ ++ mtx_lock(&sc->sc_pool_lock); ++ blocked = sc->sc_blocked; ++ if (blocked) ++ sc->sc_blocked = false; ++ mtx_unlock(&sc->sc_pool_lock); ++ ++ if (blocked) ++ crypto_unblock(sc->sc_cid, CRYPTO_SYMQ); ++ ++ /* Notify opencrypto framework */ ++ crypto_done(crp); ++} ++ ++/* ================================================================ ++ * Process — submit a crypto request to the CAAM Job Ring ++ * ++ * 1. Allocate request from pre-allocated pool ++ * 2. Copy AAD + payload (+ ICV for decrypt) into bounce buffer ++ * 3. Build the per-request job descriptor ++ * 4. Submit to the JR hardware via caam_jr_enqueue() ++ * ++ * Returns 0 if the request was accepted (errors reported via ++ * crp_etype + crypto_done). Returns ERESTART if the pool or ++ * ring is temporarily full — opencrypto will retry later. ++ * ================================================================ */ ++ ++int ++caam_process(device_t dev, struct cryptop *crp, int hint) ++{ ++ struct caam_jr_softc *sc; ++ struct caam_session *sess; ++ struct caam_request *req; ++ uint32_t *desc; ++ uint8_t *buf; ++ size_t total_len; ++ int error; ++ bool encrypt; ++ ++ sc = device_get_softc(dev); ++ sess = crypto_get_driver_session(crp->crp_session); ++ encrypt = CRYPTO_OP_IS_ENCRYPT(crp->crp_op); ++ ++ /* Allocate request from pool */ ++ req = caam_pool_alloc(sc); ++ if (__predict_false(req == NULL)) { ++ mtx_lock(&sc->sc_pool_lock); ++ sc->sc_blocked = true; ++ mtx_unlock(&sc->sc_pool_lock); ++ return (ERESTART); ++ } ++ ++ req->crp = crp; ++ req->sess = sess; ++ req->sc = sc; ++ ++ /* ++ * Determine bounce buffer size. ++ * Max of input and output is always aad + payload + icvlen. ++ * Use size_t to avoid signed integer overflow. ++ */ ++ total_len = (size_t)crp->crp_aad_length + ++ (size_t)crp->crp_payload_length + (size_t)sess->icvlen; ++ ++ if (__predict_false(total_len > CAAM_BOUNCE_SZ)) { ++ /* Oversized: allocate dynamic bounce */ ++ error = caam_dma_alloc(sc->sc_dev, &req->dyn_bounce, ++ total_len); ++ if (error != 0) { ++ caam_pool_free(sc, req); ++ crp->crp_etype = ENOMEM; ++ crypto_done(crp); ++ return (0); ++ } ++ req->using_dyn = true; ++ buf = req->dyn_bounce.vaddr; ++ } else { ++ buf = req->bounce.vaddr; ++ } ++ ++ /* ++ * Copy data into the bounce buffer. ++ * ++ * Layout: [AAD (aad_length)] [payload (payload_length)] [ICV (icvlen)] ++ * ++ * For encrypt input: AAD + plaintext ++ * For decrypt input: AAD + ciphertext + ICV ++ */ ++ if (crp->crp_aad_length > 0) { ++ if (crp->crp_aad != NULL) ++ memcpy(buf, crp->crp_aad, crp->crp_aad_length); ++ else ++ crypto_copydata(crp, crp->crp_aad_start, ++ crp->crp_aad_length, buf); ++ } ++ ++ if (crp->crp_payload_length > 0) ++ crypto_copydata(crp, crp->crp_payload_start, ++ crp->crp_payload_length, ++ buf + crp->crp_aad_length); ++ ++ if (!encrypt && sess->alg_type != CAAM_ALG_HASH && ++ sess->alg_type != CAAM_ALG_HMAC) ++ crypto_copydata(crp, crp->crp_digest_start, ++ sess->icvlen, ++ buf + crp->crp_aad_length + crp->crp_payload_length); ++ ++ /* Build the per-request job descriptor */ ++ if (sess->alg_type == CAAM_ALG_GCM) ++ error = caam_gcm_build_job(sc, req, crp); ++ else if (sess->alg_type == CAAM_ALG_CIPHER) ++ error = caam_cipher_build_job(sc, req, crp); ++ else if (sess->alg_type == CAAM_ALG_NULL_HMAC) ++ error = caam_null_hmac_build_job(sc, req, crp); ++ else if (sess->alg_type == CAAM_ALG_HASH || ++ sess->alg_type == CAAM_ALG_HMAC) ++ error = caam_hash_build_job(sc, req, crp); ++ else ++ error = caam_eta_build_job(sc, req, crp); ++ ++ if (__predict_false(error != 0)) { ++ caam_pool_free(sc, req); ++ crp->crp_etype = error; ++ crypto_done(crp); ++ return (0); ++ } ++ ++ /* Submit to the Job Ring */ ++ desc = req->desc.vaddr; ++ error = caam_jr_enqueue(sc, desc, req->desc.paddr, ++ caam_desc_len(desc) * sizeof(uint32_t), ++ caam_crypto_done, req); ++ ++ if (__predict_false(error == ENOSPC)) { ++ /* Ring full — tell opencrypto to retry */ ++ caam_pool_free(sc, req); ++ mtx_lock(&sc->sc_pool_lock); ++ sc->sc_blocked = true; ++ mtx_unlock(&sc->sc_pool_lock); ++ return (ERESTART); ++ } ++ if (__predict_false(error != 0)) { ++ caam_pool_free(sc, req); ++ crp->crp_etype = error; ++ crypto_done(crp); ++ return (0); ++ } ++ ++ return (0); ++} ++ ++/* ================================================================ ++ * Init / Detach — called from caam_jr attach/detach ++ * ================================================================ */ ++ ++int ++caam_crypto_init(struct caam_jr_softc *sc) ++{ ++ int error; ++ ++ /* Allocate request pool with bulk DMA buffers */ ++ error = caam_pool_init(sc); ++ if (error != 0) ++ return (error); ++ ++ /* Register with opencrypto framework */ ++ sc->sc_cid = crypto_get_driverid(sc->sc_dev, ++ sizeof(struct caam_session), CRYPTOCAP_F_HARDWARE); ++ if (sc->sc_cid < 0) { ++ device_printf(sc->sc_dev, ++ "failed to register with opencrypto\n"); ++ caam_pool_fini(sc); ++ return (ENXIO); ++ } ++ ++ device_printf(sc->sc_dev, ++ "registered with opencrypto (driverid %d)\n", sc->sc_cid); ++ ++ return (0); ++} ++ ++void ++caam_crypto_detach(struct caam_jr_softc *sc) ++{ ++ ++ if (sc->sc_cid >= 0) { ++ crypto_unregister_all(sc->sc_cid); ++ sc->sc_cid = -1; ++ } ++ caam_pool_fini(sc); ++} +diff --git a/sys/dev/caam/caam_crypto.h b/sys/dev/caam/caam_crypto.h +new file mode 100644 +index 00000000000..adf316bdc40 +--- /dev/null ++++ b/sys/dev/caam/caam_crypto.h +@@ -0,0 +1,149 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * CAAM opencrypto integration — per-session and per-request structures. ++ */ ++ ++#ifndef _CAAM_CRYPTO_H ++#define _CAAM_CRYPTO_H ++ ++#include ++#include ++#include "caam_jr.h" ++ ++/* Forward declaration */ ++struct caam_qi_drv_ctx; ++ ++/* Algorithm types */ ++#define CAAM_ALG_GCM 1 /* AES-GCM (AEAD) */ ++#define CAAM_ALG_CBC_HMAC 2 /* Cipher + HMAC-SHA (ETA) */ ++#define CAAM_ALG_CIPHER 3 /* Standalone cipher (no auth) */ ++#define CAAM_ALG_NULL_HMAC 4 /* NULL cipher + HMAC (auth-only) */ ++#define CAAM_ALG_HASH 5 /* Standalone hash (SHA, MD5) */ ++#define CAAM_ALG_HMAC 6 /* Standalone HMAC */ ++ ++/* Maximum key sizes */ ++#define CAAM_MAX_KEY_LEN 64 /* AES-256-XTS = 2*32 */ ++#define CAAM_MAX_SPLIT_KEY_LEN 128 /* SHA-512 split key */ ++ ++/* AES-GCM constants */ ++#define AES_GCM_IV_LEN 12 ++#define AES_GCM_TAG_LEN 16 ++ ++/* Bounce buffer for small payloads (covers standard MTU + AAD + ICV) */ ++#define CAAM_BOUNCE_SZ 2048 ++ ++/* ++ * Per-session data, stored by the opencrypto framework. ++ * Allocated as part of crypto_session; retrieved via ++ * crypto_get_driver_session(). ++ */ ++struct caam_session { ++ int alg_type; /* CAAM_ALG_GCM or CAAM_ALG_CBC_HMAC */ ++ int ivlen; ++ int icvlen; ++ int enc_klen; /* Cipher key length (bytes) */ ++ ++ /* Pre-built shared descriptors (DMA-mapped, CAAM byte order) */ ++ struct caam_dma_mem enc_shdesc; ++ struct caam_dma_mem dec_shdesc; ++ int enc_shdesc_len; /* Words */ ++ int dec_shdesc_len; ++ ++ /* Cipher key (CPU byte order, converted when building shdesc) */ ++ uint8_t enc_key[CAAM_MAX_KEY_LEN]; ++ ++ /* Raw HMAC key (for DKP inline, ERA >= 6) */ ++ uint8_t auth_key[CAAM_MAX_SPLIT_KEY_LEN]; ++ int auth_klen; ++ ++ /* Split key dimensions (for DKP descriptor space reservation) */ ++ int split_key_len; ++ int split_key_pad_len; ++ ++ /* Algorithm type for OPERATION command (CAAM encoding) */ ++ uint32_t cipher_algtype; /* e.g. AES | GCM */ ++ uint32_t auth_algtype; /* e.g. SHA256 | HMAC_PRECOMP */ ++ ++ /* QI backend: driver contexts (NULL for JR sessions) */ ++ struct caam_qi_drv_ctx *qi_enc_ctx; ++ struct caam_qi_drv_ctx *qi_dec_ctx; ++}; ++ ++/* ++ * Per-request context for in-flight crypto operations. ++ * Pre-allocated in a pool of CAAM_JR_DEPTH entries. ++ */ ++struct caam_request { ++ struct caam_jr_softc *sc; /* Owning JR (for callback) */ ++ struct cryptop *crp; ++ struct caam_session *sess; ++ ++ /* Job descriptor (pre-mapped DMA, 256 bytes = 64 words max) */ ++ struct caam_dma_mem desc; ++ ++ /* Bounce buffer for payload I/O (pre-mapped DMA) */ ++ struct caam_dma_mem bounce; ++ ++ /* Dynamic fallback for oversized payloads */ ++ struct caam_dma_mem dyn_bounce; ++ bool using_dyn; ++ ++ /* Pool linkage (free list index; -1 = not in pool) */ ++ int next_free; ++}; ++ ++/* Split key length for given hash algorithm selector */ ++int caam_split_key_len(uint32_t algsel); ++int caam_split_key_pad_len(uint32_t algsel); ++ ++/* Shared descriptor builders */ ++int caam_gcm_build_enc_shdesc(struct caam_session *sess, device_t dev); ++int caam_gcm_build_dec_shdesc(struct caam_session *sess, device_t dev); ++int caam_eta_build_enc_shdesc(struct caam_session *sess, device_t dev); ++int caam_eta_build_dec_shdesc(struct caam_session *sess, device_t dev); ++int caam_cipher_build_enc_shdesc(struct caam_session *sess, device_t dev); ++int caam_cipher_build_dec_shdesc(struct caam_session *sess, device_t dev); ++int caam_null_hmac_build_enc_shdesc(struct caam_session *sess, device_t dev); ++int caam_null_hmac_build_dec_shdesc(struct caam_session *sess, device_t dev); ++ ++/* Job descriptor builders */ ++int caam_gcm_build_job(struct caam_jr_softc *sc, ++ struct caam_request *req, struct cryptop *crp); ++int caam_eta_build_job(struct caam_jr_softc *sc, ++ struct caam_request *req, struct cryptop *crp); ++int caam_cipher_build_job(struct caam_jr_softc *sc, ++ struct caam_request *req, struct cryptop *crp); ++int caam_null_hmac_build_job(struct caam_jr_softc *sc, ++ struct caam_request *req, struct cryptop *crp); ++ ++/* Hash/HMAC descriptor builders (caam_hash.c) */ ++int caam_hash_build_shdesc(struct caam_session *sess, device_t dev); ++int caam_hash_build_job(struct caam_jr_softc *sc, ++ struct caam_request *req, struct cryptop *crp); ++ ++/* Opencrypto DEVMETHOD implementations (referenced from caam_jr_methods[]) */ ++int caam_probesession(device_t dev, ++ const struct crypto_session_params *csp); ++int caam_newsession(device_t dev, crypto_session_t cses, ++ const struct crypto_session_params *csp); ++void caam_freesession(device_t dev, crypto_session_t cses); ++int caam_process(device_t dev, struct cryptop *crp, int hint); ++ ++/* Opencrypto lifecycle (called from caam_jr attach/detach) */ ++int caam_crypto_init(struct caam_jr_softc *sc); ++void caam_crypto_detach(struct caam_jr_softc *sc); ++ ++/* DMA helpers (defined in caam_jr.c, used by crypto code) */ ++int caam_dma_alloc(device_t dev, struct caam_dma_mem *mem, bus_size_t size); ++void caam_dma_free(struct caam_dma_mem *mem); ++ ++/* Algorithm mapping helpers (defined in caam_crypto.c, shared by QI) */ ++uint32_t caam_cipher_algtype(int cipher_alg); ++int caam_cipher_ivlen(int cipher_alg); ++uint32_t caam_auth_algsel(int auth_alg); ++int caam_auth_digest_len(int auth_alg); ++ ++#endif /* _CAAM_CRYPTO_H */ +diff --git a/sys/dev/caam/caam_desc.h b/sys/dev/caam/caam_desc.h +new file mode 100644 +index 00000000000..db50a80fe48 +--- /dev/null ++++ b/sys/dev/caam/caam_desc.h +@@ -0,0 +1,714 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * 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. ++ * ++ * 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). ++ * Construction helpers handle the byte-swap transparently. ++ */ ++ ++#ifndef _CAAM_DESC_H ++#define _CAAM_DESC_H ++ ++#include "caam.h" ++ ++#define CAAM_DESC_MAX_WORDS 64 /* Max descriptor size in 32-bit words */ ++#define CAAM_DESC_MAX_BYTES (CAAM_DESC_MAX_WORDS * sizeof(uint32_t)) ++ ++/* ++ * Descriptor Command Types (bits 31:27) ++ */ ++#define CMD_SHIFT 27 ++#define CMD_MASK (0x1fU << 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 */ ++ ++/* ++ * Job Descriptor Header (word 0) ++ * ++ * Bits 31:27 = 0x16 (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) ++ ++/* ++ * 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. ++ */ ++#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) ++ ++/* Shared Descriptor Header */ ++#define SHR_HDR_DESCLEN_MASK 0x0000003f ++#define SHR_HDR_START_IDX_SHIFT 16 ++ ++/* ++ * KEY Command (bits 31:27 = 0x00) ++ * ++ * Bit 26 = SGF ++ * Bits 25:24 = CLASS (00=none, 01=class1, 10=class2, 11=both) ++ * Bit 23 = IMM (key inline in descriptor) ++ * Bit 22 = ENC (encrypted key) ++ * Bits 21:20 = DEST (00=class reg, 01=split key, 10=JDKEK, 11=TDKEK) ++ * 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 20 ++#define KEY_DEST_CLASS_REG (0x00U << KEY_DEST_SHIFT) /* Class key register */ ++#define KEY_DEST_MDHA_SPLIT (0x01U << KEY_DEST_SHIFT) /* MDHA split key */ ++#define KEY_LENGTH_MASK 0x000003ff ++ ++/* ++ * LOAD / SEQ LOAD / STORE / SEQ STORE commands ++ * ++ * Bits 26:25 = CLASS (00=ind CCB, 01=class1, 10=class2, 11=DECO) ++ * Bit 23 = IMM (immediate data follows) ++ * Bits 22:16 = SRCDST (source or destination register) ++ * 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 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 */ ++ ++/* 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 ++ ++#define LDST_OFFSET_SHIFT 8 ++#define LDST_OFFSET_MASK (0xffU << LDST_OFFSET_SHIFT) ++ ++#define LDST_LEN_SHIFT 0 ++#define 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 ++ ++/* 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) ++ ++/* Additional Algorithm Info (AAI) — bits 12:4 */ ++#define OP_ALG_AAI_SHIFT 4 ++#define OP_ALG_AAI_MASK (0x1ffU << 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) ++ ++/* 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) ++ ++/* Decrypt key derivation */ ++#define OP_ALG_AAI_DK (0x100U << 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) ++ ++/* ++ * Derived Key Protocol (DKP) — protocol info for 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 */ ++#define OP_PCL_DKP_DST_IMM (0U << 12) /* Derived key inline */ ++ ++/* 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) ++ ++/* 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 */ ++ ++/* Direction (bit 0) */ ++#define OP_ALG_DECRYPT 0 ++#define OP_ALG_ENCRYPT 1 ++ ++/* ++ * SEQ IN PTR / SEQ OUT PTR Commands ++ */ ++#define SQIN_RBS (1U << 26) ++#define SQIN_INL (1U << 25) ++#define SQIN_SGF (1U << 24) ++#define SQIN_PRE (1U << 23) ++#define SQIN_EXT (1U << 22) ++#define SQIN_RTO (1U << 21) ++#define SQIN_LEN_MASK 0x0000ffff ++ ++#define SQOUT_SGF (1U << 24) ++#define SQOUT_PRE (1U << 23) ++#define SQOUT_EXT (1U << 22) ++#define SQOUT_LEN_MASK 0x0000ffff ++ ++/* ++ * FIFO LOAD / SEQ FIFO LOAD commands ++ * ++ * Bits 26:25 = CLASS (00=skip, 01=class1, 10=class2, 11=both) ++ * Bit 24 = SGF/VLF (variable length flag for SEQ FIFO) ++ * Bit 23 = IMM (immediate data follows) ++ * Bit 22 = EXT (extended length in next word) ++ * Bits 21:16 = TYPE (data type + action bits) ++ * Bits 15:0 = LENGTH ++ * ++ * TYPE field (6 bits, split into data type [21:19] and action [18:16]): ++ * 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 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 FIFOLD_TYPE_SHIFT 16 ++#define FIFOLD_TYPE_MASK (0x3fU << 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) ++ ++/* 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 FIFOLDST_LEN_MASK 0x0000ffff ++ ++/* ++ * FIFO STORE / SEQ FIFO STORE commands ++ * ++ * Bits 26:25 = CLASS (00=normal, 01=class1key, 10=class2key) ++ * Bit 24 = SGF/VLF ++ * Bit 22 = EXT ++ * 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 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) ++ ++/* ++ * JUMP Command ++ * ++ * Bits 26:25 = CLASS ++ * Bit 24 = JSL (jump save link — used for condition codes) ++ * Bits 23:22 = TYPE (00=local, 01=nonlocal, 10=halt, 11=halt_user) ++ * Bits 17:16 = TEST (00=all, 01=invall, 10=any, 11=invany) ++ * 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 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 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) ++ ++/* 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) ++ ++/* 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) ++ ++#define JUMP_OFFSET_SHIFT 0 ++#define JUMP_OFFSET_MASK 0x000000ff ++ ++/* ++ * MATH Command ++ * ++ * Bits 26 = IFB (immediate four bytes) ++ * Bit 25 = NFU ++ * Bit 24 = STL (store result to MATH register) ++ * Bits 23:20 = FUN (function: add, sub, or, and, xor, etc.) ++ * Bits 19:16 = SRC0 ++ * Bits 15:12 = SRC1 ++ * Bits 11:8 = DEST ++ * Bits 3:0 = LEN (1, 2, 4, or 8 bytes) ++ */ ++#define 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 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 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 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 MATH_LEN_SHIFT 0 ++#define MATH_LEN_1BYTE 0x01 ++#define MATH_LEN_2BYTE 0x02 ++#define MATH_LEN_4BYTE 0x04 ++#define 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 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 MOVE_OFFSET_SHIFT 8 ++#define MOVE_LEN_SHIFT 0 ++ ++/* ++ * SEC4 Scatter-Gather Table Entry ++ * ++ * Used when data spans multiple non-contiguous DMA buffers. ++ * Fields in CAAM byte order. ++ */ ++struct sec4_sg_entry { ++ uint64_t ptr; /* DMA address of buffer */ ++ uint32_t len; /* Buffer length + flags */ ++#define SEC4_SG_OFFSET_MASK 0x00001fff ++#define SEC4_SG_LEN_MASK 0x3fffffff ++#define SEC4_SG_LEN_FIN 0x40000000 /* Final entry */ ++#define SEC4_SG_LEN_EXT 0x80000000 /* Extension (points to more SG) */ ++ uint32_t bpid_offset; /* Buffer Pool ID + offset */ ++} __packed; ++ ++/* ++ * CCB error codes from job status (when SSRC=CCB_ERROR). ++ * Lower 16 bits: bits 15:8 = index, bits 7:4 = CHA ID, bits 3:0 = error ID. ++ */ ++#define CCB_ERRID_MASK 0x0f /* Error ID in bits 3:0 */ ++#define CCB_ERR_ICV_CHECK 0x0a /* ICV verification failed */ ++ ++/* ================================================================ ++ * Descriptor construction helpers. ++ * ++ * All words are stored in CAAM byte order (BE on LS1046A ARM64). ++ * The helpers handle conversion transparently — callers pass native ++ * CPU-endian values and addresses. ++ * ================================================================ */ ++ ++/* Get descriptor length in words (reads header from CAAM byte order) */ ++static __inline int ++caam_desc_len(const uint32_t *desc) ++{ ++ ++ return (caam_to_cpu32(desc[0]) & HDR_DESCLEN_MASK); ++} ++ ++/* Get shared descriptor length in words */ ++static __inline int ++caam_shdesc_len(const uint32_t *desc) ++{ ++ ++ return (caam_to_cpu32(desc[0]) & SHR_HDR_DESCLEN_MASK); ++} ++ ++/* ++ * Initialize a job descriptor header. ++ * Sets CMD_DESC_HDR + 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); ++} ++ ++/* ++ * Initialize a shared descriptor header. ++ * Sets CMD_SH_DESC_HDR + 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. ++ */ ++ desc[0] = cpu_to_caam32(CMD_SH_DESC_HDR | HDR_ONE | options | 1); ++} ++ ++/* Append a command/data word to the descriptor (with byte-swap) */ ++static __inline void ++caam_desc_add_word(uint32_t *desc, uint32_t word) ++{ ++ uint32_t hdr; ++ int len; ++ ++ hdr = caam_to_cpu32(desc[0]); ++ len = hdr & 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)); ++} ++ ++/* ++ * Append a raw 32-bit value without byte-swap. ++ * Used for inline key material that is already in CAAM byte order. ++ */ ++static __inline void ++caam_desc_add_raw(uint32_t *desc, uint32_t raw) ++{ ++ uint32_t hdr; ++ int len; ++ ++ hdr = caam_to_cpu32(desc[0]); ++ len = hdr & 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)); ++} ++ ++/* ++ * Append a 64-bit pointer (as two 32-bit words). ++ * Word order follows CAAM endianness: ++ * BE: high 32 first, low 32 second ++ * LE: low 32 first, high 32 second ++ */ ++static __inline void ++caam_desc_add_ptr(uint32_t *desc, uint64_t ptr) ++{ ++ uint32_t hdr; ++ int len; ++ ++ hdr = caam_to_cpu32(desc[0]); ++ len = hdr & HDR_DESCLEN_MASK; ++ KASSERT(len + 1 < CAAM_DESC_MAX_WORDS, ++ ("caam_desc_add_ptr: descriptor overflow (%d words)", len)); ++ if (caam_big_endian) { ++ desc[len] = htobe32((uint32_t)(ptr >> 32)); ++ desc[len + 1] = htobe32((uint32_t)ptr); ++ } else { ++ desc[len] = (uint32_t)ptr; ++ desc[len + 1] = (uint32_t)(ptr >> 32); ++ } ++ desc[0] = cpu_to_caam32((hdr & ~HDR_DESCLEN_MASK) | (len + 2)); ++} ++ ++/* ++ * Return a pointer to the current append position and advance length. ++ * Used for jump target patching: save the position, then later ++ * set the offset to reach the target. ++ */ ++static __inline uint32_t * ++caam_desc_add_jump(uint32_t *desc, uint32_t options) ++{ ++ uint32_t hdr; ++ int len; ++ uint32_t *jump_word; ++ ++ hdr = caam_to_cpu32(desc[0]); ++ len = hdr & 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)); ++ return (jump_word); ++} ++ ++/* ++ * Patch a JUMP command's offset to jump to the current descriptor end. ++ * jump_cmd: pointer returned by caam_desc_add_jump() ++ */ ++static __inline void ++caam_desc_set_jump_target(uint32_t *desc, uint32_t *jump_cmd) ++{ ++ int jump_idx, cur_len; ++ uint32_t jcmd; ++ ++ /* Index of the jump command within the descriptor */ ++ jump_idx = jump_cmd - desc; ++ 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); ++ *jump_cmd = cpu_to_caam32(jcmd); ++} ++ ++/* ++ * Append inline byte data (key, IV, etc.) to the descriptor. ++ * ++ * 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. ++ * ++ * key_len is rounded up to 4 for word alignment; callers must ensure ++ * the key command's length field reflects the actual byte count. ++ */ ++static __inline void ++caam_desc_add_key_imm(uint32_t *desc, const uint8_t *key, int key_len) ++{ ++ int nwords = (key_len + 3) / 4; ++ uint32_t w; ++ int i; ++ ++ for (i = 0; i < nwords; i++) { ++ memcpy(&w, key + i * 4, sizeof(w)); ++ caam_desc_add_raw(desc, w); ++ } ++} ++ ++/* ++ * Append a Derived Key Protocol (DKP) OPERATION for HMAC split key. ++ * Used on ERA >= 6 instead of KEY + 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 ++ * earlier ERAs. ++ * ++ * algtype: algorithm selector (e.g. OP_ALG_ALGSEL_SHA256) ++ * key: raw HMAC key bytes ++ * keylen: raw HMAC key length in bytes ++ * keylen_pad: split key padded length (determines reserved space) ++ */ ++static __inline void ++caam_desc_add_proto_dkp(uint32_t *desc, uint32_t algtype, ++ const uint8_t *key, int keylen, int keylen_pad) ++{ ++ uint32_t protid, hdr; ++ int words, len; ++ ++ /* ++ * Translate 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); ++ ++ /* OPERATION: DKP with inline source and inline destination */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_UNI_PROTOCOL | protid | ++ OP_PCL_DKP_SRC_IMM | OP_PCL_DKP_DST_IMM | keylen); ++ ++ /* Append raw key inline */ ++ caam_desc_add_key_imm(desc, key, keylen); ++ ++ /* ++ * Reserve space for derived key output. ++ * The DKP writes split_key_pad_len bytes starting at the raw key ++ * position, so we need (split_key_pad - raw_key) extra words. ++ */ ++ words = (roundup2(keylen_pad, 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 + words)); ++ } ++} ++ ++/* ++ * QI Preheader Constants ++ * ++ * Two 32-bit words placed before the shared descriptor in DMA memory. ++ * FQ Context-A points to prehdr[0]. CAAM QI uses these to configure ++ * shared descriptor execution for compound frame processing. ++ */ ++#define PREHDR_RSLS (1U << 31) /* Route SEQ LOAD/STORE to FD */ ++#define PREHDR_ABS (1U << 25) /* Absolute addressing mode */ ++ ++/* ++ * Build a minimal NOP Job Descriptor (for testing ring operation). ++ * Header + JUMP HALT — the DECO halts immediately with status 0. ++ */ ++static __inline void ++caam_desc_build_nop(uint32_t *desc) ++{ ++ ++ caam_desc_init(desc); ++ caam_desc_add_word(desc, CMD_JUMP | JUMP_TYPE_HALT); ++} ++ ++#endif /* _CAAM_DESC_H */ +diff --git a/sys/dev/caam/caam_hash.c b/sys/dev/caam/caam_hash.c +new file mode 100644 +index 00000000000..fee3eb934fc +--- /dev/null ++++ b/sys/dev/caam/caam_hash.c +@@ -0,0 +1,164 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * CAAM hash/HMAC descriptor builders for CSP_MODE_DIGEST. ++ * ++ * Standalone hash (SHA, MD5) and HMAC use Class 2 (MDHA) only. ++ * A single shared descriptor covers both compute and verify — ++ * CAAM always computes the hash; verification (digest comparison) ++ * is done in software in the completion callback. ++ * ++ * Bounce buffer layout: ++ * [payload data (payload_length bytes)] [digest output (icvlen bytes)] ++ * SEQ IN PTR → buf_pa, payload_length ++ * SEQ OUT PTR → buf_pa + payload_length, icvlen ++ */ ++ ++#include ++#include ++#include ++#include ++ ++#include ++ ++#include ++ ++#include "caam.h" ++#include "caam_regs.h" ++#include "caam_desc.h" ++#include "caam_jr.h" ++#include "caam_crypto.h" ++ ++/* ================================================================ ++ * Hash/HMAC Shared Descriptor ++ * ++ * For plain hash: ++ * OPERATION (algtype | INITFINAL | ENCRYPT) ++ * MATH ADD (VARSEQINLEN = SEQINLEN) ++ * SEQ FIFO LOAD (CLASS2, MSG, LAST2, VLF) ++ * SEQ STORE (icvlen, CLASS_2_CCB, BYTE_CONTEXT) ++ * ++ * For HMAC: ++ * JUMP (skip key if shared) ++ * DKP (derive split key inline) ++ * [jump target] ++ * OPERATION (algtype | HMAC_PRECOMP | INITFINAL | ENCRYPT) ++ * MATH ADD (VARSEQINLEN = SEQINLEN) ++ * SEQ FIFO LOAD (CLASS2, MSG, LAST2, VLF) ++ * SEQ STORE (icvlen, CLASS_2_CCB, BYTE_CONTEXT) ++ * ================================================================ */ ++ ++int ++caam_hash_build_shdesc(struct caam_session *sess, device_t dev) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ int error; ++ bool is_hmac; ++ ++ is_hmac = (sess->alg_type == CAAM_ALG_HMAC); ++ ++ error = caam_dma_alloc(dev, &sess->enc_shdesc, CAAM_DESC_MAX_BYTES); ++ if (error != 0) ++ return (error); ++ ++ desc = sess->enc_shdesc.vaddr; ++ caam_shdesc_init(desc, 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); ++ ++ /* Derive and load HMAC split key via DKP (ERA >= 6) */ ++ caam_desc_add_proto_dkp(desc, sess->auth_algtype, ++ sess->auth_key, sess->auth_klen, ++ sess->split_key_pad_len); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ } ++ ++ /* OPERATION: hash/HMAC init+final, always "encrypt" (compute) */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS2_ALG | ++ sess->auth_algtype | ++ (is_hmac ? OP_ALG_AAI_HMAC_PRECOMP : 0) | ++ OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT); ++ ++ /* VARSEQINLEN = SEQINLEN (data length from JD's SEQ IN PTR) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | 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); ++ ++ /* 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); ++ ++ sess->enc_shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++/* ================================================================ ++ * Hash/HMAC Job Descriptor ++ * ++ * Layout: ++ * [0] JD header (SHARED | SHARE_DEFER | REVERSE) ++ * [1-2] Shared descriptor pointer (64-bit) ++ * [3] SEQ IN PTR (payload data) ++ * [4-5] Input DMA pointer ++ * [6] SEQ OUT PTR (digest output) ++ * [7-8] Output DMA pointer ++ * ================================================================ */ ++ ++int ++caam_hash_build_job(struct caam_jr_softc *sc, struct caam_request *req, ++ struct cryptop *crp) ++{ ++ struct caam_session *sess; ++ uint32_t *desc; ++ bus_addr_t buf_pa; ++ uint32_t data_len; ++ int shdesc_len; ++ ++ sess = req->sess; ++ desc = req->desc.vaddr; ++ buf_pa = req->using_dyn ? req->dyn_bounce.paddr : req->bounce.paddr; ++ ++ data_len = crp->crp_payload_length; ++ shdesc_len = sess->enc_shdesc_len; ++ ++ /* Build job descriptor */ ++ caam_desc_init(desc); ++ ++ { ++ uint32_t hdr = caam_to_cpu32(desc[0]); ++ ++ hdr |= HDR_SHARED | HDR_SHARE_DEFER | HDR_REVERSE; ++ hdr |= (shdesc_len << 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) === */ ++ ++ /* SEQ IN PTR: data to hash */ ++ caam_desc_add_word(desc, CMD_SEQ_IN_PTR | data_len); ++ caam_desc_add_ptr(desc, buf_pa); ++ ++ /* SEQ OUT PTR: digest output (immediately after input data) */ ++ caam_desc_add_word(desc, CMD_SEQ_OUT_PTR | sess->icvlen); ++ caam_desc_add_ptr(desc, buf_pa + data_len); ++ ++ return (0); ++} +diff --git a/sys/dev/caam/caam_jr.c b/sys/dev/caam/caam_jr.c +new file mode 100644 +index 00000000000..48aa1fd7f26 +--- /dev/null ++++ b/sys/dev/caam/caam_jr.c +@@ -0,0 +1,730 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * NXP CAAM Job Ring driver. ++ * ++ * Each Job Ring is a child device of the CAAM controller. It manages ++ * a hardware input/output ring pair for submitting crypto job descriptors ++ * and receiving completions. ++ * ++ * Input ring: Array of uint64_t — DMA addresses of job descriptors. ++ * Software writes, hardware reads. ++ * Output ring: Array of {uint64_t desc_addr, uint32_t status} — packed. ++ * Hardware writes, software reads. ++ * ++ * Flow: enqueue writes descriptor PA to input ring, wmb(), notifies CAAM. ++ * CAAM completes job, writes result to output ring, fires IRQ. ++ * ISR masks IRQ, schedules taskqueue. Taskqueue drains output ring ++ * and calls per-job callbacks. ++ * ++ * Matches: "fsl,sec-v4.0-job-ring" ++ * ++ * This is a clean-room implementation based on the NXP SEC reference manual. ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include "caam.h" ++#include "caam_regs.h" ++#include "caam_desc.h" ++#include "caam_jr.h" ++#include "caam_crypto.h" ++#include "caam_rng.h" ++ ++#include "cryptodev_if.h" ++ ++static MALLOC_DEFINE(M_CAAM, "caam", "CAAM Job Ring"); ++ ++static struct ofw_compat_data caam_jr_compat[] = { ++ { "fsl,sec-v4.0-job-ring", 1 }, ++ { NULL, 0 } ++}; ++ ++/* Forward declarations */ ++static void caam_jr_intr(void *arg); ++static void caam_jr_task(void *arg, int pending); ++static int caam_jr_reset(struct caam_jr_softc *sc); ++static int caam_jr_init_rings(struct caam_jr_softc *sc); ++static void caam_jr_free_rings(struct caam_jr_softc *sc); ++static int caam_jr_detach(device_t dev); ++ ++/* ++ * DMA memory allocation helpers ++ */ ++static void ++caam_dma_load_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error) ++{ ++ ++ if (error != 0) ++ return; ++ KASSERT(nseg == 1, ("%s: nsegs is %d", __func__, nseg)); ++ *(bus_addr_t *)arg = segs->ds_addr; ++} ++ ++int ++caam_dma_alloc(device_t dev, struct caam_dma_mem *mem, bus_size_t size) ++{ ++ int error; ++ ++ error = bus_dma_tag_create(bus_get_dma_tag(dev), /* parent */ ++ PAGE_SIZE, 0, /* alignment, boundary */ ++ BUS_SPACE_MAXADDR, /* lowaddr (64-bit CAAM DMA) */ ++ BUS_SPACE_MAXADDR, /* highaddr */ ++ NULL, NULL, /* filter, filterarg */ ++ size, 1, size, /* maxsize, nsegments, maxsegsz */ ++ BUS_DMA_COHERENT, /* flags */ ++ NULL, NULL, /* lockfunc, lockarg */ ++ &mem->tag); ++ if (error != 0) { ++ device_printf(dev, "bus_dma_tag_create failed: %d\n", error); ++ return (error); ++ } ++ ++ error = bus_dmamem_alloc(mem->tag, &mem->vaddr, ++ BUS_DMA_WAITOK | BUS_DMA_ZERO | BUS_DMA_COHERENT, &mem->map); ++ if (error != 0) { ++ device_printf(dev, "bus_dmamem_alloc failed: %d\n", error); ++ bus_dma_tag_destroy(mem->tag); ++ mem->tag = NULL; ++ return (error); ++ } ++ ++ error = bus_dmamap_load(mem->tag, mem->map, mem->vaddr, size, ++ caam_dma_load_cb, &mem->paddr, BUS_DMA_NOWAIT); ++ if (error != 0) { ++ device_printf(dev, "bus_dmamap_load failed: %d\n", error); ++ bus_dmamem_free(mem->tag, mem->vaddr, mem->map); ++ bus_dma_tag_destroy(mem->tag); ++ mem->tag = NULL; ++ mem->vaddr = NULL; ++ return (error); ++ } ++ ++ return (0); ++} ++ ++void ++caam_dma_free(struct caam_dma_mem *mem) ++{ ++ ++ if (mem->tag == NULL) ++ return; ++ 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; ++} ++ ++/* ++ * Reset the Job Ring hardware. ++ * Must be called before configuring ring bases/sizes. ++ */ ++static int ++caam_jr_reset(struct caam_jr_softc *sc) ++{ ++ uint32_t status; ++ int timeout; ++ ++ /* Mask interrupts during reset */ ++ JR_WRITE(sc, JR_JRCFGR_LS, ++ JR_READ(sc, JR_JRCFGR_LS) | JRCFG_IMSK); ++ ++ /* Check if halt is already in progress */ ++ status = JR_READ(sc, JR_JRINTR); ++ if ((status & JRINT_ERR_HALT_MASK) != JRINT_ERR_HALT_INPROGRESS) { ++ /* Clear halt status */ ++ JR_WRITE(sc, JR_JRINTR, ++ status & ~JRINT_ERR_HALT_MASK); ++ /* Initiate flush (required before reset) */ ++ JR_WRITE(sc, JR_JRCR, JRCR_RESET); ++ } ++ ++ /* Wait for flush/halt to complete */ ++ for (timeout = 100000; timeout > 0; timeout--) { ++ status = JR_READ(sc, JR_JRINTR); ++ if ((status & JRINT_ERR_HALT_MASK) == JRINT_ERR_HALT_COMPLETE) ++ break; ++ DELAY(1); ++ } ++ if (timeout == 0) { ++ device_printf(sc->sc_dev, "flush timeout (jrintr=0x%08x)\n", ++ status); ++ return (EIO); ++ } ++ ++ /* Issue reset */ ++ JR_WRITE(sc, JR_JRCR, JRCR_RESET); ++ ++ /* Wait for reset to complete (JRCR bit clears) */ ++ for (timeout = 100000; timeout > 0; timeout--) { ++ if ((JR_READ(sc, JR_JRCR) & JRCR_RESET) == 0) ++ break; ++ DELAY(1); ++ } ++ if (timeout == 0) { ++ device_printf(sc->sc_dev, "reset timeout\n"); ++ return (EIO); ++ } ++ ++ /* Unmask interrupts */ ++ JR_WRITE(sc, JR_JRCFGR_LS, ++ JR_READ(sc, JR_JRCFGR_LS) & ~JRCFG_IMSK); ++ ++ return (0); ++} ++ ++/* ++ * Allocate and initialize input/output rings and entry tracking. ++ */ ++static int ++caam_jr_init_rings(struct caam_jr_softc *sc) ++{ ++ int error, i; ++ ++ /* Allocate input ring */ ++ error = caam_dma_alloc(sc->sc_dev, &sc->sc_inpring, ++ CAAM_JR_INPENTRY_SZ * CAAM_JR_DEPTH); ++ if (error != 0) ++ return (error); ++ ++ /* Allocate output ring */ ++ error = caam_dma_alloc(sc->sc_dev, &sc->sc_outring, ++ CAAM_JR_OUTENTRY_SZ * CAAM_JR_DEPTH); ++ if (error != 0) { ++ caam_dma_free(&sc->sc_inpring); ++ return (error); ++ } ++ ++ /* Allocate per-slot entry tracking */ ++ sc->sc_entinfo = malloc(sizeof(struct caam_jr_entry) * CAAM_JR_DEPTH, ++ M_CAAM, M_WAITOK | M_ZERO); ++ ++ /* Mark all entries as unused */ ++ for (i = 0; i < CAAM_JR_DEPTH; i++) ++ sc->sc_entinfo[i].desc_pa = 0; ++ ++ /* Initialize ring indices */ ++ sc->sc_head = 0; ++ sc->sc_tail = 0; ++ sc->sc_out_ridx = 0; ++ sc->sc_inpring_avail = CAAM_JR_DEPTH; ++ ++ /* ++ * Program the JR hardware with ring base addresses and sizes. ++ * 64-bit registers use CAAM byte order and word order. ++ */ ++ caam_write_8(sc->sc_rres, JR_IRBA, sc->sc_inpring.paddr); ++ caam_write_8(sc->sc_rres, JR_ORBA, sc->sc_outring.paddr); ++ ++ JR_WRITE(sc, JR_IRSR, CAAM_JR_DEPTH); ++ JR_WRITE(sc, JR_ORSR, CAAM_JR_DEPTH); ++ ++ return (0); ++} ++ ++static void ++caam_jr_free_rings(struct caam_jr_softc *sc) ++{ ++ ++ if (sc->sc_entinfo != NULL) { ++ free(sc->sc_entinfo, M_CAAM); ++ sc->sc_entinfo = NULL; ++ } ++ caam_dma_free(&sc->sc_outring); ++ caam_dma_free(&sc->sc_inpring); ++} ++ ++/* ++ * Interrupt handler — top half. ++ * Mask further interrupts, ACK, and schedule taskqueue for dequeue. ++ */ ++static void ++caam_jr_intr(void *arg) ++{ ++ struct caam_jr_softc *sc = arg; ++ uint32_t irqstate; ++ ++ irqstate = JR_READ(sc, JR_JRINTR); ++ if ((irqstate & JRINT_JR_INT) == 0) ++ return; ++ ++ if (irqstate & JRINT_JR_ERROR) ++ device_printf(sc->sc_dev, ++ "job ring error: irqstate=0x%08x\n", irqstate); ++ ++ /* Mask interrupts */ ++ JR_WRITE(sc, JR_JRCFGR_LS, ++ JR_READ(sc, JR_JRCFGR_LS) | JRCFG_IMSK); ++ ++ /* ACK the interrupt */ ++ JR_WRITE(sc, JR_JRINTR, irqstate); ++ ++ /* Schedule deferred processing */ ++ taskqueue_enqueue(sc->sc_taskq, &sc->sc_task); ++} ++ ++/* ++ * Taskqueue handler — drain completed jobs from the output ring. ++ */ ++static void ++caam_jr_task(void *arg, int pending) ++{ ++ struct caam_jr_softc *sc = arg; ++ struct caam_jr_outentry *outring; ++ struct caam_jr_entry *ent; ++ uint32_t outused, jrstatus; ++ uint64_t desc_pa; ++ int hw_idx, sw_idx, head, tail, i; ++ void (*callback)(uint32_t status, void *arg); ++ void *cb_arg; ++ ++ outring = sc->sc_outring.vaddr; ++ ++ while ((outused = JR_READ(sc, JR_ORSFR)) != 0) { ++ head = sc->sc_head; ++ tail = sc->sc_tail; ++ hw_idx = sc->sc_out_ridx; ++ ++ /* Read completed descriptor address and status (CAAM byte order) */ ++ desc_pa = caam_to_cpu64(outring[hw_idx].desc_addr); ++ jrstatus = caam_to_cpu32(outring[hw_idx].jrstatus); ++ ++ /* ++ * Find matching entry in the software ring. ++ * Jobs can complete out of order, so scan from tail. ++ */ ++ sw_idx = -1; ++ for (i = 0; i < CAAM_JR_DEPTH; i++) { ++ int idx = (tail + i) & CAAM_JR_DEPTH_MASK; ++ if (idx == head) ++ break; /* Reached head, no more in-flight */ ++ if (sc->sc_entinfo[idx].desc_pa == desc_pa) { ++ sw_idx = idx; ++ break; ++ } ++ } ++ ++ if (sw_idx < 0) { ++ device_printf(sc->sc_dev, ++ "completed desc PA 0x%jx not found in ring!\n", ++ (uintmax_t)desc_pa); ++ goto ack; ++ } ++ ++ ent = &sc->sc_entinfo[sw_idx]; ++ ++ /* Stash callback info */ ++ callback = ent->callback; ++ cb_arg = ent->cb_arg; ++ ++ /* Clear entry so it won't match on reuse */ ++ ent->desc_pa = 0; ++ ent->callback = NULL; ++ ent->cb_arg = NULL; ++ ++ /* ++ * Ensure all data from the completed job is read before ++ * telling CAAM we've consumed the output ring entry. ++ */ ++ mb(); ++ ++ack: ++ /* Acknowledge one consumed output entry */ ++ JR_WRITE(sc, JR_ORJRR, 1); ++ ++ /* Advance output ring read index */ ++ sc->sc_out_ridx = (sc->sc_out_ridx + 1) & CAAM_JR_DEPTH_MASK; ++ ++ /* ++ * Advance tail past completed entries. ++ * If this job was at the tail, advance past any ++ * subsequent already-completed entries. ++ */ ++ if (sw_idx >= 0 && sw_idx == tail) { ++ do { ++ tail = (tail + 1) & CAAM_JR_DEPTH_MASK; ++ } while (tail != head && ++ sc->sc_entinfo[tail].desc_pa == 0); ++ sc->sc_tail = tail; ++ } ++ ++ if (sw_idx >= 0) { ++ /* Update available count */ ++ mtx_lock(&sc->sc_inplock); ++ sc->sc_inpring_avail++; ++ mtx_unlock(&sc->sc_inplock); ++ ++ /* Invoke callback */ ++ if (callback != NULL) ++ callback(jrstatus, cb_arg); ++ } ++ } ++ ++ /* Unmask interrupts (skip for polling-mode JR) */ ++ if (!sc->sc_polling) ++ JR_WRITE(sc, JR_JRCFGR_LS, ++ JR_READ(sc, JR_JRCFGR_LS) & ~JRCFG_IMSK); ++} ++ ++/* ++ * Poll the output ring inline — used by the dedicated RNG JR. ++ * ++ * Safe ONLY when the JR is in polling mode (sc_polling=true), ++ * meaning no concurrent taskqueue processing can occur (IRQs masked, ++ * taskqueue idle). ++ */ ++void ++caam_jr_poll(struct caam_jr_softc *sc) ++{ ++ ++ if (JR_READ(sc, JR_ORSFR) != 0) ++ caam_jr_task(sc, 0); ++} ++ ++/* ++ * Enqueue a job descriptor onto the input ring. ++ * ++ * The descriptor must already be DMA-mapped. desc_pa is the physical ++ * address CAAM will use to fetch the descriptor. ++ * ++ * Returns 0 on success, ENOSPC if the ring is full. ++ */ ++int ++caam_jr_enqueue(struct caam_jr_softc *sc, uint32_t *desc, ++ bus_addr_t desc_pa, int desc_size, ++ void (*callback)(uint32_t status, void *arg), void *cb_arg) ++{ ++ struct caam_jr_entry *ent; ++ volatile uint64_t *inpring; ++ int head; ++ ++ mtx_lock(&sc->sc_inplock); ++ ++ if (sc->sc_inpring_avail == 0) { ++ mtx_unlock(&sc->sc_inplock); ++ return (ENOSPC); ++ } ++ ++ head = sc->sc_head; ++ inpring = sc->sc_inpring.vaddr; ++ ++ /* Fill the entry info */ ++ ent = &sc->sc_entinfo[head]; ++ ent->desc_va = desc; ++ ent->desc_pa = desc_pa; ++ ent->desc_size = desc_size; ++ ent->callback = callback; ++ ent->cb_arg = cb_arg; ++ ent->crp = NULL; ++ ++ /* Write descriptor PA to the input ring (CAAM byte order) */ ++ inpring[head] = cpu_to_caam64(desc_pa); ++ ++ /* ++ * Full system memory barrier — ensures the input ring entry ++ * is visible to CAAM before we notify it. Under heavy DDR load, ++ * weaker barriers (wmb/dma_wmb) can be insufficient. ++ */ ++ wmb(); ++ ++ /* Advance head */ ++ sc->sc_head = (head + 1) & CAAM_JR_DEPTH_MASK; ++ sc->sc_inpring_avail--; ++ ++ /* Notify CAAM: one new job added to the input ring */ ++ JR_WRITE(sc, JR_IRJAR, 1); ++ ++ mtx_unlock(&sc->sc_inplock); ++ ++ return (0); ++} ++ ++/* ++ * NOP test callback — used during attach to verify ring operation. ++ */ ++struct caam_jr_nop_ctx { ++ volatile int done; ++ volatile uint32_t status; ++}; ++ ++static void ++caam_jr_nop_callback(uint32_t status, void *arg) ++{ ++ struct caam_jr_nop_ctx *ctx = arg; ++ ++ ctx->status = status; ++ ctx->done = 1; ++} ++ ++/* ++ * Submit a NOP descriptor to test ring operation. ++ */ ++static int ++caam_jr_test_nop(struct caam_jr_softc *sc) ++{ ++ struct caam_dma_mem desc_mem; ++ struct caam_jr_nop_ctx nop_ctx; ++ uint32_t *desc; ++ int error, timeout; ++ ++ /* Allocate DMA memory for a minimal descriptor (1 word) */ ++ error = caam_dma_alloc(sc->sc_dev, &desc_mem, CAAM_DESC_MAX_BYTES); ++ if (error != 0) { ++ device_printf(sc->sc_dev, "NOP test: DMA alloc failed\n"); ++ return (error); ++ } ++ ++ desc = desc_mem.vaddr; ++ caam_desc_build_nop(desc); ++ ++ nop_ctx.done = 0; ++ nop_ctx.status = 0xdeadbeef; ++ ++ error = caam_jr_enqueue(sc, desc, desc_mem.paddr, ++ caam_desc_len(desc) * sizeof(uint32_t), ++ caam_jr_nop_callback, &nop_ctx); ++ if (error != 0) { ++ device_printf(sc->sc_dev, "NOP test: enqueue failed: %d\n", ++ error); ++ caam_dma_free(&desc_mem); ++ return (error); ++ } ++ ++ /* ++ * Poll for completion by draining the output ring directly. ++ * ++ * During device attach, taskqueue threads may not be running yet ++ * (CPU 0 is busy with attach, single-threaded early boot). ++ * Call the task handler inline to process completions. ++ */ ++ for (timeout = 1000; timeout > 0 && !nop_ctx.done; timeout--) { ++ if (JR_READ(sc, JR_ORSFR) != 0) ++ caam_jr_task(sc, 0); ++ DELAY(1000); /* 1ms per iteration, 1s total */ ++ } ++ ++ caam_dma_free(&desc_mem); ++ ++ if (!nop_ctx.done) { ++ device_printf(sc->sc_dev, "NOP test: timeout\n"); ++ return (ETIMEDOUT); ++ } ++ ++ /* ++ * Check for error status. JUMP HALT produces a Condition Code ++ * status (SSRC=7) on SEC v5.4 — this is informational, not an ++ * error. Only CCB (2), DECO (4), and JR (6) SSRCs are errors. ++ */ ++ if (nop_ctx.status != 0) { ++ uint32_t ssrc; ++ ++ ssrc = nop_ctx.status & JRSTA_SSRC_MASK; ++ if (ssrc == JRSTA_SSRC_CCB_ERROR || ++ ssrc == JRSTA_SSRC_DECO || ++ ssrc == JRSTA_SSRC_JR) { ++ device_printf(sc->sc_dev, ++ "NOP test: error status 0x%08x\n", ++ nop_ctx.status); ++ return (EIO); ++ } ++ } ++ ++ device_printf(sc->sc_dev, "NOP test: passed\n"); ++ return (0); ++} ++ ++/* ++ * Probe / Attach / Detach ++ */ ++static int ++caam_jr_probe(device_t dev) ++{ ++ ++ if (!ofw_bus_status_okay(dev)) ++ return (ENXIO); ++ ++ if (ofw_bus_search_compatible(dev, caam_jr_compat)->ocd_data == 0) ++ return (ENXIO); ++ ++ device_set_desc(dev, "NXP CAAM Job Ring"); ++ return (BUS_PROBE_DEFAULT); ++} ++ ++static int ++caam_jr_attach(device_t dev) ++{ ++ struct caam_jr_softc *sc; ++ int error; ++ ++ sc = device_get_softc(dev); ++ sc->sc_dev = dev; ++ sc->sc_cid = -1; ++ ++ mtx_init(&sc->sc_inplock, "caam_jr", NULL, MTX_DEF); ++ ++ /* Map JR register space */ ++ sc->sc_rrid = 0; ++ sc->sc_rres = bus_alloc_resource_any(dev, SYS_RES_MEMORY, ++ &sc->sc_rrid, RF_ACTIVE); ++ if (sc->sc_rres == NULL) { ++ device_printf(dev, "cannot map registers\n"); ++ error = ENXIO; ++ goto fail; ++ } ++ ++ /* Allocate interrupt */ ++ sc->sc_irid = 0; ++ sc->sc_ires = bus_alloc_resource_any(dev, SYS_RES_IRQ, ++ &sc->sc_irid, RF_ACTIVE | RF_SHAREABLE); ++ if (sc->sc_ires == NULL) { ++ device_printf(dev, "cannot allocate interrupt\n"); ++ error = ENXIO; ++ goto fail; ++ } ++ ++ /* Reset the JR hardware */ ++ error = caam_jr_reset(sc); ++ if (error != 0) ++ goto fail; ++ ++ /* Initialize DMA rings */ ++ error = caam_jr_init_rings(sc); ++ if (error != 0) ++ goto fail; ++ ++ /* Create taskqueue for deferred completion processing */ ++ sc->sc_taskq = taskqueue_create("caam_jr", M_WAITOK, ++ taskqueue_thread_enqueue, &sc->sc_taskq); ++ if (sc->sc_taskq == NULL) { ++ device_printf(dev, "cannot create taskqueue\n"); ++ error = ENOMEM; ++ goto fail; ++ } ++ TASK_INIT(&sc->sc_task, 0, caam_jr_task, sc); ++ taskqueue_start_threads(&sc->sc_taskq, 1, PI_NET, "%s", ++ device_get_nameunit(dev)); ++ ++ /* Setup interrupt handler */ ++ error = bus_setup_intr(dev, sc->sc_ires, ++ INTR_TYPE_NET | INTR_MPSAFE, NULL, caam_jr_intr, sc, ++ &sc->sc_ihand); ++ if (error != 0) { ++ device_printf(dev, "cannot setup interrupt: %d\n", error); ++ goto fail; ++ } ++ ++ device_printf(dev, "ring depth %d, input PA 0x%jx, output PA 0x%jx\n", ++ CAAM_JR_DEPTH, ++ (uintmax_t)sc->sc_inpring.paddr, ++ (uintmax_t)sc->sc_outring.paddr); ++ ++ /* Run NOP test to verify ring operation */ ++ caam_jr_test_nop(sc); ++ ++ /* ++ * Register hardware entropy source (first JR only). ++ * Must happen before crypto init: if this JR is claimed for RNG, ++ * it enters polling mode and skips opencrypto registration. ++ */ ++ error = caam_rng_init(sc); ++ if (error != 0 && error != ENXIO) ++ device_printf(dev, "RNG entropy source init failed: %d\n", ++ error); ++ ++ /* Initialize opencrypto integration (skip if dedicated to RNG) */ ++ if (!sc->sc_polling) { ++ error = caam_crypto_init(sc); ++ if (error != 0) ++ device_printf(dev, ++ "opencrypto init failed: %d\n", error); ++ } ++ ++ return (0); ++ ++fail: ++ caam_jr_detach(dev); ++ return (error); ++} ++ ++static int ++caam_jr_detach(device_t dev) ++{ ++ struct caam_jr_softc *sc; ++ ++ sc = device_get_softc(dev); ++ ++ /* Deregister RNG entropy source if owned by this JR */ ++ caam_rng_detach(sc); ++ ++ /* Unregister from opencrypto and free request pool */ ++ caam_crypto_detach(sc); ++ ++ if (sc->sc_ihand != NULL) ++ bus_teardown_intr(dev, sc->sc_ires, sc->sc_ihand); ++ ++ if (sc->sc_taskq != NULL) { ++ taskqueue_drain(sc->sc_taskq, &sc->sc_task); ++ taskqueue_free(sc->sc_taskq); ++ sc->sc_taskq = NULL; ++ } ++ ++ caam_jr_free_rings(sc); ++ ++ if (sc->sc_ires != NULL) ++ bus_release_resource(dev, SYS_RES_IRQ, ++ sc->sc_irid, sc->sc_ires); ++ ++ if (sc->sc_rres != NULL) ++ bus_release_resource(dev, SYS_RES_MEMORY, ++ sc->sc_rrid, sc->sc_rres); ++ ++ mtx_destroy(&sc->sc_inplock); ++ ++ return (0); ++} ++ ++static device_method_t caam_jr_methods[] = { ++ /* Device interface */ ++ DEVMETHOD(device_probe, caam_jr_probe), ++ DEVMETHOD(device_attach, caam_jr_attach), ++ DEVMETHOD(device_detach, caam_jr_detach), ++ ++ /* Cryptodev interface */ ++ DEVMETHOD(cryptodev_probesession, caam_probesession), ++ DEVMETHOD(cryptodev_newsession, caam_newsession), ++ DEVMETHOD(cryptodev_freesession, caam_freesession), ++ DEVMETHOD(cryptodev_process, caam_process), ++ ++ DEVMETHOD_END ++}; ++ ++static driver_t caam_jr_driver = { ++ "caam_jr", ++ caam_jr_methods, ++ sizeof(struct caam_jr_softc), ++}; ++ ++DRIVER_MODULE(caam_jr, caam, caam_jr_driver, 0, 0); ++MODULE_VERSION(caam_jr, 1); ++MODULE_DEPEND(caam_jr, caam, 1, 1, 1); ++MODULE_DEPEND(caam_jr, crypto, 1, 1, 1); +diff --git a/sys/dev/caam/caam_jr.h b/sys/dev/caam/caam_jr.h +new file mode 100644 +index 00000000000..df208a67dfb +--- /dev/null ++++ b/sys/dev/caam/caam_jr.h +@@ -0,0 +1,131 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * NXP CAAM Job Ring driver — softc and ring structures. ++ */ ++ ++#ifndef _CAAM_JR_H ++#define _CAAM_JR_H ++ ++#include ++#include ++#include ++#include ++ ++#include "caam.h" ++ ++/* Forward declaration — full definition in caam_crypto.h */ ++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). ++ */ ++#define CAAM_JR_DEPTH 512 ++#define CAAM_JR_DEPTH_MASK (CAAM_JR_DEPTH - 1) ++ ++/* ++ * Input ring entry: just a 64-bit DMA pointer to a job descriptor. ++ * Size per entry: 8 bytes (64-bit pointer mode). ++ */ ++#define CAAM_JR_INPENTRY_SZ sizeof(uint64_t) ++ ++/* ++ * Output ring entry: 64-bit DMA pointer + 32-bit status, packed. ++ * Size per entry: 12 bytes (64-bit pointer mode). ++ * ++ * Fields are stored in CAAM byte order (BE on LS1046A). ++ */ ++struct caam_jr_outentry { ++ uint64_t desc_addr; /* DMA address of completed descriptor */ ++ uint32_t jrstatus; /* CAAM job status */ ++} __packed; ++ ++#define CAAM_JR_OUTENTRY_SZ sizeof(struct caam_jr_outentry) ++ ++/* ++ * DMA memory descriptor — tracks tag, map, virtual addr, physical addr. ++ */ ++struct caam_dma_mem { ++ bus_dma_tag_t tag; ++ bus_dmamap_t map; ++ void *vaddr; ++ bus_addr_t paddr; ++}; ++ ++/* ++ * Per-slot tracking for in-flight jobs. ++ * Shadows each input ring entry with SW metadata. ++ */ ++struct caam_jr_entry { ++ bus_addr_t desc_pa; /* DMA address (for matching output) */ ++ uint32_t *desc_va; /* Virtual address of descriptor */ ++ bus_dmamap_t desc_map; /* DMA map for this descriptor */ ++ int desc_size; /* Descriptor size in bytes */ ++ struct cryptop *crp; /* Pending crypto request (NULL if none) */ ++ void (*callback)(uint32_t status, void *arg); ++ void *cb_arg; ++}; ++ ++/* ++ * Job Ring softc — one per JR device (4 on LS1046A). ++ */ ++struct caam_jr_softc { ++ device_t sc_dev; ++ int32_t sc_cid; /* Opencrypto driver ID (-1 if none) */ ++ ++ /* JR register resource */ ++ struct resource *sc_rres; ++ int sc_rrid; ++ ++ /* JR interrupt */ ++ struct resource *sc_ires; ++ void *sc_ihand; /* Interrupt handler cookie */ ++ int sc_irid; ++ ++ /* Deferred completion taskqueue */ ++ struct task sc_task; ++ struct taskqueue *sc_taskq; ++ ++ /* Input ring (DMA-mapped array of uint64_t) */ ++ struct caam_dma_mem sc_inpring; ++ ++ /* Output ring (DMA-mapped array of caam_jr_outentry) */ ++ struct caam_dma_mem sc_outring; ++ ++ /* Per-slot entry tracking (kernel-allocated, not DMA) */ ++ struct caam_jr_entry *sc_entinfo; ++ ++ /* Ring indices and lock */ ++ struct mtx sc_inplock; ++ int sc_head; /* Next input slot to fill */ ++ int sc_tail; /* Next output slot to consume */ ++ int sc_inpring_avail; /* Free input slots */ ++ int sc_out_ridx; /* Output ring read index */ ++ ++ /* Crypto request pool (pre-allocated for opencrypto) */ ++ struct caam_request *sc_requests; /* [CAAM_JR_DEPTH] */ ++ struct caam_dma_mem sc_desc_bulk; /* Bulk descriptor DMA */ ++ struct caam_dma_mem sc_bounce_bulk; /* Bulk bounce buffer DMA */ ++ struct mtx sc_pool_lock; ++ int sc_pool_head; /* Free list head (-1 = empty) */ ++ bool sc_blocked; /* ERESTART returned, need unblock */ ++ bool sc_polling; /* Polling mode (RNG dedicated JR) */ ++}; ++ ++/* ++ * Register access macros for JR (relative to JR register resource). ++ * Same CAAM byte-swap as controller registers. ++ */ ++#define JR_READ(sc, off) caam_to_cpu32(bus_read_4((sc)->sc_rres, (off))) ++#define JR_WRITE(sc, off, v) \ ++ bus_write_4((sc)->sc_rres, (off), cpu_to_caam32(v)) ++ ++int caam_jr_enqueue(struct caam_jr_softc *sc, uint32_t *desc, ++ bus_addr_t desc_pa, int desc_size, ++ void (*callback)(uint32_t status, void *arg), void *cb_arg); ++void caam_jr_poll(struct caam_jr_softc *sc); ++ ++#endif /* _CAAM_JR_H */ +diff --git a/sys/dev/caam/caam_qi.c b/sys/dev/caam/caam_qi.c +new file mode 100644 +index 00000000000..6fc24adedd1 +--- /dev/null ++++ b/sys/dev/caam/caam_qi.c +@@ -0,0 +1,1042 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * CAAM QI (Queue Interface) crypto backend. ++ * ++ * Submits crypto operations through QMan frame queues instead of Job Rings. ++ * Each session creates a request FQ targeting CAAM's DCP (channel 0x840) ++ * with Context-A pointing to the preheader + shared descriptor. Per-CPU ++ * response FQs deliver completions to the originating CPU's portal. ++ * ++ * Compound frame descriptor format: ++ * fd.addr → fd_sgt[2] (DMA memory) ++ * fd_sgt[0] = OUTPUT buffer (CAAM writes result here) ++ * fd_sgt[1] = INPUT buffer (CAAM reads from here), F=1 (Final) ++ * ++ * QI shared descriptors differ from JR shared descriptors: ++ * - assoclen via SEQ LOAD (first 4 bytes of input stream) ++ * - IV via SEQ FIFO LOAD (from input stream) ++ * - KEY + OPERATION must precede SEQ FIFO LOAD with FLUSH1 ++ * ++ * QI bounce buffer layout: ++ * [assoclen (4B, BE)] [IV (ivlen)] [AAD] [payload] [ICV for decrypt] ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++ ++#include ++ ++#include ++#include ++ ++#include ++ ++#include ++ ++#include "caam.h" ++#include "caam_regs.h" ++#include "caam_desc.h" ++#include "caam_jr.h" ++#include "caam_crypto.h" ++#include "caam_qi.h" ++ ++#include "cryptodev_if.h" ++ ++static MALLOC_DEFINE(M_CAAM_QI, "caam_qi", "CAAM QI crypto requests"); ++ ++/* Singleton QI softc */ ++struct caam_qi_softc *caam_qi_sc; ++ ++/* ================================================================ ++ * QI Request Pool Management ++ * ++ * Same bulk-DMA pattern as the JR pool (caam_crypto.c). ++ * S/G tables and bounce buffers are pre-allocated in bulk regions ++ * and sliced into per-request chunks. ++ * ================================================================ */ ++ ++static int ++caam_qi_pool_init(struct caam_qi_softc *qi) ++{ ++ struct caam_qi_request *req; ++ int error, i; ++ ++ qi->requests = malloc(sizeof(struct caam_qi_request) * CAAM_QI_DEPTH, ++ M_CAAM_QI, M_WAITOK | M_ZERO); ++ ++ /* Bulk DMA: S/G tables (512 * 32 = 16KB) */ ++ error = caam_dma_alloc(qi->dev, &qi->sgt_bulk, ++ (bus_size_t)CAAM_QI_DEPTH * CAAM_QI_SGT_SZ); ++ if (error != 0) ++ goto fail_requests; ++ ++ /* Bulk DMA: bounce buffers (512 * 2048 = 1MB) */ ++ error = caam_dma_alloc(qi->dev, &qi->bounce_bulk, ++ (bus_size_t)CAAM_QI_DEPTH * CAAM_BOUNCE_SZ); ++ if (error != 0) ++ goto fail_sgt; ++ ++ mtx_init(&qi->pool_lock, "caam_qi_pool", NULL, MTX_DEF); ++ qi->pool_head = 0; ++ qi->blocked = false; ++ ++ for (i = 0; i < CAAM_QI_DEPTH; i++) { ++ req = &qi->requests[i]; ++ req->next_free = i + 1; ++ ++ /* S/G table slice */ ++ req->sgt.tag = NULL; ++ req->sgt.map = NULL; ++ req->sgt.vaddr = (uint8_t *)qi->sgt_bulk.vaddr + ++ i * CAAM_QI_SGT_SZ; ++ req->sgt.paddr = qi->sgt_bulk.paddr + ++ i * CAAM_QI_SGT_SZ; ++ ++ /* Bounce buffer slice */ ++ req->bounce.tag = NULL; ++ req->bounce.map = NULL; ++ req->bounce.vaddr = (uint8_t *)qi->bounce_bulk.vaddr + ++ i * CAAM_BOUNCE_SZ; ++ req->bounce.paddr = qi->bounce_bulk.paddr + ++ i * CAAM_BOUNCE_SZ; ++ ++ req->dyn_bounce.tag = NULL; ++ req->using_dyn = false; ++ } ++ ++ /* Terminate free list */ ++ qi->requests[CAAM_QI_DEPTH - 1].next_free = -1; ++ ++ return (0); ++ ++fail_sgt: ++ caam_dma_free(&qi->sgt_bulk); ++fail_requests: ++ free(qi->requests, M_CAAM_QI); ++ qi->requests = NULL; ++ return (error); ++} ++ ++static void ++caam_qi_pool_fini(struct caam_qi_softc *qi) ++{ ++ struct caam_qi_request *req; ++ int i; ++ ++ if (qi->requests == NULL) ++ return; ++ ++ for (i = 0; i < CAAM_QI_DEPTH; i++) { ++ req = &qi->requests[i]; ++ if (req->using_dyn) ++ caam_dma_free(&req->dyn_bounce); ++ } ++ ++ caam_dma_free(&qi->bounce_bulk); ++ caam_dma_free(&qi->sgt_bulk); ++ ++ mtx_destroy(&qi->pool_lock); ++ free(qi->requests, M_CAAM_QI); ++ qi->requests = NULL; ++} ++ ++static struct caam_qi_request * ++caam_qi_pool_alloc(struct caam_qi_softc *qi) ++{ ++ struct caam_qi_request *req; ++ int idx; ++ ++ mtx_lock(&qi->pool_lock); ++ idx = qi->pool_head; ++ if (idx < 0) { ++ mtx_unlock(&qi->pool_lock); ++ return (NULL); ++ } ++ req = &qi->requests[idx]; ++ qi->pool_head = req->next_free; ++ req->next_free = -1; ++ mtx_unlock(&qi->pool_lock); ++ ++ return (req); ++} ++ ++static void ++caam_qi_pool_free(struct caam_qi_softc *qi, struct caam_qi_request *req) ++{ ++ int idx; ++ ++ if (req->using_dyn) { ++ caam_dma_free(&req->dyn_bounce); ++ req->using_dyn = false; ++ } ++ ++ req->crp = NULL; ++ req->sess = NULL; ++ req->drv_ctx = NULL; ++ ++ idx = req - qi->requests; ++ ++ mtx_lock(&qi->pool_lock); ++ req->next_free = qi->pool_head; ++ qi->pool_head = idx; ++ mtx_unlock(&qi->pool_lock); ++} ++ ++/* ================================================================ ++ * Response FQ Callback ++ * ++ * Called by QMan portal polling when CAAM delivers a completed ++ * frame to a per-CPU response FQ. The response FD's addr field ++ * points to the S/G table, which we map back to the request index ++ * via the sgt_bulk base address. ++ * ================================================================ */ ++ ++static e_RxStoreResponse ++caam_qi_rsp_cb(t_Handle app, t_Handle qm_fqr, t_Handle qm_portal, ++ uint32_t fqid_offset, t_DpaaFD *frame) ++{ ++ struct caam_qi_softc *qi = (struct caam_qi_softc *)app; ++ struct caam_qi_request *req; ++ struct cryptop *crp; ++ struct caam_session *sess; ++ bus_addr_t sgt_pa; ++ uint32_t status, ssrc; ++ uint8_t *buf; ++ bool encrypt, blocked; ++ int idx; ++ ++ /* Recover request from S/G table DMA address */ ++ sgt_pa = DPAA_FD_GET_PHYS_ADDR(frame); ++ idx = (sgt_pa - qi->sgt_bulk.paddr) / CAAM_QI_SGT_SZ; ++ ++ if (__predict_false(idx < 0 || idx >= CAAM_QI_DEPTH)) { ++ device_printf(qi->dev, ++ "QI: bad response sgt_pa 0x%lx (idx %d)\n", ++ (unsigned long)sgt_pa, idx); ++ return (e_RX_STORE_RESPONSE_CONTINUE); ++ } ++ ++ req = &qi->requests[idx]; ++ crp = req->crp; ++ sess = req->sess; ++ encrypt = CRYPTO_OP_IS_ENCRYPT(crp->crp_op); ++ status = DPAA_FD_GET_STATUS(frame); ++ ++ /* ++ * QI bounce buffer layout differs from JR: QI prepends ++ * [assoclen(4)] [IV(ivlen)] before [AAD] [payload] [ICV]. ++ * The "data" portion starts after the QI prefix. ++ */ ++ buf = req->using_dyn ? req->dyn_bounce.vaddr : req->bounce.vaddr; ++ { ++ int qi_prefix = 4 + sess->ivlen; ++ if (sess->alg_type == CAAM_ALG_HASH || ++ sess->alg_type == CAAM_ALG_HMAC) ++ qi_prefix = 0; /* Hash has no assoclen or IV */ ++ else if (sess->alg_type == CAAM_ALG_CIPHER) ++ qi_prefix = sess->ivlen; /* Cipher: IV only, no assoclen */ ++ buf += qi_prefix; ++ } ++ ++ /* Map CAAM status to error code */ ++ if (status == 0) { ++ crp->crp_etype = 0; ++ } else { ++ ssrc = status & JRSTA_SSRC_MASK; ++ if (ssrc == JRSTA_SSRC_JUMP_HALT_USER) { ++ crp->crp_etype = 0; ++ } else if (ssrc == JRSTA_SSRC_CCB_ERROR && ++ (status & CCB_ERRID_MASK) == CCB_ERR_ICV_CHECK) { ++ crp->crp_etype = EBADMSG; ++ } else { ++ crp->crp_etype = EIO; ++ device_printf(qi->dev, ++ "QI crypto error: status 0x%08x\n", status); ++ } ++ } ++ ++ /* Copy results back on success */ ++ if (crp->crp_etype == 0) { ++ if (sess->alg_type == CAAM_ALG_HASH || ++ sess->alg_type == CAAM_ALG_HMAC) { ++ /* ++ * Hash output is just the digest at offset 0 ++ * (no payload in output — only SEQINLEN consumes it). ++ */ ++ if (crp->crp_op & CRYPTO_OP_VERIFY_DIGEST) { ++ uint8_t expected[64]; ++ ++ crypto_copydata(crp, crp->crp_digest_start, ++ sess->icvlen, expected); ++ if (timingsafe_bcmp(buf, expected, ++ sess->icvlen) != 0) ++ crp->crp_etype = EBADMSG; ++ } else { ++ crypto_copyback(crp, crp->crp_digest_start, ++ sess->icvlen, buf); ++ } ++ } else if (encrypt) { ++ crypto_copyback(crp, crp->crp_payload_start, ++ crp->crp_payload_length, ++ buf + crp->crp_aad_length); ++ crypto_copyback(crp, crp->crp_digest_start, ++ sess->icvlen, ++ buf + crp->crp_aad_length + ++ crp->crp_payload_length); ++ } else { ++ crypto_copyback(crp, crp->crp_payload_start, ++ crp->crp_payload_length, ++ buf + crp->crp_aad_length); ++ } ++ } ++ ++ caam_qi_pool_free(qi, req); ++ ++ mtx_lock(&qi->pool_lock); ++ blocked = qi->blocked; ++ if (blocked) ++ qi->blocked = false; ++ mtx_unlock(&qi->pool_lock); ++ ++ if (blocked) ++ crypto_unblock(qi->cid, CRYPTO_SYMQ); ++ ++ crypto_done(crp); ++ ++ return (e_RX_STORE_RESPONSE_CONTINUE); ++} ++ ++/* ================================================================ ++ * Response FQ Infrastructure ++ * ================================================================ */ ++ ++static int ++caam_qi_create_rsp_fqs(struct caam_qi_softc *qi) ++{ ++ int cpu, ncpus; ++ t_Error err; ++ ++ ncpus = mp_ncpus; ++ if (ncpus > MAXCPU) ++ ncpus = MAXCPU; ++ ++ for (cpu = 0; cpu < ncpus; cpu++) { ++ qi->rsp_fqr[cpu] = qman_fqr_create(1, ++ (e_QmFQChannel)(e_QM_FQ_CHANNEL_SWPORTAL0 + cpu), ++ 3, /* WQ 3 — same as dtsec TX confirm */ ++ FALSE, /* don't force FQID */ ++ 0, /* alignment */ ++ FALSE, /* not parked */ ++ FALSE, /* no hold_active */ ++ TRUE, /* prefer_in_cache */ ++ FALSE, /* no congestion avoidance */ ++ NULL, /* no congestion group */ ++ 0, /* no overhead accounting */ ++ 0); /* no tail drop */ ++ ++ if (qi->rsp_fqr[cpu] == NULL) { ++ device_printf(qi->dev, ++ "QI: failed to create response FQ for CPU %d\n", ++ cpu); ++ goto fail; ++ } ++ ++ err = qman_fqr_register_cb(qi->rsp_fqr[cpu], ++ caam_qi_rsp_cb, (t_Handle)qi); ++ if (err != E_OK) { ++ device_printf(qi->dev, ++ "QI: failed to register cb for CPU %d: %d\n", ++ cpu, err); ++ goto fail; ++ } ++ ++ qi->rsp_fqid[cpu] = qman_fqr_get_base_fqid( ++ qi->rsp_fqr[cpu]); ++ } ++ ++ device_printf(qi->dev, ++ "QI: %d response FQs created (FQID base %u)\n", ++ ncpus, qi->rsp_fqid[0]); ++ ++ return (0); ++ ++fail: ++ for (cpu = cpu - 1; cpu >= 0; cpu--) { ++ if (qi->rsp_fqr[cpu] != NULL) { ++ qman_fqr_free(qi->rsp_fqr[cpu]); ++ qi->rsp_fqr[cpu] = NULL; ++ } ++ } ++ return (ENXIO); ++} ++ ++static void ++caam_qi_destroy_rsp_fqs(struct caam_qi_softc *qi) ++{ ++ int cpu, ncpus; ++ ++ ncpus = mp_ncpus; ++ if (ncpus > MAXCPU) ++ ncpus = MAXCPU; ++ ++ for (cpu = 0; cpu < ncpus; cpu++) { ++ if (qi->rsp_fqr[cpu] != NULL) { ++ qman_fqr_free(qi->rsp_fqr[cpu]); ++ qi->rsp_fqr[cpu] = NULL; ++ } ++ } ++} ++ ++/* ================================================================ ++ * Session Lifecycle ++ * ================================================================ */ ++ ++/* ++ * Allocate and initialize a QI driver context (preheader + shared desc ++ * + request FQ). The shared descriptor is built by the caller-supplied ++ * builder function. ++ */ ++static int ++caam_qi_drv_ctx_create(struct caam_qi_softc *qi, struct caam_session *sess, ++ struct caam_qi_drv_ctx **ctxp, ++ int (*build_shdesc)(struct caam_session *, device_t, ++ struct caam_qi_drv_ctx *)) ++{ ++ struct caam_qi_drv_ctx *ctx; ++ uint32_t *prehdr; ++ t_QmContextA context_a; ++ t_QmContextB context_b; ++ uint64_t prehdr_pa; ++ int error; ++ ++ ctx = malloc(sizeof(*ctx), M_CAAM_QI, M_WAITOK | M_ZERO); ++ ++ /* Allocate DMA for preheader + shared descriptor */ ++ error = caam_dma_alloc(qi->dev, &ctx->prehdr_shdesc, ++ CAAM_QI_PREHDR_SZ); ++ if (error != 0) { ++ free(ctx, M_CAAM_QI); ++ return (error); ++ } ++ ++ /* Build the QI shared descriptor (populates prehdr[2..] and shdesc_len) */ ++ error = build_shdesc(sess, qi->dev, ctx); ++ if (error != 0) { ++ caam_dma_free(&ctx->prehdr_shdesc); ++ free(ctx, M_CAAM_QI); ++ return (error); ++ } ++ ++ /* ++ * Fill preheader (2 words before the shared descriptor). ++ * Word 0: RSLS | shdesc_len ++ * 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; ++ prehdr[0] = cpu_to_caam32(PREHDR_RSLS | ctx->shdesc_len); ++ prehdr[1] = cpu_to_caam32(PREHDR_ABS); ++ ++ /* ++ * Create per-CPU request FQs targeting CAAM's Direct Connect Portal. ++ * Context-A = DMA address of preheader (CAAM reads shdesc from here) ++ * Context-B = FQID of per-CPU response FQ (completions to submitter) ++ * ++ * Each CPU gets its own request FQ so that CAAM routes completions ++ * back to the submitting CPU's QMan portal, avoiding cross-CPU ++ * delivery overhead. ++ */ ++ prehdr_pa = ctx->prehdr_shdesc.paddr; ++ memset(&context_a, 0, sizeof(context_a)); ++ context_a.res[0] = (uint32_t)(prehdr_pa >> 32); ++ context_a.res[1] = (uint32_t)prehdr_pa; ++ ++ ctx->ncpus = mp_ncpus; ++ if (ctx->ncpus > MAXCPU) ++ ctx->ncpus = MAXCPU; ++ ++ for (int cpu = 0; cpu < ctx->ncpus; cpu++) { ++ context_b = qi->rsp_fqid[cpu]; ++ ++ ctx->req_fqr[cpu] = qman_fqr_create_ctx(1, ++ e_QM_FQ_CHANNEL_CAAM, ++ 2, /* WQ 2 */ ++ FALSE, /* don't force FQID */ ++ 0, /* alignment */ ++ TRUE, /* prefer_in_cache */ ++ &context_a, ++ &context_b); ++ ++ if (ctx->req_fqr[cpu] == NULL) { ++ device_printf(qi->dev, ++ "QI: failed to create request FQ for CPU %d\n", ++ cpu); ++ for (int j = cpu - 1; j >= 0; j--) ++ qman_fqr_free(ctx->req_fqr[j]); ++ caam_dma_free(&ctx->prehdr_shdesc); ++ free(ctx, M_CAAM_QI); ++ return (ENXIO); ++ } ++ } ++ ++ *ctxp = ctx; ++ return (0); ++} ++ ++static void ++caam_qi_drv_ctx_destroy(struct caam_qi_drv_ctx *ctx) ++{ ++ int cpu; ++ ++ if (ctx == NULL) ++ return; ++ ++ for (cpu = 0; cpu < ctx->ncpus; cpu++) { ++ if (ctx->req_fqr[cpu] != NULL) ++ 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); ++ free(ctx, M_CAAM_QI); ++} ++ ++static int ++caam_qi_newsession(device_t dev, crypto_session_t cses, ++ const struct crypto_session_params *csp) ++{ ++ struct caam_qi_softc *qi = caam_qi_sc; ++ struct caam_session *sess; ++ int error; ++ ++ sess = crypto_get_driver_session(cses); ++ memset(sess, 0, sizeof(*sess)); ++ ++ /* Copy cipher key */ ++ sess->enc_klen = csp->csp_cipher_klen; ++ if (sess->enc_klen > 0 && csp->csp_cipher_key != NULL) ++ memcpy(sess->enc_key, csp->csp_cipher_key, sess->enc_klen); ++ ++ switch (csp->csp_mode) { ++ case CSP_MODE_AEAD: ++ sess->alg_type = CAAM_ALG_GCM; ++ 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; ++ ++ error = caam_qi_drv_ctx_create(qi, sess, &sess->qi_enc_ctx, ++ caam_qi_gcm_build_enc_shdesc); ++ if (error != 0) ++ return (error); ++ error = caam_qi_drv_ctx_create(qi, sess, &sess->qi_dec_ctx, ++ caam_qi_gcm_build_dec_shdesc); ++ if (error != 0) { ++ caam_qi_drv_ctx_destroy(sess->qi_enc_ctx); ++ sess->qi_enc_ctx = NULL; ++ return (error); ++ } ++ break; ++ ++ case CSP_MODE_ETA: ++ if (csp->csp_cipher_alg == CRYPTO_NULL_CBC) ++ sess->alg_type = CAAM_ALG_NULL_HMAC; ++ else ++ sess->alg_type = CAAM_ALG_CBC_HMAC; ++ ++ sess->cipher_algtype = caam_cipher_algtype( ++ csp->csp_cipher_alg); ++ sess->ivlen = caam_cipher_ivlen(csp->csp_cipher_alg); ++ sess->icvlen = (csp->csp_auth_mlen != 0) ? ++ csp->csp_auth_mlen : ++ caam_auth_digest_len(csp->csp_auth_alg); ++ sess->auth_algtype = caam_auth_algsel(csp->csp_auth_alg); ++ if (sess->auth_algtype == 0) ++ return (EINVAL); ++ ++ 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->split_key_pad_len = caam_split_key_pad_len( ++ sess->auth_algtype & OP_ALG_ALGSEL_MASK); ++ ++ if (sess->alg_type == CAAM_ALG_NULL_HMAC) { ++ error = caam_qi_drv_ctx_create(qi, sess, ++ &sess->qi_enc_ctx, ++ caam_qi_null_hmac_build_enc_shdesc); ++ if (error != 0) ++ return (error); ++ error = caam_qi_drv_ctx_create(qi, sess, ++ &sess->qi_dec_ctx, ++ caam_qi_null_hmac_build_dec_shdesc); ++ } else { ++ error = caam_qi_drv_ctx_create(qi, sess, ++ &sess->qi_enc_ctx, ++ caam_qi_eta_build_enc_shdesc); ++ if (error != 0) ++ return (error); ++ error = caam_qi_drv_ctx_create(qi, sess, ++ &sess->qi_dec_ctx, ++ caam_qi_eta_build_dec_shdesc); ++ } ++ if (error != 0) { ++ caam_qi_drv_ctx_destroy(sess->qi_enc_ctx); ++ sess->qi_enc_ctx = NULL; ++ return (error); ++ } ++ break; ++ ++ case CSP_MODE_DIGEST: ++ sess->auth_algtype = caam_auth_algsel(csp->csp_auth_alg); ++ if (sess->auth_algtype == 0) ++ return (EINVAL); ++ sess->icvlen = (csp->csp_auth_mlen != 0) ? ++ csp->csp_auth_mlen : ++ caam_auth_digest_len(csp->csp_auth_alg); ++ sess->ivlen = 0; ++ sess->enc_klen = 0; ++ ++ if (csp->csp_auth_klen > 0) { ++ sess->alg_type = CAAM_ALG_HMAC; ++ 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->split_key_pad_len = caam_split_key_pad_len( ++ sess->auth_algtype & OP_ALG_ALGSEL_MASK); ++ } else { ++ sess->alg_type = CAAM_ALG_HASH; ++ sess->auth_klen = 0; ++ } ++ ++ error = caam_qi_drv_ctx_create(qi, sess, &sess->qi_enc_ctx, ++ caam_qi_hash_build_shdesc); ++ if (error != 0) ++ return (error); ++ /* No dec_ctx for hash — verify done in software */ ++ break; ++ ++ case CSP_MODE_CIPHER: ++ sess->alg_type = CAAM_ALG_CIPHER; ++ sess->cipher_algtype = caam_cipher_algtype( ++ csp->csp_cipher_alg); ++ sess->ivlen = caam_cipher_ivlen(csp->csp_cipher_alg); ++ sess->icvlen = 0; ++ ++ if (sess->cipher_algtype == 0) ++ return (EINVAL); ++ ++ error = caam_qi_drv_ctx_create(qi, sess, &sess->qi_enc_ctx, ++ caam_qi_cipher_build_enc_shdesc); ++ if (error != 0) ++ return (error); ++ error = caam_qi_drv_ctx_create(qi, sess, &sess->qi_dec_ctx, ++ caam_qi_cipher_build_dec_shdesc); ++ if (error != 0) { ++ caam_qi_drv_ctx_destroy(sess->qi_enc_ctx); ++ sess->qi_enc_ctx = NULL; ++ return (error); ++ } ++ break; ++ ++ default: ++ return (EINVAL); ++ } ++ ++ return (0); ++} ++ ++static void ++caam_qi_freesession(device_t dev, crypto_session_t cses) ++{ ++ struct caam_session *sess; ++ ++ sess = crypto_get_driver_session(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)); ++ ++ caam_qi_drv_ctx_destroy(sess->qi_enc_ctx); ++ caam_qi_drv_ctx_destroy(sess->qi_dec_ctx); ++ sess->qi_enc_ctx = NULL; ++ sess->qi_dec_ctx = NULL; ++} ++ ++/* ================================================================ ++ * Process — submit a crypto request via QI compound FD ++ * ================================================================ */ ++ ++static int ++caam_qi_process(device_t dev, struct cryptop *crp, int hint) ++{ ++ struct caam_qi_softc *qi = caam_qi_sc; ++ struct caam_session *sess; ++ struct caam_qi_request *req; ++ struct caam_qi_drv_ctx *drv_ctx; ++ t_DpaaSGTE *sgt; ++ t_DpaaFD fd; ++ t_Error err; ++ uint8_t *buf; ++ bus_addr_t bounce_pa; ++ size_t total_len; ++ int qi_prefix, in_len, out_len, offset; ++ bool encrypt; ++ ++ sess = crypto_get_driver_session(crp->crp_session); ++ encrypt = CRYPTO_OP_IS_ENCRYPT(crp->crp_op); ++ ++ /* Select direction-specific context */ ++ if (sess->alg_type == CAAM_ALG_HASH || ++ sess->alg_type == CAAM_ALG_HMAC) { ++ drv_ctx = sess->qi_enc_ctx; /* Hash always uses enc */ ++ } else { ++ drv_ctx = encrypt ? sess->qi_enc_ctx : sess->qi_dec_ctx; ++ } ++ ++ if (__predict_false(drv_ctx == NULL)) { ++ crp->crp_etype = EINVAL; ++ crypto_done(crp); ++ return (0); ++ } ++ ++ /* Allocate request from pool */ ++ req = caam_qi_pool_alloc(qi); ++ if (__predict_false(req == NULL)) { ++ mtx_lock(&qi->pool_lock); ++ qi->blocked = true; ++ mtx_unlock(&qi->pool_lock); ++ return (ERESTART); ++ } ++ ++ req->crp = crp; ++ req->sess = sess; ++ req->drv_ctx = drv_ctx; ++ ++ /* ++ * Compute QI prefix size. ++ * QI input: [assoclen(4B, BE)] [IV(ivlen)] [AAD] [payload] [ICV] ++ * Cipher-only: [IV(ivlen)] [payload] ++ * Hash: [payload] (no prefix) ++ */ ++ if (sess->alg_type == CAAM_ALG_HASH || ++ sess->alg_type == CAAM_ALG_HMAC) { ++ qi_prefix = 0; ++ } else if (sess->alg_type == CAAM_ALG_CIPHER) { ++ qi_prefix = sess->ivlen; ++ } else { ++ qi_prefix = 4 + sess->ivlen; /* assoclen + IV */ ++ } ++ ++ total_len = (size_t)qi_prefix + (size_t)crp->crp_aad_length + ++ (size_t)crp->crp_payload_length + (size_t)sess->icvlen; ++ ++ /* Allocate bounce buffer */ ++ if (__predict_false(total_len > CAAM_BOUNCE_SZ)) { ++ int error; ++ ++ error = caam_dma_alloc(qi->dev, &req->dyn_bounce, total_len); ++ if (error != 0) { ++ caam_qi_pool_free(qi, req); ++ crp->crp_etype = ENOMEM; ++ crypto_done(crp); ++ return (0); ++ } ++ req->using_dyn = true; ++ buf = req->dyn_bounce.vaddr; ++ bounce_pa = req->dyn_bounce.paddr; ++ } else { ++ buf = req->bounce.vaddr; ++ bounce_pa = req->bounce.paddr; ++ } ++ ++ /* ++ * Fill QI input buffer. ++ */ ++ offset = 0; ++ ++ /* QI prefix: assoclen (4 bytes, big-endian) */ ++ if (qi_prefix >= 4 && sess->alg_type != CAAM_ALG_CIPHER) { ++ *(uint32_t *)buf = htobe32(crp->crp_aad_length); ++ offset = 4; ++ } ++ ++ /* QI prefix: IV */ ++ if (sess->ivlen > 0) { ++ crypto_read_iv(crp, buf + offset); ++ offset += sess->ivlen; ++ } ++ ++ /* AAD */ ++ if (crp->crp_aad_length > 0) { ++ if (crp->crp_aad != NULL) ++ memcpy(buf + offset, crp->crp_aad, ++ crp->crp_aad_length); ++ else ++ crypto_copydata(crp, crp->crp_aad_start, ++ crp->crp_aad_length, buf + offset); ++ } ++ offset += crp->crp_aad_length; ++ ++ /* Payload */ ++ if (crp->crp_payload_length > 0) ++ crypto_copydata(crp, crp->crp_payload_start, ++ crp->crp_payload_length, buf + offset); ++ offset += crp->crp_payload_length; ++ ++ /* ICV for decrypt */ ++ if (!encrypt && sess->alg_type != CAAM_ALG_HASH && ++ sess->alg_type != CAAM_ALG_HMAC && ++ sess->icvlen > 0) ++ crypto_copydata(crp, crp->crp_digest_start, ++ sess->icvlen, buf + offset); ++ ++ /* ++ * Compute input and output lengths for the compound FD. ++ * ++ * Input = what CAAM reads (QI prefix + AAD + payload + ICV for decrypt) ++ * Output = what CAAM writes — NO qi_prefix. The shdesc consumes ++ * the prefix from SEQINLEN via SEQ LOAD/FIFO LOAD, but never ++ * writes it to output. Including qi_prefix in out_len would ++ * leave SEQOUTLEN non-zero, causing CAAM to hang. ++ */ ++ in_len = qi_prefix + crp->crp_aad_length + crp->crp_payload_length; ++ out_len = crp->crp_aad_length + crp->crp_payload_length; ++ ++ if (sess->alg_type == CAAM_ALG_HASH || ++ sess->alg_type == CAAM_ALG_HMAC) { ++ in_len = crp->crp_payload_length; ++ out_len = sess->icvlen; /* Hash output is just the digest */ ++ } else if (encrypt) { ++ out_len += sess->icvlen; /* Output includes ICV */ ++ } else { ++ in_len += sess->icvlen; /* Input includes ICV */ ++ } ++ ++ /* ++ * Build compound FD S/G table (2 entries in DMA memory). ++ * Entry 0: OUTPUT buffer (CAAM writes here, past QI prefix) ++ * Entry 1: INPUT buffer (CAAM reads here, includes QI prefix), F=1 ++ * ++ * The output buffer starts at bounce_pa + qi_prefix because the ++ * shdesc consumes the prefix (assoclen, IV) from input only. ++ * CAAM writes output sequentially: [SKIP AAD] [data] [ICV]. ++ * ++ * DPAA_SGTE_SET_* macros handle big-endian byte-swap for ++ * CAAM's DMA byte order. ++ */ ++ sgt = (t_DpaaSGTE *)req->sgt.vaddr; ++ memset(sgt, 0, CAAM_QI_SGT_SZ); ++ ++ { ++ bus_addr_t out_pa = bounce_pa + qi_prefix; ++ ++ /* Output S/G entry (past QI prefix) */ ++ DPAA_SGTE_SET_ADDRH(&sgt[0], (uint32_t)(out_pa >> 32)); ++ DPAA_SGTE_SET_ADDRL(&sgt[0], (uint32_t)out_pa); ++ DPAA_SGTE_SET_LENGTH(&sgt[0], out_len); ++ DPAA_SGTE_SET_FINAL(&sgt[0], 0); ++ DPAA_SGTE_SET_OFFSET(&sgt[0], 0); ++ } ++ ++ /* Input S/G entry (Full bounce buffer including QI prefix, Final) */ ++ DPAA_SGTE_SET_ADDRH(&sgt[1], (uint32_t)(bounce_pa >> 32)); ++ DPAA_SGTE_SET_ADDRL(&sgt[1], (uint32_t)bounce_pa); ++ DPAA_SGTE_SET_LENGTH(&sgt[1], in_len); ++ DPAA_SGTE_SET_FINAL(&sgt[1], 1); ++ DPAA_SGTE_SET_OFFSET(&sgt[1], 0); ++ ++ /* ++ * Build compound Frame Descriptor. ++ * fd.addr = DMA address of S/G table (CPU-native; QMan portal ++ * handles byte-swap during enqueue). ++ * fd.format = COMPOUND ++ * fd.length = input length (congestion weight) ++ * fd.status = 0 ++ */ ++ memset(&fd, 0, sizeof(fd)); ++ DPAA_FD_SET_ADDRH(&fd, (uint32_t)(req->sgt.paddr >> 32)); ++ DPAA_FD_SET_ADDRL(&fd, (uint32_t)req->sgt.paddr); ++ DPAA_FD_SET_FORMAT(&fd, e_DPAA_FD_FORMAT_TYPE_COMPOUND); ++ DPAA_FD_SET_LENGTH(&fd, in_len); ++ DPAA_FD_SET_STATUS(&fd, 0); ++ ++ err = qman_fqr_enqueue(drv_ctx->req_fqr[curcpu % drv_ctx->ncpus], ++ 0, &fd); ++ if (__predict_false(err != E_OK)) { ++ printf("caam_qi: enqueue failed: %d\n", err); ++ caam_qi_pool_free(qi, req); ++ if (err == E_BUSY) { ++ mtx_lock(&qi->pool_lock); ++ qi->blocked = true; ++ mtx_unlock(&qi->pool_lock); ++ return (ERESTART); ++ } ++ crp->crp_etype = EIO; ++ crypto_done(crp); ++ return (0); ++ } ++ ++ return (0); ++} ++ ++/* ================================================================ ++ * QI Device Driver ++ * ================================================================ */ ++ ++static int ++caam_qi_probe(device_t dev) ++{ ++ ++ /* ++ * Only match the pseudo-device created by device_add_child() ++ * in caam_attach(), not the FDT jr@ children which belong to ++ * the caam_jr driver. ++ * ++ * simplebus_add_child() sets obd_node = -1 for pseudo-devices. ++ * phandle_t is uint32_t, so (phandle_t)-1 = 0xFFFFFFFF. ++ * DT children have valid phandles (positive values != -1). ++ */ ++ if (ofw_bus_get_node(dev) != (phandle_t)-1) ++ return (ENXIO); ++ ++ device_set_desc(dev, "NXP CAAM QI crypto backend"); ++ return (BUS_PROBE_SPECIFIC); ++} ++ ++static int ++caam_qi_attach(device_t dev) ++{ ++ struct caam_qi_softc *qi; ++ int error; ++ ++ if (caam_qi_sc != NULL) { ++ device_printf(dev, "QI already initialized\n"); ++ return (EEXIST); ++ } ++ ++ qi = malloc(sizeof(*qi), M_CAAM_QI, M_WAITOK | M_ZERO); ++ qi->dev = dev; ++ qi->cid = -1; ++ ++ /* Create per-CPU response FQs */ ++ error = caam_qi_create_rsp_fqs(qi); ++ if (error != 0) ++ goto fail; ++ ++ /* Allocate request pool */ ++ error = caam_qi_pool_init(qi); ++ if (error != 0) { ++ caam_qi_destroy_rsp_fqs(qi); ++ goto fail; ++ } ++ ++ /* Register with opencrypto */ ++ qi->cid = crypto_get_driverid(dev, ++ sizeof(struct caam_session), CRYPTOCAP_F_HARDWARE); ++ if (qi->cid < 0) { ++ device_printf(dev, "QI: failed to register with opencrypto\n"); ++ caam_qi_pool_fini(qi); ++ caam_qi_destroy_rsp_fqs(qi); ++ goto fail; ++ } ++ ++ caam_qi_sc = qi; ++ ++ device_printf(dev, ++ "QI: registered with opencrypto (driverid %d), " ++ "%d requests (%zuKB sgt + %zuKB bounce)\n", ++ qi->cid, CAAM_QI_DEPTH, ++ (size_t)(CAAM_QI_DEPTH * CAAM_QI_SGT_SZ / 1024), ++ (size_t)(CAAM_QI_DEPTH * CAAM_BOUNCE_SZ / 1024)); ++ ++ return (0); ++ ++fail: ++ free(qi, M_CAAM_QI); ++ return (error); ++} ++ ++static int ++caam_qi_detach(device_t dev) ++{ ++ struct caam_qi_softc *qi = caam_qi_sc; ++ ++ if (qi == NULL) ++ return (0); ++ ++ if (qi->cid >= 0) { ++ crypto_unregister_all(qi->cid); ++ qi->cid = -1; ++ } ++ ++ caam_qi_pool_fini(qi); ++ caam_qi_destroy_rsp_fqs(qi); ++ ++ caam_qi_sc = NULL; ++ free(qi, M_CAAM_QI); ++ ++ return (0); ++} ++ ++/* ++ * QI probesession: same algorithm support as JR, but higher priority ++ * so opencrypto routes sessions here instead of to Job Rings. ++ * CRYPTODEV_PROBE_HARDWARE is -100; returning -99 wins the tie. ++ */ ++static int ++caam_qi_probesession(device_t dev, const struct crypto_session_params *csp) ++{ ++ int error; ++ ++ error = caam_probesession(dev, csp); ++ if (error == CRYPTODEV_PROBE_HARDWARE) ++ return (CRYPTODEV_PROBE_HARDWARE + 1); ++ return (error); ++} ++ ++static device_method_t caam_qi_methods[] = { ++ /* Device interface */ ++ DEVMETHOD(device_probe, caam_qi_probe), ++ DEVMETHOD(device_attach, caam_qi_attach), ++ DEVMETHOD(device_detach, caam_qi_detach), ++ ++ /* Cryptodev interface */ ++ DEVMETHOD(cryptodev_probesession, caam_qi_probesession), ++ DEVMETHOD(cryptodev_newsession, caam_qi_newsession), ++ DEVMETHOD(cryptodev_freesession, caam_qi_freesession), ++ DEVMETHOD(cryptodev_process, caam_qi_process), ++ ++ DEVMETHOD_END ++}; ++ ++static driver_t caam_qi_driver = { ++ "caam_qi", ++ caam_qi_methods, ++ 0, /* No private softc — we manage our own */ ++}; ++ ++DRIVER_MODULE(caam_qi, caam, caam_qi_driver, 0, 0); ++MODULE_VERSION(caam_qi, 1); ++MODULE_DEPEND(caam_qi, caam, 1, 1, 1); ++MODULE_DEPEND(caam_qi, caam_jr, 1, 1, 1); ++MODULE_DEPEND(caam_qi, crypto, 1, 1, 1); +diff --git a/sys/dev/caam/caam_qi.h b/sys/dev/caam/caam_qi.h +new file mode 100644 +index 00000000000..ec7bddb4611 +--- /dev/null ++++ b/sys/dev/caam/caam_qi.h +@@ -0,0 +1,129 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * CAAM QI (Queue Interface) backend — data structures. ++ * ++ * QI submits crypto operations through QMan frame queues instead of Job ++ * Rings, eliminating the JR spinlock for high packet-rate IPsec workloads. ++ * Per-session request FQs target CAAM's Direct Connect Portal (channel ++ * 0x840), and per-CPU response FQs deliver completions deterministically. ++ */ ++ ++#ifndef _CAAM_QI_H ++#define _CAAM_QI_H ++ ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include "caam_jr.h" ++ ++/* Forward declarations */ ++struct caam_session; ++struct cryptop; ++ ++/* ++ * Pool depth for QI requests — matches JR pool depth. ++ */ ++#define CAAM_QI_DEPTH 512 ++ ++/* ++ * Maximum shared descriptor + preheader size in bytes. ++ * Preheader = 2 words, shared desc up to 64 words = 66 words = 264 bytes. ++ * Round up to 512 for alignment. ++ */ ++#define CAAM_QI_PREHDR_SZ 512 ++ ++/* ++ * Per-session QI driver context. ++ * ++ * Holds the preheader + shared descriptor in DMA memory (FQ Context-A ++ * points here), and the request FQ targeting CAAM's DCP channel. ++ */ ++struct caam_qi_drv_ctx { ++ struct caam_dma_mem prehdr_shdesc; /* prehdr[2] + shdesc[MAX] */ ++ int shdesc_len; /* Shared desc length (words) */ ++ t_Handle req_fqr[MAXCPU]; /* Per-CPU request FQs → CAAM */ ++ int ncpus; /* Number of req FQs created */ ++}; ++ ++/* ++ * S/G entry size for compound FD: 2 entries (output + input). ++ */ ++#define CAAM_QI_SGT_SZ (2 * sizeof(t_DpaaSGTE)) ++ ++/* ++ * Per-request QI context. ++ * ++ * Pre-allocated in a pool. S/G entries for the compound FD live in ++ * the DMA-mapped sgt_bulk region (accessed via sgt.vaddr / sgt.paddr). ++ * The request index is recovered from the response FD's address. ++ */ ++struct caam_qi_request { ++ struct cryptop *crp; ++ struct caam_session *sess; ++ struct caam_qi_drv_ctx *drv_ctx; ++ ++ /* S/G table for compound FD (slice of sgt_bulk) */ ++ struct caam_dma_mem sgt; ++ ++ /* Bounce buffer for payload I/O (slice of bulk alloc) */ ++ struct caam_dma_mem bounce; ++ ++ /* Dynamic fallback for oversized payloads */ ++ struct caam_dma_mem dyn_bounce; ++ bool using_dyn; ++ ++ /* Pool linkage (free list index; -1 = not in pool) */ ++ int next_free; ++}; ++ ++/* ++ * QI softc — singleton, initialized from the first JR when QI is present. ++ */ ++struct caam_qi_softc { ++ device_t dev; /* Parent JR device */ ++ int32_t cid; /* opencrypto driver ID */ ++ ++ /* Per-CPU response FQs */ ++ t_Handle rsp_fqr[MAXCPU]; ++ uint32_t rsp_fqid[MAXCPU]; ++ ++ /* Request pool (bulk DMA, same pattern as JR) */ ++ struct caam_qi_request *requests; ++ struct caam_dma_mem sgt_bulk; /* fd_sgt arrays */ ++ struct caam_dma_mem bounce_bulk; /* bounce buffers */ ++ struct mtx pool_lock; ++ int pool_head; /* Free list head (-1 = empty) */ ++ bool blocked; /* ERESTART returned */ ++}; ++ ++/* Global QI softc — NULL if QI not available */ ++extern struct caam_qi_softc *caam_qi_sc; ++ ++/* QI-specific shared descriptor builders (caam_qi_alg.c) */ ++int caam_qi_gcm_build_enc_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx); ++int caam_qi_gcm_build_dec_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx); ++int caam_qi_eta_build_enc_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx); ++int caam_qi_eta_build_dec_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx); ++int caam_qi_cipher_build_enc_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx); ++int caam_qi_cipher_build_dec_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx); ++int caam_qi_null_hmac_build_enc_shdesc(struct caam_session *sess, ++ device_t dev, struct caam_qi_drv_ctx *ctx); ++int caam_qi_null_hmac_build_dec_shdesc(struct caam_session *sess, ++ device_t dev, struct caam_qi_drv_ctx *ctx); ++int caam_qi_hash_build_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx); ++ ++#endif /* _CAAM_QI_H */ +diff --git a/sys/dev/caam/caam_qi_alg.c b/sys/dev/caam/caam_qi_alg.c +new file mode 100644 +index 00000000000..4a2b770be70 +--- /dev/null ++++ b/sys/dev/caam/caam_qi_alg.c +@@ -0,0 +1,905 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * CAAM QI shared descriptor builders. ++ * ++ * QI shared descriptors differ from JR versions in two ways: ++ * 1. Parameters (assoclen, IV) read via SEQ LOAD from the input stream ++ * (replacing the JD body which runs first with HDR_REVERSE in JR mode) ++ * 2. No per-request job descriptor — everything is in the shared descriptor ++ * ++ * Instruction ordering: KEY and OPERATION must come before SEQ FIFO LOAD ++ * with FLUSH1 — the CHA must be initialized before it can accept flushed ++ * data. Violating this causes a DECO pipeline deadlock. ++ * ++ * QI input stream layout (compound FD input S/G → bounce buffer): ++ * AEAD: [assoclen(4B,BE)] [IV(ivlen)] [AAD] [payload] [ICV for decrypt] ++ * ETA: [assoclen(4B,BE)] [IV(ivlen)] [AAD] [payload] [ICV for decrypt] ++ * Cipher: [IV(ivlen)] [payload] ++ * Hash: [payload] ++ * ++ * The shared descriptor is written at offset 8 (after the 2-word preheader) ++ * in ctx->prehdr_shdesc DMA memory. ++ */ ++ ++#include ++#include ++#include ++#include ++ ++#include ++ ++#include ++ ++#include "caam.h" ++#include "caam_regs.h" ++#include "caam_desc.h" ++#include "caam_jr.h" ++#include "caam_crypto.h" ++#include "caam_qi.h" ++ ++/* ++ * Start address for shdesc within the preheader+shdesc DMA buffer. ++ * Preheader occupies words [0] and [1]; shdesc starts at word [2]. ++ */ ++#define QI_SHDESC_OFFSET (2 * sizeof(uint32_t)) ++ ++static uint32_t * ++qi_shdesc_ptr(struct caam_qi_drv_ctx *ctx) ++{ ++ ++ return ((uint32_t *)((uint8_t *)ctx->prehdr_shdesc.vaddr + ++ QI_SHDESC_OFFSET)); ++} ++ ++/* ++ * Prepend JUMP NIFP to shared descriptor. ++ * Tests NIFP (No Input Frame Pending) condition: ++ * - If set (no frame), jump to self (busy-wait) ++ * - If clear (frame ready), fall through ++ */ ++static void ++qi_shdesc_add_nifp(uint32_t *desc) ++{ ++ ++ caam_desc_add_word(desc, ++ CMD_JUMP | JUMP_TEST_ALL | JUMP_COND_NIFP | 1); ++} ++ ++/* ++ * Pipeline barrier after SEQ LOAD into MATH register. ++ * Ensures the DECO pipeline drains before MATH operations ++ * read the loaded value. Matches Linux's wait_load_cmd pattern. ++ */ ++static void ++qi_shdesc_add_load_barrier(uint32_t *desc) ++{ ++ ++ caam_desc_add_word(desc, ++ CMD_JUMP | JUMP_TEST_ALL | ++ JUMP_COND_CALM | JUMP_COND_NCP | JUMP_COND_NOP | ++ JUMP_COND_NIP | JUMP_COND_NIFP | 1); ++} ++ ++/* ================================================================ ++ * AES-GCM QI Shared Descriptors ++ * ++ * Input stream: [assoclen(4B)] [IV(12B)] [AAD] [payload] [ICV] ++ * ================================================================ */ ++ ++int ++caam_qi_gcm_build_enc_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump, *zero_assoc_jump1, *zero_assoc_jump2, ++ *zero_payload_jump; ++ ++ desc = qi_shdesc_ptr(ctx); ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL); ++ ++ /* Skip key loading if already shared */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ /* Load AES key (inline) */ ++ caam_desc_add_word(desc, ++ CMD_KEY | KEY_CLASS1 | KEY_DEST_CLASS_REG | ++ KEY_IMM | sess->enc_klen); ++ caam_desc_add_key_imm(desc, sess->enc_key, sess->enc_klen); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* ++ * OPERATION: AES-GCM encrypt, init+final. ++ * MUST be before SEQ FIFO LOAD IV — the GCM CHA must be ++ * initialized before it can accept IV data via FLUSH1. ++ */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ OP_ALG_ALGSEL_AES | OP_ALG_AAI_GCM | ++ OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT); ++ ++ /* Read assoclen (4 bytes, BE) from input stream → REG3 lower half */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_LOAD | LDST_CLASS_DECO | ++ LDST_SRCDST_WORD_DECO_MATH3 | ++ (4 << LDST_OFFSET_SHIFT) | sizeof(uint32_t)); ++ qi_shdesc_add_load_barrier(desc); ++ ++ /* Read IV (12 bytes) from input stream into Class 1 FIFO */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | ++ FIFOLD_TYPE_IV | FIFOLD_TYPE_FLUSH1 | AES_GCM_IV_LEN); ++ ++ /* --- Same processing body as JR shdesc --- */ ++ ++ /* VARSEQOUTLEN = SEQINLEN - REG0(=0) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_SUB | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* If total length is zero, skip to ICV write */ ++ zero_assoc_jump2 = caam_desc_add_jump(desc, ++ JUMP_TEST_ALL | JUMP_COND_MATH_Z); ++ ++ /* VARSEQINLEN = REG3 (= assoclen) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_REG3 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* If assoclen is zero, skip AAD */ ++ zero_assoc_jump1 = caam_desc_add_jump(desc, ++ JUMP_TEST_ALL | JUMP_COND_MATH_Z); ++ ++ /* VARSEQOUTLEN = REG3 */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_REG3 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Skip AAD in output */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_SKIP | FIFOLDST_VLF); ++ ++ /* cryptlen = SEQINLEN - REG3 */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_SUB | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG3 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* If cryptlen is zero, jump to zero-payload path */ ++ zero_payload_jump = caam_desc_add_jump(desc, ++ JUMP_TEST_ALL | JUMP_COND_MATH_Z); ++ ++ /* Read AAD (CLASS1, AAD, FLUSH1) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_AAD | FIFOLD_TYPE_FLUSH1); ++ ++ caam_desc_set_jump_target(desc, zero_assoc_jump1); ++ ++ /* VARSEQINLEN = SEQINLEN - REG0 (remaining = cryptlen) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_SUB | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* Write encrypted payload */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_MESSAGE_DATA | FIFOLDST_VLF); ++ ++ /* Read plaintext (CLASS1, MSG, LAST1) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG | FIFOLD_TYPE_LAST1); ++ ++ /* Jump past zero-payload path */ ++ caam_desc_add_word(desc, CMD_JUMP | JUMP_TEST_ALL | 2); ++ ++ /* Zero-payload: read AAD only (AAD | LAST1) */ ++ caam_desc_set_jump_target(desc, zero_payload_jump); ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_AAD | FIFOLD_TYPE_LAST1); ++ ++ /* Zero-total-length target */ ++ caam_desc_set_jump_target(desc, zero_assoc_jump2); ++ ++ /* Write ICV */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_STORE | LDST_CLASS_1_CCB | ++ LDST_SRCDST_BYTE_CONTEXT | sess->icvlen); ++ ++ ctx->shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++int ++caam_qi_gcm_build_dec_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump, *zero_assoc_jump1, *zero_payload_jump; ++ ++ desc = qi_shdesc_ptr(ctx); ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL); ++ ++ /* Key loading */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ caam_desc_add_word(desc, ++ CMD_KEY | KEY_CLASS1 | KEY_DEST_CLASS_REG | ++ KEY_IMM | sess->enc_klen); ++ caam_desc_add_key_imm(desc, sess->enc_key, sess->enc_klen); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* OPERATION before IV FIFO LOAD — GCM CHA must be initialized first */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ OP_ALG_ALGSEL_AES | OP_ALG_AAI_GCM | ++ OP_ALG_AS_INITFINAL | OP_ALG_DECRYPT | OP_ALG_ICV_ON); ++ ++ /* Read assoclen → REG3 lower half */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_LOAD | LDST_CLASS_DECO | ++ LDST_SRCDST_WORD_DECO_MATH3 | ++ (4 << LDST_OFFSET_SHIFT) | sizeof(uint32_t)); ++ qi_shdesc_add_load_barrier(desc); ++ ++ /* Read IV from input stream */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | ++ FIFOLD_TYPE_IV | FIFOLD_TYPE_FLUSH1 | AES_GCM_IV_LEN); ++ ++ /* --- Same processing body as JR dec shdesc --- */ ++ ++ /* VARSEQINLEN = REG3 */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_REG3 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ zero_assoc_jump1 = caam_desc_add_jump(desc, ++ JUMP_TEST_ALL | JUMP_COND_MATH_Z); ++ ++ /* VARSEQOUTLEN = REG3 */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_REG3 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Skip AAD in output */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_SKIP | FIFOLDST_VLF); ++ ++ /* Read AAD */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_AAD | FIFOLD_TYPE_FLUSH1); ++ ++ caam_desc_set_jump_target(desc, zero_assoc_jump1); ++ ++ /* cryptlen = SEQOUTLEN - REG0 */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_SUB | ++ MATH_SRC0_SEQOUTLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ zero_payload_jump = caam_desc_add_jump(desc, ++ JUMP_TEST_ALL | JUMP_COND_MATH_Z); ++ ++ /* VARSEQOUTLEN = SEQOUTLEN - REG0 */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_SUB | ++ MATH_SRC0_SEQOUTLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Write decrypted payload */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_MESSAGE_DATA | FIFOLDST_VLF); ++ ++ /* Read ciphertext */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG | FIFOLD_TYPE_FLUSH1); ++ ++ caam_desc_set_jump_target(desc, zero_payload_jump); ++ ++ /* Read ICV for verification */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | ++ FIFOLD_TYPE_ICV | FIFOLD_TYPE_LAST1 | sess->icvlen); ++ ++ ctx->shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++/* ================================================================ ++ * ETA (Cipher + HMAC) QI Shared Descriptors ++ * ++ * Input stream: [assoclen(4B)] [IV(ivlen)] [AAD] [payload] [ICV] ++ * ================================================================ */ ++ ++int ++caam_qi_eta_build_enc_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ ++ desc = qi_shdesc_ptr(ctx); ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL | HDR_SAVECTX); ++ ++ /* Key loading first (matches Linux QI ETA order) */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ caam_desc_add_proto_dkp(desc, sess->auth_algtype, ++ sess->auth_key, sess->auth_klen, sess->split_key_pad_len); ++ ++ caam_desc_add_word(desc, ++ CMD_KEY | KEY_CLASS1 | KEY_DEST_CLASS_REG | ++ KEY_IMM | sess->enc_klen); ++ caam_desc_add_key_imm(desc, sess->enc_key, sess->enc_klen); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* Read assoclen → REG3 lower half → DPOVRD */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_LOAD | LDST_CLASS_DECO | ++ LDST_SRCDST_WORD_DECO_MATH3 | ++ (4 << LDST_OFFSET_SHIFT) | sizeof(uint32_t)); ++ qi_shdesc_add_load_barrier(desc); ++ ++ /* Copy REG3 → DPOVRD (ETA uses DPOVRD for assoclen) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_REG3 | ++ MATH_DEST_DPOVRD | MATH_LEN_4BYTE); ++ ++ /* Read IV from input stream → Class 1 context register */ ++ if (sess->ivlen > 0) { ++ caam_desc_add_word(desc, ++ CMD_SEQ_LOAD | LDST_CLASS_1_CCB | ++ LDST_SRCDST_BYTE_CONTEXT | sess->ivlen); ++ } ++ ++ /* --- Same processing body as JR ETA enc shdesc --- */ ++ ++ /* Class 2 OPERATION: HMAC encrypt */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS2_ALG | ++ sess->auth_algtype | OP_ALG_AAI_HMAC_PRECOMP | ++ OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT); ++ ++ /* VARSEQINLEN = DPOVRD = assoclen */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_DPOVRD | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* VARSEQOUTLEN = DPOVRD */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_DPOVRD | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Skip AAD in output */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_SKIP | FIFOLDST_VLF); ++ ++ /* Read AAD for HMAC (CLASS2, MSG) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | ++ FIFOLD_TYPE_MSG | FIFOLDST_VLF); ++ ++ /* Class 1 OPERATION: cipher encrypt */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ sess->cipher_algtype | OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT); ++ ++ /* cryptlen = SEQINLEN + REG0(=0) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Read plaintext and write ciphertext (both classes, MSG1OUT2) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_MESSAGE_DATA | FIFOLDST_VLF); ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_BOTH | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG1OUT2); ++ ++ /* Write HMAC ICV */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_STORE | LDST_CLASS_2_CCB | ++ LDST_SRCDST_BYTE_CONTEXT | sess->icvlen); ++ ++ ctx->shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++int ++caam_qi_eta_build_dec_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ ++ desc = qi_shdesc_ptr(ctx); ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL | HDR_SAVECTX); ++ ++ /* Key loading first (matches Linux QI ETA order) */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ caam_desc_add_proto_dkp(desc, sess->auth_algtype, ++ sess->auth_key, sess->auth_klen, sess->split_key_pad_len); ++ ++ caam_desc_add_word(desc, ++ CMD_KEY | KEY_CLASS1 | KEY_DEST_CLASS_REG | ++ KEY_IMM | sess->enc_klen); ++ caam_desc_add_key_imm(desc, sess->enc_key, sess->enc_klen); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* Read assoclen → REG3 lower half → DPOVRD */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_LOAD | LDST_CLASS_DECO | ++ LDST_SRCDST_WORD_DECO_MATH3 | ++ (4 << LDST_OFFSET_SHIFT) | sizeof(uint32_t)); ++ qi_shdesc_add_load_barrier(desc); ++ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_REG3 | ++ MATH_DEST_DPOVRD | MATH_LEN_4BYTE); ++ ++ /* Read IV from input stream → Class 1 context */ ++ if (sess->ivlen > 0) { ++ caam_desc_add_word(desc, ++ CMD_SEQ_LOAD | LDST_CLASS_1_CCB | ++ LDST_SRCDST_BYTE_CONTEXT | sess->ivlen); ++ } ++ ++ /* --- Same processing body as JR ETA dec shdesc --- */ ++ ++ /* Class 2 OPERATION: HMAC verify */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS2_ALG | ++ sess->auth_algtype | OP_ALG_AAI_HMAC_PRECOMP | ++ OP_ALG_AS_INITFINAL | OP_ALG_DECRYPT | OP_ALG_ICV_ON); ++ ++ /* VARSEQINLEN = DPOVRD */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_DPOVRD | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* VARSEQOUTLEN = DPOVRD */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_ZERO | MATH_SRC1_DPOVRD | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Skip AAD in output */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_SKIP | FIFOLDST_VLF); ++ ++ /* Read AAD for HMAC */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | ++ FIFOLD_TYPE_MSG | FIFOLDST_VLF); ++ ++ /* Class 1 OPERATION: cipher decrypt */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ sess->cipher_algtype | OP_ALG_AS_INITFINAL | OP_ALG_DECRYPT); ++ ++ /* cryptlen = SEQOUTLEN + REG0(=0) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQOUTLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQOUTLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Read ciphertext and write plaintext */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_MESSAGE_DATA | FIFOLDST_VLF); ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_BOTH | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG); ++ ++ /* Read ICV for verification */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | ++ FIFOLD_TYPE_LAST2 | FIFOLD_TYPE_ICV | sess->icvlen); ++ ++ ctx->shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++/* ================================================================ ++ * Standalone Cipher QI Shared Descriptors ++ * ++ * Input stream: [IV(ivlen)] [payload] ++ * ================================================================ */ ++ ++static bool ++qi_cipher_is_xts(const struct caam_session *sess) ++{ ++ ++ return ((sess->cipher_algtype & OP_ALG_AAI_MASK) == OP_ALG_AAI_XTS); ++} ++ ++int ++caam_qi_cipher_build_enc_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ ++ desc = qi_shdesc_ptr(ctx); ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL); ++ ++ /* Key loading first (matches Linux QI cipher order) */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ caam_desc_add_word(desc, ++ CMD_KEY | KEY_CLASS1 | KEY_DEST_CLASS_REG | ++ KEY_IMM | sess->enc_klen); ++ caam_desc_add_key_imm(desc, sess->enc_key, sess->enc_klen); ++ ++ if (qi_cipher_is_xts(sess)) { ++ static const uint8_t sector_size[8] = { ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00 ++ }; ++ caam_desc_add_word(desc, ++ CMD_LOAD | LDST_CLASS_1_CCB | LDST_IMM | ++ LDST_SRCDST_BYTE_CONTEXT | ++ (0x28 << LDST_OFFSET_SHIFT) | 8); ++ caam_desc_add_key_imm(desc, sector_size, 8); ++ } ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* Read IV from input stream → Class 1 context register */ ++ if (sess->ivlen > 0) { ++ caam_desc_add_word(desc, ++ CMD_SEQ_LOAD | LDST_CLASS_1_CCB | ++ LDST_SRCDST_BYTE_CONTEXT | sess->ivlen); ++ } ++ ++ /* OPERATION: cipher encrypt */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ sess->cipher_algtype | OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT); ++ ++ /* --- Same processing as JR cipher enc shdesc --- */ ++ ++ /* VARSEQOUTLEN = SEQINLEN */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* VARSEQINLEN = SEQINLEN */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* Read plaintext and write ciphertext */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG | FIFOLD_TYPE_LAST1); ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_MESSAGE_DATA | FIFOLDST_VLF); ++ ++ ctx->shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++int ++caam_qi_cipher_build_dec_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ uint32_t algtype; ++ ++ desc = qi_shdesc_ptr(ctx); ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL); ++ ++ /* Key loading first (matches Linux QI cipher order) */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ caam_desc_add_word(desc, ++ CMD_KEY | KEY_CLASS1 | KEY_DEST_CLASS_REG | ++ KEY_IMM | sess->enc_klen); ++ caam_desc_add_key_imm(desc, sess->enc_key, sess->enc_klen); ++ ++ if (qi_cipher_is_xts(sess)) { ++ static const uint8_t sector_size[8] = { ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00 ++ }; ++ caam_desc_add_word(desc, ++ CMD_LOAD | LDST_CLASS_1_CCB | LDST_IMM | ++ LDST_SRCDST_BYTE_CONTEXT | ++ (0x28 << LDST_OFFSET_SHIFT) | 8); ++ caam_desc_add_key_imm(desc, sector_size, 8); ++ } ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* Read IV from input stream → Class 1 context register */ ++ if (sess->ivlen > 0) { ++ caam_desc_add_word(desc, ++ CMD_SEQ_LOAD | LDST_CLASS_1_CCB | ++ LDST_SRCDST_BYTE_CONTEXT | sess->ivlen); ++ } ++ ++ /* OPERATION: cipher decrypt (with DK optimization for AES) */ ++ algtype = sess->cipher_algtype; ++ if ((algtype & OP_ALG_ALGSEL_MASK) == OP_ALG_ALGSEL_AES && ++ (algtype & OP_ALG_AAI_MASK) != OP_ALG_AAI_CTR_MOD128) { ++ uint32_t *dk_jump, *skip_jump; ++ ++ dk_jump = caam_desc_add_jump(desc, ++ JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ algtype | OP_ALG_AS_INITFINAL | OP_ALG_DECRYPT); ++ ++ skip_jump = caam_desc_add_jump(desc, JUMP_TEST_ALL); ++ ++ caam_desc_set_jump_target(desc, dk_jump); ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ algtype | OP_ALG_AS_INITFINAL | ++ OP_ALG_DECRYPT | OP_ALG_AAI_DK); ++ ++ caam_desc_set_jump_target(desc, skip_jump); ++ } else { ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS1_ALG | ++ algtype | OP_ALG_AS_INITFINAL | OP_ALG_DECRYPT); ++ } ++ ++ /* --- Same processing as JR cipher dec shdesc --- */ ++ ++ /* VARSEQOUTLEN = SEQINLEN */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* VARSEQINLEN = SEQINLEN */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* Read ciphertext and write plaintext */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS1 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG | FIFOLD_TYPE_LAST1); ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_MESSAGE_DATA | FIFOLDST_VLF); ++ ++ ctx->shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++/* ================================================================ ++ * NULL cipher + HMAC QI Shared Descriptors ++ * ++ * Input stream: [assoclen(4B)] [AAD] [payload] [ICV for decrypt] ++ * (no IV — NULL cipher has no IV) ++ * ================================================================ */ ++ ++int ++caam_qi_null_hmac_build_enc_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ ++ desc = qi_shdesc_ptr(ctx); ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL | HDR_SAVECTX); ++ ++ /* Key loading first (matches Linux QI null+hmac order) */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ caam_desc_add_proto_dkp(desc, sess->auth_algtype, ++ sess->auth_key, sess->auth_klen, sess->split_key_pad_len); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* Read assoclen from input stream → REG3 lower half */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_LOAD | LDST_CLASS_DECO | ++ LDST_SRCDST_WORD_DECO_MATH3 | ++ (4 << LDST_OFFSET_SHIFT) | sizeof(uint32_t)); ++ qi_shdesc_add_load_barrier(desc); ++ ++ /* --- Same processing as JR null_hmac enc shdesc --- */ ++ ++ /* OPERATION: HMAC encrypt */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS2_ALG | ++ sess->auth_algtype | OP_ALG_AAI_HMAC_PRECOMP | ++ OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT); ++ ++ /* VARSEQINLEN = SEQINLEN */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* VARSEQOUTLEN = SEQINLEN */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Skip passthrough in output */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_SKIP | FIFOLDST_VLF); ++ ++ /* Feed all data to HMAC */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG | FIFOLD_TYPE_LAST2); ++ ++ /* Write HMAC ICV */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_STORE | LDST_CLASS_2_CCB | ++ LDST_SRCDST_BYTE_CONTEXT | sess->icvlen); ++ ++ ctx->shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++int ++caam_qi_null_hmac_build_dec_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ ++ desc = qi_shdesc_ptr(ctx); ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL | HDR_SAVECTX); ++ ++ /* Key loading first (matches Linux QI null+hmac order) */ ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ caam_desc_add_proto_dkp(desc, sess->auth_algtype, ++ sess->auth_key, sess->auth_klen, sess->split_key_pad_len); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ ++ /* Read assoclen from input stream → REG3 lower half */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_LOAD | LDST_CLASS_DECO | ++ LDST_SRCDST_WORD_DECO_MATH3 | ++ (4 << LDST_OFFSET_SHIFT) | sizeof(uint32_t)); ++ qi_shdesc_add_load_barrier(desc); ++ ++ /* --- Same processing as JR null_hmac dec shdesc --- */ ++ ++ /* OPERATION: HMAC verify */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS2_ALG | ++ sess->auth_algtype | OP_ALG_AAI_HMAC_PRECOMP | ++ OP_ALG_AS_INITFINAL | OP_ALG_DECRYPT | OP_ALG_ICV_ON); ++ ++ /* Data length = SEQOUTLEN (excludes ICV) */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQOUTLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQOUTLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQOUTLEN | MATH_LEN_4BYTE); ++ ++ /* Skip passthrough in output */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_STORE | FIFOST_TYPE_SKIP | FIFOLDST_VLF); ++ ++ /* Feed data to HMAC (no LAST2 yet — ICV follows) */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG); ++ ++ /* Read ICV for verification */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | ++ FIFOLD_TYPE_ICV | FIFOLD_TYPE_LAST2 | sess->icvlen); ++ ++ ctx->shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} ++ ++/* ================================================================ ++ * Hash/HMAC QI Shared Descriptor ++ * ++ * Input stream: [payload] (no prefix — hash has no assoclen or IV) ++ * ================================================================ */ ++ ++int ++caam_qi_hash_build_shdesc(struct caam_session *sess, device_t dev, ++ struct caam_qi_drv_ctx *ctx) ++{ ++ uint32_t *desc; ++ uint32_t *key_jump; ++ bool is_hmac; ++ ++ is_hmac = (sess->alg_type == CAAM_ALG_HMAC); ++ ++ desc = qi_shdesc_ptr(ctx); ++ caam_shdesc_init(desc, HDR_SHARE_SERIAL); ++ ++ if (is_hmac) { ++ key_jump = caam_desc_add_jump(desc, ++ JUMP_JSL | JUMP_TEST_ALL | JUMP_COND_SHRD); ++ ++ caam_desc_add_proto_dkp(desc, sess->auth_algtype, ++ sess->auth_key, sess->auth_klen, ++ sess->split_key_pad_len); ++ ++ caam_desc_set_jump_target(desc, key_jump); ++ } ++ ++ /* --- Same processing as JR hash shdesc --- */ ++ ++ /* OPERATION: hash/HMAC compute */ ++ caam_desc_add_word(desc, ++ CMD_OPERATION | OP_TYPE_CLASS2_ALG | ++ sess->auth_algtype | ++ (is_hmac ? OP_ALG_AAI_HMAC_PRECOMP : 0) | ++ OP_ALG_AS_INITFINAL | OP_ALG_ENCRYPT); ++ ++ /* VARSEQINLEN = SEQINLEN */ ++ caam_desc_add_word(desc, ++ CMD_MATH | MATH_FUN_ADD | ++ MATH_SRC0_SEQINLEN | MATH_SRC1_REG0 | ++ MATH_DEST_VARSEQINLEN | MATH_LEN_4BYTE); ++ ++ /* Feed all data to Class 2 */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_FIFO_LOAD | FIFOLD_CLASS_CLASS2 | FIFOLDST_VLF | ++ FIFOLD_TYPE_MSG | FIFOLD_TYPE_LAST2); ++ ++ /* Store digest */ ++ caam_desc_add_word(desc, ++ CMD_SEQ_STORE | LDST_CLASS_2_CCB | ++ LDST_SRCDST_BYTE_CONTEXT | sess->icvlen); ++ ++ ctx->shdesc_len = caam_shdesc_len(desc); ++ return (0); ++} +diff --git a/sys/dev/caam/caam_regs.h b/sys/dev/caam/caam_regs.h +new file mode 100644 +index 00000000000..ffaea0a92f6 +--- /dev/null ++++ b/sys/dev/caam/caam_regs.h +@@ -0,0 +1,298 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * Hardware register definitions for NXP CAAM (SEC v4.0+) crypto engine. ++ * Derived from the NXP Layerscape LS1046A Security Engine Reference Manual. ++ */ ++ ++#ifndef _CAAM_REGS_H ++#define _CAAM_REGS_H ++ ++/* ++ * CAAM Controller CCSR Registers (relative to controller base, e.g. 0x1700000) ++ * ++ * Register layout uses 64-bit slots where the upper 32 bits (at offset+0) ++ * are often reserved, and the active 32-bit register is at offset+4. ++ * 64-bit registers (ring base addresses) use both halves. ++ */ ++ ++/* Basic Configuration */ ++#define CAAM_MCFGR 0x0004 /* Master Config */ ++#define CAAM_SCFGR 0x000c /* Security Config */ ++ ++/* Job Ring Start */ ++#define CAAM_JRSTART 0x005c ++#define JRSTART_JR0 0x00000001 ++#define JRSTART_JR1 0x00000002 ++#define JRSTART_JR2 0x00000004 ++#define JRSTART_JR3 0x00000008 ++ ++/* Master Config Register bits */ ++#define MCFGR_SWRESET 0x80000000 ++#define MCFGR_WDENABLE 0x40000000 ++#define MCFGR_LONG_PTR 0x00010000 /* Use >32-bit desc addressing */ ++#define MCFGR_AWCACHE_SHIFT 8 ++#define MCFGR_AWCACHE_MASK 0x00000f00 /* AXI write cache attributes */ ++#define MCFGR_AWCACHE_CACH 0x00000200 /* Cacheable */ ++#define MCFGR_AWCACHE_BUFF 0x00000100 /* Bufferable */ ++#define MCFGR_AWCACHE_WALL 0x00000800 /* Write-allocate */ ++#define MCFGR_LARGE_BURST 0x00000004 ++#define MCFGR_BURST_64 0x00000001 ++ ++/* Security Config Register bits */ ++#define SCFGR_RDBENABLE 0x00000400 ++#define SCFGR_VIRT_EN 0x00008000 ++ ++/* ++ * DECO Control Registers (controller-relative) ++ * ++ * DECORSR: selects which JR provides SDID/ICID/TZ for DECO operations. ++ * DECORR: enables/confirms direct DECO access for descriptor execution. ++ */ ++#define CAAM_DECORSR 0x0094 /* DECO Request Source */ ++#define CAAM_DECORR 0x009c /* DECO Request */ ++ ++#define DECORSR_JR0 0x00000001 /* Use JR0 as source */ ++#define DECORSR_VALID 0x80000000 /* DECORSR valid */ ++#define DECORR_RQD0ENABLE 0x00000001 /* Request DECO0 for direct use */ ++#define DECORR_DEN0 0x00010000 /* DECO0 available */ ++ ++/* ++ * DECO Register Offsets (relative to DECO0 base) ++ * ++ * DECO0 base = controller_base + DECO_BLOCK_NUMBER * page_size ++ * Page size: 4K (0x1000) or 64K (0x10000), read from CTPR_MS. ++ * DECO_BLOCK_NUMBER = 8, so DECO0 is at +0x8000 (4K) or +0x80000 (64K). ++ */ ++#define DECO_BLOCK_NUMBER 8 ++#define PG_SIZE_4K 0x1000 ++#define PG_SIZE_64K 0x10000 ++ ++#define DECO_JR_CTL_HI 0x0800 /* DECO Job Queue Control (upper) */ ++#define DECO_JR_CTL_LO 0x0804 /* DECO Job Queue Control (lower) */ ++#define DECO_OP_STATUS_HI 0x0810 /* DECO Operation Status (upper) */ ++#define DECO_DESCBUF(n) (0x0a00 + (n) * 4) /* Descriptor buffer */ ++#define DECO_DESC_DBG 0x0e04 /* DECO Debug Register */ ++ ++/* DECO JR Control bits */ ++#define DECO_JQCR_WHL 0x20000000 /* Whole descriptor (not link) */ ++#define DECO_JQCR_FOUR 0x10000000 /* Descriptor >= 4 words */ ++ ++/* DECO Operation Status bits */ ++#define DECO_OP_STATUS_HI_ERR_MASK 0xf00000ff ++ ++/* DECO Debug Register bits */ ++#define DESC_DBG_DECO_STAT_VALID 0x80000000 ++#define DESC_DBG_DECO_STAT_MASK 0x00f00000 ++#define DESC_DBG_DECO_STAT_SHIFT 20 ++#define DECO_STAT_HOST_ERR 0xd ++ ++/* ++ * Performance Monitor / Hardware Info Registers (base + 0x0f00 to 0x0fff) ++ * ++ * These are in the "perfmon" region at the end of each 4KB page ++ * (controller page and each JR page). ++ */ ++ ++/* CHA Revision Number */ ++#define CAAM_CRNR_MS 0x0fa0 ++#define CAAM_CRNR_LS 0x0fa4 ++ ++/* Compile Time Parameters */ ++#define CAAM_CTPR_MS 0x0fa8 ++#define CAAM_CTPR_LS 0x0fac ++ ++#define CTPR_MS_QI_MASK (1U << 25) /* QI present */ ++#define CTPR_MS_PS (1U << 17) /* Pointer size: 1=64-bit */ ++#define CTPR_MS_PG_SZ_MASK 0x00000010 /* Page size: 1=64K, 0=4K */ ++#define CTPR_MS_PG_SZ_SHIFT 4 ++#define CTPR_MS_DPAA2 (1U << 13) ++#define CTPR_MS_VIRT_EN_INCL 0x00000001 ++#define CTPR_MS_VIRT_EN_POR 0x00000002 ++ ++/* CAAM Status Register */ ++#define CAAM_CSTA 0x0fd4 ++#define CSTA_PLEND (1U << 10) /* Platform Little-Endian */ ++#define CSTA_ALT_PLEND (1U << 18) ++#define CSTA_MOO_MASK 0x00000300 ++#define CSTA_MOO_SHIFT 8 ++#define CSTA_MOO_SECURE 1 ++#define CSTA_MOO_TRUSTED 2 ++ ++/* CCB Version ID (contains ERA) */ ++#define CAAM_CCBVID 0x0fe4 ++#define CCBVID_ERA_MASK 0xff000000 ++#define CCBVID_ERA_SHIFT 24 ++ ++/* CHA Version ID */ ++#define CAAM_CHAVID_MS 0x0fe8 ++#define CAAM_CHAVID_LS 0x0fec ++ ++/* CHA Number */ ++#define CAAM_CHANUM_MS 0x0ff0 ++#define CAAM_CHANUM_LS 0x0ff4 ++ ++/* CAAM Version ID */ ++#define CAAM_CAAMVID_MS 0x0ff8 ++#define CAAM_CAAMVID_LS 0x0ffc ++ ++/* SEC Version ID fields */ ++#define SECVID_MS_IPID_MASK 0xffff0000 ++#define SECVID_MS_IPID_SHIFT 16 ++#define SECVID_MS_MAJ_REV_MASK 0x0000ff00 ++#define SECVID_MS_MAJ_REV_SHIFT 8 ++ ++/* ++ * RNG4 Test Registers (base + 0x0600) ++ */ ++#define CAAM_RTMCTL 0x0600 /* RNG Miscellaneous Control */ ++#define CAAM_RTSDCTL 0x0610 /* RNG Seed Control */ ++#define CAAM_RTFRQMIN 0x0618 /* RNG Frequency Count Min */ ++#define CAAM_RTFRQMAX 0x061c /* RNG Frequency Count Max */ ++#define CAAM_RTSCMISC 0x0604 /* RNG Statistical Check Misc */ ++#define CAAM_RTPKRRNG 0x0608 /* RNG Poker Range */ ++#define CAAM_RTPKRMAX 0x060c /* RNG Poker Max Limit */ ++#define CAAM_RTSCML 0x0620 /* RNG Statistical Check Monobit Limit */ ++#define CAAM_RTSCRL(n) (0x0624 + (n) * 4) /* Run Length Limit 0-5 */ ++#define CAAM_RDSTA 0x06c0 /* RNG DRNG Status */ ++ ++#define RTMCTL_ACC (1U << 5) /* TRNG access mode */ ++#define RTMCTL_PRGM (1U << 16) /* 1=program mode, 0=run mode */ ++#define RTMCTL_SAMP_MODE_RAW 1 ++ ++#define RTSDCTL_ENT_DLY_SHIFT 16 ++#define RTSDCTL_ENT_DLY_MASK (0xffff << RTSDCTL_ENT_DLY_SHIFT) ++#define RTSDCTL_ENT_DLY_MIN 3200 ++#define RTSDCTL_ENT_DLY_MAX 12800 ++#define RTSDCTL_SAMP_SIZE_MASK 0xffff ++#define RTSDCTL_SAMP_SIZE_VAL 512 ++ ++#define RTFRQMAX_DISABLE (1U << 20) ++ ++#define RDSTA_SKVN 0x40000000 /* Secure Key Valid Notification */ ++#define RDSTA_PR0 (1U << 4) ++#define RDSTA_PR1 (1U << 5) ++#define RDSTA_IF0 0x00000001 ++#define RDSTA_IF1 0x00000002 ++#define RDSTA_MASK (RDSTA_PR1 | RDSTA_PR0 | RDSTA_IF1 | RDSTA_IF0) ++ ++/* ++ * Job Ring Registers (relative to JR base, e.g. jr@10000) ++ * ++ * Each Job Ring occupies a 64KB region with registers at low offsets ++ * and a perfmon block at offset 0xf00. ++ * ++ * 64-bit registers: low 32 bits at offset+0, high 32 bits at offset+4 ++ * on LE platforms (non-iMX). Write to higher address triggers latch. ++ */ ++ ++/* Input Ring */ ++#define JR_IRBA 0x0000 /* Input Ring Base Address (64-bit) */ ++#define JR_IRSR 0x000c /* Input Ring Size */ ++#define JR_IRSAR 0x0014 /* Input Ring Slots Available */ ++#define JR_IRJAR 0x001c /* Input Ring Jobs Added */ ++ ++/* Output Ring */ ++#define JR_ORBA 0x0020 /* Output Ring Base Address (64-bit) */ ++#define JR_ORSR 0x002c /* Output Ring Size */ ++#define JR_ORJRR 0x0034 /* Output Ring Jobs Removed */ ++#define JR_ORSFR 0x003c /* Output Ring Slots Full (used) */ ++ ++/* Status / Configuration */ ++#define JR_JRSTAR 0x0044 /* JR Output Status */ ++#define JR_JRINTR 0x004c /* JR Interrupt Status */ ++#define JR_JRCFGR_MS 0x0050 /* JR Config (high 32) */ ++#define JR_JRCFGR_LS 0x0054 /* JR Config (low 32) */ ++ ++/* Indices */ ++#define JR_IRRIR 0x005c /* Input Ring Read Index */ ++#define JR_ORWIR 0x0064 /* Output Ring Write Index */ ++ ++/* Command / Control */ ++#define JR_JRCR 0x006c /* JR Command */ ++ ++/* JR Interrupt Status Register bits (JRINTR) */ ++#define JRINT_JR_INT 0x00000001 /* Job ring interrupt */ ++#define JRINT_JR_ERROR 0x00000002 /* Job ring error */ ++#define JRINT_ERR_HALT_MASK 0x0000000c ++#define JRINT_ERR_HALT_SHIFT 2 ++#define JRINT_ERR_HALT_INPROGRESS 0x00000004 ++#define JRINT_ERR_HALT_COMPLETE 0x00000008 ++#define JRINT_ERR_TYPE_MASK 0x00000f00 ++#define JRINT_ERR_TYPE_SHIFT 8 ++#define JRINT_ERR_INDEX_MASK 0x3fff0000 ++#define JRINT_ERR_INDEX_SHIFT 16 ++ ++/* JR Config Register LS bits (JRCFGR_LS) */ ++#define JRCFG_SOE 0x00000004 /* Stop on error */ ++#define JRCFG_ICEN 0x00000002 /* Interrupt coalescing enable */ ++#define JRCFG_IMSK 0x00000001 /* Interrupt mask */ ++#define JRCFG_ICDCT_SHIFT 8 /* Int coalescing descriptor count */ ++#define JRCFG_ICTT_SHIFT 16 /* Int coalescing timer threshold */ ++ ++/* JR Command Register bits (JRCR) */ ++#define JRCR_RESET 0x00000001 /* Reset job ring */ ++ ++/* ++ * Job Ring Output Status (JRSTAR) bits ++ */ ++#define JRSTA_SSRC_SHIFT 28 ++#define JRSTA_SSRC_MASK 0xf0000000 ++#define JRSTA_SSRC_NONE 0x00000000 ++#define JRSTA_SSRC_JUMP_HALT_CC 0x10000000 ++#define JRSTA_SSRC_CCB_ERROR 0x20000000 ++#define JRSTA_SSRC_JUMP_HALT_USER 0x30000000 ++#define JRSTA_SSRC_DECO 0x40000000 ++#define JRSTA_SSRC_JR 0x60000000 ++#define JRSTA_SSRC_QI 0x70000000 ++ ++#define JR_RINGSIZE_MASK 0x000003ff ++ ++/* ++ * QI (Queue Interface) Control Registers ++ * ++ * The QI block is at page QI_BLOCK_NUMBER within the CAAM address space. ++ * Page size is 4K or 64K depending on the CAAM compile-time parameters ++ * (CTPR_MS_PG_SZ). LS1046A uses 64K pages, so QI is at 7*0x10000=0x70000. ++ * ++ * Register offsets below are relative to the QI block base (sc_qi_off). ++ * Use sc->sc_qi_off + CAAM_QI_xxx to get the absolute offset. ++ */ ++#define QI_BLOCK_NUMBER 7 ++#define CAAM_QI_CONTROL_HI 0x00 /* QI Control (upper 32-bit, swap cfg) */ ++#define CAAM_QI_CONTROL_LO 0x04 /* QI Control (lower 32-bit) */ ++#define CAAM_QI_STATUS 0x0c /* QI Status */ ++ ++#define QICTL_DQEN 0x01 /* Enable dequeue (frame pop) */ ++#define QICTL_STOP 0x02 /* Stop QI */ ++#define QICTL_SOE 0x04 /* Stop on error */ ++ ++#define QISTA_PHRDERR 0x01 /* PreHeader Read Error */ ++#define QISTA_CFRDERR 0x02 /* Compound Frame Read Error */ ++#define QISTA_OFWRERR 0x04 /* Output Frame Write Error */ ++#define QISTA_BPDERR 0x08 /* Buffer Pool Depleted */ ++#define QISTA_BTSERR 0x10 /* Buffer Undersize */ ++#define QISTA_CFWRERR 0x20 /* Compound Frame Write Error */ ++#define QISTA_STOPD 0x80000000 /* QI Stopped */ ++ ++/* ++ * Performance Monitor Counters (controller perfmon block, 0x0f00-0x0f9f) ++ * ++ * 64-bit counters: high 32 bits at offset+0, low 32 bits at offset+4 (BE). ++ */ ++#define CAAM_PC_REQ_DEQ_HI 0x0f00 /* Dequeued Requests (high) */ ++#define CAAM_PC_REQ_DEQ_LO 0x0f04 /* Dequeued Requests (low) */ ++#define CAAM_PC_OB_ENC_REQ_HI 0x0f08 /* Outbound Encrypt Requests (high) */ ++#define CAAM_PC_OB_ENC_REQ_LO 0x0f0c /* Outbound Encrypt Requests (low) */ ++ ++/* ++ * Fault Address Registers (controller perfmon, 0x0fc0-0x0fcf) ++ */ ++#define CAAM_FAR_HI 0x0fc0 /* Fault Address (high) */ ++#define CAAM_FAR_LO 0x0fc4 /* Fault Address (low) */ ++#define CAAM_FALR 0x0fc8 /* Fault Address LIODN */ ++#define CAAM_FADR 0x0fcc /* Fault Address Detail */ ++ ++#endif /* _CAAM_REGS_H */ +diff --git a/sys/dev/caam/caam_rng.c b/sys/dev/caam/caam_rng.c +new file mode 100644 +index 00000000000..75fa00b52e4 +--- /dev/null ++++ b/sys/dev/caam/caam_rng.c +@@ -0,0 +1,302 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * CAAM hardware entropy source for FreeBSD's kernel random subsystem. ++ * ++ * Submits RNG descriptors to a Job Ring to generate random data from the ++ * CAAM RNG4 hardware block (TRNG + DRBG state handles). RNG state handles ++ * must be instantiated by the controller driver before this module is used. ++ * ++ * Registered as a RANDOM_PURE_CAAM source via random_source_register(). ++ * Called from the random kthread — uses a dedicated JR in polling mode. ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include ++ ++#include "caam.h" ++#include "caam_regs.h" ++#include "caam_desc.h" ++#include "caam_jr.h" ++#include "caam_crypto.h" ++#include "caam_rng.h" ++ ++/* Generate 32 bytes (256 bits) per CAAM RNG call */ ++#define CAAM_RNG_OUTSIZE 32 ++ ++/* ++ * Static RNG state — one instance for the whole system. ++ * Protected by rng_lock for synchronous read serialization. ++ */ ++static struct { ++ struct caam_jr_softc *jr; /* JR for descriptor submission */ ++ struct caam_dma_mem desc_mem; /* Pre-mapped descriptor buffer */ ++ struct caam_dma_mem out_mem; /* Pre-mapped RNG output buffer */ ++ struct mtx lock; /* Serializes rs_read calls */ ++ int done; /* Completion flag */ ++ uint32_t status; /* Completion status */ ++ int err_count; /* Consecutive error counter */ ++ bool failed; /* Persistent HW failure detected */ ++ bool registered; /* Source registered with random */ ++ sbintime_t last_gen; /* Timestamp of last generation */ ++} caam_rng; ++ ++static u_int caam_rng_read(void *buf, u_int c); ++ ++static const struct random_source caam_rng_source = { ++ .rs_ident = "CAAM TRNG", ++ .rs_source = RANDOM_PURE_CAAM, ++ .rs_read = caam_rng_read, ++}; ++ ++/* ++ * JR completion callback for RNG descriptor. ++ * ++ * Called inline from caam_jr_poll() → caam_jr_task() on the same ++ * thread that submitted the descriptor. No lock needed — the caller ++ * already holds caam_rng.lock and this is single-threaded. ++ */ ++static void ++caam_rng_done(uint32_t status, void *arg) ++{ ++ ++ caam_rng.status = status; ++ caam_rng.done = 1; ++} ++ ++/* ++ * Build and submit an RNG descriptor, wait for completion. ++ * Returns the number of random bytes stored at out_mem.vaddr. ++ * ++ * Descriptor: ++ * [0] HDR: 5 words, one-shot ++ * [1] OPERATION: Class 1 ALG, RNG, prediction resistance ++ * [2] FIFO STORE: RNGSTORE type, CAAM_RNG_OUTSIZE bytes ++ * [3] PTR high: output DMA address (upper 32) ++ * [4] PTR low: output DMA address (lower 32) ++ * ++ * Caller must hold caam_rng.lock. ++ */ ++static int ++caam_rng_generate(void) ++{ ++ uint32_t *desc; ++ bus_addr_t out_pa; ++ int error; ++ ++ desc = caam_rng.desc_mem.vaddr; ++ 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 | ++ CAAM_RNG_OUTSIZE); ++ desc[3] = cpu_to_caam32((uint32_t)(out_pa >> 32)); ++ desc[4] = cpu_to_caam32((uint32_t)out_pa); ++ ++ caam_rng.done = 0; ++ caam_rng.status = 0; ++ ++ error = caam_jr_enqueue(caam_rng.jr, desc, caam_rng.desc_mem.paddr, ++ 5 * sizeof(uint32_t), caam_rng_done, NULL); ++ if (error != 0) ++ return (0); ++ ++ /* ++ * Poll for completion inline. The dedicated RNG JR has IRQs ++ * masked, so we drain the output ring directly. Hardware ++ * completes in ~microseconds; 100ms timeout is generous. ++ */ ++ { ++ int timeout; ++ ++ for (timeout = 100000; timeout > 0; timeout--) { ++ caam_jr_poll(caam_rng.jr); ++ if (caam_rng.done) ++ break; ++ DELAY(1); ++ } ++ if (!caam_rng.done) { ++ printf("caam_rng: polling timeout\n"); ++ return (0); ++ } ++ } ++ ++ /* Check status */ ++ if (caam_rng.status != 0) { ++ uint32_t ssrc = caam_rng.status & JRSTA_SSRC_MASK; ++ if (ssrc == JRSTA_SSRC_CCB_ERROR || ++ ssrc == JRSTA_SSRC_DECO || ++ ssrc == JRSTA_SSRC_JR) { ++ if (++caam_rng.err_count >= 100) { ++ printf("caam_rng: %d consecutive errors, " ++ "disabling entropy source\n", ++ caam_rng.err_count); ++ caam_rng.failed = true; ++ } else if (caam_rng.err_count <= 5) { ++ printf("caam_rng: RNG error 0x%08x\n", ++ caam_rng.status); ++ } else if (caam_rng.err_count == 6) { ++ printf("caam_rng: further errors suppressed\n"); ++ } ++ return (0); ++ } ++ } ++ ++ caam_rng.err_count = 0; ++ return (CAAM_RNG_OUTSIZE); ++} ++ ++/* ++ * random_source rs_read callback. ++ * ++ * Called from the random kthread to harvest entropy. When Fortuna is ++ * unseeded, the kthread calls us 256 times per iteration (~100ms). ++ * Each CAAM TRNG call with prediction resistance takes ~100-150us, ++ * so without throttling we'd burn ~35% of one core. ++ * ++ * Rate-limit to at most once per 10ms (100 Hz). This caps CPU at ++ * ~1.5% during the initial health-test phase (1024 samples, ~10s) ++ * and drops to <0.2% once Fortuna is seeded (4 calls/iteration). ++ */ ++static u_int ++caam_rng_read(void *buf, u_int c) ++{ ++ sbintime_t now; ++ int got; ++ ++ if (caam_rng.failed) ++ return (0); ++ ++ if (c > CAAM_RNG_OUTSIZE) ++ c = CAAM_RNG_OUTSIZE; ++ ++ /* Throttle: skip if called within 10ms of last generation */ ++ now = getsbinuptime(); ++ if (now - caam_rng.last_gen < SBT_1MS * 10) ++ return (0); ++ ++ mtx_lock(&caam_rng.lock); ++ got = caam_rng_generate(); ++ if (got == 0) { ++ mtx_unlock(&caam_rng.lock); ++ return (0); ++ } ++ if (got > (int)c) ++ got = c; ++ memcpy(buf, caam_rng.out_mem.vaddr, got); ++ mtx_unlock(&caam_rng.lock); ++ ++ caam_rng.last_gen = now; ++ ++ return (got); ++} ++ ++/* ++ * Initialize and register the CAAM RNG entropy source. ++ * Called from the first JR attach. ++ */ ++int ++caam_rng_init(struct caam_jr_softc *jr) ++{ ++ struct caam_softc *ctrl; ++ device_t parent; ++ int error; ++ ++ parent = device_get_parent(jr->sc_dev); ++ ctrl = device_get_softc(parent); ++ ++ /* Only register once, even with multiple JRs */ ++ if (ctrl->sc_rng_registered) ++ return (0); ++ ++ /* RNG state handles must be instantiated first */ ++ if (!ctrl->sc_rng_inited) { ++ device_printf(jr->sc_dev, ++ "RNG: skipping entropy source - state handles not ready\n"); ++ return (ENXIO); ++ } ++ ++ mtx_init(&caam_rng.lock, "caam_rng", NULL, MTX_DEF); ++ ++ /* Pre-allocate DMA memory for descriptor (64 bytes) */ ++ error = caam_dma_alloc(jr->sc_dev, &caam_rng.desc_mem, 64); ++ if (error != 0) { ++ device_printf(jr->sc_dev, ++ "RNG: cannot allocate descriptor DMA\n"); ++ goto fail; ++ } ++ ++ /* Pre-allocate DMA memory for output (32 bytes) */ ++ error = caam_dma_alloc(jr->sc_dev, &caam_rng.out_mem, ++ CAAM_RNG_OUTSIZE); ++ if (error != 0) { ++ device_printf(jr->sc_dev, ++ "RNG: cannot allocate output DMA\n"); ++ goto fail; ++ } ++ ++ caam_rng.jr = jr; ++ caam_rng.registered = true; ++ ctrl->sc_rng_registered = true; ++ ++ /* ++ * Dedicate this JR to RNG: mask IRQs permanently and switch ++ * to polling mode. The output ring is drained inline by ++ * caam_jr_poll() from caam_rng_generate(), eliminating any ++ * dependency on taskqueue scheduling under heavy load. ++ */ ++ JR_WRITE(jr, JR_JRCFGR_LS, ++ JR_READ(jr, JR_JRCFGR_LS) | JRCFG_IMSK); ++ jr->sc_polling = true; ++ ++ random_source_register(&caam_rng_source); ++ device_printf(jr->sc_dev, ++ "registered CAAM TRNG entropy source (polling mode)\n"); ++ ++ return (0); ++ ++fail: ++ caam_dma_free(&caam_rng.out_mem); ++ caam_dma_free(&caam_rng.desc_mem); ++ mtx_destroy(&caam_rng.lock); ++ return (error); ++} ++ ++/* ++ * Deregister and clean up the RNG entropy source. ++ */ ++void ++caam_rng_detach(struct caam_jr_softc *jr) ++{ ++ ++ if (!caam_rng.registered || caam_rng.jr != jr) ++ return; ++ ++ random_source_deregister(&caam_rng_source); ++ ++ mtx_lock(&caam_rng.lock); ++ caam_rng.jr = NULL; ++ caam_rng.registered = false; ++ mtx_unlock(&caam_rng.lock); ++ ++ caam_dma_free(&caam_rng.out_mem); ++ caam_dma_free(&caam_rng.desc_mem); ++ mtx_destroy(&caam_rng.lock); ++} +diff --git a/sys/dev/caam/caam_rng.h b/sys/dev/caam/caam_rng.h +new file mode 100644 +index 00000000000..fd7e50a210a +--- /dev/null ++++ b/sys/dev/caam/caam_rng.h +@@ -0,0 +1,17 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * CAAM hardware entropy source — interface. ++ */ ++ ++#ifndef _CAAM_RNG_H ++#define _CAAM_RNG_H ++ ++#include "caam_jr.h" ++ ++int caam_rng_init(struct caam_jr_softc *jr); ++void caam_rng_detach(struct caam_jr_softc *jr); ++ ++#endif /* _CAAM_RNG_H */ +diff --git a/sys/dev/dpaa/bman.c b/sys/dev/dpaa/bman.c +index 0dbcecb5d7a..3d098a4e3d5 100644 +--- a/sys/dev/dpaa/bman.c ++++ b/sys/dev/dpaa/bman.c +@@ -36,12 +36,25 @@ + #include + #include + #include ++#include ++#include + ++#include ++#ifdef __powerpc__ + #include ++#endif ++ ++#ifdef __aarch64__ ++#include ++#include ++#endif + + #include "bman.h" + ++#define FBPR_ENTRY_SIZE 64 /* matches NCSW bm.h */ ++ + static struct bman_softc *bman_sc; ++static t_Handle bman_pool_by_bpid[BM_MAX_NUM_OF_POOLS]; + + extern t_Handle bman_portal_setup(struct bman_softc *bsc); + +@@ -74,6 +87,7 @@ bman_exception(t_Handle h_App, e_BmExceptions exception) + device_printf(sc->sc_dev, "BMAN Exception: %s.\n", message); + } + ++ + int + bman_attach(device_t dev) + { +@@ -114,12 +128,47 @@ bman_attach(device_t dev) + bp.partBpidBase = 0; + bp.partNumOfPools = BM_MAX_NUM_OF_POOLS; + ++#ifdef __aarch64__ ++ /* ++ * Parse DT memory-region phandle for FBPR, matching Linux. ++ * DT: memory-region = <&bman_fbpr>; ++ * bman-fbpr: size=0x1000000 (16MB) ++ */ ++ { ++ extern void *qbman_alloc_reserved_mem(device_t, phandle_t, ++ uint32_t *, const char *); ++ phandle_t node, mem_node; ++ pcell_t mem_handle; ++ ++ node = ofw_bus_get_node(dev); ++ if (node > 0 && OF_getencprop(node, "memory-region", ++ (void *)&mem_handle, sizeof(mem_handle)) == ++ sizeof(mem_handle)) { ++ mem_node = OF_node_from_xref(mem_handle); ++ if (mem_node > 0) { ++ bp.p_FbprBase = ++ qbman_alloc_reserved_mem(dev, ++ mem_node, &bp.fbprSize, "FBPR"); ++ if (bp.p_FbprBase != NULL) ++ bp.totalNumOfBuffers = ++ bp.fbprSize / FBPR_ENTRY_SIZE * 8; ++ } ++ } else { ++ device_printf(dev, ++ "no memory-region property, using defaults\n"); ++ } ++ } ++#endif ++ ++ device_printf(dev, "CCSR va=%#lx totalBufs=%u\n", ++ (unsigned long)bp.baseAddress, bp.totalNumOfBuffers); ++ + sc->sc_bh = BM_Config(&bp); + if (sc->sc_bh == NULL) + goto err; + +- /* Warn if there is less than 5% free FPBR's in pool */ +- error = BM_ConfigFbprThreshold(sc->sc_bh, (BMAN_MAX_BUFFERS / 8) / 20); ++ /* Warn if there is less than 5% free FBPR's in pool */ ++ error = BM_ConfigFbprThreshold(sc->sc_bh, (bp.totalNumOfBuffers / 8) / 20); + if (error != E_OK) + goto err; + +@@ -134,6 +183,18 @@ bman_attach(device_t dev) + device_printf(dev, "Hardware version: %d.%d.\n", + rev.majorRev, rev.minorRev); + ++#ifdef __aarch64__ ++ /* ++ * Initialize BMan portals for all CPUs from boot CPU. ++ * ARM64: pmap_mapdev creates global kernel VA, no sched_bind needed. ++ */ ++ for (int cpu = 0; cpu < mp_ncpus; cpu++) { ++ if (bman_portal_init_cpu(sc, cpu) == NULL) ++ device_printf(dev, ++ "could not setup BMan portal on CPU %d\n", cpu); ++ } ++#endif ++ + return (0); + + err: +@@ -255,6 +316,7 @@ bman_pool_create(uint8_t *bpid, uint16_t bufferSize, uint16_t maxBuffers, + + *bpid = BM_POOL_GetId(pool); + sc->sc_bpool_cpu[*bpid] = PCPU_GET(cpuid); ++ bman_pool_by_bpid[*bpid] = pool; + + sched_unpin(); + +@@ -275,6 +337,7 @@ bman_pool_destroy(t_Handle pool) + struct bman_softc *sc; + + sc = bman_sc; ++ bman_pool_by_bpid[BM_POOL_GetId(pool)] = NULL; + thread_lock(curthread); + sched_bind(curthread, sc->sc_bpool_cpu[BM_POOL_GetId(pool)]); + thread_unlock(curthread); +@@ -363,3 +426,12 @@ bman_count(t_Handle pool) + + return (BM_POOL_GetCounter(pool, e_BM_POOL_COUNTERS_CONTENT)); + } ++ ++t_Handle ++bman_pool_for_bpid(uint8_t bpid) ++{ ++ ++ if (bpid >= BM_MAX_NUM_OF_POOLS) ++ return (NULL); ++ return (bman_pool_by_bpid[bpid]); ++} +diff --git a/sys/dev/dpaa/bman.h b/sys/dev/dpaa/bman.h +index 01c09489890..36ecd2590c4 100644 +--- a/sys/dev/dpaa/bman.h ++++ b/sys/dev/dpaa/bman.h +@@ -35,8 +35,8 @@ + * BMAN Configuration + */ + +-/* Maximum number of buffers in all BMAN pools */ +-#define BMAN_MAX_BUFFERS 4096 ++/* Maximum number of buffers in all BMAN pools (FBPR ring entries) */ ++#define BMAN_MAX_BUFFERS 65536 + + /* + * Portal definitions +@@ -189,6 +189,7 @@ int bman_put_buffer(t_Handle pool, void *buffer); + * @returns Number of free buffers in pool. + */ + uint32_t bman_count(t_Handle pool); ++t_Handle bman_pool_for_bpid(uint8_t bpid); + + /* + * Bus i/f +@@ -199,4 +200,8 @@ int bman_suspend(device_t dev); + int bman_resume(device_t dev); + int bman_shutdown(device_t dev); + ++#ifdef __aarch64__ ++t_Handle bman_portal_init_cpu(struct bman_softc *, int); ++#endif ++ + #endif /* BMAN_H */ +diff --git a/sys/dev/dpaa/bman_fdt.c b/sys/dev/dpaa/bman_fdt.c +index 2ff695bf7d8..44535e18f1f 100644 +--- a/sys/dev/dpaa/bman_fdt.c ++++ b/sys/dev/dpaa/bman_fdt.c +@@ -34,6 +34,8 @@ + #include + + #include ++#include ++#include + + #include + #include +@@ -103,7 +105,10 @@ static driver_t bm_portals_driver = { + }; + + EARLY_DRIVER_MODULE(bman_portals, ofwbus, bm_portals_driver, 0, 0, +- BUS_PASS_BUS); ++ BUS_PASS_INTERRUPT + BUS_PASS_ORDER_LAST); ++/* On ARM64, portal bus nodes are children of soc (simplebus), not ofwbus */ ++EARLY_DRIVER_MODULE(bman_portals, simplebus, bm_portals_driver, 0, 0, ++ BUS_PASS_INTERRUPT + BUS_PASS_ORDER_LAST); + + static void + get_addr_props(phandle_t node, uint32_t *addrp, uint32_t *sizep) +@@ -147,7 +152,7 @@ bman_portal_find_cpu(int cpu) + return (node); + + for (node = OF_child(node); node != 0; node = OF_peer(node)) { +- if (OF_getprop(node, "reg", ®, sizeof(reg)) <= 0) ++ if (OF_getencprop(node, "reg", ®, sizeof(reg)) <= 0) + continue; + if (reg == cpu) + return (node); +@@ -184,14 +189,16 @@ bman_portals_fdt_attach(device_t dev) + continue; + } + /* Checkout related cpu */ +- if (OF_getprop(child, "cpu-handle", (void *)&cpu, ++ if (OF_getencprop(child, "cpu-handle", (void *)&cpu, + sizeof(cpu)) <= 0) { +- cpu = bman_portal_find_cpu(cpus); +- if (cpu <= 0) ++ /* No cpu-handle (ARM64): find CPU node directly */ ++ cpu_node = bman_portal_find_cpu(cpus); ++ if (cpu_node <= 0) + continue; ++ } else { ++ /* cpu-handle is an ihandle (PowerPC) */ ++ cpu_node = OF_instance_to_package(cpu); + } +- /* Acquire cpu number */ +- cpu_node = OF_instance_to_package(cpu); + if (OF_getencprop(cpu_node, "reg", &cpu_num, sizeof(cpu_num)) <= 0) { + device_printf(dev, "Could not retrieve CPU number.\n"); + return (ENXIO); +diff --git a/sys/dev/dpaa/bman_portals.c b/sys/dev/dpaa/bman_portals.c +index 89bcbf64ce5..47f1d13f04c 100644 +--- a/sys/dev/dpaa/bman_portals.c ++++ b/sys/dev/dpaa/bman_portals.c +@@ -38,13 +38,16 @@ + #include + + #include ++#include ++#include ++#ifdef __powerpc__ + #include ++#include ++#endif + + #include + #include + +-#include +- + #include "bman.h" + #include "portals.h" + +@@ -55,15 +58,16 @@ struct dpaa_portals_softc *bp_sc; + int + bman_portals_attach(device_t dev) + { +- struct dpaa_portals_softc *sc; ++ bp_sc = device_get_softc(dev); + +- sc = bp_sc = device_get_softc(dev); +- +- /* Map bman portal to physical address space */ ++#ifdef __powerpc__ ++ struct dpaa_portals_softc *sc = bp_sc; ++ /* Map bman portal to physical address space (PowerPC LAW) */ + if (law_enable(OCP85XX_TGTIF_BMAN, sc->sc_dp_pa, sc->sc_dp_size)) { + bman_portals_detach(dev); + return (ENXIO); + } ++#endif + /* Set portal properties for XX_VirtToPhys() */ + XX_PortalSetInfo(dev); + +@@ -146,8 +150,8 @@ bman_portal_setup(struct bman_softc *bsc) + dpaa_portal_map_registers(sc); + + /* Configure and initialize portal */ +- bpp.ceBaseAddress = rman_get_bushandle(sc->sc_rres[0]); +- bpp.ciBaseAddress = rman_get_bushandle(sc->sc_rres[1]); ++ bpp.ceBaseAddress = sc->sc_dp[cpu].dp_ce_va; ++ bpp.ciBaseAddress = sc->sc_dp[cpu].dp_ci_va; + bpp.h_Bm = bsc->sc_bh; + bpp.swPortalId = cpu; + bpp.irq = (uintptr_t)sc->sc_dp[cpu].dp_ires; +@@ -174,3 +178,54 @@ bman_portal_setup(struct bman_softc *bsc) + + return (NULL); + } ++ ++#ifdef __aarch64__ ++/* ++ * Initialize a BMan portal for a specific CPU from any CPU context. ++ * Unlike bman_portal_setup() which uses PCPU_GET(cpuid), this takes ++ * an explicit CPU parameter. On ARM64, pmap_mapdev creates global ++ * kernel VA, so no sched_bind/migration is needed. ++ * ++ * BMan has no SDEST configuration (confirmed from Linux reference). ++ */ ++t_Handle ++bman_portal_init_cpu(struct bman_softc *bsc, int cpu) ++{ ++ struct dpaa_portals_softc *sc; ++ t_BmPortalParam bpp; ++ t_Handle portal; ++ ++ if (bp_sc == NULL) ++ return (NULL); ++ sc = bp_sc; ++ ++ /* Skip if already initialized */ ++ if (sc->sc_dp[cpu].dp_ph != NULL) ++ return (sc->sc_dp[cpu].dp_ph); ++ ++ /* Map CE/CI registers (global kernel VA, accessible from any CPU) */ ++ dpaa_portal_map_registers_cpu(sc, cpu); ++ ++ if (sc->sc_dp[cpu].dp_ce_va == 0 || sc->sc_dp[cpu].dp_ci_va == 0) ++ return (NULL); ++ ++ memset(&bpp, 0, sizeof(bpp)); ++ bpp.ceBaseAddress = sc->sc_dp[cpu].dp_ce_va; ++ bpp.ciBaseAddress = sc->sc_dp[cpu].dp_ci_va; ++ bpp.h_Bm = bsc->sc_bh; ++ bpp.swPortalId = cpu; ++ bpp.irq = (uintptr_t)sc->sc_dp[cpu].dp_ires; ++ ++ portal = BM_PORTAL_Config(&bpp); ++ if (portal == NULL) ++ return (NULL); ++ ++ if (BM_PORTAL_Init(portal) != E_OK) { ++ BM_PORTAL_Free(portal); ++ return (NULL); ++ } ++ ++ sc->sc_dp[cpu].dp_ph = portal; ++ return (portal); ++} ++#endif +diff --git a/sys/dev/dpaa/dpaa_oh.c b/sys/dev/dpaa/dpaa_oh.c +new file mode 100644 +index 00000000000..e5014d45228 +--- /dev/null ++++ b/sys/dev/dpaa/dpaa_oh.c +@@ -0,0 +1,566 @@ ++/*- ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * All rights reserved. ++ * ++ * 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 AUTHOR 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 AUTHOR 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. ++ */ ++ ++/* ++ * DPAA1 Offline / Header Manipulation port driver. ++ * ++ * OH ports are FMan port instances without a MAC. Software enqueues frames ++ * via QMan, FMan processes them (parse, classify, manipulate), and the ++ * results come back via QMan. They serve as "on-ramps" to inject ++ * software-originated traffic (WiFi, IPsec) into the FMan pipeline. ++ * ++ * Each OH port probes a "fsl,fman-v3-port-oh" device tree node (child of ++ * the fman bus) and creates: ++ * - An FMan offline-parsing port (FM_PORT) ++ * - A default egress FQR (frames out of OH port after processing) ++ * - An error FQR (frames that hit errors during processing) ++ * - An ingress FQR (software enqueues here → FMan OH port dequeues) ++ * ++ * Consumers (CDX, WiFi, IPsec) use the public API in dpaa_oh.h to: ++ * - Get the FM_PORT handle for PCD attachment ++ * - Enqueue frames for offline processing ++ * - Register callbacks for processed frames ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include ++#include ++ ++#include "opt_dpaa.h" ++ ++#include ++#include ++#include ++#include ++ ++#include "fman.h" ++#include "fman_chardev.h" ++#include "qman.h" ++#include "dpaa_oh.h" ++ ++ ++/** ++ * @group OH port private defines. ++ * @{ ++ */ ++ ++/* Frame queue parameters — same WQ as dtsec RX/TX */ ++#define DPAA_OH_FQR_DFLT_WQ 1 ++#define DPAA_OH_FQR_ERR_WQ 1 ++#define DPAA_OH_FQR_TX_WQ 1 ++ ++/* Pool channel for egress FQs (frames back to software) */ ++#define DPAA_OH_FQR_DFLT_CHANNEL e_QM_FQ_CHANNEL_POOL1 ++#define DPAA_OH_FQR_ERR_CHANNEL e_QM_FQ_CHANNEL_POOL1 ++ ++/* LIODN base (same as dtsec) */ ++#define DPAA_OH_LIODN_BASE 0 ++ ++/* ++ * FreeBSD's upstream DTS (qoriq-fman3-0.dtsi) uses hardware port IDs as ++ * cell-index for OH ports: port@82000 has cell-index 2, port@83000 has ++ * cell-index 3, etc. NCSW FM_PORT_Config expects a 0-based relative port ++ * ID and adds BASE_OH_PORTID internally via SwPortIdToHwPortId(). ++ * ++ * The NXP Linux SDK DTS uses 0-based cell-indices (0, 1, 2, ...) instead, ++ * so the Linux wrapper passes cell-index directly without adjustment. ++ * ++ * We subtract the first OH port cell-index to convert from FreeBSD DTS ++ * convention to the 0-based relative ID that NCSW expects. ++ */ ++#define DPAA_OH_CELL_INDEX_BASE 2 ++ ++struct dpaa_oh_softc { ++ device_t sc_dev; ++ int sc_port_id; /* cell-index from DT (2-7) */ ++ uint32_t sc_port_hw_id; /* reg from DT (0x82000, etc.) */ ++ uint32_t sc_qman_chan; /* QMan channel for this port */ ++ ++ /* FMan handles (from fman parent) */ ++ vm_offset_t sc_fm_base; ++ t_Handle sc_fmh; ++ t_Handle sc_pcdh; ++ t_Handle sc_netenvh; ++ ++ /* FMan OH port */ ++ t_Handle sc_portph; /* FM_PORT handle */ ++ uint32_t sc_data_offset; /* buffer data offset (prefix size) */ ++ ++ /* Frame queues */ ++ t_Handle sc_dflt_fqr; /* default egress FQR */ ++ uint32_t sc_dflt_fqid; ++ t_Handle sc_err_fqr; /* error FQR */ ++ uint32_t sc_err_fqid; ++ t_Handle sc_tx_fqr; /* ingress FQR (software → OH) */ ++}; ++/** @} */ ++ ++ ++/** ++ * @group FQR callbacks. ++ * @{ ++ */ ++ ++static void ++dpaa_oh_exception_callback(t_Handle app, e_FmPortExceptions exception) ++{ ++ struct dpaa_oh_softc *sc; ++ ++ sc = app; ++ device_printf(sc->sc_dev, "FMan port exception %d\n", exception); ++} ++ ++static e_RxStoreResponse ++dpaa_oh_dflt_cb(t_Handle app, t_Handle fqr, t_Handle portal, ++ uint32_t fqid_off, t_DpaaFD *frame) ++{ ++ struct dpaa_oh_softc *sc; ++ void *buf; ++ ++ sc = app; ++ ++ /* ++ * Default FQ callback — frames that PCD didn't classify. ++ * For now, just drop and return the buffer. ++ * Consumers can override this via dpaa_oh_register_cb(). ++ */ ++ buf = DPAA_FD_GET_ADDR(frame); ++ if (buf != NULL) { ++ /* ++ * We don't own a buffer pool — the buffer was allocated ++ * by whoever enqueued the frame. We can't return it to ++ * BMan without knowing which pool it came from. The ++ * consumer's callback is responsible for buffer lifecycle. ++ * If no consumer is registered, we leak. This is a ++ * configuration error — OH ports should always have a ++ * consumer or PCD attached. ++ */ ++ if (bootverbose) ++ device_printf(sc->sc_dev, ++ "default FQ: unhandled frame (no consumer)\n"); ++ } ++ ++ return (e_RX_STORE_RESPONSE_CONTINUE); ++} ++ ++static e_RxStoreResponse ++dpaa_oh_err_cb(t_Handle app, t_Handle fqr, t_Handle portal, ++ uint32_t fqid_off, t_DpaaFD *frame) ++{ ++ struct dpaa_oh_softc *sc; ++ ++ sc = app; ++ device_printf(sc->sc_dev, "error frame: status 0x%08x\n", ++ DPAA_FD_GET_STATUS(frame)); ++ ++ return (e_RX_STORE_RESPONSE_CONTINUE); ++} ++/** @} */ ++ ++ ++/** ++ * @group Driver probe/attach/detach. ++ * @{ ++ */ ++ ++static int ++dpaa_oh_probe(device_t dev) ++{ ++ ++ if (!ofw_bus_status_okay(dev)) ++ return (ENXIO); ++ ++ if (!ofw_bus_is_compatible(dev, "fsl,fman-v3-port-oh")) ++ return (ENXIO); ++ ++ device_set_desc(dev, "Freescale FMan Offline Parsing Port"); ++ ++ return (BUS_PROBE_DEFAULT); ++} ++ ++static int ++dpaa_oh_attach(device_t dev) ++{ ++ struct dpaa_oh_softc *sc; ++ device_t parent; ++ t_FmPortParams params; ++ t_FmPortNonRxParams *oh_params; ++ t_FmBufferPrefixContent prefix; ++ t_Error error; ++ phandle_t node; ++ pcell_t cell_index; ++ pcell_t port_reg; ++ t_Handle fqr; ++ ++ sc = device_get_softc(dev); ++ sc->sc_dev = dev; ++ parent = device_get_parent(dev); ++ node = ofw_bus_get_node(dev); ++ ++ /* Read cell-index — the hardware port ID for OH ports (2-7) */ ++ if (OF_getencprop(node, "cell-index", &cell_index, ++ sizeof(cell_index)) <= 0) { ++ device_printf(dev, "missing cell-index property\n"); ++ return (ENXIO); ++ } ++ sc->sc_port_id = cell_index; ++ ++ /* Read reg — hardware register offset within FMan */ ++ if (OF_getencprop(node, "reg", &port_reg, sizeof(port_reg)) <= 0) { ++ device_printf(dev, "missing reg property\n"); ++ return (ENXIO); ++ } ++ sc->sc_port_hw_id = port_reg; ++ ++ /* Get FMan handles from parent */ ++ if (fman_get_handle(parent, &sc->sc_fmh) != 0 || ++ sc->sc_fmh == NULL) { ++ device_printf(dev, "couldn't get FMan handle\n"); ++ return (ENXIO); ++ } ++ ++ if (fman_get_bushandle(parent, &sc->sc_fm_base) != 0) { ++ device_printf(dev, "couldn't get FMan base address\n"); ++ return (ENXIO); ++ } ++ ++ fman_get_pcd_handle(parent, &sc->sc_pcdh); ++ fman_get_netenv_handle(parent, &sc->sc_netenvh); ++ ++ /* Get QMan channel for this OH port */ ++ sc->sc_qman_chan = fman_qman_channel_id(parent, sc->sc_port_id); ++ if (sc->sc_qman_chan == 0) { ++ device_printf(dev, ++ "couldn't get QMan channel for port %d\n", ++ sc->sc_port_id); ++ return (ENXIO); ++ } ++ ++ /* ++ * Create frame queues. ++ */ ++ ++ /* Default egress FQR — processed frames come here */ ++ fqr = qman_fqr_create(1, DPAA_OH_FQR_DFLT_CHANNEL, ++ DPAA_OH_FQR_DFLT_WQ, false, 0, false, false, true, false, ++ 0, 0, 0); ++ if (fqr == NULL) { ++ device_printf(dev, "couldn't create default FQR\n"); ++ return (EIO); ++ } ++ sc->sc_dflt_fqr = fqr; ++ sc->sc_dflt_fqid = qman_fqr_get_base_fqid(fqr); ++ ++ error = qman_fqr_register_cb(fqr, dpaa_oh_dflt_cb, sc); ++ if (error != E_OK) { ++ device_printf(dev, "couldn't register default FQ callback\n"); ++ goto fail_dflt; ++ } ++ ++ /* Error FQR */ ++ fqr = qman_fqr_create(1, DPAA_OH_FQR_ERR_CHANNEL, ++ DPAA_OH_FQR_ERR_WQ, false, 0, false, false, true, false, ++ 0, 0, 0); ++ if (fqr == NULL) { ++ device_printf(dev, "couldn't create error FQR\n"); ++ goto fail_dflt; ++ } ++ sc->sc_err_fqr = fqr; ++ sc->sc_err_fqid = qman_fqr_get_base_fqid(fqr); ++ ++ error = qman_fqr_register_cb(fqr, dpaa_oh_err_cb, sc); ++ if (error != E_OK) { ++ device_printf(dev, "couldn't register error FQ callback\n"); ++ goto fail_err; ++ } ++ ++ /* Ingress FQR — software enqueues here, FMan OH port dequeues */ ++ fqr = qman_fqr_create(1, sc->sc_qman_chan, ++ DPAA_OH_FQR_TX_WQ, false, 0, false, false, true, false, ++ 0, 0, 0); ++ if (fqr == NULL) { ++ device_printf(dev, "couldn't create ingress FQR\n"); ++ goto fail_err; ++ } ++ sc->sc_tx_fqr = fqr; ++ ++ /* ++ * Configure FMan OH port. ++ * ++ * OH ports use nonRxParams (like TX ports) because they receive ++ * frames from QMan (not from a MAC). But they also need dfltFqid ++ * (like RX ports) for the egress path. ++ */ ++ memset(¶ms, 0, sizeof(params)); ++ params.baseAddr = sc->sc_fm_base + sc->sc_port_hw_id; ++ params.h_Fm = sc->sc_fmh; ++ params.portType = e_FM_PORT_TYPE_OH_OFFLINE_PARSING; ++ params.portId = sc->sc_port_id - DPAA_OH_CELL_INDEX_BASE; ++ params.independentModeEnable = false; ++ params.liodnBase = DPAA_OH_LIODN_BASE; ++ params.f_Exception = dpaa_oh_exception_callback; ++ params.h_App = sc; ++ ++ oh_params = ¶ms.specificParams.nonRxParams; ++ oh_params->errFqid = sc->sc_err_fqid; ++ oh_params->dfltFqid = sc->sc_dflt_fqid; ++ oh_params->qmChannel = sc->sc_qman_chan; ++#ifdef FM_OP_PARTITION_ERRATA_FMANx8 ++ oh_params->opLiodnOffset = 0; ++#endif ++ ++ sc->sc_portph = FM_PORT_Config(¶ms); ++ if (sc->sc_portph == NULL) { ++ device_printf(dev, "couldn't configure FM OH port\n"); ++ goto fail_tx; ++ } ++ ++ /* ++ * Configure buffer prefix: parse result + hash result. ++ * This enables PCD (parser writes results into prefix) and ++ * allows consumers to read parse results for classification. ++ * ++ * manipExtraSpace = 96 matches the Linux SDK DTS ++ * buffer-layout = <0x60 0x40> for OH port extended-args. ++ */ ++ memset(&prefix, 0, sizeof(prefix)); ++ prefix.privDataSize = 16; ++ prefix.passPrsResult = TRUE; ++ prefix.passHashResult = TRUE; ++ prefix.dataAlign = 64; ++ prefix.manipExtraSpace = 96; ++ ++ error = FM_PORT_ConfigBufferPrefixContent(sc->sc_portph, &prefix); ++ if (error != E_OK) { ++ device_printf(dev, "couldn't configure buffer prefix\n"); ++ goto fail_port; ++ } ++ ++ error = FM_PORT_Init(sc->sc_portph); ++ if (error != E_OK) { ++ device_printf(dev, "couldn't initialize FM OH port: %d\n", ++ error); ++ goto fail_port; ++ } ++ ++ sc->sc_data_offset = FM_PORT_GetBufferDataOffset(sc->sc_portph); ++ ++ /* Register OH port with FMD chardev for userspace PCD control */ ++ { ++ struct fmcd_softc *fmcd; ++ ++ fmcd = fman_get_fmcd(device_get_parent(dev)); ++ if (fmcd != NULL) ++ fmcd_register_oh_port(fmcd, ++ sc->sc_port_id - DPAA_OH_CELL_INDEX_BASE, ++ sc->sc_portph); ++ } ++ ++ device_printf(dev, ++ "OH port %d: QMan chan 0x%x, dflt FQID %u, err FQID %u, " ++ "data offset %u\n", ++ sc->sc_port_id, sc->sc_qman_chan, sc->sc_dflt_fqid, ++ sc->sc_err_fqid, sc->sc_data_offset); ++ ++ return (0); ++ ++fail_port: ++ FM_PORT_Free(sc->sc_portph); ++ sc->sc_portph = NULL; ++fail_tx: ++ qman_fqr_free(sc->sc_tx_fqr); ++ sc->sc_tx_fqr = NULL; ++fail_err: ++ qman_fqr_free(sc->sc_err_fqr); ++ sc->sc_err_fqr = NULL; ++fail_dflt: ++ qman_fqr_free(sc->sc_dflt_fqr); ++ sc->sc_dflt_fqr = NULL; ++ return (ENXIO); ++} ++ ++static int ++dpaa_oh_detach(device_t dev) ++{ ++ struct dpaa_oh_softc *sc; ++ ++ sc = device_get_softc(dev); ++ ++ if (sc->sc_portph != NULL) { ++ FM_PORT_Free(sc->sc_portph); ++ sc->sc_portph = NULL; ++ } ++ ++ if (sc->sc_tx_fqr != NULL) ++ qman_fqr_free(sc->sc_tx_fqr); ++ if (sc->sc_err_fqr != NULL) ++ qman_fqr_free(sc->sc_err_fqr); ++ if (sc->sc_dflt_fqr != NULL) ++ qman_fqr_free(sc->sc_dflt_fqr); ++ ++ return (0); ++} ++/** @} */ ++ ++ ++/** ++ * @group Public API. ++ * @{ ++ */ ++ ++device_t ++dpaa_oh_find_port(int cell_index) ++{ ++ devclass_t dc; ++ device_t *devlist; ++ int count, i; ++ device_t result; ++ ++ dc = devclass_find("dpaa_oh"); ++ if (dc == NULL) ++ return (NULL); ++ ++ if (devclass_get_devices(dc, &devlist, &count) != 0) ++ return (NULL); ++ ++ result = NULL; ++ for (i = 0; i < count; i++) { ++ struct dpaa_oh_softc *sc; ++ ++ sc = device_get_softc(devlist[i]); ++ if (sc->sc_port_id == cell_index) { ++ result = devlist[i]; ++ break; ++ } ++ } ++ ++ free(devlist, M_TEMP); ++ return (result); ++} ++ ++t_Handle ++dpaa_oh_get_fm_port(device_t dev) ++{ ++ struct dpaa_oh_softc *sc; ++ ++ sc = device_get_softc(dev); ++ return (sc->sc_portph); ++} ++ ++uint32_t ++dpaa_oh_get_qman_channel(device_t dev) ++{ ++ struct dpaa_oh_softc *sc; ++ ++ sc = device_get_softc(dev); ++ return (sc->sc_qman_chan); ++} ++ ++uint32_t ++dpaa_oh_get_default_fqid(device_t dev) ++{ ++ struct dpaa_oh_softc *sc; ++ ++ sc = device_get_softc(dev); ++ return (sc->sc_dflt_fqid); ++} ++ ++uint32_t ++dpaa_oh_get_data_offset(device_t dev) ++{ ++ struct dpaa_oh_softc *sc; ++ ++ sc = device_get_softc(dev); ++ return (sc->sc_data_offset); ++} ++ ++int ++dpaa_oh_enqueue(device_t dev, t_DpaaFD *fd) ++{ ++ struct dpaa_oh_softc *sc; ++ t_Error error; ++ ++ sc = device_get_softc(dev); ++ if (sc->sc_tx_fqr == NULL) ++ return (ENXIO); ++ ++ error = qman_fqr_enqueue(sc->sc_tx_fqr, 0, fd); ++ if (error != E_OK) ++ return (EIO); ++ ++ return (0); ++} ++ ++int ++dpaa_oh_register_cb(device_t dev, t_QmReceivedFrameCallback *callback, ++ t_Handle app) ++{ ++ struct dpaa_oh_softc *sc; ++ t_Error error; ++ ++ sc = device_get_softc(dev); ++ if (sc->sc_dflt_fqr == NULL) ++ return (ENXIO); ++ ++ error = qman_fqr_register_cb(sc->sc_dflt_fqr, callback, app); ++ if (error != E_OK) ++ return (EIO); ++ ++ return (0); ++} ++/** @} */ ++ ++ ++/** ++ * @group Device driver boilerplate. ++ * @{ ++ */ ++ ++static device_method_t dpaa_oh_methods[] = { ++ DEVMETHOD(device_probe, dpaa_oh_probe), ++ DEVMETHOD(device_attach, dpaa_oh_attach), ++ DEVMETHOD(device_detach, dpaa_oh_detach), ++ { 0, 0 } ++}; ++ ++static driver_t dpaa_oh_driver = { ++ "dpaa_oh", ++ dpaa_oh_methods, ++ sizeof(struct dpaa_oh_softc), ++}; ++ ++DRIVER_MODULE(dpaa_oh, fman, dpaa_oh_driver, 0, 0); ++/** @} */ +diff --git a/sys/dev/dpaa/dpaa_oh.h b/sys/dev/dpaa/dpaa_oh.h +new file mode 100644 +index 00000000000..74474fd8ec9 +--- /dev/null ++++ b/sys/dev/dpaa/dpaa_oh.h +@@ -0,0 +1,90 @@ ++/*- ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * All rights reserved. ++ * ++ * 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 AUTHOR 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 AUTHOR 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. ++ */ ++ ++#ifndef DPAA_OH_H_ ++#define DPAA_OH_H_ ++ ++#include ++#include ++ ++/** ++ * Find an OH port device by its cell-index (hardware port ID). ++ * Cell-index values are 2-7 for FManv3 OH ports. ++ * ++ * @param cell_index The cell-index from device tree. ++ * @return The device_t, or NULL if not found. ++ */ ++device_t dpaa_oh_find_port(int cell_index); ++ ++/** ++ * Get the FM_PORT handle for PCD attachment. ++ * Consumers (e.g., CDX) use this to call FM_PORT_SetPCD(). ++ */ ++t_Handle dpaa_oh_get_fm_port(device_t dev); ++ ++/** ++ * Get the QMan channel ID for this OH port. ++ * Consumers create FQs with this channel as destination to send ++ * frames to the OH port for processing. ++ */ ++uint32_t dpaa_oh_get_qman_channel(device_t dev); ++ ++/** ++ * Get the default (egress) FQID. ++ * Frames that pass through the OH port without PCD classification ++ * are enqueued to this FQID. ++ */ ++uint32_t dpaa_oh_get_default_fqid(device_t dev); ++ ++/** ++ * Get the buffer data offset (prefix size). ++ * When building frames to send to the OH port, data must start ++ * at this offset within the buffer to leave room for the prefix. ++ */ ++uint32_t dpaa_oh_get_data_offset(device_t dev); ++ ++/** ++ * Enqueue a frame descriptor to the OH port for processing. ++ * ++ * @param dev The OH port device. ++ * @param fd The frame descriptor to enqueue. ++ * @return 0 on success, errno on failure. ++ */ ++int dpaa_oh_enqueue(device_t dev, t_DpaaFD *fd); ++ ++/** ++ * Register a callback for frames exiting the OH port's default FQ. ++ * These are "miss" frames that PCD did not classify into a flow. ++ * ++ * @param dev The OH port device. ++ * @param callback The callback function (same signature as QMan RX cb). ++ * @param app Opaque argument passed to callback. ++ * @return 0 on success, errno on failure. ++ */ ++int dpaa_oh_register_cb(device_t dev, ++ t_QmReceivedFrameCallback *callback, t_Handle app); ++ ++#endif /* DPAA_OH_H_ */ +diff --git a/sys/dev/dpaa/fman.c b/sys/dev/dpaa/fman.c +index f14ca45e1fc..42079c28282 100644 +--- a/sys/dev/dpaa/fman.c ++++ b/sys/dev/dpaa/fman.c +@@ -38,19 +38,33 @@ + #include + + #include ++#include ++ ++#include ++#include + + #include "opt_platform.h" ++#include "opt_dpaa.h" + + #include + #include ++#include + #include ++#include + #include + + #include "fman.h" ++#include "fman_chardev.h" ++#include ++ ++/* NCSW internal headers — needed for hot-adding HC to existing PCD */ ++#include ++#include + + + static MALLOC_DEFINE(M_FMAN, "fman", "fman devices information"); + ++ + /** + * @group FMan private defines. + * @{ +@@ -62,7 +76,11 @@ enum fman_irq_enum { + + enum fman_mu_ram_map { + FMAN_MURAM_OFF = 0x0, +- FMAN_MURAM_SIZE = 0x28000 ++#ifdef __aarch64__ ++ FMAN_MURAM_SIZE = 0x60000 /* LS1046A FManv3: 384KB */ ++#else ++ FMAN_MURAM_SIZE = 0x28000 /* P5020 FManv2: 160KB */ ++#endif + }; + + struct fman_config { +@@ -81,11 +99,13 @@ struct fman_config { + */ + /** + * Frame Manager firmware. +- * We use the same firmware for both P3041 and P2041 devices. ++ * On ARM64 (LS1046A), U-Boot preloads FManv3 microcode into IRAM, ++ * so we skip embedding firmware. On PowerPC, use the P3041 image. + */ ++#ifndef __aarch64__ + const uint32_t fman_firmware[] = FMAN_UC_IMG; + const uint32_t fman_firmware_size = sizeof(fman_firmware); +- ++#endif + int + fman_activate_resource(device_t bus, device_t child, int type, int rid, + struct resource *res) +@@ -260,6 +280,110 @@ fman_fill_ranges(phandle_t node, struct simplebus_softc *sc) + return (sc->nranges); + } + ++static void ++fman_pcd_exception_callback(t_Handle app_handle, ++ e_FmPcdExceptions exception) ++{ ++ struct fman_softc *sc; ++ ++ sc = app_handle; ++ device_printf(sc->sc_base.dev, "PCD exception %d occurred.\n", ++ exception); ++} ++ ++static void ++fman_pcd_id_exception_callback(t_Handle app_handle, ++ e_FmPcdExceptions exception, uint16_t index) ++{ ++ struct fman_softc *sc; ++ ++ sc = app_handle; ++ device_printf(sc->sc_base.dev, ++ "PCD indexed exception %d, index %u.\n", exception, index); ++} ++ ++/* ++ * Host Command (HC) port parameters. ++ * ++ * The HC port uses OH port cell-index 0x2 (the first offline port), ++ * which is reserved in the Mono Gateway DTS with status="disabled" ++ * so dpaa_oh doesn't claim it. FMANv3 requires portId=0 for HC. ++ */ ++#define FMAN_HC_OH_REG_OFFSET 0x82000 /* OH port 0x2 register offset */ ++#define FMAN_HC_PORT_ID 0 /* MUST be 0 for FMANv3 */ ++#define FMAN_HC_OH_CELL_INDEX 0x02 /* DT cell-index for QMan channel */ ++#define FMAN_HC_LIODN_BASE 0 /* ARM64 SMMU handles LIODN */ ++#define FMAN_HC_FQ_WQ 1 /* Work queue priority */ ++ ++/* ++ * Byte-swap every uint32_t in a buffer. ++ * ++ * FMan is big-endian and reads HC frame data via DMA with no hardware ++ * swap (DMA_NO_SWAP). On PPC (big-endian), native uint32_t values ++ * are already in the correct byte order. On ARM64 (little-endian), ++ * every uint32_t must be byte-swapped so FMan reads correct values. ++ * ++ * The Linux NXP SDK does exactly this in QmEnqueueCB (before enqueue) ++ * and qm_tx_conf_dqrr_cb (after confirmation) in lnxwrp_fm_port.c. ++ */ ++static __inline void ++fman_hc_bswap_frame(void *buf, uint32_t len) ++{ ++#if _BYTE_ORDER == _LITTLE_ENDIAN ++ uint32_t *p = (uint32_t *)buf; ++ uint32_t i; ++ ++ for (i = 0; i < len / 4; i++) ++ p[i] = __builtin_bswap32(p[i]); ++#endif ++} ++ ++/* ++ * QMan enqueue callback for the HC port. ++ * Called by NCSW HC code (hc.c EnQFrm) to send command frames ++ * through QMan to the FMan HC offline port. ++ */ ++static t_Error ++fman_hc_qm_enqueue(t_Handle h_arg, void *p_fd) ++{ ++ struct fman_softc *sc; ++ t_DpaaFD *fd = (t_DpaaFD *)p_fd; ++ ++ sc = h_arg; ++ ++ /* Byte-swap HC frame data for FMan big-endian DMA */ ++ fman_hc_bswap_frame(DPAA_FD_GET_ADDR(fd), DPAA_FD_GET_LENGTH(fd)); ++ ++ return (qman_fqr_enqueue(sc->hc_tx_fqr, 0, fd)); ++} ++ ++/* ++ * QMan receive callback for HC confirmation frames. ++ * ++ * FMan sends HC command completions on the confirmation FQ. QMan ++ * delivers them here; we forward to FM_PCD_HcTxConf() which clears ++ * the "enqueued" flag in hc.c, unblocking the spinning EnQFrm(). ++ * ++ * The HC frame data was byte-swapped before enqueue (for FMan BE DMA). ++ * Swap it back to native byte order so FmHcTxConf can read fields ++ * like commandSequence in native format. ++ */ ++static e_RxStoreResponse ++fman_hc_conf_callback(t_Handle app, t_Handle qm_fqr, t_Handle qm_portal, ++ uint32_t fqid_offset, t_DpaaFD *frame) ++{ ++ struct fman_softc *sc; ++ ++ sc = app; ++ ++ /* Byte-swap HC frame data back to native byte order */ ++ fman_hc_bswap_frame(DPAA_FD_GET_ADDR(frame), ++ DPAA_FD_GET_LENGTH(frame)); ++ ++ FM_PCD_HcTxConf(sc->pcd_handle, frame); ++ return (e_RX_STORE_RESPONSE_CONTINUE); ++} ++ + static t_Handle + fman_init(struct fman_softc *sc, struct fman_config *cfg) + { +@@ -271,6 +395,8 @@ fman_init(struct fman_softc *sc, struct fman_config *cfg) + uint16_t clock; + uint32_t tmp, mod; + ++ memset(&fm_params, 0, sizeof(fm_params)); ++ + /* MURAM configuration */ + muram_handle = FM_MURAM_ConfigAndInit(cfg->mem_base_addr + + FMAN_MURAM_OFF, FMAN_MURAM_SIZE); +@@ -281,6 +407,12 @@ fman_init(struct fman_softc *sc, struct fman_config *cfg) + } + sc->muram_handle = muram_handle; + ++ /* ++ * MURAM stays as Device-nGnRnE (the default bus resource mapping), ++ * matching Linux devm_ioremap(). All MURAM accesses must use ++ * WRITE_UINT32/GET_UINT32/IOMemSet32 — never plain memset/memcpy. ++ */ ++ + /* Fill in FM configuration */ + fm_params.fmId = cfg->fm_id; + /* XXX we support only one partition thus each fman has master id */ +@@ -307,8 +439,22 @@ fman_init(struct fman_softc *sc, struct fman_config *cfg) + fm_params.irq = cfg->irq_num; + fm_params.errIrq = cfg->err_irq_num; + ++#ifdef __aarch64__ ++ /* U-Boot preloads FMan microcode into IRAM; skip firmware loading */ ++ fm_params.firmware.size = 0; ++ fm_params.firmware.p_Code = NULL; ++#else + fm_params.firmware.size = fman_firmware_size; + fm_params.firmware.p_Code = (uint32_t*)fman_firmware; ++#endif ++ ++#if (DPAA_VERSION >= 11) ++ /* FManv3 Virtual Storage Profiles — master owns all 64 entries. ++ * VSP register block at FMan base + 0xdc000 (from fm_common.h FM_MM_SP). */ ++ fm_params.partVSPBase = 0; ++ fm_params.partNumOfVSPs = FM_VSP_MAX_NUM_OF_ENTRIES; ++ fm_params.vspBaseAddr = cfg->mem_base_addr + 0xdc000; ++#endif + + fm_handle = FM_Config(&fm_params); + if (fm_handle == NULL) { +@@ -317,7 +463,12 @@ fman_init(struct fman_softc *sc, struct fman_config *cfg) + goto err; + } + ++#ifdef __aarch64__ ++ /* Don't reset FMan — would wipe U-Boot's pre-loaded microcode */ ++ FM_ConfigResetOnInit(fm_handle, FALSE); ++#else + FM_ConfigResetOnInit(fm_handle, TRUE); ++#endif + + error = FM_Init(fm_handle); + if (error != E_OK) { +@@ -334,6 +485,100 @@ fman_init(struct fman_softc *sc, struct fman_config *cfg) + device_printf(cfg->fman_device, "Hardware version: %d.%d.\n", + revision_info.majorRev, revision_info.minorRev); + ++ { ++ t_FmCtrlCodeRevisionInfo ucode_rev; ++ if (FM_GetFmanCtrlCodeRevision(fm_handle, &ucode_rev) == E_OK) ++ device_printf(cfg->fman_device, ++ "Microcode: package %u, version %u.%u%s\n", ++ ucode_rev.packageRev, ++ ucode_rev.majorRev, ucode_rev.minorRev, ++ ucode_rev.packageRev >= 209 ? " (CDX/ASK)" : ++ ucode_rev.packageRev == 106 ? " (IP offload)" : ++ " (unknown)"); ++ } ++ ++ /* ++ * Initialize PCD (Parse-Classify-Distribute) with Parser + ++ * KeyGen + CC for RSS/multi-queue RX distribution and ++ * classification support. ++ * ++ * CC is enabled here so CDX can use it for hash tables. ++ * Host Command (HC) is NOT enabled here because QMan portals ++ * aren't ready during early FMan attach. CDX calls ++ * fman_reinit_pcd_with_hc() later to hot-add HC to this PCD ++ * without rebuilding it — preserving existing dtsec schemes. ++ */ ++ { ++ t_FmPcdParams pcd_params; ++ t_FmPcdNetEnvParams netenv_params; ++ ++ sc->pcd_handle = NULL; ++ sc->netenv_handle = NULL; ++ sc->hc_tx_fqr = NULL; ++ sc->hc_err_fqr = NULL; ++ sc->hc_conf_fqr = NULL; ++ ++ memset(&pcd_params, 0, sizeof(pcd_params)); ++ pcd_params.h_Fm = fm_handle; ++ pcd_params.prsSupport = TRUE; ++ pcd_params.ccSupport = TRUE; ++ pcd_params.kgSupport = TRUE; ++ pcd_params.plcrSupport = TRUE; ++ pcd_params.numOfSchemes = FM_PCD_KG_NUM_OF_SCHEMES; ++ pcd_params.f_Exception = fman_pcd_exception_callback; ++ pcd_params.f_ExceptionId = fman_pcd_id_exception_callback; ++ pcd_params.h_App = sc; ++ ++ sc->pcd_handle = FM_PCD_Config(&pcd_params); ++ if (sc->pcd_handle == NULL) { ++ device_printf(cfg->fman_device, ++ "couldn't configure PCD\n"); ++ goto skip_pcd; ++ } ++ ++ FM_PCD_ConfigPlcrNumOfSharedProfiles(sc->pcd_handle, 16); ++ ++ error = FM_PCD_Init(sc->pcd_handle); ++ if (error != E_OK) { ++ device_printf(cfg->fman_device, ++ "couldn't init PCD: %d\n", error); ++ FM_PCD_Free(sc->pcd_handle); ++ sc->pcd_handle = NULL; ++ goto skip_pcd; ++ } ++ ++ error = FM_PCD_Enable(sc->pcd_handle); ++ if (error != E_OK) { ++ device_printf(cfg->fman_device, ++ "couldn't enable PCD: %d\n", error); ++ FM_PCD_Free(sc->pcd_handle); ++ sc->pcd_handle = NULL; ++ goto skip_pcd; ++ } ++ ++ /* ++ * Network environment: IPv4/IPv6 + TCP/UDP distinction. ++ * This tells PCD which protocol layers to recognize. ++ */ ++ memset(&netenv_params, 0, sizeof(netenv_params)); ++ netenv_params.numOfDistinctionUnits = 2; ++ netenv_params.units[0].hdrs[0].hdr = HEADER_TYPE_IPv4; ++ netenv_params.units[0].hdrs[1].hdr = HEADER_TYPE_IPv6; ++ netenv_params.units[1].hdrs[0].hdr = HEADER_TYPE_TCP; ++ netenv_params.units[1].hdrs[1].hdr = HEADER_TYPE_UDP; ++ ++ sc->netenv_handle = FM_PCD_NetEnvCharacteristicsSet( ++ sc->pcd_handle, &netenv_params); ++ if (sc->netenv_handle == NULL) ++ device_printf(cfg->fman_device, ++ "couldn't set NetEnv characteristics\n"); ++ ++ device_printf(cfg->fman_device, ++ "PCD initialized: Parser + KeyGen\n"); ++skip_pcd: ++ ; ++ } ++ + /* Initialize the simplebus part of things */ + simplebus_init(sc->sc_base.dev, 0); + +@@ -352,6 +597,7 @@ fman_init(struct fman_softc *sc, struct fman_config *cfg) + FM_Free(fm_handle); + err: + FM_MURAM_Free(muram_handle); ++ sc->muram_handle = NULL; + return (NULL); + } + +@@ -361,7 +607,7 @@ fman_exception_callback(t_Handle app_handle, e_FmExceptions exception) + struct fman_softc *sc; + + sc = app_handle; +- device_printf(sc->sc_base.dev, "FMan exception occurred.\n"); ++ device_printf(sc->sc_base.dev, "FMan exception %d\n", exception); + } + + static void +@@ -371,8 +617,11 @@ fman_error_callback(t_Handle app_handle, e_FmPortType port_type, + struct fman_softc *sc; + + sc = app_handle; +- device_printf(sc->sc_base.dev, "FMan error occurred.\n"); ++ device_printf(sc->sc_base.dev, ++ "FMan error: portType=%d portId=%u addr=0x%llx tnum=%u liodn=%u\n", ++ port_type, port_id, (unsigned long long)addr, tnum, liodn); + } ++ + /** @} */ + + +@@ -411,6 +660,34 @@ fman_get_bushandle(device_t dev, vm_offset_t *fm_base) + return (0); + } + ++int ++fman_get_pcd_handle(device_t dev, t_Handle *pcdh) ++{ ++ struct fman_softc *sc = device_get_softc(dev); ++ ++ *pcdh = sc->pcd_handle; ++ ++ return (0); ++} ++ ++int ++fman_get_netenv_handle(device_t dev, t_Handle *netenvh) ++{ ++ struct fman_softc *sc = device_get_softc(dev); ++ ++ *netenvh = sc->netenv_handle; ++ ++ return (0); ++} ++ ++struct fmcd_softc * ++fman_get_fmcd(device_t dev) ++{ ++ struct fman_softc *sc = device_get_softc(dev); ++ ++ return (sc->fmcd); ++} ++ + int + fman_attach(device_t dev) + { +@@ -475,7 +752,20 @@ fman_attach(device_t dev) + goto err; + } + +- return (bus_generic_attach(dev)); ++ /* Initialize FMD chardev interface for userspace PCD control */ ++ if (sc->pcd_handle != NULL) { ++ sc->fmcd = malloc(sizeof(struct fmcd_softc), M_FMAN, ++ M_WAITOK | M_ZERO); ++ if (fmcd_init(dev, sc->fmcd) != 0) { ++ free(sc->fmcd, M_FMAN); ++ sc->fmcd = NULL; ++ device_printf(dev, ++ "fmcd: chardev init failed (non-fatal)\n"); ++ } ++ } ++ ++ bus_attach_children(dev); ++ return (0); + + err: + fman_detach(dev); +@@ -489,12 +779,29 @@ fman_detach(device_t dev) + + sc = device_get_softc(dev); + +- if (sc->muram_handle) { +- FM_MURAM_Free(sc->muram_handle); ++ if (sc->fmcd) { ++ fmcd_destroy(sc->fmcd); ++ free(sc->fmcd, M_FMAN); ++ sc->fmcd = NULL; ++ } ++ if (sc->netenv_handle) { ++ FM_PCD_NetEnvCharacteristicsDelete(sc->netenv_handle); ++ sc->netenv_handle = NULL; ++ } ++ if (sc->pcd_handle) { ++ FM_PCD_Disable(sc->pcd_handle); ++ FM_PCD_Free(sc->pcd_handle); ++ sc->pcd_handle = NULL; + } + + if (sc->fm_handle) { + FM_Free(sc->fm_handle); ++ sc->fm_handle = NULL; ++ } ++ ++ if (sc->muram_handle) { ++ FM_MURAM_Free(sc->muram_handle); ++ sc->muram_handle = NULL; + } + + if (sc->mem_res) { +@@ -507,7 +814,7 @@ fman_detach(device_t dev) + sc->irq_res); + } + +- if (sc->irq_res) { ++ if (sc->err_irq_res) { + bus_release_resource(dev, SYS_RES_IRQ, sc->err_irq_rid, + sc->err_irq_res); + } +@@ -540,8 +847,15 @@ int + fman_qman_channel_id(device_t dev, int port) + { + struct fman_softc *sc; ++#ifdef __aarch64__ ++ /* FMan v3 / Major >= 6 (LS1046A): 2x 10G + 6x 1G + 6x OH ports. ++ * Order matches Linux fman_get_qman_channel_id() for Major >= 6. */ ++ int qman_port_id[] = {0x30, 0x31, 0x28, 0x29, 0x2a, 0x2b, ++ 0x2c, 0x2d, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; ++#else + int qman_port_id[] = {0x31, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, + 0x2f, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; ++#endif + int i; + + sc = device_get_softc(dev); +@@ -553,4 +867,152 @@ fman_qman_channel_id(device_t dev, int port) + return (0); + } + ++/* ++ * Hot-add Host Command port to existing PCD for advanced offload. ++ * ++ * Called by CDX module init (after QMan portals are ready) to add HC ++ * support to the existing PCD. Unlike the previous approach of ++ * destroying and rebuilding PCD (which invalidated dtsec schemes and ++ * caused FM_FD_ERR_NO_SCHEME), this preserves the PCD, all existing ++ * KeyGen schemes, and dtsec port bindings. ++ * ++ * Sequence: ++ * 1. Create QMan FQRs for HC TX/confirmation/error ++ * 2. Disable PCD (brief pause — schemes survive) ++ * 3. Create HC port via FmHcConfigAndInit ++ * 4. Set p_FmPcd->h_Hc to enable HC in the PCD ++ * 5. FM_PCD_SetAdvancedOffloadSupport (requires HC + PCD disabled) ++ * 6. Re-enable PCD ++ * ++ * Returns 0 on success, errno on failure. ++ */ ++int ++fman_reinit_pcd_with_hc(device_t dev) ++{ ++ struct fman_softc *sc; ++ t_FmPcd *p_FmPcd; ++ t_FmHcParams hc_params; ++ t_Handle hc_handle; ++ uint32_t hc_qman_chan; ++ t_Handle fqr; ++ t_Error error; ++ ++ sc = device_get_softc(dev); ++ ++ if (sc->pcd_handle == NULL) { ++ device_printf(dev, "PCD not initialized\n"); ++ return (ENXIO); ++ } ++ ++ /* Resolve QMan channel for HC offline port (cell-index 0x2) */ ++ hc_qman_chan = fman_qman_channel_id(dev, FMAN_HC_OH_CELL_INDEX); ++ if (hc_qman_chan == 0) { ++ device_printf(dev, ++ "couldn't get QMan channel for HC port\n"); ++ return (ENXIO); ++ } ++ ++ /* TX FQR — HC enqueues command frames here for FMan */ ++ fqr = qman_fqr_create(1, hc_qman_chan, FMAN_HC_FQ_WQ, ++ false, 0, false, false, true, false, 0, 0, 0); ++ if (fqr == NULL) { ++ device_printf(dev, "couldn't create HC TX FQR\n"); ++ return (ENOMEM); ++ } ++ sc->hc_tx_fqr = fqr; ++ ++ /* Confirmation FQR — FMan sends HC completions here */ ++ fqr = qman_fqr_create(1, e_QM_FQ_CHANNEL_POOL1, ++ FMAN_HC_FQ_WQ, false, 0, false, false, true, false, ++ 0, 0, 0); ++ if (fqr == NULL) { ++ device_printf(dev, "couldn't create HC confirmation FQR\n"); ++ return (ENOMEM); ++ } ++ sc->hc_conf_fqr = fqr; ++ ++ /* ++ * Register callback for HC confirmation frames. ++ * FMan sends command completions on confFqid; without this ++ * callback, they hit QMan's dummy handler and EnQFrm() in ++ * hc.c spins until timeout. ++ */ ++ error = qman_fqr_register_cb(sc->hc_conf_fqr, ++ fman_hc_conf_callback, sc); ++ if (error != E_OK) { ++ device_printf(dev, ++ "couldn't register HC confirmation callback: %d\n", ++ error); ++ return (ENXIO); ++ } ++ ++ /* Error FQR — FMan sends HC errors here */ ++ fqr = qman_fqr_create(1, e_QM_FQ_CHANNEL_POOL1, ++ FMAN_HC_FQ_WQ, false, 0, false, false, true, false, ++ 0, 0, 0); ++ if (fqr == NULL) { ++ device_printf(dev, "couldn't create HC error FQR\n"); ++ return (ENOMEM); ++ } ++ sc->hc_err_fqr = fqr; ++ ++ /* ++ * Temporarily disable PCD to add HC and enable advanced ++ * offload. Existing KeyGen schemes and port bindings survive ++ * the Disable/Enable cycle — only the PRS/KG/PLCR hardware ++ * engines are paused. ++ */ ++ error = FM_PCD_Disable(sc->pcd_handle); ++ if (error != E_OK) { ++ device_printf(dev, "couldn't disable PCD: %d\n", error); ++ return (ENXIO); ++ } ++ ++ /* Create HC port and attach to existing PCD */ ++ memset(&hc_params, 0, sizeof(hc_params)); ++ hc_params.h_Fm = sc->fm_handle; ++ hc_params.h_FmPcd = sc->pcd_handle; ++ hc_params.params.portBaseAddr = rman_get_bushandle(sc->mem_res) + ++ FMAN_HC_OH_REG_OFFSET; ++ hc_params.params.portId = FMAN_HC_PORT_ID; ++ hc_params.params.liodnBase = FMAN_HC_LIODN_BASE; ++ hc_params.params.errFqid = ++ qman_fqr_get_base_fqid(sc->hc_err_fqr); ++ hc_params.params.confFqid = ++ qman_fqr_get_base_fqid(sc->hc_conf_fqr); ++ hc_params.params.qmChannel = hc_qman_chan; ++ hc_params.params.f_QmEnqueue = fman_hc_qm_enqueue; ++ hc_params.params.h_QmArg = sc; ++ ++ hc_handle = FmHcConfigAndInit(&hc_params); ++ if (hc_handle == NULL) { ++ device_printf(dev, "couldn't create HC port\n"); ++ FM_PCD_Enable(sc->pcd_handle); ++ return (ENXIO); ++ } ++ ++ /* Wire HC into the existing PCD */ ++ p_FmPcd = (t_FmPcd *)sc->pcd_handle; ++ p_FmPcd->h_Hc = hc_handle; ++ ++ /* Enable advanced offload (requires HC + PCD disabled) */ ++ error = FM_PCD_SetAdvancedOffloadSupport(sc->pcd_handle); ++ if (error != E_OK) { ++ device_printf(dev, ++ "couldn't set advanced offload support: %d\n", error); ++ /* Non-fatal — HC still works, just no offload flag */ ++ } ++ ++ /* Re-enable PCD — resumes Parser/KeyGen/CC processing */ ++ error = FM_PCD_Enable(sc->pcd_handle); ++ if (error != E_OK) { ++ device_printf(dev, "couldn't re-enable PCD: %d\n", error); ++ return (ENXIO); ++ } ++ ++ device_printf(dev, "PCD upgraded: HC port added, " ++ "existing schemes preserved\n"); ++ return (0); ++} ++ + /** @} */ +diff --git a/sys/dev/dpaa/fman.h b/sys/dev/dpaa/fman.h +index c7b57c60171..affb2dc6a75 100644 +--- a/sys/dev/dpaa/fman.h ++++ b/sys/dev/dpaa/fman.h +@@ -27,8 +27,11 @@ + #ifndef FMAN_H_ + #define FMAN_H_ + ++#include + #include + ++struct fmcd_softc; /* Forward declaration */ ++ + /** + * FMan driver instance data. + */ +@@ -46,6 +49,16 @@ struct fman_softc { + + t_Handle fm_handle; + t_Handle muram_handle; ++ t_Handle pcd_handle; ++ t_Handle netenv_handle; ++ ++ /* Host Command port state (for advanced offload) */ ++ t_Handle hc_tx_fqr; /* TX FQR for HC enqueue */ ++ t_Handle hc_err_fqr; /* Error FQR for HC port */ ++ t_Handle hc_conf_fqr; /* Confirmation FQR for HC port */ ++ ++ /* FMD chardev interface (for userspace PCD control via fmlib/FMC) */ ++ struct fmcd_softc *fmcd; + }; + + +@@ -73,5 +86,9 @@ uint32_t fman_get_clock(struct fman_softc *sc); + int fman_get_handle(device_t dev, t_Handle *fmh); + int fman_get_muram_handle(device_t dev, t_Handle *muramh); + int fman_get_bushandle(device_t dev, vm_offset_t *fm_base); ++int fman_get_pcd_handle(device_t dev, t_Handle *pcdh); ++int fman_get_netenv_handle(device_t dev, t_Handle *netenvh); ++int fman_reinit_pcd_with_hc(device_t dev); ++struct fmcd_softc *fman_get_fmcd(device_t dev); + + #endif /* FMAN_H_ */ +diff --git a/sys/dev/dpaa/fman_chardev.c b/sys/dev/dpaa/fman_chardev.c +new file mode 100644 +index 00000000000..af23617ef01 +--- /dev/null ++++ b/sys/dev/dpaa/fman_chardev.c +@@ -0,0 +1,1777 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * All rights reserved. ++ * ++ * FMan character device — exposes NCSW PCD API to userspace via ioctls. ++ * ++ * Creates /dev/fm0, /dev/fm0-pcd, /dev/fm0-port-rx*, /dev/fm0-port-oh* ++ * character devices. Userspace tools (fmlib, FMC, dpa_app) open these devices ++ * and issue ioctls that map 1:1 to NCSW kernel functions: ++ * ++ * FM_PCD_IOC_KG_SCHEME_SET → FM_PCD_KgSchemeSet() ++ * FM_PCD_IOC_HASH_TABLE_SET → FM_PCD_HashTableSet() ++ * FM_PCD_IOC_CC_ROOT_BUILD → FM_PCD_CcRootBuild() ++ * FM_PORT_IOC_SET_PCD → FM_PORT_SetPCD() ++ * ... etc. ++ * ++ * Handle management: NCSW returns opaque kernel pointers (t_Handle). ++ * A per-device handle table maps these to opaque integer IDs that are ++ * exposed to userspace — kernel pointers are never leaked. The ioc ++ * structs have identical binary layouts to the NCSW structs (plus a ++ * trailing void *id for output handles); the kernel translates handle ++ * IDs to/from kernel pointers at the ioctl boundary. ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "opt_dpaa.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++/* ++ * fmlib ioctl ABI headers — authoritative struct/ioctl definitions. ++ * These are included via FMCD_COMPILE_CMD -I paths (see config.dpaa_arm64). ++ */ ++#include "fm_pcd_ioctls.h" ++ ++#include "fman.h" ++#include "fman_chardev.h" ++ ++static MALLOC_DEFINE(M_FMCD, "fmcd", "FMan chardev data"); ++ ++/* ++ * Port PCD types and ioctl commands. ++ * ++ * These come from fm_port_ioctls.h in fmlib, but we cannot include that ++ * header because it pulls in fmlib's "enet_ext.h" which conflicts with ++ * the NCSW kernel copy (contrib/ncsw/inc/enet_ext.h). The types below ++ * are copied verbatim from fm_port_ioctls.h and must stay in sync. ++ */ ++typedef enum ioc_fm_port_pcd_support { ++ e_IOC_FM_PORT_PCD_SUPPORT_NONE = 0, ++ e_IOC_FM_PORT_PCD_SUPPORT_PRS_ONLY, ++ e_IOC_FM_PORT_PCD_SUPPORT_PLCR_ONLY, ++ e_IOC_FM_PORT_PCD_SUPPORT_PRS_AND_PLCR, ++ e_IOC_FM_PORT_PCD_SUPPORT_PRS_AND_KG, ++ e_IOC_FM_PORT_PCD_SUPPORT_PRS_AND_KG_AND_CC, ++ e_IOC_FM_PORT_PCD_SUPPORT_PRS_AND_KG_AND_CC_AND_PLCR, ++ e_IOC_FM_PORT_PCD_SUPPORT_PRS_AND_KG_AND_PLCR, ++ e_IOC_FM_PORT_PCD_SUPPORT_PRS_AND_CC, ++ e_IOC_FM_PORT_PCD_SUPPORT_PRS_AND_CC_AND_PLCR, ++ e_IOC_FM_PORT_PCD_SUPPORT_CC_ONLY, ++} ioc_fm_port_pcd_support; ++ ++typedef union ioc_fm_pcd_hdr_prs_opts_u { ++ struct { ++ bool label_interpretation_enable; ++ ioc_net_header_type next_parse; ++ } mpls_prs_options; ++ struct { ++ uint16_t tag_protocol_id1; ++ uint16_t tag_protocol_id2; ++ } vlan_prs_options; ++ struct { ++ bool enable_mtu_check; ++ } pppoe_prs_options; ++ struct { ++ bool routing_hdr_disable; ++ } ipv6_prs_options; ++ struct { ++ bool pad_ignore_checksum; ++ } udp_prs_options; ++ struct { ++ bool pad_ignore_checksum; ++ } tcp_prs_options; ++} ioc_fm_pcd_hdr_prs_opts_u; ++ ++typedef struct ioc_fm_pcd_prs_additional_hdr_params_t { ++ ioc_net_header_type hdr; ++ bool err_disable; ++ bool soft_prs_enable; ++ uint8_t index_per_hdr; ++ bool use_prs_opts; ++ ioc_fm_pcd_hdr_prs_opts_u prs_opts; ++} ioc_fm_pcd_prs_additional_hdr_params_t; ++ ++typedef struct ioc_fm_port_pcd_prs_params_t { ++ uint8_t prs_res_priv_info; ++ uint8_t parsing_offset; ++ ioc_net_header_type first_prs_hdr; ++ bool include_in_prs_statistics; ++ uint8_t num_of_hdrs_with_additional_params; ++ ioc_fm_pcd_prs_additional_hdr_params_t ++ additional_params[IOC_FM_PCD_PRS_NUM_OF_HDRS]; ++ bool set_vlan_tpid1; ++ uint16_t vlan_tpid1; ++ bool set_vlan_tpid2; ++ uint16_t vlan_tpid2; ++} ioc_fm_port_pcd_prs_params_t; ++ ++typedef struct ioc_fm_port_pcd_cc_params_t { ++ void *cc_tree_id; ++} ioc_fm_port_pcd_cc_params_t; ++ ++typedef struct ioc_fm_port_pcd_kg_params_t { ++ uint8_t num_of_schemes; ++ void *scheme_ids[FM_PCD_KG_NUM_OF_SCHEMES]; ++ bool direct_scheme; ++ void *direct_scheme_id; ++} ioc_fm_port_pcd_kg_params_t; ++ ++typedef struct ioc_fm_port_pcd_plcr_params_t { ++ void *plcr_profile_id; ++} ioc_fm_port_pcd_plcr_params_t; ++ ++typedef struct ioc_fm_port_pcd_params_t { ++ ioc_fm_port_pcd_support pcd_support; ++ void *net_env_id; ++ ioc_fm_port_pcd_prs_params_t *p_prs_params; ++ ioc_fm_port_pcd_cc_params_t *p_cc_params; ++ ioc_fm_port_pcd_kg_params_t *p_kg_params; ++ ioc_fm_port_pcd_plcr_params_t *p_plcr_params; ++ void *p_ip_reassembly_manip; ++ void *p_capwap_reassembly_manip; ++} ioc_fm_port_pcd_params_t; ++ ++#define FM_PORT_IOC_DISABLE _IO(FM_IOC_TYPE_BASE, FM_PORT_IOC_NUM(1)) ++#define FM_PORT_IOC_ENABLE _IO(FM_IOC_TYPE_BASE, FM_PORT_IOC_NUM(2)) ++#define FM_PORT_IOC_SET_PCD \ ++ _IOW(FM_IOC_TYPE_BASE, FM_PORT_IOC_NUM(20), ioc_fm_port_pcd_params_t) ++#define FM_PORT_IOC_DELETE_PCD _IO(FM_IOC_TYPE_BASE, FM_PORT_IOC_NUM(21)) ++ ++/* ------------------------------------------------------------------ */ ++/* Struct layout assertions */ ++/* ------------------------------------------------------------------ */ ++ ++/* ++ * The ioc structs must have identical binary layout to the corresponding ++ * NCSW structs, with only a trailing void *id output field appended. ++ * This is verified at compile time, matching Linux's ASSERT_COND pattern. ++ * ++ * roundup2() accounts for alignment padding the compiler may insert ++ * before the trailing void *id pointer (e.g. NetEnvParams: NCSW=964, ++ * ioc=976 because of 4 bytes padding to align void *id to 8 bytes). ++ */ ++#define FMCD_IOC_SIZE(ncsw_t) \ ++ roundup2(sizeof(ncsw_t) + sizeof(void *), _Alignof(void *)) ++ ++_Static_assert( ++ sizeof(ioc_fm_pcd_net_env_params_t) == FMCD_IOC_SIZE(t_FmPcdNetEnvParams), ++ "NetEnvParams size mismatch — ioc and NCSW struct layouts diverged"); ++ ++_Static_assert( ++ sizeof(ioc_fm_pcd_kg_scheme_params_t) == ++ FMCD_IOC_SIZE(t_FmPcdKgSchemeParams), ++ "KgSchemeParams size mismatch — ioc and NCSW struct layouts diverged"); ++ ++_Static_assert( ++ sizeof(ioc_fm_pcd_cc_tree_params_t) == ++ FMCD_IOC_SIZE(t_FmPcdCcTreeParams), ++ "CcTreeParams size mismatch — ioc and NCSW struct layouts diverged"); ++ ++_Static_assert( ++ sizeof(ioc_fm_pcd_cc_node_params_t) == ++ FMCD_IOC_SIZE(t_FmPcdCcNodeParams), ++ "CcNodeParams size mismatch — ioc and NCSW struct layouts diverged"); ++ ++_Static_assert( ++ sizeof(ioc_fm_pcd_hash_table_params_t) == ++ FMCD_IOC_SIZE(t_FmPcdHashTableParams), ++ "HashTableParams size mismatch — ioc and NCSW struct layouts diverged"); ++ ++_Static_assert( ++ sizeof(ioc_fm_pcd_manip_params_t) == ++ FMCD_IOC_SIZE(t_FmPcdManipParams), ++ "ManipParams size mismatch — ioc and NCSW struct layouts diverged"); ++ ++_Static_assert( ++ sizeof(ioc_fm_pcd_plcr_profile_params_t) == ++ FMCD_IOC_SIZE(t_FmPcdPlcrProfileParams), ++ "PlcrProfileParams size mismatch — ioc and NCSW struct layouts diverged"); ++ ++#if (DPAA_VERSION >= 11) ++_Static_assert( ++ sizeof(ioc_fm_pcd_frm_replic_group_params_t) == ++ FMCD_IOC_SIZE(t_FmPcdFrmReplicGroupParams), ++ "FrmReplicGroupParams size mismatch — ioc and NCSW struct layouts diverged"); ++#endif ++ ++/* Port PCD struct: no trailing id field, sizes must match exactly. */ ++_Static_assert( ++ sizeof(ioc_fm_port_pcd_params_t) == sizeof(t_FmPortPcdParams), ++ "PortPcdParams size mismatch — ioc and NCSW struct layouts diverged"); ++ ++/* ------------------------------------------------------------------ */ ++/* Port registration */ ++/* ------------------------------------------------------------------ */ ++ ++/* ++ * Convert DT cell-index to fmlib RX port index. ++ * ++ * fmlib convention (matching Linux SDK): ++ * 1G MACs: cell-index 0-5 → port index 0-5 ++ * 10G MACs: cell-index 8-9 → port index 6-7 ++ */ ++#define FMCD_1G_RX_PORTS 6 ++ ++static inline int ++fmcd_cell_to_rxidx(int cell_index) ++{ ++ if (cell_index >= 8) /* 10G MAC */ ++ return (FMCD_1G_RX_PORTS + (cell_index - 8)); ++ return (cell_index); /* 1G MAC */ ++} ++ ++void ++fmcd_register_rx_port(struct fmcd_softc *sc, int cell_index, t_Handle h_port, ++ uint32_t dflt_fqid) ++{ ++ int index = fmcd_cell_to_rxidx(cell_index); ++ ++ if (sc == NULL || index < 0 || index >= 8) ++ return; ++ ++ sx_xlock(&sc->port_lock); ++ sc->rx_port_handles[index] = h_port; ++ sc->rx_port_fqids[index] = dflt_fqid; ++ if (sc->cdev_port_rx[index] != NULL) ++ sc->cdev_port_rx[index]->si_drv2 = h_port; ++ sx_xunlock(&sc->port_lock); ++ ++ device_printf(sc->fman_dev, ++ "fmcd: rx port registered: cell=%d idx=%d fqid=%u\n", ++ cell_index, index, dflt_fqid); ++} ++ ++uint32_t ++fmcd_get_rx_dflt_fqid(struct fmcd_softc *sc, int index) ++{ ++ ++ if (sc == NULL || index < 0 || index >= 8) ++ return (0); ++ return (sc->rx_port_fqids[index]); ++} ++ ++void ++fmcd_register_rx_port_scheme(struct fmcd_softc *sc, int cell_index, ++ t_Handle h_scheme, t_Handle *p_scheme) ++{ ++ int index = fmcd_cell_to_rxidx(cell_index); ++ ++ if (sc == NULL || index < 0 || index >= 8) ++ return; ++ ++ sx_xlock(&sc->port_lock); ++ sc->rx_port_schemes[index] = h_scheme; ++ sc->rx_port_scheme_ptrs[index] = p_scheme; ++ sx_xunlock(&sc->port_lock); ++} ++ ++void ++fmcd_register_oh_port(struct fmcd_softc *sc, int index, t_Handle h_port) ++{ ++ if (sc == NULL || index < 0 || index >= 6) ++ return; ++ ++ sx_xlock(&sc->port_lock); ++ sc->oh_port_handles[index] = h_port; ++ if (sc->cdev_port_oh[index] != NULL) ++ sc->cdev_port_oh[index]->si_drv2 = h_port; ++ sx_xunlock(&sc->port_lock); ++} ++ ++void ++fmcd_pcd_mark_transferred(struct fmcd_softc *sc) ++{ ++ ++ sx_xlock(&sc->port_lock); ++ sc->pcd_transferred = true; ++ sx_xunlock(&sc->port_lock); ++} ++ ++/* ------------------------------------------------------------------ */ ++/* Handle table helpers */ ++/* ------------------------------------------------------------------ */ ++ ++/* ++ * Allocate a handle slot, store the kernel pointer and type. ++ * Returns the opaque handle ID, or 0 on failure (table full). ++ * Caller must hold sc->port_lock. ++ */ ++static uint64_t ++fmcd_handle_alloc(struct fmcd_softc *sc, t_Handle ptr, ++ enum fmcd_handle_type type) ++{ ++ int i; ++ ++ KASSERT(ptr != NULL, ("fmcd_handle_alloc: NULL ptr")); ++ KASSERT(type != FMCD_HDL_NONE, ("fmcd_handle_alloc: NONE type")); ++ ++ for (i = 0; i < FMCD_MAX_HANDLES; i++) { ++ if (sc->handles[i].ptr == NULL) { ++ sc->handles[i].ptr = ptr; ++ sc->handles[i].type = type; ++ return (((uint64_t)sc->handle_gen << ++ FMCD_HANDLE_SHIFT) | (uint64_t)i); ++ } ++ } ++ printf("fmcd: handle table full (%d entries)\n", FMCD_MAX_HANDLES); ++ return (0); ++} ++ ++/* ++ * Look up a handle ID and return the kernel pointer. ++ * If expected_type is not FMCD_HDL_NONE, validates the type matches. ++ * Returns NULL if the handle is invalid, stale, or type mismatches. ++ * Caller must hold sc->port_lock. ++ */ ++static t_Handle ++fmcd_handle_lookup(struct fmcd_softc *sc, uint64_t id, ++ enum fmcd_handle_type expected_type) ++{ ++ uint32_t slot, gen; ++ ++ if (id == 0) ++ return (NULL); ++ ++ slot = (uint32_t)(id & FMCD_HANDLE_MASK); ++ gen = (uint32_t)(id >> FMCD_HANDLE_SHIFT); ++ ++ if (slot >= FMCD_MAX_HANDLES) ++ return (NULL); ++ if (gen != sc->handle_gen) ++ return (NULL); ++ if (sc->handles[slot].ptr == NULL) ++ return (NULL); ++ if (expected_type != FMCD_HDL_NONE && ++ sc->handles[slot].type != expected_type) ++ return (NULL); ++ ++ return (sc->handles[slot].ptr); ++} ++ ++/* ++ * Free a handle slot. Returns the kernel pointer for the caller ++ * to pass to NCSW delete, or NULL if the handle is invalid. ++ * Caller must hold sc->port_lock. ++ */ ++static t_Handle ++fmcd_handle_free(struct fmcd_softc *sc, uint64_t id, ++ enum fmcd_handle_type expected_type) ++{ ++ uint32_t slot, gen; ++ t_Handle ptr; ++ ++ if (id == 0) ++ return (NULL); ++ ++ slot = (uint32_t)(id & FMCD_HANDLE_MASK); ++ gen = (uint32_t)(id >> FMCD_HANDLE_SHIFT); ++ ++ if (slot >= FMCD_MAX_HANDLES) ++ return (NULL); ++ if (gen != sc->handle_gen) ++ return (NULL); ++ if (sc->handles[slot].ptr == NULL) ++ return (NULL); ++ if (expected_type != FMCD_HDL_NONE && ++ sc->handles[slot].type != expected_type) ++ return (NULL); ++ ++ ptr = sc->handles[slot].ptr; ++ sc->handles[slot].ptr = NULL; ++ sc->handles[slot].type = FMCD_HDL_NONE; ++ return (ptr); ++} ++ ++/* ++ * Resolve a handle ID to a kernel pointer without freeing the slot. ++ * Used by the CDX module to translate hash table handles received ++ * from userspace (dpa_app) into NCSW kernel pointers. ++ * Returns NULL if the handle is invalid or stale. ++ */ ++t_Handle ++fmcd_handle_resolve(struct fmcd_softc *sc, uint64_t id, ++ enum fmcd_handle_type expected_type) ++{ ++ t_Handle ptr; ++ ++ sx_xlock(&sc->port_lock); ++ ptr = fmcd_handle_lookup(sc, id, expected_type); ++ sx_xunlock(&sc->port_lock); ++ return (ptr); ++} ++ ++/* ++ * Translate a void* field that holds an opaque handle ID to a kernel ++ * pointer. Returns 0 on success (field updated in-place), EINVAL on ++ * bad handle. NULL fields are left alone (returns 0). ++ * Caller must hold sc->port_lock. ++ */ ++static int ++fmcd_xlate(struct fmcd_softc *sc, void **field, ++ enum fmcd_handle_type expected_type) ++{ ++ t_Handle ptr; ++ ++ if (*field == NULL) ++ return (0); ++ ++ ptr = fmcd_handle_lookup(sc, (uint64_t)(uintptr_t)*field, ++ expected_type); ++ if (ptr == NULL) ++ return (EINVAL); ++ ++ *field = ptr; ++ return (0); ++} ++ ++/* ++ * Translate handle IDs embedded within a cc_next_engine_params_t ++ * to kernel pointers. Returns 0 on success, EINVAL on bad handle. ++ * Caller must hold sc->port_lock. ++ */ ++static int ++fmcd_translate_next_engine(struct fmcd_softc *sc, ++ ioc_fm_pcd_cc_next_engine_params_t *ne) ++{ ++ int error; ++ ++ switch (ne->next_engine) { ++ case e_IOC_FM_PCD_HASH: ++ case e_IOC_FM_PCD_CC: ++ error = fmcd_xlate(sc, ++ &ne->params.cc_params.cc_node_id, FMCD_HDL_NONE); ++ if (error) ++ return (error); ++ break; ++ case e_IOC_FM_PCD_KG: ++ error = fmcd_xlate(sc, ++ &ne->params.kg_params.p_direct_scheme, ++ FMCD_HDL_KG_SCHEME); ++ if (error) ++ return (error); ++ break; ++#if (DPAA_VERSION >= 11) ++ case e_IOC_FM_PCD_FR: ++ error = fmcd_xlate(sc, ++ &ne->params.fr_params.frm_replic_id, ++ FMCD_HDL_FRM_REPLIC); ++ if (error) ++ return (error); ++ break; ++#endif ++ default: ++ break; ++ } ++ ++ /* manip_id can appear regardless of next_engine */ ++ error = fmcd_xlate(sc, &ne->manip_id, FMCD_HDL_MANIP); ++ return (error); ++} ++ ++/* ++ * Translate handle IDs in a policer profile's color action params. ++ * Caller must hold sc->port_lock. ++ */ ++static int ++fmcd_translate_plcr_color(struct fmcd_softc *sc, ++ ioc_fm_pcd_engine next_engine, ++ ioc_fm_pcd_plcr_next_engine_params_u *p) ++{ ++ int error; ++ ++ switch (next_engine) { ++ case e_IOC_FM_PCD_PLCR: ++ error = fmcd_xlate(sc, &p->p_profile, ++ FMCD_HDL_PLCR_PROFILE); ++ return (error); ++ case e_IOC_FM_PCD_KG: ++ error = fmcd_xlate(sc, &p->p_direct_scheme, ++ FMCD_HDL_KG_SCHEME); ++ return (error); ++ default: ++ return (0); ++ } ++} ++ ++/* ------------------------------------------------------------------ */ ++/* PCD ioctl handlers */ ++/* ------------------------------------------------------------------ */ ++ ++static int ++fmcd_ioc_pcd_enable(struct fmcd_softc *sc) ++{ ++ t_Error err; ++ ++ err = FM_PCD_Enable(sc->pcd_handle); ++ return (err == E_OK ? 0 : EIO); ++} ++ ++static int ++fmcd_ioc_pcd_disable(struct fmcd_softc *sc) ++{ ++ t_Error err; ++ ++ err = FM_PCD_Disable(sc->pcd_handle); ++ return (err == E_OK ? 0 : EIO); ++} ++ ++static int ++fmcd_ioc_get_api_version(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_api_version_t *p = (ioc_fm_api_version_t *)data; ++ ++ p->version.major = FMD_API_VERSION_MAJOR; ++ p->version.minor = FMD_API_VERSION_MINOR; ++ p->version.respin = FMD_API_VERSION_RESPIN; ++ p->version.reserved = 0; ++ return (0); ++} ++ ++/* ++ * NetEnvCharacteristicsSet — _IOWR, framework copies in/out. ++ * Direct cast: ioc struct layout == NCSW struct layout. ++ */ ++static int ++fmcd_ioc_net_env_set(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_pcd_net_env_params_t *param = ++ (ioc_fm_pcd_net_env_params_t *)data; ++ t_Handle ptr; ++ uint64_t id; ++ ++ ptr = FM_PCD_NetEnvCharacteristicsSet(sc->pcd_handle, ++ (t_FmPcdNetEnvParams *)param); ++ if (ptr == NULL) ++ return (EIO); ++ ++ sx_xlock(&sc->port_lock); ++ id = fmcd_handle_alloc(sc, ptr, FMCD_HDL_NET_ENV); ++ sx_xunlock(&sc->port_lock); ++ if (id == 0) { ++ FM_PCD_NetEnvCharacteristicsDelete(ptr); ++ return (ENOMEM); ++ } ++ ++ param->id = (void *)(uintptr_t)id; ++ return (0); ++} ++ ++static int ++fmcd_ioc_net_env_delete(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_obj_t *ioc = (ioc_fm_obj_t *)data; ++ uint64_t id = (uint64_t)(uintptr_t)ioc->obj; ++ t_Handle ptr; ++ ++ sx_xlock(&sc->port_lock); ++ ptr = fmcd_handle_free(sc, id, FMCD_HDL_NET_ENV); ++ sx_xunlock(&sc->port_lock); ++ ++ if (ptr == NULL) ++ return (EINVAL); ++ ++ return (FM_PCD_NetEnvCharacteristicsDelete(ptr) ++ == E_OK ? 0 : EIO); ++} ++ ++/* ++ * KgSchemeSet — _IOWR, framework copies in/out. ++ * Direct cast: ioc struct layout == NCSW struct layout ++ * (after adding bool shared to t_FmPcdKgSchemeParams). ++ */ ++static int ++fmcd_ioc_kg_scheme_set(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_pcd_kg_scheme_params_t *param = ++ (ioc_fm_pcd_kg_scheme_params_t *)data; ++ t_FmPcdKgSchemeParams *ncsw = (t_FmPcdKgSchemeParams *)param; ++ t_Handle ptr; ++ uint64_t id; ++ int error; ++ ++ /* Translate input handle references */ ++ sx_xlock(&sc->port_lock); ++ if (param->modify) { ++ error = fmcd_xlate(sc, ¶m->scm_id.scheme_id, ++ FMCD_HDL_KG_SCHEME); ++ if (error) ++ goto unlock; ++ } ++ error = fmcd_xlate(sc, ¶m->net_env_params.net_env_id, ++ FMCD_HDL_NET_ENV); ++ if (error) ++ goto unlock; ++ if (param->next_engine == e_IOC_FM_PCD_CC) { ++ error = fmcd_xlate(sc, ++ ¶m->kg_next_engine_params.cc.tree_id, ++ FMCD_HDL_CC_ROOT); ++ if (error) ++ goto unlock; ++ } ++ /* PLCR profile in KG scheme context uses a numeric index ++ * (profile_select), not a handle — no translation needed. */ ++ sx_xunlock(&sc->port_lock); ++ ++ ptr = FM_PCD_KgSchemeSet(sc->pcd_handle, ncsw); ++ if (ptr == NULL) ++ return (EIO); ++ ++ sx_xlock(&sc->port_lock); ++ id = fmcd_handle_alloc(sc, ptr, FMCD_HDL_KG_SCHEME); ++ sx_xunlock(&sc->port_lock); ++ if (id == 0) { ++ FM_PCD_KgSchemeDelete(ptr); ++ return (ENOMEM); ++ } ++ ++ param->id = (void *)(uintptr_t)id; ++ return (0); ++ ++unlock: ++ sx_xunlock(&sc->port_lock); ++ return (error); ++} ++ ++static int ++fmcd_ioc_kg_scheme_delete(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_obj_t *ioc = (ioc_fm_obj_t *)data; ++ uint64_t id = (uint64_t)(uintptr_t)ioc->obj; ++ t_Handle ptr; ++ ++ sx_xlock(&sc->port_lock); ++ ptr = fmcd_handle_free(sc, id, FMCD_HDL_KG_SCHEME); ++ sx_xunlock(&sc->port_lock); ++ ++ if (ptr == NULL) ++ return (EINVAL); ++ ++ return (FM_PCD_KgSchemeDelete(ptr) == E_OK ? 0 : EIO); ++} ++ ++/* ++ * CcRootBuild — _IO on FreeBSD (struct exceeds IOCPARM_MAX). ++ * Manual copyin/copyout, direct cast. ++ */ ++static int ++fmcd_ioc_cc_root_build(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_pcd_cc_tree_params_t *param; ++ void *uptr; ++ t_Handle ptr; ++ uint64_t hid; ++ int i, j, error; ++ ++ uptr = *(void **)data; ++ if (uptr == NULL) ++ return (EINVAL); ++ ++ param = malloc(sizeof(*param), M_FMCD, M_WAITOK); ++ error = copyin(uptr, param, sizeof(*param)); ++ if (error) { ++ free(param, M_FMCD); ++ return (error); ++ } ++ ++ /* Translate input handle references */ ++ sx_xlock(&sc->port_lock); ++ error = fmcd_xlate(sc, ¶m->net_env_id, FMCD_HDL_NET_ENV); ++ if (error) ++ goto unlock; ++ ++ for (i = 0; i < param->num_of_groups && ++ i < IOC_FM_PCD_MAX_NUM_OF_CC_GROUPS; i++) { ++ uint8_t ndu = param->fm_pcd_cc_group_params[i]. ++ num_of_distinction_units; ++ int n_entries = (1 << ndu); /* 2^ndu entries per group */ ++ for (j = 0; j < n_entries && ++ j < IOC_FM_PCD_MAX_NUM_OF_CC_ENTRIES_IN_GRP; j++) { ++ ioc_fm_pcd_cc_next_engine_params_t *ne = ++ ¶m->fm_pcd_cc_group_params[i]. ++ next_engine_per_entries_in_grp[j]; ++ error = fmcd_translate_next_engine(sc, ne); ++ if (error) ++ goto unlock; ++ } ++ } ++ sx_xunlock(&sc->port_lock); ++ ++ ptr = FM_PCD_CcRootBuild(sc->pcd_handle, ++ (t_FmPcdCcTreeParams *)param); ++ if (ptr == NULL) { ++ free(param, M_FMCD); ++ return (EIO); ++ } ++ ++ sx_xlock(&sc->port_lock); ++ hid = fmcd_handle_alloc(sc, ptr, FMCD_HDL_CC_ROOT); ++ sx_xunlock(&sc->port_lock); ++ if (hid == 0) { ++ FM_PCD_CcRootDelete(ptr); ++ free(param, M_FMCD); ++ return (ENOMEM); ++ } ++ ++ param->id = (void *)(uintptr_t)hid; ++ error = copyout(param, uptr, sizeof(*param)); ++ free(param, M_FMCD); ++ return (error); ++ ++unlock: ++ sx_xunlock(&sc->port_lock); ++ free(param, M_FMCD); ++ return (error); ++} ++ ++static int ++fmcd_ioc_cc_root_delete(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_obj_t *ioc = (ioc_fm_obj_t *)data; ++ uint64_t id = (uint64_t)(uintptr_t)ioc->obj; ++ t_Handle ptr; ++ ++ sx_xlock(&sc->port_lock); ++ ptr = fmcd_handle_free(sc, id, FMCD_HDL_CC_ROOT); ++ sx_xunlock(&sc->port_lock); ++ ++ if (ptr == NULL) ++ return (EINVAL); ++ ++ return (FM_PCD_CcRootDelete(ptr) == E_OK ? 0 : EIO); ++} ++ ++/* ++ * HashTableSet — _IOWR, framework copies in/out. ++ * Direct cast. ++ */ ++static int ++fmcd_ioc_hash_table_set(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_pcd_hash_table_params_t *param = ++ (ioc_fm_pcd_hash_table_params_t *)data; ++ t_Handle ptr; ++ uint64_t id; ++ int error; ++ ++ /* Translate miss next-engine handle references */ ++ sx_xlock(&sc->port_lock); ++ error = fmcd_translate_next_engine(sc, ++ ¶m->cc_next_engine_params_for_miss); ++ sx_xunlock(&sc->port_lock); ++ if (error) ++ return (error); ++ ++ ptr = FM_PCD_HashTableSet(sc->pcd_handle, ++ (t_FmPcdHashTableParams *)param); ++ if (ptr == NULL) ++ return (EIO); ++ ++ sx_xlock(&sc->port_lock); ++ id = fmcd_handle_alloc(sc, ptr, FMCD_HDL_HASH_TABLE); ++ sx_xunlock(&sc->port_lock); ++ if (id == 0) { ++ FM_PCD_HashTableDelete(ptr); ++ return (ENOMEM); ++ } ++ ++ param->id = (void *)(uintptr_t)id; ++ return (0); ++} ++ ++static int ++fmcd_ioc_hash_table_delete(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_obj_t *ioc = (ioc_fm_obj_t *)data; ++ uint64_t id = (uint64_t)(uintptr_t)ioc->obj; ++ t_Handle ptr; ++ ++ sx_xlock(&sc->port_lock); ++ ptr = fmcd_handle_free(sc, id, FMCD_HDL_HASH_TABLE); ++ sx_xunlock(&sc->port_lock); ++ ++ if (ptr == NULL) ++ return (EINVAL); ++ ++ return (FM_PCD_HashTableDelete(ptr) == E_OK ? 0 : EIO); ++} ++ ++/* ++ * MatchTableSet — _IO on FreeBSD (struct exceeds IOCPARM_MAX). ++ * Manual copyin/copyout, direct cast. ++ * ++ * Special handling: key_params[i].p_key and p_mask point to userspace ++ * memory after copyin of the outer struct. Must copyin each key/mask ++ * buffer and redirect the pointers before calling NCSW. ++ */ ++static int ++fmcd_ioc_match_table_set(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_pcd_cc_node_params_t *param; ++ void *uptr; ++ uint8_t key_size; ++ int i, error; ++ int processed_keys = 0; ++ ++ uptr = *(void **)data; ++ if (uptr == NULL) ++ return (EINVAL); ++ ++ param = malloc(sizeof(*param), M_FMCD, M_WAITOK); ++ error = copyin(uptr, param, sizeof(*param)); ++ if (error) { ++ free(param, M_FMCD); ++ return (error); ++ } ++ ++ key_size = param->keys_params.key_size; ++ ++ /* ++ * Copyin key and mask buffers from userspace. ++ * After copyin of the outer struct, p_key/p_mask still reference ++ * userspace addresses. Allocate kernel buffers, copyin, redirect. ++ * ++ * Track processed_keys so the cleanup path only frees keys whose ++ * pointers were replaced with kernel allocations. Keys beyond ++ * processed_keys still hold raw userspace addresses from the ++ * outer copyin and must NOT be freed. ++ */ ++ for (i = 0; i < param->keys_params.num_of_keys && ++ i < IOC_FM_PCD_MAX_NUM_OF_KEYS; i++) { ++ ioc_fm_pcd_cc_key_params_t *kp = ++ ¶m->keys_params.key_params[i]; ++ void *umask = kp->p_mask; ++ ++ /* ++ * Clear p_mask before processing p_key so that if ++ * p_key copyin fails, the cleanup path won't call ++ * free() on the userspace address still in p_mask. ++ */ ++ kp->p_mask = NULL; ++ ++ if (kp->p_key != NULL && key_size > 0) { ++ void *usrc = kp->p_key; ++ kp->p_key = malloc(key_size, M_FMCD, M_WAITOK); ++ processed_keys = i + 1; ++ error = copyin(usrc, kp->p_key, key_size); ++ if (error) ++ goto fail; ++ } ++ ++ if (umask != NULL && key_size > 0) { ++ kp->p_mask = malloc(key_size, M_FMCD, M_WAITOK); ++ processed_keys = i + 1; ++ error = copyin(umask, kp->p_mask, key_size); ++ if (error) ++ goto fail; ++ } ++ ++ processed_keys = i + 1; ++ } ++ ++ /* Translate handle references in next-engine params */ ++ sx_xlock(&sc->port_lock); ++ for (i = 0; i < param->keys_params.num_of_keys && ++ i < IOC_FM_PCD_MAX_NUM_OF_KEYS; i++) { ++ error = fmcd_translate_next_engine(sc, ++ ¶m->keys_params.key_params[i].cc_next_engine_params); ++ if (error) { ++ sx_xunlock(&sc->port_lock); ++ goto fail; ++ } ++ } ++ error = fmcd_translate_next_engine(sc, ++ ¶m->keys_params.cc_next_engine_params_for_miss); ++ sx_xunlock(&sc->port_lock); ++ if (error) ++ goto fail; ++ ++ { ++ t_Handle ptr; ++ uint64_t hid; ++ ++ ptr = FM_PCD_MatchTableSet(sc->pcd_handle, ++ (t_FmPcdCcNodeParams *)param); ++ if (ptr == NULL) { ++ error = EIO; ++ goto fail; ++ } ++ ++ sx_xlock(&sc->port_lock); ++ hid = fmcd_handle_alloc(sc, ptr, FMCD_HDL_MATCH_TABLE); ++ sx_xunlock(&sc->port_lock); ++ if (hid == 0) { ++ FM_PCD_MatchTableDelete(ptr); ++ error = ENOMEM; ++ goto fail; ++ } ++ ++ param->id = (void *)(uintptr_t)hid; ++ } ++ ++ error = copyout(param, uptr, sizeof(*param)); ++ ++fail: ++ /* ++ * Free only key/mask buffers that were replaced with kernel ++ * allocations (indices 0..processed_keys-1). Entries beyond ++ * processed_keys still hold userspace addresses and must not ++ * be passed to free(). ++ */ ++ for (i = 0; i < processed_keys; i++) { ++ ioc_fm_pcd_cc_key_params_t *kp = ++ ¶m->keys_params.key_params[i]; ++ if (kp->p_key != NULL) ++ free(kp->p_key, M_FMCD); ++ if (kp->p_mask != NULL) ++ free(kp->p_mask, M_FMCD); ++ } ++ free(param, M_FMCD); ++ return (error); ++} ++ ++static int ++fmcd_ioc_match_table_delete(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_obj_t *ioc = (ioc_fm_obj_t *)data; ++ uint64_t id = (uint64_t)(uintptr_t)ioc->obj; ++ t_Handle ptr; ++ ++ sx_xlock(&sc->port_lock); ++ ptr = fmcd_handle_free(sc, id, FMCD_HDL_MATCH_TABLE); ++ sx_xunlock(&sc->port_lock); ++ ++ if (ptr == NULL) ++ return (EINVAL); ++ ++ return (FM_PCD_MatchTableDelete(ptr) == E_OK ? 0 : EIO); ++} ++ ++/* ++ * ManipNodeSet — _IOWR, framework copies in/out. ++ * Direct cast. ++ */ ++static int ++fmcd_ioc_manip_node_set(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_pcd_manip_params_t *param = ++ (ioc_fm_pcd_manip_params_t *)data; ++ t_Handle ptr; ++ uint64_t id; ++ int error; ++ ++ /* Translate chained manipulation handle */ ++ sx_xlock(&sc->port_lock); ++ error = fmcd_xlate(sc, ¶m->p_next_manip, FMCD_HDL_MANIP); ++ sx_xunlock(&sc->port_lock); ++ if (error) ++ return (error); ++ ++ ptr = FM_PCD_ManipNodeSet(sc->pcd_handle, ++ (t_FmPcdManipParams *)param); ++ if (ptr == NULL) ++ return (EIO); ++ ++ sx_xlock(&sc->port_lock); ++ id = fmcd_handle_alloc(sc, ptr, FMCD_HDL_MANIP); ++ sx_xunlock(&sc->port_lock); ++ if (id == 0) { ++ FM_PCD_ManipNodeDelete(ptr); ++ return (ENOMEM); ++ } ++ ++ param->id = (void *)(uintptr_t)id; ++ return (0); ++} ++ ++static int ++fmcd_ioc_manip_node_delete(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_obj_t *ioc = (ioc_fm_obj_t *)data; ++ uint64_t id = (uint64_t)(uintptr_t)ioc->obj; ++ t_Handle ptr; ++ ++ sx_xlock(&sc->port_lock); ++ ptr = fmcd_handle_free(sc, id, FMCD_HDL_MANIP); ++ sx_xunlock(&sc->port_lock); ++ ++ if (ptr == NULL) ++ return (EINVAL); ++ ++ return (FM_PCD_ManipNodeDelete(ptr) == E_OK ? 0 : EIO); ++} ++ ++#if (DPAA_VERSION >= 11) ++/* ++ * FrmReplicSetGroup — _IO on FreeBSD (struct exceeds IOCPARM_MAX). ++ * Manual copyin/copyout, direct cast. ++ */ ++static int ++fmcd_ioc_frm_replic_set_group(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_pcd_frm_replic_group_params_t *param; ++ void *uptr; ++ t_Handle ptr; ++ uint64_t hid; ++ int i, error; ++ ++ uptr = *(void **)data; ++ if (uptr == NULL) ++ return (EINVAL); ++ ++ param = malloc(sizeof(*param), M_FMCD, M_WAITOK); ++ error = copyin(uptr, param, sizeof(*param)); ++ if (error) { ++ free(param, M_FMCD); ++ return (error); ++ } ++ ++ /* Translate handle references in each entry's next-engine params */ ++ sx_xlock(&sc->port_lock); ++ for (i = 0; i < param->num_of_entries && ++ i < IOC_FM_PCD_FRM_REPLIC_MAX_NUM_OF_ENTRIES; i++) { ++ error = fmcd_translate_next_engine(sc, ++ ¶m->next_engine_params[i]); ++ if (error) { ++ sx_xunlock(&sc->port_lock); ++ free(param, M_FMCD); ++ return (error); ++ } ++ } ++ sx_xunlock(&sc->port_lock); ++ ++ ptr = FM_PCD_FrmReplicSetGroup(sc->pcd_handle, ++ (t_FmPcdFrmReplicGroupParams *)param); ++ if (ptr == NULL) { ++ free(param, M_FMCD); ++ return (EIO); ++ } ++ ++ sx_xlock(&sc->port_lock); ++ hid = fmcd_handle_alloc(sc, ptr, FMCD_HDL_FRM_REPLIC); ++ sx_xunlock(&sc->port_lock); ++ if (hid == 0) { ++ FM_PCD_FrmReplicDeleteGroup(ptr); ++ free(param, M_FMCD); ++ return (ENOMEM); ++ } ++ ++ param->id = (void *)(uintptr_t)hid; ++ error = copyout(param, uptr, sizeof(*param)); ++ free(param, M_FMCD); ++ return (error); ++} ++ ++static int ++fmcd_ioc_frm_replic_delete_group(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_obj_t *ioc = (ioc_fm_obj_t *)data; ++ uint64_t id = (uint64_t)(uintptr_t)ioc->obj; ++ t_Handle ptr; ++ ++ sx_xlock(&sc->port_lock); ++ ptr = fmcd_handle_free(sc, id, FMCD_HDL_FRM_REPLIC); ++ sx_xunlock(&sc->port_lock); ++ ++ if (ptr == NULL) ++ return (EINVAL); ++ ++ return (FM_PCD_FrmReplicDeleteGroup(ptr) == E_OK ? 0 : EIO); ++} ++#endif /* DPAA_VERSION >= 11 */ ++ ++/* ++ * PrsLoadSw — _IOW, framework copies in. ++ * Direct cast, but p_code pointer needs copyin + redirect. ++ */ ++static int ++fmcd_ioc_prs_load_sw(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_pcd_prs_sw_params_t *param = ++ (ioc_fm_pcd_prs_sw_params_t *)data; ++ uint8_t *code_buf; ++ t_Error err; ++ ++ if (param->size == 0 || param->p_code == NULL) ++ return (EINVAL); ++ if (param->size > FM_PCD_SW_PRS_SIZE) ++ return (EINVAL); ++ ++ /* Copyin the parser microcode from userspace */ ++ code_buf = malloc(param->size, M_FMCD, M_WAITOK); ++ if (copyin(param->p_code, code_buf, param->size) != 0) { ++ free(code_buf, M_FMCD); ++ return (EFAULT); ++ } ++ ++ /* Redirect pointer to kernel buffer */ ++ param->p_code = code_buf; ++ ++ err = FM_PCD_PrsLoadSw(sc->pcd_handle, (t_FmPcdPrsSwParams *)param); ++ free(code_buf, M_FMCD); ++ ++ return (err == E_OK ? 0 : EIO); ++} ++ ++/* ++ * PlcrProfileSet — _IOWR, framework copies in/out. ++ * Direct cast. ++ */ ++static int ++fmcd_ioc_plcr_profile_set(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_pcd_plcr_profile_params_t *param = ++ (ioc_fm_pcd_plcr_profile_params_t *)data; ++ t_Handle ptr; ++ uint64_t id; ++ int error; ++ ++ /* Translate input handle references */ ++ sx_xlock(&sc->port_lock); ++ if (param->modify) { ++ error = fmcd_xlate(sc, ¶m->profile_select.p_profile, ++ FMCD_HDL_PLCR_PROFILE); ++ if (error) ++ goto unlock; ++ } ++ error = fmcd_translate_plcr_color(sc, param->next_engine_on_green, ++ ¶m->params_on_green); ++ if (error) ++ goto unlock; ++ error = fmcd_translate_plcr_color(sc, param->next_engine_on_yellow, ++ ¶m->params_on_yellow); ++ if (error) ++ goto unlock; ++ error = fmcd_translate_plcr_color(sc, param->next_engine_on_red, ++ ¶m->params_on_red); ++ if (error) ++ goto unlock; ++ sx_xunlock(&sc->port_lock); ++ ++ ptr = FM_PCD_PlcrProfileSet(sc->pcd_handle, ++ (t_FmPcdPlcrProfileParams *)param); ++ if (ptr == NULL) ++ return (EIO); ++ ++ sx_xlock(&sc->port_lock); ++ id = fmcd_handle_alloc(sc, ptr, FMCD_HDL_PLCR_PROFILE); ++ sx_xunlock(&sc->port_lock); ++ if (id == 0) { ++ FM_PCD_PlcrProfileDelete(ptr); ++ return (ENOMEM); ++ } ++ ++ param->id = (void *)(uintptr_t)id; ++ return (0); ++ ++unlock: ++ sx_xunlock(&sc->port_lock); ++ return (error); ++} ++ ++static int ++fmcd_ioc_plcr_profile_delete(struct fmcd_softc *sc, caddr_t data) ++{ ++ ioc_fm_obj_t *ioc = (ioc_fm_obj_t *)data; ++ uint64_t id = (uint64_t)(uintptr_t)ioc->obj; ++ t_Handle ptr; ++ ++ sx_xlock(&sc->port_lock); ++ ptr = fmcd_handle_free(sc, id, FMCD_HDL_PLCR_PROFILE); ++ sx_xunlock(&sc->port_lock); ++ ++ if (ptr == NULL) ++ return (EINVAL); ++ ++ return (FM_PCD_PlcrProfileDelete(ptr) == E_OK ? 0 : EIO); ++} ++ ++/* ------------------------------------------------------------------ */ ++/* Port ioctl handlers */ ++/* ------------------------------------------------------------------ */ ++ ++/* ++ * PortSetPCD — _IOW, framework copies in the outer struct. ++ * The pointer members (p_prs_params, p_cc_params, p_kg_params, ++ * p_plcr_params) still reference userspace sub-structs after copyin. ++ * Copyin each and redirect, then direct-cast to NCSW type. ++ * ++ * Handle references (net_env_id, cc_tree_id, scheme_ids[], etc.) ++ * are translated from opaque IDs to kernel pointers. ++ */ ++static int ++fmcd_ioc_port_set_pcd(struct fmcd_softc *sc, t_Handle h_port, caddr_t data) ++{ ++ ioc_fm_port_pcd_params_t *param = (ioc_fm_port_pcd_params_t *)data; ++ ioc_fm_port_pcd_prs_params_t *prs = NULL; ++ ioc_fm_port_pcd_cc_params_t *cc_p = NULL; ++ ioc_fm_port_pcd_kg_params_t *kg_p = NULL; ++ ioc_fm_port_pcd_plcr_params_t *plcr = NULL; ++ t_Error err; ++ int i, error = 0; ++ ++ if (h_port == NULL) ++ return (ENXIO); ++ ++ /* Copyin sub-structs from userspace pointers */ ++ if (param->p_prs_params != NULL) { ++ prs = malloc(sizeof(*prs), M_FMCD, M_WAITOK); ++ error = copyin(param->p_prs_params, prs, sizeof(*prs)); ++ if (error) ++ goto out; ++ param->p_prs_params = prs; ++ } ++ ++ if (param->p_cc_params != NULL) { ++ cc_p = malloc(sizeof(*cc_p), M_FMCD, M_WAITOK); ++ error = copyin(param->p_cc_params, cc_p, sizeof(*cc_p)); ++ if (error) ++ goto out; ++ param->p_cc_params = cc_p; ++ } ++ ++ if (param->p_kg_params != NULL) { ++ kg_p = malloc(sizeof(*kg_p), M_FMCD, M_WAITOK); ++ error = copyin(param->p_kg_params, kg_p, sizeof(*kg_p)); ++ if (error) ++ goto out; ++ param->p_kg_params = kg_p; ++ } ++ ++ if (param->p_plcr_params != NULL) { ++ plcr = malloc(sizeof(*plcr), M_FMCD, M_WAITOK); ++ error = copyin(param->p_plcr_params, plcr, sizeof(*plcr)); ++ if (error) ++ goto out; ++ param->p_plcr_params = plcr; ++ } ++ ++ /* Translate handle references in copyin'd sub-structs */ ++ sx_xlock(&sc->port_lock); ++ error = fmcd_xlate(sc, ¶m->net_env_id, FMCD_HDL_NET_ENV); ++ if (error) ++ goto unlock; ++ ++ if (cc_p != NULL) { ++ error = fmcd_xlate(sc, &cc_p->cc_tree_id, FMCD_HDL_CC_ROOT); ++ if (error) ++ goto unlock; ++ } ++ ++ if (kg_p != NULL) { ++ for (i = 0; i < kg_p->num_of_schemes && ++ i < FM_PCD_KG_NUM_OF_SCHEMES; i++) { ++ error = fmcd_xlate(sc, &kg_p->scheme_ids[i], ++ FMCD_HDL_KG_SCHEME); ++ if (error) ++ goto unlock; ++ } ++ if (kg_p->direct_scheme) { ++ error = fmcd_xlate(sc, &kg_p->direct_scheme_id, ++ FMCD_HDL_KG_SCHEME); ++ if (error) ++ goto unlock; ++ } ++ } ++ ++ if (plcr != NULL) { ++ error = fmcd_xlate(sc, &plcr->plcr_profile_id, ++ FMCD_HDL_PLCR_PROFILE); ++ if (error) ++ goto unlock; ++ } ++ ++ error = fmcd_xlate(sc, ¶m->p_ip_reassembly_manip, ++ FMCD_HDL_MANIP); ++ if (error) ++ goto unlock; ++ error = fmcd_xlate(sc, ¶m->p_capwap_reassembly_manip, ++ FMCD_HDL_MANIP); ++ if (error) ++ goto unlock; ++ sx_xunlock(&sc->port_lock); ++ ++ err = FM_PORT_SetPCD(h_port, (t_FmPortPcdParams *)param); ++ if (err != E_OK) { ++ printf("fmcd: SetPCD FAILED err=%d\n", (int)err); ++ error = EIO; ++ goto out; ++ } ++ ++out: ++ free(prs, M_FMCD); ++ free(cc_p, M_FMCD); ++ free(kg_p, M_FMCD); ++ free(plcr, M_FMCD); ++ return (error); ++ ++unlock: ++ sx_xunlock(&sc->port_lock); ++ goto out; ++} ++ ++static int ++fmcd_ioc_port_delete_pcd(struct fmcd_softc *sc, t_Handle h_port) ++{ ++ ++ if (h_port == NULL) ++ return (ENXIO); ++ ++ { ++ t_Error err = FM_PORT_DeletePCD(h_port); ++ return (err == E_OK ? 0 : EIO); ++ } ++} ++ ++static int ++fmcd_ioc_port_enable(struct fmcd_softc *sc, t_Handle h_port) ++{ ++ t_Error err; ++ ++ if (h_port == NULL) { ++ printf("fmcd: port_enable: h_port=NULL!\n"); ++ return (ENXIO); ++ } ++ ++ err = FM_PORT_Enable(h_port); ++ return (err == E_OK ? 0 : EIO); ++} ++ ++static int ++fmcd_ioc_port_disable(struct fmcd_softc *sc, t_Handle h_port) ++{ ++ t_Error err; ++ ++ if (h_port == NULL) { ++ printf("fmcd: port_disable: h_port=NULL!\n"); ++ return (ENXIO); ++ } ++ ++ err = FM_PORT_Disable(h_port); ++ return (err == E_OK ? 0 : EIO); ++} ++ ++/* ------------------------------------------------------------------ */ ++/* Chardev operations */ ++/* ------------------------------------------------------------------ */ ++ ++static int ++fmcd_open(struct cdev *dev, int flags, int fmt, struct thread *td) ++{ ++ return (0); ++} ++ ++/* ++ * PCD device open handler. ++ * ++ * When userspace opens /dev/fm0-pcd, it is taking over PCD management ++ * (e.g., FMC/dpa_app is starting). Tear down any existing PCD set up ++ * by the dtsec driver (RSS KG schemes) to free KG scheme IDs for FMC. ++ * Also reset the handle table and bump the generation counter to ++ * invalidate any stale handles from a previous session. ++ */ ++static int ++fmcd_pcd_open(struct cdev *dev, int flags, int fmt, struct thread *td) ++{ ++ struct fmcd_softc *sc = dev->si_drv1; ++ int i; ++ ++ sx_xlock(&sc->port_lock); ++ ++ for (i = 0; i < 8; i++) { ++ if (sc->rx_port_schemes[i] != NULL) { ++ if (sc->rx_port_handles[i] != NULL) ++ FM_PORT_DeletePCD(sc->rx_port_handles[i]); ++ FM_PCD_KgSchemeDelete(sc->rx_port_schemes[i]); ++ sc->rx_port_schemes[i] = NULL; ++ /* Clear dtsec's handle so pcd_free() won't ++ * double-free */ ++ if (sc->rx_port_scheme_ptrs[i] != NULL) { ++ *sc->rx_port_scheme_ptrs[i] = NULL; ++ sc->rx_port_scheme_ptrs[i] = NULL; ++ } ++ } ++ } ++ ++ /* ++ * Clear handle table and bump generation. We don't delete ++ * NCSW objects here — the previous session should have cleaned ++ * up via close, and the PCD enable/disable cycle that ++ * fmc/dpa_app does on startup resets PCD state. ++ */ ++ for (i = 0; i < FMCD_MAX_HANDLES; i++) { ++ sc->handles[i].ptr = NULL; ++ sc->handles[i].type = FMCD_HDL_NONE; ++ } ++ sc->handle_gen++; ++ if (sc->handle_gen == 0) ++ sc->handle_gen = 1; ++ ++ sx_xunlock(&sc->port_lock); ++ ++ return (0); ++} ++ ++/* ++ * PCD device close handler. ++ * ++ * Delete all PCD objects created during this session in dependency ++ * order (reverse of creation). This prevents kernel memory leaks ++ * if userspace crashes without explicit cleanup. ++ */ ++static int ++fmcd_pcd_close(struct cdev *dev, int flags, int fmt, struct thread *td) ++{ ++ struct fmcd_softc *sc = dev->si_drv1; ++ int i; ++ ++ sx_xlock(&sc->port_lock); ++ ++ if (sc->pcd_transferred) { ++ /* ++ * CDX has taken ownership of all PCD resources via ++ * CDX_CTRL_DPA_SET_PARAMS. The NCSW objects (hash tables, ++ * CC trees, KG schemes, net envs) are bound to FMan ports ++ * and must not be deleted. Just clear the handle table. ++ */ ++ for (i = 0; i < FMCD_MAX_HANDLES; i++) { ++ sc->handles[i].ptr = NULL; ++ sc->handles[i].type = FMCD_HDL_NONE; ++ } ++ } else { ++ /* ++ * No CDX takeover — dpa_app exited before CDX claimed ++ * the PCD resources. Delete all NCSW objects in ++ * dependency order to prevent kernel memory leaks. ++ */ ++ static const enum fmcd_handle_type teardown_order[] = { ++ FMCD_HDL_FRM_REPLIC, ++ FMCD_HDL_PLCR_PROFILE, ++ FMCD_HDL_MATCH_TABLE, ++ FMCD_HDL_HASH_TABLE, ++ FMCD_HDL_CC_ROOT, ++ FMCD_HDL_KG_SCHEME, ++ FMCD_HDL_MANIP, ++ FMCD_HDL_NET_ENV, ++ }; ++ int phase; ++ ++ for (phase = 0; phase < nitems(teardown_order); phase++) { ++ for (i = 0; i < FMCD_MAX_HANDLES; i++) { ++ t_Handle ptr = sc->handles[i].ptr; ++ t_Error err; ++ ++ if (ptr == NULL || ++ sc->handles[i].type != ++ teardown_order[phase]) ++ continue; ++ ++ sc->handles[i].ptr = NULL; ++ sc->handles[i].type = FMCD_HDL_NONE; ++ ++ switch (teardown_order[phase]) { ++ case FMCD_HDL_NET_ENV: ++ err = FM_PCD_NetEnvCharacteristicsDelete(ptr); ++ break; ++ case FMCD_HDL_KG_SCHEME: ++ err = FM_PCD_KgSchemeDelete(ptr); ++ break; ++ case FMCD_HDL_CC_ROOT: ++ err = FM_PCD_CcRootDelete(ptr); ++ break; ++ case FMCD_HDL_MATCH_TABLE: ++ err = FM_PCD_MatchTableDelete(ptr); ++ break; ++ case FMCD_HDL_HASH_TABLE: ++ err = FM_PCD_HashTableDelete(ptr); ++ break; ++ case FMCD_HDL_MANIP: ++ err = FM_PCD_ManipNodeDelete(ptr); ++ break; ++ case FMCD_HDL_PLCR_PROFILE: ++ err = FM_PCD_PlcrProfileDelete(ptr); ++ break; ++ case FMCD_HDL_FRM_REPLIC: ++ err = FM_PCD_FrmReplicDeleteGroup(ptr); ++ break; ++ default: ++ err = E_OK; ++ break; ++ } ++ ++ if (err != E_OK) ++ printf("fmcd: close: failed to " ++ "delete slot %d type %d\n", ++ i, teardown_order[phase]); ++ } ++ } ++ } ++ ++ /* Bump generation to invalidate any lingering handle IDs */ ++ sc->handle_gen++; ++ if (sc->handle_gen == 0) ++ sc->handle_gen = 1; ++ ++ sc->pcd_transferred = false; ++ sx_xunlock(&sc->port_lock); ++ return (0); ++} ++ ++static int ++fmcd_close(struct cdev *dev, int flags, int fmt, struct thread *td) ++{ ++ return (0); ++} ++ ++/* ++ * PCD device ioctl handler (/dev/fm0-pcd). ++ */ ++static int ++fmcd_pcd_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, ++ struct thread *td) ++{ ++ struct fmcd_softc *sc = dev->si_drv1; ++ int error; ++ ++ /* PCD operations require root */ ++ error = priv_check(td, PRIV_DRIVER); ++ if (error) ++ return (error); ++ ++ if (sc->pcd_handle == NULL) ++ return (ENXIO); ++ ++ switch (cmd) { ++ case FM_PCD_IOC_ENABLE: ++ return (fmcd_ioc_pcd_enable(sc)); ++ case FM_PCD_IOC_DISABLE: ++ return (fmcd_ioc_pcd_disable(sc)); ++ case FM_PCD_IOC_NET_ENV_CHARACTERISTICS_SET: ++ return (fmcd_ioc_net_env_set(sc, data)); ++ case FM_PCD_IOC_NET_ENV_CHARACTERISTICS_DELETE: ++ return (fmcd_ioc_net_env_delete(sc, data)); ++ case FM_PCD_IOC_KG_SCHEME_SET: ++ return (fmcd_ioc_kg_scheme_set(sc, data)); ++ case FM_PCD_IOC_KG_SCHEME_DELETE: ++ return (fmcd_ioc_kg_scheme_delete(sc, data)); ++ case FM_PCD_IOC_CC_ROOT_BUILD: ++ return (fmcd_ioc_cc_root_build(sc, data)); ++ case FM_PCD_IOC_CC_ROOT_DELETE: ++ return (fmcd_ioc_cc_root_delete(sc, data)); ++ case FM_PCD_IOC_HASH_TABLE_SET: ++ return (fmcd_ioc_hash_table_set(sc, data)); ++ case FM_PCD_IOC_HASH_TABLE_DELETE: ++ return (fmcd_ioc_hash_table_delete(sc, data)); ++ case FM_PCD_IOC_MATCH_TABLE_SET: ++ return (fmcd_ioc_match_table_set(sc, data)); ++ case FM_PCD_IOC_MATCH_TABLE_DELETE: ++ return (fmcd_ioc_match_table_delete(sc, data)); ++ case FM_PCD_IOC_MANIP_NODE_SET: ++ return (fmcd_ioc_manip_node_set(sc, data)); ++ case FM_PCD_IOC_MANIP_NODE_DELETE: ++ return (fmcd_ioc_manip_node_delete(sc, data)); ++#if (DPAA_VERSION >= 11) ++ case FM_PCD_IOC_FRM_REPLIC_GROUP_SET: ++ return (fmcd_ioc_frm_replic_set_group(sc, data)); ++ case FM_PCD_IOC_FRM_REPLIC_GROUP_DELETE: ++ return (fmcd_ioc_frm_replic_delete_group(sc, data)); ++#endif ++ case FM_PCD_IOC_PRS_LOAD_SW: ++ return (fmcd_ioc_prs_load_sw(sc, data)); ++ case FM_PCD_IOC_PLCR_PROFILE_SET: ++ return (fmcd_ioc_plcr_profile_set(sc, data)); ++ case FM_PCD_IOC_PLCR_PROFILE_DELETE: ++ return (fmcd_ioc_plcr_profile_delete(sc, data)); ++ case FM_PCD_IOC_SET_ADVANCED_OFFLOAD_SUPPORT: ++ return (FM_PCD_SetAdvancedOffloadSupport(sc->pcd_handle) ++ == E_OK ? 0 : EIO); ++ case FM_PCD_IOC_ALLOW_HC_USAGE: ++ /* HC is already configured by fman.c — just accept */ ++ return (0); ++ default: ++ printf("fmcd: unknown PCD ioctl 0x%lx\n", cmd); ++ return (ENOTTY); ++ } ++} ++ ++/* ++ * FM device ioctl handler (/dev/fm0). ++ */ ++static int ++fmcd_fm_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, ++ struct thread *td) ++{ ++ struct fmcd_softc *sc = dev->si_drv1; ++ ++ switch (cmd) { ++ case FM_IOC_GET_API_VERSION: ++ return (fmcd_ioc_get_api_version(sc, data)); ++ default: ++ printf("fmcd: unknown FM ioctl 0x%lx\n", cmd); ++ return (ENOTTY); ++ } ++} ++ ++/* ++ * Port device ioctl handler (/dev/fm0-port-rx*, /dev/fm0-port-oh*). ++ */ ++static int ++fmcd_port_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, ++ struct thread *td) ++{ ++ struct fmcd_softc *sc = dev->si_drv1; ++ t_Handle h_port = dev->si_drv2; ++ int error; ++ ++ error = priv_check(td, PRIV_DRIVER); ++ if (error) ++ return (error); ++ ++ switch (cmd) { ++ case FM_PORT_IOC_SET_PCD: ++ return (fmcd_ioc_port_set_pcd(sc, h_port, data)); ++ case FM_PORT_IOC_DELETE_PCD: ++ return (fmcd_ioc_port_delete_pcd(sc, h_port)); ++ case FM_PORT_IOC_ENABLE: ++ return (fmcd_ioc_port_enable(sc, h_port)); ++ case FM_PORT_IOC_DISABLE: ++ return (fmcd_ioc_port_disable(sc, h_port)); ++ default: ++ printf("fmcd: unknown PORT ioctl 0x%lx\n", cmd); ++ return (ENOTTY); ++ } ++} ++ ++static struct cdevsw fmcd_fm_cdevsw = { ++ .d_version = D_VERSION, ++ .d_open = fmcd_open, ++ .d_close = fmcd_close, ++ .d_ioctl = fmcd_fm_ioctl, ++ .d_name = "fm", ++}; ++ ++static struct cdevsw fmcd_pcd_cdevsw = { ++ .d_version = D_VERSION, ++ .d_open = fmcd_pcd_open, ++ .d_close = fmcd_pcd_close, ++ .d_ioctl = fmcd_pcd_ioctl, ++ .d_name = "fm-pcd", ++}; ++ ++static struct cdevsw fmcd_port_cdevsw = { ++ .d_version = D_VERSION, ++ .d_open = fmcd_open, ++ .d_close = fmcd_close, ++ .d_ioctl = fmcd_port_ioctl, ++ .d_name = "fm-port", ++}; ++ ++/* ------------------------------------------------------------------ */ ++/* Init / Destroy */ ++/* ------------------------------------------------------------------ */ ++ ++int ++fmcd_init(device_t fman_dev, struct fmcd_softc *sc) ++{ ++ struct fman_softc *fsc; ++ int i; ++ ++ fsc = device_get_softc(fman_dev); ++ ++ memset(sc, 0, sizeof(*sc)); ++ sc->fman_dev = fman_dev; ++ sc->fm_handle = fsc->fm_handle; ++ sc->pcd_handle = fsc->pcd_handle; ++ sc->handle_gen = 1; /* start at 1 so slot 0's first ID != 0 */ ++ ++ sx_init(&sc->port_lock, "fmcd_port"); ++ ++ /* /dev/fman0 */ ++ sc->cdev_fm = make_dev(&fmcd_fm_cdevsw, FMD_MINOR_FM, ++ UID_ROOT, GID_WHEEL, 0600, "fm%d", device_get_unit(fman_dev)); ++ if (sc->cdev_fm == NULL) { ++ device_printf(fman_dev, "fmcd: couldn't create /dev/fm\n"); ++ goto fail; ++ } ++ sc->cdev_fm->si_drv1 = sc; ++ ++ /* /dev/fman0-pcd */ ++ sc->cdev_pcd = make_dev(&fmcd_pcd_cdevsw, FMD_MINOR_PCD, ++ UID_ROOT, GID_WHEEL, 0600, "fm%d-pcd", ++ device_get_unit(fman_dev)); ++ if (sc->cdev_pcd == NULL) { ++ device_printf(fman_dev, ++ "fmcd: couldn't create /dev/fm-pcd\n"); ++ goto fail; ++ } ++ sc->cdev_pcd->si_drv1 = sc; ++ ++ /* ++ * Port devices are created eagerly — the handles are filled in ++ * when dtsec/oh drivers attach via fmcd_register_rx_port/oh_port. ++ */ ++ for (i = 0; i < 8; i++) { ++ sc->cdev_port_rx[i] = make_dev(&fmcd_port_cdevsw, ++ FMD_MINOR_RX_BASE + i, UID_ROOT, GID_WHEEL, 0600, ++ "fm%d-port-rx%d", device_get_unit(fman_dev), i); ++ if (sc->cdev_port_rx[i]) { ++ sc->cdev_port_rx[i]->si_drv1 = sc; ++ sc->cdev_port_rx[i]->si_drv2 = NULL; ++ } ++ } ++ ++ for (i = 0; i < 6; i++) { ++ sc->cdev_port_oh[i] = make_dev(&fmcd_port_cdevsw, ++ FMD_MINOR_OH_BASE + i, UID_ROOT, GID_WHEEL, 0600, ++ "fm%d-port-oh%d", device_get_unit(fman_dev), i); ++ if (sc->cdev_port_oh[i]) { ++ sc->cdev_port_oh[i]->si_drv1 = sc; ++ sc->cdev_port_oh[i]->si_drv2 = NULL; ++ } ++ } ++ ++ device_printf(fman_dev, "fmcd: chardev interface ready\n"); ++ return (0); ++ ++fail: ++ fmcd_destroy(sc); ++ return (ENXIO); ++} ++ ++void ++fmcd_destroy(struct fmcd_softc *sc) ++{ ++ int i; ++ ++ for (i = 0; i < 6; i++) { ++ if (sc->cdev_port_oh[i]) ++ destroy_dev(sc->cdev_port_oh[i]); ++ } ++ for (i = 0; i < 8; i++) { ++ if (sc->cdev_port_rx[i]) ++ destroy_dev(sc->cdev_port_rx[i]); ++ } ++ if (sc->cdev_pcd) ++ destroy_dev(sc->cdev_pcd); ++ if (sc->cdev_fm) ++ destroy_dev(sc->cdev_fm); ++ ++ sx_destroy(&sc->port_lock); ++} +diff --git a/sys/dev/dpaa/fman_chardev.h b/sys/dev/dpaa/fman_chardev.h +new file mode 100644 +index 00000000000..523ba7ad8c0 +--- /dev/null ++++ b/sys/dev/dpaa/fman_chardev.h +@@ -0,0 +1,155 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * All rights reserved. ++ * ++ * FMan character device interface — exposes NCSW PCD API to userspace. ++ * ++ * Ioctl command numbers and data structures are ABI-compatible with the ++ * Linux NXP SDK FMD driver so that the same fmlib/FMC userspace tools ++ * work unchanged. ++ * ++ * Handle management: NCSW returns opaque kernel pointers (t_Handle). ++ * Userspace receives opaque integer handle IDs via a kernel handle ++ * table — kernel pointers are never exposed. The ioc structs have ++ * identical binary layouts to the NCSW structs (with a trailing ++ * void *id field); the kernel translates handle IDs to/from kernel ++ * pointers at the ioctl boundary. ++ * ++ * The ioctl struct definitions come from the fmlib ioctl headers ++ * (fm_pcd_ioctls.h, fm_port_ioctls.h) which are included directly ++ * by fman_chardev.c via the FMCD_COMPILE_CMD include paths. ++ * This header only exposes kernel-private definitions. ++ */ ++ ++#ifndef FMAN_CHARDEV_H_ ++#define FMAN_CHARDEV_H_ ++ ++/* ++ * Device minor number layout. ++ * For FMan instance 0: ++ * minor 0 = /dev/fm0 (FM management) ++ * minor 1 = /dev/fm0-pcd (PCD operations) ++ * minor 2 = /dev/fm0-port-oh0 (OH port, cell-index 3) ++ * minor 3 = /dev/fm0-port-oh1 (OH port, cell-index 4) ++ * minor 8-15 = /dev/fm0-port-rx0..rx7 (RX ports, fmlib convention: ++ * 0-5 = 1G, 6-7 = 10G) ++ */ ++#define FMD_MINOR_FM 0 ++#define FMD_MINOR_PCD 1 ++#define FMD_MINOR_OH_BASE 2 ++#define FMD_MINOR_RX_BASE 8 /* after 6 OH slots */ ++#define FMD_MINOR_MAX 16 /* 8 + 8 RX port slots */ ++ ++/* ------------------------------------------------------------------ */ ++/* Kernel-only: chardev state and functions */ ++/* ------------------------------------------------------------------ */ ++ ++#ifdef _KERNEL ++ ++#include ++#include ++#include ++ ++/* ++ * PCD handle table — maps opaque integer IDs (exposed to userspace) ++ * to kernel pointers (used internally by NCSW). ++ * ++ * Handle ID encoding (uint64_t, same width as void* on arm64): ++ * bits [6:0] = slot index (0..FMCD_MAX_HANDLES-1) ++ * bits [31:7] = generation counter (invalidates stale handles) ++ * bits [63:32] = 0 (ensures ID never resembles a kernel pointer) ++ * ++ * Value 0 is reserved as "invalid/NULL handle". handle_gen starts ++ * at 1 so slot 0's first ID is (1 << 7) | 0 = 128, not 0. ++ */ ++enum fmcd_handle_type { ++ FMCD_HDL_NONE = 0, ++ FMCD_HDL_NET_ENV, ++ FMCD_HDL_KG_SCHEME, ++ FMCD_HDL_CC_ROOT, ++ FMCD_HDL_MATCH_TABLE, ++ FMCD_HDL_HASH_TABLE, ++ FMCD_HDL_MANIP, ++ FMCD_HDL_PLCR_PROFILE, ++ FMCD_HDL_FRM_REPLIC, ++}; ++ ++struct fmcd_handle_entry { ++ t_Handle ptr; /* kernel pointer (NULL = free slot) */ ++ enum fmcd_handle_type type; ++}; ++ ++#define FMCD_MAX_HANDLES 128 ++#define FMCD_HANDLE_MASK 0x7f /* slot index in lower 7 bits */ ++#define FMCD_HANDLE_SHIFT 7 /* generation counter above */ ++ ++/* ++ * Per-FMan chardev state. ++ */ ++struct fmcd_softc { ++ device_t fman_dev; /* parent fman device */ ++ struct cdev *cdev_fm; /* /dev/fm0 */ ++ struct cdev *cdev_pcd; /* /dev/fm0-pcd */ ++ struct cdev *cdev_port_rx[8]; /* /dev/fm0-port-rx[0-7] */ ++ struct cdev *cdev_port_oh[6]; /* /dev/fm0-port-oh[0-5] */ ++ ++ t_Handle fm_handle; /* NCSW FM handle */ ++ t_Handle pcd_handle; /* NCSW PCD handle */ ++ ++ /* Port handle registry — indexed by fmlib convention: ++ * 0-5 = 1G MACs (cell-index 0-5), 6-7 = 10G MACs (cell-index 8-9). ++ * fmcd_cell_to_rxidx() in fman_chardev.c converts DT cell-index. */ ++ struct sx port_lock; ++ t_Handle rx_port_handles[8]; ++ t_Handle rx_port_schemes[8]; /* dtsec KG scheme handles */ ++ t_Handle *rx_port_scheme_ptrs[8]; /* ptr to dtsec sc_scheme */ ++ uint32_t rx_port_fqids[8]; /* dtsec default RX FQIDs */ ++ t_Handle oh_port_handles[6]; ++ ++ /* PCD handle table — protected by port_lock */ ++ struct fmcd_handle_entry handles[FMCD_MAX_HANDLES]; ++ uint32_t handle_gen; /* generation counter */ ++ bool pcd_transferred; /* CDX has taken PCD ownership */ ++}; ++ ++/* ++ * Chardev lifecycle. ++ */ ++int fmcd_init(device_t fman_dev, struct fmcd_softc *sc); ++void fmcd_destroy(struct fmcd_softc *sc); ++ ++/* ++ * Port registration (called by dtsec and dpaa_oh during attach). ++ */ ++void fmcd_register_rx_port(struct fmcd_softc *sc, int index, ++ t_Handle h_port, uint32_t dflt_fqid); ++void fmcd_register_oh_port(struct fmcd_softc *sc, int index, ++ t_Handle h_port); ++uint32_t fmcd_get_rx_dflt_fqid(struct fmcd_softc *sc, int index); ++ ++/* ++ * Register dtsec's KG scheme handle for PCD teardown. ++ * p_scheme points to dtsec_softc->sc_scheme so the chardev can ++ * clear it when userspace takes over PCD management. ++ */ ++void fmcd_register_rx_port_scheme(struct fmcd_softc *sc, int index, ++ t_Handle h_scheme, t_Handle *p_scheme); ++ ++/* ++ * Mark PCD resources as transferred to CDX. After this call, ++ * fmcd_pcd_close() will not attempt to delete NCSW PCD objects. ++ */ ++void fmcd_pcd_mark_transferred(struct fmcd_softc *sc); ++ ++/* ++ * Resolve a handle ID to a kernel pointer (read-only, does not free). ++ * Used by CDX to translate userspace handle IDs to NCSW pointers. ++ */ ++t_Handle fmcd_handle_resolve(struct fmcd_softc *sc, uint64_t id, ++ enum fmcd_handle_type expected_type); ++ ++#endif /* _KERNEL */ ++ ++#endif /* FMAN_CHARDEV_H_ */ +diff --git a/sys/dev/dpaa/fman_fdt.c b/sys/dev/dpaa/fman_fdt.c +index 8fb06924e10..5510f69b0e7 100644 +--- a/sys/dev/dpaa/fman_fdt.c ++++ b/sys/dev/dpaa/fman_fdt.c +@@ -31,6 +31,7 @@ + #include + #include + ++#include + #include + #include + #include +@@ -62,8 +63,11 @@ static device_method_t fman_methods[] = { + + DEFINE_CLASS_1(fman, fman_driver, fman_methods, + sizeof(struct fman_softc), simplebus_driver); ++/* Probe after GIC (BUS_PASS_INTERRUPT + BUS_PASS_ORDER_MIDDLE = 45) ++ * so interrupt allocation works on the first attempt. ++ * Also after clockgen (BUS_PASS_BUS + BUS_PASS_ORDER_MIDDLE) for clk_get_freq(). */ + EARLY_DRIVER_MODULE(fman, simplebus, fman_driver, 0, 0, +- BUS_PASS_BUS + BUS_PASS_ORDER_MIDDLE); ++ BUS_PASS_INTERRUPT + BUS_PASS_ORDER_LAST); + + + static int +@@ -87,18 +91,29 @@ fman_get_clock(struct fman_softc *sc) + device_t dev; + phandle_t node; + pcell_t fman_clock; ++ clk_t clk; ++ uint64_t freq; + + dev = sc->sc_base.dev; + node = ofw_bus_get_node(dev); + ++ /* Try static clock-frequency property first (PowerPC style) */ + if ((OF_getprop(node, "clock-frequency", &fman_clock, +- sizeof(fman_clock)) <= 0) || (fman_clock == 0)) { +- device_printf(dev, "could not acquire correct frequency " +- "from DTS\n"); +- +- return (0); ++ sizeof(fman_clock)) > 0) && (fman_clock != 0)) ++ return ((uint32_t)fman_clock); ++ ++ /* Fall back to clock framework (ARM64 style) */ ++ if (clk_get_by_ofw_index(dev, node, 0, &clk) == 0) { ++ if (clk_enable(clk) == 0 && ++ clk_get_freq(clk, &freq) == 0 && freq != 0) { ++ device_printf(dev, "FMan clock: %ju Hz\n", ++ (uintmax_t)freq); ++ return ((uint32_t)freq); ++ } ++ clk_release(clk); + } + +- return ((uint32_t)fman_clock); ++ device_printf(dev, "could not acquire correct frequency from DTS\n"); ++ return (0); + } + +diff --git a/sys/dev/dpaa/if_dtsec.c b/sys/dev/dpaa/if_dtsec.c +index dfa76a47662..e98e2321f3e 100644 +--- a/sys/dev/dpaa/if_dtsec.c ++++ b/sys/dev/dpaa/if_dtsec.c +@@ -55,12 +55,23 @@ + + #include "miibus_if.h" + ++#include "opt_dpaa.h" ++ + #include + #include + #include ++#include ++#if (DPAA_VERSION < 11) ++#include ++#endif + #include + + #include "fman.h" ++#include "bman.h" ++ ++/* FM port internal header — needed for RCCB register access in stall diag */ ++#include ++#include "qman.h" + #include "if_dtsec.h" + #include "if_dtsec_im.h" + #include "if_dtsec_rm.h" +@@ -68,7 +79,12 @@ + #define DTSEC_MIN_FRAME_SIZE 64 + #define DTSEC_MAX_FRAME_SIZE 9600 + ++#if (DPAA_VERSION < 11) + #define DTSEC_REG_MAXFRM 0x110 ++#define DTSEC_REG_GADDR(i) (0x0a0 + 4*(i)) ++#else ++#define MEMAC_REG_MAXFRM 0x014 ++#endif + + /** + * @group dTSEC private defines. +@@ -156,7 +172,7 @@ dtsec_fm_mac_mdio_event_callback(t_Handle h_App, + struct dtsec_softc *sc; + + sc = h_App; +- device_printf(sc->sc_dev, "MDIO event %i: %s.\n", exception, ++ if_printf(sc->sc_ifnet, "MDIO event %i: %s.\n", exception, + dtsec_fm_mac_ex_to_str(exception)); + } + +@@ -166,7 +182,7 @@ dtsec_fm_mac_exception_callback(t_Handle app, e_FmMacExceptions exception) + struct dtsec_softc *sc; + + sc = app; +- device_printf(sc->sc_dev, "MAC exception %i: %s.\n", exception, ++ if_printf(sc->sc_ifnet, "MAC exception %i: %s.\n", exception, + dtsec_fm_mac_ex_to_str(exception)); + } + +@@ -214,7 +230,9 @@ dtsec_fm_mac_init(struct dtsec_softc *sc, uint8_t *mac) + return (ENXIO); + } + +- /* Do not inform about pause frames */ ++#if (DPAA_VERSION < 11) ++ /* Do not inform about pause frames (dTSEC only; MEMAC has no ++ * equivalent interrupt — it simply never generates this event). */ + error = FM_MAC_ConfigException(sc->sc_mach, e_FM_MAC_EX_1G_RX_CTL, + FALSE); + if (error != E_OK) { +@@ -223,6 +241,7 @@ dtsec_fm_mac_init(struct dtsec_softc *sc, uint8_t *mac) + dtsec_fm_mac_free(sc); + return (ENXIO); + } ++#endif + + error = FM_MAC_Init(sc->sc_mach); + if (error != E_OK) { +@@ -232,6 +251,18 @@ dtsec_fm_mac_init(struct dtsec_softc *sc, uint8_t *mac) + return (ENXIO); + } + ++ /* Diagnostic: dump MEMAC IF_MODE and IF_STATUS registers */ ++ { ++ uint32_t ifmode = be32toh(bus_read_4(sc->sc_mem, 0x300)); ++ uint32_t ifstat = be32toh(bus_read_4(sc->sc_mem, 0x304)); ++ device_printf(sc->sc_dev, ++ "MEMAC IF_MODE=0x%08x IF_STATUS=0x%08x mode=%s\n", ++ ifmode, ifstat, ++ (ifmode & 0x3) == 0 ? "XGMII(10G)" : ++ (ifmode & 0x3) == 2 ? "GMII(1G)" : ++ (ifmode & 0x3) == 4 ? "RGMII" : "unknown"); ++ } ++ + return (0); + } + /** @} */ +@@ -260,7 +291,7 @@ dtsec_fm_port_rx_exception_callback(t_Handle app, + struct dtsec_softc *sc; + + sc = app; +- device_printf(sc->sc_dev, "RX exception: %i: %s.\n", exception, ++ if_printf(sc->sc_ifnet, "RX exception: %i: %s.\n", exception, + dtsec_fm_port_ex_to_str(exception)); + } + +@@ -271,7 +302,7 @@ dtsec_fm_port_tx_exception_callback(t_Handle app, + struct dtsec_softc *sc; + + sc = app; +- device_printf(sc->sc_dev, "TX exception: %i: %s.\n", exception, ++ if_printf(sc->sc_ifnet, "TX exception: %i: %s.\n", exception, + dtsec_fm_port_ex_to_str(exception)); + } + +@@ -305,6 +336,11 @@ dtsec_fm_port_tx_type(enum eth_dev_type type) + static void + dtsec_fm_port_free_both(struct dtsec_softc *sc) + { ++ if (sc->sc_vsph) { ++ FM_VSP_Free(sc->sc_vsph); ++ sc->sc_vsph = NULL; ++ } ++ + if (sc->sc_rxph) { + FM_PORT_Free(sc->sc_rxph); + sc->sc_rxph = NULL; +@@ -331,13 +367,50 @@ dtsec_set_mtu(struct dtsec_softc *sc, unsigned int mtu) + DTSEC_LOCK_ASSERT(sc); + + if (mtu >= DTSEC_MIN_FRAME_SIZE && mtu <= DTSEC_MAX_FRAME_SIZE) { ++#if (DPAA_VERSION < 11) + bus_write_4(sc->sc_mem, DTSEC_REG_MAXFRM, mtu); ++#else ++ bus_write_4(sc->sc_mem, MEMAC_REG_MAXFRM, ++ htobe32((uint32_t)mtu)); ++#endif + return (mtu); + } + + return (0); + } + ++static u_int ++dtsec_hash_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt) ++{ ++ struct dtsec_softc *sc = arg; ++ ++ FM_MAC_AddHashMacAddr(sc->sc_mach, (t_EnetAddr *)LLADDR(sdl)); ++ ++ return (1); ++} ++ ++static void ++dtsec_setup_multicast(struct dtsec_softc *sc) ++{ ++#if (DPAA_VERSION < 11) ++ int i; ++ ++ if (if_getflags(sc->sc_ifnet) & IFF_ALLMULTI) { ++ for (i = 0; i < 8; i++) ++ bus_write_4(sc->sc_mem, DTSEC_REG_GADDR(i), 0xFFFFFFFF); ++ ++ return; ++ } ++ ++ fman_dtsec_reset_filter_table(rman_get_virtual(sc->sc_mem), ++ true, false); ++#else ++ /* mEMAC: no hash reset API — SetPromiscuous(false) clears filter */ ++ FM_MAC_SetPromiscuous(sc->sc_mach, false); ++#endif ++ if_foreach_llmaddr(sc->sc_ifnet, dtsec_hash_maddr, sc); ++} ++ + static int + dtsec_if_enable_locked(struct dtsec_softc *sc) + { +@@ -357,6 +430,8 @@ dtsec_if_enable_locked(struct dtsec_softc *sc) + if (error != E_OK) + return (EIO); + ++ dtsec_setup_multicast(sc); ++ + if_setdrvflagbits(sc->sc_ifnet, IFF_DRV_RUNNING, 0); + + /* Refresh link state */ +@@ -423,10 +498,39 @@ dtsec_if_ioctl(if_t ifp, u_long command, caddr_t data) + + case SIOCGIFMEDIA: + case SIOCSIFMEDIA: +- error = ifmedia_ioctl(ifp, ifr, &sc->sc_mii->mii_media, +- command); ++ if (sc->sc_mii != NULL) ++ error = ifmedia_ioctl(ifp, ifr, ++ &sc->sc_mii->mii_media, command); ++ else ++ error = ENOTTY; + break; + ++ case SIOCSIFCAP: { ++ int mask; ++ ++ mask = ifr->ifr_reqcap ^ if_getcapenable(ifp); ++ ++ if (mask & IFCAP_TXCSUM) { ++ if_togglecapenable(ifp, IFCAP_TXCSUM); ++ if (if_getcapenable(ifp) & IFCAP_TXCSUM) ++ if_sethwassist(ifp, if_gethwassist(ifp) | ++ (CSUM_IP | CSUM_IP_TCP | CSUM_IP_UDP)); ++ else ++ if_sethwassist(ifp, if_gethwassist(ifp) & ++ ~(CSUM_IP | CSUM_IP_TCP | CSUM_IP_UDP)); ++ } ++ if (mask & IFCAP_TXCSUM_IPV6) { ++ if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6); ++ if (if_getcapenable(ifp) & IFCAP_TXCSUM_IPV6) ++ if_sethwassist(ifp, if_gethwassist(ifp) | ++ (CSUM_IP6_TCP | CSUM_IP6_UDP)); ++ else ++ if_sethwassist(ifp, if_gethwassist(ifp) & ++ ~(CSUM_IP6_TCP | CSUM_IP6_UDP)); ++ } ++ break; ++ } ++ + default: + error = ether_ioctl(ifp, command, data); + } +@@ -441,10 +545,11 @@ dtsec_if_tick(void *arg) + + sc = arg; + +- /* TODO */ + DTSEC_LOCK(sc); + +- mii_tick(sc->sc_mii); ++ if (sc->sc_mii != NULL) ++ mii_tick(sc->sc_mii); ++ + callout_reset(&sc->sc_tick_callout, hz, dtsec_if_tick, sc); + + DTSEC_UNLOCK(sc); +@@ -472,13 +577,12 @@ dtsec_if_init_locked(struct dtsec_softc *sc) + error = FM_MAC_ModifyMacAddr(sc->sc_mach, + (t_EnetAddr *)if_getlladdr(sc->sc_ifnet)); + if (error != E_OK) { +- device_printf(sc->sc_dev, "couldn't set MAC address.\n"); ++ if_printf(sc->sc_ifnet, "couldn't set MAC address.\n"); + goto err; + } + +- /* Start MII polling */ +- if (sc->sc_mii) +- callout_reset(&sc->sc_tick_callout, hz, dtsec_if_tick, sc); ++ /* Start MII polling / periodic diagnostics */ ++ callout_reset(&sc->sc_tick_callout, hz, dtsec_if_tick, sc); + + if (if_getflags(sc->sc_ifnet) & IFF_UP) { + error = dtsec_if_enable_locked(sc); +@@ -494,7 +598,7 @@ dtsec_if_init_locked(struct dtsec_softc *sc) + + err: + dtsec_if_deinit_locked(sc); +- device_printf(sc->sc_dev, "initialization error.\n"); ++ if_printf(sc->sc_ifnet, "initialization error.\n"); + return; + } + +@@ -521,6 +625,12 @@ dtsec_if_start(if_t ifp) + DTSEC_UNLOCK(sc); + } + ++static void ++dtsec_if_qflush(if_t ifp) ++{ ++ /* No software queue — nothing to flush */ ++} ++ + static void + dtsec_if_watchdog(if_t ifp) + { +@@ -539,7 +649,8 @@ dtsec_ifmedia_upd(if_t ifp) + struct dtsec_softc *sc = if_getsoftc(ifp); + + DTSEC_LOCK(sc); +- mii_mediachg(sc->sc_mii); ++ if (sc->sc_mii != NULL) ++ mii_mediachg(sc->sc_mii); + DTSEC_UNLOCK(sc); + + return (0); +@@ -552,10 +663,15 @@ dtsec_ifmedia_sts(if_t ifp, struct ifmediareq *ifmr) + + DTSEC_LOCK(sc); + +- mii_pollstat(sc->sc_mii); +- +- ifmr->ifm_active = sc->sc_mii->mii_media_active; +- ifmr->ifm_status = sc->sc_mii->mii_media_status; ++ if (sc->sc_mii != NULL) { ++ mii_pollstat(sc->sc_mii); ++ ifmr->ifm_active = sc->sc_mii->mii_media_active; ++ ifmr->ifm_status = sc->sc_mii->mii_media_status; ++ } else { ++ /* 10G port with no PHY — report fixed 10G media, always up */ ++ ifmr->ifm_active = IFM_ETHER | IFM_10G_SR | IFM_FDX; ++ ifmr->ifm_status = IFM_AVALID | IFM_ACTIVE; ++ } + + DTSEC_UNLOCK(sc); + } +@@ -580,7 +696,7 @@ dtsec_configure_mode(struct dtsec_softc *sc) + if (sc->sc_mode == DTSEC_MODE_REGULAR) { + sc->sc_port_rx_init = dtsec_rm_fm_port_rx_init; + sc->sc_port_tx_init = dtsec_rm_fm_port_tx_init; +- sc->sc_start_locked = dtsec_rm_if_start_locked; ++ /* RM uses if_transmit, no sc_start_locked needed */ + } else { + sc->sc_port_rx_init = dtsec_im_fm_port_rx_init; + sc->sc_port_tx_init = dtsec_im_fm_port_tx_init; +@@ -591,6 +707,129 @@ dtsec_configure_mode(struct dtsec_softc *sc) + (sc->sc_mode == DTSEC_MODE_REGULAR) ? "regular" : "independent"); + } + ++static int ++dtsec_sysctl_bman_free(SYSCTL_HANDLER_ARGS) ++{ ++ struct dtsec_softc *sc = (struct dtsec_softc *)arg1; ++ uint32_t count; ++ ++ if (sc->sc_rx_pool == NULL) ++ count = 0; ++ else ++ count = bman_count(sc->sc_rx_pool); ++ ++ return (sysctl_handle_int(oidp, &count, 0, req)); ++} ++ ++static int ++dtsec_sysctl_diag(SYSCTL_HANDLER_ARGS) ++{ ++ struct dtsec_softc *sc = (struct dtsec_softc *)arg1; ++ int val = 0; ++ int error; ++ ++ error = sysctl_handle_int(oidp, &val, 0, req); ++ if (error || req->newptr == NULL) ++ return (error); ++ ++ if (val != 0) { ++ uint32_t bcount = sc->sc_rx_pool ? ++ bman_count(sc->sc_rx_pool) : 0; ++ printf("%s: DIAG bman_free=%u bman_total=%u bpid=%u " ++ "rx_fqid=%u\n", ++ if_name(sc->sc_ifnet), bcount, ++ sc->sc_rx_buf_total, sc->sc_rx_bpid, ++ sc->sc_rx_fqr[0] ? qman_fqr_get_base_fqid(sc->sc_rx_fqr[0]) : 0); ++ qman_portal_dqrr_diag(); ++ if (sc->sc_rxph != NULL) { ++ printf("%s: FMan RX: frame=%u discard=%u " ++ "bad=%u filter=%u oobd=%u enq=%u\n", ++ if_name(sc->sc_ifnet), ++ FM_PORT_GetCounter(sc->sc_rxph, ++ e_FM_PORT_COUNTERS_FRAME), ++ FM_PORT_GetCounter(sc->sc_rxph, ++ e_FM_PORT_COUNTERS_DISCARD_FRAME), ++ FM_PORT_GetCounter(sc->sc_rxph, ++ e_FM_PORT_COUNTERS_RX_BAD_FRAME), ++ FM_PORT_GetCounter(sc->sc_rxph, ++ e_FM_PORT_COUNTERS_RX_FILTER_FRAME), ++ FM_PORT_GetCounter(sc->sc_rxph, ++ e_FM_PORT_COUNTERS_RX_OUT_OF_BUFFERS_DISCARD), ++ FM_PORT_GetCounter(sc->sc_rxph, ++ e_FM_PORT_COUNTERS_ENQ_TOTAL)); ++ } ++ if (sc->sc_txph != NULL) { ++ printf("%s: FMan TX: frame=%u discard=%u " ++ "len_err=%u unsup=%u deq=%u deq_dflt=%u " ++ "deq_conf=%u\n", ++ if_name(sc->sc_ifnet), ++ FM_PORT_GetCounter(sc->sc_txph, ++ e_FM_PORT_COUNTERS_FRAME), ++ FM_PORT_GetCounter(sc->sc_txph, ++ e_FM_PORT_COUNTERS_DISCARD_FRAME), ++ FM_PORT_GetCounter(sc->sc_txph, ++ e_FM_PORT_COUNTERS_LENGTH_ERR), ++ FM_PORT_GetCounter(sc->sc_txph, ++ e_FM_PORT_COUNTERS_UNSUPPRTED_FORMAT), ++ FM_PORT_GetCounter(sc->sc_txph, ++ e_FM_PORT_COUNTERS_DEQ_TOTAL), ++ FM_PORT_GetCounter(sc->sc_txph, ++ e_FM_PORT_COUNTERS_DEQ_FROM_DEFAULT), ++ FM_PORT_GetCounter(sc->sc_txph, ++ e_FM_PORT_COUNTERS_DEQ_CONFIRM)); ++ } ++ if (sc->sc_mach != NULL) { ++ t_FmMacStatistics ms; ++ if (FM_MAC_GetStatistics(sc->sc_mach, &ms) == E_OK) { ++ printf("%s: MAC: rxPkts=%llu rxBytes=%llu " ++ "rxDiscard=%llu rxErr=%llu " ++ "txPkts=%llu txBytes=%llu " ++ "txErr=%llu\n", ++ if_name(sc->sc_ifnet), ++ (unsigned long long)ms.ifInPkts, ++ (unsigned long long)ms.ifInOctets, ++ (unsigned long long)ms.ifInDiscards, ++ (unsigned long long)ms.ifInErrors, ++ (unsigned long long)ms.ifOutPkts, ++ (unsigned long long)ms.ifOutOctets, ++ (unsigned long long)ms.ifOutErrors); ++ } ++ } ++ } ++ ++ return (0); ++} ++ ++static uint64_t ++dtsec_get_counter(if_t ifp, ift_counter cnt) ++{ ++ struct dtsec_softc *sc = if_getsoftc(ifp); ++ t_FmMacStatistics ms; ++ ++ if (sc->sc_mach != NULL && ++ FM_MAC_GetStatistics(sc->sc_mach, &ms) == E_OK) { ++ switch (cnt) { ++ case IFCOUNTER_IPACKETS: ++ return (ms.ifInPkts); ++ case IFCOUNTER_OPACKETS: ++ return (ms.ifOutPkts); ++ case IFCOUNTER_IBYTES: ++ return (ms.ifInOctets); ++ case IFCOUNTER_OBYTES: ++ return (ms.ifOutOctets); ++ case IFCOUNTER_IERRORS: ++ return (ms.ifInErrors); ++ case IFCOUNTER_OERRORS: ++ return (ms.ifOutErrors); ++ case IFCOUNTER_IMCASTS: ++ return (ms.ifInMcastPkts); ++ default: ++ break; ++ } ++ } ++ return (if_get_counter_default(ifp, cnt)); ++} ++ + int + dtsec_attach(device_t dev) + { +@@ -629,6 +868,9 @@ dtsec_attach(device_t dev) + if ((error = fman_get_bushandle(parent, &sc->sc_fm_base)) != 0) + return (error); + ++ fman_get_pcd_handle(parent, &sc->sc_pcdh); ++ fman_get_netenv_handle(parent, &sc->sc_netenvh); ++ + /* Configure working mode */ + dtsec_configure_mode(sc); + +@@ -676,21 +918,33 @@ dtsec_attach(device_t dev) + return (ENXIO); + } + ++ if (sc->sc_mode == DTSEC_MODE_REGULAR) { ++ error = dtsec_rm_pcd_init(sc); ++ if (error != 0) ++ device_printf(dev, ++ "PCD init failed, continuing without RSS\n"); ++ } ++ + /* Create network interface for upper layers */ + ifp = sc->sc_ifnet = if_alloc(IFT_ETHER); + if_setsoftc(ifp, sc); + +- if_setflags(ifp, IFF_SIMPLEX | IFF_BROADCAST); ++ if_setflags(ifp, IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST); + if_setinitfn(ifp, dtsec_if_init); +- if_setstartfn(ifp, dtsec_if_start); + if_setioctlfn(ifp, dtsec_if_ioctl); +- if_setsendqlen(ifp, IFQ_MAXLEN); ++ if_setgetcounterfn(ifp, dtsec_get_counter); + +- if (sc->sc_phy_addr >= 0) +- if_initname(ifp, device_get_name(sc->sc_dev), +- device_get_unit(sc->sc_dev)); +- else +- if_initname(ifp, "dtsec_phy", device_get_unit(sc->sc_dev)); ++ if (sc->sc_mode == DTSEC_MODE_REGULAR) { ++ /* Modern if_transmit: per-CPU TX FQs, no locks, no sendq */ ++ if_settransmitfn(ifp, dtsec_rm_if_transmit); ++ if_setqflushfn(ifp, dtsec_if_qflush); ++ } else { ++ /* Legacy if_start for Independent Mode */ ++ if_setstartfn(ifp, dtsec_if_start); ++ if_setsendqlen(ifp, IFQ_MAXLEN); ++ } ++ ++ if_initname(ifp, "dtsec", device_get_unit(sc->sc_dev)); + + /* TODO */ + #if 0 +@@ -698,22 +952,59 @@ dtsec_attach(device_t dev) + if_setsendqready(ifp); + #endif + ++ if_setcapabilities(ifp, IFCAP_JUMBO_MTU | IFCAP_VLAN_MTU ++ | IFCAP_TXCSUM | IFCAP_TXCSUM_IPV6 ++ | IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6); + if_setcapenable(ifp, if_getcapabilities(ifp)); +- +- /* Attach PHY(s) */ +- error = mii_attach(sc->sc_dev, &sc->sc_mii_dev, ifp, dtsec_ifmedia_upd, +- dtsec_ifmedia_sts, BMSR_DEFCAPMASK, sc->sc_phy_addr, +- MII_OFFSET_ANY, 0); +- if (error) { +- device_printf(sc->sc_dev, "attaching PHYs failed: %d\n", error); +- dtsec_detach(sc->sc_dev); +- return (error); ++ if_sethwassist(ifp, CSUM_IP | CSUM_IP_TCP | CSUM_IP_UDP | ++ CSUM_IP6_TCP | CSUM_IP6_UDP); ++ ++ /* Attach PHY(s) — skip for 10G ports with no external PHY ++ * (SFP+ uses in-band status, sc_phy_addr set to -1). */ ++ if (sc->sc_phy_addr >= 0) { ++ error = mii_attach(sc->sc_dev, &sc->sc_mii_dev, ifp, ++ dtsec_ifmedia_upd, dtsec_ifmedia_sts, BMSR_DEFCAPMASK, ++ sc->sc_phy_addr, MII_OFFSET_ANY, 0); ++ if (error) { ++ if_printf(sc->sc_ifnet, "attaching PHYs failed: " ++ "%d\n", error); ++ dtsec_detach(sc->sc_dev); ++ return (error); ++ } ++ sc->sc_mii = device_get_softc(sc->sc_mii_dev); + } +- sc->sc_mii = device_get_softc(sc->sc_mii_dev); + + /* Attach to stack */ + ether_ifattach(ifp, sc->sc_mac_addr); + ++ /* Set baudrate */ ++ if (sc->sc_eth_dev_type == ETH_10GSEC) ++ if_setbaudrate(ifp, IF_Gbps(10ULL)); ++ else ++ if_setbaudrate(ifp, IF_Gbps(1ULL)); ++ ++ /* 10G SFP+ direct-attach: link is always up (no PHY) */ ++ if (sc->sc_phy_addr < 0) ++ if_link_state_change(ifp, LINK_STATE_UP); ++ ++ /* Add diagnostic sysctls */ ++ if (sc->sc_mode == DTSEC_MODE_REGULAR) { ++ struct sysctl_ctx_list *ctx; ++ struct sysctl_oid *tree; ++ ++ ctx = device_get_sysctl_ctx(dev); ++ tree = device_get_sysctl_tree(dev); ++ ++ SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, ++ "bman_free", CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, ++ sc, 0, dtsec_sysctl_bman_free, "IU", ++ "BMan free buffer count"); ++ SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, ++ "diag", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, ++ sc, 0, dtsec_sysctl_diag, "I", ++ "Write 1 to dump DQRR + BMan state to dmesg"); ++ } ++ + return (0); + } + +@@ -740,6 +1031,9 @@ dtsec_detach(device_t dev) + } + + if (sc->sc_mode == DTSEC_MODE_REGULAR) { ++ /* Free PCD (must happen before port free) */ ++ dtsec_rm_pcd_free(sc); ++ + /* Free RX/TX FQRs */ + dtsec_rm_fqr_rx_free(sc); + dtsec_rm_fqr_tx_free(sc); +@@ -820,6 +1114,9 @@ dtsec_miibus_statchg(device_t dev) + + DTSEC_LOCK_ASSERT(sc); + ++ if (sc->sc_mii == NULL) ++ return; /* 10G port, no PHY — nothing to adjust */ ++ + duplex = ((sc->sc_mii->mii_media_active & IFM_GMASK) == IFM_FDX); + + switch (IFM_SUBTYPE(sc->sc_mii->mii_media_active)) { +@@ -842,6 +1139,6 @@ dtsec_miibus_statchg(device_t dev) + + error = FM_MAC_AdjustLink(sc->sc_mach, speed, duplex); + if (error != E_OK) +- device_printf(sc->sc_dev, "error while adjusting MAC speed.\n"); ++ if_printf(sc->sc_ifnet, "error while adjusting MAC speed.\n"); + } + /** @} */ +diff --git a/sys/dev/dpaa/if_dtsec.h b/sys/dev/dpaa/if_dtsec.h +index 4de0b776e9f..2e50a3a22f4 100644 +--- a/sys/dev/dpaa/if_dtsec.h ++++ b/sys/dev/dpaa/if_dtsec.h +@@ -27,6 +27,8 @@ + #ifndef IF_DTSEC_H_ + #define IF_DTSEC_H_ + ++#include "opt_dpaa.h" ++ + /** + * @group dTSEC common API. + * @{ +@@ -34,6 +36,9 @@ + #define DTSEC_MODE_REGULAR 0 + #define DTSEC_MODE_INDEPENDENT 1 + ++#define DTSEC_TX_NUM_FQS 4 /* One per CPU (LS1046A quad-core) */ ++#define DTSEC_RX_NUM_FQS 128 /* RSS hash distribution (power of 2) */ ++ + #define DTSEC_LOCK(sc) mtx_lock(&(sc)->sc_lock) + #define DTSEC_UNLOCK(sc) mtx_unlock(&(sc)->sc_lock) + #define DTSEC_LOCK_ASSERT(sc) mtx_assert(&(sc)->sc_lock, MA_OWNED) +@@ -65,6 +70,7 @@ struct dtsec_softc { + /* dTSEC data */ + enum eth_dev_type sc_eth_dev_type; + uint8_t sc_eth_id; /* Ethernet ID within its frame manager */ ++ uint8_t sc_mac_cell_index; /* raw DT cell-index */ + uintptr_t sc_mac_mem_offset; + e_EnetMode sc_mac_enet_mode; + int sc_mac_mdio_irq; +@@ -97,20 +103,38 @@ struct dtsec_softc { + uint8_t sc_rx_bpid; + uma_zone_t sc_rx_zone; + char sc_rx_zname[64]; ++ uint32_t sc_rx_buf_total; /* total buffers alloc'd from UMA */ + +- /* RX Frame Queue */ +- t_Handle sc_rx_fqr; ++ /* RX Frame Queues — RSS hash distribution via dedicated channels */ ++ t_Handle sc_rx_fqr[DTSEC_RX_NUM_FQS]; + uint32_t sc_rx_fqid; + +- /* TX Frame Queue */ +- t_Handle sc_tx_fqr; +- bool sc_tx_fqr_full; ++ /* Per-CPU TX Frame Queues */ ++ t_Handle sc_tx_fqs[DTSEC_TX_NUM_FQS]; ++ volatile int sc_tx_inflight[DTSEC_TX_NUM_FQS]; ++ ++ /* TX Confirmation Frame Queue (single, on pool channel) */ + t_Handle sc_tx_conf_fqr; + uint32_t sc_tx_conf_fqid; + + /* Frame Info Zone */ + uma_zone_t sc_fi_zone; + char sc_fi_zname[64]; ++ ++ /* TX buffer prefix data offset (from FM_PORT_GetBufferDataOffset) */ ++ uint32_t sc_tx_data_offset; ++ ++ /* SG table buffer zone (prefix + SG entries) */ ++ uma_zone_t sc_sgt_zone; ++ char sc_sgt_zname[64]; ++ uint32_t sc_sgt_buf_size; ++ ++ /* PCD (Parse-Classify-Distribute) for RSS + RX checksum */ ++ t_Handle sc_pcdh; ++ t_Handle sc_netenvh; ++ t_Handle sc_scheme; ++ uint32_t sc_rx_data_offset; ++ t_Handle sc_vsph; /* default VSP handle */ + }; + /** @} */ + +@@ -124,7 +148,7 @@ enum dtsec_fm_port_params { + FM_PORT_LIODN_OFFSET = 0, + FM_PORT_MEM_ID = 0, + FM_PORT_MEM_ATTR = MEMORY_ATTR_CACHEABLE, +- FM_PORT_BUFFER_SIZE = MCLBYTES, ++ FM_PORT_BUFFER_SIZE = (9600 + 64), /* DTSEC_MAX_FRAME_SIZE + headroom */ + }; + + e_FmPortType dtsec_fm_port_rx_type(enum eth_dev_type type); +diff --git a/sys/dev/dpaa/if_dtsec_fdt.c b/sys/dev/dpaa/if_dtsec_fdt.c +index f2f61777fbe..a38c8dc3b5b 100644 +--- a/sys/dev/dpaa/if_dtsec_fdt.c ++++ b/sys/dev/dpaa/if_dtsec_fdt.c +@@ -35,7 +35,9 @@ + + #include + ++#ifdef __powerpc__ + #include ++#endif + + #include + #include +@@ -100,11 +102,11 @@ dtsec_fdt_probe(device_t dev) + return (ENXIO); + + if (!ofw_bus_is_compatible(dev, "fsl,fman-dtsec") && +- !ofw_bus_is_compatible(dev, "fsl,fman-xgec")) ++ !ofw_bus_is_compatible(dev, "fsl,fman-xgec") && ++ !ofw_bus_is_compatible(dev, "fsl,fman-memac")) + return (ENXIO); + +- device_set_desc(dev, "Freescale Data Path Triple Speed Ethernet " +- "Controller"); ++ device_set_desc(dev, "Freescale Data Path Ethernet Controller"); + + return (BUS_PROBE_DEFAULT); + } +@@ -116,7 +118,7 @@ dtsec_fdt_attach(device_t dev) + device_t phy_dev; + phandle_t enet_node, phy_node; + phandle_t fman_rxtx_node[2]; +- char phy_type[6]; ++ char phy_type[16]; + pcell_t fman_tx_cell, mac_id; + int rid; + +@@ -130,26 +132,47 @@ dtsec_fdt_attach(device_t dev) + return (ENXIO); + } + +- /* Get link speed */ +- if (ofw_bus_is_compatible(dev, "fsl,fman-dtsec") != 0) ++ /* Determine MAC type / link speed */ ++ if (ofw_bus_is_compatible(dev, "fsl,fman-memac") != 0) { ++ /* mEMAC: detect 10G from phy-connection-type */ ++ if (OF_getprop(enet_node, "phy-connection-type", ++ (void *)phy_type, sizeof(phy_type)) > 0 && ++ (!strcmp(phy_type, "xgmii") || ++ !strcmp(phy_type, "10gbase-r"))) ++ sc->sc_eth_dev_type = ETH_10GSEC; ++ else ++ sc->sc_eth_dev_type = ETH_DTSEC; ++ } else if (ofw_bus_is_compatible(dev, "fsl,fman-dtsec") != 0) + sc->sc_eth_dev_type = ETH_DTSEC; + else if (ofw_bus_is_compatible(dev, "fsl,fman-xgec") != 0) + sc->sc_eth_dev_type = ETH_10GSEC; +- else ++ else { ++ device_printf(dev, "unknown MAC compatible\n"); + return(ENXIO); ++ } + + /* Get PHY address */ +- if (OF_getprop(enet_node, "phy-handle", (void *)&phy_node, +- sizeof(phy_node)) <= 0) ++ if (OF_getencprop(enet_node, "phy-handle", (void *)&phy_node, ++ sizeof(phy_node)) <= 0) { ++ /* 10G ports may use managed="in-band-status" with no PHY */ ++ if (sc->sc_eth_dev_type == ETH_10GSEC) { ++ sc->sc_phy_addr = -1; ++ sc->sc_mdio = NULL; ++ goto skip_phy; ++ } ++ device_printf(dev, "missing phy-handle\n"); + return (ENXIO); ++ } + + phy_node = OF_node_from_xref(phy_node); + +- if (OF_getprop(phy_node, "reg", (void *)&sc->sc_phy_addr, +- sizeof(sc->sc_phy_addr)) <= 0) ++ if (OF_getencprop(phy_node, "reg", (void *)&sc->sc_phy_addr, ++ sizeof(sc->sc_phy_addr)) <= 0) { ++ device_printf(dev, "missing phy reg\n"); + return (ENXIO); ++ } + +- phy_dev = OF_device_from_xref(OF_parent(phy_node)); ++ phy_dev = OF_device_from_xref(OF_xref_from_node(OF_parent(phy_node))); + + if (phy_dev == NULL) { + device_printf(dev, "No PHY found.\n"); +@@ -157,68 +180,106 @@ dtsec_fdt_attach(device_t dev) + } + + sc->sc_mdio = phy_dev; ++skip_phy: + + /* Get MAC memory offset in SoC */ + rid = 0; + sc->sc_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE); +- if (sc->sc_mem == NULL) ++ if (sc->sc_mem == NULL) { ++ device_printf(dev, "could not alloc memory resource\n"); + return (ENXIO); ++ } + + /* Get PHY connection type */ + if (OF_getprop(enet_node, "phy-connection-type", (void *)phy_type, +- sizeof(phy_type)) <= 0) ++ sizeof(phy_type)) <= 0) { ++ device_printf(dev, "missing phy-connection-type\n"); + return (ENXIO); ++ } + + if (!strcmp(phy_type, "sgmii")) + sc->sc_mac_enet_mode = e_ENET_MODE_SGMII_1000; + else if (!strcmp(phy_type, "rgmii")) + sc->sc_mac_enet_mode = e_ENET_MODE_RGMII_1000; + else if (!strcmp(phy_type, "xgmii")) +- /* We set 10 Gigabit mode flag however we don't support it */ + sc->sc_mac_enet_mode = e_ENET_MODE_XGMII_10000; +- else ++ else if (!strcmp(phy_type, "10gbase-r")) ++ sc->sc_mac_enet_mode = e_ENET_MODE_XGMII_10000; ++ else { ++ device_printf(dev, "unsupported phy-connection-type: %s\n", ++ phy_type); + return (ENXIO); ++ } + + if (OF_getencprop(enet_node, "cell-index", +- (void *)&mac_id, sizeof(mac_id)) <= 0) ++ (void *)&mac_id, sizeof(mac_id)) <= 0) { ++ device_printf(dev, "missing cell-index\n"); + return (ENXIO); ++ } + sc->sc_eth_id = mac_id; ++ sc->sc_mac_cell_index = mac_id; ++ /* ncsw expects 0-based per-type MAC IDs: 0..5 for 1G, 0..1 for 10G. ++ * FManV3 device trees use cell-index 0-5 for 1G MACs but 8-9 for ++ * 10G MACs (hardware MEMAC slot numbering). Remap to 0-based. */ ++ if (sc->sc_eth_dev_type == ETH_10GSEC && mac_id >= 8) ++ sc->sc_eth_id = mac_id - 8; + + /* Get RX/TX port handles */ +- if (OF_getprop(enet_node, "fsl,fman-ports", (void *)fman_rxtx_node, +- sizeof(fman_rxtx_node)) <= 0) ++ if (OF_getencprop(enet_node, "fsl,fman-ports", (void *)fman_rxtx_node, ++ sizeof(fman_rxtx_node)) <= 0) { ++ device_printf(dev, "missing fsl,fman-ports\n"); + return (ENXIO); ++ } + +- if (fman_rxtx_node[0] == 0) ++ if (fman_rxtx_node[0] == 0) { ++ device_printf(dev, "fsl,fman-ports[0] is zero\n"); + return (ENXIO); ++ } + +- if (fman_rxtx_node[1] == 0) ++ if (fman_rxtx_node[1] == 0) { ++ device_printf(dev, "fsl,fman-ports[1] is zero\n"); + return (ENXIO); ++ } + +- fman_rxtx_node[0] = OF_instance_to_package(fman_rxtx_node[0]); +- fman_rxtx_node[1] = OF_instance_to_package(fman_rxtx_node[1]); ++ /* fsl,fman-ports are phandle references on ARM64, ihandles on PPC */ ++ fman_rxtx_node[0] = OF_node_from_xref(fman_rxtx_node[0]); ++ fman_rxtx_node[1] = OF_node_from_xref(fman_rxtx_node[1]); + + if (ofw_bus_node_is_compatible(fman_rxtx_node[0], +- "fsl,fman-v2-port-rx") == 0) ++ "fsl,fman-v2-port-rx") == 0 && ++ ofw_bus_node_is_compatible(fman_rxtx_node[0], ++ "fsl,fman-v3-port-rx") == 0) { ++ device_printf(dev, "RX port incompatible\n"); + return (ENXIO); ++ } + + if (ofw_bus_node_is_compatible(fman_rxtx_node[1], +- "fsl,fman-v2-port-tx") == 0) ++ "fsl,fman-v2-port-tx") == 0 && ++ ofw_bus_node_is_compatible(fman_rxtx_node[1], ++ "fsl,fman-v3-port-tx") == 0) { ++ device_printf(dev, "TX port incompatible\n"); + return (ENXIO); ++ } + + /* Get RX port HW id */ +- if (OF_getprop(fman_rxtx_node[0], "reg", (void *)&sc->sc_port_rx_hw_id, +- sizeof(sc->sc_port_rx_hw_id)) <= 0) ++ if (OF_getencprop(fman_rxtx_node[0], "reg", (void *)&sc->sc_port_rx_hw_id, ++ sizeof(sc->sc_port_rx_hw_id)) <= 0) { ++ device_printf(dev, "missing RX port reg\n"); + return (ENXIO); ++ } + + /* Get TX port HW id */ +- if (OF_getprop(fman_rxtx_node[1], "reg", (void *)&sc->sc_port_tx_hw_id, +- sizeof(sc->sc_port_tx_hw_id)) <= 0) ++ if (OF_getencprop(fman_rxtx_node[1], "reg", (void *)&sc->sc_port_tx_hw_id, ++ sizeof(sc->sc_port_tx_hw_id)) <= 0) { ++ device_printf(dev, "missing TX port reg\n"); + return (ENXIO); ++ } + +- if (OF_getprop(fman_rxtx_node[1], "cell-index", &fman_tx_cell, +- sizeof(fman_tx_cell)) <= 0) ++ if (OF_getencprop(fman_rxtx_node[1], "cell-index", &fman_tx_cell, ++ sizeof(fman_tx_cell)) <= 0) { ++ device_printf(dev, "missing TX port cell-index\n"); + return (ENXIO); ++ } + /* Get QMan channel */ + sc->sc_port_tx_qman_chan = fman_qman_channel_id(device_get_parent(dev), + fman_tx_cell); +diff --git a/sys/dev/dpaa/if_dtsec_im.c b/sys/dev/dpaa/if_dtsec_im.c +index fcde0df6030..0cd55dbc7c7 100644 +--- a/sys/dev/dpaa/if_dtsec_im.c ++++ b/sys/dev/dpaa/if_dtsec_im.c +@@ -229,7 +229,8 @@ dtsec_im_if_start_locked(struct dtsec_softc *sc) + DTSEC_LOCK_ASSERT(sc); + /* TODO: IFF_DRV_OACTIVE */ + +- if ((sc->sc_mii->mii_media_status & IFM_ACTIVE) == 0) ++ if (sc->sc_mii != NULL && ++ (sc->sc_mii->mii_media_status & IFM_ACTIVE) == 0) + return; + + if ((if_getdrvflags(sc->sc_ifnet) & IFF_DRV_RUNNING) != IFF_DRV_RUNNING) +diff --git a/sys/dev/dpaa/if_dtsec_rm.c b/sys/dev/dpaa/if_dtsec_rm.c +index b213a259b5b..486994431a9 100644 +--- a/sys/dev/dpaa/if_dtsec_rm.c ++++ b/sys/dev/dpaa/if_dtsec_rm.c +@@ -36,6 +36,8 @@ + #include + #include + #include ++#include ++#include + + #include + #include +@@ -49,13 +51,25 @@ + + #include "miibus_if.h" + ++#include "opt_dpaa.h" ++ ++#include ++#include ++#include ++#include ++#include ++ + #include + #include + #include + #include ++#include ++#include + #include ++#include + + #include "fman.h" ++#include "fman_chardev.h" + #include "bman.h" + #include "qman.h" + #include "if_dtsec.h" +@@ -69,23 +83,62 @@ + #define DTSEC_BPOOLS_USED (1) + #define DTSEC_MAX_TX_QUEUE_LEN 256 + ++#define DTSEC_RX_QUEUES 128 /* Power of 2, 7-bit hash mask like Linux */ ++ ++/* FMan parse result L3/L4 type indicators (big-endian in parse result) */ ++#define FM_L3_PARSE_RESULT_IPV4 0x8000 ++#define FM_L3_PARSE_RESULT_IPV6 0x4000 ++#define FM_L4_PARSE_RESULT_UDP 0x40 ++#define FM_L4_PARSE_RESULT_TCP 0x20 ++ + struct dtsec_rm_frame_info { + struct mbuf *fi_mbuf; + t_DpaaSGTE fi_sgt[DPAA_NUM_OF_SG_TABLE_ENTRY]; ++ void *fi_tx_buf; /* SG table buffer (prefix + SG entries) */ ++ uint8_t fi_cpu; /* CPU index for in-flight tracking */ + }; + + enum dtsec_rm_pool_params { +- DTSEC_RM_POOL_RX_LOW_MARK = 16, +- DTSEC_RM_POOL_RX_HIGH_MARK = 64, +- DTSEC_RM_POOL_RX_MAX_SIZE = 256, ++ DTSEC_RM_POOL_RX_LOW_MARK = 256, ++ DTSEC_RM_POOL_RX_HIGH_MARK = 2048, ++ DTSEC_RM_POOL_RX_MAX_SIZE = 2048, ++ /* ++ * Maximum total buffers allocated from UMA per port. ++ * ++ * After the BMan/FMan/QMan round-trip, XX_PhysToVirt returns a ++ * DMAP address that differs from the original UMA KVA address. ++ * Buffers cannot be returned to UMA (address mismatch), so they ++ * permanently cycle between BMan and mbufs. This cap bounds ++ * total memory consumption. ++ * ++ * With 4-CPU forwarding at 10G, each packet holds an RX buffer ++ * through the full RX -> pf/NAT -> routing -> TX -> TX_confirm ++ * pipeline. 4096 was too low — caused chronic buffer pool ++ * exhaustion (oobd > 800K frames). ++ * ++ * 16384 × 9664 bytes = ~150 MB per port, ~300 MB for 2 active ++ * 10G ports. Board has 4 GB RAM. ++ */ ++ DTSEC_RM_POOL_RX_MAX_TOTAL = 16384, ++ /* ++ * Active refill threshold: when free buffer count drops below ++ * this, the RX callback allocates new buffers. FMan acquires ++ * buffers directly from BMan hardware, bypassing software ++ * depletion callbacks — without active refill the pool exhausts ++ * under sustained RX load. ++ */ ++ DTSEC_RM_POOL_RX_REFILL_THRESH = 1024, ++ DTSEC_RM_POOL_RX_REFILL_COUNT = 256, + + DTSEC_RM_POOL_FI_LOW_MARK = 16, + DTSEC_RM_POOL_FI_HIGH_MARK = 64, + DTSEC_RM_POOL_FI_MAX_SIZE = 256, + }; + ++#ifndef __aarch64__ + #define DTSEC_RM_FQR_RX_CHANNEL e_QM_FQ_CHANNEL_POOL1 +-#define DTSEC_RM_FQR_TX_CONF_CHANNEL e_QM_FQ_CHANNEL_SWPORTAL0 ++#endif ++#define DTSEC_RM_FQR_TX_CONF_CHANNEL e_QM_FQ_CHANNEL_POOL1 + enum dtsec_rm_fqr_params { + DTSEC_RM_FQR_RX_WQ = 1, + DTSEC_RM_FQR_TX_WQ = 1, +@@ -104,6 +157,8 @@ dtsec_rm_fi_pool_free(struct dtsec_softc *sc) + + if (sc->sc_fi_zone != NULL) + uma_zdestroy(sc->sc_fi_zone); ++ if (sc->sc_sgt_zone != NULL) ++ uma_zdestroy(sc->sc_sgt_zone); + } + + int +@@ -178,13 +233,167 @@ dtsec_rm_fm_port_rx_init(struct dtsec_softc *sc, int unit) + return (ENXIO); + } + ++ if (sc->sc_pcdh != NULL) { ++ /* ++ * Configure RX buffer prefix: parse result for checksum ++ * validation and hash result for RSS distribution. ++ * ++ * manipExtraSpace = 96 matches the Linux SDK DTS ++ * buffer-layout = <0x60 0x40> which reserves 96 bytes ++ * for header manipulation (NAT, encap) by CDX/FMan. ++ */ ++ t_FmBufferPrefixContent prefix; ++ ++ memset(&prefix, 0, sizeof(prefix)); ++ prefix.privDataSize = 16; ++ prefix.passPrsResult = TRUE; ++ prefix.passHashResult = TRUE; ++ prefix.dataAlign = 64; ++ prefix.manipExtraSpace = 96; ++ ++ error = FM_PORT_ConfigBufferPrefixContent(sc->sc_rxph, ++ &prefix); ++ if (error != E_OK) { ++ device_printf(sc->sc_dev, ++ "couldn't configure RX buffer prefix.\n"); ++ FM_PORT_Free(sc->sc_rxph); ++ sc->sc_rxph = NULL; ++ return (ENXIO); ++ } ++ } ++ ++#ifdef FM_HEAVY_TRAFFIC_HANG_ERRATA_FMAN_A005669 ++ /* Errata A005669: discard frames with physical errors (FCS, SGMII ++ * disparity, FIFO overflow) in FMan hardware and increase FIFO by ++ * 4KB to prevent FMan hang under heavy traffic. */ ++ FM_PORT_ConfigBCBWorkaround(sc->sc_rxph); ++#endif ++ + error = FM_PORT_Init(sc->sc_rxph); + if (error != E_OK) { + device_printf(sc->sc_dev, "couldn't initialize FM Port RX.\n"); + FM_PORT_Free(sc->sc_rxph); ++ sc->sc_rxph = NULL; + return (ENXIO); + } + ++ /* Enable BMI statistics counters for PCD diagnostics */ ++ FM_PORT_SetStatisticsCounters(sc->sc_rxph, TRUE); ++ ++ /* ++ * Reserve 1 port-private policer profile slot for this RX port. ++ * CDX QoS creates the actual profile via FM_PCD_PlcrProfileSet() ++ * when the CDX module loads (before dpa_app calls FM_PORT_SetPCD). ++ * Must be called after FM_PORT_Init() and before FM_PORT_SetPCD(). ++ */ ++ error = FM_PORT_PcdPlcrAllocProfiles(sc->sc_rxph, 1); ++ if (error != E_OK) ++ device_printf(sc->sc_dev, ++ "FM_PORT_PcdPlcrAllocProfiles failed: %d\n", error); ++ ++ /* ++ * Allocate Virtual Storage Profiles for this RX port. ++ * FManv3+ (DPAA >= 11) requires per-port VSP allocation for ++ * the CC/PCD pipeline to work correctly after CDX/dpa_app ++ * replaces the default PCD. This matches the Linux SDK driver ++ * which reads vsp-window = <2 0> from the DTS extended-args. ++ * ++ * Must be called after FM_PORT_Init() and before FM_PORT_SetPCD() ++ * and FM_PORT_Enable(). ++ */ ++#if (DPAA_VERSION >= 11) ++ if (sc->sc_pcdh != NULL && sc->sc_txph != NULL) { ++ t_FmPortVSPAllocParams vsp_alloc; ++ t_FmVspParams vsp_params; ++ t_FmBufferPrefixContent vsp_prefix; ++ t_Handle h_vsp; ++ ++ /* Step 1: Allocate 2 VSP slots for this port */ ++ memset(&vsp_alloc, 0, sizeof(vsp_alloc)); ++ vsp_alloc.numOfProfiles = 2; ++ vsp_alloc.dfltRelativeId = 0; ++ vsp_alloc.h_FmTxPort = sc->sc_txph; ++ ++ error = FM_PORT_VSPAlloc(sc->sc_rxph, &vsp_alloc); ++ if (error != E_OK) { ++ device_printf(sc->sc_dev, ++ "couldn't allocate VSP: error %d\n", error); ++ goto vsp_done; ++ } ++ ++ /* Step 2: Configure default VSP (profile 0) */ ++ memset(&vsp_params, 0, sizeof(vsp_params)); ++ vsp_params.h_Fm = sc->sc_fmh; ++ vsp_params.portParams.portType = ++ dtsec_fm_port_rx_type(sc->sc_eth_dev_type); ++ vsp_params.portParams.portId = sc->sc_eth_id; ++ vsp_params.relativeProfileId = 0; ++ vsp_params.liodnOffset = 0; ++ vsp_params.extBufPools.numOfPoolsUsed = DTSEC_BPOOLS_USED; ++ vsp_params.extBufPools.extBufPool[0].id = sc->sc_rx_bpid; ++ vsp_params.extBufPools.extBufPool[0].size = FM_PORT_BUFFER_SIZE; ++ ++ h_vsp = FM_VSP_Config(&vsp_params); ++ if (h_vsp == NULL) { ++ device_printf(sc->sc_dev, ++ "couldn't configure VSP.\n"); ++ goto vsp_done; ++ } ++ ++ /* Step 3: Set VSP buffer prefix (matching SDK DTS ++ * buffer-layout = <0x60 0x40>) */ ++ memset(&vsp_prefix, 0, sizeof(vsp_prefix)); ++ vsp_prefix.privDataSize = 16; ++ vsp_prefix.passPrsResult = TRUE; ++ vsp_prefix.passHashResult = TRUE; ++ vsp_prefix.dataAlign = 64; ++ vsp_prefix.manipExtraSpace = 96; ++ ++ error = FM_VSP_ConfigBufferPrefixContent(h_vsp, &vsp_prefix); ++ if (error != E_OK) { ++ device_printf(sc->sc_dev, ++ "couldn't configure VSP buffer prefix: %d\n", ++ error); ++ FM_VSP_Free(h_vsp); ++ goto vsp_done; ++ } ++ ++ /* Step 4: Initialize VSP hardware registers */ ++ error = FM_VSP_Init(h_vsp); ++ if (error != E_OK) { ++ device_printf(sc->sc_dev, ++ "couldn't initialize VSP: %d\n", error); ++ FM_VSP_Free(h_vsp); ++ goto vsp_done; ++ } ++ ++ sc->sc_vsph = h_vsp; ++ device_printf(sc->sc_dev, ++ "VSP allocated: 2 profiles, default ID 0\n"); ++vsp_done: ; ++ } ++#endif /* DPAA_VERSION >= 11 */ ++ ++ /* Register RX port with FMD chardev for userspace PCD control */ ++ { ++ struct fmcd_softc *fmcd; ++ ++ fmcd = fman_get_fmcd(device_get_parent(sc->sc_dev)); ++ if (fmcd != NULL) ++ fmcd_register_rx_port(fmcd, ++ sc->sc_mac_cell_index, sc->sc_rxph, ++ sc->sc_rx_fqid); ++ } ++ ++ if (sc->sc_pcdh != NULL) { ++ sc->sc_rx_data_offset = ++ FM_PORT_GetBufferDataOffset(sc->sc_rxph); ++ if (bootverbose) ++ device_printf(sc->sc_dev, ++ "RX buffer data offset: %u\n", ++ sc->sc_rx_data_offset); ++ } ++ + if (bootverbose) + device_printf(sc->sc_dev, "RX hw port 0x%02x initialized.\n", + sc->sc_port_rx_hw_id); +@@ -224,13 +433,57 @@ dtsec_rm_fm_port_tx_init(struct dtsec_softc *sc, int unit) + return (ENXIO); + } + ++ /* Configure TX buffer prefix to include parse results area. ++ * When TX checksum offload is requested, the driver fills in the ++ * parse result and sets FM_FD_CMD_RPD | FM_FD_CMD_DTC. ++ * ++ * manipExtraSpace = 96 matches the Linux SDK DTS ++ * buffer-layout = <0x60 0x40> for TX port extended-args. ++ */ ++ { ++ t_FmBufferPrefixContent prefix; ++ ++ memset(&prefix, 0, sizeof(prefix)); ++ prefix.privDataSize = 16; ++ prefix.passPrsResult = TRUE; ++ prefix.passTimeStamp = FALSE; ++ prefix.passHashResult = FALSE; ++ prefix.passAllOtherPCDInfo = FALSE; ++ prefix.dataAlign = 64; ++ prefix.manipExtraSpace = 96; ++ ++ error = FM_PORT_ConfigBufferPrefixContent(sc->sc_txph, ++ &prefix); ++ if (error != E_OK) { ++ device_printf(sc->sc_dev, ++ "couldn't configure TX buffer prefix.\n"); ++ FM_PORT_Free(sc->sc_txph); ++ sc->sc_txph = NULL; ++ return (ENXIO); ++ } ++ } ++ + error = FM_PORT_Init(sc->sc_txph); + if (error != E_OK) { + device_printf(sc->sc_dev, "couldn't initialize FM Port TX.\n"); + FM_PORT_Free(sc->sc_txph); ++ sc->sc_txph = NULL; + return (ENXIO); + } + ++ sc->sc_tx_data_offset = FM_PORT_GetBufferDataOffset(sc->sc_txph); ++ if (bootverbose) ++ device_printf(sc->sc_dev, "TX buffer data offset: %u\n", ++ sc->sc_tx_data_offset); ++ ++ /* Create UMA zone for SG table buffers (prefix + SG entries) */ ++ sc->sc_sgt_buf_size = sc->sc_tx_data_offset + ++ DPAA_NUM_OF_SG_TABLE_ENTRY * sizeof(t_DpaaSGTE); ++ snprintf(sc->sc_sgt_zname, sizeof(sc->sc_sgt_zname), "%s: SGT buf", ++ device_get_nameunit(sc->sc_dev)); ++ sc->sc_sgt_zone = uma_zcreate(sc->sc_sgt_zname, sc->sc_sgt_buf_size, ++ NULL, NULL, NULL, NULL, 63 /* 64-byte align */, 0); ++ + if (bootverbose) + device_printf(sc->sc_dev, "TX hw port 0x%02x initialized.\n", + sc->sc_port_tx_hw_id); +@@ -268,23 +521,58 @@ dtsec_rm_pool_rx_get_buffer(t_Handle h_BufferPool, t_Handle *context) + return (buffer); + } + ++/* ++ * Refill the BMan buffer pool directly from UMA, bypassing ++ * BM_POOL_FillBufs. This avoids the NCSW RETURN_ERROR printf ++ * when uma_zalloc(M_NOWAIT) transiently fails — a single printf ++ * to serial console at 115200 baud takes ~5ms, blocking the CPU ++ * in interrupt context and causing cascading buffer exhaustion. ++ * ++ * Returns the number of buffers actually allocated. ++ */ ++static unsigned int ++dtsec_rm_pool_rx_refill(struct dtsec_softc *sc, unsigned int nbufs) ++{ ++ unsigned int i; ++ uint8_t *buf; ++ ++ for (i = 0; i < nbufs; i++) { ++ buf = uma_zalloc(sc->sc_rx_zone, M_NOWAIT); ++ if (buf == NULL) ++ break; ++ if (bman_put_buffer(sc->sc_rx_pool, buf) != 0) { ++ uma_zfree(sc->sc_rx_zone, buf); ++ break; ++ } ++ } ++ return (i); ++} ++ + static void + dtsec_rm_pool_rx_depleted(t_Handle h_App, bool in) + { + struct dtsec_softc *sc; +- unsigned int count; ++ unsigned int count, headroom, nbufs; + + sc = h_App; + + if (!in) + return; + +- while (1) { +- count = bman_count(sc->sc_rx_pool); +- if (count > DTSEC_RM_POOL_RX_HIGH_MARK) +- return; ++ /* Only refill up to the per-port cap */ ++ if (atomic_load_32(&sc->sc_rx_buf_total) >= ++ DTSEC_RM_POOL_RX_MAX_TOTAL) ++ return; + +- bman_pool_fill(sc->sc_rx_pool, DTSEC_RM_POOL_RX_HIGH_MARK); ++ count = bman_count(sc->sc_rx_pool); ++ if (count < DTSEC_RM_POOL_RX_HIGH_MARK) { ++ headroom = DTSEC_RM_POOL_RX_MAX_TOTAL - ++ atomic_load_32(&sc->sc_rx_buf_total); ++ nbufs = DTSEC_RM_POOL_RX_HIGH_MARK - count; ++ if (nbufs > headroom) ++ nbufs = headroom; ++ nbufs = dtsec_rm_pool_rx_refill(sc, nbufs); ++ atomic_add_32(&sc->sc_rx_buf_total, nbufs); + } + } + +@@ -303,14 +591,11 @@ int + dtsec_rm_pool_rx_init(struct dtsec_softc *sc) + { + +- /* FM_PORT_BUFFER_SIZE must be less than PAGE_SIZE */ +- CTASSERT(FM_PORT_BUFFER_SIZE < PAGE_SIZE); +- + snprintf(sc->sc_rx_zname, sizeof(sc->sc_rx_zname), "%s: RX Buffers", + device_get_nameunit(sc->sc_dev)); + + sc->sc_rx_zone = uma_zcreate(sc->sc_rx_zname, FM_PORT_BUFFER_SIZE, NULL, +- NULL, NULL, NULL, FM_PORT_BUFFER_SIZE - 1, 0); ++ NULL, NULL, NULL, 255 /* 256-byte align for DMA */, 0); + + sc->sc_rx_pool = bman_pool_create(&sc->sc_rx_bpid, FM_PORT_BUFFER_SIZE, + 0, 0, DTSEC_RM_POOL_RX_MAX_SIZE, dtsec_rm_pool_rx_get_buffer, +@@ -323,6 +608,8 @@ dtsec_rm_pool_rx_init(struct dtsec_softc *sc) + return (EIO); + } + ++ sc->sc_rx_buf_total = DTSEC_RM_POOL_RX_MAX_SIZE; ++ + return (0); + } + /** @} */ +@@ -340,10 +627,21 @@ dtsec_rm_fqr_mext_free(struct mbuf *m) + + buffer = m->m_ext.ext_arg1; + sc = m->m_ext.ext_arg2; +- if (bman_count(sc->sc_rx_pool) <= DTSEC_RM_POOL_RX_MAX_SIZE) +- bman_put_buffer(sc->sc_rx_pool, buffer); +- else +- dtsec_rm_pool_rx_put_buffer(sc, buffer, NULL); ++ ++ /* ++ * Always return buffers to BMan, never to UMA. ++ * ++ * After the BMan/FMan/QMan round-trip, XX_PhysToVirt returns ++ * the DMAP virtual address for the buffer, which differs from ++ * the original KVA address that uma_zalloc returned. Calling ++ * uma_zfree with the DMAP address corrupts UMA slab tracking ++ * and leads to use-after-free panics. ++ * ++ * With the 16 MB FBPR (no-map reserved memory), the pool can ++ * hold far more entries than we'll ever need, so there is no ++ * reason to cap the pool at POOL_RX_MAX_SIZE. ++ */ ++ bman_put_buffer(sc->sc_rx_pool, buffer); + } + + static e_RxStoreResponse +@@ -357,20 +655,66 @@ dtsec_rm_fqr_rx_callback(t_Handle app, t_Handle fqr, t_Handle portal, + m = NULL; + sc = app; + +- frame_va = DPAA_FD_GET_ADDR(frame); +- KASSERT(DPAA_FD_GET_FORMAT(frame) == e_DPAA_FD_FORMAT_TYPE_SHORT_SBSF, +- ("%s(): Got unsupported frame format 0x%02X!", __func__, +- DPAA_FD_GET_FORMAT(frame))); +- +- KASSERT(DPAA_FD_GET_OFFSET(frame) == 0, +- ("%s(): Only offset 0 is supported!", __func__)); ++ /* ++ * Refill BMan buffer pool if running low. ++ * FMan acquires buffers directly from BMan hardware, bypassing ++ * software depletion callbacks. Without active refill, the pool ++ * exhausts under sustained RX load: all buffers end up in mbufs ++ * held by the TCP stack, FMan drops every subsequent frame, and ++ * retransmissions are also dropped — permanent deadlock. ++ */ ++ if (__predict_false(bman_count(sc->sc_rx_pool) < ++ DTSEC_RM_POOL_RX_REFILL_THRESH) && ++ atomic_load_32(&sc->sc_rx_buf_total) < ++ DTSEC_RM_POOL_RX_MAX_TOTAL) { ++ unsigned int n, added; ++ uint32_t total; ++ ++ total = atomic_load_32(&sc->sc_rx_buf_total); ++ n = DTSEC_RM_POOL_RX_REFILL_COUNT; ++ if (n > DTSEC_RM_POOL_RX_MAX_TOTAL - total) ++ n = DTSEC_RM_POOL_RX_MAX_TOTAL - total; ++ added = dtsec_rm_pool_rx_refill(sc, n); ++ atomic_add_32(&sc->sc_rx_buf_total, added); ++ } + +- if (DPAA_FD_GET_STATUS(frame) != 0) { +- device_printf(sc->sc_dev, "RX error: 0x%08X\n", +- DPAA_FD_GET_STATUS(frame)); ++ frame_va = DPAA_FD_GET_ADDR(frame); ++ if (frame_va == NULL) ++ return (e_RX_STORE_RESPONSE_CONTINUE); ++ ++ if (DPAA_FD_GET_FORMAT(frame) != e_DPAA_FD_FORMAT_TYPE_SHORT_SBSF) { ++ /* SG/compound FDs should not occur with our buffer pool size. ++ * Log and drop rather than panic. */ ++ if_printf(sc->sc_ifnet, ++ "RX: unexpected FD format 0x%02X, dropping\n", ++ DPAA_FD_GET_FORMAT(frame)); + goto err; + } + ++ { ++ uint32_t fd_st = DPAA_FD_GET_STATUS(frame); ++ uint32_t err_bits = fd_st & ++ (FM_FD_RX_STATUS_ERR_MASK & ~FM_FD_ERR_NO_SCHEME); ++ if (err_bits) { ++ static volatile uint32_t rx_err_cnt; ++ uint32_t n = atomic_fetchadd_32(&rx_err_cnt, 1) + 1; ++ if (n <= 10 || (n % 100) == 0) ++ if_printf(sc->sc_ifnet, ++ "RX error #%u: fd_status=0x%08X" ++ " (phy=%d cls=%d red=%d yel=%d" ++ " plcr=%d prs=%d ext=%d)\n", ++ n, fd_st, ++ !!(fd_st & FM_FD_ERR_PHYSICAL), ++ !!(fd_st & FM_FD_ERR_CLS_DISCARD), ++ !!(fd_st & FM_FD_ERR_COLOR_RED), ++ !!(fd_st & FM_FD_ERR_COLOR_YELLOW), ++ !!(fd_st & FM_FD_ERR_ILL_PLCR), ++ !!(fd_st & FM_FD_ERR_PRS_HDR_ERR), ++ !!(fd_st & FM_FD_ERR_EXTRACTION)); ++ goto err; ++ } ++ } ++ + m = m_gethdr(M_NOWAIT, MT_HEADER); + if (m == NULL) + goto err; +@@ -380,14 +724,64 @@ dtsec_rm_fqr_rx_callback(t_Handle app, t_Handle fqr, t_Handle portal, + EXT_NET_DRV); + + m->m_pkthdr.rcvif = sc->sc_ifnet; ++ m->m_data = (char *)frame_va + DPAA_FD_GET_OFFSET(frame); + m->m_len = DPAA_FD_GET_LENGTH(frame); +- m_fixhdr(m); ++ m->m_pkthdr.len = m->m_len; ++ ++ /* Extract RX checksum result from parse result in buffer prefix */ ++ if (sc->sc_rx_data_offset > 0) { ++ t_FmPrsResult *prs; ++ ++ prs = FM_PORT_GetBufferPrsResult(sc->sc_rxph, ++ (char *)frame_va); ++ if (prs != NULL) { ++ uint16_t l3r = be16toh(prs->l3r); ++ ++ if (l3r & (FM_L3_PARSE_RESULT_IPV4 | ++ FM_L3_PARSE_RESULT_IPV6)) { ++ m->m_pkthdr.csum_flags |= ++ CSUM_L3_CALC | CSUM_L3_VALID; ++ ++ if (prs->l4r & (FM_L4_PARSE_RESULT_TCP | ++ FM_L4_PARSE_RESULT_UDP)) { ++ uint32_t fd_status = ++ DPAA_FD_GET_STATUS(frame); ++ /* ++ * DCL4C = "Didn't Compute L4 Checksum". ++ * Only claim HW-verified when clear. ++ * When set, leave flags alone so the ++ * stack verifies L4 csum in software. ++ * ++ * csum_data = 0xffff: tells the stack ++ * the full checksum (incl pseudo-hdr) ++ * is valid. Without this, the stack ++ * reads csum_data=0 and drops the ++ * packet as a checksum failure. ++ */ ++ if (!(fd_status & FM_FD_CMD_DCL4C)) { ++ m->m_pkthdr.csum_flags |= ++ CSUM_L4_CALC | ++ CSUM_L4_VALID; ++ m->m_pkthdr.csum_data = ++ 0xffff; ++ } ++ } ++ } ++ } ++ } + ++ if_inc_counter(sc->sc_ifnet, IFCOUNTER_IPACKETS, 1); ++ if_inc_counter(sc->sc_ifnet, IFCOUNTER_IBYTES, m->m_pkthdr.len); ++#ifdef __aarch64__ ++ qman_rx_defer(m); ++#else + if_input(sc->sc_ifnet, m); ++#endif + + return (e_RX_STORE_RESPONSE_CONTINUE); + + err: ++ if_inc_counter(sc->sc_ifnet, IFCOUNTER_IERRORS, 1); + bman_put_buffer(sc->sc_rx_pool, frame_va); + if (m != NULL) + m_freem(m); +@@ -401,49 +795,93 @@ dtsec_rm_fqr_tx_confirm_callback(t_Handle app, t_Handle fqr, t_Handle portal, + { + struct dtsec_rm_frame_info *fi; + struct dtsec_softc *sc; +- unsigned int qlen; + t_DpaaSGTE *sgt0; ++ void *buf; ++ int cpu; + + sc = app; + +- if (DPAA_FD_GET_STATUS(frame) != 0) +- device_printf(sc->sc_dev, "TX error: 0x%08X\n", +- DPAA_FD_GET_STATUS(frame)); +- +- /* +- * We are storing struct dtsec_rm_frame_info in first entry +- * of scatter-gather table. +- */ +- sgt0 = DPAA_FD_GET_ADDR(frame); +- fi = DPAA_SGTE_GET_ADDR(sgt0); ++ buf = DPAA_FD_GET_ADDR(frame); ++ if (buf == NULL) ++ return (e_RX_STORE_RESPONSE_CONTINUE); ++ ++ if (DPAA_FD_GET_FORMAT(frame) == e_DPAA_FD_FORMAT_TYPE_SHORT_MBSF && ++ DPAA_FD_GET_OFFSET(frame) > 0) { ++ /* SG+prefix FD (checksum offload path). ++ * fi pointer stored in private data area at start of buf. ++ * SG table buffer allocated from sc_sgt_zone. */ ++ fi = *(struct dtsec_rm_frame_info **)buf; ++ cpu = fi->fi_cpu; ++ m_freem(fi->fi_mbuf); ++ uma_zfree(sc->sc_sgt_zone, buf); ++ dtsec_rm_fi_free(sc, fi); ++ } else { ++ /* Legacy SG FD (no prefix, offset=0). ++ * fi pointer stored in first SG entry. */ ++ sgt0 = buf; ++ fi = DPAA_SGTE_GET_ADDR(sgt0); ++ cpu = fi->fi_cpu; ++ m_freem(fi->fi_mbuf); ++ dtsec_rm_fi_free(sc, fi); ++ } + +- /* Free transmitted frame */ +- m_freem(fi->fi_mbuf); +- dtsec_rm_fi_free(sc, fi); ++ atomic_subtract_int(&sc->sc_tx_inflight[cpu], 1); + +- qlen = qman_fqr_get_counter(sc->sc_tx_conf_fqr, 0, +- e_QM_FQR_COUNTERS_FRAME); ++ return (e_RX_STORE_RESPONSE_CONTINUE); ++} + +- if (qlen == 0) { +- DTSEC_LOCK(sc); ++void ++dtsec_rm_fqr_rx_free(struct dtsec_softc *sc) ++{ ++ int i; + +- if (sc->sc_tx_fqr_full) { +- sc->sc_tx_fqr_full = 0; +- dtsec_rm_if_start_locked(sc); ++ for (i = 0; i < DTSEC_RX_QUEUES; i++) { ++ if (sc->sc_rx_fqr[i] != NULL) { ++ qman_fqr_free(sc->sc_rx_fqr[i]); ++ sc->sc_rx_fqr[i] = NULL; + } +- +- DTSEC_UNLOCK(sc); + } +- +- return (e_RX_STORE_RESPONSE_CONTINUE); + } + ++/* ++ * dtsec_release_rss_fqrs — Free RSS FQRs 1..127 from all dtsec ports. ++ * ++ * Called by CDX module during takeover, before creating CDX distribution ++ * FQRs. After CDX replaces the driver's PCD, the RSS FQRs are orphaned ++ * (no KeyGen scheme directs traffic to them). FQR 0 (base FQID) is kept ++ * alive — CDX miss-action routes unmatched frames there for stack delivery. ++ * ++ * Safe to call at boot before any traffic has flowed (instant, no drain). ++ */ + void +-dtsec_rm_fqr_rx_free(struct dtsec_softc *sc) ++dtsec_release_rss_fqrs(void) + { ++ devclass_t dc; ++ device_t dev; ++ struct dtsec_softc *sc; ++ int i, unit; + +- if (sc->sc_rx_fqr) +- qman_fqr_free(sc->sc_rx_fqr); ++ dc = devclass_find("dtsec"); ++ if (dc == NULL) ++ return; ++ ++ for (unit = 0; unit < devclass_get_maxunit(dc); unit++) { ++ dev = devclass_get_device(dc, unit); ++ if (dev == NULL) ++ continue; ++ sc = device_get_softc(dev); ++ if (sc == NULL || sc->sc_rx_fqr[1] == NULL) ++ continue; ++ for (i = 1; i < DTSEC_RX_QUEUES; i++) { ++ if (sc->sc_rx_fqr[i] != NULL) { ++ qman_fqr_free(sc->sc_rx_fqr[i]); ++ sc->sc_rx_fqr[i] = NULL; ++ } ++ } ++ device_printf(dev, ++ "released %d RSS FQRs for CDX (base FQID %u kept)\n", ++ DTSEC_RX_QUEUES - 1, sc->sc_rx_fqid); ++ } + } + + int +@@ -451,17 +889,103 @@ dtsec_rm_fqr_rx_init(struct dtsec_softc *sc) + { + t_Error error; + t_Handle fqr; ++ uint32_t base_fqid; ++ int i; + +- /* Default Frame Queue */ +- fqr = qman_fqr_create(1, DTSEC_RM_FQR_RX_CHANNEL, DTSEC_RM_FQR_RX_WQ, +- false, 0, false, false, true, false, 0, 0, 0); ++#ifdef __aarch64__ ++ /* ++ * RSS via per-CPU dedicated QMan channels (matching Linux). ++ * ++ * Create DTSEC_RX_QUEUES (128) single-FQID FQRs with contiguous ++ * FQIDs, round-robin assigned to dedicated SW portal channels: ++ * FQID base+0 -> SWPORTAL0, base+1 -> SWPORTAL1, ... ++ * base+4 -> SWPORTAL0, base+5 -> SWPORTAL1, etc. ++ * ++ * KeyGen hashes 4-tuple -> baseFqid + (hash & 127). With a ++ * 7-bit hash mask, different flows distribute well across CPUs. ++ * Same flow always hashes to same FQID -> same CPU (no reorder). ++ * ++ * The first FQR is allocated with alignment = DTSEC_RX_QUEUES ++ * to satisfy the KeyGen alignment requirement. The remaining ++ * 127 FQRs use force_fqid for contiguous FQIDs. ++ */ ++ ++ /* FQID 0: allocate with alignment to get contiguous base */ ++ fqr = qman_fqr_create(1, ++ (e_QmFQChannel)(e_QM_FQ_CHANNEL_SWPORTAL0), ++ DTSEC_RM_FQR_RX_WQ, false, ++ DTSEC_RX_QUEUES, /* alignment */ ++ false, false, true, false, 0, 0, 0); + if (fqr == NULL) { +- device_printf(sc->sc_dev, "could not create default RX queue" +- "\n"); ++ device_printf(sc->sc_dev, ++ "could not create aligned RX FQR for FQID 0\n"); ++ return (EIO); ++ } ++ ++ sc->sc_rx_fqr[0] = fqr; ++ base_fqid = qman_fqr_get_base_fqid(fqr); ++ sc->sc_rx_fqid = base_fqid; ++ ++ error = qman_fqr_register_cb(fqr, dtsec_rm_fqr_rx_callback, sc); ++ if (error != E_OK) { ++ device_printf(sc->sc_dev, ++ "could not register RX callback for FQID 0\n"); ++ qman_fqr_free(fqr); ++ sc->sc_rx_fqr[0] = NULL; + return (EIO); + } + +- sc->sc_rx_fqr = fqr; ++ /* FQIDs 1..N-1: force-allocate, round-robin across CPUs */ ++ for (i = 1; i < DTSEC_RX_QUEUES; i++) { ++ e_QmFQChannel channel = ++ (e_QmFQChannel)(e_QM_FQ_CHANNEL_SWPORTAL0 + ++ (i % DTSEC_TX_NUM_FQS)); ++ ++ fqr = qman_fqr_create(1, channel, DTSEC_RM_FQR_RX_WQ, ++ true, base_fqid + i, ++ false, false, true, false, 0, 0, 0); ++ if (fqr == NULL) { ++ device_printf(sc->sc_dev, ++ "could not create RX FQR %d " ++ "(FQID %u, channel %d)\n", ++ i, base_fqid + i, (int)channel); ++ goto fail; ++ } ++ ++ sc->sc_rx_fqr[i] = fqr; ++ ++ error = qman_fqr_register_cb(fqr, ++ dtsec_rm_fqr_rx_callback, sc); ++ if (error != E_OK) { ++ device_printf(sc->sc_dev, ++ "could not register RX callback for FQ %d\n", i); ++ qman_fqr_free(fqr); ++ sc->sc_rx_fqr[i] = NULL; ++ goto fail; ++ } ++ } ++ ++ device_printf(sc->sc_dev, ++ "RX RSS: base FQID %u, %d queues across %d CPUs\n", ++ base_fqid, DTSEC_RX_QUEUES, DTSEC_TX_NUM_FQS); ++ ++ return (0); ++ ++fail: ++ dtsec_rm_fqr_rx_free(sc); ++ return (EIO); ++ ++#else /* !__aarch64__ — PowerPC: single FQR on pool channel */ ++ fqr = qman_fqr_create(DTSEC_RX_QUEUES, DTSEC_RM_FQR_RX_CHANNEL, ++ DTSEC_RM_FQR_RX_WQ, false, ++ DTSEC_RX_QUEUES > 1 ? DTSEC_RX_QUEUES : 0, ++ false, false, true, false, 0, 0, 0); ++ if (fqr == NULL) { ++ device_printf(sc->sc_dev, "could not create RX queue range\n"); ++ return (EIO); ++ } ++ ++ sc->sc_rx_fqr[0] = fqr; + sc->sc_rx_fqid = qman_fqr_get_base_fqid(fqr); + + error = qman_fqr_register_cb(fqr, dtsec_rm_fqr_rx_callback, sc); +@@ -471,18 +995,30 @@ dtsec_rm_fqr_rx_init(struct dtsec_softc *sc) + return (EIO); + } + ++ if (bootverbose) ++ device_printf(sc->sc_dev, "RX FQR: base FQID %u, %d queues\n", ++ sc->sc_rx_fqid, DTSEC_RX_QUEUES); ++ + return (0); ++#endif + } + + void + dtsec_rm_fqr_tx_free(struct dtsec_softc *sc) + { ++ int i; + +- if (sc->sc_tx_fqr) +- qman_fqr_free(sc->sc_tx_fqr); ++ for (i = 0; i < DTSEC_TX_NUM_FQS; i++) { ++ if (sc->sc_tx_fqs[i] != NULL) { ++ qman_fqr_free(sc->sc_tx_fqs[i]); ++ sc->sc_tx_fqs[i] = NULL; ++ } ++ } + +- if (sc->sc_tx_conf_fqr) ++ if (sc->sc_tx_conf_fqr != NULL) { + qman_fqr_free(sc->sc_tx_conf_fqr); ++ sc->sc_tx_conf_fqr = NULL; ++ } + } + + int +@@ -490,19 +1026,24 @@ dtsec_rm_fqr_tx_init(struct dtsec_softc *sc) + { + t_Error error; + t_Handle fqr; +- +- /* TX Frame Queue */ +- fqr = qman_fqr_create(1, sc->sc_port_tx_qman_chan, +- DTSEC_RM_FQR_TX_WQ, false, 0, false, false, true, false, 0, 0, 0); +- if (fqr == NULL) { +- device_printf(sc->sc_dev, "could not create default TX queue" +- "\n"); +- return (EIO); ++ int i; ++ ++ /* Per-CPU TX Frame Queues — all target the same FMan TX port channel */ ++ for (i = 0; i < DTSEC_TX_NUM_FQS; i++) { ++ fqr = qman_fqr_create(1, sc->sc_port_tx_qman_chan, ++ DTSEC_RM_FQR_TX_WQ, false, 0, false, false, true, false, ++ 0, 0, 0); ++ if (fqr == NULL) { ++ device_printf(sc->sc_dev, ++ "could not create TX queue for CPU %d\n", i); ++ dtsec_rm_fqr_tx_free(sc); ++ return (EIO); ++ } ++ sc->sc_tx_fqs[i] = fqr; ++ sc->sc_tx_inflight[i] = 0; + } + +- sc->sc_tx_fqr = fqr; +- +- /* TX Confirmation Frame Queue */ ++ /* TX Confirmation Frame Queue (single, on pool channel) */ + fqr = qman_fqr_create(1, DTSEC_RM_FQR_TX_CONF_CHANNEL, + DTSEC_RM_FQR_TX_CONF_WQ, false, 0, false, false, true, false, 0, 0, + 0); +@@ -524,129 +1065,554 @@ dtsec_rm_fqr_tx_init(struct dtsec_softc *sc) + return (EIO); + } + ++ if (bootverbose) ++ device_printf(sc->sc_dev, ++ "TX FQs: %d per-CPU queues, confirm FQID %u\n", ++ DTSEC_TX_NUM_FQS, sc->sc_tx_conf_fqid); ++ + return (0); + } + /** @} */ + + + /** +- * @group dTSEC IFnet routines. ++ * @group dTSEC PCD (Parse-Classify-Distribute) routines. + * @{ + */ ++ ++/** ++ * Initialize PCD on the RX port: create a KeyGen scheme for RSS ++ * hash distribution across DTSEC_RX_QUEUES, then attach PCD ++ * (Parser + KeyGen) to the RX port. ++ * ++ * Called from dtsec_attach() after RX port and FQR are initialized. ++ * Non-fatal: returns 0 on success or if PCD is unavailable. ++ */ ++int ++dtsec_rm_pcd_init(struct dtsec_softc *sc) ++{ ++ t_FmPcdKgSchemeParams scheme; ++ t_FmPortPcdParams port_pcd; ++ t_FmPortPcdPrsParams prs; ++ t_FmPortPcdKgParams kg; ++ t_Error error; ++ int i; ++ ++ if (sc->sc_pcdh == NULL) ++ return (0); ++ ++ /* --- Create KeyGen scheme --- */ ++ memset(&scheme, 0, sizeof(scheme)); ++ scheme.modify = FALSE; ++ scheme.id.relativeSchemeId = device_get_unit(sc->sc_dev); ++ scheme.alwaysDirect = TRUE; ++ scheme.useHash = TRUE; ++ scheme.bypassFqidGeneration = FALSE; ++ scheme.baseFqid = sc->sc_rx_fqid; ++ scheme.nextEngine = e_FM_PCD_DONE; ++ scheme.kgNextEngineParams.doneAction = e_FM_PCD_ENQ_FRAME; ++ ++ /* ++ * Extract 4-tuple for hash: IPv4 SRC/DST + L4 SRC/DST port. ++ * Using HEADER_TYPE_TCP for L4 ports — the KeyGen's known-field ++ * registers (KG_SCH_KN_L4PSRC/L4PDST) are protocol-agnostic and ++ * extract L4 ports for both TCP and UDP. For non-IP/non-L4 ++ * frames, the default value (zeros) is used, so they all hash ++ * to baseFqid + 0. ++ */ ++ i = 0; ++ ++ /* IPv4 source IP */ ++ scheme.keyExtractAndHashParams.extractArray[i].type = ++ e_FM_PCD_EXTRACT_BY_HDR; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr.hdr = ++ HEADER_TYPE_IPv4; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr.hdrIndex = ++ e_FM_PCD_HDR_INDEX_NONE; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr ++ .ignoreProtocolValidation = FALSE; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr.type = ++ e_FM_PCD_EXTRACT_FULL_FIELD; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr ++ .extractByHdrType.fullField.ipv4 = NET_HEADER_FIELD_IPv4_SRC_IP; ++ i++; ++ ++ /* IPv4 destination IP */ ++ scheme.keyExtractAndHashParams.extractArray[i].type = ++ e_FM_PCD_EXTRACT_BY_HDR; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr.hdr = ++ HEADER_TYPE_IPv4; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr.hdrIndex = ++ e_FM_PCD_HDR_INDEX_NONE; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr ++ .ignoreProtocolValidation = FALSE; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr.type = ++ e_FM_PCD_EXTRACT_FULL_FIELD; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr ++ .extractByHdrType.fullField.ipv4 = NET_HEADER_FIELD_IPv4_DST_IP; ++ i++; ++ ++ /* TCP/UDP source port (KG_SCH_KN_L4PSRC covers both TCP and UDP) */ ++ scheme.keyExtractAndHashParams.extractArray[i].type = ++ e_FM_PCD_EXTRACT_BY_HDR; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr.hdr = ++ HEADER_TYPE_TCP; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr.hdrIndex = ++ e_FM_PCD_HDR_INDEX_NONE; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr ++ .ignoreProtocolValidation = FALSE; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr.type = ++ e_FM_PCD_EXTRACT_FULL_FIELD; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr ++ .extractByHdrType.fullField.tcp = NET_HEADER_FIELD_TCP_PORT_SRC; ++ i++; ++ ++ /* TCP/UDP destination port (KG_SCH_KN_L4PDST covers both TCP and UDP) */ ++ scheme.keyExtractAndHashParams.extractArray[i].type = ++ e_FM_PCD_EXTRACT_BY_HDR; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr.hdr = ++ HEADER_TYPE_TCP; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr.hdrIndex = ++ e_FM_PCD_HDR_INDEX_NONE; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr ++ .ignoreProtocolValidation = FALSE; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr.type = ++ e_FM_PCD_EXTRACT_FULL_FIELD; ++ scheme.keyExtractAndHashParams.extractArray[i].extractByHdr ++ .extractByHdrType.fullField.tcp = NET_HEADER_FIELD_TCP_PORT_DST; ++ i++; ++ ++ scheme.keyExtractAndHashParams.numOfUsedExtracts = i; ++ scheme.keyExtractAndHashParams.hashDistributionNumOfFqids = ++ DTSEC_RX_QUEUES; ++ scheme.keyExtractAndHashParams.hashShift = 0; ++ scheme.keyExtractAndHashParams.hashDistributionFqidsShift = 0; ++ scheme.keyExtractAndHashParams.symmetricHash = FALSE; ++ ++ /* Defaults for missing headers: use privateDflt0 (all zeros) */ ++ scheme.keyExtractAndHashParams.numOfUsedDflts = 2; ++ scheme.keyExtractAndHashParams.dflts[0].type = e_FM_PCD_KG_IP_ADDR; ++ scheme.keyExtractAndHashParams.dflts[0].dfltSelect = ++ e_FM_PCD_KG_DFLT_PRIVATE_0; ++ scheme.keyExtractAndHashParams.dflts[1].type = e_FM_PCD_KG_L4_PORT; ++ scheme.keyExtractAndHashParams.dflts[1].dfltSelect = ++ e_FM_PCD_KG_DFLT_PRIVATE_0; ++ ++ sc->sc_scheme = FM_PCD_KgSchemeSet(sc->sc_pcdh, &scheme); ++ if (sc->sc_scheme == NULL) { ++ device_printf(sc->sc_dev, "couldn't create KeyGen scheme\n"); ++ return (ENXIO); ++ } ++ ++ device_printf(sc->sc_dev, ++ "KeyGen scheme created: baseFqid=%u, queues=%d\n", ++ sc->sc_rx_fqid, DTSEC_RX_QUEUES); ++ ++ /* --- Attach PCD to RX port --- */ ++ memset(&port_pcd, 0, sizeof(port_pcd)); ++ port_pcd.pcdSupport = e_FM_PORT_PCD_SUPPORT_PRS_AND_KG; ++ port_pcd.h_NetEnv = sc->sc_netenvh; ++ ++ memset(&prs, 0, sizeof(prs)); ++ prs.firstPrsHdr = HEADER_TYPE_ETH; ++ port_pcd.p_PrsParams = &prs; ++ ++ memset(&kg, 0, sizeof(kg)); ++ kg.numOfSchemes = 1; ++ kg.h_Schemes[0] = sc->sc_scheme; ++ kg.directScheme = TRUE; ++ kg.h_DirectScheme = sc->sc_scheme; ++ port_pcd.p_KgParams = &kg; ++ ++ error = FM_PORT_SetPCD(sc->sc_rxph, &port_pcd); ++ if (error != E_OK) { ++ device_printf(sc->sc_dev, ++ "couldn't set PCD on RX port: %d\n", error); ++ FM_PCD_KgSchemeDelete(sc->sc_scheme); ++ sc->sc_scheme = NULL; ++ return (ENXIO); ++ } ++ ++ device_printf(sc->sc_dev, "PCD enabled: PRS+KG on RX port\n"); ++ ++ ++ /* Register scheme with chardev so it can tear down PCD when ++ * userspace (FMC/dpa_app) takes over PCD management. */ ++ { ++ struct fmcd_softc *fmcd; ++ ++ fmcd = fman_get_fmcd(device_get_parent(sc->sc_dev)); ++ if (fmcd != NULL) ++ fmcd_register_rx_port_scheme(fmcd, ++ sc->sc_mac_cell_index, ++ sc->sc_scheme, &sc->sc_scheme); ++ } ++ ++ return (0); ++} ++ + void +-dtsec_rm_if_start_locked(struct dtsec_softc *sc) ++dtsec_rm_pcd_free(struct dtsec_softc *sc) + { +- vm_size_t dsize, psize, ssize; ++ ++ if (sc->sc_scheme != NULL) { ++ FM_PORT_DeletePCD(sc->sc_rxph); ++ FM_PCD_KgSchemeDelete(sc->sc_scheme); ++ sc->sc_scheme = NULL; ++ } ++} ++/** @} */ ++ ++ ++/** ++ * Fill parse result for TX checksum offload. ++ * Returns 0 on success, non-zero if the frame can't be checksummed by HW. ++ */ ++static int ++dtsec_rm_tx_csum_fill(struct dtsec_softc *sc, struct mbuf *m, ++ t_FmPrsResult *prs) ++{ ++ struct ether_header *eh; ++ struct ip *ip; ++ struct ip6_hdr *ip6; ++ uint16_t etype; ++ int ehlen; ++ ++ if (m->m_len < sizeof(*eh)) ++ return (EINVAL); ++ ++ eh = mtod(m, struct ether_header *); ++ etype = ntohs(eh->ether_type); ++ ehlen = sizeof(*eh); ++ ++ /* Handle VLAN-tagged frames */ ++ if (etype == ETHERTYPE_VLAN) { ++ if (m->m_len < sizeof(*eh) + 4) ++ return (EINVAL); ++ etype = ntohs(*(uint16_t *)((char *)eh + sizeof(*eh) + 2)); ++ ehlen += 4; ++ } ++ ++ memset(prs, 0, sizeof(*prs)); ++ ++ switch (etype) { ++ case ETHERTYPE_IP: ++ if (m->m_len < ehlen + sizeof(*ip)) ++ return (EINVAL); ++ prs->l3r = htobe16(FM_L3_PARSE_RESULT_IPV4); ++ ip = (struct ip *)((char *)eh + ehlen); ++ prs->ip_off[0] = ehlen; ++ prs->l4_off = ehlen + (ip->ip_hl << 2); ++ switch (ip->ip_p) { ++ case IPPROTO_TCP: ++ prs->l4r = FM_L4_PARSE_RESULT_TCP; ++ break; ++ case IPPROTO_UDP: ++ prs->l4r = FM_L4_PARSE_RESULT_UDP; ++ break; ++ default: ++ return (EINVAL); ++ } ++ break; ++ ++ case ETHERTYPE_IPV6: ++ if (m->m_len < ehlen + sizeof(*ip6)) ++ return (EINVAL); ++ prs->l3r = htobe16(FM_L3_PARSE_RESULT_IPV6); ++ ip6 = (struct ip6_hdr *)((char *)eh + ehlen); ++ prs->ip_off[0] = ehlen; ++ prs->l4_off = ehlen + sizeof(*ip6); ++ switch (ip6->ip6_nxt) { ++ case IPPROTO_TCP: ++ prs->l4r = FM_L4_PARSE_RESULT_TCP; ++ break; ++ case IPPROTO_UDP: ++ prs->l4r = FM_L4_PARSE_RESULT_UDP; ++ break; ++ default: ++ return (EINVAL); ++ } ++ break; ++ ++ default: ++ return (EINVAL); ++ } ++ ++ return (0); ++} ++ ++/** ++ * @group dTSEC IFnet routines. ++ * @{ ++ */ ++ ++/** ++ * Modern if_transmit entry point for RM (Regular Mode). ++ * ++ * Each CPU builds the FD and enqueues to its own per-CPU TX FQ on its ++ * own QMan portal. No locks, no sendq, no contention. The stack ++ * calls this directly with one mbuf at a time. ++ */ ++int ++dtsec_rm_if_transmit(if_t ifp, struct mbuf *m0) ++{ ++ struct dtsec_softc *sc; + struct dtsec_rm_frame_info *fi; +- unsigned int qlen, i; +- struct mbuf *m0, *m; ++ vm_size_t dsize, psize, ssize; ++ unsigned int i; ++ struct mbuf *m; + vm_offset_t vaddr; + t_DpaaFD fd; ++ int cpu, error; ++ t_DpaaSGTE *sgt; ++ void *sgt_buf; + +- DTSEC_LOCK_ASSERT(sc); +- /* TODO: IFF_DRV_OACTIVE */ ++ sc = if_getsoftc(ifp); + +- if ((sc->sc_mii->mii_media_status & IFM_ACTIVE) == 0) +- return; ++ if (__predict_false(!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))) { ++ m_freem(m0); ++ return (ENETDOWN); ++ } + +- if ((if_getdrvflags(sc->sc_ifnet) & IFF_DRV_RUNNING) != IFF_DRV_RUNNING) +- return; ++ /* Pin to current CPU for consistent FQ selection and portal use */ ++ sched_pin(); ++ cpu = curcpu % DTSEC_TX_NUM_FQS; ++ ++ /* Check per-CPU in-flight limit (software counter, no portal read) */ ++ if (__predict_false(atomic_load_int(&sc->sc_tx_inflight[cpu]) >= ++ DTSEC_MAX_TX_QUEUE_LEN)) { ++ sched_unpin(); ++ m_freem(m0); ++ if_inc_counter(ifp, IFCOUNTER_OQDROPS, 1); ++ return (ENOBUFS); ++ } + +- while (!if_sendq_empty(sc->sc_ifnet)) { +- /* Check length of the TX queue */ +- qlen = qman_fqr_get_counter(sc->sc_tx_fqr, 0, +- e_QM_FQR_COUNTERS_FRAME); ++ fi = dtsec_rm_fi_alloc(sc); ++ if (__predict_false(fi == NULL)) { ++ sched_unpin(); ++ m_freem(m0); ++ if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); ++ return (ENOBUFS); ++ } + +- if (qlen >= DTSEC_MAX_TX_QUEUE_LEN) { +- sc->sc_tx_fqr_full = 1; +- return; +- } ++ fi->fi_cpu = cpu; + +- fi = dtsec_rm_fi_alloc(sc); +- if (fi == NULL) +- return; ++ fi->fi_tx_buf = NULL; + +- m0 = if_dequeue(sc->sc_ifnet); +- if (m0 == NULL) { ++ /* ++ * TX checksum offload: build SG FD with buffer prefix ++ * containing parse result. SG entries point directly to ++ * mbuf fragment data — zero-copy, no linearization. ++ */ ++ if ((m0->m_pkthdr.csum_flags & ++ (CSUM_IP | CSUM_IP_TCP | CSUM_IP_UDP | ++ CSUM_IP6_TCP | CSUM_IP6_UDP)) && ++ sc->sc_tx_data_offset > 0) { ++ t_FmPrsResult prs; ++ t_FmPrsResult *buf_prs; ++ ++ /* Fill parse result for hardware checksum */ ++ if (dtsec_rm_tx_csum_fill(sc, m0, &prs) != 0) { ++ /* Can't offload L4 (e.g. ICMP) — compute ++ * IP header checksum in software since the ++ * stack left ip_sum=0 relying on CSUM_IP. */ ++ if (m0->m_pkthdr.csum_flags & CSUM_IP) { ++ struct ether_header *eh2; ++ struct ip *ip2; ++ uint16_t et; ++ int ehl; ++ ++ eh2 = mtod(m0, struct ether_header *); ++ et = ntohs(eh2->ether_type); ++ ehl = sizeof(*eh2); ++ if (et == ETHERTYPE_VLAN) ++ ehl += 4; ++ if (m0->m_len >= ehl + (int)sizeof(*ip2)) { ++ ip2 = (struct ip *) ++ (mtod(m0, char *) + ehl); ++ ip2->ip_sum = 0; ++ ip2->ip_sum = in_cksum_hdr(ip2); ++ } ++ } ++ m0->m_pkthdr.csum_flags = 0; ++ goto tx_sg_path; ++ } ++ ++ /* Allocate SG table buffer: [prefix | SG entries] */ ++ sgt_buf = uma_zalloc(sc->sc_sgt_zone, M_NOWAIT); ++ if (sgt_buf == NULL) { ++ sched_unpin(); + dtsec_rm_fi_free(sc, fi); +- return; ++ m_freem(m0); ++ if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); ++ return (ENOBUFS); + } ++ memset(sgt_buf, 0, sc->sc_sgt_buf_size); ++ ++ /* Store fi pointer in private data area (offset 0) */ ++ *(struct dtsec_rm_frame_info **)sgt_buf = fi; ++ ++ /* Copy parse result into prefix */ ++ buf_prs = FM_PORT_GetBufferPrsResult( ++ sc->sc_txph, (char *)sgt_buf); ++ if (buf_prs != NULL) ++ memcpy(buf_prs, &prs, sizeof(prs)); + ++ /* Build SG entries at sgt_buf + tx_data_offset */ ++ sgt = (t_DpaaSGTE *)((char *)sgt_buf + ++ sc->sc_tx_data_offset); + i = 0; +- m = m0; + psize = 0; +- dsize = 0; +- fi->fi_mbuf = m0; +- while (m && i < DPAA_NUM_OF_SG_TABLE_ENTRY) { ++ for (m = m0; m != NULL; m = m->m_next) { + if (m->m_len == 0) + continue; +- +- /* +- * First entry in scatter-gather table is used to keep +- * pointer to frame info structure. +- */ +- DPAA_SGTE_SET_ADDR(&fi->fi_sgt[i], (void *)fi); +- DPAA_SGTE_SET_LENGTH(&fi->fi_sgt[i], 0); +- +- DPAA_SGTE_SET_EXTENSION(&fi->fi_sgt[i], 0); +- DPAA_SGTE_SET_FINAL(&fi->fi_sgt[i], 0); +- DPAA_SGTE_SET_BPID(&fi->fi_sgt[i], 0); +- DPAA_SGTE_SET_OFFSET(&fi->fi_sgt[i], 0); +- i++; +- + dsize = m->m_len; + vaddr = (vm_offset_t)m->m_data; +- while (dsize > 0 && i < DPAA_NUM_OF_SG_TABLE_ENTRY) { +- ssize = PAGE_SIZE - (vaddr & PAGE_MASK); +- if (m->m_len < ssize) +- ssize = m->m_len; +- +- DPAA_SGTE_SET_ADDR(&fi->fi_sgt[i], ++ while (dsize > 0 && ++ i < DPAA_NUM_OF_SG_TABLE_ENTRY) { ++ ssize = PAGE_SIZE - ++ (vaddr & PAGE_MASK); ++ if (ssize > dsize) ++ ssize = dsize; ++ ++ DPAA_SGTE_SET_ADDR(&sgt[i], + (void *)vaddr); +- DPAA_SGTE_SET_LENGTH(&fi->fi_sgt[i], ssize); +- +- DPAA_SGTE_SET_EXTENSION(&fi->fi_sgt[i], 0); +- DPAA_SGTE_SET_FINAL(&fi->fi_sgt[i], 0); +- DPAA_SGTE_SET_BPID(&fi->fi_sgt[i], 0); +- DPAA_SGTE_SET_OFFSET(&fi->fi_sgt[i], 0); ++ DPAA_SGTE_SET_LENGTH(&sgt[i], ssize); ++ DPAA_SGTE_SET_EXTENSION(&sgt[i], 0); ++ DPAA_SGTE_SET_FINAL(&sgt[i], 0); ++ DPAA_SGTE_SET_BPID(&sgt[i], 0); ++ DPAA_SGTE_SET_OFFSET(&sgt[i], 0); + + dsize -= ssize; + vaddr += ssize; + psize += ssize; + i++; + } +- + if (dsize > 0) + break; +- +- m = m->m_next; + } + +- /* Check if SG table was constructed properly */ +- if (m != NULL || dsize != 0) { ++ if (m != NULL || i == 0) { ++ /* SG table overflow or empty — drop */ ++ sched_unpin(); ++ uma_zfree(sc->sc_sgt_zone, sgt_buf); + dtsec_rm_fi_free(sc, fi); + m_freem(m0); +- continue; ++ if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); ++ return (EIO); + } + +- DPAA_SGTE_SET_FINAL(&fi->fi_sgt[i-1], 1); +- +- DPAA_FD_SET_ADDR(&fd, fi->fi_sgt); +- DPAA_FD_SET_LENGTH(&fd, psize); +- DPAA_FD_SET_FORMAT(&fd, e_DPAA_FD_FORMAT_TYPE_SHORT_MBSF); ++ DPAA_SGTE_SET_FINAL(&sgt[i - 1], 1); + +- fd.liodn = 0; +- fd.bpid = 0; +- fd.elion = 0; +- DPAA_FD_SET_OFFSET(&fd, 0); +- DPAA_FD_SET_STATUS(&fd, 0); ++ fi->fi_mbuf = m0; ++ fi->fi_tx_buf = sgt_buf; + +- DTSEC_UNLOCK(sc); +- if (qman_fqr_enqueue(sc->sc_tx_fqr, 0, &fd) != E_OK) { ++ memset(&fd, 0, sizeof(fd)); ++ DPAA_FD_SET_ADDR(&fd, sgt_buf); ++ DPAA_FD_SET_LENGTH(&fd, psize); ++ DPAA_FD_SET_FORMAT(&fd, ++ e_DPAA_FD_FORMAT_TYPE_SHORT_MBSF); ++ DPAA_FD_SET_OFFSET(&fd, sc->sc_tx_data_offset); ++ DPAA_FD_SET_STATUS(&fd, ++ FM_FD_CMD_RPD | FM_FD_CMD_DTC); ++ ++ error = qman_fqr_enqueue(sc->sc_tx_fqs[cpu], 0, &fd); ++ if (__predict_false(error != E_OK)) { ++ sched_unpin(); ++ if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); ++ uma_zfree(sc->sc_sgt_zone, fi->fi_tx_buf); + dtsec_rm_fi_free(sc, fi); + m_freem(m0); ++ return (EIO); + } +- DTSEC_LOCK(sc); ++ ++ atomic_add_int(&sc->sc_tx_inflight[cpu], 1); ++ sched_unpin(); ++ if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); ++ if_inc_counter(ifp, IFCOUNTER_OBYTES, psize); ++ return (0); + } ++tx_sg_path: ++ ++ /* ++ * Legacy SG path (no checksum offload). ++ * First SG entry stores fi self-reference for TX confirm. ++ */ ++ i = 0; ++ psize = 0; ++ fi->fi_mbuf = m0; ++ ++ /* SGT[0]: fi pointer (metadata, zero-length) */ ++ DPAA_SGTE_SET_ADDR(&fi->fi_sgt[0], (void *)fi); ++ DPAA_SGTE_SET_LENGTH(&fi->fi_sgt[0], 0); ++ DPAA_SGTE_SET_EXTENSION(&fi->fi_sgt[0], 0); ++ DPAA_SGTE_SET_FINAL(&fi->fi_sgt[0], 0); ++ DPAA_SGTE_SET_BPID(&fi->fi_sgt[0], 0); ++ DPAA_SGTE_SET_OFFSET(&fi->fi_sgt[0], 0); ++ i = 1; ++ ++ /* SGT[1..N]: data entries from mbuf chain */ ++ for (m = m0; m != NULL && i < DPAA_NUM_OF_SG_TABLE_ENTRY; ++ m = m->m_next) { ++ if (m->m_len == 0) ++ continue; ++ ++ dsize = m->m_len; ++ vaddr = (vm_offset_t)m->m_data; ++ while (dsize > 0 && i < DPAA_NUM_OF_SG_TABLE_ENTRY) { ++ ssize = PAGE_SIZE - (vaddr & PAGE_MASK); ++ if (ssize > dsize) ++ ssize = dsize; ++ ++ DPAA_SGTE_SET_ADDR(&fi->fi_sgt[i], ++ (void *)vaddr); ++ DPAA_SGTE_SET_LENGTH(&fi->fi_sgt[i], ssize); ++ DPAA_SGTE_SET_EXTENSION(&fi->fi_sgt[i], 0); ++ DPAA_SGTE_SET_FINAL(&fi->fi_sgt[i], 0); ++ DPAA_SGTE_SET_BPID(&fi->fi_sgt[i], 0); ++ DPAA_SGTE_SET_OFFSET(&fi->fi_sgt[i], 0); ++ ++ dsize -= ssize; ++ vaddr += ssize; ++ psize += ssize; ++ i++; ++ } ++ ++ if (dsize > 0) ++ break; ++ } ++ ++ /* Check if SG table was constructed properly */ ++ if (m != NULL || psize == 0) { ++ sched_unpin(); ++ dtsec_rm_fi_free(sc, fi); ++ m_freem(m0); ++ if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); ++ return (EIO); ++ } ++ ++ DPAA_SGTE_SET_FINAL(&fi->fi_sgt[i - 1], 1); ++ ++ memset(&fd, 0, sizeof(fd)); ++ DPAA_FD_SET_ADDR(&fd, fi->fi_sgt); ++ DPAA_FD_SET_LENGTH(&fd, psize); ++ DPAA_FD_SET_FORMAT(&fd, e_DPAA_FD_FORMAT_TYPE_SHORT_MBSF); ++ DPAA_FD_SET_OFFSET(&fd, 0); ++ DPAA_FD_SET_STATUS(&fd, 0); ++ ++ error = qman_fqr_enqueue(sc->sc_tx_fqs[cpu], 0, &fd); ++ if (__predict_false(error != E_OK)) { ++ sched_unpin(); ++ if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); ++ dtsec_rm_fi_free(sc, fi); ++ m_freem(m0); ++ return (EIO); ++ } ++ ++ atomic_add_int(&sc->sc_tx_inflight[cpu], 1); ++ sched_unpin(); ++ if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); ++ if_inc_counter(ifp, IFCOUNTER_OBYTES, psize); ++ return (0); + } + /** @} */ +diff --git a/sys/dev/dpaa/if_dtsec_rm.h b/sys/dev/dpaa/if_dtsec_rm.h +index 28f779a1138..97a9ceb4be3 100644 +--- a/sys/dev/dpaa/if_dtsec_rm.h ++++ b/sys/dev/dpaa/if_dtsec_rm.h +@@ -34,7 +34,7 @@ + int dtsec_rm_fm_port_rx_init(struct dtsec_softc *sc, int unit); + int dtsec_rm_fm_port_tx_init(struct dtsec_softc *sc, int unit); + +-void dtsec_rm_if_start_locked(struct dtsec_softc *sc); ++int dtsec_rm_if_transmit(if_t ifp, struct mbuf *m); + + int dtsec_rm_pool_rx_init(struct dtsec_softc *sc); + void dtsec_rm_pool_rx_free(struct dtsec_softc *sc); +@@ -46,6 +46,10 @@ int dtsec_rm_fqr_rx_init(struct dtsec_softc *sc); + int dtsec_rm_fqr_tx_init(struct dtsec_softc *sc); + void dtsec_rm_fqr_rx_free(struct dtsec_softc *sc); + void dtsec_rm_fqr_tx_free(struct dtsec_softc *sc); ++void dtsec_release_rss_fqrs(void); ++ ++int dtsec_rm_pcd_init(struct dtsec_softc *sc); ++void dtsec_rm_pcd_free(struct dtsec_softc *sc); + /** @} */ + + #endif /* IF_DTSEC_RM_H_ */ +diff --git a/sys/dev/dpaa/memac_mdio.c b/sys/dev/dpaa/memac_mdio.c +new file mode 100644 +index 00000000000..cda5daae448 +--- /dev/null ++++ b/sys/dev/dpaa/memac_mdio.c +@@ -0,0 +1,328 @@ ++/*- ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * All rights reserved. ++ * ++ * 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 AUTHOR 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 AUTHOR 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. ++ */ ++ ++/* ++ * mEMAC external MDIO controller driver for FManv3 (fsl,fman-memac-mdio). ++ * ++ * On LS1046A, external PHYs are accessed through dedicated MDIO controllers ++ * (mdio@fc000, mdio@fd000) rather than through each MAC's internal MDIO. ++ * Register layout matches NXP's "xgmac_mdio" Linux driver. ++ * ++ * Modeled after fman_mdio.c (pqmdio) which handles the dTSEC MDIO layout. ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include ++#include ++ ++#include "miibus_if.h" ++ ++/* ++ * MDIO registers at offset 0x30 from the MDIO controller base. ++ * See struct memac_mii_access_mem_map in fsl_fman_memac_mii_acc.h. ++ */ ++#define MEMAC_MDIO_CFG 0x030 ++#define MEMAC_MDIO_CTRL 0x034 ++#define MEMAC_MDIO_DATA 0x038 ++#define MEMAC_MDIO_ADDR 0x03c ++ ++/* MDIO_CFG bits */ ++#define MDIO_CFG_BSY 0x80000000 ++#define MDIO_CFG_READ_ERR 0x00000002 ++#define MDIO_CFG_ENC45 0x00000040 ++#define MDIO_CFG_CLK_DIV_MASK 0x0080ff80 ++#define MDIO_CFG_HOLD_MASK 0x0000001c ++ ++/* MDIO_CTRL bits */ ++#define MDIO_CTL_READ 0x00008000 ++#define MDIO_CTL_PHY_ADDR_SHIFT 5 ++ ++/* MDIO_DATA bits */ ++#define MDIO_DATA_BSY 0x80000000 ++ ++#define MDIO_TIMEOUT 1000 /* iterations */ ++ ++struct memac_mdio_softc { ++ device_t sc_dev; ++ struct mtx sc_lock; ++ struct resource *sc_mem; ++}; ++ ++/* ++ * FMan registers are big-endian. bus_read_4/write_4 on ARM64 give ++ * native (little-endian) access, so we byte-swap. ++ */ ++static inline uint32_t ++memac_mdio_read(struct memac_mdio_softc *sc, bus_size_t off) ++{ ++ ++ return (be32toh(bus_read_4(sc->sc_mem, off))); ++} ++ ++static inline void ++memac_mdio_write(struct memac_mdio_softc *sc, bus_size_t off, uint32_t val) ++{ ++ ++ bus_write_4(sc->sc_mem, off, htobe32(val)); ++} ++ ++#define MDIO_LOCK() mtx_lock(&sc->sc_lock) ++#define MDIO_UNLOCK() mtx_unlock(&sc->sc_lock) ++ ++static int memac_mdio_probe(device_t dev); ++static int memac_mdio_attach(device_t dev); ++static int memac_mdio_detach(device_t dev); ++static int memac_mdio_readreg(device_t dev, int phy, int reg); ++static int memac_mdio_writereg(device_t dev, int phy, int reg, int value); ++ ++static device_method_t memac_mdio_methods[] = { ++ DEVMETHOD(device_probe, memac_mdio_probe), ++ DEVMETHOD(device_attach, memac_mdio_attach), ++ DEVMETHOD(device_detach, memac_mdio_detach), ++ ++ /* MII interface */ ++ DEVMETHOD(miibus_readreg, memac_mdio_readreg), ++ DEVMETHOD(miibus_writereg, memac_mdio_writereg), ++ ++ DEVMETHOD_END ++}; ++ ++static struct ofw_compat_data memac_mdio_compat[] = { ++ {"fsl,fman-memac-mdio", 1}, ++ {NULL, 0} ++}; ++ ++static driver_t memac_mdio_driver = { ++ "memac_mdio", ++ memac_mdio_methods, ++ sizeof(struct memac_mdio_softc), ++}; ++ ++static int ++memac_mdio_wait_free(struct memac_mdio_softc *sc) ++{ ++ int timeout; ++ ++ for (timeout = MDIO_TIMEOUT; timeout > 0; timeout--) { ++ if (!(memac_mdio_read(sc, MEMAC_MDIO_CFG) & MDIO_CFG_BSY)) ++ return (0); ++ DELAY(1); ++ } ++ return (ETIMEDOUT); ++} ++ ++static int ++memac_mdio_probe(device_t dev) ++{ ++ ++ if (!ofw_bus_status_okay(dev)) ++ return (ENXIO); ++ ++ if (!ofw_bus_search_compatible(dev, memac_mdio_compat)->ocd_str) ++ return (ENXIO); ++ ++ device_set_desc(dev, "Freescale mEMAC MDIO Controller"); ++ ++ return (BUS_PROBE_DEFAULT); ++} ++ ++static int ++memac_mdio_attach(device_t dev) ++{ ++ struct memac_mdio_softc *sc; ++ int rid; ++ ++ sc = device_get_softc(dev); ++ sc->sc_dev = dev; ++ ++ rid = 0; ++ sc->sc_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, ++ RF_ACTIVE); ++ if (sc->sc_mem == NULL) { ++ device_printf(dev, "could not allocate memory resource\n"); ++ return (ENXIO); ++ } ++ ++ OF_device_register_xref(OF_xref_from_node(ofw_bus_get_node(dev)), dev); ++ ++ mtx_init(&sc->sc_lock, device_get_nameunit(dev), ++ "mEMAC MDIO lock", MTX_DEF); ++ ++ return (0); ++} ++ ++static int ++memac_mdio_detach(device_t dev) ++{ ++ struct memac_mdio_softc *sc; ++ ++ sc = device_get_softc(dev); ++ ++ if (sc->sc_mem != NULL) ++ bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_mem); ++ ++ mtx_destroy(&sc->sc_lock); ++ ++ return (0); ++} ++ ++/* ++ * Clause 22 (1G) MDIO read. ++ * Register protocol matches fman_memac_mii_acc.c:read_phy_reg_1g(). ++ */ ++static int ++memac_mdio_readreg(device_t dev, int phy, int reg) ++{ ++ struct memac_mdio_softc *sc; ++ uint32_t cfg, ctl, data; ++ ++ sc = device_get_softc(dev); ++ ++ MDIO_LOCK(); ++ ++ /* Clause 22: clear ENC45, preserve clock divider and hold */ ++ cfg = memac_mdio_read(sc, MEMAC_MDIO_CFG); ++ cfg &= (MDIO_CFG_CLK_DIV_MASK | MDIO_CFG_HOLD_MASK); ++ memac_mdio_write(sc, MEMAC_MDIO_CFG, cfg); ++ ++ if (memac_mdio_wait_free(sc) != 0) { ++ MDIO_UNLOCK(); ++ return (0xffff); ++ } ++ ++ /* Initiate read: phy in bits [9:5], register in bits [4:0] */ ++ ctl = ((phy & 0x1f) << MDIO_CTL_PHY_ADDR_SHIFT) | (reg & 0x1f); ++ ctl |= MDIO_CTL_READ; ++ memac_mdio_write(sc, MEMAC_MDIO_CTRL, ctl); ++ ++ if (memac_mdio_wait_free(sc) != 0) { ++ MDIO_UNLOCK(); ++ return (0xffff); ++ } ++ ++ /* Wait for data valid */ ++ { ++ int timeout; ++ for (timeout = MDIO_TIMEOUT; timeout > 0; timeout--) { ++ data = memac_mdio_read(sc, MEMAC_MDIO_DATA); ++ if (!(data & MDIO_DATA_BSY)) ++ break; ++ DELAY(1); ++ } ++ if (timeout <= 0) { ++ MDIO_UNLOCK(); ++ return (0xffff); ++ } ++ } ++ ++ /* Check for read error */ ++ if (memac_mdio_read(sc, MEMAC_MDIO_CFG) & MDIO_CFG_READ_ERR) { ++ MDIO_UNLOCK(); ++ return (0xffff); ++ } ++ ++ MDIO_UNLOCK(); ++ ++ return (data & 0xffff); ++} ++ ++/* ++ * Clause 22 (1G) MDIO write. ++ * Register protocol matches fman_memac_mii_acc.c:write_phy_reg_1g(). ++ */ ++static int ++memac_mdio_writereg(device_t dev, int phy, int reg, int value) ++{ ++ struct memac_mdio_softc *sc; ++ uint32_t cfg, ctl; ++ ++ sc = device_get_softc(dev); ++ ++ MDIO_LOCK(); ++ ++ /* Clause 22: clear ENC45, preserve clock divider and hold */ ++ cfg = memac_mdio_read(sc, MEMAC_MDIO_CFG); ++ cfg &= (MDIO_CFG_CLK_DIV_MASK | MDIO_CFG_HOLD_MASK); ++ memac_mdio_write(sc, MEMAC_MDIO_CFG, cfg); ++ ++ if (memac_mdio_wait_free(sc) != 0) { ++ MDIO_UNLOCK(); ++ return (EIO); ++ } ++ ++ /* Set phy address and register */ ++ ctl = ((phy & 0x1f) << MDIO_CTL_PHY_ADDR_SHIFT) | (reg & 0x1f); ++ memac_mdio_write(sc, MEMAC_MDIO_CTRL, ctl); ++ ++ if (memac_mdio_wait_free(sc) != 0) { ++ MDIO_UNLOCK(); ++ return (EIO); ++ } ++ ++ /* Write data */ ++ memac_mdio_write(sc, MEMAC_MDIO_DATA, (uint32_t)(value & 0xffff)); ++ ++ /* Wait for write to complete */ ++ { ++ int timeout; ++ for (timeout = MDIO_TIMEOUT; timeout > 0; timeout--) { ++ if (!(memac_mdio_read(sc, MEMAC_MDIO_DATA) & ++ MDIO_DATA_BSY)) ++ break; ++ DELAY(1); ++ } ++ } ++ ++ MDIO_UNLOCK(); ++ ++ return (0); ++} ++ ++/* Probe before dtsec (BUS_PASS_SUPPORTDEV) so sc_mdio lookup succeeds */ ++EARLY_DRIVER_MODULE(memac_mdio, fman, memac_mdio_driver, 0, 0, ++ BUS_PASS_SUPPORTDEV); ++DRIVER_MODULE(miibus, memac_mdio, miibus_driver, 0, 0); ++MODULE_DEPEND(memac_mdio, miibus, 1, 1, 1); +diff --git a/sys/dev/dpaa/portals.h b/sys/dev/dpaa/portals.h +index a2d6294f3d8..3e921f6ae1b 100644 +--- a/sys/dev/dpaa/portals.h ++++ b/sys/dev/dpaa/portals.h +@@ -35,6 +35,8 @@ typedef struct dpaa_portal { + vm_paddr_t dp_ci_pa; /* portal's CI area PA */ + uint32_t dp_ce_size; /* portal's CE area size */ + uint32_t dp_ci_size; /* portal's CI area size */ ++ vm_offset_t dp_ce_va; /* per-CPU CE virtual addr */ ++ vm_offset_t dp_ci_va; /* per-CPU CI virtual addr */ + uintptr_t dp_intr_num; /* portal's intr. number */ + } dpaa_portal_t; + +@@ -60,3 +62,6 @@ int qman_portals_detach(device_t); + + int dpaa_portal_alloc_res(device_t, struct dpaa_portals_devinfo *, int); + void dpaa_portal_map_registers(struct dpaa_portals_softc *); ++#ifdef __aarch64__ ++void dpaa_portal_map_registers_cpu(struct dpaa_portals_softc *, int); ++#endif +diff --git a/sys/dev/dpaa/portals_common.c b/sys/dev/dpaa/portals_common.c +index 5ef28570b48..58e63d0f405 100644 +--- a/sys/dev/dpaa/portals_common.c ++++ b/sys/dev/dpaa/portals_common.c +@@ -39,7 +39,12 @@ + #include + + #include ++#ifdef __powerpc__ + #include ++#endif ++#ifdef __aarch64__ ++#include ++#endif + + #include + #include +@@ -70,6 +75,11 @@ dpaa_portal_alloc_res(device_t dev, struct dpaa_portals_devinfo *di, int cpu) + /* Cache enabled area */ + rle = resource_list_find(res, SYS_RES_MEMORY, 0); + sc->sc_rrid[0] = 0; ++ device_printf(dev, "CE alloc: pa=%#lx-%#lx size=%#lx dp_pa=%#lx\n", ++ (unsigned long)(rle->start + sc->sc_dp_pa), ++ (unsigned long)(rle->end + sc->sc_dp_pa), ++ (unsigned long)rle->count, ++ (unsigned long)sc->sc_dp_pa); + sc->sc_rres[0] = bus_alloc_resource(dev, + SYS_RES_MEMORY, &sc->sc_rrid[0], rle->start + sc->sc_dp_pa, + rle->end + sc->sc_dp_pa, rle->count, RF_ACTIVE); +@@ -78,11 +88,37 @@ dpaa_portal_alloc_res(device_t dev, struct dpaa_portals_devinfo *di, int cpu) + "Could not allocate cache enabled memory.\n"); + return (ENXIO); + } ++ device_printf(dev, "CE mapped: va=%#lx\n", ++ (unsigned long)rman_get_bushandle(sc->sc_rres[0])); ++#ifdef __powerpc__ + tlb1_set_entry(rman_get_bushandle(sc->sc_rres[0]), + rle->start + sc->sc_dp_pa, rle->count, _TLB_ENTRY_MEM); ++#endif ++#ifdef __aarch64__ ++ /* ++ * ARM64: The CE portal region must be Normal Non-Cacheable. ++ * Linux maps this as MEMREMAP_WC (pgprot_writecombine = ++ * Normal-NC) on ARM64. Stores go directly to the portal ++ * hardware without cache involvement. dc zva works on ++ * Normal-NC (zeros written as burst), dc cvac is a no-op. ++ */ ++ pmap_change_attr( ++ (vm_offset_t)rman_get_bushandle(sc->sc_rres[0]), ++ rle->count, VM_MEMATTR_UNCACHEABLE); ++ device_printf(dev, "CE pa_verify: va=%#lx -> pa=%#lx " ++ "(expected %#lx)\n", ++ (unsigned long)rman_get_bushandle(sc->sc_rres[0]), ++ (unsigned long)pmap_kextract( ++ (vm_offset_t)rman_get_bushandle(sc->sc_rres[0])), ++ (unsigned long)(rle->start + sc->sc_dp_pa)); ++#endif + /* Cache inhibited area */ + rle = resource_list_find(res, SYS_RES_MEMORY, 1); + sc->sc_rrid[1] = 1; ++ device_printf(dev, "CI alloc: pa=%#lx-%#lx size=%#lx\n", ++ (unsigned long)(rle->start + sc->sc_dp_pa), ++ (unsigned long)(rle->end + sc->sc_dp_pa), ++ (unsigned long)rle->count); + sc->sc_rres[1] = bus_alloc_resource(dev, + SYS_RES_MEMORY, &sc->sc_rrid[1], rle->start + sc->sc_dp_pa, + rle->end + sc->sc_dp_pa, rle->count, RF_ACTIVE); +@@ -93,8 +129,16 @@ dpaa_portal_alloc_res(device_t dev, struct dpaa_portals_devinfo *di, int cpu) + sc->sc_rrid[0], sc->sc_rres[0]); + return (ENXIO); + } ++ device_printf(dev, "CI mapped: va=%#lx\n", ++ (unsigned long)rman_get_bushandle(sc->sc_rres[1])); ++#ifdef __powerpc__ + tlb1_set_entry(rman_get_bushandle(sc->sc_rres[1]), + rle->start + sc->sc_dp_pa, rle->count, _TLB_ENTRY_IO); ++#endif ++ sc->sc_dp[cpu].dp_ce_va = ++ rman_get_bushandle(sc->sc_rres[0]); ++ sc->sc_dp[cpu].dp_ci_va = ++ rman_get_bushandle(sc->sc_rres[1]); + sc->sc_dp[cpu].dp_regs_mapped = 1; + } + /* Acquire portal's CE_PA and CI_PA */ +@@ -153,15 +197,64 @@ dpaa_portal_map_registers(struct dpaa_portals_softc *sc) + if (sc->sc_dp[cpu].dp_regs_mapped) + goto out; + ++#ifdef __powerpc__ ++ /* PowerPC: remap the shared VA to this CPU's portal PA via TLB */ + tlb1_set_entry(rman_get_bushandle(sc->sc_rres[0]), + sc->sc_dp[cpu].dp_ce_pa, sc->sc_dp[cpu].dp_ce_size, + _TLB_ENTRY_MEM); + tlb1_set_entry(rman_get_bushandle(sc->sc_rres[1]), + sc->sc_dp[cpu].dp_ci_pa, sc->sc_dp[cpu].dp_ci_size, + _TLB_ENTRY_IO); ++ sc->sc_dp[cpu].dp_ce_va = rman_get_bushandle(sc->sc_rres[0]); ++ sc->sc_dp[cpu].dp_ci_va = rman_get_bushandle(sc->sc_rres[1]); ++#endif ++#ifdef __aarch64__ ++ /* ++ * ARM64: Each CPU needs its own VA→PA mapping because we can't ++ * remap a shared VA per-CPU like PowerPC does with TLB1 entries. ++ * Map each portal's CE as Normal Non-Cacheable, CI as Device. ++ */ ++ if (sc->sc_dp[cpu].dp_ce_pa == 0) { ++ printf("dpaa_portal_map_registers: cpu %u has no portal allocated\n", cpu); ++ goto out; ++ } ++ sc->sc_dp[cpu].dp_ce_va = (vm_offset_t)pmap_mapdev_attr( ++ sc->sc_dp[cpu].dp_ce_pa, sc->sc_dp[cpu].dp_ce_size, ++ VM_MEMATTR_UNCACHEABLE); ++ sc->sc_dp[cpu].dp_ci_va = (vm_offset_t)pmap_mapdev( ++ sc->sc_dp[cpu].dp_ci_pa, sc->sc_dp[cpu].dp_ci_size); ++#endif + + sc->sc_dp[cpu].dp_regs_mapped = 1; + + out: + sched_unpin(); + } ++ ++#ifdef __aarch64__ ++/* ++ * Map portal CE/CI registers for a specific CPU. ++ * Unlike dpaa_portal_map_registers() which uses PCPU_GET(cpuid), ++ * this takes an explicit CPU parameter so it can be called from ++ * any CPU context during early boot (before smp_started=1). ++ * pmap_mapdev_attr/pmap_mapdev create global kernel VA mappings. ++ */ ++void ++dpaa_portal_map_registers_cpu(struct dpaa_portals_softc *sc, int cpu) ++{ ++ ++ if (sc->sc_dp[cpu].dp_regs_mapped) ++ return; ++ if (sc->sc_dp[cpu].dp_ce_pa == 0) { ++ printf("dpaa_portal_map_registers_cpu: " ++ "cpu %d has no portal allocated\n", cpu); ++ return; ++ } ++ sc->sc_dp[cpu].dp_ce_va = (vm_offset_t)pmap_mapdev_attr( ++ sc->sc_dp[cpu].dp_ce_pa, sc->sc_dp[cpu].dp_ce_size, ++ VM_MEMATTR_UNCACHEABLE); ++ sc->sc_dp[cpu].dp_ci_va = (vm_offset_t)pmap_mapdev( ++ sc->sc_dp[cpu].dp_ci_pa, sc->sc_dp[cpu].dp_ci_size); ++ sc->sc_dp[cpu].dp_regs_mapped = 1; ++} ++#endif +diff --git a/sys/dev/dpaa/qman.c b/sys/dev/dpaa/qman.c +index e9159f25d74..ccabb5819ef 100644 +--- a/sys/dev/dpaa/qman.c ++++ b/sys/dev/dpaa/qman.c +@@ -25,6 +25,8 @@ + */ + + #include ++#include "opt_dpaa.h" ++ + #include + #include + #include +@@ -37,16 +39,33 @@ + #include + #include + #include ++#include + + #include + #include ++#ifdef __powerpc__ + #include ++#endif ++ ++#ifdef __aarch64__ ++#include ++#include ++#include ++#include ++#endif + ++#include "bman.h" + #include "qman.h" + #include "portals.h" + ++#ifdef QMAN_CEETM_SUPPORT ++#include "qman_ceetm.h" ++#endif ++ ++#define FQD_ENTRY_SIZE 64 /* matches NCSW qm.h */ ++ + extern struct dpaa_portals_softc *qp_sc; +-static struct qman_softc *qman_sc; ++struct qman_softc *qman_sc; + + extern t_Handle qman_portal_setup(struct qman_softc *qsc); + +@@ -126,11 +145,28 @@ e_RxStoreResponse + qman_received_frame_callback(t_Handle app, t_Handle qm_fqr, t_Handle qm_portal, + uint32_t fqid_offset, t_DpaaFD *frame) + { +- struct qman_softc *sc; +- +- sc = app; +- +- device_printf(sc->sc_dev, "dummy callback for received frame.\n"); ++ static volatile int dflt_cb_count = 0; ++ t_Handle pool; ++ int n = ++dflt_cb_count; ++ ++ /* ++ * This callback fires for frames dequeued from FQs that have no ++ * registered callback (e.g., FQIDs created by FMC PCD schemes). ++ * When fqr==NULL, fqid_offset is the raw FQID, not an offset. ++ * ++ * Return the buffer to its BMan pool to prevent pool depletion. ++ */ ++ pool = bman_pool_for_bpid(frame->bpid); ++ if (pool != NULL) { ++ bman_put_buffer(pool, DPAA_FD_GET_ADDR(frame)); ++ } else if (n <= 50 || (n % 500) == 0) { ++ printf("qman: DEFAULT CB #%d: fqr=%p fqid=%u bpid=%u " ++ "status=0x%08x len=%u addr=%p [NO POOL]\n", ++ n, qm_fqr, fqid_offset, frame->bpid, ++ DPAA_FD_GET_STATUS(frame), ++ DPAA_FD_GET_LENGTH(frame), ++ DPAA_FD_GET_ADDR(frame)); ++ } + return (e_RX_STORE_RESPONSE_CONTINUE); + } + +@@ -144,14 +180,112 @@ qman_rejected_frame_callback(t_Handle app, t_Handle qm_fqr, t_Handle qm_portal, + uint32_t fqid_offset, t_DpaaFD *frame, + t_QmRejectedFrameInfo *qm_rejected_frame_info) + { ++ static int ern_count; + struct qman_softc *sc; + + sc = app; + +- device_printf(sc->sc_dev, "dummy callback for rejected frame.\n"); ++ if (ern_count++ < 20) ++ device_printf(sc->sc_dev, ++ "ERN: rejected frame fqid_off=%u rc=%d\n", ++ fqid_offset, ++ qm_rejected_frame_info ? ++ qm_rejected_frame_info->rejectionCode : -1); + return (e_RX_STORE_RESPONSE_CONTINUE); + } + ++/* ++ * Map a DT reserved-memory region for QBMan use. ++ * ++ * If the reserved-memory node has a 'reg' property (fixed physical address), ++ * the region is already excluded from phys_avail[] by early boot code ++ * (fdt_foreach_reserved_mem + no-map). We map it with pmap_mapdev_attr() ++ * as write-back cacheable — LS1046A CCI-400 provides HW coherency. ++ * ++ * Falls back to contigmalloc for nodes with only 'size' (no fixed address). ++ * ++ * Returns mapped VA, or NULL on failure. *out_size receives the size. ++ */ ++#ifdef __aarch64__ ++MALLOC_DECLARE(M_NETCOMMSW); ++ ++void * ++qbman_alloc_reserved_mem(device_t dev, phandle_t mem_node, ++ uint32_t *out_size, const char *name) ++{ ++ pcell_t reg[4]; /* addr_hi, addr_lo, size_hi, size_lo */ ++ pcell_t cells[2]; ++ uint64_t pa, size, alignment; ++ void *va; ++ ++ /* ++ * Prefer fixed physical address from 'reg' property. ++ * DT reserved-memory with no-map + reg is excluded from phys_avail[] ++ * at early boot, so this memory is never touched by the VM system. ++ */ ++ if (OF_getencprop(mem_node, "reg", reg, sizeof(reg)) == ++ sizeof(reg)) { ++ pa = ((uint64_t)reg[0] << 32) | reg[1]; ++ size = ((uint64_t)reg[2] << 32) | reg[3]; ++ ++ if (size == 0 || size > 64 * 1024 * 1024) { ++ device_printf(dev, "%s: invalid reg size %#jx\n", ++ name, (uintmax_t)size); ++ return (NULL); ++ } ++ ++ va = pmap_mapdev_attr(pa, size, VM_MEMATTR_WRITE_BACK); ++ if (va == NULL) { ++ device_printf(dev, ++ "%s: pmap_mapdev_attr(%#jx, %#jx) failed\n", ++ name, (uintmax_t)pa, (uintmax_t)size); ++ return (NULL); ++ } ++ ++ memset(va, 0, size); ++ ++ *out_size = (uint32_t)size; ++ device_printf(dev, ++ "%s: %uMB at pa=%#jx va=%p (no-map reserved)\n", ++ name, (unsigned)(size >> 20), (uintmax_t)pa, va); ++ return (va); ++ } ++ ++ /* ++ * Fallback: dynamic allocation from 'size' property. ++ */ ++ if (OF_getencprop(mem_node, "size", cells, sizeof(cells)) <= 0) { ++ device_printf(dev, "%s: no 'reg' or 'size' property\n", name); ++ return (NULL); ++ } ++ size = ((uint64_t)cells[0] << 32) | cells[1]; ++ ++ if (OF_getencprop(mem_node, "alignment", cells, sizeof(cells)) <= 0) ++ alignment = size; ++ else ++ alignment = ((uint64_t)cells[0] << 32) | cells[1]; ++ ++ if (size == 0 || size > 64 * 1024 * 1024) { ++ device_printf(dev, "%s: invalid size %#jx\n", ++ name, (uintmax_t)size); ++ return (NULL); ++ } ++ ++ va = contigmalloc(size, M_NETCOMMSW, M_WAITOK | M_ZERO, ++ 0, 0xFFFFFFFFULL, alignment, 0); ++ if (va == NULL) { ++ device_printf(dev, "%s: contigmalloc(%#jx, align=%#jx) failed\n", ++ name, (uintmax_t)size, (uintmax_t)alignment); ++ return (NULL); ++ } ++ ++ *out_size = (uint32_t)size; ++ device_printf(dev, "%s: %uMB at %p (contigmalloc, align=%#jx)\n", ++ name, (unsigned)(size >> 20), va, (uintmax_t)alignment); ++ return (va); ++} ++#endif ++ + int + qman_attach(device_t dev) + { +@@ -191,9 +325,12 @@ qman_attach(device_t dev) + if (qp_sc == NULL) + goto err; + ++#ifndef __aarch64__ + dpaa_portal_map_registers(qp_sc); ++#endif + + /* Initialize QMan */ ++ memset(&qp, 0, sizeof(qp)); + qp.guestId = NCSW_MASTER_ID; + qp.baseAddress = rman_get_bushandle(sc->sc_rres); + qp.swPortalsBaseAddress = rman_get_bushandle(qp_sc->sc_rres[0]); +@@ -209,6 +346,48 @@ qman_attach(device_t dev) + qp.partCgsBase = 0; + qp.partNumOfCgs = 0; + ++#ifdef __aarch64__ ++ /* ++ * Parse DT memory-region phandles to allocate FQD and PFDR memory ++ * from reserved-memory nodes, matching Linux's qbman_init_private_mem(). ++ * DT: memory-region = <&qman_fqd &qman_pfdr>; ++ * qman-fqd: size=0x800000 (8MB) → 131072 FQIDs ++ * qman-pfdr: size=0x2000000 (32MB) → 524288 PFDRs ++ */ ++ { ++ phandle_t node, mem_node; ++ pcell_t mem_handles[2]; ++ ++ node = ofw_bus_get_node(dev); ++ if (node > 0 && OF_getencprop(node, "memory-region", ++ (void *)mem_handles, sizeof(mem_handles)) == ++ sizeof(mem_handles)) { ++ /* Index 0 = FQD, Index 1 = PFDR */ ++ mem_node = OF_node_from_xref(mem_handles[0]); ++ if (mem_node > 0) { ++ qp.p_FqdBase = qbman_alloc_reserved_mem(dev, ++ mem_node, &qp.fqdSize, "FQD"); ++ if (qp.p_FqdBase != NULL) { ++ qp.totalNumOfFqids = ++ qp.fqdSize / FQD_ENTRY_SIZE; ++ qp.partNumOfFqids = ++ qp.totalNumOfFqids; ++ } ++ } ++ /* Index 1 = PFDR */ ++ mem_node = OF_node_from_xref(mem_handles[1]); ++ if (mem_node > 0) { ++ qp.p_PfdrBase = ++ qbman_alloc_reserved_mem(dev, ++ mem_node, &qp.pfdrSize, "PFDR"); ++ } ++ } else { ++ device_printf(dev, ++ "no memory-region property, using defaults\n"); ++ } ++ } ++#endif ++ + sc->sc_qh = QM_Config(&qp); + if (sc->sc_qh == NULL) { + device_printf(dev, "could not be configured\n"); +@@ -230,9 +409,34 @@ qman_attach(device_t dev) + device_printf(dev, "Hardware version: %d.%d.\n", + rev.majorRev, rev.minorRev); + ++#ifndef __aarch64__ ++ qman_portal_setup(sc); ++#endif ++ + sched_unpin(); + +- qman_portal_setup(sc); ++#ifdef __aarch64__ ++ /* ++ * Initialize portals for all CPUs from boot CPU. ++ * ARM64: pmap_mapdev creates global kernel VA, no sched_bind needed. ++ * SDEST configured per-portal via QM_PORTAL_ConfigStash. ++ * All portals use NAPI-style interrupt handling (FILTER + taskqueue). ++ */ ++ for (int cpu = 0; cpu < mp_ncpus; cpu++) { ++ if (qman_portal_init_cpu(sc, cpu) == NULL) ++ device_printf(dev, ++ "could not setup QMan portal on CPU %d\n", cpu); ++ else ++ device_printf(dev, ++ "QMan portal %d initialized (SDEST=%d)\n", ++ cpu, cpu / 2); ++ } ++ ++#ifdef QMAN_CEETM_SUPPORT ++ /* Initialize CEETM if DT node is present */ ++ qman_ceetm_init(); ++#endif ++#endif + + return (0); + +@@ -360,7 +564,73 @@ qman_fqr_create(uint32_t fqids_num, e_QmFQChannel channel, uint8_t wq, + goto err; + } + +- sc->sc_fqr_cpu[QM_FQR_GetFqid(fqrh)] = PCPU_GET(cpuid); ++ if (QM_FQR_GetFqid(fqrh) < QMAN_MAX_FQIDS) ++ sc->sc_fqr_cpu[QM_FQR_GetFqid(fqrh)] = PCPU_GET(cpuid); ++ ++ sched_unpin(); ++ ++ return (fqrh); ++ ++err: ++ sched_unpin(); ++ ++ return (NULL); ++} ++ ++t_Handle ++qman_fqr_create_ctx(uint32_t fqids_num, e_QmFQChannel channel, uint8_t wq, ++ bool force_fqid, uint32_t fqid_or_align, bool prefer_in_cache, ++ t_QmContextA *p_context_a, t_QmContextB *p_context_b) ++{ ++ struct qman_softc *sc; ++ t_QmFqrParams fqr; ++ t_Handle fqrh, portal; ++ ++ sc = qman_sc; ++ ++ sched_pin(); ++ ++ portal = qman_portal_setup(sc); ++ if (portal == NULL) { ++ device_printf(sc->sc_dev, "could not setup QMan portal\n"); ++ goto err; ++ } ++ ++ fqr.h_Qm = sc->sc_qh; ++ fqr.h_QmPortal = portal; ++ fqr.initParked = FALSE; ++ fqr.holdActive = FALSE; ++ fqr.preferInCache = prefer_in_cache; ++ ++ fqr.useContextAForStash = FALSE; ++ fqr.p_ContextA = p_context_a; ++ fqr.p_ContextB = p_context_b; ++ ++ fqr.channel = channel; ++ fqr.wq = wq; ++ fqr.shadowMode = FALSE; ++ fqr.numOfFqids = fqids_num; ++ ++ fqr.useForce = force_fqid; ++ if (force_fqid) ++ fqr.qs.frcQ.fqid = fqid_or_align; ++ else ++ fqr.qs.nonFrcQs.align = fqid_or_align; ++ ++ fqr.congestionAvoidanceEnable = FALSE; ++ fqr.congestionAvoidanceParams.h_QmCg = 0; ++ fqr.congestionAvoidanceParams.overheadAccountingLength = 0; ++ fqr.congestionAvoidanceParams.fqTailDropThreshold = 0; ++ ++ fqrh = QM_FQR_Create(&fqr); ++ if (fqrh == NULL) { ++ device_printf(sc->sc_dev, ++ "could not create Frame Queue Range (ctx)\n"); ++ goto err; ++ } ++ ++ if (QM_FQR_GetFqid(fqrh) < QMAN_MAX_FQIDS) ++ sc->sc_fqr_cpu[QM_FQR_GetFqid(fqrh)] = PCPU_GET(cpuid); + + sched_unpin(); + +@@ -379,9 +649,11 @@ qman_fqr_free(t_Handle fqr) + t_Error error; + + sc = qman_sc; +- thread_lock(curthread); +- sched_bind(curthread, sc->sc_fqr_cpu[QM_FQR_GetFqid(fqr)]); +- thread_unlock(curthread); ++ if (QM_FQR_GetFqid(fqr) < QMAN_MAX_FQIDS) { ++ thread_lock(curthread); ++ sched_bind(curthread, sc->sc_fqr_cpu[QM_FQR_GetFqid(fqr)]); ++ thread_unlock(curthread); ++ } + + error = QM_FQR_Free(fqr); + +@@ -545,7 +817,64 @@ qman_poll(e_QmPortalPollSource source) + } + + /* +- * TODO: add polling and/or congestion support. ++ * QMan diagnostic counters — expose QM_GetCounter to dtsec driver. + */ ++uint32_t ++qman_get_pfdr_in_use(void) ++{ ++ struct qman_softc *sc; ++ ++ sc = qman_sc; ++ if (sc == NULL || sc->sc_qh == NULL) ++ return (0); ++ ++ return (QM_GetCounter(sc->sc_qh, e_QM_COUNTERS_PFDR_IN_USE)); ++} ++ ++uint32_t ++qman_get_sfdr_in_use(void) ++{ ++ struct qman_softc *sc; ++ ++ sc = qman_sc; ++ if (sc == NULL || sc->sc_qh == NULL) ++ return (0); ++ ++ return (QM_GetCounter(sc->sc_qh, e_QM_COUNTERS_SFDR_IN_USE)); ++} ++ ++#ifdef __aarch64__ ++void ++qman_ccsr_diag(void) ++{ ++ struct qman_softc *sc; ++ uint32_t err_isr, ecsr, ecir, pfdr_fpc, sfdr_in_use; ++ uint32_t idle_stat, dcp0_cfg, dcp0_dlm_avg; ++ uint32_t dcp_dd_ihrsr, dcp_dd_hasr; ++ ++ sc = qman_sc; ++ if (sc == NULL || sc->sc_qh == NULL) ++ return; ++ ++ QM_ErrorDiag(sc->sc_qh, &err_isr, &ecsr, &ecir, &pfdr_fpc, ++ &sfdr_in_use, &idle_stat, &dcp0_cfg, &dcp0_dlm_avg, ++ &dcp_dd_ihrsr, &dcp_dd_hasr); ++ ++ printf("qman: CCSR err_isr=0x%08x ecsr=0x%08x ecir=0x%08x\n", ++ err_isr, ecsr, ecir); ++ if (ecir) { ++ printf("qman: ecir: %s portal %u fqid %u\n", ++ (ecir & 0x20000000) ? "DCP" : "SWP", ++ (ecir >> 24) & 0x1f, ++ ecir & 0x00ffffff); ++ } ++ printf("qman: pfdr_free=%u sfdr_in_use=%u idle=0x%08x\n", ++ pfdr_fpc, sfdr_in_use, idle_stat); ++ printf("qman: dcp0: cfg=0x%08x dlm_avg=0x%08x\n", ++ dcp0_cfg, dcp0_dlm_avg); ++ printf("qman: dcp_dd: ihrsr=0x%08x hasr=0x%08x\n", ++ dcp_dd_ihrsr, dcp_dd_hasr); ++} ++#endif + + /** @} */ +diff --git a/sys/dev/dpaa/qman.h b/sys/dev/dpaa/qman.h +index 815ef1f6d33..ed00f4cb8d4 100644 +--- a/sys/dev/dpaa/qman.h ++++ b/sys/dev/dpaa/qman.h +@@ -39,7 +39,7 @@ + /** + * Maximum number of frame queues in all QMans. + */ +-#define QMAN_MAX_FQIDS 16 ++#define QMAN_MAX_FQIDS 4096 + + /** + * Pool channel common to all software portals. +@@ -85,6 +85,8 @@ struct qman_softc { + * @group QMan bus interface + * @{ + */ ++extern struct qman_softc *qman_sc; ++ + int qman_attach(device_t dev); + int qman_detach(device_t dev); + int qman_suspend(device_t dev); +@@ -239,6 +241,39 @@ e_RxStoreResponse qman_rejected_frame_callback(t_Handle app, t_Handle qm_fqr, + t_Handle qm_portal, uint32_t fqid_offset, t_DpaaFD *frame, + t_QmRejectedFrameInfo *qm_rejected_frame_info); + ++/** ++ * Create Frame Queue Range with explicit contextA/B. ++ * ++ * Same as qman_fqr_create() but allows setting raw FQD contextA and ++ * contextB fields. Used by CDX to create forwarding TX FQs with ++ * OVFQ/EBD bits set for hardware flow offload. ++ * ++ * @param fqids_num Number of frame queues in the range. ++ * @param channel Dedicated channel (e.g. FMan TX port). ++ * @param wq Work Queue Number within the channel. ++ * @param force_fqid If TRUE, force allocation of specific FQID. ++ * @param fqid_or_align FQID if force_fqid, alignment otherwise. ++ * @param prefer_in_cache If TRUE, prefer QMan internal cache. ++ * @param p_context_a Raw contextA (8 bytes), or NULL. ++ * @param p_context_b Raw contextB (4 bytes), or NULL. ++ * @return NCSW FQR handle, or NULL on failure. ++ */ ++t_Handle qman_fqr_create_ctx(uint32_t fqids_num, e_QmFQChannel channel, ++ uint8_t wq, bool force_fqid, uint32_t fqid_or_align, ++ bool prefer_in_cache, t_QmContextA *p_context_a, ++ t_QmContextB *p_context_b); ++ ++uint32_t qman_get_pfdr_in_use(void); ++uint32_t qman_get_sfdr_in_use(void); ++ ++#ifdef __aarch64__ ++t_Handle qman_portal_init_cpu(struct qman_softc *, int); ++void qman_portal_dqrr_diag(void); ++void qman_ccsr_diag(void); ++struct mbuf; ++void qman_rx_defer(struct mbuf *); ++#endif ++ + /** @} */ + + #endif /* QMAN_H */ +diff --git a/sys/dev/dpaa/qman_ceetm.c b/sys/dev/dpaa/qman_ceetm.c +new file mode 100644 +index 00000000000..5e5cf4f64e4 +--- /dev/null ++++ b/sys/dev/dpaa/qman_ceetm.c +@@ -0,0 +1,1874 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * QMan CEETM (Channel Egress Enhancement and Traffic Management) driver ++ * for FreeBSD. Ported from the Linux NXP QBMan SDK driver. ++ * ++ * Original Linux source: ++ * drivers/staging/fsl_qbman/qman_high.c (API implementation) ++ * drivers/staging/fsl_qbman/qman_driver.c (DT init) ++ * drivers/staging/fsl_qbman/qman_config.c (CCSR registers) ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++ ++/* NCSW internal headers — accessible because we compile with DPAA_COMPILE_CMD */ ++#include "qm.h" ++#include "qman_low.h" ++ ++/* FreeBSD DPAA headers */ ++#include "qman.h" ++#include "qman_ceetm.h" ++ ++MALLOC_DECLARE(M_NETCOMMSW); ++ ++/* ================================================================ ++ * Global State ++ * ================================================================ */ ++ ++uint8_t qman_num_ceetms; ++struct qm_ceetm qman_ceetms[QMAN_CEETM_MAX]; ++ ++/* QMan clock frequency (Hz) — set during init from DT or default */ ++static uint32_t qman_clk; ++ ++/* CEETM update period in nanoseconds (default 1µs) */ ++#define CEETM_UPDATE_PERIOD_NS 1000 ++ ++/* LFQID and Channel allocators — simple bitmaps */ ++#define CEETM_MAX_LFQIDS 4096 ++#define CEETM_MAX_CHANNELS 32 ++ ++struct ceetm_pool { ++ uint32_t base; ++ uint32_t count; ++ uint32_t bitmap[CEETM_MAX_LFQIDS / 32]; /* max size */ ++}; ++ ++static struct ceetm_pool ceetm_lfqid_pool[QMAN_CEETM_MAX]; ++static struct ceetm_pool ceetm_channel_pool[QMAN_CEETM_MAX]; ++static struct mtx ceetm_alloc_lock; ++ ++static void ++ceetm_pool_seed(struct ceetm_pool *pool, uint32_t base, uint32_t count) ++{ ++ pool->base = base; ++ pool->count = count; ++ memset(pool->bitmap, 0, sizeof(pool->bitmap)); ++} ++ ++static int ++ceetm_pool_alloc(struct ceetm_pool *pool, uint32_t *id) ++{ ++ unsigned int i; ++ ++ mtx_lock(&ceetm_alloc_lock); ++ for (i = 0; i < pool->count; i++) { ++ if (!(pool->bitmap[i / 32] & (1U << (i % 32)))) { ++ pool->bitmap[i / 32] |= (1U << (i % 32)); ++ *id = pool->base + i; ++ mtx_unlock(&ceetm_alloc_lock); ++ return (0); ++ } ++ } ++ mtx_unlock(&ceetm_alloc_lock); ++ return (ENOSPC); ++} ++ ++static void ++ceetm_pool_free(struct ceetm_pool *pool, uint32_t id) ++{ ++ unsigned int idx; ++ ++ if (id < pool->base || id >= pool->base + pool->count) ++ return; ++ idx = id - pool->base; ++ mtx_lock(&ceetm_alloc_lock); ++ pool->bitmap[idx / 32] &= ~(1U << (idx % 32)); ++ mtx_unlock(&ceetm_alloc_lock); ++} ++ ++/* ================================================================ ++ * Portal MC (Management Command) Helpers ++ * ++ * Pattern: sched_pin → get portal → NCSW_PLOCK → mc_start → ++ * fill command → mc_commit → spin on mc_result → ++ * check result → PUNLOCK → sched_unpin ++ * ================================================================ */ ++ ++/* ++ * Get the current CPU's NCSW QM portal, with preemption pinned. ++ * Caller must have called sched_pin() first. ++ */ ++static inline t_QmPortal * ++ceetm_get_portal(void) ++{ ++ return ((t_QmPortal *)qman_sc->sc_qph[PCPU_GET(cpuid)]); ++} ++ ++/* ++ * Get the t_Qm handle for CCSR register access. ++ */ ++static inline t_Qm * ++ceetm_get_qm(void) ++{ ++ return ((t_Qm *)qman_sc->sc_qh); ++} ++ ++/* ++ * CCSR register read/write — for registers not in t_QmRegs struct. ++ * Uses byte offset from QMan CCSR base. ++ */ ++static inline uint32_t ++ceetm_ccsr_read(uint32_t offset) ++{ ++ volatile uint32_t *reg; ++ ++ reg = (volatile uint32_t *)((uint8_t *)ceetm_get_qm()->p_QmRegs + ++ offset); ++ return (GET_UINT32(*reg)); ++} ++ ++static inline void ++ceetm_ccsr_write(uint32_t offset, uint32_t val) ++{ ++ volatile uint32_t *reg; ++ ++ reg = (volatile uint32_t *)((uint8_t *)ceetm_get_qm()->p_QmRegs + ++ offset); ++ WRITE_UINT32(*reg, val); ++} ++ ++/* Rounding helper for integer division */ ++static inline uint64_t ++ceetm_div_round(uint64_t n, uint64_t d, int rounding) ++{ ++ if (rounding < 0) ++ return (n / d); /* round down */ ++ else if (rounding > 0) ++ return ((n + d - 1) / d); /* round up */ ++ else ++ return ((n + d / 2) / d); /* round nearest */ ++} ++ ++/* ================================================================ ++ * CCSR Register Access Functions ++ * ================================================================ */ ++ ++int ++qman_sp_enable_ceetm_mode(enum qm_dc_portal portal, uint16_t sub_portal) ++{ ++ uint32_t dcp_cfg; ++ t_Qm *qm; ++ ++ if (qman_num_ceetms == 0) ++ return (ENODEV); ++ ++ qm = ceetm_get_qm(); ++ dcp_cfg = GET_UINT32(qm->p_QmRegs->dcpConfRegs[portal].cfg); ++ dcp_cfg |= QM_SP_ENABLE_CEETM(sub_portal); ++ WRITE_UINT32(qm->p_QmRegs->dcpConfRegs[portal].cfg, dcp_cfg); ++ return (0); ++} ++ ++int ++qman_sp_disable_ceetm_mode(enum qm_dc_portal portal, uint16_t sub_portal) ++{ ++ uint32_t dcp_cfg; ++ t_Qm *qm; ++ ++ if (qman_num_ceetms == 0) ++ return (ENODEV); ++ ++ qm = ceetm_get_qm(); ++ dcp_cfg = GET_UINT32(qm->p_QmRegs->dcpConfRegs[portal].cfg); ++ dcp_cfg &= ~QM_SP_ENABLE_CEETM(sub_portal); ++ WRITE_UINT32(qm->p_QmRegs->dcpConfRegs[portal].cfg, dcp_cfg); ++ return (0); ++} ++ ++int ++qman_ceetm_get_xsfdr(enum qm_dc_portal portal, unsigned int *num) ++{ ++ if (qman_num_ceetms == 0) ++ return (ENODEV); ++ *num = ceetm_ccsr_read(QM_REG_CEETM_XSFDR_IN_USE); ++ return (0); ++} ++ ++static int ++qman_ceetm_set_prescaler(enum qm_dc_portal portal) ++{ ++ uint64_t temp; ++ uint16_t pres; ++ ++ if (qman_clk == 0) ++ return (EINVAL); ++ ++ /* ++ * PRES = (2^22 * 10^9 / update_period_ns) / qman_clk ++ * Split to avoid 64-bit overflow: ++ * temp = 0x400000 * 100 ++ * temp /= (update_period_ns / 10000000) ++ * But simpler: temp = (0x400000ULL * 1000000000ULL) / (period * clk) ++ */ ++ temp = 0x400000ULL * 100; ++ temp /= CEETM_UPDATE_PERIOD_NS; ++ temp *= 10000000; ++ temp /= qman_clk; ++ pres = (uint16_t)temp; ++ ++ ceetm_ccsr_write(QM_REG_CEETM_CFG_IDX, portal); ++ ceetm_ccsr_write(QM_REG_CEETM_CFG_PRES, pres); ++ return (0); ++} ++ ++static int ++qman_ceetm_get_prescaler(uint16_t *pres) ++{ ++ if (qman_num_ceetms == 0) ++ return (ENODEV); ++ *pres = (uint16_t)ceetm_ccsr_read(QM_REG_CEETM_CFG_PRES); ++ return (0); ++} ++ ++/* ================================================================ ++ * Low-Level MC Command Wrappers ++ * ++ * Each sends a single MC command and returns the result code. ++ * The command struct is filled by the caller; these functions handle ++ * portal lock/unlock, commit, and result polling. ++ * ================================================================ */ ++ ++/* ++ * Generic MC command execution pattern. ++ * cmd points to the filled command struct (excluding verb byte). ++ * cmd_size is the size of the command struct. ++ * verb is the CEETM verb code. ++ * result is filled with the 64-byte result on success. ++ * Returns 0 on success, error code otherwise. ++ */ ++static int ++ceetm_mc_command(uint8_t verb, const void *cmd, size_t cmd_size, ++ void *result, size_t result_size) ++{ ++ t_QmPortal *portal; ++ struct qm_portal *low; ++ struct qm_mc_command *mcc; ++ struct qm_mc_result *mcr; ++ struct qm_mcr_ceetm_generic *gen; ++ int timeout; ++ ++ sched_pin(); ++ portal = ceetm_get_portal(); ++ if (portal == NULL) { ++ sched_unpin(); ++ return (ENXIO); ++ } ++ ++ low = portal->p_LowQmPortal; ++ NCSW_PLOCK(portal); ++ ++ mcc = qm_mc_start(low); ++ if (mcc == NULL) { ++ PUNLOCK(portal); ++ sched_unpin(); ++ return (EBUSY); ++ } ++ ++ /* Copy command data after the verb byte */ ++ memcpy((uint8_t *)mcc + 1, cmd, cmd_size); ++ qm_mc_commit(low, verb); ++ ++ /* Poll for result */ ++ timeout = 10000; ++ do { ++ mcr = qm_mc_result(low); ++ if (mcr != NULL) ++ break; ++ cpu_spinwait(); ++ } while (--timeout > 0); ++ ++ PUNLOCK(portal); ++ sched_unpin(); ++ ++ if (timeout == 0) { ++ printf("ceetm: MC command 0x%02x timeout\n", verb); ++ return (ETIMEDOUT); ++ } ++ ++ /* Check result code */ ++ gen = (struct qm_mcr_ceetm_generic *)mcr; ++ if (gen->result != QM_MCR_RESULT_OK) { ++ printf("ceetm: MC command 0x%02x failed, result=0x%02x\n", ++ verb, gen->result); ++ return (EIO); ++ } ++ ++ if (result != NULL && result_size > 0) ++ memcpy(result, mcr, result_size); ++ return (0); ++} ++ ++/* Convenience wrappers for config (no result needed) and query (result needed) */ ++static int ++ceetm_mc_config(uint8_t verb, const void *cmd, size_t cmd_size) ++{ ++ return (ceetm_mc_command(verb, cmd, cmd_size, NULL, 0)); ++} ++ ++static int ++ceetm_mc_query(uint8_t verb, const void *cmd, size_t cmd_size, ++ void *result, size_t result_size) ++{ ++ return (ceetm_mc_command(verb, cmd, cmd_size, result, result_size)); ++} ++ ++/* ================================================================ ++ * Pure Math Functions ++ * ================================================================ */ ++ ++int ++qman_ceetm_bps2tokenrate(uint64_t bps, struct qm_ceetm_rate *token_rate, ++ int rounding) ++{ ++ uint16_t pres; ++ uint64_t temp, qman_freq; ++ int ret; ++ ++ ret = qman_ceetm_get_prescaler(&pres); ++ if (ret) ++ return (EINVAL); ++ if (pres == 0) ++ return (EINVAL); ++ ++ qman_freq = (uint64_t)qman_clk; ++ if (qman_freq == 0) ++ return (EINVAL); ++ ++ /* ++ * N = (bps * 2^32) / (PRES * QHz) ++ * Split into two 16-bit shifts to avoid overflow: ++ * N = (((bps << 16) / PRES) << 16) / QHz ++ */ ++ temp = ceetm_div_round(bps << 16, pres, rounding); ++ temp = ceetm_div_round(temp << 16, qman_freq, rounding); ++ token_rate->whole = (uint32_t)(temp >> 13); ++ token_rate->fraction = (uint32_t)(temp & 0x1FFF); ++ return (0); ++} ++ ++int ++qman_ceetm_tokenrate2bps(const struct qm_ceetm_rate *token_rate, ++ uint64_t *bps, int rounding) ++{ ++ uint16_t pres; ++ uint64_t temp, qman_freq; ++ int ret; ++ ++ ret = qman_ceetm_get_prescaler(&pres); ++ if (ret) ++ return (EINVAL); ++ ++ qman_freq = (uint64_t)qman_clk; ++ if (qman_freq == 0) ++ return (EINVAL); ++ ++ /* ++ * bps = N * PRES * QHz / 2^32 ++ * Split: temp = (PRES * QHz) >> 16, then bps = (temp * N) >> 16 ++ */ ++ temp = ceetm_div_round(qman_freq * pres, (uint64_t)1 << 16, rounding); ++ temp *= ((uint64_t)token_rate->whole << 13) + token_rate->fraction; ++ *bps = ceetm_div_round(temp, (uint64_t)1 << 16, rounding); ++ return (0); ++} ++ ++/* ++ * Find greatest common divisor. ++ */ ++static uint32_t ++ceetm_gcd(uint32_t a, uint32_t b) ++{ ++ while (b != 0) { ++ uint32_t t = b; ++ b = a % b; ++ a = t; ++ } ++ return (a); ++} ++ ++int ++qman_ceetm_ratio2wbfs(uint32_t numerator, uint32_t denominator, ++ struct qm_ceetm_weight_code *weight_code, int rounding) ++{ ++ uint32_t g; ++ uint64_t n, d; ++ int best_err; ++ ++ if (denominator == 0 || numerator == 0) ++ return (EINVAL); ++ ++ /* Reduce fraction */ ++ g = ceetm_gcd(numerator, denominator); ++ n = numerator / g; ++ d = denominator / g; ++ ++ /* ++ * WBFS weight = 2^(x+6) / (64-y) ++ * Find (x,y) such that n/d ~ 2^(x+6)/(64-y) ++ * i.e., y ~ 64 - d * 2^(x+6) / n ++ */ ++ best_err = INT_MAX; ++ weight_code->x = 0; ++ weight_code->y = 0; ++ ++ for (uint8_t x = 0; x <= 7; x++) { ++ int64_t ideal_64_minus_y; ++ int64_t y_candidate; ++ int err; ++ ++ ideal_64_minus_y = (int64_t)((d * ((uint64_t)1 << (x + 6))) / ++ n); ++ y_candidate = 64 - ideal_64_minus_y; ++ ++ if (y_candidate < 0) ++ y_candidate = 0; ++ if (y_candidate > 31) ++ y_candidate = 31; ++ ++ /* Check error */ ++ err = (int)((int64_t)n * (64 - y_candidate) - ++ (int64_t)d * ((uint64_t)1 << (x + 6))); ++ if (err < 0) ++ err = -err; ++ ++ if (err < best_err) { ++ best_err = err; ++ weight_code->x = x; ++ weight_code->y = (uint8_t)y_candidate; ++ if (err == 0) ++ break; ++ } ++ } ++ return (0); ++} ++ ++int ++qman_ceetm_wbfs2ratio(struct qm_ceetm_weight_code *weight_code, ++ uint32_t *numerator, uint32_t *denominator) ++{ ++ uint32_t g; ++ ++ /* weight = 2^(x+6) / (64-y) */ ++ *numerator = 1U << (weight_code->x + 6); ++ *denominator = 64 - weight_code->y; ++ if (*denominator == 0) ++ return (EINVAL); ++ ++ g = ceetm_gcd(*numerator, *denominator); ++ *numerator /= g; ++ *denominator /= g; ++ return (0); ++} ++ ++/* ================================================================ ++ * Sub-Portal Management ++ * ================================================================ */ ++ ++int ++qman_ceetm_sp_claim(struct qm_ceetm_sp **sp, enum qm_dc_portal dcp_idx, ++ unsigned int sp_idx) ++{ ++ struct qm_ceetm_sp *p; ++ ++ if (dcp_idx >= qman_num_ceetms) ++ return (EINVAL); ++ if (sp_idx < qman_ceetms[dcp_idx].sp_range[0] || ++ sp_idx >= qman_ceetms[dcp_idx].sp_range[0] + ++ qman_ceetms[dcp_idx].sp_range[1]) ++ return (EINVAL); ++ ++ TAILQ_FOREACH(p, &qman_ceetms[dcp_idx].sub_portals, entries) { ++ if (p->idx == sp_idx) { ++ if (p->is_claimed) ++ return (EBUSY); ++ p->is_claimed = 1; ++ *sp = p; ++ return (0); ++ } ++ } ++ return (ENOENT); ++} ++ ++int ++qman_ceetm_sp_release(struct qm_ceetm_sp *sp) ++{ ++ if (sp == NULL) ++ return (EINVAL); ++ if (sp->lni != NULL) ++ qman_sp_disable_ceetm_mode(sp->dcp_idx, sp->idx); ++ sp->lni = NULL; ++ sp->is_claimed = 0; ++ return (0); ++} ++ ++int ++qman_ceetm_sp_set_lni(struct qm_ceetm_sp *sp, struct qm_ceetm_lni *lni) ++{ ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_config cmd; ++ int ret; ++ ++ if (sp == NULL || lni == NULL) ++ return (EINVAL); ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cid = htobe16(CEETM_COMMAND_SP_MAPPING | sp->idx); ++ cmd.dcpid = sp->dcp_idx; ++ cmd.sp_mapping.map_flags = lni->idx & 0x07; ++ ++ ret = ceetm_mc_config(QM_CEETM_VERB_MAPPING_SHAPER_TCFC_CONFIG, ++ &cmd, sizeof(cmd)); ++ if (ret) ++ return (ret); ++ ++ sp->lni = lni; ++ lni->sp = sp; ++ qman_sp_enable_ceetm_mode(sp->dcp_idx, sp->idx); ++ return (0); ++} ++ ++int ++qman_ceetm_sp_get_lni(struct qm_ceetm_sp *sp, unsigned int *lni_idx) ++{ ++ if (sp == NULL || sp->lni == NULL) ++ return (EINVAL); ++ *lni_idx = sp->lni->idx; ++ return (0); ++} ++ ++/* ================================================================ ++ * LNI Management ++ * ================================================================ */ ++ ++int ++qman_ceetm_lni_claim(struct qm_ceetm_lni **lni, enum qm_dc_portal dcp_idx, ++ unsigned int lni_idx) ++{ ++ struct qm_ceetm_lni *p; ++ ++ if (dcp_idx >= qman_num_ceetms) ++ return (EINVAL); ++ ++ TAILQ_FOREACH(p, &qman_ceetms[dcp_idx].lnis, entries) { ++ if (p->idx == lni_idx) { ++ if (p->is_claimed) ++ return (EBUSY); ++ p->is_claimed = 1; ++ *lni = p; ++ return (0); ++ } ++ } ++ return (ENOENT); ++} ++ ++int ++qman_ceetm_lni_release(struct qm_ceetm_lni *lni) ++{ ++ if (lni == NULL) ++ return (EINVAL); ++ if (lni->shaper_enable) ++ qman_ceetm_lni_disable_shaper(lni); ++ lni->sp = NULL; ++ lni->is_claimed = 0; ++ return (0); ++} ++ ++int ++qman_ceetm_lni_enable_shaper(struct qm_ceetm_lni *lni, int coupled, int oal) ++{ ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_config cmd; ++ int ret; ++ ++ if (lni == NULL) ++ return (EINVAL); ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cid = htobe16(CEETM_COMMAND_LNI_SHAPER | lni->idx); ++ cmd.dcpid = lni->dcp_idx; ++ cmd.shaper_config.cpl_oal = (coupled ? 0x80 : 0) | (oal & 0x1F); ++ cmd.shaper_config.crtcr_hi = (lni->cr_token_rate.whole >> 8) & 0x07; ++ cmd.shaper_config.crtcr_lo = htobe16( ++ ((lni->cr_token_rate.whole & 0xFF) << 13) | ++ (lni->cr_token_rate.fraction & 0x1FFF)); ++ cmd.shaper_config.ertcr_hi = (lni->er_token_rate.whole >> 8) & 0x07; ++ cmd.shaper_config.ertcr_lo = htobe16( ++ ((lni->er_token_rate.whole & 0xFF) << 13) | ++ (lni->er_token_rate.fraction & 0x1FFF)); ++ cmd.shaper_config.crtbl = htobe16(lni->cr_token_bucket_limit); ++ cmd.shaper_config.ertbl = htobe16(lni->er_token_bucket_limit); ++ ++ ret = ceetm_mc_config(QM_CEETM_VERB_MAPPING_SHAPER_TCFC_CONFIG, ++ &cmd, sizeof(cmd)); ++ if (ret) ++ return (ret); ++ ++ lni->shaper_enable = 1; ++ lni->shaper_couple = coupled; ++ lni->oal = oal; ++ return (0); ++} ++ ++int ++qman_ceetm_lni_disable_shaper(struct qm_ceetm_lni *lni) ++{ ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_config cmd; ++ int ret; ++ ++ if (lni == NULL) ++ return (EINVAL); ++ ++ /* Write zero rates to disable shaper */ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cid = htobe16(CEETM_COMMAND_LNI_SHAPER | lni->idx); ++ cmd.dcpid = lni->dcp_idx; ++ ++ ret = ceetm_mc_config(QM_CEETM_VERB_MAPPING_SHAPER_TCFC_CONFIG, ++ &cmd, sizeof(cmd)); ++ if (ret) ++ return (ret); ++ ++ lni->shaper_enable = 0; ++ return (0); ++} ++ ++int ++qman_ceetm_lni_is_shaper_enabled(struct qm_ceetm_lni *lni) ++{ ++ if (lni == NULL) ++ return (0); ++ return (lni->shaper_enable); ++} ++ ++int ++qman_ceetm_lni_set_commit_rate(struct qm_ceetm_lni *lni, ++ const struct qm_ceetm_rate *cr, uint16_t cr_limit) ++{ ++ if (lni == NULL || cr == NULL) ++ return (EINVAL); ++ ++ lni->cr_token_rate = *cr; ++ lni->cr_token_bucket_limit = cr_limit; ++ ++ /* If shaper is already enabled, re-program */ ++ if (lni->shaper_enable) ++ return (qman_ceetm_lni_enable_shaper(lni, ++ lni->shaper_couple, lni->oal)); ++ return (0); ++} ++ ++int ++qman_ceetm_lni_set_excess_rate(struct qm_ceetm_lni *lni, ++ const struct qm_ceetm_rate *er, uint16_t er_limit) ++{ ++ if (lni == NULL || er == NULL) ++ return (EINVAL); ++ ++ lni->er_token_rate = *er; ++ lni->er_token_bucket_limit = er_limit; ++ ++ if (lni->shaper_enable) ++ return (qman_ceetm_lni_enable_shaper(lni, ++ lni->shaper_couple, lni->oal)); ++ return (0); ++} ++ ++int ++qman_ceetm_lni_get_commit_rate(struct qm_ceetm_lni *lni, ++ struct qm_ceetm_rate *cr, uint16_t *cr_limit) ++{ ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_query qcmd; ++ struct qm_mcr_ceetm_mapping_shaper_tcfc_query qr; ++ uint32_t tcr; ++ int ret; ++ ++ if (lni == NULL) ++ return (EINVAL); ++ ++ memset(&qcmd, 0, sizeof(qcmd)); ++ qcmd.cid = htobe16(CEETM_COMMAND_LNI_SHAPER | lni->idx); ++ qcmd.dcpid = lni->dcp_idx; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_MAPPING_SHAPER_TCFC_QUERY, ++ &qcmd, sizeof(qcmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ tcr = ((uint32_t)qr.shaper_query.crtcr_hi << 16) | ++ be16toh(qr.shaper_query.crtcr_lo); ++ if (cr != NULL) { ++ cr->whole = tcr >> 13; ++ cr->fraction = tcr & 0x1FFF; ++ } ++ if (cr_limit != NULL) ++ *cr_limit = be16toh(qr.shaper_query.crtbl); ++ return (0); ++} ++ ++int ++qman_ceetm_lni_get_excess_rate(struct qm_ceetm_lni *lni, ++ struct qm_ceetm_rate *er, uint16_t *er_limit) ++{ ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_query qcmd; ++ struct qm_mcr_ceetm_mapping_shaper_tcfc_query qr; ++ uint32_t tcr; ++ int ret; ++ ++ if (lni == NULL) ++ return (EINVAL); ++ ++ memset(&qcmd, 0, sizeof(qcmd)); ++ qcmd.cid = htobe16(CEETM_COMMAND_LNI_SHAPER | lni->idx); ++ qcmd.dcpid = lni->dcp_idx; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_MAPPING_SHAPER_TCFC_QUERY, ++ &qcmd, sizeof(qcmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ tcr = ((uint32_t)qr.shaper_query.ertcr_hi << 16) | ++ be16toh(qr.shaper_query.ertcr_lo); ++ if (er != NULL) { ++ er->whole = tcr >> 13; ++ er->fraction = tcr & 0x1FFF; ++ } ++ if (er_limit != NULL) ++ *er_limit = be16toh(qr.shaper_query.ertbl); ++ return (0); ++} ++ ++/* ================================================================ ++ * Channel Management ++ * ================================================================ */ ++ ++int ++qman_ceetm_channel_claim(struct qm_ceetm_channel **channel, ++ struct qm_ceetm_lni *lni) ++{ ++ struct qm_ceetm_channel *ch; ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_config cmd; ++ uint32_t ch_id; ++ int ret; ++ ++ if (lni == NULL || channel == NULL) ++ return (EINVAL); ++ ++ ret = ceetm_pool_alloc(&ceetm_channel_pool[lni->dcp_idx], &ch_id); ++ if (ret) ++ return (ret); ++ ++ ch = malloc(sizeof(*ch), M_NETCOMMSW, M_NOWAIT | M_ZERO); ++ if (ch == NULL) { ++ ceetm_pool_free(&ceetm_channel_pool[lni->dcp_idx], ch_id); ++ return (ENOMEM); ++ } ++ ++ ch->idx = ch_id; ++ ch->lni = lni; ++ ch->lni_idx = lni->idx; ++ ch->dcp_idx = lni->dcp_idx; ++ TAILQ_INIT(&ch->class_queues); ++ TAILQ_INIT(&ch->ccgs); ++ ++ /* Map channel to LNI */ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cid = htobe16(CEETM_COMMAND_CHANNEL_MAPPING | ch->idx); ++ cmd.dcpid = ch->dcp_idx; ++ cmd.channel_mapping.map_flags = lni->idx & 0x07; ++ ++ ret = ceetm_mc_config(QM_CEETM_VERB_MAPPING_SHAPER_TCFC_CONFIG, ++ &cmd, sizeof(cmd)); ++ if (ret) { ++ ceetm_pool_free(&ceetm_channel_pool[lni->dcp_idx], ch_id); ++ free(ch, M_NETCOMMSW); ++ return (ret); ++ } ++ ++ TAILQ_INSERT_TAIL(&lni->channels, ch, entries); ++ *channel = ch; ++ return (0); ++} ++ ++int ++qman_ceetm_channel_release(struct qm_ceetm_channel *channel) ++{ ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_config cmd; ++ ++ if (channel == NULL) ++ return (EINVAL); ++ ++ /* Disable shaper if enabled */ ++ if (channel->shaper_enable) ++ qman_ceetm_channel_disable_shaper(channel); ++ ++ /* Clear channel mapping */ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cid = htobe16(CEETM_COMMAND_CHANNEL_MAPPING | channel->idx); ++ cmd.dcpid = channel->dcp_idx; ++ ceetm_mc_config(QM_CEETM_VERB_MAPPING_SHAPER_TCFC_CONFIG, ++ &cmd, sizeof(cmd)); ++ ++ ceetm_pool_free(&ceetm_channel_pool[channel->dcp_idx], channel->idx); ++ if (channel->lni != NULL) ++ TAILQ_REMOVE(&channel->lni->channels, channel, entries); ++ free(channel, M_NETCOMMSW); ++ return (0); ++} ++ ++int ++qman_ceetm_channel_enable_shaper(struct qm_ceetm_channel *channel, ++ int coupled) ++{ ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_config cmd; ++ int ret; ++ ++ if (channel == NULL) ++ return (EINVAL); ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cid = htobe16(CEETM_COMMAND_CHANNEL_SHAPER | channel->idx); ++ cmd.dcpid = channel->dcp_idx; ++ cmd.shaper_config.cpl_oal = coupled ? 0x80 : 0; ++ cmd.shaper_config.crtcr_hi = ++ (channel->cr_token_rate.whole >> 8) & 0x07; ++ cmd.shaper_config.crtcr_lo = htobe16( ++ ((channel->cr_token_rate.whole & 0xFF) << 13) | ++ (channel->cr_token_rate.fraction & 0x1FFF)); ++ cmd.shaper_config.ertcr_hi = ++ (channel->er_token_rate.whole >> 8) & 0x07; ++ cmd.shaper_config.ertcr_lo = htobe16( ++ ((channel->er_token_rate.whole & 0xFF) << 13) | ++ (channel->er_token_rate.fraction & 0x1FFF)); ++ cmd.shaper_config.crtbl = htobe16(channel->cr_token_bucket_limit); ++ cmd.shaper_config.ertbl = htobe16(channel->er_token_bucket_limit); ++ ++ ret = ceetm_mc_config(QM_CEETM_VERB_MAPPING_SHAPER_TCFC_CONFIG, ++ &cmd, sizeof(cmd)); ++ if (ret) ++ return (ret); ++ ++ channel->shaper_enable = 1; ++ channel->shaper_couple = coupled; ++ return (0); ++} ++ ++int ++qman_ceetm_channel_disable_shaper(struct qm_ceetm_channel *channel) ++{ ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_config cmd; ++ int ret; ++ ++ if (channel == NULL) ++ return (EINVAL); ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cid = htobe16(CEETM_COMMAND_CHANNEL_SHAPER | channel->idx); ++ cmd.dcpid = channel->dcp_idx; ++ ++ ret = ceetm_mc_config(QM_CEETM_VERB_MAPPING_SHAPER_TCFC_CONFIG, ++ &cmd, sizeof(cmd)); ++ if (ret) ++ return (ret); ++ ++ channel->shaper_enable = 0; ++ return (0); ++} ++ ++int ++qman_ceetm_channel_is_shaper_enabled(struct qm_ceetm_channel *channel) ++{ ++ if (channel == NULL) ++ return (0); ++ return (channel->shaper_enable); ++} ++ ++int ++qman_ceetm_channel_set_commit_rate(struct qm_ceetm_channel *channel, ++ const struct qm_ceetm_rate *cr, uint16_t cr_limit) ++{ ++ if (channel == NULL || cr == NULL) ++ return (EINVAL); ++ ++ channel->cr_token_rate = *cr; ++ channel->cr_token_bucket_limit = cr_limit; ++ ++ if (channel->shaper_enable) ++ return (qman_ceetm_channel_enable_shaper(channel, ++ channel->shaper_couple)); ++ return (0); ++} ++ ++int ++qman_ceetm_channel_set_excess_rate(struct qm_ceetm_channel *channel, ++ const struct qm_ceetm_rate *er, uint16_t er_limit) ++{ ++ if (channel == NULL || er == NULL) ++ return (EINVAL); ++ ++ channel->er_token_rate = *er; ++ channel->er_token_bucket_limit = er_limit; ++ ++ if (channel->shaper_enable) ++ return (qman_ceetm_channel_enable_shaper(channel, ++ channel->shaper_couple)); ++ return (0); ++} ++ ++int ++qman_ceetm_channel_get_commit_rate(struct qm_ceetm_channel *channel, ++ struct qm_ceetm_rate *cr, uint16_t *cr_limit) ++{ ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_query qcmd; ++ struct qm_mcr_ceetm_mapping_shaper_tcfc_query qr; ++ uint32_t tcr; ++ int ret; ++ ++ if (channel == NULL) ++ return (EINVAL); ++ ++ memset(&qcmd, 0, sizeof(qcmd)); ++ qcmd.cid = htobe16(CEETM_COMMAND_CHANNEL_SHAPER | channel->idx); ++ qcmd.dcpid = channel->dcp_idx; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_MAPPING_SHAPER_TCFC_QUERY, ++ &qcmd, sizeof(qcmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ tcr = ((uint32_t)qr.shaper_query.crtcr_hi << 16) | ++ be16toh(qr.shaper_query.crtcr_lo); ++ if (cr != NULL) { ++ cr->whole = tcr >> 13; ++ cr->fraction = tcr & 0x1FFF; ++ } ++ if (cr_limit != NULL) ++ *cr_limit = be16toh(qr.shaper_query.crtbl); ++ return (0); ++} ++ ++int ++qman_ceetm_channel_get_excess_rate(struct qm_ceetm_channel *channel, ++ struct qm_ceetm_rate *er, uint16_t *er_limit) ++{ ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_query qcmd; ++ struct qm_mcr_ceetm_mapping_shaper_tcfc_query qr; ++ uint32_t tcr; ++ int ret; ++ ++ if (channel == NULL) ++ return (EINVAL); ++ ++ memset(&qcmd, 0, sizeof(qcmd)); ++ qcmd.cid = htobe16(CEETM_COMMAND_CHANNEL_SHAPER | channel->idx); ++ qcmd.dcpid = channel->dcp_idx; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_MAPPING_SHAPER_TCFC_QUERY, ++ &qcmd, sizeof(qcmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ tcr = ((uint32_t)qr.shaper_query.ertcr_hi << 16) | ++ be16toh(qr.shaper_query.ertcr_lo); ++ if (er != NULL) { ++ er->whole = tcr >> 13; ++ er->fraction = tcr & 0x1FFF; ++ } ++ if (er_limit != NULL) ++ *er_limit = be16toh(qr.shaper_query.ertbl); ++ return (0); ++} ++ ++/* ================================================================ ++ * Channel Class Scheduler (Group/Eligibility) ++ * ================================================================ */ ++ ++int ++qman_ceetm_channel_set_group(struct qm_ceetm_channel *channel, ++ int group_b, unsigned int prio_a, unsigned int prio_b) ++{ ++ struct qm_mcc_ceetm_class_scheduler_config cmd; ++ int ret; ++ ++ if (channel == NULL) ++ return (EINVAL); ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cqcid = htobe16(channel->idx); ++ cmd.dcpid = channel->dcp_idx; ++ cmd.gpc = (prio_a & CEETM_GPC_PRIO_A_MASK); ++ if (group_b) { ++ cmd.gpc |= CEETM_GPC_COMBINE_FLAG; ++ cmd.gpc |= (prio_b << CEETM_GPC_PRIO_B_SHIFT) & ++ CEETM_GPC_PRIO_B_MASK; ++ } ++ ++ ret = ceetm_mc_config(QM_CEETM_VERB_CLASS_SCHEDULER_CONFIG, ++ &cmd, sizeof(cmd)); ++ return (ret); ++} ++ ++int ++qman_ceetm_channel_get_group(struct qm_ceetm_channel *channel, ++ int *group_b, unsigned int *prio_a, unsigned int *prio_b) ++{ ++ struct qm_mcc_ceetm_class_scheduler_query qcmd; ++ struct qm_mcr_ceetm_class_scheduler_query qr; ++ int ret; ++ ++ if (channel == NULL) ++ return (EINVAL); ++ ++ memset(&qcmd, 0, sizeof(qcmd)); ++ qcmd.cqcid = htobe16(channel->idx); ++ qcmd.dcpid = channel->dcp_idx; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_CLASS_SCHEDULER_QUERY, ++ &qcmd, sizeof(qcmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ if (group_b != NULL) ++ *group_b = (qr.gpc & CEETM_GPC_COMBINE_FLAG) ? 1 : 0; ++ if (prio_a != NULL) ++ *prio_a = qr.gpc & CEETM_GPC_PRIO_A_MASK; ++ if (prio_b != NULL) ++ *prio_b = (qr.gpc & CEETM_GPC_PRIO_B_MASK) >> ++ CEETM_GPC_PRIO_B_SHIFT; ++ return (0); ++} ++ ++int ++qman_ceetm_channel_set_group_cr_eligibility( ++ struct qm_ceetm_channel *channel, int group_b, int cre) ++{ ++ struct qm_mcc_ceetm_class_scheduler_query qcmd; ++ struct qm_mcr_ceetm_class_scheduler_query qr; ++ struct qm_mcc_ceetm_class_scheduler_config cmd; ++ uint16_t mask; ++ int ret; ++ ++ if (channel == NULL) ++ return (EINVAL); ++ ++ /* Query current state */ ++ memset(&qcmd, 0, sizeof(qcmd)); ++ qcmd.cqcid = htobe16(channel->idx); ++ qcmd.dcpid = channel->dcp_idx; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_CLASS_SCHEDULER_QUERY, ++ &qcmd, sizeof(qcmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ mask = be16toh(qr.crem); ++ if (group_b) { ++ if (cre) ++ mask |= (1 << 9); ++ else ++ mask &= ~(1 << 9); ++ } else { ++ if (cre) ++ mask |= (1 << 8); ++ else ++ mask &= ~(1 << 8); ++ } ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cqcid = htobe16(channel->idx); ++ cmd.dcpid = channel->dcp_idx; ++ cmd.gpc = qr.gpc; ++ cmd.crem = htobe16(mask); ++ cmd.erem = qr.erem; ++ memcpy(cmd.w, qr.w, 8); ++ ++ return (ceetm_mc_config(QM_CEETM_VERB_CLASS_SCHEDULER_CONFIG, ++ &cmd, sizeof(cmd))); ++} ++ ++int ++qman_ceetm_channel_set_group_er_eligibility( ++ struct qm_ceetm_channel *channel, int group_b, int ere) ++{ ++ struct qm_mcc_ceetm_class_scheduler_query qcmd; ++ struct qm_mcr_ceetm_class_scheduler_query qr; ++ struct qm_mcc_ceetm_class_scheduler_config cmd; ++ uint16_t mask; ++ int ret; ++ ++ if (channel == NULL) ++ return (EINVAL); ++ ++ memset(&qcmd, 0, sizeof(qcmd)); ++ qcmd.cqcid = htobe16(channel->idx); ++ qcmd.dcpid = channel->dcp_idx; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_CLASS_SCHEDULER_QUERY, ++ &qcmd, sizeof(qcmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ mask = be16toh(qr.erem); ++ if (group_b) { ++ if (ere) ++ mask |= (1 << 9); ++ else ++ mask &= ~(1 << 9); ++ } else { ++ if (ere) ++ mask |= (1 << 8); ++ else ++ mask &= ~(1 << 8); ++ } ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cqcid = htobe16(channel->idx); ++ cmd.dcpid = channel->dcp_idx; ++ cmd.gpc = qr.gpc; ++ cmd.crem = qr.crem; ++ cmd.erem = htobe16(mask); ++ memcpy(cmd.w, qr.w, 8); ++ ++ return (ceetm_mc_config(QM_CEETM_VERB_CLASS_SCHEDULER_CONFIG, ++ &cmd, sizeof(cmd))); ++} ++ ++int ++qman_ceetm_channel_set_cq_cr_eligibility( ++ struct qm_ceetm_channel *channel, unsigned int idx, int cre) ++{ ++ struct qm_mcc_ceetm_class_scheduler_query qcmd; ++ struct qm_mcr_ceetm_class_scheduler_query qr; ++ struct qm_mcc_ceetm_class_scheduler_config cmd; ++ uint16_t mask; ++ int ret; ++ ++ if (channel == NULL || idx > 7) ++ return (EINVAL); ++ ++ memset(&qcmd, 0, sizeof(qcmd)); ++ qcmd.cqcid = htobe16(channel->idx); ++ qcmd.dcpid = channel->dcp_idx; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_CLASS_SCHEDULER_QUERY, ++ &qcmd, sizeof(qcmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ mask = be16toh(qr.crem); ++ if (cre) ++ mask |= (1 << idx); ++ else ++ mask &= ~(1 << idx); ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cqcid = htobe16(channel->idx); ++ cmd.dcpid = channel->dcp_idx; ++ cmd.gpc = qr.gpc; ++ cmd.crem = htobe16(mask); ++ cmd.erem = qr.erem; ++ memcpy(cmd.w, qr.w, 8); ++ ++ return (ceetm_mc_config(QM_CEETM_VERB_CLASS_SCHEDULER_CONFIG, ++ &cmd, sizeof(cmd))); ++} ++ ++int ++qman_ceetm_channel_set_cq_er_eligibility( ++ struct qm_ceetm_channel *channel, unsigned int idx, int ere) ++{ ++ struct qm_mcc_ceetm_class_scheduler_query qcmd; ++ struct qm_mcr_ceetm_class_scheduler_query qr; ++ struct qm_mcc_ceetm_class_scheduler_config cmd; ++ uint16_t mask; ++ int ret; ++ ++ if (channel == NULL || idx > 7) ++ return (EINVAL); ++ ++ memset(&qcmd, 0, sizeof(qcmd)); ++ qcmd.cqcid = htobe16(channel->idx); ++ qcmd.dcpid = channel->dcp_idx; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_CLASS_SCHEDULER_QUERY, ++ &qcmd, sizeof(qcmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ mask = be16toh(qr.erem); ++ if (ere) ++ mask |= (1 << idx); ++ else ++ mask &= ~(1 << idx); ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cqcid = htobe16(channel->idx); ++ cmd.dcpid = channel->dcp_idx; ++ cmd.gpc = qr.gpc; ++ cmd.crem = qr.crem; ++ cmd.erem = htobe16(mask); ++ memcpy(cmd.w, qr.w, 8); ++ ++ return (ceetm_mc_config(QM_CEETM_VERB_CLASS_SCHEDULER_CONFIG, ++ &cmd, sizeof(cmd))); ++} ++ ++/* ================================================================ ++ * Class Queue Management ++ * ================================================================ */ ++ ++int ++qman_ceetm_cq_claim(struct qm_ceetm_cq **cq, ++ struct qm_ceetm_channel *channel, unsigned int idx, ++ struct qm_ceetm_ccg *ccg) ++{ ++ struct qm_ceetm_cq *p; ++ struct qm_mcc_ceetm_cq_config cmd; ++ int ret; ++ ++ if (channel == NULL || cq == NULL || idx > 7) ++ return (EINVAL); ++ ++ /* Check not already claimed */ ++ TAILQ_FOREACH(p, &channel->class_queues, entries) { ++ if (p->idx == idx) ++ return (EBUSY); ++ } ++ ++ p = malloc(sizeof(*p), M_NETCOMMSW, M_NOWAIT | M_ZERO); ++ if (p == NULL) ++ return (ENOMEM); ++ ++ p->idx = idx; ++ p->parent = channel; ++ p->ccg = ccg; ++ TAILQ_INIT(&p->bound_lfqids); ++ ++ /* Configure CQ */ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cqid = htobe16((channel->idx << 4) | idx); ++ cmd.dcpid = channel->dcp_idx; ++ if (ccg != NULL) ++ cmd.ccgid = htobe16((ccg->parent->idx << 4) | ccg->idx); ++ ++ ret = ceetm_mc_config(QM_CEETM_VERB_CQ_CONFIG, &cmd, sizeof(cmd)); ++ if (ret) { ++ free(p, M_NETCOMMSW); ++ return (ret); ++ } ++ ++ TAILQ_INSERT_TAIL(&channel->class_queues, p, entries); ++ p->is_claimed = 1; ++ *cq = p; ++ return (0); ++} ++ ++int ++qman_ceetm_cq_claim_A(struct qm_ceetm_cq **cq, ++ struct qm_ceetm_channel *channel, unsigned int idx, ++ struct qm_ceetm_ccg *ccg) ++{ ++ /* Group A uses CQ indices 8-15 */ ++ if (idx < 8 || idx > 15) ++ return (EINVAL); ++ return (qman_ceetm_cq_claim(cq, channel, idx, ccg)); ++} ++ ++int ++qman_ceetm_cq_release(struct qm_ceetm_cq *cq) ++{ ++ if (cq == NULL) ++ return (EINVAL); ++ ++ TAILQ_REMOVE(&cq->parent->class_queues, cq, entries); ++ free(cq, M_NETCOMMSW); ++ return (0); ++} ++ ++int ++qman_ceetm_set_queue_weight(struct qm_ceetm_cq *cq, ++ struct qm_ceetm_weight_code *weight_code) ++{ ++ struct qm_mcc_ceetm_class_scheduler_query qcmd; ++ struct qm_mcr_ceetm_class_scheduler_query qr; ++ struct qm_mcc_ceetm_class_scheduler_config cmd; ++ int ret; ++ unsigned int w_idx; ++ ++ if (cq == NULL || weight_code == NULL) ++ return (EINVAL); ++ if (cq->idx > 15) ++ return (EINVAL); ++ ++ /* Query current scheduler state */ ++ memset(&qcmd, 0, sizeof(qcmd)); ++ qcmd.cqcid = htobe16(cq->parent->idx); ++ qcmd.dcpid = cq->parent->dcp_idx; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_CLASS_SCHEDULER_QUERY, ++ &qcmd, sizeof(qcmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ /* Weight index: CQ 0-7 → w[0-7], CQ 8-15 → w[0-7] (group B offset) */ ++ w_idx = cq->idx & 0x07; ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cqcid = htobe16(cq->parent->idx); ++ cmd.dcpid = cq->parent->dcp_idx; ++ cmd.gpc = qr.gpc; ++ cmd.crem = qr.crem; ++ cmd.erem = qr.erem; ++ memcpy(cmd.w, qr.w, 8); ++ ++ /* Encode weight: w = (y << 3) | x */ ++ cmd.w[w_idx] = (weight_code->y << 3) | weight_code->x; ++ ++ return (ceetm_mc_config(QM_CEETM_VERB_CLASS_SCHEDULER_CONFIG, ++ &cmd, sizeof(cmd))); ++} ++ ++int ++qman_ceetm_get_queue_weight(struct qm_ceetm_cq *cq, ++ struct qm_ceetm_weight_code *weight_code) ++{ ++ struct qm_mcc_ceetm_class_scheduler_query qcmd; ++ struct qm_mcr_ceetm_class_scheduler_query qr; ++ int ret; ++ unsigned int w_idx; ++ ++ if (cq == NULL || weight_code == NULL) ++ return (EINVAL); ++ ++ memset(&qcmd, 0, sizeof(qcmd)); ++ qcmd.cqcid = htobe16(cq->parent->idx); ++ qcmd.dcpid = cq->parent->dcp_idx; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_CLASS_SCHEDULER_QUERY, ++ &qcmd, sizeof(qcmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ w_idx = cq->idx & 0x07; ++ weight_code->y = (qr.w[w_idx] >> 3) & 0x1F; ++ weight_code->x = qr.w[w_idx] & 0x07; ++ return (0); ++} ++ ++/* ================================================================ ++ * LFQ (Logical Frame Queue) Management ++ * ================================================================ */ ++ ++#define CEETM_LFQMT_LFQID_MSB 0xF00000 ++#define CEETM_LFQMT_LFQID_LSB 0x000FFF ++ ++int ++qman_ceetm_lfq_claim(struct qm_ceetm_lfq **lfq, struct qm_ceetm_cq *cq) ++{ ++ struct qm_ceetm_lfq *p; ++ struct qm_mcc_ceetm_lfqmt_config cmd; ++ uint32_t lfqid, lfqid_packed; ++ int ret; ++ ++ if (cq == NULL || lfq == NULL) ++ return (EINVAL); ++ ++ ret = ceetm_pool_alloc(&ceetm_lfqid_pool[cq->parent->dcp_idx], ++ &lfqid); ++ if (ret) ++ return (ret); ++ ++ p = malloc(sizeof(*p), M_NETCOMMSW, M_NOWAIT | M_ZERO); ++ if (p == NULL) { ++ ceetm_pool_free(&ceetm_lfqid_pool[cq->parent->dcp_idx], ++ lfqid); ++ return (ENOMEM); ++ } ++ ++ p->idx = lfqid; ++ p->dctidx = (uint16_t)(lfqid & CEETM_LFQMT_LFQID_LSB); ++ p->parent = cq; ++ ++ /* Configure LFQMT */ ++ memset(&cmd, 0, sizeof(cmd)); ++ lfqid_packed = CEETM_LFQMT_LFQID_MSB | ++ ((uint32_t)cq->parent->dcp_idx << 16) | ++ (lfqid & CEETM_LFQMT_LFQID_LSB); ++ cmd.lfqid_hi = (lfqid_packed >> 16) & 0xFF; ++ cmd.lfqid_lo = htobe16(lfqid_packed & 0xFFFF); ++ cmd.cqid = htobe16((cq->parent->idx << 4) | cq->idx); ++ cmd.dctidx = htobe16(p->dctidx); ++ ++ ret = ceetm_mc_config(QM_CEETM_VERB_LFQMT_CONFIG, ++ &cmd, sizeof(cmd)); ++ if (ret) { ++ ceetm_pool_free(&ceetm_lfqid_pool[cq->parent->dcp_idx], ++ lfqid); ++ free(p, M_NETCOMMSW); ++ return (ret); ++ } ++ ++ TAILQ_INSERT_TAIL(&cq->bound_lfqids, p, entries); ++ *lfq = p; ++ return (0); ++} ++ ++int ++qman_ceetm_lfq_release(struct qm_ceetm_lfq *lfq) ++{ ++ enum qm_dc_portal dcp_idx; ++ ++ if (lfq == NULL) ++ return (EINVAL); ++ ++ dcp_idx = lfq->parent->parent->dcp_idx; ++ ceetm_pool_free(&ceetm_lfqid_pool[dcp_idx], lfq->idx); ++ TAILQ_REMOVE(&lfq->parent->bound_lfqids, lfq, entries); ++ free(lfq, M_NETCOMMSW); ++ return (0); ++} ++ ++int ++qman_ceetm_lfq_set_context(struct qm_ceetm_lfq *lfq, ++ uint64_t context_a, uint32_t context_b) ++{ ++ struct qm_mcc_ceetm_dct_config cmd; ++ ++ if (lfq == NULL) ++ return (EINVAL); ++ ++ lfq->context_a = context_a; ++ lfq->context_b = context_b; ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.dctidx = htobe16(lfq->dctidx); ++ cmd.dcpid = lfq->parent->parent->dcp_idx; ++ cmd.context_b = htobe32(context_b); ++ cmd.context_a = htobe64(context_a); ++ ++ return (ceetm_mc_config(QM_CEETM_VERB_DCT_CONFIG, ++ &cmd, sizeof(cmd))); ++} ++ ++int ++qman_ceetm_lfq_get_context(struct qm_ceetm_lfq *lfq, ++ uint64_t *context_a, uint32_t *context_b) ++{ ++ struct qm_mcc_ceetm_dct_query qcmd; ++ struct qm_mcr_ceetm_dct_query qr; ++ int ret; ++ ++ if (lfq == NULL) ++ return (EINVAL); ++ ++ memset(&qcmd, 0, sizeof(qcmd)); ++ qcmd.dctidx = htobe16(lfq->dctidx); ++ qcmd.dcpid = lfq->parent->parent->dcp_idx; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_DCT_QUERY, ++ &qcmd, sizeof(qcmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ if (context_a != NULL) ++ *context_a = be64toh(qr.context_a); ++ if (context_b != NULL) ++ *context_b = be32toh(qr.context_b); ++ return (0); ++} ++ ++int ++qman_ceetm_create_fq(struct qm_ceetm_lfq *lfq, struct qman_fq *fq) ++{ ++ if (lfq == NULL || fq == NULL) ++ return (EINVAL); ++ ++ memset(fq, 0, sizeof(*fq)); ++ fq->fqid = lfq->idx; ++ fq->flags = 0; /* QMAN_FQ_FLAG_NO_MODIFY equivalent */ ++ return (0); ++} ++ ++/* ================================================================ ++ * CCG (Class Congestion Group) Management ++ * ================================================================ */ ++ ++#define MAX_CCG_IDX 0x000F ++ ++int ++qman_ceetm_ccg_claim(struct qm_ceetm_ccg **ccg, ++ struct qm_ceetm_channel *channel, unsigned int idx, ++ void (*cb)(void *, int), void *cb_ctx) ++{ ++ struct qm_ceetm_ccg *p; ++ ++ if (channel == NULL || ccg == NULL || idx > MAX_CCG_IDX) ++ return (EINVAL); ++ ++ /* Check not already claimed */ ++ TAILQ_FOREACH(p, &channel->ccgs, entries) { ++ if (p->idx == idx) ++ return (EBUSY); ++ } ++ ++ p = malloc(sizeof(*p), M_NETCOMMSW, M_NOWAIT | M_ZERO); ++ if (p == NULL) ++ return (ENOMEM); ++ ++ p->idx = idx; ++ p->parent = channel; ++ TAILQ_INSERT_TAIL(&channel->ccgs, p, entries); ++ *ccg = p; ++ return (0); ++} ++ ++int ++qman_ceetm_ccg_release(struct qm_ceetm_ccg *ccg) ++{ ++ if (ccg == NULL) ++ return (EINVAL); ++ ++ TAILQ_REMOVE(&ccg->parent->ccgs, ccg, entries); ++ free(ccg, M_NETCOMMSW); ++ return (0); ++} ++ ++int ++qman_ceetm_ccg_set(struct qm_ceetm_ccg *ccg, uint16_t we_mask, ++ struct qm_mcc_ceetm_ccgr_config *opts) ++{ ++ struct qm_mcc_ceetm_ccgr_config cmd; ++ ++ if (ccg == NULL || opts == NULL) ++ return (EINVAL); ++ ++ memcpy(&cmd, opts, sizeof(cmd)); ++ cmd.ccgrid = htobe16(CEETM_CCGR_CM_CONFIGURE | ++ (ccg->parent->idx << 4) | ccg->idx); ++ cmd.dcpid = ccg->parent->dcp_idx; ++ cmd.we_mask = htobe16(we_mask); ++ ++ return (ceetm_mc_config(QM_CEETM_VERB_CCGR_CONFIG, ++ &cmd, sizeof(cmd))); ++} ++ ++int ++qman_ceetm_ccg_get_reject_statistics(struct qm_ceetm_ccg *ccg, ++ uint32_t flags, uint64_t *frame_count, uint64_t *byte_count) ++{ ++ struct qm_mcc_ceetm_statistics_query_write cmd; ++ struct qm_mcr_ceetm_statistics_query qr; ++ uint16_t command_type; ++ int ret; ++ ++ if (ccg == NULL) ++ return (EINVAL); ++ ++ if (flags & 0x01) ++ command_type = CEETM_QUERY_REJECT_CLEAR_STATISTICS; ++ else ++ command_type = CEETM_QUERY_REJECT_STATISTICS; ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cid = htobe16((ccg->parent->idx << 4) | ccg->idx); ++ cmd.dcpid = ccg->parent->dcp_idx; ++ cmd.ct = command_type; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_STATISTICS_QUERY_WRITE, ++ &cmd, sizeof(cmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ /* Decode 40-bit frame count and 48-bit byte count */ ++ if (frame_count != NULL) { ++ *frame_count = ((uint64_t)qr.frm_cnt[0] << 32) | ++ ((uint64_t)qr.frm_cnt[1] << 24) | ++ ((uint64_t)qr.frm_cnt[2] << 16) | ++ ((uint64_t)qr.frm_cnt[3] << 8) | ++ (uint64_t)qr.frm_cnt[4]; ++ } ++ if (byte_count != NULL) { ++ *byte_count = ((uint64_t)qr.byte_cnt[0] << 40) | ++ ((uint64_t)qr.byte_cnt[1] << 32) | ++ ((uint64_t)qr.byte_cnt[2] << 24) | ++ ((uint64_t)qr.byte_cnt[3] << 16) | ++ ((uint64_t)qr.byte_cnt[4] << 8) | ++ (uint64_t)qr.byte_cnt[5]; ++ } ++ return (0); ++} ++ ++/* ================================================================ ++ * Statistics/Query ++ * ================================================================ */ ++ ++int ++qman_ceetm_query_cq(unsigned int cqid, unsigned int dcpid, ++ struct qm_mcr_ceetm_cq_query *cq_query) ++{ ++ struct qm_mcc_ceetm_cq_query cmd; ++ ++ if (cq_query == NULL) ++ return (EINVAL); ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cqid = htobe16(cqid); ++ cmd.dcpid = dcpid; ++ ++ return (ceetm_mc_query(QM_CEETM_VERB_CQ_QUERY, ++ &cmd, sizeof(cmd), cq_query, sizeof(*cq_query))); ++} ++ ++int ++qman_ceetm_cq_get_dequeue_statistics(struct qm_ceetm_cq *cq, ++ uint32_t flags, uint64_t *frame_count, uint64_t *byte_count) ++{ ++ struct qm_mcc_ceetm_statistics_query_write cmd; ++ struct qm_mcr_ceetm_statistics_query qr; ++ uint16_t command_type; ++ int ret; ++ ++ if (cq == NULL) ++ return (EINVAL); ++ ++ if (flags & 0x01) ++ command_type = CEETM_QUERY_DEQUEUE_CLEAR_STATISTICS; ++ else ++ command_type = CEETM_QUERY_DEQUEUE_STATISTICS; ++ ++ memset(&cmd, 0, sizeof(cmd)); ++ cmd.cid = htobe16((cq->parent->idx << 4) | cq->idx); ++ cmd.dcpid = cq->parent->dcp_idx; ++ cmd.ct = command_type; ++ ++ ret = ceetm_mc_query(QM_CEETM_VERB_STATISTICS_QUERY_WRITE, ++ &cmd, sizeof(cmd), &qr, sizeof(qr)); ++ if (ret) ++ return (ret); ++ ++ if (frame_count != NULL) { ++ *frame_count = ((uint64_t)qr.frm_cnt[0] << 32) | ++ ((uint64_t)qr.frm_cnt[1] << 24) | ++ ((uint64_t)qr.frm_cnt[2] << 16) | ++ ((uint64_t)qr.frm_cnt[3] << 8) | ++ (uint64_t)qr.frm_cnt[4]; ++ } ++ if (byte_count != NULL) { ++ *byte_count = ((uint64_t)qr.byte_cnt[0] << 40) | ++ ((uint64_t)qr.byte_cnt[1] << 32) | ++ ((uint64_t)qr.byte_cnt[2] << 24) | ++ ((uint64_t)qr.byte_cnt[3] << 16) | ++ ((uint64_t)qr.byte_cnt[4] << 8) | ++ (uint64_t)qr.byte_cnt[5]; ++ } ++ return (0); ++} ++ ++/* ================================================================ ++ * MAPPING_SHAPER_TCFC direct command ++ * ================================================================ */ ++ ++int ++qman_ceetm_configure_mapping_shaper_tcfc( ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_config *opts) ++{ ++ if (opts == NULL) ++ return (EINVAL); ++ return (ceetm_mc_config(QM_CEETM_VERB_MAPPING_SHAPER_TCFC_CONFIG, ++ opts, sizeof(*opts))); ++} ++ ++/* ================================================================ ++ * Initialization — called from qman_attach() if DT node present ++ * ================================================================ */ ++ ++int ++qman_ceetm_init(void) ++{ ++ phandle_t qman_node, ceetm_node, child; ++ pcell_t range[2]; ++ enum qm_dc_portal dcp_portal; ++ struct qm_ceetm_sp *sp; ++ struct qm_ceetm_lni *lni; ++ int ret, i, found; ++ ++ mtx_init(&ceetm_alloc_lock, "ceetm_alloc", NULL, MTX_DEF); ++ qman_num_ceetms = 0; ++ ++ /* Find the qman node */ ++ qman_node = ofw_bus_get_node(qman_sc->sc_dev); ++ if (qman_node <= 0) ++ return (0); /* No DT node — CEETM not available */ ++ ++ /* ++ * Get QMan clock frequency. ++ * Try "clock-frequency" on qman node first, then fall back to ++ * the soc node's "bus-frequency", then default to 400MHz. ++ */ ++ qman_clk = 0; ++ if (OF_getencprop(qman_node, "clock-frequency", ++ (void *)&qman_clk, sizeof(qman_clk)) <= 0) { ++ phandle_t soc_node; ++ ++ soc_node = OF_finddevice("/soc"); ++ if (soc_node > 0) ++ OF_getencprop(soc_node, "bus-frequency", ++ (void *)&qman_clk, sizeof(qman_clk)); ++ } ++ if (qman_clk == 0) { ++ printf("ceetm: no clock-frequency, defaulting to 400MHz\n"); ++ qman_clk = 400000000; ++ } ++ /* ++ * Search for fsl,qman-ceetm child nodes under the qman-portals ++ * parent, or directly under qman. ++ * The DT layout varies — check all children of the qman portals ++ * node and the qman node itself. ++ */ ++ found = 0; ++ ++ /* Search children of qman node */ ++ for (child = OF_child(qman_node); child > 0; child = OF_peer(child)) { ++ if (!ofw_bus_node_is_compatible(child, "fsl,qman-ceetm")) ++ continue; ++ if (!ofw_bus_node_status_okay(child)) ++ continue; ++ ++ /* Parse LFQID range — extract DCP portal index */ ++ if (OF_getencprop(child, "fsl,ceetm-lfqid-range", ++ (void *)range, sizeof(range)) != sizeof(range)) { ++ printf("ceetm: missing fsl,ceetm-lfqid-range\n"); ++ continue; ++ } ++ ++ dcp_portal = (range[0] & 0x0F0000) >> 16; ++ if (dcp_portal >= QMAN_CEETM_MAX) { ++ printf("ceetm: DCP portal %d out of range\n", ++ dcp_portal); ++ continue; ++ } ++ ++ /* Seed LFQID allocator */ ++ ceetm_pool_seed(&ceetm_lfqid_pool[dcp_portal], ++ range[0], range[1]); ++ ++ /* Initialize CEETM instance */ ++ qman_ceetms[dcp_portal].idx = dcp_portal; ++ TAILQ_INIT(&qman_ceetms[dcp_portal].sub_portals); ++ TAILQ_INIT(&qman_ceetms[dcp_portal].lnis); ++ ++ /* Parse SP range */ ++ if (OF_getencprop(child, "fsl,ceetm-sp-range", ++ (void *)range, sizeof(range)) != sizeof(range)) { ++ printf("ceetm: missing fsl,ceetm-sp-range\n"); ++ continue; ++ } ++ qman_ceetms[dcp_portal].sp_range[0] = range[0]; ++ qman_ceetms[dcp_portal].sp_range[1] = range[1]; ++ ++ for (i = 0; i < (int)range[1]; i++) { ++ sp = malloc(sizeof(*sp), M_NETCOMMSW, ++ M_WAITOK | M_ZERO); ++ sp->idx = range[0] + i; ++ sp->dcp_idx = dcp_portal; ++ TAILQ_INSERT_TAIL( ++ &qman_ceetms[dcp_portal].sub_portals, ++ sp, entries); ++ } ++ ++ /* Parse LNI range */ ++ if (OF_getencprop(child, "fsl,ceetm-lni-range", ++ (void *)range, sizeof(range)) != sizeof(range)) { ++ printf("ceetm: missing fsl,ceetm-lni-range\n"); ++ continue; ++ } ++ qman_ceetms[dcp_portal].lni_range[0] = range[0]; ++ qman_ceetms[dcp_portal].lni_range[1] = range[1]; ++ ++ for (i = 0; i < (int)range[1]; i++) { ++ lni = malloc(sizeof(*lni), M_NETCOMMSW, ++ M_WAITOK | M_ZERO); ++ lni->idx = range[0] + i; ++ lni->dcp_idx = dcp_portal; ++ TAILQ_INIT(&lni->channels); ++ TAILQ_INSERT_TAIL( ++ &qman_ceetms[dcp_portal].lnis, ++ lni, entries); ++ } ++ ++ /* Parse channel range */ ++ if (OF_getencprop(child, "fsl,ceetm-channel-range", ++ (void *)range, sizeof(range)) != sizeof(range)) { ++ printf("ceetm: missing fsl,ceetm-channel-range\n"); ++ continue; ++ } ++ ceetm_pool_seed(&ceetm_channel_pool[dcp_portal], ++ range[0], range[1]); ++ ++ /* Set prescaler */ ++ ret = qman_ceetm_set_prescaler(dcp_portal); ++ if (ret) { ++ printf("ceetm: failed to set prescaler for DCP%d\n", ++ dcp_portal); ++ continue; ++ } ++ ++ if (dcp_portal >= qman_num_ceetms) ++ qman_num_ceetms = dcp_portal + 1; ++ found++; ++ ++ printf("ceetm: DCP%d initialized: %d SPs, %d LNIs, " ++ "clk=%uMHz\n", ++ dcp_portal, ++ qman_ceetms[dcp_portal].sp_range[1], ++ qman_ceetms[dcp_portal].lni_range[1], ++ qman_clk / 1000000); ++ } ++ ++ if (found == 0) { ++ /* Also search under qman-portals parent node */ ++ ceetm_node = OF_finddevice("/soc/fsl,dpaa/fsl,qman-portals"); ++ if (ceetm_node > 0) { ++ for (child = OF_child(ceetm_node); child > 0; ++ child = OF_peer(child)) { ++ if (ofw_bus_node_is_compatible(child, ++ "fsl,qman-ceetm")) ++ printf("ceetm: found CEETM under " ++ "qman-portals, not yet " ++ "supported — add to qman " ++ "node instead\n"); ++ } ++ } ++ } ++ ++ if (qman_num_ceetms > 0) ++ printf("ceetm: %d CEETM instance%s available\n", ++ qman_num_ceetms, ++ qman_num_ceetms > 1 ? "s" : ""); ++ ++ return (0); ++} +diff --git a/sys/dev/dpaa/qman_ceetm.h b/sys/dev/dpaa/qman_ceetm.h +new file mode 100644 +index 00000000000..42e6fe839d5 +--- /dev/null ++++ b/sys/dev/dpaa/qman_ceetm.h +@@ -0,0 +1,719 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * QMan CEETM (Channel Egress Enhancement and Traffic Management) driver ++ * for FreeBSD. Ported from the Linux NXP QBMan SDK driver. ++ * ++ * CEETM provides hierarchical egress QoS: ++ * Sub-portals → LNIs → Channels → Class Queues ++ * with per-level token-bucket shapers and WBFQ scheduling. ++ * ++ * Original Linux source: ++ * drivers/staging/fsl_qbman/qman_high.c (API implementation) ++ * include/linux/fsl_qman.h (types, MC structures) ++ * drivers/staging/fsl_qbman/qman_driver.c (DT init) ++ * drivers/staging/fsl_qbman/qman_config.c (CCSR registers) ++ */ ++ ++#ifndef _QMAN_CEETM_H ++#define _QMAN_CEETM_H ++ ++#include ++#include ++ ++/* ++ * Forward declarations — NCSW types used by qman_ceetm.c but not ++ * needed by external callers. ++ */ ++struct qm_portal; ++ ++/* ================================================================ ++ * CEETM Management Command Verb Codes (QMan RM section 1.5.9.7) ++ * ++ * These are sent via the same portal MC interface as FQ/CGR commands ++ * (qm_mc_start / qm_mc_commit / qm_mc_result). ++ * ================================================================ */ ++ ++#define QM_CEETM_VERB_LFQMT_CONFIG 0x70 ++#define QM_CEETM_VERB_LFQMT_QUERY 0x71 ++#define QM_CEETM_VERB_CQ_CONFIG 0x72 ++#define QM_CEETM_VERB_CQ_QUERY 0x73 ++#define QM_CEETM_VERB_DCT_CONFIG 0x74 ++#define QM_CEETM_VERB_DCT_QUERY 0x75 ++#define QM_CEETM_VERB_CLASS_SCHEDULER_CONFIG 0x76 ++#define QM_CEETM_VERB_CLASS_SCHEDULER_QUERY 0x77 ++#define QM_CEETM_VERB_MAPPING_SHAPER_TCFC_CONFIG 0x78 ++#define QM_CEETM_VERB_MAPPING_SHAPER_TCFC_QUERY 0x79 ++#define QM_CEETM_VERB_CCGR_CONFIG 0x7A ++#define QM_CEETM_VERB_CCGR_QUERY 0x7B ++#define QM_CEETM_VERB_CQ_PEEK_POP_XFDRREAD 0x7C ++#define QM_CEETM_VERB_STATISTICS_QUERY_WRITE 0x7D ++ ++/* MAPPING_SHAPER_TCFC sub-command types (upper 4 bits of cid field) */ ++#define CEETM_COMMAND_CHANNEL_MAPPING (0 << 12) ++#define CEETM_COMMAND_SP_MAPPING (1 << 12) ++#define CEETM_COMMAND_CHANNEL_SHAPER (2 << 12) ++#define CEETM_COMMAND_LNI_SHAPER (3 << 12) ++#define CEETM_COMMAND_TCFC (4 << 12) ++ ++/* CCGR sub-command types (upper 2 bits of ccgrid field) */ ++#define CEETM_CCGRID_MASK 0x01FF ++#define CEETM_CCGR_CM_CONFIGURE (0 << 14) ++#define CEETM_CCGR_DN_CONFIGURE (1 << 14) ++#define CEETM_CCGR_TEST_WRITE (2 << 14) ++#define CEETM_CCGR_CM_QUERY (0 << 14) ++#define CEETM_CCGR_DN_QUERY (1 << 14) ++#define CEETM_CCGR_DN_QUERY_FLUSH (2 << 14) ++#define CEETM_QUERY_CONGESTION_STATE (3 << 14) ++ ++/* Statistics query/write command types */ ++#define CEETM_QUERY_DEQUEUE_STATISTICS 0x00 ++#define CEETM_QUERY_DEQUEUE_CLEAR_STATISTICS 0x01 ++#define CEETM_WRITE_DEQUEUE_STATISTICS 0x02 ++#define CEETM_QUERY_REJECT_STATISTICS 0x03 ++#define CEETM_QUERY_REJECT_CLEAR_STATISTICS 0x04 ++#define CEETM_WRITE_REJECT_STATISTICS 0x05 ++ ++/* MC result codes */ ++#define QM_MCR_RESULT_OK 0xf0 ++#define QM_MCR_RESULT_ERR_BADCOMMAND 0xff ++ ++/* DCP_CFG CEETM enable bit for a sub-portal */ ++#define QM_SP_ENABLE_CEETM(sp) (0x80000000 >> (sp)) ++ ++/* ================================================================ ++ * CEETM MC Command Structures (MCC) ++ * ++ * Each is exactly 63 bytes (64 - 1 verb byte). These overlay the ++ * generic qm_mc_command union returned by qm_mc_start(). All ++ * multi-byte fields are big-endian on the wire; callers use ++ * WRITE_UINT16/WRITE_UINT32 macros. ++ * ++ * Field layout matches Linux include/linux/fsl_qman.h verbatim. ++ * ================================================================ */ ++ ++struct qm_mcc_ceetm_lfqmt_config { ++ uint8_t __reserved1[3]; ++ uint8_t lfqid_hi; /* lfqid[23:16] */ ++ uint16_t lfqid_lo; /* lfqid[15:0] */ ++ uint8_t __reserved2[2]; ++ uint16_t cqid; ++ uint8_t __reserved3[2]; ++ uint16_t dctidx; ++ uint8_t __reserved4[48]; ++} __packed; ++ ++struct qm_mcc_ceetm_lfqmt_query { ++ uint8_t __reserved1[3]; ++ uint8_t lfqid_hi; ++ uint16_t lfqid_lo; ++ uint8_t __reserved2[56]; ++} __packed; ++ ++struct qm_mcc_ceetm_cq_config { ++ uint16_t cqid; ++ uint8_t dcpid; ++ uint8_t __reserved1; ++ uint16_t ccgid; ++ uint8_t __reserved2[56]; ++} __packed; ++ ++struct qm_mcc_ceetm_cq_query { ++ uint16_t cqid; ++ uint8_t dcpid; ++ uint8_t __reserved1[59]; ++} __packed; ++ ++struct qm_mcc_ceetm_dct_config { ++ uint16_t dctidx; ++ uint8_t dcpid; ++ uint8_t __reserved1[15]; ++ uint32_t context_b; ++ uint64_t context_a; ++ uint8_t __reserved2[32]; ++} __packed; ++ ++struct qm_mcc_ceetm_dct_query { ++ uint16_t dctidx; ++ uint8_t dcpid; ++ uint8_t __reserved1[59]; ++} __packed; ++ ++/* ++ * Class scheduler config — GPC byte layout (big-endian on wire): ++ * bit 7: reserved ++ * bit 6: combine_flag ++ * bits 5-3: prio_b ++ * bits 2-0: prio_a ++ */ ++#define CEETM_GPC_COMBINE_FLAG 0x40 ++#define CEETM_GPC_PRIO_B_SHIFT 3 ++#define CEETM_GPC_PRIO_B_MASK 0x38 ++#define CEETM_GPC_PRIO_A_MASK 0x07 ++ ++struct qm_mcc_ceetm_class_scheduler_config { ++ uint16_t cqcid; /* channel CQ channel id */ ++ uint8_t dcpid; ++ uint8_t __reserved1[6]; ++ uint8_t gpc; /* group priority control */ ++ uint16_t crem; /* CR eligibility mask */ ++ uint16_t erem; /* ER eligibility mask */ ++ uint8_t w[8]; /* weight codes */ ++ uint8_t __reserved2[40]; ++} __packed; ++ ++struct qm_mcc_ceetm_class_scheduler_query { ++ uint16_t cqcid; ++ uint8_t dcpid; ++ uint8_t __reserved1[59]; ++} __packed; ++ ++/* ++ * MAPPING_SHAPER_TCFC config — multiplexed command. ++ * The upper 4 bits of cid select the sub-command type. ++ */ ++struct qm_mcc_ceetm_mapping_shaper_tcfc_config { ++ uint16_t cid; /* sub-command type | resource index */ ++ uint8_t dcpid; ++ union { ++ struct { ++ uint8_t map_flags; /* bit7=shaped, bits2-0=lni_id */ ++ uint8_t __reserved[58]; ++ } __packed channel_mapping; ++ struct { ++ uint8_t map_flags; /* bits2-0=lni_id */ ++ uint8_t __reserved[58]; ++ } __packed sp_mapping; ++ struct { ++ uint8_t cpl_oal; /* bit7=coupled, bits4-0=oal */ ++ uint8_t crtcr_hi; /* crtcr[23:16] */ ++ uint16_t crtcr_lo; /* crtcr[15:0] */ ++ uint8_t ertcr_hi; /* ertcr[23:16] */ ++ uint16_t ertcr_lo; /* ertcr[15:0] */ ++ uint16_t crtbl; ++ uint16_t ertbl; ++ uint8_t mps; ++ uint8_t __reserved[47]; ++ } __packed shaper_config; ++ struct { ++ uint8_t __reserved1[11]; ++ uint64_t lnitcfcc; ++ uint8_t __reserved2[40]; ++ } __packed tcfc_config; ++ }; ++} __packed; ++ ++struct qm_mcc_ceetm_mapping_shaper_tcfc_query { ++ uint16_t cid; ++ uint8_t dcpid; ++ uint8_t __reserved[59]; ++} __packed; ++ ++/* ++ * CCGR config — Congestion Manager or Dequeue Notification config. ++ * We only use CM config (tail-drop threshold for class queues). ++ */ ++struct qm_mcc_ceetm_ccgr_config { ++ uint16_t ccgrid; /* sub-command | ccg index */ ++ uint8_t dcpid; ++ uint8_t __reserved1; ++ uint16_t we_mask; ++ /* CM config fields (when ccgrid sub-command = CM_CONFIGURE) */ ++ uint8_t ctl; /* control byte */ ++ uint8_t cdv; ++ uint16_t cscn_tupd; ++ uint8_t oal; ++ uint8_t __reserved2; ++ uint16_t cs_thres; /* qm_cgr_cs_thres format */ ++ uint16_t cs_thres_x; ++ uint16_t td_thres; ++ uint32_t wr_parm_g; /* qm_cgr_wr_parm format */ ++ uint32_t wr_parm_y; ++ uint32_t wr_parm_r; ++ uint8_t __reserved3[32]; ++} __packed; ++ ++struct qm_mcc_ceetm_ccgr_query { ++ uint16_t ccgrid; ++ uint8_t dcpid; ++ uint8_t __reserved[59]; ++} __packed; ++ ++struct qm_mcc_ceetm_cq_peek_pop_xsfdrread { ++ uint16_t cqid; ++ uint8_t dcpid; ++ uint8_t ct; ++ uint16_t xsfdr; ++ uint8_t __reserved[56]; ++} __packed; ++ ++struct qm_mcc_ceetm_statistics_query_write { ++ uint16_t cid; ++ uint8_t dcpid; ++ uint8_t ct; ++ uint8_t __reserved1[13]; ++ uint8_t frm_cnt[5]; /* 40-bit frame count */ ++ uint8_t __reserved2[2]; ++ uint8_t byte_cnt[6]; /* 48-bit byte count */ ++ uint8_t __reserved3[32]; ++} __packed; ++ ++/* ================================================================ ++ * CEETM MC Result Structures (MCR) ++ * ++ * Each is exactly 64 bytes. First two bytes are verb + result. ++ * These overlay the generic qm_mc_result returned by qm_mc_result(). ++ * ================================================================ */ ++ ++struct qm_mcr_ceetm_generic { ++ uint8_t verb; ++ uint8_t result; ++ uint8_t __reserved[62]; ++} __packed; ++ ++/* LFQMT query result */ ++struct qm_mcr_ceetm_lfqmt_query { ++ uint8_t verb; ++ uint8_t result; ++ uint8_t __reserved1[8]; ++ uint16_t cqid; ++ uint8_t __reserved2[2]; ++ uint16_t dctidx; ++ uint8_t __reserved3[2]; ++ uint16_t ccgid; ++ uint8_t __reserved4[44]; ++} __packed; ++ ++/* CQ query result */ ++struct qm_mcr_ceetm_cq_query { ++ uint8_t verb; ++ uint8_t result; ++ uint8_t __reserved1[4]; ++ uint16_t ccgid; ++ uint16_t state; ++ uint8_t pfdr_hptr_hi; ++ uint16_t pfdr_hptr_lo; ++ uint8_t pfdr_tptr_hi; ++ uint16_t pfdr_tptr_lo; ++ uint16_t od1_xsfdr; ++ uint16_t od2_xsfdr; ++ uint16_t od3_xsfdr; ++ uint16_t od4_xsfdr; ++ uint16_t od5_xsfdr; ++ uint16_t od6_xsfdr; ++ uint16_t ra1_xsfdr; ++ uint16_t ra2_xsfdr; ++ uint8_t __reserved2; ++ uint8_t frm_cnt_hi; ++ uint16_t frm_cnt_lo; ++ uint8_t __reserved3[28]; ++} __packed; ++ ++/* DCT query result */ ++struct qm_mcr_ceetm_dct_query { ++ uint8_t verb; ++ uint8_t result; ++ uint8_t __reserved1[18]; ++ uint32_t context_b; ++ uint64_t context_a; ++ uint8_t __reserved2[32]; ++} __packed; ++ ++/* Class scheduler query result */ ++struct qm_mcr_ceetm_class_scheduler_query { ++ uint8_t verb; ++ uint8_t result; ++ uint8_t __reserved1[9]; ++ uint8_t gpc; ++ uint16_t crem; ++ uint16_t erem; ++ uint8_t w[8]; ++ uint8_t __reserved2[5]; ++ uint8_t wbfslist_hi; ++ uint16_t wbfslist_lo; ++ uint32_t d8; ++ uint32_t d9; ++ uint32_t d10; ++ uint32_t d11; ++ uint32_t d12; ++ uint32_t d13; ++ uint32_t d14; ++ uint32_t d15; ++} __packed; ++ ++/* MAPPING_SHAPER_TCFC query result */ ++struct qm_mcr_ceetm_mapping_shaper_tcfc_query { ++ uint8_t verb; ++ uint8_t result; ++ uint16_t cid; ++ uint8_t __reserved1; ++ union { ++ struct { ++ uint8_t map_flags; ++ uint8_t __reserved[58]; ++ } __packed channel_mapping_query; ++ struct { ++ uint8_t map_flags; ++ uint8_t __reserved[58]; ++ } __packed sp_mapping_query; ++ struct { ++ uint8_t cpl_oal; ++ uint8_t crtcr_hi; ++ uint16_t crtcr_lo; ++ uint8_t ertcr_hi; ++ uint16_t ertcr_lo; ++ uint16_t crtbl; ++ uint16_t ertbl; ++ uint8_t mps; ++ uint8_t __reserved1[15]; ++ uint32_t crat; ++ uint32_t erat; ++ uint8_t __reserved2[24]; ++ } __packed shaper_query; ++ struct { ++ uint8_t __reserved1[11]; ++ uint64_t lnitcfcc; ++ uint8_t __reserved2[40]; ++ } __packed tcfc_query; ++ }; ++} __packed; ++ ++/* CCGR config result (test-write variant has extra fields) */ ++struct qm_mcr_ceetm_ccgr_config { ++ uint8_t verb; ++ uint8_t result; ++ uint8_t __reserved1[62]; ++} __packed; ++ ++/* CCGR query result (CM query variant) */ ++struct qm_mcr_ceetm_ccgr_query { ++ uint8_t verb; ++ uint8_t result; ++ uint8_t __reserved1[6]; ++ /* CM query fields */ ++ uint8_t ctl; ++ uint8_t cdv; ++ uint8_t __reserved2[2]; ++ uint8_t oal; ++ uint8_t __reserved3; ++ uint16_t cs_thres; ++ uint16_t cs_thres_x; ++ uint16_t td_thres; ++ uint32_t wr_parm_g; ++ uint32_t wr_parm_y; ++ uint32_t wr_parm_r; ++ uint16_t cscn_targ_dcp; ++ uint8_t dcp_lsn; ++ uint8_t i_cnt[5]; /* 40-bit */ ++ uint8_t __reserved4[3]; ++ uint8_t a_cnt[5]; /* 40-bit */ ++ uint32_t cscn_targ_swp[4]; ++} __packed; ++ ++/* CQ peek/pop result */ ++struct qm_mcr_ceetm_cq_peek_pop_xsfdrread { ++ uint8_t verb; ++ uint8_t result; ++ uint8_t stat; ++ uint8_t __reserved1[61]; ++} __packed; ++ ++/* Statistics query result */ ++struct qm_mcr_ceetm_statistics_query { ++ uint8_t verb; ++ uint8_t result; ++ uint8_t __reserved1[17]; ++ uint8_t frm_cnt[5]; /* 40-bit frame count */ ++ uint8_t __reserved2[2]; ++ uint8_t byte_cnt[6]; /* 48-bit byte count */ ++ uint8_t __reserved3[32]; ++} __packed; ++ ++/* ================================================================ ++ * CEETM High-Level Data Structures ++ * ++ * These represent the CEETM resource hierarchy. Ported from ++ * Linux include/linux/fsl_qman.h, adapted to FreeBSD conventions. ++ * ================================================================ */ ++ ++/* Maximum CEETM instances (one per FMan / DCP portal) */ ++#define QMAN_CEETM_MAX 2 ++ ++/* Token rate (for shapers) */ ++struct qm_ceetm_rate { ++ uint32_t whole; /* integer part (0..2047) */ ++ uint32_t fraction; /* fractional part (0..8191) */ ++}; ++ ++/* WBFS weight code */ ++struct qm_ceetm_weight_code { ++ uint8_t y; /* 0..31 */ ++ uint8_t x; /* 0..7 */ ++ /* effective weight = 2^(x+6) / (64 - y) */ ++}; ++ ++/* DCP portal enum — already defined in NCSW fsl_qman.h for kernel context */ ++#ifndef __FSL_QMAN_H ++enum qm_dc_portal { ++ qm_dc_portal_fman0 = 0, ++ qm_dc_portal_fman1 = 1, ++}; ++#endif ++ ++/* Sub-portal */ ++struct qm_ceetm_sp { ++ TAILQ_ENTRY(qm_ceetm_sp) entries; ++ unsigned int idx; ++ unsigned int dcp_idx; ++ int is_claimed; ++ struct qm_ceetm_lni *lni; ++}; ++ ++/* Logical Network Interface */ ++struct qm_ceetm_lni { ++ TAILQ_ENTRY(qm_ceetm_lni) entries; ++ unsigned int idx; ++ unsigned int dcp_idx; ++ int is_claimed; ++ struct qm_ceetm_sp *sp; ++ TAILQ_HEAD(, qm_ceetm_channel) channels; ++ int shaper_enable; ++ int shaper_couple; ++ int oal; ++ struct qm_ceetm_rate cr_token_rate; ++ struct qm_ceetm_rate er_token_rate; ++ uint16_t cr_token_bucket_limit; ++ uint16_t er_token_bucket_limit; ++}; ++ ++/* CQ Channel */ ++struct qm_ceetm_channel { ++ TAILQ_ENTRY(qm_ceetm_channel) entries; ++ struct qm_ceetm_lni *lni; /* parent LNI */ ++ unsigned int idx; ++ unsigned int lni_idx; ++ unsigned int dcp_idx; ++ TAILQ_HEAD(, qm_ceetm_cq) class_queues; ++ TAILQ_HEAD(, qm_ceetm_ccg) ccgs; ++ uint8_t shaper_enable; ++ uint8_t shaper_couple; ++ struct qm_ceetm_rate cr_token_rate; ++ struct qm_ceetm_rate er_token_rate; ++ uint16_t cr_token_bucket_limit; ++ uint16_t er_token_bucket_limit; ++}; ++ ++/* Class Queue */ ++struct qm_ceetm_cq { ++ TAILQ_ENTRY(qm_ceetm_cq) entries; ++ struct qm_ceetm_channel *parent; ++ struct qm_ceetm_ccg *ccg; ++ unsigned int idx; /* 0-7 individual, 8-15 grouped */ ++ int is_claimed; ++ TAILQ_HEAD(, qm_ceetm_lfq) bound_lfqids; ++}; ++ ++/* Logical Frame Queue */ ++struct qm_ceetm_lfq { ++ TAILQ_ENTRY(qm_ceetm_lfq) entries; ++ struct qm_ceetm_cq *parent; ++ unsigned int idx; /* LFQID */ ++ unsigned int dctidx; /* dequeue context table index */ ++ uint64_t context_a; ++ uint32_t context_b; ++}; ++ ++/* Class Congestion Group */ ++struct qm_ceetm_ccg { ++ TAILQ_ENTRY(qm_ceetm_ccg) entries; ++ struct qm_ceetm_channel *parent; ++ unsigned int idx; /* 0-15 */ ++}; ++ ++/* Top-level CEETM instance (one per DCP/FMan) */ ++struct qm_ceetm { ++ unsigned int idx; /* DCP portal index */ ++ TAILQ_HEAD(, qm_ceetm_sp) sub_portals; ++ TAILQ_HEAD(, qm_ceetm_lni) lnis; ++ unsigned int sp_range[2]; /* [start, count] */ ++ unsigned int lni_range[2]; ++}; ++ ++/* ================================================================ ++ * CEETM CCSR Register Offsets (relative to QMan CCSR base) ++ * ================================================================ */ ++ ++#define QM_REG_DCP_CFG(n) (0x0300 + ((n) * 0x10)) ++#define QM_REG_CEETM_CFG_IDX 0x0900 ++#define QM_REG_CEETM_CFG_PRES 0x0904 ++#define QM_REG_CEETM_XSFDR_IN_USE 0x0908 ++ ++/* ================================================================ ++ * CEETM CCGR WE (Write Enable) Mask Bits ++ * ================================================================ */ ++ ++#define QM_CEETM_CCGR_WE_CSCN_EN 0x4000 ++#define QM_CEETM_CCGR_WE_TD_EN 0x2000 ++#define QM_CEETM_CCGR_WE_TD_MODE 0x1000 ++#define QM_CEETM_CCGR_WE_TD_THRES 0x0800 ++#define QM_CEETM_CCGR_WE_OAL 0x0400 ++#define QM_CEETM_CCGR_WE_CDV 0x0200 ++#define QM_CEETM_CCGR_WE_CSCN_TUPD 0x0100 ++#define QM_CEETM_CCGR_WE_CS_THRES 0x0080 ++#define QM_CEETM_CCGR_WE_CS_THRES_X 0x0040 ++#define QM_CEETM_CCGR_WE_MODE 0x0020 ++#define QM_CEETM_CCGR_WE_WR_PARM_G 0x0010 ++#define QM_CEETM_CCGR_WE_WR_PARM_Y 0x0008 ++#define QM_CEETM_CCGR_WE_WR_PARM_R 0x0004 ++#define QM_CEETM_CCGR_WE_DN 0x0002 ++ ++/* CCGR CTL byte bit definitions */ ++#define QM_CEETM_CCGR_CTL_WR_EN_G 0x40 ++#define QM_CEETM_CCGR_CTL_WR_EN_Y 0x20 ++#define QM_CEETM_CCGR_CTL_WR_EN_R 0x10 ++#define QM_CEETM_CCGR_CTL_TD_EN 0x08 ++#define QM_CEETM_CCGR_CTL_TD_MODE 0x04 ++#define QM_CEETM_CCGR_CTL_CSCN_EN 0x02 ++#define QM_CEETM_CCGR_CTL_MODE 0x01 ++ ++/* ================================================================ ++ * Public API — implemented in qman_ceetm.c ++ * ================================================================ */ ++ ++/* Initialization (called from qman_attach if DT node present) */ ++int qman_ceetm_init(void); ++ ++/* Global state */ ++extern uint8_t qman_num_ceetms; ++extern struct qm_ceetm qman_ceetms[QMAN_CEETM_MAX]; ++ ++/* Pure math */ ++int qman_ceetm_bps2tokenrate(uint64_t bps, ++ struct qm_ceetm_rate *token_rate, int rounding); ++int qman_ceetm_tokenrate2bps(const struct qm_ceetm_rate *token_rate, ++ uint64_t *bps, int rounding); ++int qman_ceetm_ratio2wbfs(uint32_t numerator, uint32_t denominator, ++ struct qm_ceetm_weight_code *weight_code, int rounding); ++int qman_ceetm_wbfs2ratio(struct qm_ceetm_weight_code *weight_code, ++ uint32_t *numerator, uint32_t *denominator); ++ ++/* Sub-portal management */ ++int qman_ceetm_sp_claim(struct qm_ceetm_sp **sp, ++ enum qm_dc_portal dcp_idx, unsigned int sp_idx); ++int qman_ceetm_sp_release(struct qm_ceetm_sp *sp); ++int qman_ceetm_sp_set_lni(struct qm_ceetm_sp *sp, ++ struct qm_ceetm_lni *lni); ++int qman_ceetm_sp_get_lni(struct qm_ceetm_sp *sp, unsigned int *lni_idx); ++ ++/* LNI management */ ++int qman_ceetm_lni_claim(struct qm_ceetm_lni **lni, ++ enum qm_dc_portal dcp_idx, unsigned int lni_idx); ++int qman_ceetm_lni_release(struct qm_ceetm_lni *lni); ++int qman_ceetm_lni_enable_shaper(struct qm_ceetm_lni *lni, ++ int coupled, int oal); ++int qman_ceetm_lni_disable_shaper(struct qm_ceetm_lni *lni); ++int qman_ceetm_lni_is_shaper_enabled(struct qm_ceetm_lni *lni); ++int qman_ceetm_lni_set_commit_rate(struct qm_ceetm_lni *lni, ++ const struct qm_ceetm_rate *cr, uint16_t cr_limit); ++int qman_ceetm_lni_set_excess_rate(struct qm_ceetm_lni *lni, ++ const struct qm_ceetm_rate *er, uint16_t er_limit); ++int qman_ceetm_lni_get_commit_rate(struct qm_ceetm_lni *lni, ++ struct qm_ceetm_rate *cr, uint16_t *cr_limit); ++int qman_ceetm_lni_get_excess_rate(struct qm_ceetm_lni *lni, ++ struct qm_ceetm_rate *er, uint16_t *er_limit); ++ ++/* Channel management */ ++int qman_ceetm_channel_claim(struct qm_ceetm_channel **channel, ++ struct qm_ceetm_lni *lni); ++int qman_ceetm_channel_release(struct qm_ceetm_channel *channel); ++int qman_ceetm_channel_enable_shaper(struct qm_ceetm_channel *channel, ++ int coupled); ++int qman_ceetm_channel_disable_shaper(struct qm_ceetm_channel *channel); ++int qman_ceetm_channel_is_shaper_enabled( ++ struct qm_ceetm_channel *channel); ++int qman_ceetm_channel_set_commit_rate(struct qm_ceetm_channel *channel, ++ const struct qm_ceetm_rate *cr, uint16_t cr_limit); ++int qman_ceetm_channel_set_excess_rate(struct qm_ceetm_channel *channel, ++ const struct qm_ceetm_rate *er, uint16_t er_limit); ++int qman_ceetm_channel_get_commit_rate(struct qm_ceetm_channel *channel, ++ struct qm_ceetm_rate *cr, uint16_t *cr_limit); ++int qman_ceetm_channel_get_excess_rate(struct qm_ceetm_channel *channel, ++ struct qm_ceetm_rate *er, uint16_t *er_limit); ++int qman_ceetm_channel_set_group(struct qm_ceetm_channel *channel, ++ int group_b, unsigned int prio_a, unsigned int prio_b); ++int qman_ceetm_channel_get_group(struct qm_ceetm_channel *channel, ++ int *group_b, unsigned int *prio_a, unsigned int *prio_b); ++int qman_ceetm_channel_set_group_cr_eligibility( ++ struct qm_ceetm_channel *channel, int group_b, int cre); ++int qman_ceetm_channel_set_group_er_eligibility( ++ struct qm_ceetm_channel *channel, int group_b, int ere); ++int qman_ceetm_channel_set_cq_cr_eligibility( ++ struct qm_ceetm_channel *channel, unsigned int idx, int cre); ++int qman_ceetm_channel_set_cq_er_eligibility( ++ struct qm_ceetm_channel *channel, unsigned int idx, int ere); ++ ++/* Class queue management */ ++int qman_ceetm_cq_claim(struct qm_ceetm_cq **cq, ++ struct qm_ceetm_channel *channel, unsigned int idx, ++ struct qm_ceetm_ccg *ccg); ++int qman_ceetm_cq_claim_A(struct qm_ceetm_cq **cq, ++ struct qm_ceetm_channel *channel, unsigned int idx, ++ struct qm_ceetm_ccg *ccg); ++int qman_ceetm_cq_release(struct qm_ceetm_cq *cq); ++int qman_ceetm_set_queue_weight(struct qm_ceetm_cq *cq, ++ struct qm_ceetm_weight_code *weight_code); ++int qman_ceetm_get_queue_weight(struct qm_ceetm_cq *cq, ++ struct qm_ceetm_weight_code *weight_code); ++ ++/* LFQ management */ ++int qman_ceetm_lfq_claim(struct qm_ceetm_lfq **lfq, ++ struct qm_ceetm_cq *cq); ++int qman_ceetm_lfq_release(struct qm_ceetm_lfq *lfq); ++int qman_ceetm_lfq_set_context(struct qm_ceetm_lfq *lfq, ++ uint64_t context_a, uint32_t context_b); ++int qman_ceetm_lfq_get_context(struct qm_ceetm_lfq *lfq, ++ uint64_t *context_a, uint32_t *context_b); ++ ++/* ++ * QMan FQ for CEETM egress — minimal struct matching Linux fsl_qman.h. ++ * In kernel context, NCSW qm.h provides the full struct qman_fq. ++ * In module context, dpaa_eth.h provides the minimal struct. ++ */ ++#if !defined(__QM_H) && !defined(_QMAN_FQ_DEFINED) ++#define _QMAN_FQ_DEFINED ++struct qman_fq { ++ uint32_t fqid; ++ uint32_t flags; ++}; ++#endif ++int qman_ceetm_create_fq(struct qm_ceetm_lfq *lfq, ++ struct qman_fq *fq); ++ ++/* CCG management */ ++int qman_ceetm_ccg_claim(struct qm_ceetm_ccg **ccg, ++ struct qm_ceetm_channel *channel, unsigned int idx, ++ void (*cb)(void *, int), void *cb_ctx); ++int qman_ceetm_ccg_release(struct qm_ceetm_ccg *ccg); ++int qman_ceetm_ccg_set(struct qm_ceetm_ccg *ccg, ++ uint16_t we_mask, struct qm_mcc_ceetm_ccgr_config *opts); ++int qman_ceetm_ccg_get_reject_statistics(struct qm_ceetm_ccg *ccg, ++ uint32_t flags, uint64_t *frame_count, uint64_t *byte_count); ++ ++/* Statistics/query */ ++int qman_ceetm_query_cq(unsigned int cqid, unsigned int dcpid, ++ struct qm_mcr_ceetm_cq_query *cq_query); ++int qman_ceetm_cq_get_dequeue_statistics(struct qm_ceetm_cq *cq, ++ uint32_t flags, uint64_t *frame_count, uint64_t *byte_count); ++ ++/* CCSR register access */ ++int qman_sp_enable_ceetm_mode(enum qm_dc_portal portal, ++ uint16_t sub_portal); ++int qman_sp_disable_ceetm_mode(enum qm_dc_portal portal, ++ uint16_t sub_portal); ++int qman_ceetm_configure_mapping_shaper_tcfc( ++ struct qm_mcc_ceetm_mapping_shaper_tcfc_config *opts); ++int qman_ceetm_get_xsfdr(enum qm_dc_portal portal, unsigned int *num); ++ ++#endif /* _QMAN_CEETM_H */ +diff --git a/sys/dev/dpaa/qman_fdt.c b/sys/dev/dpaa/qman_fdt.c +index fac845c8f2b..6c6263258e6 100644 +--- a/sys/dev/dpaa/qman_fdt.c ++++ b/sys/dev/dpaa/qman_fdt.c +@@ -103,7 +103,10 @@ static driver_t qm_portals_driver = { + }; + + EARLY_DRIVER_MODULE(qman_portals, ofwbus, qm_portals_driver, 0, 0, +- BUS_PASS_BUS); ++ BUS_PASS_INTERRUPT + BUS_PASS_ORDER_LAST); ++/* On ARM64, portal bus nodes are children of soc (simplebus), not ofwbus */ ++EARLY_DRIVER_MODULE(qman_portals, simplebus, qm_portals_driver, 0, 0, ++ BUS_PASS_INTERRUPT + BUS_PASS_ORDER_LAST); + + static void + get_addr_props(phandle_t node, uint32_t *addrp, uint32_t *sizep) +@@ -147,7 +150,7 @@ qman_portal_find_cpu(int cpu) + return (-1); + + for (node = OF_child(node); node != 0; node = OF_peer(node)) { +- if (OF_getprop(node, "reg", ®, sizeof(reg)) <= 0) ++ if (OF_getencprop(node, "reg", ®, sizeof(reg)) <= 0) + continue; + if (reg == cpu) + return (node); +@@ -212,14 +215,16 @@ qman_portals_fdt_attach(device_t dev) + continue; + } + /* Checkout related cpu */ +- if (OF_getprop(child, "cpu-handle", (void *)&cpu, ++ if (OF_getencprop(child, "cpu-handle", (void *)&cpu, + sizeof(cpu)) <= 0) { +- cpu = qman_portal_find_cpu(cpus); +- if (cpu <= 0) ++ /* No cpu-handle (ARM64): find CPU node directly */ ++ cpu_node = qman_portal_find_cpu(cpus); ++ if (cpu_node <= 0) + continue; ++ } else { ++ /* cpu-handle is an ihandle (PowerPC) */ ++ cpu_node = OF_instance_to_package(cpu); + } +- /* Acquire cpu number */ +- cpu_node = OF_instance_to_package(cpu); + if (OF_getencprop(cpu_node, "reg", &cpu_num, sizeof(cpu_num)) <= 0) { + device_printf(dev, "Could not retrieve CPU number.\n"); + return (ENXIO); +diff --git a/sys/dev/dpaa/qman_portals.c b/sys/dev/dpaa/qman_portals.c +index 76d89784ab5..625471026ff 100644 +--- a/sys/dev/dpaa/qman_portals.c ++++ b/sys/dev/dpaa/qman_portals.c +@@ -36,15 +36,19 @@ + #include + #include + #include ++#include + + #include ++#include ++#include ++#ifdef __powerpc__ + #include ++#include ++#endif + + #include + #include + +-#include +- + #include "qman.h" + #include "portals.h" + +@@ -60,15 +64,16 @@ struct dpaa_portals_softc *qp_sc; + int + qman_portals_attach(device_t dev) + { +- struct dpaa_portals_softc *sc; ++ qp_sc = device_get_softc(dev); + +- sc = qp_sc = device_get_softc(dev); +- +- /* Map bman portal to physical address space */ ++#ifdef __powerpc__ ++ struct dpaa_portals_softc *sc = qp_sc; ++ /* Map qman portal to physical address space (PowerPC LAW) */ + if (law_enable(OCP85XX_TGTIF_QMAN, sc->sc_dp_pa, sc->sc_dp_size)) { + qman_portals_detach(dev); + return (ENXIO); + } ++#endif + /* Set portal properties for XX_VirtToPhys() */ + XX_PortalSetInfo(dev); + +@@ -128,6 +133,19 @@ qman_portal_setup(struct qman_softc *qsc) + + sc = qp_sc; + ++#ifdef __aarch64__ ++ /* ++ * On ARM64, all portals are pre-initialized with NAPI-style ++ * interrupt handling via qman_portal_init_cpu() in qman_attach(). ++ * Just return the portal for the current CPU. ++ */ ++ sched_pin(); ++ cpu = PCPU_GET(cpuid); ++ portal = sc->sc_dp[cpu].dp_ph; ++ sched_unpin(); ++ return (portal); ++#endif ++ + sched_pin(); + portal = NULL; + cpu = PCPU_GET(cpuid); +@@ -150,9 +168,14 @@ qman_portal_setup(struct qman_softc *qsc) + /* Map portal registers */ + dpaa_portal_map_registers(sc); + ++ ++ /* Bail if portal mapping failed (e.g. no portal allocated for this CPU) */ ++ if (sc->sc_dp[cpu].dp_ce_va == 0 || sc->sc_dp[cpu].dp_ci_va == 0) ++ goto err; ++ + /* Configure and initialize portal */ +- qpp.ceBaseAddress = rman_get_bushandle(sc->sc_rres[0]); +- qpp.ciBaseAddress = rman_get_bushandle(sc->sc_rres[1]); ++ qpp.ceBaseAddress = sc->sc_dp[cpu].dp_ce_va; ++ qpp.ciBaseAddress = sc->sc_dp[cpu].dp_ci_va; + qpp.h_Qm = qsc->sc_qh; + qpp.swPortalId = cpu; + qpp.irq = (uintptr_t)sc->sc_dp[cpu].dp_ires; +@@ -186,3 +209,220 @@ qman_portal_setup(struct qman_softc *qsc) + + return (NULL); + } ++ ++#ifdef __aarch64__ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++/* Per-portal NAPI state */ ++static struct { ++ struct task task; ++ struct taskqueue *tq; ++ struct mbufq rxq; /* deferred RX mbufs */ ++} qman_napi[MAXCPU]; ++ ++/* Declared in xx_arm64.c */ ++extern void XX_ConfigPortalNapi(uintptr_t irq, struct taskqueue *tq, ++ struct task *task); ++extern void XX_SetPortalNapiHandle(uintptr_t irq, t_Handle portal); ++ ++/* ++ * Enqueue an mbuf for deferred delivery after QM_PORTAL_Poll returns. ++ * Called from the DQRR RX callback (inside NCSW_PLOCK) to avoid ++ * re-entering the portal via if_input -> TCP -> TX -> QM_FQR_Enqueue. ++ */ ++void ++qman_rx_defer(struct mbuf *m) ++{ ++ int cpu = PCPU_GET(cpuid); ++ ++ if (mbufq_enqueue(&qman_napi[cpu].rxq, m) != 0) { ++ static volatile uint32_t defer_drop_cnt; ++ uint32_t n = atomic_fetchadd_32(&defer_drop_cnt, 1) + 1; ++ if (n <= 5) ++ printf("qman: rx_defer queue full on CPU %d (#%u)," ++ " dropping\n", cpu, n); ++ m_freem(m); ++ } ++} ++ ++/* ++ * NAPI-style poll task for QMan portals (FreeBSD equivalent of Linux ++ * dpaa_eth_poll). Runs in a per-CPU taskqueue thread at PI_NET, ++ * scheduled by the FILTER interrupt handler via XX_PortalFilter. ++ * ++ * Drains the entire DQRR (max 16 entries) and MR in one shot via ++ * QM_PORTAL_Poll, then delivers deferred RX mbufs outside NCSW_PLOCK ++ * to prevent nested portal enqueue from the TX path. ++ */ ++static void ++qman_portal_poll_task(void *arg, int pending) ++{ ++ t_Handle portal = arg; ++ struct mbuf *m; ++ int cpu = PCPU_GET(cpuid); ++ ++ QM_PORTAL_Poll(portal, e_QM_PORTAL_POLL_SOURCE_BOTH); ++ QM_PORTAL_Uninhibit(portal); ++ ++ /* Deliver deferred RX mbufs outside NCSW_PLOCK */ ++ while ((m = mbufq_dequeue(&qman_napi[cpu].rxq)) != NULL) ++ if_input(m->m_pkthdr.rcvif, m); ++} ++ ++/* ++ * Initialize a QMan portal for a specific CPU with NAPI-style ++ * interrupt handling. Like Linux's qman_create_affine_portal + ++ * dpaa_eth_add_channel: ++ * ++ * 1. Create a per-CPU taskqueue pinned to the portal's CPU ++ * 2. Configure the portal interrupt for FILTER mode (via ++ * XX_ConfigPortalNapi) — the FILTER handler inhibits the ++ * portal and enqueues the taskqueue task ++ * 3. Initialize the NCSW portal (Config + Stash + Init) ++ * 4. Subscribe to the pool channel so QMan distributes RX ++ * frames across all portals (round-robin) ++ * ++ * On ARM64, pmap_mapdev creates global kernel VA, so no ++ * sched_bind/migration is needed. ++ */ ++t_Handle ++qman_portal_init_cpu(struct qman_softc *qsc, int cpu) ++{ ++ struct dpaa_portals_softc *sc; ++ t_QmPortalParam qpp; ++ t_QmPortalStashParam stash; ++ t_Handle portal; ++ cpuset_t cpumask; ++ ++ if (qp_sc == NULL) ++ return (NULL); ++ sc = qp_sc; ++ ++ /* Skip if already initialized */ ++ if (sc->sc_dp[cpu].dp_ph != NULL) ++ return (sc->sc_dp[cpu].dp_ph); ++ ++ /* Map CE/CI registers (global kernel VA, accessible from any CPU) */ ++ dpaa_portal_map_registers_cpu(sc, cpu); ++ ++ if (sc->sc_dp[cpu].dp_ce_va == 0 || sc->sc_dp[cpu].dp_ci_va == 0) ++ return (NULL); ++ ++ if (sc->sc_dp[cpu].dp_ires == NULL) { ++ printf("qman: portal %d has no IRQ resource\n", cpu); ++ return (NULL); ++ } ++ ++ /* Init deferred RX mbuf queue (unlimited — DQRR ring is the natural cap) */ ++ mbufq_init(&qman_napi[cpu].rxq, 0); ++ ++ /* ++ * Create per-CPU taskqueue for NAPI-style polling. ++ * The task arg is set to the portal handle after Init. ++ */ ++ CPU_ZERO(&cpumask); ++ CPU_SET(cpu, &cpumask); ++ NET_TASK_INIT(&qman_napi[cpu].task, 0, qman_portal_poll_task, NULL); ++ qman_napi[cpu].tq = taskqueue_create_fast("qman_poll", M_WAITOK, ++ taskqueue_thread_enqueue, &qman_napi[cpu].tq); ++ taskqueue_start_threads_cpuset(&qman_napi[cpu].tq, 1, PI_NET, ++ &cpumask, "qman%d", cpu); ++ ++ /* ++ * Configure NAPI mode before QM_PORTAL_Init — Init calls ++ * XX_SetIntr internally, which checks for NAPI mode and ++ * registers a FILTER handler instead of an ithread handler. ++ */ ++ XX_ConfigPortalNapi((uintptr_t)sc->sc_dp[cpu].dp_ires, ++ qman_napi[cpu].tq, &qman_napi[cpu].task); ++ ++ /* Configure portal */ ++ memset(&qpp, 0, sizeof(qpp)); ++ qpp.ceBaseAddress = sc->sc_dp[cpu].dp_ce_va; ++ qpp.ciBaseAddress = sc->sc_dp[cpu].dp_ci_va; ++ qpp.h_Qm = qsc->sc_qh; ++ qpp.swPortalId = cpu; ++ qpp.irq = (uintptr_t)sc->sc_dp[cpu].dp_ires; ++ qpp.fdLiodnOffset = 0; ++ qpp.f_DfltFrame = qman_received_frame_callback; ++ qpp.f_RejectedFrame = qman_rejected_frame_callback; ++ qpp.h_App = qsc; ++ ++ portal = QM_PORTAL_Config(&qpp); ++ if (portal == NULL) ++ return (NULL); ++ ++ /* ++ * Configure stash destination (SDEST) for this CPU. ++ * Linux: qman_set_sdest(channel, cpu_idx / 2) for QMan v3+. ++ * Each pair of cores shares one Stash Request Queue (SRQ) in ++ * the CoreNet fabric. LS1046A: SRQ0=CPU0-1, SRQ1=CPU2-3. ++ */ ++ memset(&stash, 0, sizeof(stash)); ++ stash.stashDestQueue = cpu / 2; ++ QM_PORTAL_ConfigStash(portal, &stash); ++ ++ if (QM_PORTAL_Init(portal) != E_OK) { ++ QM_PORTAL_Free(portal); ++ return (NULL); ++ } ++ ++ /* ++ * Set portal handle for the FILTER handler and task. ++ * The FILTER handler uses this to call QM_PORTAL_Inhibit. ++ * The task function receives it as the arg parameter. ++ */ ++ XX_SetPortalNapiHandle((uintptr_t)sc->sc_dp[cpu].dp_ires, portal); ++ qman_napi[cpu].task.ta_context = portal; ++ ++ /* ++ * Subscribe to pool channel — all portals get RX frames. ++ * QMan hardware distributes frames round-robin across all ++ * portals subscribed to the pool channel, matching Linux's ++ * dpaa_eth_add_channel() which calls qman_p_static_dequeue_add ++ * for every CPU's portal. ++ * ++ * RX FQs are on per-CPU dedicated channels (RSS), so pool ++ * channel round-robin no longer causes TCP reordering. Pool ++ * channel is still needed for TX confirm, CDX dist FQs, and ++ * CAAM QI response FQs. ++ */ ++ QM_PORTAL_AddPoolChannel(portal, QMAN_COMMON_POOL_CHANNEL); ++ ++ sc->sc_dp[cpu].dp_ph = portal; ++ return (portal); ++} ++ ++void ++qman_portal_dqrr_diag(void) ++{ ++ struct dpaa_portals_softc *sc; ++ t_Handle portal; ++ uint8_t sw_pi, sw_ci, sw_fill, hw_pi, hw_ci; ++ uint32_t isr, ier, iir; ++ int cpu; ++ ++ if (qp_sc == NULL) ++ return; ++ sc = qp_sc; ++ ++ for (cpu = 0; cpu < mp_ncpus; cpu++) { ++ portal = sc->sc_dp[cpu].dp_ph; ++ if (portal == NULL) ++ continue; ++ QM_PORTAL_DqrrDiag(portal, &sw_pi, &sw_ci, &sw_fill, ++ &hw_pi, &hw_ci); ++ QM_PORTAL_IsrDiag(portal, &isr, &ier, &iir); ++ printf("qman: portal%d: dqrr sw_pi=%u sw_ci=%u fill=%u " ++ "hw_pi=%u hw_ci=%u isr=0x%05x ier=0x%05x iir=%u\n", ++ cpu, sw_pi, sw_ci, sw_fill, hw_pi, hw_ci, ++ isr, ier, iir); ++ } ++} ++#endif +diff --git a/sys/dev/gpio/qoriq_gpio.c b/sys/dev/gpio/qoriq_gpio.c +index 5dabe03b775..c67e704effd 100644 +--- a/sys/dev/gpio/qoriq_gpio.c ++++ b/sys/dev/gpio/qoriq_gpio.c +@@ -31,6 +31,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -48,6 +49,28 @@ + + #include "gpio_if.h" + ++/* ++ * QorIQ GPIO registers are big-endian. bus_read_4/bus_write_4 return/accept ++ * data in CPU-native byte order. On PowerPC (BE) this is a no-op, but on ++ * ARM64 (LE) the bytes get swapped, which shifts bit positions within the ++ * 32-bit word and breaks the pin ↔ bit mapping. Wrap all register access ++ * with be32toh/htobe32 so pin numbering matches the hardware datasheet on ++ * both architectures. ++ */ ++static inline uint32_t ++gpio_read(struct qoriq_gpio_softc *sc, bus_size_t off) ++{ ++ ++ return (be32toh(bus_read_4(sc->sc_mem, off))); ++} ++ ++static inline void ++gpio_write(struct qoriq_gpio_softc *sc, bus_size_t off, uint32_t val) ++{ ++ ++ bus_write_4(sc->sc_mem, off, htobe32(val)); ++} ++ + static device_t + qoriq_gpio_get_bus(device_t dev) + { +@@ -112,20 +135,20 @@ qoriq_gpio_pin_configure(device_t dev, uint32_t pin, uint32_t flags) + } + + if (flags & GPIO_PIN_INPUT) { +- reg = bus_read_4(sc->sc_mem, GPIO_GPDIR); ++ reg = gpio_read(sc, GPIO_GPDIR); + reg &= ~(1 << (31 - pin)); +- bus_write_4(sc->sc_mem, GPIO_GPDIR, reg); ++ gpio_write(sc, GPIO_GPDIR, reg); + } + else if (flags & GPIO_PIN_OUTPUT) { +- reg = bus_read_4(sc->sc_mem, GPIO_GPDIR); ++ reg = gpio_read(sc, GPIO_GPDIR); + reg |= (1 << (31 - pin)); +- bus_write_4(sc->sc_mem, GPIO_GPDIR, reg); +- reg = bus_read_4(sc->sc_mem, GPIO_GPODR); ++ gpio_write(sc, GPIO_GPDIR, reg); ++ reg = gpio_read(sc, GPIO_GPODR); + if (flags & GPIO_PIN_OPENDRAIN) + reg |= (1 << (31 - pin)); + else + reg &= ~(1 << (31 - pin)); +- bus_write_4(sc->sc_mem, GPIO_GPODR, reg); ++ gpio_write(sc, GPIO_GPODR, reg); + } + sc->sc_pins[pin].gp_flags = flags; + +@@ -183,10 +206,10 @@ qoriq_gpio_pin_set(device_t dev, uint32_t pin, unsigned int value) + GPIO_LOCK(sc); + pinbit = 31 - pin; + +- outvals = bus_read_4(sc->sc_mem, GPIO_GPDAT); ++ outvals = gpio_read(sc, GPIO_GPDAT); + outvals &= ~(1 << pinbit); + outvals |= (value << pinbit); +- bus_write_4(sc->sc_mem, GPIO_GPDAT, outvals); ++ gpio_write(sc, GPIO_GPDAT, outvals); + + GPIO_UNLOCK(sc); + +@@ -202,7 +225,7 @@ qoriq_gpio_pin_get(device_t dev, uint32_t pin, unsigned int *value) + if (!VALID_PIN(pin)) + return (EINVAL); + +- *value = (bus_read_4(sc->sc_mem, GPIO_GPDAT) >> (31 - pin)) & 1; ++ *value = (gpio_read(sc, GPIO_GPDAT) >> (31 - pin)) & 1; + + return (0); + } +@@ -219,9 +242,9 @@ qoriq_gpio_pin_toggle(device_t dev, uint32_t pin) + + GPIO_LOCK(sc); + +- val = bus_read_4(sc->sc_mem, GPIO_GPDAT); ++ val = gpio_read(sc, GPIO_GPDAT); + val ^= (1 << (31 - pin)); +- bus_write_4(sc->sc_mem, GPIO_GPDAT, val); ++ gpio_write(sc, GPIO_GPDAT, val); + + GPIO_UNLOCK(sc); + +@@ -260,8 +283,8 @@ qoriq_gpio_pin_access_32(device_t dev, uint32_t first_pin, uint32_t clear_pins, + return (EINVAL); + + GPIO_LOCK(sc); +- hwstate = bus_read_4(sc->sc_mem, GPIO_GPDAT); +- bus_write_4(sc->sc_mem, GPIO_GPDAT, ++ hwstate = gpio_read(sc, GPIO_GPDAT); ++ gpio_write(sc, GPIO_GPDAT, + (hwstate & ~clear_pins) ^ change_pins); + GPIO_UNLOCK(sc); + +@@ -310,11 +333,11 @@ qoriq_gpio_pin_config_32(device_t dev, uint32_t first_pin, uint32_t num_pins, + + GPIO_LOCK(sc); + +- reg = (bus_read_4(sc->sc_mem, GPIO_GPDIR) & ~mask) | dir; +- bus_write_4(sc->sc_mem, GPIO_GPDIR, reg); ++ reg = (gpio_read(sc, GPIO_GPDIR) & ~mask) | dir; ++ gpio_write(sc, GPIO_GPDIR, reg); + +- reg = (bus_read_4(sc->sc_mem, GPIO_GPODR) & ~mask) | odr; +- bus_write_4(sc->sc_mem, GPIO_GPODR, reg); ++ reg = (gpio_read(sc, GPIO_GPODR) & ~mask) | odr; ++ gpio_write(sc, GPIO_GPODR, reg); + + for (i = 0; i < num_pins; i++) + sc->sc_pins[i].gp_flags = newflags[i]; +@@ -381,7 +404,7 @@ qoriq_gpio_attach(device_t dev) + * devices ignore writes and read 0's in undefined portions of the map. + */ + if (ofw_bus_is_compatible(dev, "fsl,qoriq-gpio")) +- bus_write_4(sc->sc_mem, GPIO_GPIBE, 0xffffffff); ++ gpio_write(sc, GPIO_GPIBE, 0xffffffff); + + OF_device_register_xref(OF_xref_from_node(ofw_bus_get_node(dev)), dev); + +diff --git a/sys/dev/iicbus/mux/iicmux.c b/sys/dev/iicbus/mux/iicmux.c +index 5eafc8a5a21..36a405f6f32 100644 +--- a/sys/dev/iicbus/mux/iicmux.c ++++ b/sys/dev/iicbus/mux/iicmux.c +@@ -279,7 +279,8 @@ iicmux_attach_children(struct iicmux_softc *sc) + idx, sc->numbuses); + continue; + } +- sc->childdevs[idx] = device_add_child(sc->dev, "iicbus", -1); ++ sc->childdevs[idx] = device_add_child(sc->dev, ++ "iicbus", -1); + sc->childnodes[idx] = child; + if (sc->maxbus < (int)idx) + sc->maxbus = idx; +diff --git a/sys/dev/iicbus/mux/pca954x.c b/sys/dev/iicbus/mux/pca954x.c +index befa0db3917..8a8ae3cf05d 100644 +--- a/sys/dev/iicbus/mux/pca954x.c ++++ b/sys/dev/iicbus/mux/pca954x.c +@@ -94,6 +94,7 @@ static struct pca954x_descr pca9548_descr = { + #ifdef FDT + static struct ofw_compat_data compat_data[] = { + { "nxp,pca9540", (uintptr_t)&pca9540_descr }, ++ { "nxp,pca9545", (uintptr_t)&pca9546_descr }, + { "nxp,pca9546", (uintptr_t)&pca9546_descr }, + { "nxp,pca9547", (uintptr_t)&pca9547_descr }, + { "nxp,pca9548", (uintptr_t)&pca9548_descr }, +diff --git a/sys/dev/iicbus/ofw_iicbus.c b/sys/dev/iicbus/ofw_iicbus.c +index fdf7e0e188f..f2c0d41b294 100644 +--- a/sys/dev/iicbus/ofw_iicbus.c ++++ b/sys/dev/iicbus/ofw_iicbus.c +@@ -125,7 +125,7 @@ ofw_iicbus_attach(device_t dev) + freq = 0; + OF_getencprop(node, "clock-frequency", &freq, sizeof(freq)); + iicbus_init_frequency(dev, freq); +- ++ + iicbus_reset(dev, IIC_FASTEST, 0, NULL); + + bus_generic_probe(dev); +diff --git a/sys/dev/iicbus/rtc/pcf2131.c b/sys/dev/iicbus/rtc/pcf2131.c +new file mode 100644 +index 00000000000..9f73d826673 +--- /dev/null ++++ b/sys/dev/iicbus/rtc/pcf2131.c +@@ -0,0 +1,480 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies ++ * ++ * 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 AUTHOR 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 AUTHOR 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. ++ */ ++ ++#include ++/* ++ * Driver for the NXP PCF2131 real-time clock. ++ * ++ * The PCF2131 is an enhanced RTC with TCXO, 4 tamper-detect inputs, dual ++ * interrupt outputs, and a 1/4 Hz watchdog. Its register layout is NOT ++ * compatible with the older PCF2127/2129 — time registers start at 0x07 ++ * (not 0x03), extra control registers occupy 0x03-0x05, and watchdog/clkout ++ * addresses are completely different. A previous attempt to use the nxprtc ++ * driver (which targets PCF2127/2129) wrote to wrong registers and bricked ++ * the chip, so this is a standalone driver. ++ * ++ * Reference: NXP PCF2131 datasheet (Rev. 2, 2022-06-17) and ++ * Linux rtc-pcf2127.c (PCF2131 support by Hugo Villeneuve). ++ */ ++ ++#include "opt_platform.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#ifdef FDT ++#include ++#include ++#include ++#endif ++ ++#include "clock_if.h" ++#include "iicbus_if.h" ++ ++/* ++ * PCF2131 register map. ++ */ ++#define PCF2131_R_CTRL1 0x00 ++#define PCF2131_R_CTRL2 0x01 ++#define PCF2131_R_CTRL3 0x02 ++#define PCF2131_R_CTRL4 0x03 ++#define PCF2131_R_CTRL5 0x04 ++#define PCF2131_R_SR_RESET 0x05 ++ ++#define PCF2131_R_SECOND 0x07 /* Time registers 0x07-0x0D */ ++#define PCF2131_R_CLKOUT 0x13 ++#define PCF2131_R_WD_CTL 0x35 ++#define PCF2131_R_WD_VAL 0x36 ++ ++/* Interrupt mask registers (write 0 to unmask → enable on INT_A). */ ++#define PCF2131_R_INT_A_MASK1 0x31 ++#define PCF2131_R_INT_A_MASK2 0x32 ++#define PCF2131_R_INT_B_MASK1 0x33 ++#define PCF2131_R_INT_B_MASK2 0x34 ++ ++/* CTRL1 bits */ ++#define PCF2131_B_CTRL1_POR_OVRD 0x08 /* Power-On Reset Override */ ++#define PCF2131_B_CTRL1_STOP 0x20 /* Stop clock */ ++ ++/* CTRL3 bits (battery management) */ ++#define PCF2131_B_CTRL3_BLF 0x04 /* Battery Low Flag */ ++#define PCF2131_B_CTRL3_BF 0x08 /* Battery switch-over Flag */ ++#define PCF2131_B_CTRL3_BTSE 0x10 /* Battery timestamp enable */ ++#define PCF2131_B_CTRL3_BIE 0x02 /* Battery interrupt enable */ ++#define PCF2131_B_CTRL3_BLIE 0x01 /* Battery low int enable */ ++ ++/* SR_RESET: CPR (Clear Prescaler) command */ ++#define PCF2131_CPR_CMD 0xa4 /* BIT(7)|BIT(5)|BIT(2) */ ++ ++/* CLKOUT bits */ ++#define PCF2131_B_CLKOUT_OTPR 0x20 /* OTP refresh */ ++#define PCF2131_B_CLKOUT_HIGHZ 0x07 /* Clock output disabled */ ++ ++/* Seconds register: oscillator stopped flag */ ++#define PCF2131_B_SC_OSF 0x80 ++ ++/* Watchdog control bits */ ++#define PCF2131_B_WD_CD1 0x80 /* Watchdog counter disabled / reset */ ++#define PCF2131_B_WD_TF1 0x02 /* Timer source flag 1 (1/4 Hz) */ ++ ++/* BCD time field masks */ ++#define PCF2131_M_SECOND 0x7f ++#define PCF2131_M_MINUTE 0x7f ++#define PCF2131_M_24HOUR 0x3f ++#define PCF2131_M_DAY 0x3f ++#define PCF2131_M_MONTH 0x1f ++#define PCF2131_M_YEAR 0xff ++ ++/* ++ * I2C wait flags: wait for bus, but allow recursive locking so we can ++ * do multi-register sequences under a single bus reservation. ++ */ ++#define WAITFLAGS (IIC_WAIT | IIC_RECURSIVE) ++ ++struct time_regs { ++ uint8_t sec, min, hour, day, wday, month, year; ++}; ++ ++struct pcf2131_softc { ++ device_t dev; ++ device_t busdev; ++ struct intr_config_hook config_hook; ++}; ++ ++/* ++ * I2C helpers. The PCF2131 (like PCF2127) requires a STOP condition between ++ * the register address write and the data read — no repeated START. ++ */ ++static int ++pcf2131_readfrom(device_t slavedev, uint8_t regaddr, void *buffer, ++ uint16_t buflen, int waithow) ++{ ++ struct iic_msg msg; ++ int err; ++ uint8_t slaveaddr; ++ ++ slaveaddr = iicbus_get_addr(slavedev); ++ ++ msg.slave = slaveaddr; ++ msg.flags = IIC_M_WR; ++ msg.len = 1; ++ msg.buf = ®addr; ++ ++ if ((err = iicbus_transfer_excl(slavedev, &msg, 1, waithow)) != 0) ++ return (err); ++ ++ msg.slave = slaveaddr; ++ msg.flags = IIC_M_RD; ++ msg.len = buflen; ++ msg.buf = buffer; ++ ++ return (iicbus_transfer_excl(slavedev, &msg, 1, waithow)); ++} ++ ++static int ++read_reg(struct pcf2131_softc *sc, uint8_t reg, uint8_t *val) ++{ ++ ++ return (pcf2131_readfrom(sc->dev, reg, val, sizeof(*val), WAITFLAGS)); ++} ++ ++static int ++write_reg(struct pcf2131_softc *sc, uint8_t reg, uint8_t val) ++{ ++ ++ return (iicdev_writeto(sc->dev, reg, &val, sizeof(val), WAITFLAGS)); ++} ++ ++static int ++read_timeregs(struct pcf2131_softc *sc, struct time_regs *tregs) ++{ ++ ++ return (pcf2131_readfrom(sc->dev, PCF2131_R_SECOND, tregs, ++ sizeof(*tregs), WAITFLAGS)); ++} ++ ++static int ++write_timeregs(struct pcf2131_softc *sc, struct time_regs *tregs) ++{ ++ ++ return (iicdev_writeto(sc->dev, PCF2131_R_SECOND, tregs, ++ sizeof(*tregs), WAITFLAGS)); ++} ++ ++/* ++ * Chip initialization, called via config_intrhook once interrupts are up. ++ */ ++static void ++pcf2131_start(void *arg) ++{ ++ struct pcf2131_softc *sc; ++ device_t dev; ++ int clockflags, err; ++ uint8_t ctrl1, sec, clkout; ++ ++ dev = (device_t)arg; ++ sc = device_get_softc(dev); ++ config_intrhook_disestablish(&sc->config_hook); ++ ++ /* ++ * Read CTRL1 and seconds to check for oscillator stop / clock halt. ++ */ ++ if ((err = read_reg(sc, PCF2131_R_CTRL1, &ctrl1)) != 0) { ++ device_printf(dev, "cannot read CTRL1\n"); ++ return; ++ } ++ if ((err = read_reg(sc, PCF2131_R_SECOND, &sec)) != 0) { ++ device_printf(dev, "cannot read seconds register\n"); ++ return; ++ } ++ ++ if ((ctrl1 & PCF2131_B_CTRL1_STOP) || (sec & PCF2131_B_SC_OSF)) { ++ device_printf(dev, ++ "WARNING: RTC battery failed; time is invalid\n"); ++ ++ /* ++ * Clear POR Override bit (used for manufacturing test only). ++ */ ++ ctrl1 &= ~PCF2131_B_CTRL1_POR_OVRD; ++ ctrl1 &= ~PCF2131_B_CTRL1_STOP; ++ if ((err = write_reg(sc, PCF2131_R_CTRL1, ctrl1)) != 0) { ++ device_printf(dev, "cannot write CTRL1\n"); ++ return; ++ } ++ } else { ++ /* ++ * Normal operation — still clear POR Override if set. ++ */ ++ if (ctrl1 & PCF2131_B_CTRL1_POR_OVRD) { ++ ctrl1 &= ~PCF2131_B_CTRL1_POR_OVRD; ++ if ((err = write_reg(sc, PCF2131_R_CTRL1, ++ ctrl1)) != 0) { ++ device_printf(dev, "cannot write CTRL1\n"); ++ return; ++ } ++ } ++ } ++ ++ /* ++ * OTP refresh: trigger if OTPR bit is not set. ++ */ ++ if ((err = read_reg(sc, PCF2131_R_CLKOUT, &clkout)) != 0) { ++ device_printf(dev, "cannot read CLKOUT\n"); ++ return; ++ } ++ if (!(clkout & PCF2131_B_CLKOUT_OTPR)) { ++ err = write_reg(sc, PCF2131_R_CLKOUT, ++ clkout | PCF2131_B_CLKOUT_OTPR); ++ if (err != 0) { ++ device_printf(dev, "cannot trigger OTP refresh\n"); ++ return; ++ } ++ pause_sbt("pcfotp", mstosbt(100), mstosbt(10), 0); ++ } ++ ++ /* ++ * Disable battery low/switch-over timestamp and interrupts. ++ * Clear pending battery flags. ++ */ ++ err = write_reg(sc, PCF2131_R_CTRL3, ++ PCF2131_B_CTRL3_BTSE | PCF2131_B_CTRL3_BIE | ++ PCF2131_B_CTRL3_BLIE); ++ /* Clear by writing 0 to BLF/BF while keeping disables set — actually ++ * Linux clears BTSE/BIE/BLIE to 0 (disable all battery interrupts). */ ++ write_reg(sc, PCF2131_R_CTRL3, 0); ++ ++ /* ++ * Route all interrupts to INT_A pin (mask = 0 means enabled). ++ * Mask everything on INT_B. ++ */ ++ write_reg(sc, PCF2131_R_INT_A_MASK1, 0); ++ write_reg(sc, PCF2131_R_INT_A_MASK2, 0); ++ write_reg(sc, PCF2131_R_INT_B_MASK1, 0xff); ++ write_reg(sc, PCF2131_R_INT_B_MASK2, 0xff); ++ ++ /* ++ * Configure watchdog: enable reset output (CD1), 1/4 Hz clock (TF1). ++ * Don't start it (value register = 0). ++ */ ++ write_reg(sc, PCF2131_R_WD_CTL, PCF2131_B_WD_CD1 | PCF2131_B_WD_TF1); ++ write_reg(sc, PCF2131_R_WD_VAL, 0); ++ ++ /* ++ * Register as an RTC. No fractional-second timer on PCF2131, so ++ * resolution is 500ms (half-second rounding like nxprtc without timer). ++ */ ++ clockflags = CLOCKF_GETTIME_NO_ADJ | CLOCKF_SETTIME_NO_TS; ++ clock_register_flags(dev, 1000000 / 2, clockflags); ++ clock_schedule(dev, 495000000); ++} ++ ++static int ++pcf2131_gettime(device_t dev, struct timespec *ts) ++{ ++ struct bcd_clocktime bct; ++ struct time_regs tregs; ++ struct pcf2131_softc *sc; ++ int err; ++ uint8_t ctrl1; ++ ++ sc = device_get_softc(dev); ++ ++ if ((err = iicbus_request_bus(sc->busdev, sc->dev, IIC_WAIT)) != 0) ++ return (err); ++ if ((err = read_timeregs(sc, &tregs)) == 0) ++ err = read_reg(sc, PCF2131_R_CTRL1, &ctrl1); ++ iicbus_release_bus(sc->busdev, sc->dev); ++ ++ if (err != 0) ++ return (err); ++ ++ if ((tregs.sec & PCF2131_B_SC_OSF) || ++ (ctrl1 & PCF2131_B_CTRL1_STOP)) { ++ device_printf(dev, "RTC clock not running\n"); ++ return (EINVAL); ++ } ++ ++ bct.nsec = 0; ++ bct.ispm = false; ++ bct.sec = tregs.sec & PCF2131_M_SECOND; ++ bct.min = tregs.min & PCF2131_M_MINUTE; ++ bct.hour = tregs.hour & PCF2131_M_24HOUR; ++ bct.day = tregs.day & PCF2131_M_DAY; ++ bct.mon = tregs.month & PCF2131_M_MONTH; ++ bct.year = tregs.year & PCF2131_M_YEAR; ++ bct.dow = tregs.wday & 0x07; ++ ++ clock_dbgprint_bcd(sc->dev, CLOCK_DBG_READ, &bct); ++ err = clock_bcd_to_ts(&bct, ts, false); ++ ts->tv_sec += utc_offset(); ++ ++ return (err); ++} ++ ++static int ++pcf2131_settime(device_t dev, struct timespec *ts) ++{ ++ struct bcd_clocktime bct; ++ struct time_regs tregs; ++ struct pcf2131_softc *sc; ++ int err; ++ uint8_t ctrl1; ++ ++ sc = device_get_softc(dev); ++ ++ if ((err = iicbus_request_bus(sc->busdev, sc->dev, IIC_WAIT)) != 0) ++ return (err); ++ ++ /* ++ * PCF2131 time write sequence: ++ * 1. Set STOP bit in CTRL1 ++ * 2. Write CPR (Clear Prescaler) command to SR_RESET ++ * 3. Write time registers ++ * 4. Clear STOP bit ++ */ ++ if ((err = read_reg(sc, PCF2131_R_CTRL1, &ctrl1)) != 0) ++ goto errout; ++ ctrl1 |= PCF2131_B_CTRL1_STOP; ++ if ((err = write_reg(sc, PCF2131_R_CTRL1, ctrl1)) != 0) ++ goto errout; ++ ++ if ((err = write_reg(sc, PCF2131_R_SR_RESET, PCF2131_CPR_CMD)) != 0) ++ goto errout; ++ ++ /* Grab a fresh post-sleep idea of what time it is. */ ++ getnanotime(ts); ++ ts->tv_sec -= utc_offset(); ++ ts->tv_nsec = 0; ++ clock_ts_to_bcd(ts, &bct, false); ++ clock_dbgprint_bcd(sc->dev, CLOCK_DBG_WRITE, &bct); ++ ++ tregs.sec = bct.sec; ++ tregs.min = bct.min; ++ tregs.hour = bct.hour; ++ tregs.day = bct.day; ++ tregs.month = bct.mon; ++ tregs.year = bct.year & 0xff; ++ tregs.wday = bct.dow; ++ ++ if ((err = write_timeregs(sc, &tregs)) != 0) ++ goto errout; ++ ++ /* Clear STOP to resume clock. */ ++ ctrl1 &= ~PCF2131_B_CTRL1_STOP; ++ err = write_reg(sc, PCF2131_R_CTRL1, ctrl1); ++ ++errout: ++ iicbus_release_bus(sc->busdev, sc->dev); ++ ++ if (err != 0) ++ device_printf(dev, "cannot write RTC time\n"); ++ ++ return (err); ++} ++ ++/* ++ * FDT compatible strings. ++ */ ++#ifdef FDT ++static struct ofw_compat_data compat_data[] = { ++ {"nxp,pcf2131", 1}, ++ {NULL, 0}, ++}; ++#endif ++ ++static int ++pcf2131_probe(device_t dev) ++{ ++ ++#ifdef FDT ++ if (!ofw_bus_status_okay(dev)) ++ return (ENXIO); ++ if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == 0) ++ return (ENXIO); ++#else ++ return (ENXIO); /* FDT only */ ++#endif ++ device_set_desc(dev, "NXP PCF2131 RTC"); ++ return (BUS_PROBE_GENERIC); ++} ++ ++static int ++pcf2131_attach(device_t dev) ++{ ++ struct pcf2131_softc *sc; ++ ++ sc = device_get_softc(dev); ++ sc->dev = dev; ++ sc->busdev = device_get_parent(dev); ++ ++ /* Defer init until interrupts are available. */ ++ sc->config_hook.ich_func = pcf2131_start; ++ sc->config_hook.ich_arg = dev; ++ if (config_intrhook_establish(&sc->config_hook) != 0) ++ return (ENOMEM); ++ ++ return (0); ++} ++ ++static int ++pcf2131_detach(device_t dev) ++{ ++ ++ clock_unregister(dev); ++ return (0); ++} ++ ++static device_method_t pcf2131_methods[] = { ++ DEVMETHOD(device_probe, pcf2131_probe), ++ DEVMETHOD(device_attach, pcf2131_attach), ++ DEVMETHOD(device_detach, pcf2131_detach), ++ ++ DEVMETHOD(clock_gettime, pcf2131_gettime), ++ DEVMETHOD(clock_settime, pcf2131_settime), ++ ++ DEVMETHOD_END ++}; ++ ++static driver_t pcf2131_driver = { ++ "pcf2131", ++ pcf2131_methods, ++ sizeof(struct pcf2131_softc), ++}; ++ ++DRIVER_MODULE(pcf2131, iicbus, pcf2131_driver, NULL, NULL); ++MODULE_VERSION(pcf2131, 1); ++MODULE_DEPEND(pcf2131, iicbus, IICBUS_MINVER, IICBUS_PREFVER, IICBUS_MAXVER); ++#ifdef FDT ++IICBUS_FDT_PNP_INFO(compat_data); ++#endif +diff --git a/sys/dev/iicbus/sensor/ina2xx.c b/sys/dev/iicbus/sensor/ina2xx.c +new file mode 100644 +index 00000000000..1554ba75236 +--- /dev/null ++++ b/sys/dev/iicbus/sensor/ina2xx.c +@@ -0,0 +1,399 @@ ++/*- ++ * SPDX-License-Identifier: BSD-2-Clause ++ * ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * ++ * Texas Instruments INA219/INA226/INA234 I2C power monitor driver. ++ * 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. ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++ ++/* 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 ++ ++/* Default shunt resistance: 10 mOhm = 10000 uOhm */ ++#define INA2XX_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; ++}; ++ ++static const struct ina2xx_config ina2xx_configs[] = { ++ [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, ++ }, ++ [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, ++ }, ++ [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, ++ }, ++}; ++ ++struct ina2xx_softc { ++ device_t dev; ++ enum ina2xx_chip chip; ++ const struct ina2xx_config *config; ++ uint32_t rshunt; /* shunt resistance, uOhm */ ++ long current_lsb_uA; ++ long power_lsb_uW; ++ struct sysctl_ctx_list sysctl_ctx; ++ char label[64]; ++}; ++ ++/* ================================================================ ++ * I2C register helpers — 16-bit big-endian ++ * ================================================================ */ ++ ++static int ++ina2xx_read_reg(device_t dev, uint8_t reg, uint16_t *val) ++{ ++ uint8_t buf[2]; ++ int error; ++ ++ error = iicdev_readfrom(dev, reg, buf, 2, IIC_WAIT); ++ if (error != 0) ++ return (error); ++ *val = (buf[0] << 8) | buf[1]; ++ return (0); ++} ++ ++static int ++ina2xx_write_reg(device_t dev, uint8_t reg, uint16_t val) ++{ ++ uint8_t buf[2]; ++ ++ buf[0] = (val >> 8) & 0xFF; ++ buf[1] = val & 0xFF; ++ return (iicdev_writeto(dev, reg, buf, 2, IIC_WAIT)); ++} ++ ++/* ================================================================ ++ * Measurement value conversion (matches Linux ina2xx_get_value) ++ * ================================================================ */ ++ ++static int ++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); ++ if (error != 0) ++ return (error); ++ *millivolts = ((raw >> sc->config->bus_voltage_shift) * ++ sc->config->bus_voltage_lsb) / 1000; ++ return (0); ++} ++ ++static int ++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); ++ if (error != 0) ++ return (error); ++ /* Shunt voltage register is signed */ ++ *microvolts = (int16_t)raw * 1000 / sc->config->shunt_div; ++ return (0); ++} ++ ++static int ++ina2xx_read_current(struct ina2xx_softc *sc, int *milliamps) ++{ ++ uint16_t raw; ++ int error; ++ ++ error = ina2xx_read_reg(sc->dev, INA2XX_CURRENT, &raw); ++ if (error != 0) ++ return (error); ++ /* Current register is signed */ ++ *milliamps = (int16_t)raw * sc->current_lsb_uA / 1000; ++ return (0); ++} ++ ++static int ++ina2xx_read_power(struct ina2xx_softc *sc, int *milliwatts) ++{ ++ uint16_t raw; ++ int error; ++ ++ error = ina2xx_read_reg(sc->dev, INA2XX_POWER, &raw); ++ if (error != 0) ++ return (error); ++ /* Power register is unsigned */ ++ *milliwatts = (int)((uint32_t)raw * sc->power_lsb_uW / 1000); ++ return (0); ++} ++ ++/* ================================================================ ++ * Sysctl handlers ++ * ================================================================ */ ++ ++static int ++ina2xx_sysctl_bus_voltage(SYSCTL_HANDLER_ARGS) ++{ ++ struct ina2xx_softc *sc = arg1; ++ int val, error; ++ ++ if (req->newptr != NULL) ++ return (EINVAL); ++ error = ina2xx_read_bus_voltage(sc, &val); ++ if (error != 0) ++ return (error); ++ return (sysctl_handle_int(oidp, &val, 0, req)); ++} ++ ++static int ++ina2xx_sysctl_shunt_voltage(SYSCTL_HANDLER_ARGS) ++{ ++ struct ina2xx_softc *sc = arg1; ++ int val, error; ++ ++ if (req->newptr != NULL) ++ return (EINVAL); ++ error = ina2xx_read_shunt_voltage(sc, &val); ++ if (error != 0) ++ return (error); ++ return (sysctl_handle_int(oidp, &val, 0, req)); ++} ++ ++static int ++ina2xx_sysctl_current(SYSCTL_HANDLER_ARGS) ++{ ++ struct ina2xx_softc *sc = arg1; ++ int val, error; ++ ++ if (req->newptr != NULL) ++ return (EINVAL); ++ error = ina2xx_read_current(sc, &val); ++ if (error != 0) ++ return (error); ++ return (sysctl_handle_int(oidp, &val, 0, req)); ++} ++ ++static int ++ina2xx_sysctl_power(SYSCTL_HANDLER_ARGS) ++{ ++ struct ina2xx_softc *sc = arg1; ++ int val, error; ++ ++ if (req->newptr != NULL) ++ return (EINVAL); ++ error = ina2xx_read_power(sc, &val); ++ if (error != 0) ++ return (error); ++ return (sysctl_handle_int(oidp, &val, 0, req)); ++} ++ ++/* ================================================================ ++ * Probe / Attach / Detach ++ * ================================================================ */ ++ ++static struct ofw_compat_data compat_data[] = { ++ { "ti,ina219", (uintptr_t)INA219 }, ++ { "ti,ina220", (uintptr_t)INA219 }, ++ { "ti,ina226", (uintptr_t)INA226 }, ++ { "ti,ina230", (uintptr_t)INA226 }, ++ { "ti,ina231", (uintptr_t)INA226 }, ++ { "ti,ina234", (uintptr_t)INA234 }, ++ { NULL, 0 }, ++}; ++ ++static int ++ina2xx_probe(device_t dev) ++{ ++ const struct ofw_compat_data *cd; ++ phandle_t node; ++ char desc[80]; ++ char label[64]; ++ ++ if (!ofw_bus_status_okay(dev)) ++ return (ENXIO); ++ ++ cd = ofw_bus_search_compatible(dev, compat_data); ++ if (cd->ocd_data == 0) ++ return (ENXIO); ++ ++ node = ofw_bus_get_node(dev); ++ if (OF_getprop(node, "label", label, sizeof(label)) > 0) { ++ label[sizeof(label) - 1] = '\0'; ++ snprintf(desc, sizeof(desc), "INA2xx Power Monitor (%s)", ++ label); ++ } ++ else ++ snprintf(desc, sizeof(desc), "INA2xx Power Monitor"); ++ device_set_desc_copy(dev, desc); ++ ++ return (BUS_PROBE_DEFAULT); ++} ++ ++static int ++ina2xx_attach(device_t dev) ++{ ++ struct ina2xx_softc *sc; ++ const struct ofw_compat_data *cd; ++ phandle_t node; ++ struct sysctl_oid *oid; ++ uint32_t shunt; ++ long dividend; ++ int error; ++ ++ sc = device_get_softc(dev); ++ sc->dev = dev; ++ ++ cd = ofw_bus_search_compatible(dev, compat_data); ++ sc->chip = (enum ina2xx_chip)cd->ocd_data; ++ sc->config = &ina2xx_configs[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; ++ sc->rshunt = shunt; ++ if (sc->rshunt == 0) ++ sc->rshunt = INA2XX_RSHUNT_DEFAULT; ++ ++ /* Read label from DT */ ++ sc->label[0] = '\0'; ++ OF_getprop(node, "label", sc->label, sizeof(sc->label)); ++ 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; ++ ++ /* Program configuration register */ ++ error = ina2xx_write_reg(dev, INA2XX_CONFIG, ++ sc->config->config_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); ++ if (error != 0) { ++ device_printf(dev, "failed to write calibration register\n"); ++ return (ENXIO); ++ } ++ ++ /* Create sysctl tree */ ++ sysctl_ctx_init(&sc->sysctl_ctx); ++ oid = device_get_sysctl_tree(dev); ++ ++ if (sc->label[0] != '\0') { ++ SYSCTL_ADD_STRING(&sc->sysctl_ctx, SYSCTL_CHILDREN(oid), ++ OID_AUTO, "label", CTLFLAG_RD, sc->label, 0, ++ "Sensor label"); ++ } ++ ++ SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(oid), ++ OID_AUTO, "bus_voltage", ++ CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, ++ sc, 0, ina2xx_sysctl_bus_voltage, "I", ++ "Bus voltage (mV)"); ++ ++ SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(oid), ++ OID_AUTO, "shunt_voltage", ++ CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, ++ sc, 0, ina2xx_sysctl_shunt_voltage, "I", ++ "Shunt voltage (uV)"); ++ ++ SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(oid), ++ OID_AUTO, "current", ++ CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, ++ sc, 0, ina2xx_sysctl_current, "I", ++ "Current (mA)"); ++ ++ SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(oid), ++ OID_AUTO, "power", ++ CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, ++ sc, 0, ina2xx_sysctl_power, "I", ++ "Power (mW)"); ++ ++ if (sc->label[0] != '\0') ++ device_printf(dev, "%s: shunt=%u uOhm, " ++ "current_lsb=%ld uA, power_lsb=%ld uW\n", ++ sc->label, sc->rshunt, ++ sc->current_lsb_uA, sc->power_lsb_uW); ++ ++ return (0); ++} ++ ++static int ++ina2xx_detach(device_t dev) ++{ ++ struct ina2xx_softc *sc; ++ ++ sc = device_get_softc(dev); ++ sysctl_ctx_free(&sc->sysctl_ctx); ++ return (0); ++} ++ ++static device_method_t ina2xx_methods[] = { ++ DEVMETHOD(device_probe, ina2xx_probe), ++ DEVMETHOD(device_attach, ina2xx_attach), ++ DEVMETHOD(device_detach, ina2xx_detach), ++ DEVMETHOD_END ++}; ++ ++static driver_t ina2xx_driver = { ++ "ina2xx", ++ ina2xx_methods, ++ sizeof(struct ina2xx_softc), ++}; ++ ++DRIVER_MODULE(ina2xx, iicbus, ina2xx_driver, NULL, NULL); ++MODULE_VERSION(ina2xx, 1); ++MODULE_DEPEND(ina2xx, iicbus, IICBUS_MODVER, IICBUS_MODVER, IICBUS_MODVER); ++IICBUS_FDT_PNP_INFO(compat_data); +diff --git a/sys/dev/mii/gpyphy.c b/sys/dev/mii/gpyphy.c +new file mode 100644 +index 00000000000..6357000a4e6 +--- /dev/null ++++ b/sys/dev/mii/gpyphy.c +@@ -0,0 +1,371 @@ ++/*- ++ * Copyright (c) 2026 Mono Technologies Inc. ++ * All rights reserved. ++ * ++ * 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 AUTHOR 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 AUTHOR 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. ++ */ ++ ++/* ++ * MaxLinear GPY115/GPY211/GPY212/GPY215/GPY241/GPY245 PHY driver. ++ * ++ * These PHYs require explicit SGMII auto-negotiation enable via a ++ * vendor-specific MMD register (VSPEC1_SGMII_CTRL). Without this, ++ * the MAC-side PCS never synchronizes and the link stays down. ++ * ++ * Reference: Linux drivers/net/phy/mxl-gpy.c ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include ++#include ++#include "miidevs.h" ++ ++#include "miibus_if.h" ++ ++/* Vendor-specific Clause 22 registers */ ++#define GPY_MIISTAT 0x18 /* MII state */ ++#define GPY_IMASK 0x19 /* Interrupt mask */ ++#define GPY_ISTAT 0x1A /* Interrupt status */ ++#define GPY_FWV 0x1E /* Firmware version */ ++ ++/* GPY_MIISTAT bits */ ++#define GPY_MIISTAT_LS (1 << 10) /* Link status */ ++#define GPY_MIISTAT_DPX (1 << 3) /* Duplex: 1=full */ ++#define GPY_MIISTAT_SPD_MASK 0x0007 ++#define GPY_MIISTAT_SPD_10 0 ++#define GPY_MIISTAT_SPD_100 1 ++#define GPY_MIISTAT_SPD_1000 2 ++#define GPY_MIISTAT_SPD_2500 4 ++ ++/* GPY_FWV bits */ ++#define GPY_FWV_REL_MASK (1 << 15) ++#define GPY_FWV_MAJOR_MASK 0x0F00 ++#define GPY_FWV_MAJOR_SHIFT 8 ++#define GPY_FWV_MINOR_MASK 0x00FF ++ ++/* MMD device address for vendor-specific registers */ ++#define MDIO_MMD_VEND1 30 ++ ++/* VSPEC1 (MMD30) registers */ ++#define VSPEC1_SGMII_CTRL 0x08 ++#define VSPEC1_SGMII_CTRL_ANEN (1 << 12) /* SGMII AN enable */ ++#define VSPEC1_SGMII_CTRL_ANRS (1 << 9) /* SGMII AN restart */ ++ ++/* ++ * Firmware versions that need SGMII AN re-trigger workaround. ++ * If firmware is older than these, SGMII AN must be manually ++ * restarted on link-up because the PHY won't re-trigger it ++ * when link partner speed hasn't changed. ++ */ ++static const struct { ++ int major; ++ int minor; ++} gpy_sgmii_reaneg_ver[] = { ++ { 7, 0x6D }, ++ { 8, 0x6D }, ++ { 9, 0x73 }, ++}; ++ ++struct gpyphy_softc { ++ struct mii_softc mii_sc; ++ uint8_t fw_major; ++ uint8_t fw_minor; ++ int prev_link; ++}; ++ ++static int gpyphy_probe(device_t); ++static int gpyphy_attach(device_t); ++static int gpyphy_service(struct mii_softc *, struct mii_data *, int); ++static void gpyphy_status(struct mii_softc *); ++static void gpyphy_reset(struct mii_softc *); ++ ++static device_method_t gpyphy_methods[] = { ++ DEVMETHOD(device_probe, gpyphy_probe), ++ DEVMETHOD(device_attach, gpyphy_attach), ++ DEVMETHOD(device_detach, mii_phy_detach), ++ DEVMETHOD(device_shutdown, bus_generic_shutdown), ++ DEVMETHOD_END ++}; ++ ++static driver_t gpyphy_driver = { ++ "gpyphy", ++ gpyphy_methods, ++ sizeof(struct gpyphy_softc) ++}; ++ ++DRIVER_MODULE(gpyphy, miibus, gpyphy_driver, 0, 0); ++ ++static const struct mii_phydesc gpyphys[] = { ++ MII_PHY_DESC(MAXLINEAR, GPY2xx), ++ MII_PHY_DESC(MAXLINEAR, GPY115), ++ MII_PHY_DESC(MAXLINEAR, GPY115C), ++ MII_PHY_DESC(MAXLINEAR, GPY211), ++ MII_PHY_DESC(MAXLINEAR, GPY211C), ++ MII_PHY_DESC(MAXLINEAR, GPY212C), ++ MII_PHY_DESC(MAXLINEAR, GPY215C), ++ MII_PHY_DESC(MAXLINEAR, GPY241), ++ MII_PHY_DESC(MAXLINEAR, GPY241BM), ++ MII_PHY_DESC(MAXLINEAR, GPY245), ++ MII_PHY_END ++}; ++ ++static const struct mii_phy_funcs gpyphy_funcs = { ++ gpyphy_service, ++ gpyphy_status, ++ gpyphy_reset ++}; ++ ++/* ++ * MMD indirect access via Clause 22 registers 13/14 (MII_MMDACR/MII_MMDAADR). ++ * Same pattern used by micphy.c (ksz9031_read/write) and rgephy.c. ++ */ ++static int ++gpyphy_mmd_read(struct mii_softc *sc, int devaddr, int reg) ++{ ++ ++ /* Set MMD device address */ ++ PHY_WRITE(sc, MII_MMDACR, devaddr & MMDACR_DADDRMASK); ++ /* Set MMD register address */ ++ PHY_WRITE(sc, MII_MMDAADR, reg); ++ /* Select data, no post-increment */ ++ PHY_WRITE(sc, MII_MMDACR, ++ MMDACR_FN_DATANPI | (devaddr & MMDACR_DADDRMASK)); ++ /* Read data */ ++ return (PHY_READ(sc, MII_MMDAADR)); ++} ++ ++static void ++gpyphy_mmd_write(struct mii_softc *sc, int devaddr, int reg, int val) ++{ ++ ++ /* Set MMD device address */ ++ PHY_WRITE(sc, MII_MMDACR, devaddr & MMDACR_DADDRMASK); ++ /* Set MMD register address */ ++ PHY_WRITE(sc, MII_MMDAADR, reg); ++ /* Select data, no post-increment */ ++ PHY_WRITE(sc, MII_MMDACR, ++ MMDACR_FN_DATANPI | (devaddr & MMDACR_DADDRMASK)); ++ /* Write data */ ++ PHY_WRITE(sc, MII_MMDAADR, val); ++} ++ ++/* ++ * Enable and restart SGMII auto-negotiation. ++ * ++ * The GPY PHY uses SGMII to communicate with the MAC's PCS. ++ * Without SGMII AN enabled, the PCS never synchronizes and the ++ * MAC reports no carrier even when the copper link is up. ++ */ ++static void ++gpyphy_sgmii_aneg(struct mii_softc *sc) ++{ ++ int val; ++ ++ val = gpyphy_mmd_read(sc, MDIO_MMD_VEND1, VSPEC1_SGMII_CTRL); ++ val |= VSPEC1_SGMII_CTRL_ANEN | VSPEC1_SGMII_CTRL_ANRS; ++ gpyphy_mmd_write(sc, MDIO_MMD_VEND1, VSPEC1_SGMII_CTRL, val); ++} ++ ++static bool ++gpyphy_need_sgmii_reaneg(struct gpyphy_softc *gsc) ++{ ++ size_t i; ++ ++ for (i = 0; i < nitems(gpy_sgmii_reaneg_ver); i++) { ++ if (gsc->fw_major != gpy_sgmii_reaneg_ver[i].major) ++ continue; ++ if (gsc->fw_minor < gpy_sgmii_reaneg_ver[i].minor) ++ return (true); ++ break; ++ } ++ ++ return (false); ++} ++ ++static int ++gpyphy_probe(device_t dev) ++{ ++ ++ return (mii_phy_dev_probe(dev, gpyphys, BUS_PROBE_DEFAULT)); ++} ++ ++static int ++gpyphy_attach(device_t dev) ++{ ++ struct gpyphy_softc *gsc; ++ struct mii_softc *sc; ++ int fwv; ++ ++ gsc = device_get_softc(dev); ++ sc = &gsc->mii_sc; ++ gsc->prev_link = 0; ++ ++ /* Must initialize mii_softc before any PHY register access */ ++ mii_phy_dev_attach(dev, MIIF_NOMANPAUSE, &gpyphy_funcs, 1); ++ ++ /* Read firmware version */ ++ fwv = PHY_READ(sc, GPY_FWV); ++ gsc->fw_major = (fwv & GPY_FWV_MAJOR_MASK) >> GPY_FWV_MAJOR_SHIFT; ++ gsc->fw_minor = fwv & GPY_FWV_MINOR_MASK; ++ ++ device_printf(dev, "MaxLinear GPY Firmware: %d.%d (0x%04x%s)\n", ++ gsc->fw_major, gsc->fw_minor, fwv, ++ (fwv & GPY_FWV_REL_MASK) ? "" : " test"); ++ ++ /* Enable SGMII auto-negotiation — critical for MAC-side link */ ++ gpyphy_sgmii_aneg(sc); ++ ++ mii_phy_setmedia(sc); ++ ++ return (0); ++} ++ ++static int ++gpyphy_service(struct mii_softc *sc, struct mii_data *mii, int cmd) ++{ ++ struct gpyphy_softc *gsc = (struct gpyphy_softc *)sc; ++ ++ switch (cmd) { ++ case MII_POLLSTAT: ++ break; ++ ++ case MII_MEDIACHG: ++ mii_phy_setmedia(sc); ++ /* Re-trigger SGMII AN after media change */ ++ gpyphy_sgmii_aneg(sc); ++ break; ++ ++ case MII_TICK: ++ if (mii_phy_tick(sc) == EJUSTRETURN) ++ return (0); ++ break; ++ } ++ ++ /* Update the media status */ ++ PHY_STATUS(sc); ++ ++ /* ++ * Re-trigger SGMII AN on link-up transitions. ++ * ++ * Some GPY firmware versions don't re-trigger SGMII AN when the ++ * copper link comes back at the same speed. Always re-trigger ++ * on down→up transitions to be safe — SGMII AN restart is ++ * harmless if already negotiated. ++ */ ++ if ((mii->mii_media_status & IFM_ACTIVE) && !gsc->prev_link) { ++ gpyphy_sgmii_aneg(sc); ++ } ++ gsc->prev_link = (mii->mii_media_status & IFM_ACTIVE) ? 1 : 0; ++ ++ /* Callback if something changed */ ++ mii_phy_update(sc, cmd); ++ return (0); ++} ++ ++static void ++gpyphy_status(struct mii_softc *sc) ++{ ++ struct mii_data *mii = sc->mii_pdata; ++ int bmsr, miistat; ++ ++ mii->mii_media_status = IFM_AVALID; ++ mii->mii_media_active = IFM_ETHER; ++ ++ /* Read BMSR twice — link status bit latches low */ ++ bmsr = PHY_READ(sc, MII_BMSR) | PHY_READ(sc, MII_BMSR); ++ ++ /* ++ * Read vendor-specific MIISTAT for link, speed, and duplex. ++ * PHY_MIISTAT reflects the actual resolved link state and is ++ * more reliable than decoding ANLPAR for GPY PHYs. ++ */ ++ miistat = PHY_READ(sc, GPY_MIISTAT); ++ ++ if (!(miistat & GPY_MIISTAT_LS)) { ++ /* No link — check BMSR too for consistency */ ++ if (bmsr & BMSR_LINK) { ++ /* ++ * BMSR shows link but MIISTAT doesn't — this can ++ * happen briefly during SGMII negotiation. Report ++ * no link; the next tick will re-check. ++ */ ++ } ++ mii->mii_media_active |= IFM_NONE; ++ return; ++ } ++ ++ mii->mii_media_status |= IFM_ACTIVE; ++ ++ /* Duplex */ ++ if (miistat & GPY_MIISTAT_DPX) ++ mii->mii_media_active |= IFM_FDX; ++ else ++ mii->mii_media_active |= IFM_HDX; ++ ++ /* Speed */ ++ switch (miistat & GPY_MIISTAT_SPD_MASK) { ++ case GPY_MIISTAT_SPD_1000: ++ mii->mii_media_active |= IFM_1000_T; ++ break; ++ case GPY_MIISTAT_SPD_100: ++ mii->mii_media_active |= IFM_100_TX; ++ break; ++ case GPY_MIISTAT_SPD_10: ++ mii->mii_media_active |= IFM_10_T; ++ break; ++ case GPY_MIISTAT_SPD_2500: ++ mii->mii_media_active |= IFM_2500_T; ++ break; ++ default: ++ mii->mii_media_active |= IFM_NONE; ++ break; ++ } ++ ++ if ((mii->mii_media_active & IFM_FDX) != 0) ++ mii->mii_media_active |= mii_phy_flowstatus(sc); ++} ++ ++static void ++gpyphy_reset(struct mii_softc *sc) ++{ ++ ++ /* ++ * GPY is a firmware-based PHY. BMCR software reset disrupts ++ * firmware operation (copper link never establishes, LEDs stay ++ * dark). Linux's GPY driver does not define .soft_reset either. ++ * ++ * Skip mii_phy_reset() and just ensure SGMII AN is enabled. ++ * mii_phy_setmedia() calls PHY_RESET before mii_phy_auto(), ++ * so this path is hit on every media change. ++ */ ++ gpyphy_sgmii_aneg(sc); ++} +diff --git a/sys/dev/mii/miidevs b/sys/dev/mii/miidevs +index 78d1dddba59..e28154eaef8 100644 +--- a/sys/dev/mii/miidevs ++++ b/sys/dev/mii/miidevs +@@ -61,6 +61,7 @@ oui INTEL 0x00aa00 Intel Corporation + oui JMICRON 0x00d831 JMicron Technologies + oui LEVEL1 0x00207b Level 1 + oui MARVELL 0x005043 Marvell Semiconductor ++oui MAXLINEAR 0x984fee MaxLinear Inc. + oui MICREL 0x0010a1 Micrel + oui MOTORCOMM 0x000000 Motorcomm + oui MYSON 0x00c0b4 Myson Technology +@@ -288,6 +289,18 @@ model MARVELL E1000_3 0x0003 Marvell 88E1000 Gigabit PHY + model MARVELL E1000_5 0x0005 Marvell 88E1000 Gigabit PHY + model MARVELL E1111 0x000c Marvell 88E1111 Gigabit PHY + ++/* MaxLinear GPY PHYs */ ++model MAXLINEAR GPY2xx 0x0000 MaxLinear GPY2xx 10/100/1000 PHY ++model MAXLINEAR GPY115 0x0030 MaxLinear GPY115 10/100/1000 PHY ++model MAXLINEAR GPY115C 0x0031 MaxLinear GPY115C 10/100/1000 PHY ++model MAXLINEAR GPY211 0x0020 MaxLinear GPY211 10/100/1000 PHY ++model MAXLINEAR GPY211C 0x0021 MaxLinear GPY211C 10/100/1000 PHY ++model MAXLINEAR GPY212C 0x0022 MaxLinear GPY212C 10/100/1000 PHY ++model MAXLINEAR GPY215C 0x0032 MaxLinear GPY215C 10/100/1000 PHY ++model MAXLINEAR GPY241 0x0024 MaxLinear GPY241 10/100/1000 PHY ++model MAXLINEAR GPY241BM 0x0028 MaxLinear GPY241BM 10/100/1000 PHY ++model MAXLINEAR GPY245 0x002c MaxLinear GPY245 10/100/1000 PHY ++ + /* Micrel PHYs */ + model MICREL KSZ8081 0x0016 Micrel KSZ8081 10/100 PHY + model MICREL KSZ9021 0x0021 Micrel KSZ9021 10/100/1000 PHY +diff --git a/sys/dev/random/random_harvestq.c b/sys/dev/random/random_harvestq.c +index 2a218970b85..f37f32e0f04 100644 +--- a/sys/dev/random/random_harvestq.c ++++ b/sys/dev/random/random_harvestq.c +@@ -387,6 +387,7 @@ static const char *random_source_descr[ENTROPYSOURCE] = { + [RANDOM_PURE_VMGENID] = "PURE_VMGENID", + [RANDOM_PURE_QUALCOMM] = "PURE_QUALCOMM", + [RANDOM_PURE_ARMV8] = "PURE_ARMV8", ++ [RANDOM_PURE_CAAM] = "PURE_CAAM", + /* "ENTROPYSOURCE" */ + }; + +diff --git a/sys/dev/uart/uart_dev_ns8250.c b/sys/dev/uart/uart_dev_ns8250.c +index ced3b44b574..ac760b064b2 100644 +--- a/sys/dev/uart/uart_dev_ns8250.c ++++ b/sys/dev/uart/uart_dev_ns8250.c +@@ -78,6 +78,30 @@ static int broken_txfifo = 0; + SYSCTL_INT(_hw, OID_AUTO, broken_txfifo, CTLFLAG_RWTUN, + &broken_txfifo, 0, "UART FIFO has QEMU emulation bug"); + ++/* ++ * To use early printf on NXP QorIQ (LS1046A, etc.), add to kernel config: ++ * ++ * options SOCDEV_PA=0x2000000 ++ * options EARLY_PRINTF=qoriq ++ * ++ * SOCDEV_PA must be 2MB-aligned (L2 block constraint in locore.S). ++ * The DUART is at SOCDEV_PA + 0x1c0500. ++ */ ++#if CHECK_EARLY_PRINTF(qoriq) ++extern uintptr_t socdev_va; ++static void ++uart_qoriq_early_putc(int c) ++{ ++ volatile uint8_t *base = (volatile uint8_t *)(socdev_va + 0x1c0500); ++ int limit = 10000; ++ ++ while ((base[5] & 0x20) == 0 && --limit > 0) ++ continue; ++ base[0] = c; ++} ++early_putc_t *early_putc = uart_qoriq_early_putc; ++#endif /* CHECK_EARLY_PRINTF(qoriq) */ ++ + /* + * Clear pending interrupts. THRE is cleared by reading IIR. Data + * that may have been received gets lost here. +diff --git a/sys/modules/dtb/freescale/Makefile b/sys/modules/dtb/freescale/Makefile +index 871c15330fe..22712ad7bb3 100644 +--- a/sys/modules/dtb/freescale/Makefile ++++ b/sys/modules/dtb/freescale/Makefile +@@ -1,8 +1,44 @@ + # All the dts files for Freescale (now NXP) systems we support. +-DTS= freescale/fsl-ls1028a-rdb.dts \ ++DTS= freescale/fsl-ls1012a-frdm.dts \ ++ freescale/fsl-ls1012a-frwy.dts \ ++ freescale/fsl-ls1012a-oxalis.dts \ ++ freescale/fsl-ls1012a-qds.dts \ ++ freescale/fsl-ls1012a-rdb.dts \ ++ freescale/fsl-ls1028a-kontron-kbox-a-230-ls.dts \ ++ freescale/fsl-ls1028a-kontron-sl28.dts \ ++ freescale/fsl-ls1028a-kontron-sl28-var1.dts \ ++ freescale/fsl-ls1028a-kontron-sl28-var2.dts \ ++ freescale/fsl-ls1028a-kontron-sl28-var3-ads2.dts \ ++ freescale/fsl-ls1028a-kontron-sl28-var4.dts \ ++ freescale/fsl-ls1028a-qds-13bb.dts \ ++ freescale/fsl-ls1028a-qds-65bb.dts \ ++ freescale/fsl-ls1028a-qds-7777.dts \ ++ freescale/fsl-ls1028a-qds-85bb.dts \ ++ freescale/fsl-ls1028a-qds-899b.dts \ ++ freescale/fsl-ls1028a-qds-9999.dts \ ++ freescale/fsl-ls1028a-qds.dts \ ++ freescale/fsl-ls1028a-rdb.dts \ ++ freescale/fsl-ls1043a-qds.dts \ ++ freescale/fsl-ls1043a-rdb.dts \ ++ freescale/fsl-ls1046a-frwy.dts \ ++ freescale/fsl-ls1046a-qds.dts \ ++ freescale/fsl-ls1046a-rdb.dts \ ++ freescale/fsl-ls1088a-qds.dts \ ++ freescale/fsl-ls1088a-rdb.dts \ ++ freescale/fsl-ls1088a-ten64.dts \ ++ freescale/fsl-ls2080a-qds.dts \ ++ freescale/fsl-ls2080a-rdb.dts \ ++ freescale/fsl-ls2080a-simu.dts \ ++ freescale/fsl-ls2081a-rdb.dts \ ++ freescale/fsl-ls2088a-qds.dts \ ++ freescale/fsl-ls2088a-rdb.dts \ ++ freescale/fsl-lx2160a-bluebox3.dts \ ++ freescale/fsl-lx2160a-bluebox3-rev-a.dts \ + freescale/fsl-lx2160a-clearfog-cx.dts \ + freescale/fsl-lx2160a-honeycomb.dts \ + freescale/fsl-lx2160a-qds.dts \ +- freescale/fsl-lx2160a-rdb.dts ++ freescale/fsl-lx2160a-rdb.dts \ ++ freescale/fsl-lx2162a-qds.dts \ ++ freescale/mono-gateway-dk.dts + + .include +diff --git a/sys/net/if_bridge.c b/sys/net/if_bridge.c +index 0f4ec01fb39..bae570386f7 100644 +--- a/sys/net/if_bridge.c ++++ b/sys/net/if_bridge.c +@@ -303,6 +303,10 @@ int bridge_rtable_prune_period = BRIDGE_RTABLE_PRUNE_PERIOD; + VNET_DEFINE_STATIC(uma_zone_t, bridge_rtnode_zone); + #define V_bridge_rtnode_zone VNET(bridge_rtnode_zone) + ++/* L2 flow offload hooks (set by auto_bridge.ko) */ ++bridge_l2flow_hook_t bridge_l2flow_hook; ++bridge_fdb_can_expire_hook_t bridge_fdb_can_expire_hook; ++ + static int bridge_clone_create(struct if_clone *, char *, size_t, + struct ifc_data *, struct ifnet **); + static int bridge_clone_destroy(struct if_clone *, struct ifnet *, uint32_t); +@@ -2528,6 +2532,9 @@ bridge_forward(struct bridge_softc *sc, struct bridge_iflist *sbif, + return; + } + ++ if (bridge_l2flow_hook != NULL) ++ bridge_l2flow_hook(ifp, m, src_if, dst_if); ++ + bridge_enqueue(sc, dst_if, m); + return; + +@@ -3110,8 +3117,16 @@ bridge_rtage(struct bridge_softc *sc) + + CK_LIST_FOREACH_SAFE(brt, &sc->sc_rtlist, brt_list, nbrt) { + if ((brt->brt_flags & IFBAF_TYPEMASK) == IFBAF_DYNAMIC) { +- if (time_uptime >= brt->brt_expire) ++ if (time_uptime >= brt->brt_expire) { ++ if (bridge_fdb_can_expire_hook != NULL && ++ bridge_fdb_can_expire_hook(brt->brt_addr, ++ sc->sc_ifp) == 0) { ++ brt->brt_expire = time_uptime + ++ sc->sc_brttimeout; ++ continue; ++ } + bridge_rtnode_destroy(sc, brt); ++ } + } + } + } +diff --git a/sys/net/if_bridgevar.h b/sys/net/if_bridgevar.h +index 511ca753858..72c6f4abbf3 100644 +--- a/sys/net/if_bridgevar.h ++++ b/sys/net/if_bridgevar.h +@@ -325,6 +325,18 @@ struct ifbpstpconf { + extern void (*bridge_dn_p)(struct mbuf *, struct ifnet *); + extern bool (*bridge_member_ifaddrs_p)(void); + ++/* ++ * L2 flow offload hooks — set by auto_bridge.ko, called from ++ * bridge_forward() and bridge_rtage() respectively. ++ */ ++typedef void (*bridge_l2flow_hook_t)(struct ifnet *bridge_ifp, ++ struct mbuf *m, struct ifnet *src_if, struct ifnet *dst_if); ++typedef int (*bridge_fdb_can_expire_hook_t)(const uint8_t *mac, ++ struct ifnet *bridge_ifp); ++ ++extern bridge_l2flow_hook_t bridge_l2flow_hook; ++extern bridge_fdb_can_expire_hook_t bridge_fdb_can_expire_hook; ++ + #endif /* _KERNEL */ + + #endif /* _NET_IF_BRIDGEVAR_H_ */ +diff --git a/sys/net/pfvar.h b/sys/net/pfvar.h +index 0f6e2e24022..0bddfb49087 100644 +--- a/sys/net/pfvar.h ++++ b/sys/net/pfvar.h +@@ -1198,6 +1198,28 @@ VNET_DECLARE(pfsync_defer_t *, pfsync_defer_ptr); + #define V_pfsync_defer_ptr VNET(pfsync_defer_ptr) + extern pfsync_detach_ifnet_t *pfsync_detach_ifnet_ptr; + ++/* ++ * pf_notify — offload state change notification (separate from pfsync). ++ * ++ * Lock context for callbacks: ++ * INSERT: PF_HASHROW_LOCK held, NET_EPOCH ++ * UPDATE: PF_RULES_RLOCK + PF_STATE_LOCK(s) held, NET_EPOCH ++ * DELETE: PF_HASHROW_LOCK held, NET_EPOCH ++ * ++ * Callbacks MUST NOT sleep, acquire PF_RULES_WLOCK, or re-enter the ++ * pf state machine. ++ */ ++typedef void pfnotify_insert_state_t(struct pf_kstate *); ++typedef void pfnotify_update_state_t(struct pf_kstate *); ++typedef void pfnotify_delete_state_t(struct pf_kstate *); ++ ++VNET_DECLARE(pfnotify_insert_state_t *, pfnotify_insert_state_ptr); ++#define V_pfnotify_insert_state_ptr VNET(pfnotify_insert_state_ptr) ++VNET_DECLARE(pfnotify_update_state_t *, pfnotify_update_state_ptr); ++#define V_pfnotify_update_state_ptr VNET(pfnotify_update_state_ptr) ++VNET_DECLARE(pfnotify_delete_state_t *, pfnotify_delete_state_ptr); ++#define V_pfnotify_delete_state_ptr VNET(pfnotify_delete_state_ptr) ++ + void pfsync_state_export_1301(struct pfsync_state_1301 *, + struct pf_kstate *); + void pfsync_state_export_1400(struct pfsync_state_1400 *, +diff --git a/sys/netpfil/pf/pf.c b/sys/netpfil/pf/pf.c +index c9b61f7b652..dac5ce76f33 100644 +--- a/sys/netpfil/pf/pf.c ++++ b/sys/netpfil/pf/pf.c +@@ -1670,6 +1670,8 @@ pf_state_insert(struct pfi_kkif *kif, struct pfi_kkif *orig_kif, + pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_INSERT], 1); + if (V_pfsync_insert_state_ptr != NULL) + V_pfsync_insert_state_ptr(s); ++ if (V_pfnotify_insert_state_ptr != NULL) ++ V_pfnotify_insert_state_ptr(s); + + /* Returns locked. */ + return (0); +@@ -2457,6 +2459,8 @@ pf_unlink_state(struct pf_kstate *s) + + if (V_pfsync_delete_state_ptr != NULL) + V_pfsync_delete_state_ptr(s); ++ if (V_pfnotify_delete_state_ptr != NULL) ++ V_pfnotify_delete_state_ptr(s); + + STATE_DEC_COUNTERS(s); + +@@ -8652,6 +8656,8 @@ pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, + if (s != NULL) { + if (V_pfsync_update_state_ptr != NULL) + V_pfsync_update_state_ptr(s); ++ if (V_pfnotify_update_state_ptr != NULL) ++ V_pfnotify_update_state_ptr(s); + r = s->rule.ptr; + a = s->anchor.ptr; + } +@@ -8717,6 +8723,8 @@ pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, + if (s != NULL) { + if (V_pfsync_update_state_ptr != NULL) + V_pfsync_update_state_ptr(s); ++ if (V_pfnotify_update_state_ptr != NULL) ++ V_pfnotify_update_state_ptr(s); + r = s->rule.ptr; + a = s->anchor.ptr; + } +@@ -8750,6 +8758,8 @@ pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, + if (action == PF_PASS) { + if (V_pfsync_update_state_ptr != NULL) + V_pfsync_update_state_ptr(s); ++ if (V_pfnotify_update_state_ptr != NULL) ++ V_pfnotify_update_state_ptr(s); + r = s->rule.ptr; + a = s->anchor.ptr; + } else if (s == NULL) { +@@ -8770,6 +8780,8 @@ pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, + if (action == PF_PASS) { + if (V_pfsync_update_state_ptr != NULL) + V_pfsync_update_state_ptr(s); ++ if (V_pfnotify_update_state_ptr != NULL) ++ V_pfnotify_update_state_ptr(s); + r = s->rule.ptr; + a = s->anchor.ptr; + } else if (s == NULL) +@@ -8792,6 +8804,8 @@ pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, + if (action == PF_PASS) { + if (V_pfsync_update_state_ptr != NULL) + V_pfsync_update_state_ptr(s); ++ if (V_pfnotify_update_state_ptr != NULL) ++ V_pfnotify_update_state_ptr(s); + r = s->rule.ptr; + a = s->anchor.ptr; + } else if (s == NULL) +@@ -9310,6 +9324,8 @@ pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb + if (action == PF_PASS) { + if (V_pfsync_update_state_ptr != NULL) + V_pfsync_update_state_ptr(s); ++ if (V_pfnotify_update_state_ptr != NULL) ++ V_pfnotify_update_state_ptr(s); + r = s->rule.ptr; + a = s->anchor.ptr; + } else if (s == NULL) { +@@ -9374,6 +9390,8 @@ pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb + if (action == PF_PASS) { + if (V_pfsync_update_state_ptr != NULL) + V_pfsync_update_state_ptr(s); ++ if (V_pfnotify_update_state_ptr != NULL) ++ V_pfnotify_update_state_ptr(s); + r = s->rule.ptr; + a = s->anchor.ptr; + } else if (s == NULL) +@@ -9404,6 +9422,8 @@ pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb + if (action == PF_PASS) { + if (V_pfsync_update_state_ptr != NULL) + V_pfsync_update_state_ptr(s); ++ if (V_pfnotify_update_state_ptr != NULL) ++ V_pfnotify_update_state_ptr(s); + r = s->rule.ptr; + a = s->anchor.ptr; + } else if (s == NULL) { +@@ -9431,6 +9451,8 @@ pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb + if (action == PF_PASS) { + if (V_pfsync_update_state_ptr != NULL) + V_pfsync_update_state_ptr(s); ++ if (V_pfnotify_update_state_ptr != NULL) ++ V_pfnotify_update_state_ptr(s); + r = s->rule.ptr; + a = s->anchor.ptr; + } else if (s == NULL) +@@ -9444,6 +9466,8 @@ pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb + if (action == PF_PASS) { + if (V_pfsync_update_state_ptr != NULL) + V_pfsync_update_state_ptr(s); ++ if (V_pfnotify_update_state_ptr != NULL) ++ V_pfnotify_update_state_ptr(s); + r = s->rule.ptr; + a = s->anchor.ptr; + } else if (s == NULL) +diff --git a/sys/netpfil/pf/pf_ioctl.c b/sys/netpfil/pf/pf_ioctl.c +index 88203411e3e..a003f8d3673 100644 +--- a/sys/netpfil/pf/pf_ioctl.c ++++ b/sys/netpfil/pf/pf_ioctl.c +@@ -304,6 +304,11 @@ VNET_DEFINE(pfsync_clear_states_t *, pfsync_clear_states_ptr); + VNET_DEFINE(pfsync_defer_t *, pfsync_defer_ptr); + pfsync_detach_ifnet_t *pfsync_detach_ifnet_ptr; + ++/* pf_notify */ ++VNET_DEFINE(pfnotify_insert_state_t *, pfnotify_insert_state_ptr); ++VNET_DEFINE(pfnotify_update_state_t *, pfnotify_update_state_ptr); ++VNET_DEFINE(pfnotify_delete_state_t *, pfnotify_delete_state_ptr); ++ + /* pflog */ + pflog_packet_t *pflog_packet_ptr = NULL; + +diff --git a/sys/sys/random.h b/sys/sys/random.h +index aa4457fc8c2..6ff4f163f32 100644 +--- a/sys/sys/random.h ++++ b/sys/sys/random.h +@@ -103,6 +103,7 @@ enum random_entropy_source { + RANDOM_PURE_VMGENID, + RANDOM_PURE_QUALCOMM, + RANDOM_PURE_ARMV8, ++ RANDOM_PURE_CAAM, + ENTROPYSOURCE + }; + _Static_assert(ENTROPYSOURCE <= 32, +diff --git a/sys/sys/systm.h b/sys/sys/systm.h +index 973a7604fe5..88cd70878b3 100644 +--- a/sys/sys/systm.h ++++ b/sys/sys/systm.h +@@ -212,6 +212,17 @@ critical_exit(void) + #ifdef EARLY_PRINTF + typedef void early_putc_t(int ch); + extern early_putc_t *early_putc; ++#define CHECK_EARLY_PRINTF(x) \ ++ __CONCAT(early_printf_, EARLY_PRINTF) == __CONCAT(early_printf_, x) ++#define early_printf_1 1 ++#define early_printf_mvebu 2 ++#define early_printf_ns8250 3 ++#define early_printf_pl011 4 ++#define early_printf_snps 5 ++#define early_printf_sbi 6 ++#define early_printf_qoriq 7 ++#else ++#define CHECK_EARLY_PRINTF(x) 0 + #endif + int kvprintf(char const *, void (*)(int, void*), void *, int, + __va_list) __printflike(1, 0); +-- +2.47.3 + diff --git a/README.md b/README.md new file mode 100644 index 0000000..b0b5f66 --- /dev/null +++ b/README.md @@ -0,0 +1,205 @@ +# Mono Gateway custom components for OPNsense + +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 +(LP5812 LED, EMC2302 fan, INA2xx power, SFP LED), FMan toolchain (fmlib, fmc, +dpa_app), and helper scripts for kernel image creation and deployment. + +## Build instructions + +All commands run on the build server (amd64 FreeBSD). + +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 cross-compiled kernel modules. + +### 1. Prerequisites + +``` +sudo pkg install -y git aarch64-binutils qemu-user-static +``` + +### 2. Set up `/build` + +All build paths assume the source tree is at `/build`. This directory must contain +`opnsense-build`, `opnsense-src`, and `opnsense-deps`. + +**Local development** (source tree lives on the build server): + +``` +# Clone into /build directly +sudo mkdir /build && sudo chown $(whoami) /build +cd /build +git clone https://github.com/opnsense/tools.git opnsense-build +git clone https://github.com/opnsense/src.git opnsense-src +# opnsense-deps is this repository + +# Copy the GATEWAY device config into the build system +cp /build/opnsense-deps/config/GATEWAY.conf /build/opnsense-build/device/ +``` + +**Remote source via NFS** (source tree lives on another machine): + +``` +# Mount the remote share, then expose it at /build via nullfs +echo '/path/to/nfs/mount /mnt/remote nfs rw 0 0' | sudo tee -a /etc/fstab +sudo mount /mnt/remote + +sudo mkdir /build +echo '/mnt/remote /build nullfs rw,late 0 0' | sudo tee -a /etc/fstab +sudo mount /build + +# Copy the GATEWAY device config into the build system +cp /build/opnsense-deps/config/GATEWAY.conf /build/opnsense-build/device/ +``` + +Using nullfs (rather than a symlink) ensures `pwd` reports `/build/...` 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. + +``` +VERSION=26.1.1 # use latest available on the mirror + +sudo make -C /build/opnsense-build prefetch-base DEVICE=GATEWAY SETTINGS=26.1 TOOLSDIR=/build/opnsense-build 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 /build/opnsense-build prefetch-packages DEVICE=GATEWAY SETTINGS=26.1 TOOLSDIR=/build/opnsense-build MIRRORS=https://opnsense-update.walker.earth VERSION=$VERSION +``` + +This skips `make base`, `make ports`, `make core`, and `make plugins` (no cross-compilation needed). + +**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. Build kernel + +``` +sudo make -C /build/opnsense-build kernel DEVICE=GATEWAY SETTINGS=26.1 TOOLSDIR=/build/opnsense-build SRCDIR=/build/opnsense-src +``` + +The OPNsense build system defaults `SRCDIR` to `/usr/src`; since our source tree +is named `opnsense-src`, the explicit `SRCDIR=` is required on all make targets +that touch the kernel source (kernel, arm). + +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/build/opnsense-src/arm64.aarch64/sys/GATEWAY +``` +### 5. Install libxml2 into cross-compilation sysroot + +Required by opnsense-deps (fmc links against libxml2). + +``` +fetch -o /tmp/libxml2.pkg 'https://pkg.FreeBSD.org/FreeBSD:14:aarch64/latest/All/Hashed/libxml2-2.15.1_1~82f6f2bc79.pkg' +mkdir -p /tmp/libxml2-extract && cd /tmp/libxml2-extract && tar xf /tmp/libxml2.pkg + +SYSROOT=/usr/obj/build/opnsense-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/ +``` + +### 6. Build custom modules and tools + +``` +make -C /build/opnsense-deps -j24 all +``` + +### 7. Assemble eMMC image + +``` +sudo make -C /build/opnsense-build arm-5G DEVICE=GATEWAY SETTINGS=26.1 TOOLSDIR=/build/opnsense-build SRCDIR=/build/opnsense-src +``` + +Output: `/usr/local/opnsense/build/26.1/aarch64/images/OPNsense-*-arm-aarch64-GATEWAY.img` + +## Development + +The kernel source tree (`opnsense-src`) is patched from upstream OPNsense via +`OPNsense-26.1-aarch64-GATEWAY.patch`. To work on kernel changes: + +1. Clone a fresh `opnsense-src` and apply the patch: + ``` + git clone https://github.com/opnsense/src.git opnsense-src + cd opnsense-src + git checkout stable/26.1 + git apply ../opnsense-deps/OPNsense-26.1-aarch64-GATEWAY.patch + git checkout -b mono-gateway + git commit -am "Apply Mono Gateway patch" + ``` + +2. Make your changes, build, test, and commit as needed. + +3. When done, regenerate the patch. Use `git format-patch` to produce a patch + with a proper commit header (author, date, subject, diffstat): + ``` + git format-patch -1 mono-gateway --stdout > ../opnsense-deps/OPNsense-26.1-aarch64-GATEWAY.patch + ``` + This generates a patch from the single squashed commit on `mono-gateway`. + If you have multiple commits on top of `stable/26.1`, squash them first: + ``` + git reset --soft stable/26.1 + git commit -m "Port Mono Gateway (NXP LS1046A) to OPNsense's FreeBSD 14.3" + git format-patch -1 --stdout > ../opnsense-deps/OPNsense-26.1-aarch64-GATEWAY.patch + ``` + +## Local / Test Deployment + +Boot the gateway into Recovery Linux. Assign an IP since Recovery Linux has no DHCP (adjust IPs to match your network): + +``` +ip link set eth3 up +ip addr add 10.0.0.69/24 dev eth3 +ip route add default via 10.0.0.1 dev eth3 +``` + +On your build server, serve the image directory over HTTP: + +``` +python3 -m http.server +``` + +Then on the gateway, fetch and flash in one go (the image is too large to store locally first): + +``` +curl http://10.0.0.70:8000/OPNsense-GATEWAY.img | dd of=/dev/mmcblk0 bs=1M +``` + +**Warning:** This overwrites the entire eMMC, including any firmware stored there. + +## Booting into OPNsense + +The board's default boot command loads Recovery Linux. To boot OPNsense instead, +interrupt U-Boot's autoboot (press any key during the countdown) and configure +a persistent `opnsense` boot environment: + +``` +=> setenv opnsense "load mmc 0:1 ${kernel_addr_r} kernel.img; load mmc 0:1 ${fdt_addr_r} dtb/mono-gateway-dk.dtb; booti 0x82000000 - 0x88000000" +=> setenv bootcmd_bak ${bootcmd} +=> setenv bootcmd "run opnsense || run recovery" +=> saveenv +=> reset +``` + +This saves the original boot command as `bootcmd_bak`, then sets `bootcmd` to +try OPNsense first and fall back to Recovery Linux if the kernel image is missing. +After `saveenv` and `reset`, the board will automatically boot into OPNsense on +every subsequent power-on. + +> ## Disclaimer +> Many of the files in this repository, including the large kernel patch, were ported from Linux sources provided by NXP (originally targeting Linux kernel 5.4). Due to the sheer scope of the porting effort, Claude Opus 4.6 was used to assist with the adaptation of this code to FreeBSD. As such, this project should be considered **highly experimental** and is **not fit for production use** until thorough reviews and testing have been performed by the wider community. \ No newline at end of file diff --git a/config/GATEWAY.conf b/config/GATEWAY.conf new file mode 100644 index 0000000..a52091b --- /dev/null +++ b/config/GATEWAY.conf @@ -0,0 +1,114 @@ +# Mono Gateway Development Kit (NXP LS1046A) +# https://mono.vision +# +# Boot: U-Boot booti (NOT EFI -- loader.efi broken on this SoC) +# Console: serial 115200 (headless, no video output) +# U-Boot lives on QSPI NOR -- not installed from SD card + +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" +# No PRODUCT_UEFI -- we boot via U-Boot booti, not EFI + +# Artifacts directory (custom board modules, tools, configs) +MONO_GW_DEPS="${MONO_GW_DEPS:-${TOOLSDIR%/*}/opnsense-deps/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. + + local KERNEL_ELF="${STAGEDIR}/boot/kernel/kernel" + + # Convert ELF kernel to ARM64 Image format for U-Boot booti + sh "${TOOLSDIR%/*}/opnsense-deps/mk-kernel-img.sh" \ + "${KERNEL_ELF}" "${STAGEDIR}/boot/msdos/kernel.img" + + # Copy device tree binary + mkdir -p ${STAGEDIR}/boot/msdos/dtb + cp ${STAGEDIR}/boot/dtb/freescale/mono-gateway-dk.dtb \ + ${STAGEDIR}/boot/msdos/dtb/ + + # rc.conf.local must be written here (not in arm_hook) because + # setup_xbase() deletes rc.conf.local after arm_hook runs. + local MONO_GW_RCD="${TOOLSDIR%/*}/opnsense-deps/rc.d" + if [ -f "${MONO_GW_RCD}/rc.conf.local" ]; then + cat "${MONO_GW_RCD}/rc.conf.local" >> \ + "${STAGEDIR}/etc/rc.conf.local" + fi +} + +arm_hook() +{ + local STAGEDIR=${1} + + # The generic arm_hook (extras.conf) already ran and set + # primaryconsole=video. Fix it: this board has no video. + sed -i '' \ + 's|video|serial|' \ + ${STAGEDIR}${CONFIG_XML} + sed -i '' '//d' ${STAGEDIR}${CONFIG_XML} + + # Headless serial only (generic set -D for dual console) + echo "-S${PRODUCT_COMSPEED} -h" > ${STAGEDIR}/boot.config + + # Serial console: auto-detect terminal size on login + echo "resizewin" >> ${STAGEDIR}/root/.profile + + # --- Custom kernel modules --- + for mod in cdx auto_bridge pf_notify fci sfpled lp5812 \ + emc2302 ina2xx; do + if [ -f "${MONO_GW_DEPS}/${mod}.ko" ]; then + cp "${MONO_GW_DEPS}/${mod}.ko" \ + "${STAGEDIR}/boot/modules/" + fi + done + + # --- Userspace tools --- + for bin in cmm cmmctl dpa_app fmc fand; do + if [ -f "${MONO_GW_DEPS}/${bin}" ]; then + cp "${MONO_GW_DEPS}/${bin}" \ + "${STAGEDIR}/usr/local/sbin/" + chmod 755 "${STAGEDIR}/usr/local/sbin/${bin}" + fi + done + + # --- PCD/CDX configuration --- + local MONO_GW_CONFIG="${TOOLSDIR%/*}/opnsense-deps/config" + if [ -d "${MONO_GW_CONFIG}" ]; then + cp "${MONO_GW_CONFIG}/cdx_cfg.xml" "${STAGEDIR}/etc/" + cp "${MONO_GW_CONFIG}/cdx_pcd.xml" "${STAGEDIR}/etc/" + cp "${MONO_GW_CONFIG}/cdx_sp.xml" "${STAGEDIR}/etc/" + mkdir -p "${STAGEDIR}/etc/fmc/config" + cp "${MONO_GW_CONFIG}/hxs_pdl_v3.xml" \ + "${STAGEDIR}/etc/fmc/config/" + fi + + # --- rc.d boot scripts --- + local MONO_GW_RCD="${TOOLSDIR%/*}/opnsense-deps/rc.d" + mkdir -p "${STAGEDIR}/usr/local/etc/rc.d" + for script in cmm fand; do + if [ -f "${MONO_GW_RCD}/${script}" ]; then + cp "${MONO_GW_RCD}/${script}" \ + "${STAGEDIR}/usr/local/etc/rc.d/" + chmod 755 \ + "${STAGEDIR}/usr/local/etc/rc.d/${script}" + fi + done + + # --- rc.syshook early script (kernel module loading) --- + # OPNsense ignores FreeBSD's kld rc.d service and rcorder + # BEFORE:NETWORKING. Use rc.syshook.d/early/ to load modules + # before interfaces come up (cdx calls dpa_app internally). + mkdir -p "${STAGEDIR}/usr/local/etc/rc.syshook.d/early" + if [ -f "${MONO_GW_RCD}/02-mono-modules" ]; then + cp "${MONO_GW_RCD}/02-mono-modules" \ + "${STAGEDIR}/usr/local/etc/rc.syshook.d/early/" + chmod 755 \ + "${STAGEDIR}/usr/local/etc/rc.syshook.d/early/02-mono-modules" + fi +} diff --git a/config/cdx_cfg.xml b/config/cdx_cfg.xml new file mode 100644 index 0000000..6243430 --- /dev/null +++ b/config/cdx_cfg.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/config/cdx_pcd.xml b/config/cdx_pcd.xml new file mode 100644 index 0000000..8d6b26c --- /dev/null +++ b/config/cdx_pcd.xml @@ -0,0 +1,525 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/cdx_sp.xml b/config/cdx_sp.xml new file mode 100644 index 0000000..82422f1 --- /dev/null +++ b/config/cdx_sp.xml @@ -0,0 +1,194 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/hxs_pdl_v3.xml b/config/hxs_pdl_v3.xml new file mode 100644 index 0000000..a3d311a --- /dev/null +++ b/config/hxs_pdl_v3.xml @@ -0,0 +1,1753 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dist/.keep b/dist/.keep new file mode 100644 index 0000000..e69de29 diff --git a/drivers/emc2302/Makefile b/drivers/emc2302/Makefile new file mode 100644 index 0000000..2bb8aca --- /dev/null +++ b/drivers/emc2302/Makefile @@ -0,0 +1,17 @@ +# Microchip EMC2301/2302/2303/2305 Fan Controller kernel module for FreeBSD +# +# Build: +# make -C /build/opnsense-deps/drivers/emc2302 \ +# KERNBUILDDIR=/usr/obj/build/opnsense-src/arm64.aarch64/sys/MONO-GATEWAY \ +# MACHINE=arm64 MACHINE_ARCH=aarch64 CC=cc LD=ld.lld +# +# Copyright 2026 Mono Technologies Inc. +# SPDX-License-Identifier: BSD-2-Clause + +SYSDIR?= ${.CURDIR}/../../../opnsense-src/sys + +KMOD= emc2302 +SRCS= emc2302.c +SRCS+= opt_platform.h device_if.h bus_if.h iicbus_if.h ofw_bus_if.h + +.include diff --git a/drivers/emc2302/emc2302.c b/drivers/emc2302/emc2302.c new file mode 100644 index 0000000..1518af4 --- /dev/null +++ b/drivers/emc2302/emc2302.c @@ -0,0 +1,433 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Mono Technologies Inc. + * + * Microchip EMC2301/2302/2303/2305 RPM-based PWM fan controller driver. + * Provides per-channel sysctl nodes for PWM duty cycle (RW), + * tachometer RPM (RO), and drive fault status (RO). + * + * Based on Linux hwmon/emc2305.c by Nvidia. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +/* Identification registers */ +#define EMC2305_REG_VENDOR 0xFE +#define EMC2305_REG_PRODUCT_ID 0xFD +#define EMC2305_VENDOR_MICROCHIP 0x5D + +/* Product IDs */ +#define EMC2305_PID_2305 0x34 /* 5 channels */ +#define EMC2305_PID_2303 0x35 /* 3 channels */ +#define EMC2305_PID_2302 0x36 /* 2 channels */ +#define EMC2305_PID_2301 0x37 /* 1 channel */ + +/* Global configuration registers */ +#define EMC2305_REG_DRIVE_FAIL 0x27 +#define EMC2305_REG_POLARITY 0x2A +#define EMC2305_REG_OUTPUT_TYPE 0x2B + +/* Per-channel registers (n = 0..4) */ +#define EMC2305_REG_FAN_DRIVE(n) (0x30 + 0x10 * (n)) +#define EMC2305_REG_FAN_MIN_DRIVE(n) (0x38 + 0x10 * (n)) +#define EMC2305_REG_FAN_TACH(n) (0x3E + 0x10 * (n)) + +/* RPM calculation constants (from datasheet) */ +#define EMC2305_RPM_FACTOR 3932160 +#define EMC2305_TACH_SHIFT 3 /* lower 3 bits unused */ +#define EMC2305_TACH_MULTIPLIER 2 +#define EMC2305_RPM_MIN 480 + +#define EMC2305_MAX_FANS 5 + +struct emc2302_softc { + device_t dev; + int nfans; + uint8_t product_id; + struct sysctl_ctx_list sysctl_ctx; +}; + +/* ================================================================ + * I2C register helpers + * ================================================================ */ + +static int +emc2302_read8(device_t dev, uint8_t reg, uint8_t *val) +{ + + return (iicdev_readfrom(dev, reg, val, 1, IIC_WAIT)); +} + +static int +emc2302_write8(device_t dev, uint8_t reg, uint8_t val) +{ + + return (iicdev_writeto(dev, reg, &val, 1, IIC_WAIT)); +} + +static int +emc2302_read16(device_t dev, uint8_t reg, uint16_t *val) +{ + uint8_t buf[2]; + int error; + + error = iicdev_readfrom(dev, reg, buf, 2, IIC_WAIT); + if (error != 0) + return (error); + *val = (buf[0] << 8) | buf[1]; + return (0); +} + +/* ================================================================ + * Hardware read helpers + * ================================================================ */ + +static int +emc2302_read_rpm(struct emc2302_softc *sc, int ch, int *rpm) +{ + uint16_t raw; + uint32_t count; + int error; + + error = emc2302_read16(sc->dev, EMC2305_REG_FAN_TACH(ch), &raw); + if (error != 0) + return (error); + + count = raw >> EMC2305_TACH_SHIFT; + if (count == 0) { + *rpm = 0; + return (0); + } + + *rpm = (EMC2305_RPM_FACTOR / count) * EMC2305_TACH_MULTIPLIER; + if (*rpm <= EMC2305_RPM_MIN) + *rpm = 0; + + return (0); +} + +/* ================================================================ + * Sysctl handlers + * ================================================================ */ + +static int +emc2302_sysctl_pwm(SYSCTL_HANDLER_ARGS) +{ + struct emc2302_softc *sc = arg1; + int ch = arg2; + uint8_t reg_val; + int val, error; + + error = emc2302_read8(sc->dev, EMC2305_REG_FAN_DRIVE(ch), ®_val); + if (error != 0) + return (EIO); + val = reg_val; + + error = sysctl_handle_int(oidp, &val, 0, req); + if (error != 0 || req->newptr == NULL) + return (error); + + if (val < 0) + val = 0; + if (val > 255) + val = 255; + + error = emc2302_write8(sc->dev, EMC2305_REG_FAN_DRIVE(ch), + (uint8_t)val); + if (error != 0) + return (EIO); + + return (0); +} + +static int +emc2302_sysctl_rpm(SYSCTL_HANDLER_ARGS) +{ + struct emc2302_softc *sc = arg1; + int ch = arg2; + int val, error; + + if (req->newptr != NULL) + return (EINVAL); + + error = emc2302_read_rpm(sc, ch, &val); + if (error != 0) + return (EIO); + + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +emc2302_sysctl_fault(SYSCTL_HANDLER_ARGS) +{ + struct emc2302_softc *sc = arg1; + int ch = arg2; + uint8_t status; + int val, error; + + if (req->newptr != NULL) + return (EINVAL); + + error = emc2302_read8(sc->dev, EMC2305_REG_DRIVE_FAIL, &status); + if (error != 0) + return (EIO); + + val = (status >> ch) & 1; + + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +/* ================================================================ + * DT child node parsing + * ================================================================ */ + +static void +emc2302_parse_dt(struct emc2302_softc *sc) +{ + phandle_t node, child; + uint32_t reg, pwm_args[3]; + uint8_t polarity, output_type; + int i; + + node = ofw_bus_get_node(sc->dev); + if (node == 0) + return; + + polarity = 0; + output_type = 0; + + for (child = OF_child(node); child != 0; child = OF_peer(child)) { + if (OF_getencprop(child, "reg", ®, sizeof(reg)) <= 0) + continue; + if ((int)reg >= sc->nfans) + continue; + + /* Parse pwms = <&ref freq polarity output_type> */ + if (OF_getencprop(child, "pwms", pwm_args, + sizeof(pwm_args)) >= (int)(3 * sizeof(uint32_t))) { + /* pwm_args[0] = phandle (skip) */ + /* pwm_args[1] = polarity */ + if (pwm_args[1]) + polarity |= (1 << reg); + /* pwm_args[2] = output type (push-pull) */ + if (pwm_args[2]) + output_type |= (1 << reg); + } + } + + /* Write polarity and output type registers */ + emc2302_write8(sc->dev, EMC2305_REG_POLARITY, polarity); + emc2302_write8(sc->dev, EMC2305_REG_OUTPUT_TYPE, output_type); + + /* Set minimum PWM per channel from DT if specified */ + for (child = OF_child(node); child != 0; child = OF_peer(child)) { + uint32_t min_pwm; + + if (OF_getencprop(child, "reg", ®, sizeof(reg)) <= 0) + continue; + if ((int)reg >= sc->nfans) + continue; + if (OF_getencprop(child, "pwm-min", &min_pwm, + sizeof(min_pwm)) > 0) { + if (min_pwm > 255) + min_pwm = 255; + emc2302_write8(sc->dev, + EMC2305_REG_FAN_MIN_DRIVE(reg), (uint8_t)min_pwm); + } + } + + /* Log per-channel labels */ + for (child = OF_child(node); child != 0; child = OF_peer(child)) { + char label[64]; + + if (OF_getencprop(child, "reg", ®, sizeof(reg)) <= 0) + continue; + if ((int)reg >= sc->nfans) + continue; + if (OF_getprop(child, "label", label, sizeof(label)) > 0) { + label[sizeof(label) - 1] = '\0'; + device_printf(sc->dev, "fan%u: %s\n", reg, label); + } + } + + i = 0; + for (child = OF_child(node); child != 0; child = OF_peer(child)) + i++; + if (i > 0) + device_printf(sc->dev, "polarity=0x%02x output=0x%02x\n", + polarity, output_type); +} + +/* ================================================================ + * Probe / Attach / Detach + * ================================================================ */ + +static struct ofw_compat_data compat_data[] = { + { "microchip,emc2305", EMC2305_PID_2305 }, + { "microchip,emc2303", EMC2305_PID_2303 }, + { "microchip,emc2302", EMC2305_PID_2302 }, + { "microchip,emc2301", EMC2305_PID_2301 }, + { NULL, 0 }, +}; + +static const char * +emc2302_chip_name(uint8_t pid) +{ + + switch (pid) { + case EMC2305_PID_2305: return ("EMC2305"); + case EMC2305_PID_2303: return ("EMC2303"); + case EMC2305_PID_2302: return ("EMC2302"); + case EMC2305_PID_2301: return ("EMC2301"); + default: return ("EMC23xx"); + } +} + +static int +emc2302_nfans_from_pid(uint8_t pid) +{ + + switch (pid) { + case EMC2305_PID_2305: return (5); + case EMC2305_PID_2303: return (3); + case EMC2305_PID_2302: return (2); + case EMC2305_PID_2301: return (1); + default: return (0); + } +} + +static int +emc2302_probe(device_t dev) +{ + const struct ofw_compat_data *cd; + char desc[80]; + + if (!ofw_bus_status_okay(dev)) + return (ENXIO); + + cd = ofw_bus_search_compatible(dev, compat_data); + if (cd->ocd_data == 0) + return (ENXIO); + + snprintf(desc, sizeof(desc), "%s Fan Controller", + emc2302_chip_name((uint8_t)cd->ocd_data)); + device_set_desc_copy(dev, desc); + + return (BUS_PROBE_DEFAULT); +} + +static int +emc2302_attach(device_t dev) +{ + struct emc2302_softc *sc; + struct sysctl_oid *tree, *fan_oid; + uint8_t vendor, pid; + char fan_name[8]; + int error, i; + + sc = device_get_softc(dev); + sc->dev = dev; + + /* Verify vendor ID */ + error = emc2302_read8(dev, EMC2305_REG_VENDOR, &vendor); + if (error != 0) { + device_printf(dev, "failed to read vendor register\n"); + return (ENXIO); + } + if (vendor != EMC2305_VENDOR_MICROCHIP) { + device_printf(dev, "unexpected vendor ID: 0x%02x\n", vendor); + return (ENXIO); + } + + /* Read product ID and determine fan count */ + error = emc2302_read8(dev, EMC2305_REG_PRODUCT_ID, &pid); + if (error != 0) { + device_printf(dev, "failed to read product ID\n"); + return (ENXIO); + } + sc->product_id = pid; + sc->nfans = emc2302_nfans_from_pid(pid); + if (sc->nfans == 0) { + device_printf(dev, "unknown product ID: 0x%02x\n", pid); + return (ENXIO); + } + + device_printf(dev, "%s (product 0x%02x), %d fan channel%s\n", + emc2302_chip_name(pid), pid, sc->nfans, + sc->nfans > 1 ? "s" : ""); + + /* Parse DT child nodes for polarity, output type, min PWM */ + emc2302_parse_dt(sc); + + /* Create sysctl tree */ + sysctl_ctx_init(&sc->sysctl_ctx); + tree = device_get_sysctl_tree(dev); + + for (i = 0; i < sc->nfans; i++) { + snprintf(fan_name, sizeof(fan_name), "fan%d", i); + + fan_oid = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(tree), OID_AUTO, fan_name, + CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "Fan channel"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(fan_oid), OID_AUTO, "pwm", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, i, emc2302_sysctl_pwm, "I", + "PWM duty cycle (0-255)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(fan_oid), OID_AUTO, "rpm", + CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, i, emc2302_sysctl_rpm, "I", + "Fan speed (RPM)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(fan_oid), OID_AUTO, "fault", + CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, i, emc2302_sysctl_fault, "I", + "Drive failure (0=ok, 1=fault)"); + } + + return (0); +} + +static int +emc2302_detach(device_t dev) +{ + struct emc2302_softc *sc; + + sc = device_get_softc(dev); + sysctl_ctx_free(&sc->sysctl_ctx); + return (0); +} + +static device_method_t emc2302_methods[] = { + DEVMETHOD(device_probe, emc2302_probe), + DEVMETHOD(device_attach, emc2302_attach), + DEVMETHOD(device_detach, emc2302_detach), + DEVMETHOD_END +}; + +static driver_t emc2302_driver = { + "emc2302", + emc2302_methods, + sizeof(struct emc2302_softc), +}; + +DRIVER_MODULE(emc2302, iicbus, emc2302_driver, NULL, NULL); +MODULE_VERSION(emc2302, 1); +MODULE_DEPEND(emc2302, iicbus, IICBUS_MODVER, IICBUS_MODVER, IICBUS_MODVER); +IICBUS_FDT_PNP_INFO(compat_data); diff --git a/drivers/fand/Makefile b/drivers/fand/Makefile new file mode 100644 index 0000000..aca5d41 --- /dev/null +++ b/drivers/fand/Makefile @@ -0,0 +1,29 @@ +# Fan control daemon for Mono Gateway +# +# Build: +# mkdir -p /tmp/fand-build && cd /tmp/fand-build +# make -f /build/opnsense-deps/drivers/fand/Makefile +# +# Copyright 2026 Mono Technologies Inc. +# SPDX-License-Identifier: BSD-2-Clause + +SYSROOT?= /usr/obj/build/opnsense-src/arm64.aarch64/tmp +CC?= cc +TARGET?= --target=aarch64-unknown-freebsd14.3 + +CFLAGS= -O2 -pipe -Wall --sysroot=${SYSROOT} ${TARGET} +LDFLAGS= ${TARGET} --sysroot=${SYSROOT} + +SRCDIR?= ${MAKEFILE:H} + +PROG= fand + +all: ${PROG} + +${PROG}: ${SRCDIR}/fand.c + ${CC} ${CFLAGS} ${LDFLAGS} -o ${PROG} ${SRCDIR}/fand.c + +clean: + rm -f ${PROG} + +.PHONY: all clean diff --git a/drivers/fand/fand.c b/drivers/fand/fand.c new file mode 100644 index 0000000..d78679e --- /dev/null +++ b/drivers/fand/fand.c @@ -0,0 +1,158 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Mono Technologies Inc. + * + * Fan control daemon for the Mono Gateway. + * Linearly scales PWM from 20% at 40°C to 100% at 80°C + * using the SoC TMU temperature and EMC2302 fan controller. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include + +/* Temperature thresholds (millidegrees C) */ +#define TEMP_LOW_MC 40000 /* 40°C — minimum fan speed */ +#define TEMP_HIGH_MC 80000 /* 80°C — maximum fan speed */ + +/* PWM range (0-255) */ +#define PWM_MIN 51 /* 20% of 255 */ +#define PWM_MAX 255 /* 100% */ + +/* Polling interval */ +#define POLL_INTERVAL 2 /* seconds */ + +/* Sysctl names */ +#define SYSCTL_TEMP "hw.temperature.core-cluster" +#define SYSCTL_FAN0_PWM "dev.emc2302.0.fan0.pwm" +#define SYSCTL_FAN1_PWM "dev.emc2302.0.fan1.pwm" + +static volatile sig_atomic_t running = 1; + +static void +signal_handler(int sig __unused) +{ + + running = 0; +} + +static int +read_temp_mc(void) +{ + int val; + size_t len; + + len = sizeof(val); + if (sysctlbyname(SYSCTL_TEMP, &val, &len, NULL, 0) != 0) + return (-1); + + /* Convert decikelvin to millidegrees C */ + return ((val - 2731) * 100); +} + +static int +set_pwm(const char *name, int pwm) +{ + + return (sysctlbyname(name, NULL, NULL, &pwm, sizeof(pwm))); +} + +static int +compute_pwm(int temp_mc) +{ + + if (temp_mc <= TEMP_LOW_MC) + return (PWM_MIN); + if (temp_mc >= TEMP_HIGH_MC) + return (PWM_MAX); + + return (PWM_MIN + (temp_mc - TEMP_LOW_MC) * + (PWM_MAX - PWM_MIN) / (TEMP_HIGH_MC - TEMP_LOW_MC)); +} + +static void +set_fans(int pwm) +{ + + set_pwm(SYSCTL_FAN0_PWM, pwm); + set_pwm(SYSCTL_FAN1_PWM, pwm); +} + +static void +usage(void) +{ + + fprintf(stderr, "usage: fand [-d]\n"); + fprintf(stderr, " -d daemonize\n"); + exit(1); +} + +int +main(int argc, char *argv[]) +{ + int dflag, ch, temp_mc, pwm, last_pwm; + + dflag = 0; + while ((ch = getopt(argc, argv, "d")) != -1) { + switch (ch) { + case 'd': + dflag = 1; + break; + default: + usage(); + } + } + + /* Verify sysctls exist */ + temp_mc = read_temp_mc(); + if (temp_mc < 0) + errx(1, "cannot read %s", SYSCTL_TEMP); + if (set_pwm(SYSCTL_FAN0_PWM, PWM_MIN) != 0) + errx(1, "cannot write %s", SYSCTL_FAN0_PWM); + if (set_pwm(SYSCTL_FAN1_PWM, PWM_MIN) != 0) + errx(1, "cannot write %s", SYSCTL_FAN1_PWM); + + if (dflag && daemon(0, 0) != 0) + err(1, "daemon"); + + signal(SIGTERM, signal_handler); + signal(SIGINT, signal_handler); + + last_pwm = -1; + + while (running) { + temp_mc = read_temp_mc(); + if (temp_mc < 0) { + /* Sensor failure — full speed for safety */ + set_fans(PWM_MAX); + last_pwm = PWM_MAX; + sleep(POLL_INTERVAL); + continue; + } + + pwm = compute_pwm(temp_mc); + + if (last_pwm < 0 || abs(pwm - last_pwm) >= 5) { + fprintf(stderr, "fand: %d.%d°C -> PWM %d (%d%%)\n", + temp_mc / 1000, (temp_mc % 1000) / 100, + pwm, pwm * 100 / 255); + set_fans(pwm); + last_pwm = pwm; + } + + sleep(POLL_INTERVAL); + } + + /* Safety: full speed on exit */ + fprintf(stderr, "fand: shutting down, fans to 100%%\n"); + set_fans(PWM_MAX); + + return (0); +} diff --git a/drivers/fand/fand.rc b/drivers/fand/fand.rc new file mode 100644 index 0000000..9eacc2c --- /dev/null +++ b/drivers/fand/fand.rc @@ -0,0 +1,16 @@ +#!/bin/sh + +# PROVIDE: fand +# REQUIRE: DAEMON +# KEYWORD: shutdown + +. /etc/rc.subr + +name="fand" +desc="Fan control daemon" +rcvar="fand_enable" +command="/usr/local/sbin/${name}" +command_args="-d" + +load_rc_config $name +run_rc_command "$1" diff --git a/drivers/ina2xx/Makefile b/drivers/ina2xx/Makefile new file mode 100644 index 0000000..cd3de39 --- /dev/null +++ b/drivers/ina2xx/Makefile @@ -0,0 +1,17 @@ +# TI INA2xx Power Monitor kernel module for FreeBSD +# +# Build: +# make -C /build/opnsense-deps/drivers/ina2xx \ +# KERNBUILDDIR=/usr/obj/build/opnsense-src/arm64.aarch64/sys/MONO-GATEWAY \ +# MACHINE=arm64 MACHINE_ARCH=aarch64 CC=cc LD=ld.lld +# +# Copyright 2026 Mono Technologies Inc. +# SPDX-License-Identifier: BSD-2-Clause + +SYSDIR?= ${.CURDIR}/../../../opnsense-src/sys + +KMOD= ina2xx +SRCS= ina2xx.c +SRCS+= opt_platform.h device_if.h bus_if.h iicbus_if.h ofw_bus_if.h + +.include diff --git a/drivers/ina2xx/ina2xx.c b/drivers/ina2xx/ina2xx.c new file mode 100644 index 0000000..a1b853d --- /dev/null +++ b/drivers/ina2xx/ina2xx.c @@ -0,0 +1,395 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Mono Technologies Inc. + * + * Texas Instruments INA219/INA226/INA234 I2C power monitor driver. + * 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. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +/* 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 + +/* Default shunt resistance: 10 mOhm = 10000 uOhm */ +#define INA2XX_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; +}; + +static const struct ina2xx_config ina2xx_configs[] = { + [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, + }, + [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, + }, + [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, + }, +}; + +struct ina2xx_softc { + device_t dev; + enum ina2xx_chip chip; + const struct ina2xx_config *config; + uint32_t rshunt; /* shunt resistance, uOhm */ + long current_lsb_uA; + long power_lsb_uW; + struct sysctl_ctx_list sysctl_ctx; + char label[64]; +}; + +/* ================================================================ + * I2C register helpers — 16-bit big-endian + * ================================================================ */ + +static int +ina2xx_read_reg(device_t dev, uint8_t reg, uint16_t *val) +{ + uint8_t buf[2]; + int error; + + error = iicdev_readfrom(dev, reg, buf, 2, IIC_WAIT); + if (error != 0) + return (error); + *val = (buf[0] << 8) | buf[1]; + return (0); +} + +static int +ina2xx_write_reg(device_t dev, uint8_t reg, uint16_t val) +{ + uint8_t buf[2]; + + buf[0] = (val >> 8) & 0xFF; + buf[1] = val & 0xFF; + return (iicdev_writeto(dev, reg, buf, 2, IIC_WAIT)); +} + +/* ================================================================ + * Measurement value conversion (matches Linux ina2xx_get_value) + * ================================================================ */ + +static int +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); + if (error != 0) + return (error); + *millivolts = ((raw >> sc->config->bus_voltage_shift) * + sc->config->bus_voltage_lsb) / 1000; + return (0); +} + +static int +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); + if (error != 0) + return (error); + /* Shunt voltage register is signed */ + *microvolts = (int16_t)raw * 1000 / sc->config->shunt_div; + return (0); +} + +static int +ina2xx_read_current(struct ina2xx_softc *sc, int *milliamps) +{ + uint16_t raw; + int error; + + error = ina2xx_read_reg(sc->dev, INA2XX_CURRENT, &raw); + if (error != 0) + return (error); + /* Current register is signed */ + *milliamps = (int16_t)raw * sc->current_lsb_uA / 1000; + return (0); +} + +static int +ina2xx_read_power(struct ina2xx_softc *sc, int *milliwatts) +{ + uint16_t raw; + int error; + + error = ina2xx_read_reg(sc->dev, INA2XX_POWER, &raw); + if (error != 0) + return (error); + /* Power register is unsigned */ + *milliwatts = (int)((uint32_t)raw * sc->power_lsb_uW / 1000); + return (0); +} + +/* ================================================================ + * Sysctl handlers + * ================================================================ */ + +static int +ina2xx_sysctl_bus_voltage(SYSCTL_HANDLER_ARGS) +{ + struct ina2xx_softc *sc = arg1; + int val, error; + + if (req->newptr != NULL) + return (EINVAL); + error = ina2xx_read_bus_voltage(sc, &val); + if (error != 0) + return (error); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +ina2xx_sysctl_shunt_voltage(SYSCTL_HANDLER_ARGS) +{ + struct ina2xx_softc *sc = arg1; + int val, error; + + if (req->newptr != NULL) + return (EINVAL); + error = ina2xx_read_shunt_voltage(sc, &val); + if (error != 0) + return (error); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +ina2xx_sysctl_current(SYSCTL_HANDLER_ARGS) +{ + struct ina2xx_softc *sc = arg1; + int val, error; + + if (req->newptr != NULL) + return (EINVAL); + error = ina2xx_read_current(sc, &val); + if (error != 0) + return (error); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +ina2xx_sysctl_power(SYSCTL_HANDLER_ARGS) +{ + struct ina2xx_softc *sc = arg1; + int val, error; + + if (req->newptr != NULL) + return (EINVAL); + error = ina2xx_read_power(sc, &val); + if (error != 0) + return (error); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +/* ================================================================ + * Probe / Attach / Detach + * ================================================================ */ + +static struct ofw_compat_data compat_data[] = { + { "ti,ina219", (uintptr_t)INA219 }, + { "ti,ina220", (uintptr_t)INA219 }, + { "ti,ina226", (uintptr_t)INA226 }, + { "ti,ina230", (uintptr_t)INA226 }, + { "ti,ina231", (uintptr_t)INA226 }, + { "ti,ina234", (uintptr_t)INA234 }, + { NULL, 0 }, +}; + +static int +ina2xx_probe(device_t dev) +{ + const struct ofw_compat_data *cd; + phandle_t node; + char desc[80]; + char label[64]; + + if (!ofw_bus_status_okay(dev)) + return (ENXIO); + + cd = ofw_bus_search_compatible(dev, compat_data); + if (cd->ocd_data == 0) + return (ENXIO); + + node = ofw_bus_get_node(dev); + if (OF_getprop(node, "label", label, sizeof(label)) > 0) + snprintf(desc, sizeof(desc), "INA2xx Power Monitor (%s)", + label); + else + snprintf(desc, sizeof(desc), "INA2xx Power Monitor"); + device_set_desc_copy(dev, desc); + + return (BUS_PROBE_DEFAULT); +} + +static int +ina2xx_attach(device_t dev) +{ + struct ina2xx_softc *sc; + const struct ofw_compat_data *cd; + phandle_t node; + struct sysctl_oid *oid; + uint32_t shunt; + long dividend; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + + cd = ofw_bus_search_compatible(dev, compat_data); + sc->chip = (enum ina2xx_chip)cd->ocd_data; + sc->config = &ina2xx_configs[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; + sc->rshunt = shunt; + + /* Read label from DT */ + sc->label[0] = '\0'; + OF_getprop(node, "label", sc->label, sizeof(sc->label)); + 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; + + /* Program configuration register */ + error = ina2xx_write_reg(dev, INA2XX_CONFIG, + sc->config->config_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); + if (error != 0) { + device_printf(dev, "failed to write calibration register\n"); + return (ENXIO); + } + + /* Create sysctl tree */ + sysctl_ctx_init(&sc->sysctl_ctx); + oid = device_get_sysctl_tree(dev); + + if (sc->label[0] != '\0') { + SYSCTL_ADD_STRING(&sc->sysctl_ctx, SYSCTL_CHILDREN(oid), + OID_AUTO, "label", CTLFLAG_RD, sc->label, 0, + "Sensor label"); + } + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(oid), + OID_AUTO, "bus_voltage", + CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, ina2xx_sysctl_bus_voltage, "I", + "Bus voltage (mV)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(oid), + OID_AUTO, "shunt_voltage", + CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, ina2xx_sysctl_shunt_voltage, "I", + "Shunt voltage (uV)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(oid), + OID_AUTO, "current", + CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, ina2xx_sysctl_current, "I", + "Current (mA)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(oid), + OID_AUTO, "power", + CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, ina2xx_sysctl_power, "I", + "Power (mW)"); + + if (sc->label[0] != '\0') + device_printf(dev, "%s: shunt=%u uOhm, " + "current_lsb=%ld uA, power_lsb=%ld uW\n", + sc->label, sc->rshunt, + sc->current_lsb_uA, sc->power_lsb_uW); + + return (0); +} + +static int +ina2xx_detach(device_t dev) +{ + struct ina2xx_softc *sc; + + sc = device_get_softc(dev); + sysctl_ctx_free(&sc->sysctl_ctx); + return (0); +} + +static device_method_t ina2xx_methods[] = { + DEVMETHOD(device_probe, ina2xx_probe), + DEVMETHOD(device_attach, ina2xx_attach), + DEVMETHOD(device_detach, ina2xx_detach), + DEVMETHOD_END +}; + +static driver_t ina2xx_driver = { + "ina2xx", + ina2xx_methods, + sizeof(struct ina2xx_softc), +}; + +DRIVER_MODULE(ina2xx, iicbus, ina2xx_driver, NULL, NULL); +MODULE_VERSION(ina2xx, 1); +MODULE_DEPEND(ina2xx, iicbus, IICBUS_MODVER, IICBUS_MODVER, IICBUS_MODVER); +IICBUS_FDT_PNP_INFO(compat_data); diff --git a/drivers/lp5812/Makefile b/drivers/lp5812/Makefile new file mode 100644 index 0000000..db6bd27 --- /dev/null +++ b/drivers/lp5812/Makefile @@ -0,0 +1,19 @@ +# TI LP5812 LED Controller kernel module for FreeBSD +# +# Build: +# make -C /build/opnsense-deps/drivers/lp5812 \ +# KERNBUILDDIR=/usr/obj/build/opnsense-src/arm64.aarch64/sys/MONO-GATEWAY \ +# MACHINE=arm64 MACHINE_ARCH=aarch64 CC=cc LD=ld.lld +# +# Copyright 2026 Mono Technologies Inc. +# SPDX-License-Identifier: BSD-2-Clause + +SYSDIR?= ${.CURDIR}/../../../opnsense-src/sys + +KMOD= lp5812 +SRCS= lp5812.c + +# Auto-generated headers required for OFW/FDT + I2C driver +SRCS+= opt_platform.h device_if.h bus_if.h iicbus_if.h ofw_bus_if.h + +.include diff --git a/drivers/lp5812/lp5812.c b/drivers/lp5812/lp5812.c new file mode 100644 index 0000000..b2c75ca --- /dev/null +++ b/drivers/lp5812/lp5812.c @@ -0,0 +1,516 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright 2026 Mono Technologies Inc. + * Author: Tomaz Zaman + * + * TI LP5812 I2C LED Driver for FreeBSD + * + * Controls up to 12 LED channels via I2C in direct (non-multiplexed) mode. + * Each LED is exposed as /dev/led/