From 3f71ede86ffd50f2026b09f9460d45e3f88d5ddf Mon Sep 17 00:00:00 2001 From: Kotaro Chikuba Date: Sat, 5 Dec 2026 08:50:12 +0900 Subject: [PATCH] js: use Wasm SIMD to sum packet checksums (#189) --- js/core/net-checksum.ts | 88 ++++++++++++++++++++++++++++++++++++++++ js/core/net-checksum.zig | 29 +++++++++++++ js/core/net-tunnel.ts | 14 +------ js/core/net.ts | 14 +------ test/net.test.ts | 33 +++++++++++++++ 5 files changed, 152 insertions(+), 26 deletions(-) create mode 100644 js/core/net-checksum.ts create mode 100644 js/core/net-checksum.zig diff --git a/js/core/net-checksum.ts b/js/core/net-checksum.ts new file mode 100644 index 0000000..59932ec --- /dev/null +++ b/js/core/net-checksum.ts @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: MIT +// Copyright (C) 2026 Pooya Parsa +// Copyright (C) 2026 mizchi + +// Generated from net-checksum.zig with Zig 0.16.0, from the repository root: +// zig build-exe js/core/net-checksum.zig -target wasm32-freestanding -mcpu=mvp+simd128 \ +// -O ReleaseFast -fno-entry -fstrip -rdynamic --stack 0 --global-base=16 \ +// --initial-memory=131072 --max-memory=131072 -femit-bin=/tmp/net-checksum.wasm +// Embed the resulting bytes so the SDK can run directly from source. +// test/net.test.ts runs this command when Zig 0.16 is on PATH and compares. +const wasm = new Uint8Array([ + 0, 97, 115, 109, 1, 0, 0, 0, 1, 10, 2, 96, 1, 127, 1, 127, 96, 0, 1, 127, + 3, 3, 2, 0, 1, 4, 5, 1, 112, 1, 1, 1, 5, 4, 1, 1, 2, 2, 6, 8, + 1, 127, 1, 65, 144, 128, 4, 11, 7, 34, 3, 6, 109, 101, 109, 111, 114, 121, 2, 0, + 5, 115, 117, 109, 49, 54, 0, 0, 13, 115, 99, 114, 97, 116, 99, 104, 79, 102, 102, 115, + 101, 116, 0, 1, 10, 219, 2, 2, 207, 2, 5, 1, 127, 1, 123, 1, 127, 2, 123, 2, + 127, 65, 0, 33, 1, 2, 64, 32, 0, 65, 255, 255, 3, 75, 13, 0, 253, 12, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 2, 2, 64, 2, 64, + 32, 0, 65, 16, 79, 13, 0, 65, 0, 33, 3, 32, 2, 33, 4, 12, 1, 11, 65, 0, + 33, 1, 32, 2, 33, 4, 3, 64, 32, 4, 32, 1, 65, 144, 128, 128, 128, 0, 106, 253, + 0, 4, 0, 32, 2, 253, 13, 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, + 12, 15, 14, 34, 5, 253, 170, 1, 253, 174, 1, 33, 4, 32, 2, 32, 5, 253, 169, 1, + 253, 174, 1, 33, 2, 32, 1, 65, 32, 106, 33, 6, 32, 1, 65, 16, 106, 34, 3, 33, + 1, 32, 6, 32, 0, 77, 13, 0, 11, 11, 32, 2, 32, 4, 253, 174, 1, 34, 2, 32, + 2, 32, 2, 253, 13, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 0, 1, 2, + 3, 253, 174, 1, 34, 2, 32, 2, 32, 2, 253, 13, 4, 5, 6, 7, 0, 1, 2, 3, + 0, 1, 2, 3, 0, 1, 2, 3, 253, 174, 1, 253, 27, 0, 33, 1, 2, 64, 2, 64, + 32, 3, 65, 1, 114, 32, 0, 73, 13, 0, 32, 3, 33, 7, 12, 1, 11, 3, 64, 32, + 3, 65, 144, 128, 128, 128, 0, 106, 45, 0, 0, 65, 8, 116, 32, 3, 65, 145, 128, 128, + 128, 0, 106, 45, 0, 0, 114, 32, 1, 106, 33, 1, 32, 3, 65, 3, 106, 33, 6, 32, + 3, 65, 2, 106, 34, 7, 33, 3, 32, 6, 32, 0, 73, 13, 0, 11, 11, 32, 7, 32, + 0, 79, 13, 0, 32, 7, 45, 0, 144, 128, 128, 128, 0, 65, 8, 116, 32, 1, 106, 33, + 1, 11, 32, 1, 11, 8, 0, 65, 144, 128, 128, 128, 0, 11, +]); + +interface Simd { + scratch: Uint8Array; + sum16(length: number): number; +} + +let simd: Simd | null | undefined; + +function getSimd(): Simd | null { + if (simd !== undefined) return simd; + try { + const { memory, scratchOffset, sum16 } = new WebAssembly.Instance(new WebAssembly.Module(wasm)).exports as { + memory: WebAssembly.Memory; + scratchOffset(): number; + sum16(length: number): number; + }; + simd = { + scratch: new Uint8Array(memory.buffer, scratchOffset(), 65536), + sum16, + }; + } catch { + simd = null; + } + return simd; +} + +/** Whether the SIMD module loaded (sums of 512 to 65535 bytes use it). */ +export function hasSimdChecksum(): boolean { + return getSimd() !== null; +} + +function simdSum16(bytes: Uint8Array, off: number, length: number): number | undefined { + if (length < 512 || length > 65535 || off < 0 || off + length > bytes.length) return; + const host = getSimd(); + if (!host) return; + host.scratch.set(bytes.subarray(off, off + length)); + return host.sum16(length) >>> 0; +} + +/** Add the big-endian words of an Internet checksum. Pad an odd last byte with zero. */ +export function sum16(bytes: Uint8Array, off: number, len: number, sum = 0): number { + const vectorSum = simdSum16(bytes, off, len); + if (vectorSum !== undefined) return sum + vectorSum; + const end = off + len; + let i = off; + for (; i + 1 < end; i += 2) sum += (bytes[i]! << 8) | bytes[i + 1]!; + if (i < end) sum += bytes[i]! << 8; + return sum; +} + +export function fold(sum: number): number { + while (sum > 0xffff) sum = (sum & 0xffff) + Math.floor(sum / 65536); + return ~sum & 0xffff; +} diff --git a/js/core/net-checksum.zig b/js/core/net-checksum.zig new file mode 100644 index 0000000..24faa8d --- /dev/null +++ b/js/core/net-checksum.zig @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT +// Copyright (C) 2026 mizchi + +const Words = @Vector(8, u16); +const Sums = @Vector(8, u32); +// The build links data from address 16 (--global-base), since a Zig pointer +// may not be 0, and gives the module two pages to hold it. +var scratch: [65536]u8 align(16) = undefined; + +export fn scratchOffset() usize { + return @intFromPtr(&scratch); +} + +export fn sum16(length: usize) u32 { + // One IPv4 packet's length fits in a 16-bit field, and its sum in u32. + if (length > 65535) return 0; + var accum: Sums = @splat(0); + var i: usize = 0; + while (i + @sizeOf(Words) <= length) : (i += @sizeOf(Words)) { + const lanes: *const Words = @ptrCast(@alignCast(&scratch[i])); + const shift: @Vector(8, u4) = @splat(8); + const network = (lanes.* << shift) | (lanes.* >> shift); + accum += @intCast(network); + } + var sum: u32 = @reduce(.Add, accum); + while (i + 1 < length) : (i += 2) sum += (@as(u32, scratch[i]) << 8) | scratch[i + 1]; + if (i < length) sum += @as(u32, scratch[i]) << 8; + return sum; +} diff --git a/js/core/net-tunnel.ts b/js/core/net-tunnel.ts index b3e8adc..e28ac5a 100644 --- a/js/core/net-tunnel.ts +++ b/js/core/net-tunnel.ts @@ -34,6 +34,7 @@ // DHCP discover from the guest drops the last at once and is passed on. import type { NetTunnel, NetTunnelResolver } from "./net.ts"; +import { fold, sum16 } from "./net-checksum.ts"; /** Tailscale's (and the default) tunnel MTU. */ export const TUNNEL_MTU = 1280; @@ -108,19 +109,6 @@ export const newTunnelStats = (): NetTunnelStats => ({ tx: 0, txBytes: 0, rx: 0, // ---- checksums ---- -function sum16(b: Uint8Array, off: number, len: number, s = 0): number { - const end = off + len; - let i = off; - for (; i + 1 < end; i += 2) s += (b[i]! << 8) | b[i + 1]!; - if (i < end) s += b[i]! << 8; - return s; -} - -function fold(s: number): number { - while (s > 0xffff) s = (s & 0xffff) + Math.floor(s / 65536); - return ~s & 0xffff; -} - const u16 = (b: Uint8Array, o: number) => (b[o]! << 8) | b[o + 1]!; const put16 = (b: Uint8Array, o: number, v: number) => { b[o] = v >> 8; b[o + 1] = v & 255; }; const u32 = (b: Uint8Array, o: number) => ((b[o]! << 24) | (b[o + 1]! << 16) | (b[o + 2]! << 8) | b[o + 3]!) >>> 0; diff --git a/js/core/net.ts b/js/core/net.ts index c9ceff7..cad77c0 100644 --- a/js/core/net.ts +++ b/js/core/net.ts @@ -50,6 +50,7 @@ // connections and datagrams (except through a tunnel). import type { Kernel, NetDevice } from "./kernel.ts"; +import { fold, sum16 } from "./net-checksum.ts"; import { FRAG_NEEDED, RewrittenFlows, TUNNEL_MTU, newTunnelStats, tunnelEgress, tunnelIngress, tunnelPass, type NetTunnelStats } from "./net-tunnel.ts"; import { errorText } from "./output.ts"; @@ -208,19 +209,6 @@ function parseMac(s: string): Uint8Array { return Uint8Array.from(s.split(":").map((h) => parseInt(h, 16))); } -// Internet checksum helpers. -function sum16(u8: Uint8Array, off: number, len: number, s = 0): number { - const end = off + len; - let i = off; - for (; i + 1 < end; i += 2) s += (u8[i]! << 8) | u8[i + 1]!; - if (i < end) s += u8[i]! << 8; - return s; -} -function fold(s: number): number { - while (s > 0xffff) s = (s & 0xffff) + Math.floor(s / 65536); - return ~s & 0xffff; -} - const seqLt = (a: number, b: number) => ((a - b) | 0) < 0; const seqLe = (a: number, b: number) => ((a - b) | 0) <= 0; const seqAdd = (a: number, n: number) => (a + n) >>> 0; diff --git a/test/net.test.ts b/test/net.test.ts index 8c8e26f..d9c3506 100644 --- a/test/net.test.ts +++ b/test/net.test.ts @@ -9,7 +9,13 @@ import assert from "node:assert/strict"; import { createServer, type AddressInfo } from "node:net"; import { createServer as createHttpServer } from "node:http"; import dgram from "node:dgram"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; import { NetStack, UDP_IDLE_MS, ip4, ip4str, type NetBackend, type NetConnectionEvents, type NetDatagramEvents, type NetTunnel } from "../js/core/net.ts"; +import { fold, hasSimdChecksum, sum16 } from "../js/core/net-checksum.ts"; import { RemoteTunnel } from "../js/core/net-tunnel.ts"; import { wispBackend } from "../js/core/net-wisp.ts"; import { fetchRoutes } from "../js/core/net-fetch.ts"; @@ -17,6 +23,33 @@ import { directBackend } from "../js/node/net.ts"; import { acceptWebSocket } from "./ws-server.ts"; import { GUEST, GUEST_MAC, collect, csum, echoTest, eth, ipv4, mkStack, parse, tcp, udp, until, withWisp } from "./net-helpers.ts"; +test("Internet checksum covers short and full-size packets at an odd offset", () => { + assert.ok(hasSimdChecksum(), "the SIMD checksum module did not load"); + const bytes = Uint8Array.from({ length: 65537 }, (_, i) => (i * 73 + (i >>> 8)) & 255); + for (const len of [20, 512, 513, 1500, 65535, 65536]) { + assert.equal(fold(sum16(bytes, 1, len, 271)), csum(bytes, 1, len, 271), `length ${len}`); + } +}); + +test("the embedded checksum module is what its build command in net-checksum.ts makes of net-checksum.zig", (t) => { + const version = spawnSync("zig", ["version"], { encoding: "utf8" }); + if (version.status !== 0 || !version.stdout.startsWith("0.16.")) return t.skip("needs Zig 0.16 on PATH"); + const root = fileURLToPath(new URL("..", import.meta.url)); + const source = readFileSync(join(root, "js/core/net-checksum.ts"), "utf8"); + const command = source.match(/^\/\/ (zig build-exe (?:.*\\\n\/\/ )*.*)$/m)![1]!.replace(/\\\n\/\/ /g, " ").trim().split(/\s+/); + const embedded = Uint8Array.from(source.match(/new Uint8Array\(\[([^\]]*)\]\)/)![1]!.split(",").filter((s) => s.trim()).map(Number)); + const dir = mkdtempSync(join(tmpdir(), "net-checksum-")); + try { + const out = join(dir, "net-checksum.wasm"); + const args = command.slice(1).map((a) => (a.startsWith("-femit-bin=") ? `-femit-bin=${out}` : a)); + const r = spawnSync("zig", args, { cwd: root, encoding: "utf8" }); + assert.equal(r.status, 0, r.stderr); + assert.deepEqual(new Uint8Array(readFileSync(out)), embedded); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + test("ARP for the gateway, none for the guest's own address", () => { const { stack, out } = mkStack({}); const arp = (tip: string) => {