// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The WIZnet W5100, the Ethernet chip on an a2RetroSystems Uthernet II. //! //! What makes the W5100 unlike the Ethernet cards before it — the CS8900A on //! the original Uthernet, say — is that the TCP/IP stack is *in the chip*. A //! program does not build packets and hand them to an Ethernet controller; it //! opens a socket, connects it, and moves bytes, and the silicon does the rest. //! That is exactly the shape of a host's own sockets, which is what makes this //! card the one to model in a terminal: there is no raw Ethernet to bridge and //! no privilege to ask for, only four sockets that map to four of the host's. //! //! This is the chip and nothing of the host. It is the register file, the four //! sockets' state, and the transmit and receive rings, and it turns the //! commands a driver writes to `Sn_CR` into changes a session can see and act //! on — a socket that wants to connect somewhere, bytes waiting to go out, room //! that has opened up for bytes to come in. The session (`session8.zig`) is //! what has the host sockets and does the connecting and the moving; see //! `pumpEthernet` there. Keeping the two apart is what lets the chip be tested //! with no network at all. //! //! A driver reaches the chip through the indirect bus interface (W5100 data //! sheet, §6.2), which is the four addresses the Uthernet II wires to its slot: //! a mode register, a two-byte pointer into the chip's internal memory, and a //! data register that reads or writes the byte the pointer names and, with the //! mode register's auto-increment bit set, steps the pointer on. Everything //! else — the socket registers, the rings — lives in that internal memory and //! is reached only through the pointer. (WIZnet, 2011.) const std = @import("std"); /// The chip's internal address space is 32K: the registers low down, and the /// transmit and receive memories high up. pub const memory_size = 0x8000; // The common registers (W5100 data sheet, §4.1). Only the ones the model acts // on are named; the rest are stored and read back. const mr: u16 = 0x0000; // this is the *indirect* MR, kept outside `memory` const shar: u16 = 0x0009; // source hardware address (MAC), six bytes const sipr: u16 = 0x000f; // source IP, four bytes // The socket registers (§4.2), as offsets from a socket's base. A socket's // base is `socket_base + n * socket_stride`. const socket_base: u16 = 0x0400; const socket_stride: u16 = 0x0100; const sn_mr: u16 = 0x00; // mode: the protocol const sn_cr: u16 = 0x01; // command const sn_ir: u16 = 0x02; // interrupt const sn_sr: u16 = 0x03; // status const sn_port: u16 = 0x04; // source port, two bytes const sn_dipr: u16 = 0x0c; // destination IP, four bytes const sn_dport: u16 = 0x10; // destination port, two bytes const sn_tx_fsr: u16 = 0x20; // transmit free size, two bytes const sn_tx_rd: u16 = 0x22; // transmit read pointer, two bytes const sn_tx_wr: u16 = 0x24; // transmit write pointer, two bytes const sn_rx_rsr: u16 = 0x26; // receive received size, two bytes const sn_rx_rd: u16 = 0x28; // receive read pointer, two bytes /// The transmit and receive memories, each 8K, one quarter to each socket. const tx_base: u16 = 0x4000; const rx_base: u16 = 0x6000; const socket_buffer: u16 = 0x0800; // 2K a socket, the reset default /// The protocol a socket is opened in, the low four bits of `Sn_MR`. pub const Protocol = enum(u8) { closed = 0x00, tcp = 0x01, udp = 0x02, ip_raw = 0x03, _, }; /// The commands written to `Sn_CR` (§4.2). The chip clears the register once it /// has taken the command, which is why a driver watches `Sn_SR` and `Sn_IR` /// rather than the command register to know it is done. pub const Command = enum(u8) { open = 0x01, listen = 0x02, connect = 0x04, disconnect = 0x08, close = 0x10, send = 0x20, receive = 0x40, _, }; /// The socket status values `Sn_SR` takes (§4.2). Only the ones a settled /// connection rests in are modeled; the handshake's transient states are the /// host's to pass through. pub const Status = enum(u8) { closed = 0x00, init = 0x13, listen = 0x14, established = 0x17, close_wait = 0x1c, udp = 0x22, _, }; /// The `Sn_IR` interrupt bits (§4.2), written back as 1 to clear. const ir_con: u8 = 0x01; // a connection was established const ir_discon: u8 = 0x02; // the peer disconnected const ir_recv: u8 = 0x04; // data arrived const ir_timeout: u8 = 0x08; // a connect or send gave up const ir_send_ok: u8 = 0x10; // a send finished /// What a socket wants the session to do next, taken by the session once and /// then cleared. A socket asks for one thing at a time, in the order a driver /// issues the commands. pub const Wants = union(enum) { nothing, /// Connect out to this address and port (a TCP client). connect: struct { ip: [4]u8, port: u16 }, /// Listen on this port for one connection (a TCP server). listen: u16, /// Bind this port for datagrams (UDP). bind: u16, /// Close the host socket. close, }; const Socket = struct { protocol: Protocol = .closed, /// What the session has to do for this socket, set when a command is /// written and cleared when the session takes it. wants: Wants = .nothing, }; pub const W5100 = struct { /// The internal memory the pointer addresses: registers and the two rings. memory: [memory_size]u8 = @splat(0), /// The mode register, which is not in `memory`: it is one of the four /// registers the bus reaches directly. mode: u8 = 0, /// The pointer the data register reads and writes through. pointer: u16 = 0, sockets: [4]Socket = .{ .{}, .{}, .{}, .{} }, /// The receive write pointer is the chip's own, moved as bytes come in from /// the host, not a register a driver sees — so it is kept here rather than /// in `memory`. The driver's read pointer chases it. rxWrite: [4]u16 = .{ 0, 0, 0, 0 }, /// The mode register's auto-increment bit: after each data-register access /// the pointer steps on by one. fn autoIncrement(self: W5100) bool { return self.mode & 0x02 != 0; } fn socketAt(comptime n: usize, offset: u16) u16 { return socket_base + @as(u16, n) * socket_stride + offset; } pub fn word(self: *const W5100, at: u16) u16 { return @as(u16, self.memory[at]) << 8 | self.memory[at + 1]; } pub fn setWord(self: *W5100, at: u16, value: u16) void { self.memory[at] = @truncate(value >> 8); self.memory[at + 1] = @truncate(value); } // -- the bus, four registers on the slot (§6.2) -------------------------- /// The Uthernet II's four slot addresses: 0 is the mode register, 1 and 2 /// the pointer's high and low bytes, 3 the data register. pub fn read(self: *W5100, register: u2) u8 { return switch (register) { 0 => self.mode, 1 => @truncate(self.pointer >> 8), 2 => @truncate(self.pointer), 3 => self.readData(), }; } pub fn write(self: *W5100, register: u2, value: u8) void { switch (register) { 0 => self.mode = value, 1 => self.pointer = @as(u16, value) << 8 | (self.pointer & 0x00ff), 2 => self.pointer = (self.pointer & 0xff00) | value, 3 => self.writeData(value), } } fn readData(self: *W5100) u8 { const at = self.pointer; if (self.autoIncrement()) self.pointer +%= 1; return self.internalRead(at); } fn writeData(self: *W5100, value: u8) void { const at = self.pointer; if (self.autoIncrement()) self.pointer +%= 1; self.internalWrite(at, value); } // -- the internal memory, reached through the pointer -------------------- fn internalRead(self: *W5100, at: u16) u8 { if (at >= memory_size) return 0; return self.memory[at]; } fn internalWrite(self: *W5100, at: u16, value: u8) void { if (at >= memory_size) return; self.memory[at] = value; // A write to a socket's command register is a command to run. inline for (0..4) |n| { if (at == socketAt(n, sn_cr)) { self.runCommand(n, @enumFromInt(value)); // The chip clears the command register once it has it. self.memory[at] = 0; } } } // -- the socket command machine (§5) ------------------------------------- fn runCommand(self: *W5100, comptime n: usize, command: Command) void { const socket = &self.sockets[n]; switch (command) { .open => { socket.protocol = @enumFromInt(self.memory[socketAt(n, sn_mr)] & 0x0f); switch (socket.protocol) { .tcp => self.setStatus(n, .init), .udp => { self.setStatus(n, .udp); socket.wants = .{ .bind = self.word(socketAt(n, sn_port)) }; }, else => self.setStatus(n, .closed), } // A freshly opened socket's rings are empty and all free. self.setWord(socketAt(n, sn_tx_fsr), socket_buffer); self.setWord(socketAt(n, sn_tx_rd), 0); self.setWord(socketAt(n, sn_tx_wr), 0); self.setWord(socketAt(n, sn_rx_rsr), 0); self.setWord(socketAt(n, sn_rx_rd), 0); }, .connect => { socket.wants = .{ .connect = .{ .ip = self.memory[socketAt(n, sn_dipr)..][0..4].*, .port = self.word(socketAt(n, sn_dport)), } }; }, .listen => { self.setStatus(n, .listen); socket.wants = .{ .listen = self.word(socketAt(n, sn_port)) }; }, .send => { // The bytes between the read and write pointers are ready; the // session takes them from `sent`. Nothing to do here but let // the free size catch up when they are consumed. }, .receive => { // The driver has advanced the receive read pointer, freeing // that much of the ring; the size still waiting is the write // pointer less the new read pointer. self.recomputeReceived(n); }, .disconnect, .close => { socket.wants = .close; socket.protocol = .closed; self.setStatus(n, .closed); }, else => {}, } } fn setStatus(self: *W5100, comptime n: usize, status: Status) void { self.memory[socketAt(n, sn_sr)] = @intFromEnum(status); } fn raise(self: *W5100, comptime n: usize, bit: u8) void { self.memory[socketAt(n, sn_ir)] |= bit; } fn recomputeReceived(self: *W5100, comptime n: usize) void { // Received size is what is between the read pointer and the write // pointer of the receive ring. const write_at = self.rxWrite[n]; const read_at = self.word(socketAt(n, sn_rx_rd)); self.setWord(socketAt(n, sn_rx_rsr), write_at -% read_at); } // -- what the session drives --------------------------------------------- /// What a socket wants done, taken once. The session calls this for each /// socket; a `.nothing` means leave it be. pub fn take(self: *W5100, socket: usize) Wants { const wants = self.sockets[socket].wants; self.sockets[socket].wants = .nothing; return wants; } /// The bytes a socket has queued to send: everything between its transmit /// read and write pointers. pub fn sent(self: *W5100, comptime n: usize) []const u8 { const read_at = self.word(socketAt(n, sn_tx_rd)) % socket_buffer; const write_at = self.word(socketAt(n, sn_tx_wr)) % socket_buffer; const base = tx_base + n * socket_buffer; // The ring does not wrap within one call here: a driver sends a burst // and waits, and the model hands back the contiguous run to the end of // the buffer, the session calling again for the wrapped remainder. if (write_at >= read_at) return self.memory[base + read_at ..][0 .. write_at - read_at]; return self.memory[base + read_at ..][0 .. socket_buffer - read_at]; } /// Tells the chip `count` queued bytes have gone out: the read pointer /// catches up and the free size grows. pub fn didSend(self: *W5100, comptime n: usize, count: u16) void { self.setWord(socketAt(n, sn_tx_rd), self.word(socketAt(n, sn_tx_rd)) +% count); self.setWord(socketAt(n, sn_tx_fsr), self.word(socketAt(n, sn_tx_fsr)) + count); self.raise(n, ir_send_ok); } /// Hands the chip bytes that came in on a socket, into its receive ring, /// and raises the receive interrupt. Returns how many were taken; a full /// ring takes fewer than offered. pub fn receive(self: *W5100, comptime n: usize, bytes: []const u8) usize { const base = rx_base + n * socket_buffer; var taken: usize = 0; while (taken < bytes.len) { const used = self.rxWrite[n] -% self.word(socketAt(n, sn_rx_rd)); if (used >= socket_buffer) break; // ring full self.memory[base + (self.rxWrite[n] % socket_buffer)] = bytes[taken]; self.rxWrite[n] +%= 1; taken += 1; } self.recomputeReceived(n); if (taken > 0) self.raise(n, ir_recv); return taken; } /// Where a UDP socket's datagrams go: the destination address and port a /// driver wrote before its SEND. TCP has this from the connection instead. pub fn destination(self: *const W5100, comptime n: usize) struct { ip: [4]u8, port: u16 } { return .{ .ip = self.memory[socketAt(n, sn_dipr)..][0..4].*, .port = @as(u16, self.memory[socketAt(n, sn_dport)]) << 8 | self.memory[socketAt(n, sn_dport) + 1], }; } /// Hands the chip a whole UDP datagram, which it stores the way the W5100 /// does: an eight-byte header — the peer's address and port and the length /// — and then the data (§5.2.2). A driver reads the header to learn who /// sent it. Returns whether it fit. pub fn receiveDatagram(self: *W5100, comptime n: usize, peer_ip: [4]u8, peer_port: u16, bytes: []const u8) bool { var header: [8]u8 = undefined; header[0..4].* = peer_ip; header[4] = @truncate(peer_port >> 8); header[5] = @truncate(peer_port); header[6] = @truncate(bytes.len >> 8); header[7] = @truncate(bytes.len); const room = socket_buffer - (self.rxWrite[n] -% self.word(socketAt(n, sn_rx_rd))); if (room < header.len + bytes.len) return false; _ = self.receive(n, &header); _ = self.receive(n, bytes); return true; } /// The host connected this socket (a client's connect finished, or a /// server accepted): status established, and the connect interrupt. pub fn connected(self: *W5100, comptime n: usize) void { self.setStatus(n, .established); self.raise(n, ir_con); } /// The peer closed a socket. pub fn disconnected(self: *W5100, comptime n: usize) void { self.setStatus(n, .close_wait); self.raise(n, ir_discon); } /// A connect the host could not make: the socket closes and the timeout /// interrupt is raised, which is what a driver waits on to give up. pub fn timedOut(self: *W5100, comptime n: usize) void { self.setStatus(n, .closed); self.raise(n, ir_timeout); } pub fn reset(self: *W5100) void { self.* = .{}; } /// Sets the card's source hardware address (its MAC), which a driver /// otherwise writes into the SHAR registers itself. pub fn setMac(self: *W5100, address: [6]u8) void { @memcpy(self.memory[shar..][0..6], &address); } }; const testing = std.testing; test "the pointer and the data register reach the internal memory" { var chip: W5100 = .{}; chip.write(0, 0x03); // MR: indirect on, auto-increment on // Point at the source IP register and write four bytes with the pointer // stepping on by itself. chip.write(1, @truncate(sipr >> 8)); chip.write(2, @truncate(sipr)); chip.write(3, 192); chip.write(3, 168); chip.write(3, 1); chip.write(3, 64); try testing.expectEqualSlices(u8, &.{ 192, 168, 1, 64 }, chip.memory[sipr..][0..4]); // Read them back the same way. chip.write(1, @truncate(sipr >> 8)); chip.write(2, @truncate(sipr)); try testing.expectEqual(@as(u8, 192), chip.read(3)); try testing.expectEqual(@as(u8, 168), chip.read(3)); } /// Writes a byte into the chip's internal memory through the bus, the way a /// driver does, so a test reads as a driver would. fn poke(chip: *W5100, at: u16, value: u8) void { chip.write(1, @truncate(at >> 8)); chip.write(2, @truncate(at)); chip.write(0, 0x01); // indirect, no auto-increment chip.write(3, value); } fn peek(chip: *W5100, at: u16) u8 { chip.write(1, @truncate(at >> 8)); chip.write(2, @truncate(at)); chip.write(0, 0x01); return chip.read(3); } test "opening a TCP socket and connecting asks the session to connect" { var chip: W5100 = .{}; const base = socket_base; // socket 0 poke(&chip, base + sn_mr, @intFromEnum(Protocol.tcp)); poke(&chip, base + sn_cr, @intFromEnum(Command.open)); try testing.expectEqual(@as(u8, @intFromEnum(Status.init)), peek(&chip, base + sn_sr)); // A destination and a connect command make the socket want a connection. poke(&chip, base + sn_dipr, 10); poke(&chip, base + sn_dipr + 1, 0); poke(&chip, base + sn_dipr + 2, 0); poke(&chip, base + sn_dipr + 3, 5); poke(&chip, base + sn_dport, 0x1f); // port 8080 = 0x1f90 poke(&chip, base + sn_dport + 1, 0x90); poke(&chip, base + sn_cr, @intFromEnum(Command.connect)); switch (chip.take(0)) { .connect => |c| { try testing.expectEqualSlices(u8, &.{ 10, 0, 0, 5 }, &c.ip); try testing.expectEqual(@as(u16, 8080), c.port); }, else => return error.NotConnecting, } // The session says it connected; the driver sees established. chip.connected(0); try testing.expectEqual(@as(u8, @intFromEnum(Status.established)), peek(&chip, base + sn_sr)); try testing.expect(peek(&chip, base + sn_ir) & ir_con != 0); } test "bytes go out through the transmit ring and come in through the receive ring" { var chip: W5100 = .{}; const base = socket_base; poke(&chip, base + sn_mr, @intFromEnum(Protocol.tcp)); poke(&chip, base + sn_cr, @intFromEnum(Command.open)); // Put three bytes in the transmit memory and move the write pointer past // them, the way a driver does before SEND. poke(&chip, tx_base + 0, 'H'); poke(&chip, tx_base + 1, 'i'); poke(&chip, tx_base + 2, '!'); poke(&chip, base + sn_tx_wr, 0); poke(&chip, base + sn_tx_wr + 1, 3); poke(&chip, base + sn_cr, @intFromEnum(Command.send)); try testing.expectEqualSlices(u8, "Hi!", chip.sent(0)); chip.didSend(0, 3); try testing.expectEqual(@as(usize, 0), chip.sent(0).len); // Bytes in from the peer land in the receive ring and set the received // size and the receive interrupt. try testing.expectEqual(@as(usize, 5), chip.receive(0, "world")); try testing.expectEqual(@as(u16, 5), chip.word(socket_base + sn_rx_rsr)); try testing.expect(peek(&chip, base + sn_ir) & ir_recv != 0); // The bytes are readable in the receive memory. try testing.expectEqualSlices(u8, "world", chip.memory[rx_base..][0..5]); }