Skip to content

Read FreeBSD TCP and UDP statistics as 64-bit counters - #3795

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:freebsd-tcp-stats
Oct 13, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:freebsd-tcp-stats

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Fixes the TCP and UDP statistics from InternetProtocolStats on FreeBSD, found by comparing an OSHI report against the OS's own tools on cfarm430 (FreeBSD 16-CURRENT).

The bug

Every counter in struct tcpstat and struct udpstat has been a uint64_t since FreeBSD 10.0, but OSHI read them as 32-bit values at the macOS offsets. On cfarm430 that gave passive opens 0 (netstat: 5133), segments received 171 (827k), UDP datagrams sent 0 (448k), and so on.

The fix

  • The structs have no version field, and FreeBSD 14.0 inserted tcps_progdrops mid-struct, moving every TCP counter from tcps_sndtotal on by 8 bytes. The size the sysctl returns identifies the layout:

    Releases tcpstat size Offsets
    10.x, 11.x 880 before tcps_progdrops
    12.x, 13.x 904 before tcps_progdrops
    14.x / 15.0 / main 984 / 1000 / 1048 shifted by 8
    anything else (incl. 9.x and earlier) — netstat -s fallback

    Offsets were checked against tcp_var.h and udp_var.h from 10.0, 11.4, 12.4, 13.5, 14.0, 14.3, 15.0 and main. udpstat is unchanged since 10.0 (112 bytes).

  • Parsing moves to FreeBsdInternetProtocolStats in oshi-common; the JNA and FFM twins only fetch the bytes.

  • UDP no-port now counts udps_noport + udps_noportbcast + udps_noportmcast, matching what netstat prints.

  • UDPv6 reports zeros instead of the IPv6 software-checksum counters it showed; FreeBSD does not count IPv6 datagrams separately in this struct.

  • The now-unused stat carriers in CLibrary are removed (macOS has its own in oshi-common).

New comparison test

IpStatsComparisonTest (in oshi.comparison, run by -Paggregate-coverage) checks the native counters against netstat -s on FreeBSD and macOS. Counters only grow, so each netstat value must lie between a native read taken before it and one taken after. It parses netstat itself rather than through the production parser. The FreeBSD and macOS CI jobs already run this profile, so a future release that moves the offsets again fails CI.

On macOS, TCP counters are zero without root and some fields are estimated from IP counters, so macOS compares only the fields read directly; UDP no-port is skipped there because macOS still reports only udps_noportmcast (follow-up).

Testing

  • Fixture tests for each known size, and for unknown sizes that must fall back.
  • cfarm430 (FreeBSD 16-CURRENT, JDK 25): the new test fails on master (every TCP field, plus UDP sent and no-port) and passes on this branch; JNA and FFM reports match netstat -s.
  • macOS: full gate, -Perror-prone, and -Pnative-comparison green.
  • Not run live on 10–15; those layouts are covered by the header checks and fixture tests, and CI's FreeBSD VM covers the current release.

Unrelated: DiskDriversTest.testDiskDrivers fails on cfarm430 on master too (a multi-disk VM); that is a separate partition-listing bug, tracked separately.

Summary by CodeRabbit

  • Bug Fixes
    • FreeBSD TCP and UDP statistics now use the correct 64-bit kernel counters, improving reported values across supported system layouts.
    • IPv6 UDP statistics are reported as 0, as FreeBSD does not track them separately.
  • Tests
    • Added comparisons of native TCP and UDP statistics with netstat output on macOS and FreeBSD.

Every counter in struct tcpstat and struct udpstat has been a uint64_t
since FreeBSD 10.0, but OSHI read them as 32-bit values at the macOS
offsets, so most TCP and UDP statistics were wrong: passive opens 0,
segments received a different counter, UDP datagrams sent 0.

The structs carry no version field, and FreeBSD 14.0 inserted
tcps_progdrops mid-struct, moving every TCP counter from tcps_sndtotal
on by 8 bytes. The size the sysctl returns identifies the layout: 880
or 904 bytes before the insertion, 984 or more after it. Any other size
falls back to netstat -s. Offsets were checked against tcp_var.h and
udp_var.h from 10.0, 11.4, 12.4, 13.5, 14.0, 14.3, 15.0 and main.

The parsing moves to FreeBsdInternetProtocolStats in oshi-common; the
JNA and FFM twins only fetch the bytes. UDP no-port now counts
udps_noport, udps_noportbcast and udps_noportmcast, which netstat
reports together. UDPv6 reports zeros instead of the IPv6
software-checksum counters it showed. The now-unused stat carriers in
CLibrary are removed.

IpStatsComparisonTest checks the native counters against netstat -s on
FreeBSD and macOS, bracketing each netstat count between two native
reads. It fails on master and passes here on FreeBSD 16-CURRENT.
@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a3bf37fc-cd82-45a8-adb5-9c349702a57a
📥 Commits

Reviewing files that changed from the base of the PR and between ad232c7 and c131ddd.

📒 Files selected for processing (7)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/IpStatsComparisonTest.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/freebsd/FreeBsdInternetProtocolStats.java
  • oshi-common/src/test/java/oshi/software/common/os/unix/freebsd/FreeBsdInternetProtocolStatsTest.java
  • oshi-core-ffm/src/main/java/oshi/software/os/unix/freebsd/FreeBsdInternetProtocolStatsFFM.java
  • oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdInternetProtocolStatsJNA.java
💤 Files with no reviewable changes (1)
  • oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

📜 Recent review details
⏰ Context from checks skipped due to timeout. (11)
  • GitHub Check: Test JDK 25, OpenBSD
  • GitHub Check: Test JDK 25, NetBSD
  • GitHub Check: Test JDK 25, OpenIndiana
  • GitHub Check: Test JDK 25, FreeBSD
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
  • GitHub Check: Error Prone
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 25, ubuntu-latest
  • GitHub Check: Lint (ForbiddenAPIs, Javadoc, SLF4J)
  • GitHub Check: Lint (Spotless, Checkstyle)
🧰 Additional context used
📚 Code guidelines (2)
AGENTS.md — auto-discovered
CONTRIBUTING.md — auto-discovered
📓 Path-based instructions (3)
Source excerpt: **Banned APIs** (`config/forbidden-apis.txt` and friends, enforced by `forbiddenapis:check`): `oshi-core-ffm` may not reference `com.sun.jna.**`.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-core-ffm/src/main/java/oshi/software/os/unix/freebsd/FreeBsdInternetProtocolStatsFFM.java
Source excerpt: **Banned APIs** (`config/forbidden-apis.txt` and friends, enforced by `forbiddenapis:check`): `oshi-common` may not reference `com.sun.jna.**`, `java.lang.foreign.**`, or any `System.load`/`loadLibrary`.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-common/src/test/java/oshi/software/common/os/unix/freebsd/FreeBsdInternetProtocolStatsTest.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/freebsd/FreeBsdInternetProtocolStats.java
Source excerpt: The Changelog lets users know what's changed.

📄 CodeRabbit inference engine (CONTRIBUTING.md)

Files:

  • CHANGELOG.md
🔇 Additional comments (6)
oshi-common/src/main/java/oshi/software/common/os/unix/freebsd/FreeBsdInternetProtocolStats.java (1)

7-149: LGTM!

oshi-common/src/test/java/oshi/software/common/os/unix/freebsd/FreeBsdInternetProtocolStatsTest.java (1)

1-86: LGTM!

oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdInternetProtocolStatsJNA.java (1)

20-22: LGTM!

oshi-core-ffm/src/main/java/oshi/software/os/unix/freebsd/FreeBsdInternetProtocolStatsFFM.java (1)

7-7: LGTM!

Also applies to: 16-17, 23-25

oshi-benchmark/src/test/java/oshi/comparison/IpStatsComparisonTest.java (1)

1-155: LGTM!

CHANGELOG.md (1)

10-10: LGTM!

📝 Walkthrough

Walkthrough

FreeBSD TCP and UDP statistics now use a shared parser for raw sysctl data, with netstat fallbacks when parsing fails. The JNA and FFM implementations provide sysctl bytes to that parser. Tests compare selected native statistics with netstat output.

Changes

FreeBSD Protocol Statistics

Layer / File(s) Summary
Shared parsing and validation
oshi-common/src/main/java/oshi/software/common/os/unix/freebsd/FreeBsdInternetProtocolStats.java, oshi-common/src/test/java/oshi/software/common/os/unix/freebsd/FreeBsdInternetProtocolStatsTest.java
The shared class parses recognized TCP and UDP sysctl layouts using native-endian 64-bit counters. It falls back to protocol-specific netstat output when parsing fails. Tests cover supported layouts, counter mappings, and rejected buffers.
Native sysctl adapters
oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdInternetProtocolStatsJNA.java, oshi-core-ffm/src/main/java/oshi/software/os/unix/freebsd/FreeBsdInternetProtocolStatsFFM.java, oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java
The JNA and FFM classes provide raw sysctl bytes to the shared parser. The JNA BSD statistics structure classes are removed.
Statistics comparison checks
oshi-benchmark/src/test/java/oshi/comparison/IpStatsComparisonTest.java, CHANGELOG.md
The comparison test checks selected native TCP and UDP counts against netstat output on macOS and FreeBSD. The changelog describes the FreeBSD counter correction and reports IPv6 UDP statistics as 0.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to c131d

FreeBSD TCP and UDP statistics are now read as 64-bit counters at layout-appropriate offsets, and unrecognized layouts fall back to netstat. No concrete defects were identified, so the change appears ready to merge.

Pre-merge checks · Passed 4 · Failed 1

Failed Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 5 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks (4 passed)
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: reading FreeBSD TCP and UDP statistics as 64-bit counters.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 5 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

A rabbit checks the counters twice,
Then reads the bytes in native order.
TCP and UDP find their place,
While netstat waits as fallback.
The rabbit marks each passing test,
And hops away through clover-green.

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.67568% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.58%. Comparing base (ad232c7) to head (c131ddd).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
.../os/unix/freebsd/FreeBsdInternetProtocolStats.java 78.78% 5 Missing and 2 partials ⚠️
.../unix/freebsd/FreeBsdInternetProtocolStatsFFM.java 50.00% 0 Missing and 1 partial ⚠️
.../unix/freebsd/FreeBsdInternetProtocolStatsJNA.java 50.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3795      +/-   ##
============================================
- Coverage     80.66%   80.58%   -0.08%     
- Complexity       83      561     +478     
============================================
  Files           725      725              
  Lines         25991    25944      -47     
  Branches       4399     4399              
============================================
- Hits          20965    20908      -57     
- Misses         2785     2793       +8     
- Partials       2241     2243       +2     
Flag Coverage Δ
freebsd 36.64% <75.67%> (-0.13%) ⬇️
linux 40.69% <45.94%> (+0.14%) ⬆️
macos 41.51% <45.94%> (+0.10%) ⬆️
netbsd 35.62% <45.94%> (+0.12%) ⬆️
openbsd 36.19% <45.94%> (+0.13%) ⬆️
solaris 37.50% <45.94%> (+0.11%) ⬆️
windows 47.78% <45.94%> (+0.14%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@dbwiddis
dbwiddis merged commit 486e68c into oshi:master Oct 13, 2026
20 checks passed
@dbwiddis
dbwiddis deleted the freebsd-tcp-stats branch October 13, 2026 00:29
dbwiddis added a commit that referenced this pull request Oct 14, 2026
* Count every macOS datagram with no socket on its port

getUDPv4Stats() read udps_noportmcast, which holds only the IPv6
multicast datagrams that found no socket. MIB-II's udpNoPorts, and what
netstat -s -p udp prints, also covers the unicast and the IPv4
broadcast/multicast ones, so the count was short by orders of magnitude:
12 against netstat's 47782 on a desktop with a week of uptime.

Probing the kernel's counters settles how they partition, which the header
comments describe loosely as "of above":

  case                        noport  noportbcast  noportmcast
  IPv4 unicast, no socket        +1            0            0
  IPv4 multicast, no socket       0           +1            0
  IPv6 unicast, no socket        +1            0            0
  IPv6 multicast, no socket      +1            0           +1

So udps_noportbcast is disjoint from udps_noport and must be added, while
udps_noportmcast is a subset of it and must not be, or every IPv6
multicast datagram counts twice. macOS therefore differs from FreeBSD,
where #3795 adds all three.

BsdUdpstat carries udps_noport and udps_noportbcast, read at offsets 16
and 20, within the size the existing guard already requires. It no longer
carries udps_noportmcast, which nothing reads now. Offsets verified field
by field against netinet/udp_var.h.

With the count correct, the macOS exclusion comes off the no-port check in
IpStatsComparisonTest, which brackets netstat's figure between two native
reads. It passes, as does NativeComparisonTest.internetProtocolStats,
confirming the JNA and FFM twins read the new offsets alike.

* Stop reporting macOS checksum counters as UDPv6 datagrams

getUDPv6Stats() returned udps_snd6_swcsum and udps_rcv6_swcsum as the
datagrams sent and received. Those count datagrams whose checksum was
computed in software, not datagrams. Probing them shows how far apart
those are:

  traffic generated              snd6_swcsum  rcv6_swcsum
  20 UDP datagrams over ::1               +0           +0
  25 UDP datagrams out en0               +25           +0

So the sent figure matches off-box traffic but counts no loopback
datagram, and the received figure does not increment at all: it reads 0
against 6441827 IPv6 packets received on a desktop with a week of uptime.

No better counter exists. macOS has no net.inet6.udp6 sysctl, and
udps_ipackets and udps_opackets provably count both families, so there is
nothing per-family to read. The override is therefore removed in favor of
the zeros AbstractInternetProtocolStats already returns for an OS that
keeps no separate UDPv6 statistics, which is where FreeBSD landed in

getTCPv6Stats() keeps subtracting the same two fields from the IPv6 packet
totals and is left alone: as a correction term, not a count, the sent one
removes 610176 of 2734898 packets of real UDPv6 traffic from the estimate
and earns its place. Its comment now records what the fields are, that the
received side is uncorrected because udps_rcv6_swcsum never increments,
and why they are not reported as datagram counts, so this does not come
back.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant