Browse Source

Add a netdev layer and the RTL8111/8168 Gigabit driver

Johannes Zellner 1 month ago
parent
commit
6d52abe5ce
12 changed files with 2000 additions and 34 deletions
  1. 10 4
      Makefile
  2. 4 0
      kernel.c
  3. 5 0
      ne2000.c
  4. 4 0
      ne2000.h
  5. 165 11
      net.c
  6. 37 1
      net.h
  7. 469 18
      netcmd.c
  8. 61 0
      netdev.c
  9. 36 0
      netdev.h
  10. 1089 0
      r8168.c
  11. 23 0
      r8168.h
  12. 97 0
      terminal.c

+ 10 - 4
Makefile

@@ -143,10 +143,16 @@ peek.o: peek.c io.h
 ne2000.o: ne2000.c ne2000.h pci.h timer.h io.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-netcmd.o: netcmd.c io.h timer.h ne2000.h net.h
+r8168.o: r8168.c r8168.h netdev.h io.h kdbg.h mm.h paging.h pci.h process.h serial.h timer.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-net.o: net.c net.h io.h ne2000.h
+netcmd.o: netcmd.c io.h timer.h netdev.h net.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+netdev.o: netdev.c netdev.h ne2000.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+net.o: net.c net.h io.h netdev.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 blkdev.o: blkdev.c blkdev.h ata.h disk.h
@@ -236,7 +242,7 @@ syscall_stub.o: syscall_stub.S
 mem.o: mem.c mm.h io.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-kernel.elf: vesa_stage.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o ls.o cat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o usb.o lsusb.o kdbg.o blkdev.o ata.o fatdetect.o storage.o fatformat.o format.o vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o peek.o ne2000.o netcmd.o net.o hello_embed.o
+kernel.elf: vesa_stage.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o ls.o cat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o usb.o lsusb.o kdbg.o blkdev.o ata.o fatdetect.o storage.o fatformat.o format.o vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o peek.o ne2000.o r8168.o netdev.o netcmd.o net.o hello_embed.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -412,4 +418,4 @@ dev: kernel.bin kexec_send
 	./kexec_send $(SERIAL_DEV) $(SERIAL_BAUD) $$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o ls.o cat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o usb.o lsusb.o kdbg.o blkdev.o ata.o fatdetect.o storage.o fatformat.o format.o vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o peek.o ne2000.o netcmd.o net.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send
+	rm -f boot.o vesa_stage.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o ls.o cat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o usb.o lsusb.o kdbg.o blkdev.o ata.o fatdetect.o storage.o fatformat.o format.o vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o peek.o ne2000.o r8168.o netdev.o netcmd.o net.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send

+ 4 - 0
kernel.c

@@ -6,6 +6,7 @@
 #include "kmalloc.h"
 #include "mm.h"
 #include "mouse.h"
+#include "netdev.h"
 #include "paging.h"
 #include "process.h"
 #include "timer.h"
@@ -194,5 +195,8 @@ void kernel_main(void)
 	kdbg_init();
 	kdbg_status();
 	vfs_mount_all();
+	/* Bring the NIC up before the WM loop starts, so an idle board can pick
+	 * up a network kexec (`make net-dev`) without any typing. */
+	netdev_active();
 	wm_run();
 }

+ 5 - 0
ne2000.c

@@ -398,3 +398,8 @@ void ne2000_print_info(void)
 	}
 	io_putchar('\n');
 }
+
+const struct netdev ne2000_netdev = {
+	"ne2000", "RTL8029AS",
+	ne2000_init, ne2000_get_mac, ne2000_rx, ne2000_tx, ne2000_print_info, 0, 0, 0,
+};

+ 4 - 0
ne2000.h

@@ -23,4 +23,8 @@ int ne2000_rx(unsigned char *buf, unsigned int maxlen);
    Returns 0 on success, -1 on error. */
 int ne2000_tx(const unsigned char *buf, unsigned int len);
 
+/* netdev adapter (see netdev.h). */
+#include "netdev.h"
+extern const struct netdev ne2000_netdev;
+
 #endif

+ 165 - 11
net.c

@@ -1,11 +1,13 @@
-/* Minimal network stack: ARP + ICMP echo (ping) over the NE2000 driver.
+/* Minimal network stack: ARP + ICMP echo (ping) over a netdev NIC.
    Freestanding, no malloc; fixed-size buffers and a single configured IP. */
 
 #include "io.h"
-#include "ne2000.h"
+#include "netdev.h"
 #include "net.h"
 
-static unsigned char my_ip[4] = { 192, 168, 0, 99 };
+static unsigned char my_ip[4] = { 192, 168, 178, 240 };
+static unsigned char my_mask[4];
+static unsigned char my_gw[4];
 
 /* ---- small print helpers (framebuffer console) ---- */
 
@@ -65,7 +67,7 @@ static int ip_eq(const unsigned char *a, const unsigned char *b)
 }
 
 /* Internet checksum (16-bit one's complement, network byte order). */
-static unsigned short checksum(const void *data, unsigned int len)
+unsigned short net_checksum(const void *data, unsigned int len)
 {
 	const unsigned char *p = (const unsigned char *)data;
 	unsigned int sum = 0;
@@ -87,8 +89,26 @@ static unsigned short checksum(const void *data, unsigned int len)
 void net_set_ip(const unsigned char ip[4])
 {
 	unsigned int i;
-	for (i = 0; i < 4; i++)
+
+	/* Manual override: subnet knowledge is dropped, so the stack keeps
+	 * treating everything as directly reachable. */
+	for (i = 0; i < 4; i++) {
+		my_ip[i] = ip[i];
+		my_mask[i] = 0;
+		my_gw[i] = 0;
+	}
+}
+
+void net_configure(const unsigned char ip[4], const unsigned char mask[4],
+		   const unsigned char gw[4])
+{
+	unsigned int i;
+
+	for (i = 0; i < 4; i++) {
 		my_ip[i] = ip[i];
+		my_mask[i] = mask ? mask[i] : 0;
+		my_gw[i] = gw ? gw[i] : 0;
+	}
 }
 
 void net_get_ip(unsigned char ip[4])
@@ -98,6 +118,25 @@ void net_get_ip(unsigned char ip[4])
 		ip[i] = my_ip[i];
 }
 
+void net_get_mask(unsigned char mask[4])
+{
+	unsigned int i;
+	for (i = 0; i < 4; i++)
+		mask[i] = my_mask[i];
+}
+
+void net_get_gateway(unsigned char gw[4])
+{
+	unsigned int i;
+	for (i = 0; i < 4; i++)
+		gw[i] = my_gw[i];
+}
+
+int net_is_configured(void)
+{
+	return my_ip[0] || my_ip[1] || my_ip[2] || my_ip[3];
+}
+
 int net_parse_ip(const char *s, unsigned char ip[4])
 {
 	unsigned int i, val = 0, nparts = 0;
@@ -130,8 +169,124 @@ void net_print_ip(void)
 	print_ip(my_ip);
 }
 
-/* ---- ethertype naming ---- */
+/* ---- UDP send/parse (used by netlog, netkexec and the DHCP client) ---- */
+
+static unsigned char udp_frame[14 + 20 + 8 + NET_UDP_MAX];
 
+int net_udp_send_from(const unsigned char *src_ip,
+		      const unsigned char *dst_mac, const unsigned char *dst_ip,
+		      unsigned int src_port, unsigned int dst_port,
+		      const void *payload, unsigned int len)
+{
+	const struct netdev *nd = netdev_active();
+	unsigned char my_mac[6];
+	unsigned char *ip = udp_frame + 14;
+	unsigned char *udp = ip + 20;
+	unsigned short cs;
+	unsigned int i, total = 20 + 8 + len;
+	const unsigned char *p = (const unsigned char *)payload;
+
+	if (!nd || len > NET_UDP_MAX)
+		return -1;
+	nd->get_mac(my_mac);
+
+	for (i = 0; i < 6; i++)
+		udp_frame[i] = dst_mac[i];
+	for (i = 0; i < 6; i++)
+		udp_frame[6 + i] = my_mac[i];
+	udp_frame[12] = 0x08;
+	udp_frame[13] = 0x00;
+
+	for (i = 0; i < 20; i++)
+		ip[i] = 0;
+	ip[0] = 0x45;
+	ip[2] = (unsigned char)(total >> 8);
+	ip[3] = (unsigned char)(total & 0xFF);
+	ip[8] = 64;
+	ip[9] = IPPROTO_UDP;
+	for (i = 0; i < 4; i++)
+		ip[12 + i] = src_ip[i];
+	for (i = 0; i < 4; i++)
+		ip[16 + i] = dst_ip[i];
+	cs = net_checksum(ip, 20);
+	ip[10] = (unsigned char)(cs >> 8);
+	ip[11] = (unsigned char)(cs & 0xFF);
+
+	udp[0] = (unsigned char)(src_port >> 8);
+	udp[1] = (unsigned char)(src_port & 0xFF);
+	udp[2] = (unsigned char)(dst_port >> 8);
+	udp[3] = (unsigned char)(dst_port & 0xFF);
+	udp[4] = (unsigned char)((8 + len) >> 8);
+	udp[5] = (unsigned char)((8 + len) & 0xFF);
+	udp[6] = 0;   /* checksum disabled (allowed for IPv4) */
+	udp[7] = 0;
+	for (i = 0; i < len; i++)
+		udp[8 + i] = p[i];
+
+	return nd->tx(udp_frame, 14 + total);
+}
+
+int net_udp_send(const unsigned char *dst_mac, const unsigned char *dst_ip,
+		 unsigned int src_port, unsigned int dst_port,
+		 const void *payload, unsigned int len)
+{
+	unsigned char my_ip[4];
+
+	net_get_ip(my_ip);
+	return net_udp_send_from(my_ip, dst_mac, dst_ip, src_port, dst_port,
+				 payload, len);
+}
+
+int net_udp_parse(const unsigned char *f, unsigned int len,
+		  unsigned char src_ip[4], unsigned char dst_ip[4],
+		  unsigned int *src_port, unsigned int *dst_port,
+		  const unsigned char **payload, unsigned int *plen)
+{
+	const unsigned char *ip = f + 14;
+	const unsigned char *udp;
+	unsigned char my_ip[4];
+	unsigned int i, ihl, ip_len;
+	int dst_ok = 0, dst_bcast = 1;
+
+	if (len < 14 + 20 + 8)
+		return 0;
+	if ((((unsigned int)f[12] << 8) | f[13]) != ET_IPV4)
+		return 0;
+	if ((ip[0] >> 4) != 4)
+		return 0;
+	ihl = (unsigned int)(ip[0] & 0x0F) * 4;
+	if (ihl < 20 || ip[9] != IPPROTO_UDP)
+		return 0;
+	ip_len = ((unsigned int)ip[2] << 8) | ip[3];
+	if (ip_len < ihl + 8 || 14 + ip_len > len)
+		return 0;
+
+	/* Accept datagrams for us or for the broadcast address (a DHCP client
+	 * has no address yet). */
+	net_get_ip(my_ip);
+	dst_ok = 1;
+	for (i = 0; i < 4; i++) {
+		if (ip[16 + i] != my_ip[i])
+			dst_ok = 0;
+		if (ip[16 + i] != 0xFF)
+			dst_bcast = 0;
+	}
+	if (!dst_ok && !dst_bcast)
+		return 0;
+
+	udp = ip + ihl;
+	for (i = 0; i < 4; i++) {
+		src_ip[i] = ip[12 + i];
+		dst_ip[i] = ip[16 + i];
+	}
+	*src_port = ((unsigned int)udp[0] << 8) | udp[1];
+	*dst_port = ((unsigned int)udp[2] << 8) | udp[3];
+	*payload = udp + 8;
+	*plen = ip_len - ihl - 8;
+	return 1;
+}
+
+/* ---- ethertype naming ---- */
 const char *net_ethertype_name(unsigned short et)
 {
 	switch (et) {
@@ -219,10 +374,9 @@ int net_build_reply(const unsigned char *frame, unsigned int len,
 		return 0;
 	et = ((unsigned short)frame[12] << 8) | frame[13];
 
-	ne2000_get_mac(mac);
+	netdev_get_mac(mac);
 
-	/* ARP request for our IP -> ARP reply. */
-	if (et == ET_ARP && len >= 14 + 28) {
+	/* ARP request for our IP -> ARP reply. */	if (et == ET_ARP && len >= 14 + 28) {
 		const unsigned char *a = frame + 14;
 		unsigned short op = ((unsigned short)a[6] << 8) | a[7];
 
@@ -325,12 +479,12 @@ int net_build_reply(const unsigned char *frame, unsigned int len,
 		ric[2] = 0; ric[3] = 0;
 
 		{
-			unsigned short cs = checksum(rip, ihl);
+			unsigned short cs = net_checksum(rip, ihl);
 			rip[10] = (unsigned char)(cs >> 8);
 			rip[11] = (unsigned char)(cs & 0xFF);
 		}
 		{
-			unsigned short cs = checksum(ric, icmp_len);
+			unsigned short cs = net_checksum(ric, icmp_len);
 			ric[2] = (unsigned char)(cs >> 8);
 			ric[3] = (unsigned char)(cs & 0xFF);
 		}

+ 37 - 1
net.h

@@ -1,4 +1,4 @@
-/* Minimal network stack: ARP + ICMP echo (ping) over the NE2000 driver.
+/* Minimal network stack: ARP + ICMP echo (ping) over a netdev NIC.
    Parsing, decoding, reply generation, and the card's IPv4 address. */
 #ifndef NET_H
 #define NET_H
@@ -22,8 +22,44 @@ void net_get_ip(unsigned char ip[4]);
 int  net_parse_ip(const char *s, unsigned char ip[4]);  /* 0 on success, -1 on error */
 void net_print_ip(void);
 
+/* Full configuration (mask/gateway stay zero when unknown).  net_set_ip()
+ * keeps the manual override semantics and clears mask/gateway; DHCP uses
+ * net_configure(). */
+void net_configure(const unsigned char ip[4], const unsigned char mask[4],
+		   const unsigned char gw[4]);
+void net_get_mask(unsigned char mask[4]);
+void net_get_gateway(unsigned char gw[4]);
+int  net_is_configured(void);   /* ip != 0.0.0.0 */
+
 const char *net_ethertype_name(unsigned short et);
 
+/* Internet checksum (16-bit one's complement, network byte order). */
+unsigned short net_checksum(const void *data, unsigned int len);
+
+/* Largest UDP payload net_udp_send() accepts. */
+#define NET_UDP_MAX 1400
+
+/* Send one UDP datagram (IPv4, checksum disabled) in a single Ethernet frame
+ * to dst_mac/dst_ip, with the configured source address.  Returns 0 on
+ * success, -1 on error. */
+int net_udp_send(const unsigned char *dst_mac, const unsigned char *dst_ip,
+		 unsigned int src_port, unsigned int dst_port,
+		 const void *payload, unsigned int len);
+
+/* Same, but with an explicit source address (DHCP uses 0.0.0.0). */
+int net_udp_send_from(const unsigned char *src_ip,
+		      const unsigned char *dst_mac, const unsigned char *dst_ip,
+		      unsigned int src_port, unsigned int dst_port,
+		      const void *payload, unsigned int len);
+
+/* Parse one Ethernet frame as a UDP datagram addressed to us or to the
+ * broadcast address.  Fills the addresses/ports and the payload location.
+ * Returns 1 on match. */
+int net_udp_parse(const unsigned char *frame, unsigned int len,
+		  unsigned char src_ip[4], unsigned char dst_ip[4],
+		  unsigned int *src_port, unsigned int *dst_port,
+		  const unsigned char **payload, unsigned int *plen);
+
 /* Print one decoded frame summary line (dst/src/ethertype + ARP/IP/ICMP). */
 void net_decode_frame(const unsigned char *frame, unsigned int len);
 

+ 469 - 18
netcmd.c

@@ -1,8 +1,9 @@
-/* Network test commands: netinfo, netrecv, netsend, netip, ping. */
+/* Network commands: netinfo, netrecv, netsend, netip, ping (responder) and
+ * netping (active ARP + ICMP echo), over the netdev NIC layer. */
 
 #include "io.h"
 #include "timer.h"
-#include "ne2000.h"
+#include "netdev.h"
 #include "net.h"
 
 /* Shared frame buffers (file scope, not stack: the 4 KB process stack can't
@@ -37,32 +38,89 @@ static void put_dec(unsigned int v)
 		io_putchar(b[--i]);
 }
 
+static void put_mac(const unsigned char *m)
+{
+	unsigned int i;
+	for (i = 0; i < 6; i++) {
+		if (i)
+			io_putchar(':');
+		put_hex2(m[i]);
+	}
+}
+
+static void put_ip(const unsigned char *ip)
+{
+	unsigned int i;
+	for (i = 0; i < 4; i++) {
+		if (i)
+			io_putchar('.');
+		put_dec(ip[i]);
+	}
+}
+
+static int ip_eq(const unsigned char *a, const unsigned char *b)
+{
+	return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3];
+}
+
+/* ---- netinfo ---- */
+
 void program_netinfo_main(void)
 {
-	ne2000_init();
-	ne2000_print_info();
-	if (ne2000_present()) {
-		io_putstr("ip=");
-		net_print_ip();
+	const struct netdev *nd = netdev_active();
+
+	if (!nd) {
+		io_putstr("netinfo: no NIC found\n");
+		return;
+	}
+	io_putstr("netdev: ");
+	io_putstr(nd->name);
+	io_putstr(" (");
+	io_putstr(nd->chip);
+	io_putstr(")\n");
+	nd->print_info();
+	io_putstr("ip=");
+	net_print_ip();
+	io_putchar('\n');
+}
+
+/* ---- netregs: driver register dump ---- */
+
+void program_netregs_main(void)
+{
+	const struct netdev *nd = netdev_active();
+
+	if (!nd) {
+		io_putstr("netregs: no NIC found\n");
+		return;
+	}
+	if (!nd->dump_regs) {
+		io_putstr("netregs: no register dump for ");
+		io_putstr(nd->name);
 		io_putchar('\n');
+		return;
 	}
+	nd->dump_regs();
 }
 
+/* ---- netrecv ---- */
+
 void program_netrecv_main(void)
 {
+	const struct netdev *nd = netdev_active();
 	unsigned int deadline, count = 0;
 
-	ne2000_init();
-	if (!ne2000_present()) {
+	if (!nd) {
 		io_putstr("netrecv: no NIC found\n");
 		return;
 	}
 
 	io_putstr("netrecv: listening (8s)...\n");
+	netdev_acquire();
 	deadline = get_ticks_ms() + 8000;
 
 	while (get_ticks_ms() < deadline) {
-		int len = ne2000_rx(net_rx_buf, NET_FRAME_MAX);
+		int len = nd->rx(net_rx_buf, NET_FRAME_MAX);
 		unsigned int i;
 
 		if (len < 0)
@@ -88,21 +146,24 @@ void program_netrecv_main(void)
 	io_putstr("netrecv: ");
 	put_dec(count);
 	io_putstr(" frame(s)\n");
+	netdev_release();
 }
 
+/* ---- netsend ---- */
+
 void program_netsend_main(void)
 {
+	const struct netdev *nd = netdev_active();
 	unsigned char frame[64];
 	unsigned char mac[6];
 	unsigned int i;
 
-	ne2000_init();
-	if (!ne2000_present()) {
+	if (!nd) {
 		io_putstr("netsend: no NIC found\n");
 		return;
 	}
 
-	ne2000_get_mac(mac);
+	nd->get_mac(mac);
 
 	/* Broadcast test frame: dst=ff:ff:ff:ff:ff:ff, src=our MAC,
 	   ethertype 0x88B5 (local experimental), payload "NEBS". */
@@ -119,13 +180,15 @@ void program_netsend_main(void)
 	for (i = 18; i < 64; i++)
 		frame[i] = 0x00;
 
-	if (ne2000_tx(frame, sizeof(frame)) != 0) {
+	if (nd->tx(frame, sizeof(frame)) != 0) {
 		io_putstr("netsend: transmit failed\n");
 		return;
 	}
 	io_putstr("netsend: sent 64-byte broadcast frame\n");
 }
 
+/* ---- netip ---- */
+
 void program_netip_main(const char *arg)
 {
 	unsigned char ip[4];
@@ -147,12 +210,14 @@ void program_netip_main(const char *arg)
 	io_putchar('\n');
 }
 
+/* ---- ping: answer ARP/ICMP for our IP (responder mode) ---- */
+
 void program_ping_main(void)
 {
+	const struct netdev *nd = netdev_active();
 	unsigned int deadline, count = 0;
 
-	ne2000_init();
-	if (!ne2000_present()) {
+	if (!nd) {
 		io_putstr("ping: no NIC found\n");
 		return;
 	}
@@ -160,10 +225,11 @@ void program_ping_main(void)
 	io_putstr("ping: answering ARP/ICMP for 30s (ip=");
 	net_print_ip();
 	io_putstr(")...\n");
+	netdev_acquire();
 
 	deadline = get_ticks_ms() + 30000;
 	while (get_ticks_ms() < deadline) {
-		int len = ne2000_rx(net_rx_buf, NET_FRAME_MAX);
+		int len = nd->rx(net_rx_buf, NET_FRAME_MAX);
 		int rlen;
 
 		if (len < 0)
@@ -172,7 +238,7 @@ void program_ping_main(void)
 		rlen = net_build_reply(net_rx_buf, (unsigned int)len,
 				       net_reply_buf, NET_FRAME_MAX);
 		if (rlen > 0) {
-			if (ne2000_tx(net_reply_buf, (unsigned int)rlen) == 0) {
+			if (nd->tx(net_reply_buf, (unsigned int)rlen) == 0) {
 				io_putstr("reply: ");
 				net_decode_frame(net_reply_buf, (unsigned int)rlen);
 				io_putchar('\n');
@@ -184,4 +250,389 @@ void program_ping_main(void)
 	io_putstr("ping: done (");
 	put_dec(count);
 	io_putstr(" replies)\n");
+	netdev_release();
+}
+
+/* ---- netreset: ask the driver for a full NIC re-init ---- */
+
+void program_netreset_main(void)
+{
+	const struct netdev *nd = netdev_active();
+
+	if (!nd) {
+		io_putstr("netreset: no NIC found\n");
+		return;
+	}
+	if (!nd->reset) {
+		io_putstr("netreset: not supported by ");
+		io_putstr(nd->name);
+		io_putchar('\n');
+		return;
+	}
+	io_putstr("netreset: re-initializing ");
+	io_putstr(nd->name);
+	io_putstr("...\n");
+	nd->reset();
+	nd->print_info();
+}
+
+/* ---- netloop: PHY loopback self-test (no cable/peer needed) ---- */
+
+static void netloop_run(void)
+{
+	const struct netdev *nd = netdev_active();
+	unsigned char frame[64], mac[6];
+	unsigned int i, deadline;
+	int got = 0;
+
+	if (!nd) {
+		io_putstr("netloop: no NIC found\n");
+		return;
+	}
+	if (!nd->set_loopback) {
+		io_putstr("netloop: not supported by ");
+		io_putstr(nd->name);
+		io_putchar('\n');
+		return;
+	}
+
+	nd->get_mac(mac);
+	for (i = 0; i < 6; i++)
+		frame[i] = 0xFF;                      /* broadcast */
+	for (i = 0; i < 6; i++)
+		frame[6 + i] = mac[i];
+	frame[12] = 0x88;
+	frame[13] = 0xB6;                             /* local experimental */
+	frame[14] = 'N'; frame[15] = 'E'; frame[16] = 'B';
+	frame[17] = 'O'; frame[18] = 'S'; frame[19] = 'L';
+	frame[20] = 'O'; frame[21] = 'O';
+	for (i = 22; i < 64; i++)
+		frame[i] = 0x00;
+
+	io_putstr("netloop: PHY loopback on, sending...\n");
+	nd->set_loopback(1);
+
+	if (nd->tx(frame, sizeof(frame)) != 0) {
+		io_putstr("netloop: transmit failed\n");
+		nd->set_loopback(0);
+		return;
+	}
+
+	deadline = get_ticks_ms() + 1000;
+	while (get_ticks_ms() < deadline) {
+		int len = nd->rx(net_rx_buf, NET_FRAME_MAX);
+
+		if (len < 0)
+			continue;
+		if (len >= 22 &&
+		    net_rx_buf[12] == 0x88 && net_rx_buf[13] == 0xB6 &&
+		    net_rx_buf[14] == 'N' && net_rx_buf[15] == 'E' &&
+		    net_rx_buf[16] == 'B' && net_rx_buf[17] == 'O' &&
+		    net_rx_buf[18] == 'S') {
+			got = 1;
+			break;
+		}
+	}
+
+	nd->set_loopback(0);
+
+	io_putstr(got ? "netloop: PASS (frame came back)\n"
+		      : "netloop: FAIL (no frame came back)\n");
+}
+
+void program_netloop_main(void)
+{
+	netdev_acquire();
+	netloop_run();
+	netdev_release();
+}
+
+/* ---- netping: active ARP + ICMP echo ---- */
+
+#define NETPING_COUNT  4
+#define NETPING_ID     0x4E42   /* "NB" */
+#define NETPING_WAIT_MS 1000
+
+static unsigned int netping_sent_ms[NETPING_COUNT];
+
+/* ARP request "who has target? tell my_ip" -> 42-byte frame. */
+static unsigned int build_arp_request(const unsigned char *my_mac,
+				      const unsigned char *my_ip,
+				      const unsigned char *target_ip,
+				      unsigned char *out)
+{
+	unsigned char *a = out + 14;
+	unsigned int i;
+
+	for (i = 0; i < 6; i++)
+		out[i] = 0xFF;                        /* broadcast */
+	for (i = 0; i < 6; i++)
+		out[6 + i] = my_mac[i];
+	out[12] = 0x08;
+	out[13] = 0x06;
+	a[0] = 0; a[1] = 1;                           /* htype Ethernet */
+	a[2] = 0x08; a[3] = 0;                        /* ptype IPv4 */
+	a[4] = 6; a[5] = 4;
+	a[6] = 0; a[7] = 1;                           /* opcode request */
+	for (i = 0; i < 6; i++)                       /* sha */
+		a[8 + i] = my_mac[i];
+	for (i = 0; i < 4; i++)                       /* spa */
+		a[14 + i] = my_ip[i];
+	for (i = 0; i < 6; i++)                       /* tha */
+		a[18 + i] = 0;
+	for (i = 0; i < 4; i++)                       /* tpa */
+		a[24 + i] = target_ip[i];
+	return 42;
+}
+
+/* 1 + peer MAC if frame is an ARP reply from target_ip. */
+static int parse_arp_reply(const unsigned char *f, unsigned int len,
+			   const unsigned char *target_ip, unsigned char *mac)
+{
+	const unsigned char *a = f + 14;
+	unsigned int i;
+
+	if (len < 14 + 28)
+		return 0;
+	if ((((unsigned int)f[12] << 8) | f[13]) != ET_ARP)
+		return 0;
+	if ((((unsigned int)a[6] << 8) | a[7]) != 2)   /* opcode reply */
+		return 0;
+	if (a[4] != 6 || a[5] != 4)
+		return 0;
+	if (!ip_eq(a + 14, target_ip))                 /* sender IP == target */
+		return 0;
+	for (i = 0; i < 6; i++)
+		mac[i] = a[8 + i];
+	return 1;
+}
+
+/* ICMP echo request (14 + 20 + 16 bytes; the driver pads to 60). */
+static unsigned int build_icmp_echo(const unsigned char *src_mac,
+				    const unsigned char *dst_mac,
+				    const unsigned char *src_ip,
+				    const unsigned char *dst_ip,
+				    unsigned short seq, unsigned char *out)
+{
+	unsigned char *ip = out + 14;
+	unsigned char *ic = ip + 20;
+	unsigned char *pl = ic + 8;
+	unsigned short cs;
+	unsigned int i;
+
+	for (i = 0; i < 6; i++)
+		out[i] = dst_mac[i];
+	for (i = 0; i < 6; i++)
+		out[6 + i] = src_mac[i];
+	out[12] = 0x08;
+	out[13] = 0x00;
+
+	for (i = 0; i < 20; i++)
+		ip[i] = 0;
+	ip[0] = 0x45;
+	ip[2] = 0; ip[3] = 36;                        /* total length */
+	ip[8] = 64;                                   /* TTL */
+	ip[9] = IPPROTO_ICMP;
+	for (i = 0; i < 4; i++)
+		ip[12 + i] = src_ip[i];
+	for (i = 0; i < 4; i++)
+		ip[16 + i] = dst_ip[i];
+	cs = net_checksum(ip, 20);
+	ip[10] = (unsigned char)(cs >> 8);
+	ip[11] = (unsigned char)(cs & 0xFF);
+
+	ic[0] = ICMP_ECHO_REQUEST;
+	ic[1] = 0;
+	ic[2] = 0; ic[3] = 0;
+	ic[4] = (unsigned char)(NETPING_ID >> 8);
+	ic[5] = (unsigned char)(NETPING_ID & 0xFF);
+	ic[6] = (unsigned char)(seq >> 8);
+	ic[7] = (unsigned char)(seq & 0xFF);
+	pl[0] = 'n'; pl[1] = 'e'; pl[2] = 'b'; pl[3] = 'o';
+	pl[4] = 's'; pl[5] = 0; pl[6] = 0; pl[7] = 0;
+	cs = net_checksum(ic, 16);
+	ic[2] = (unsigned char)(cs >> 8);
+	ic[3] = (unsigned char)(cs & 0xFF);
+
+	return 14 + 20 + 16;
+}
+
+/* 1 + ICMP echo-reply seq for our IP from peer_ip. */
+static int parse_icmp_reply(const unsigned char *f, unsigned int len,
+			    const unsigned char *my_ip,
+			    const unsigned char *peer_ip,
+			    unsigned short *seq)
+{
+	const unsigned char *ip = f + 14;
+	const unsigned char *ic;
+	unsigned int ihl;
+	unsigned short ip_len, id;
+
+	if (len < 14 + 20)
+		return 0;
+	if ((((unsigned int)f[12] << 8) | f[13]) != ET_IPV4)
+		return 0;
+	if ((ip[0] >> 4) != 4)
+		return 0;
+	ihl = (unsigned int)(ip[0] & 0x0F) * 4;
+	if (ihl < 20 || ip[9] != IPPROTO_ICMP)
+		return 0;
+	ip_len = ((unsigned short)ip[2] << 8) | ip[3];
+	if (ip_len < ihl + 8 || (unsigned int)ip_len > len - 14)
+		return 0;
+	if (!ip_eq(ip + 12, peer_ip))                 /* src == peer */
+		return 0;
+	if (!ip_eq(ip + 16, my_ip))                   /* dst == us */
+		return 0;
+	ic = ip + ihl;
+	if (ic[0] != ICMP_ECHO_REPLY || ic[1] != 0)
+		return 0;
+	id = ((unsigned short)ic[4] << 8) | ic[5];
+	if (id != NETPING_ID)
+		return 0;
+	*seq = ((unsigned short)ic[6] << 8) | ic[7];
+	if (*seq < 1 || *seq > NETPING_COUNT)
+		return 0;
+	return 1;
+}
+
+/* Resolve target_ip's MAC by ARP (3 tries, 1 s each).
+ * Returns 0 = resolved, -1 = no reply, -2 = transmit failed.
+ * Prints the frames seen while waiting (capped) so a silent peer, a filtered
+ * reply and a reply we refuse to parse can be told apart on screen. */
+static int netping_arp(const struct netdev *nd, const unsigned char *my_mac,
+		       const unsigned char *my_ip, const unsigned char *target_ip,
+		       unsigned char *target_mac)
+{
+	unsigned char frame[64];
+	unsigned int tries, seen = 0;
+
+	for (tries = 0; tries < 3; tries++) {
+		unsigned int deadline = get_ticks_ms() + NETPING_WAIT_MS;
+		unsigned int flen = build_arp_request(my_mac, my_ip, target_ip, frame);
+
+		if (nd->tx(frame, flen) != 0)
+			return -2;
+		io_putstr("netping: ARP request sent (try ");
+		put_dec(tries + 1);
+		io_putstr("/3)\n");
+		while (get_ticks_ms() < deadline) {
+			int len = nd->rx(net_rx_buf, NET_FRAME_MAX);
+
+			if (len < 0)
+				continue;
+			if (seen < 8) {
+				io_putstr("netping: rx ");
+				net_decode_frame(net_rx_buf, (unsigned int)len);
+				io_putchar('\n');
+				seen++;
+			}
+			if (parse_arp_reply(net_rx_buf, (unsigned int)len,
+					    target_ip, target_mac))
+				return 0;
+		}
+	}
+	io_putstr("netping: saw ");
+	put_dec(seen);
+	io_putstr(" frame(s) while waiting\n");
+	return -1;
+}
+
+static void netping_run(const char *arg)
+{
+	const struct netdev *nd;
+	unsigned char target[4], my_ip[4], my_mac[6], target_mac[6];
+	unsigned int i, replies = 0;
+
+	if (arg[0] == '\0' || net_parse_ip(arg, target) != 0) {
+		io_putstr("netping: usage netping <a.b.c.d>\n");
+		return;
+	}
+
+	nd = netdev_active();
+	if (!nd) {
+		io_putstr("netping: no NIC found\n");
+		return;
+	}
+	nd->get_mac(my_mac);
+	net_get_ip(my_ip);
+
+	{
+		int r = netping_arp(nd, my_mac, my_ip, target, target_mac);
+
+		if (r == -2) {
+			io_putstr("netping: transmit failed (see netregs)\n");
+			return;
+		}
+		if (r != 0) {
+			io_putstr("netping: no ARP reply from ");
+			put_ip(target);
+			io_putchar('\n');
+			return;
+		}
+	}
+
+	io_putstr("netping: ");
+	put_ip(target);
+	io_putstr(" is-at ");
+	put_mac(target_mac);
+	io_putchar('\n');
+
+	for (i = 0; i < NETPING_COUNT; i++) {
+		unsigned char frame[64];
+		unsigned int flen, deadline;
+		int got = 0;
+
+		flen = build_icmp_echo(my_mac, target_mac, my_ip, target,
+				       (unsigned short)(i + 1), frame);
+		netping_sent_ms[i] = get_ticks_ms();
+		if (nd->tx(frame, flen) != 0) {
+			io_putstr("netping: transmit failed\n");
+			return;
+		}
+
+		deadline = get_ticks_ms() + NETPING_WAIT_MS;
+		while (get_ticks_ms() < deadline && !got) {
+			unsigned short seq;
+			int len = nd->rx(net_rx_buf, NET_FRAME_MAX);
+			unsigned int rtt;
+
+			if (len < 0)
+				continue;
+			if (!parse_icmp_reply(net_rx_buf, (unsigned int)len,
+					      my_ip, target, &seq))
+				continue;
+			rtt = get_ticks_ms() - netping_sent_ms[seq - 1];
+			io_putstr("reply: seq=");
+			put_dec(seq);
+			io_putstr(" rtt=");
+			if (rtt == 0)
+				io_putstr("<1");
+			else
+				put_dec(rtt);
+			io_putstr("ms\n");
+			got = 1;
+			replies++;
+		}
+		if (!got) {
+			io_putstr("netping: timeout, seq=");
+			put_dec(i + 1);
+			io_putchar('\n');
+		}
+	}
+
+	io_putstr("netping: ");
+	put_dec(replies);
+	io_putstr("/");
+	put_dec(NETPING_COUNT);
+	io_putstr(" replies from ");
+	put_ip(target);
+	io_putchar('\n');
+}
+
+void program_netping_main(const char *arg)
+{
+	netdev_acquire();
+	netping_run(arg);
+	netdev_release();
 }

+ 61 - 0
netdev.c

@@ -0,0 +1,61 @@
+/* NIC driver registry: see netdev.h. */
+
+#include "netdev.h"
+#include "ne2000.h"
+#include "r8168.h"
+static const struct netdev *const netdev_drivers[] = {
+	/* PCIe Gigabit first: on the AT3IONT-I this is the real NIC, while
+	 * the NE2000 only exists under QEMU/ISA-era hardware. */
+	&r8168_netdev,
+	&ne2000_netdev,
+};
+
+static const struct netdev *active;
+static int probed;
+static unsigned int busy;
+
+void netdev_acquire(void)
+{
+	busy++;
+}
+
+void netdev_release(void)
+{
+	if (busy)
+		busy--;
+}
+
+int netdev_in_use(void)
+{
+	return busy != 0;
+}
+
+const struct netdev *netdev_active(void)
+{
+	unsigned int i;
+
+	if (!probed) {
+		probed = 1;
+		for (i = 0; i < sizeof(netdev_drivers) / sizeof(netdev_drivers[0]); i++) {
+			if (netdev_drivers[i]->init() == 0) {
+				active = netdev_drivers[i];
+				break;
+			}
+		}
+	}
+	return active;
+}
+
+int netdev_get_mac(unsigned char mac[6])
+{
+	const struct netdev *nd = netdev_active();
+	unsigned int i;
+
+	if (!nd) {
+		for (i = 0; i < 6; i++)
+			mac[i] = 0;
+		return -1;
+	}
+	nd->get_mac(mac);
+	return 0;
+}

+ 36 - 0
netdev.h

@@ -0,0 +1,36 @@
+/* Network device interface: one struct per NIC driver, shared by the network
+ * stack (net.c) and the net* shell commands (netcmd.c).
+ *
+ * Drivers are registered in the table in netdev.c (first match wins); add new
+ * ones there.  Everything here is polled, matching the rest of the kernel. */
+#ifndef NETDEV_H
+#define NETDEV_H
+
+struct netdev {
+	const char *name;    /* short driver name, e.g. "ne2000" */
+	const char *chip;    /* detected chip, e.g. "RTL8029AS" */
+	int  (*init)(void);  /* probe + bring up: 0 = ready, -1 = not present */
+	void (*get_mac)(unsigned char mac[6]);
+	int  (*rx)(unsigned char *buf, unsigned int maxlen);    /* len, or -1 */
+	int  (*tx)(const unsigned char *buf, unsigned int len); /* 0, or -1 */
+	void (*print_info)(void);   /* status lines (MAC, link, ...) */
+	void (*dump_regs)(void);    /* register dump; may be NULL */
+	int  (*set_loopback)(int on);   /* PHY loopback for self-test; may be NULL */
+	void (*reset)(void);        /* full NIC re-init (recover from a stall); may be NULL */
+};
+
+/* First registered driver that probes successfully (probe result is cached);
+ * NULL when no NIC is present. */
+const struct netdev *netdev_active(void);
+
+/* Busy gate for commands that poll the NIC for a while (netrecv, ping,
+ * netping, netloop, netkexec): the background kexec watcher must not steal
+ * frames while one of them owns the receiver. */
+void netdev_acquire(void);
+void netdev_release(void);
+int  netdev_in_use(void);
+
+/* Fill the active NIC's MAC; -1 (and a zero MAC) when there is no NIC. */
+int netdev_get_mac(unsigned char mac[6]);
+
+#endif

+ 1089 - 0
r8168.c

@@ -0,0 +1,1089 @@
+/* Realtek RTL8111/8168 Gigabit Ethernet driver (C+ mode, 8168c/d/e class).
+ *
+ * Target chip: the RTL8112L on the ASUS AT3IONT-I -- PCI 10ec:8168 rev 03,
+ * register window in BAR2 (64-bit, 4 KB, prefetchable).  Polled: no IRQ.
+ * TX/RX use 16-byte descriptors the NIC DMAs to/from memory; register and
+ * descriptor values mirror the r8169 sequence from Linux.
+ *
+ * Every wait is time-bounded and each bring-up step writes a kdbg info row
+ * (and serial), because the target machine has no serial console: a wedged
+ * driver must still be diagnosable from the screen (progress row + PIT
+ * heartbeat).
+ */
+
+#include "io.h"
+#include "kdbg.h"
+#include "mm.h"
+#include "netdev.h"
+#include "paging.h"
+#include "pci.h"
+#include "process.h"
+#include "serial.h"
+#include "timer.h"
+#include "r8168.h"
+
+/* ---- chip registers (offsets into the MMIO window) ---- */
+#define REG_MAC0         0x00
+#define REG_TxDescLow    0x20
+#define REG_TxDescHigh   0x24
+#define REG_ChipCmd      0x37
+#define REG_TxPoll       0x38
+#define REG_IntrMask     0x3c
+#define REG_IntrStatus   0x3e
+#define REG_TxConfig     0x40   /* also carries the chip version (XID) */
+#define REG_RxConfig     0x44
+#define REG_Cfg9346      0x50
+#define REG_PHYAR        0x60
+#define REG_PHYstatus    0x6c
+#define REG_RDSAR1       0xd0   /* RX ring high 32 bits (8168c only) */
+#define REG_RxMaxSize    0xda
+#define REG_CPlusCmd     0xe0
+#define REG_IntrMitigate 0xe2
+#define REG_RxDescLow    0xe4
+#define REG_RxDescHigh   0xe8
+#define REG_MaxTxPacket  0xec
+
+/* ChipCmd bits. */
+#define ChipCmd_Reset    0x10
+#define ChipCmd_RxEnb    0x08
+#define ChipCmd_TxEnb    0x04
+
+#define Cfg9346_Unlock   0xC0
+
+/* TxPoll: kick the normal priority queue. */
+#define TxPoll_NPQ       0x40
+
+/* TxConfig: max PCI burst + shortest inter-frame gap. */
+#define TXCONFIG_VALUE   ((7 << 8) | (3 << 24))
+
+/* RxConfig. */
+#define RX_DMA_BURST     0x0700
+#define RX128_INT_EN     0x8000
+#define RX_ACCEPT_MASK   0x3f
+#define RX_ACCEPT_BROADCAST 0x08
+#define RX_ACCEPT_MULTICAST 0x04
+#define RX_ACCEPT_MYPHYS    0x02
+#define RX_ACCEPT_ALLPHYS   0x01   /* promiscuous (bring-up: see set_rx_mode) */
+
+/* PHYstatus (0x6c). */
+#define PHYST_LINK       0x02
+#define PHYST_FULLDUP    0x01
+#define PHYST_1000       0x10
+#define PHYST_100        0x08
+#define PHYST_10         0x04
+
+/* PHYAR: bit 31 = busy/valid, reg in bits 20:16, data in 15:0. */
+#define PHYAR_FLAG       0x80000000u
+
+/* Interrupt/event status bits (IntrStatus, 0x3e).  The register latches
+ * events; each bit is cleared by writing it back.  With IntrMask = 0 we only
+ * use these as a diagnostic and to detect an RX stall. */
+#define ISR_RxOK         0x0001
+#define ISR_RxErr        0x0002
+#define ISR_TxOK         0x0004
+#define ISR_TxErr        0x0008
+#define ISR_ROVW         0x0010   /* RX FIFO overflow */
+#define ISR_LinkChg      0x0020
+#define ISR_FOV          0x0040   /* RX FIFO overflow (8168) */
+#define ISR_TDU          0x0080   /* TX descriptor unavailable */
+#define ISR_SWInt        0x0100
+
+/* PHY registers. */
+#define MII_BMCR         0
+#define MII_BMSR         1
+#define MII_PHYSID1      2
+#define MII_PHYSID2      3
+#define MII_ANAR         4
+#define MII_GBSR         9
+
+#define BMCR_AUTONEG     0x1000
+#define BMCR_RESTART_AN  0x0200
+#define BMSR_LINK        0x0004
+
+/* Descriptor bits (C+ mode). */
+#define DescOwn          0x80000000u
+#define DescRingEnd      0x40000000u
+#define DescFirstFrag    0x20000000u
+#define DescLastFrag     0x10000000u
+#define RxRES            (1u << 21)   /* RX error summary */
+#define RxPktLenMask     0x3fffu      /* length field, includes the FCS */
+
+/* Rings. */
+#define R8168_NTX        16
+#define R8168_NRX        16
+#define R8168_BUF_SIZE   2048
+#define R8168_RX_ARM     (R8168_BUF_SIZE - 1)
+
+/* PCI ids. */
+#define R8168_VENDOR     0x10ECu
+#define R8168_DEVICE     0x8168u
+
+struct r8168_desc {
+	volatile unsigned int opts1;
+	volatile unsigned int opts2;
+	volatile unsigned int addr_lo;
+	volatile unsigned int addr_hi;
+};
+
+static unsigned char *mmio;
+static int present;
+static int inited;
+static unsigned char mac[6];
+static unsigned int xid;               /* (TxConfig >> 20) & 0xfcf */
+static unsigned int bar_base, bar_size;
+static unsigned int pci_bus, pci_dev, pci_func;
+
+static struct r8168_desc *tx_ring;
+static struct r8168_desc *rx_ring;
+static unsigned char *tx_bufs;
+static unsigned char *rx_bufs;
+static unsigned int tx_cur;
+static unsigned int rx_cur;
+
+/* Counters (mirrored into the kdbg status row). */
+static unsigned int tx_ok, tx_err, rx_ok, rx_err, rx_drop;
+static unsigned int last_tx_status;     /* raw descriptor status after TX */
+static unsigned int isr_last;           /* last IntrStatus value we acked */
+static unsigned int isr_rovw, isr_fov, isr_tdu;
+static unsigned int rx_restarts;
+
+static int kdbg_stat_row = -1;          /* link + counters */
+
+static int timed_out(unsigned int start_ms, unsigned int ms)
+{
+	return get_ticks_ms() - start_ms > ms;
+}
+
+/* ---- MMIO accessors (uncacheable mapping) ---- */
+
+static inline unsigned int r32(unsigned int reg)
+{
+	return *(volatile unsigned int *)(mmio + reg);
+}
+
+static inline void w32(unsigned int reg, unsigned int v)
+{
+	*(volatile unsigned int *)(mmio + reg) = v;
+}
+
+static inline unsigned short r16(unsigned int reg)
+{
+	return *(volatile unsigned short *)(mmio + reg);
+}
+
+static inline void w16(unsigned int reg, unsigned short v)
+{
+	*(volatile unsigned short *)(mmio + reg) = v;
+}
+
+static inline unsigned char r8(unsigned int reg)
+{
+	return *(volatile unsigned char *)(mmio + reg);
+}
+
+static inline void w8(unsigned int reg, unsigned char v)
+{
+	*(volatile unsigned char *)(mmio + reg) = v;
+}
+
+/* Keep the compiler from reordering descriptor/MMIO stores.  x86 caches are
+ * coherent with PCI DMA, so no instruction barrier is needed. */
+static inline void dma_barrier(void)
+{
+	__asm__ volatile ("" ::: "memory");
+}
+
+/* ---- small string/decimal/hex buffer helpers ---- */
+
+static unsigned int app(char *b, unsigned int i, const char *s)
+{
+	while (*s)
+		b[i++] = *s++;
+	return i;
+}
+
+static unsigned int appd(char *b, unsigned int i, unsigned int v)
+{
+	char t[11];
+	unsigned int n = 0;
+
+	if (v > 9999)
+		v = 9999;               /* keep rows short */
+	if (v == 0) {
+		b[i++] = '0';
+		return i;
+	}
+	while (v) {
+		t[n++] = (char)('0' + v % 10);
+		v /= 10;
+	}
+	while (n)
+		b[i++] = t[--n];
+	return i;
+}
+
+static unsigned int apph(char *b, unsigned int i, unsigned int v, unsigned int digits)
+{
+	static const char hex[] = "0123456789ABCDEF";
+	unsigned int d;
+
+	for (d = 0; d < digits; d++)
+		b[i++] = hex[(v >> (4 * (digits - 1 - d))) & 0xF];
+	return i;
+}
+
+/* ---- console printing helpers ---- */
+
+static void put_hex1(unsigned int v)
+{
+	static const char hex[] = "0123456789ABCDEF";
+	io_putchar(hex[v & 0xF]);
+}
+
+static void put_hex2(unsigned int v)
+{
+	put_hex1((v >> 4) & 0xF);
+	put_hex1(v & 0xF);
+}
+
+static void put_hex4(unsigned int v)
+{
+	put_hex2((v >> 8) & 0xFF);
+	put_hex2(v & 0xFF);
+}
+
+static void put_dec(unsigned int v)
+{
+	char b[12];
+	int i = 0;
+
+	if (v == 0) {
+		io_putchar('0');
+		return;
+	}
+	while (v) {
+		b[i++] = (char)('0' + (v % 10));
+		v /= 10;
+	}
+	while (i)
+		io_putchar(b[--i]);
+}
+
+/* ---- debug trail (kdbg rows + serial) ---- */
+
+/* Each step advances to a fresh info row (up to R8168_TRAIL_ROWS) so a photo
+ * of the screen shows the bring-up sequence (PCI -> reset -> ... -> link);
+ * after that the last row is reused, which keeps the most recent step
+ * visible.  The row count is capped because the pool is shared with the MTRR
+ * dump (11 rows on the AT3IONT-I). */
+#define R8168_TRAIL_ROWS 2
+
+static int trail_row = -1;
+static int trail_used;
+
+static void dbg(const char *s)
+{
+	if (trail_row < 0) {
+		trail_row = kdbg_info_alloc();
+		trail_used = 1;
+	} else if (trail_used < R8168_TRAIL_ROWS) {
+		int next = kdbg_info_alloc();
+
+		if (next >= 0) {
+			trail_row = next;
+			trail_used++;
+		}
+	}
+	if (trail_row >= 0)
+		kdbg_info((unsigned int)trail_row, s);
+	serial_puts(SERIAL_COM1, "r8168: ");
+	serial_puts(SERIAL_COM1, s);
+	serial_puts(SERIAL_COM1, "\n");
+}
+
+static const char *chip_name(void)
+{
+	switch (xid & 0x7c8) {
+	case 0x280: return "RTL8168d/8111d";   /* RTL8112L class */
+	case 0x3c0: return "RTL8168c/8111c";
+	case 0x3c8: return "RTL8168cp/8111cp";
+	case 0x380: return "RTL8168b/8111b";
+	case 0x2c0: return "RTL8168e/8111e";
+	default:    return "RTL8168/8111 (unknown rev)";
+	}
+}
+
+/* ---- PHY access via PHYAR ---- */
+
+static int phy_busy(void)
+{
+	unsigned int t0 = get_ticks_ms();
+
+	while (r32(REG_PHYAR) & PHYAR_FLAG) {
+		if (timed_out(t0, 100))
+			return -1;
+	}
+	return 0;
+}
+
+static int mdio_write(unsigned int reg, unsigned int val)
+{
+	if (phy_busy() != 0)
+		return -1;
+	w32(REG_PHYAR, PHYAR_FLAG | ((reg & 0x1f) << 16) | (val & 0xffff));
+	return 0;
+}
+
+static int mdio_read(unsigned int reg)
+{
+	unsigned int t0 = get_ticks_ms();
+
+	if (phy_busy() != 0)
+		return -1;
+	w32(REG_PHYAR, (reg & 0x1f) << 16);
+	while (!(r32(REG_PHYAR) & PHYAR_FLAG)) {
+		if (timed_out(t0, 100))
+			return -1;
+	}
+	return (int)(r32(REG_PHYAR) & 0xffff);
+}
+
+/* ---- status row ---- */
+
+/* "1000M"/"100M"/"10M"/"?" + duplex letter, into out[6]. */
+static void speed_string(unsigned int st, char *out)
+{
+	if (st & PHYST_1000) {
+		out[0] = '1'; out[1] = '0'; out[2] = '0'; out[3] = '0'; out[4] = 'M';
+	} else if (st & PHYST_100) {
+		out[0] = '1'; out[1] = '0'; out[2] = '0'; out[3] = 'M'; out[4] = ' ';
+	} else if (st & PHYST_10) {
+		out[0] = '1'; out[1] = '0'; out[2] = 'M'; out[3] = ' '; out[4] = ' ';
+	} else {
+		out[0] = '?'; out[1] = out[2] = out[3] = out[4] = ' ';
+	}
+	out[5] = '\0';
+}
+
+/* "NIC U 1000MF TX 3/0 RX 5/0" into the kdbg status row. */
+static void status_line(void)
+{
+	char buf[40];
+	unsigned int st = r8(REG_PHYstatus);
+	unsigned int i = 0;
+
+	if (kdbg_stat_row < 0)
+		kdbg_stat_row = kdbg_info_alloc();   /* reserve the row up front */
+
+	if (kdbg_stat_row < 0)
+		return;
+
+	i = app(buf, i, "NIC ");
+	buf[i++] = (st & PHYST_LINK) ? 'U' : 'D';
+	buf[i++] = ' ';
+	{
+		char sp[6];
+		unsigned int j;
+
+		speed_string(st, sp);
+		for (j = 0; sp[j]; j++)
+			buf[i++] = sp[j];
+	}
+	buf[i++] = (st & PHYST_FULLDUP) ? 'F' : 'H';
+	i = app(buf, i, " TX ");
+	i = appd(buf, i, tx_ok);
+	buf[i++] = '/';
+	i = appd(buf, i, tx_err);
+	i = app(buf, i, " RX ");
+	i = appd(buf, i, rx_ok);
+	buf[i++] = '/';
+	i = appd(buf, i, rx_err);
+	buf[i] = '\0';
+
+	if (kdbg_stat_row < 0)
+		kdbg_stat_row = kdbg_info_alloc();
+	if (kdbg_stat_row >= 0)
+		kdbg_info((unsigned int)kdbg_stat_row, buf);
+}
+
+/* Re-arm every RX descriptor and restart the RX engine.  The chip can halt
+ * its RX DMA after a FIFO overflow or when it ran out of descriptors (which
+ * happens when nothing polls for a while, e.g. while a command is printing);
+ * re-asserting CmdRxEnb resumes it. */
+static void rx_restart(void)
+{
+	unsigned int i;
+
+	w8(REG_ChipCmd, ChipCmd_TxEnb);        /* stop RX */
+	for (i = 0; i < 1000; i++)             /* let the engine settle */
+		(void)r8(REG_ChipCmd);
+	for (i = 0; i < R8168_NRX; i++) {
+		rx_ring[i].opts2 = 0;
+		rx_ring[i].addr_lo = (unsigned int)(rx_bufs + i * R8168_BUF_SIZE);
+		rx_ring[i].addr_hi = 0;
+		rx_ring[i].opts1 = DescOwn | R8168_RX_ARM |
+				   (i == R8168_NRX - 1 ? DescRingEnd : 0);
+	}
+	dma_barrier();
+	rx_cur = 0;
+	w8(REG_ChipCmd, ChipCmd_RxEnb | ChipCmd_TxEnb);
+	rx_restarts++;
+}
+
+/* Read + acknowledge latched events; recover from an RX stall. */
+static void isr_poll(void)
+{
+	unsigned int st = r16(REG_IntrStatus);
+
+	if (st == 0)
+		return;
+	w16(REG_IntrStatus, st);               /* write back to clear */
+	isr_last = st;
+	if (st & ISR_ROVW) {
+		isr_rovw++;
+		rx_restart();
+	}
+	if (st & ISR_FOV) {
+		isr_fov++;
+		rx_restart();
+	}
+	if (st & ISR_TDU) {
+		isr_tdu++;
+		w8(REG_TxPoll, TxPoll_NPQ);    /* nudge the TX queue */
+	}
+}
+
+/* ---- PCI probe ---- */
+
+static int bar_is_mmio(unsigned int val)
+{
+	return !(val & 1u) && (val & 0xFFFFFFF0u);
+}
+
+static int probe_pci(void)
+{
+	unsigned int bus, dev, func, bar;
+
+	for (bus = 0; bus < 256; bus++) {
+		for (dev = 0; dev < 32; dev++) {
+			unsigned int id = pci_cfg_read32(bus, dev, 0, 0x00);
+			unsigned int htype, nfunc;
+
+			if (id == 0xFFFFFFFFu || id == 0)
+				continue;
+			/* Multifunction: scan every function. */
+			htype = (pci_cfg_read32(bus, dev, 0, 0x0C) >> 16) & 0xFFu;
+			nfunc = (htype & 0x80u) ? 8u : 1u;
+
+			for (func = 0; func < nfunc; func++) {
+				unsigned int idf = pci_cfg_read32(bus, dev, func, 0x00);
+				unsigned int cmd;
+
+				if (idf == 0xFFFFFFFFu || idf == 0)
+					continue;
+				if ((idf & 0xFFFFu) != R8168_VENDOR)
+					continue;
+				if (((idf >> 16) & 0xFFFFu) != R8168_DEVICE)
+					continue;
+
+				/* Enable memory space + bus master. */
+				cmd = pci_cfg_read32(bus, dev, func, 0x04);
+				pci_cfg_write32(bus, dev, func, 0x04, cmd | 0x0006u);
+
+				/* First memory BAR (BAR2 on this chip). */
+				for (bar = 0; bar < 6; bar++) {
+					unsigned int val = pci_cfg_read32(bus, dev, func,
+									  0x10 + 4 * bar);
+					unsigned int hi = 0, mask;
+
+					if (!bar_is_mmio(val))
+						continue;
+
+					if (val & 4u)   /* 64-bit BAR: high half */
+						hi = pci_cfg_read32(bus, dev, func,
+								    0x10 + 4 * bar + 4);
+
+					/* Size probe: all-ones, read mask, restore. */
+					pci_cfg_write32(bus, dev, func, 0x10 + 4 * bar,
+							0xFFFFFFFFu);
+					if (val & 4u)
+						pci_cfg_write32(bus, dev, func,
+								0x10 + 4 * bar + 4,
+								0xFFFFFFFFu);
+					mask = pci_cfg_read32(bus, dev, func,
+							      0x10 + 4 * bar) & 0xFFFFFFF0u;
+					pci_cfg_write32(bus, dev, func, 0x10 + 4 * bar, val);
+					if (val & 4u)
+						pci_cfg_write32(bus, dev, func,
+								0x10 + 4 * bar + 4, hi);
+
+					if (mask == 0)
+						continue;
+
+					bar_base = val & 0xFFFFFFF0u;
+					bar_size = (~mask + 1u);
+					if (bar_size < 0x1000)
+						bar_size = 0x1000;
+					pci_bus = bus;
+					pci_dev = dev;
+					pci_func = func;
+					return 0;
+				}
+			}
+		}
+	}
+	return -1;
+}
+
+/* ---- bring-up steps ---- */
+
+static int hw_reset(void)
+{
+	unsigned int t0;
+
+	w8(REG_ChipCmd, ChipCmd_Reset);
+	t0 = get_ticks_ms();
+	while (r8(REG_ChipCmd) & ChipCmd_Reset) {
+		if (timed_out(t0, 100))
+			return -1;
+	}
+	return 0;
+}
+
+static void read_mac(void)
+{
+	unsigned int v, i;
+
+	w8(REG_Cfg9346, Cfg9346_Unlock);
+	v = r32(REG_MAC0);
+	for (i = 0; i < 4; i++)
+		mac[i] = (unsigned char)((v >> (8 * i)) & 0xFF);
+	v = r16(REG_MAC0 + 4);
+	mac[4] = (unsigned char)(v & 0xFF);
+	mac[5] = (unsigned char)((v >> 8) & 0xFF);
+
+	/* Program the address back into the chip.  The MAC filter registers
+	 * (IDR/RAR) must hold our address or unicast frames are dropped, and a
+	 * soft reset may have cleared them; every driver does this after a
+	 * reset.  Order matters: MAC4 (high word) first, then MAC0. */
+	w16(REG_MAC0 + 4, (unsigned short)(mac[4] | (mac[5] << 8)));
+	w32(REG_MAC0, (unsigned int)mac[0] | ((unsigned int)mac[1] << 8) |
+		      ((unsigned int)mac[2] << 16) | ((unsigned int)mac[3] << 24));
+	w8(REG_Cfg9346, 0x00);
+}
+
+static void setup_rings(void)
+{
+	unsigned int i;
+
+	w32(REG_TxDescHigh, 0);
+	w32(REG_TxDescLow, (unsigned int)tx_ring);
+	w32(REG_RxDescHigh, 0);
+	w32(REG_RxDescLow, (unsigned int)rx_ring);
+	if ((xid & 0x7c8) == 0x3c0 || (xid & 0x7c8) == 0x3c8)
+		w32(REG_RDSAR1, 0);   /* 8168c takes the RX ring high half too */
+
+	for (i = 0; i < R8168_NTX; i++) {
+		tx_ring[i].opts1 = 0;
+		tx_ring[i].opts2 = 0;
+		tx_ring[i].addr_lo = (unsigned int)(tx_bufs + i * R8168_BUF_SIZE);
+		tx_ring[i].addr_hi = 0;
+	}
+	for (i = 0; i < R8168_NRX; i++) {
+		rx_ring[i].opts2 = 0;
+		rx_ring[i].addr_lo = (unsigned int)(rx_bufs + i * R8168_BUF_SIZE);
+		rx_ring[i].addr_hi = 0;
+		rx_ring[i].opts1 = DescOwn | R8168_RX_ARM;
+	}
+	rx_ring[R8168_NRX - 1].opts1 |= DescRingEnd;
+	dma_barrier();
+	tx_cur = 0;
+	rx_cur = 0;
+}
+
+static void set_rx_mode(void)
+{
+	unsigned int cfg = r32(REG_RxConfig);
+
+	/* Promiscuous for bring-up (same choice as the ne2000 driver): keeps
+	 * NIC and switch filtering out of the picture while we validate the
+	 * DMA path; netrecv is a diagnosis tool and wants to see everything. */
+	cfg = (cfg & ~RX_ACCEPT_MASK) |
+	      RX_ACCEPT_BROADCAST | RX_ACCEPT_MULTICAST | RX_ACCEPT_MYPHYS |
+	      RX_ACCEPT_ALLPHYS;
+	w32(REG_RxConfig, cfg);
+}
+
+static void phy_autoneg(void)
+{
+	int id1 = mdio_read(MII_PHYSID1);
+	int id2 = mdio_read(MII_PHYSID2);
+
+	serial_puts(SERIAL_COM1, "r8168: phy id ");
+	serial_puthex(SERIAL_COM1, (unsigned int)(id1 < 0 ? 0xFFFF : id1));
+	serial_puts(SERIAL_COM1, ":");
+	serial_puthex(SERIAL_COM1, (unsigned int)(id2 < 0 ? 0xFFFF : id2));
+	serial_puts(SERIAL_COM1, "\n");
+
+	mdio_write(MII_ANAR, 0x01E1);   /* advertise 10/100 half+full */
+	mdio_write(MII_GBSR, 0x0300);   /* advertise 1000 half+full */
+	mdio_write(MII_BMCR, BMCR_AUTONEG | BMCR_RESTART_AN);
+}
+
+static void wait_link(unsigned int ms)
+{
+	unsigned int t0 = get_ticks_ms();
+
+	while (get_ticks_ms() - t0 <= ms) {
+		int bmsr = mdio_read(MII_BMSR);
+
+		if ((bmsr >= 0 && (bmsr & BMSR_LINK)) ||
+		    (r8(REG_PHYstatus) & PHYST_LINK))
+			return;
+	}
+}
+
+/* ---- netdev interface ---- */
+
+/* Rings + configuration registers + PHY + RX/TX enable.  Used by both the
+ * first probe and `netreset`. */
+static void hw_start(void)
+{
+	w8(REG_Cfg9346, Cfg9346_Unlock);
+	setup_rings();
+	w32(REG_RxConfig, RX128_INT_EN | RX_DMA_BURST);
+	set_rx_mode();
+	w32(REG_TxConfig, TXCONFIG_VALUE);
+	w16(REG_RxMaxSize, R8168_BUF_SIZE);
+	w8(REG_MaxTxPacket, 0x3f);
+	w16(REG_IntrMitigate, 0x0000);
+	w16(REG_IntrMask, 0x0000);
+	w16(REG_IntrStatus, 0xFFFF);
+	w8(REG_Cfg9346, 0x00);
+	dbg("regs ok");
+
+	phy_autoneg();
+	dbg("phy up");
+
+	w8(REG_ChipCmd, ChipCmd_RxEnb | ChipCmd_TxEnb);
+
+	/* Give autoneg a moment, then wait for link (bounded). */
+	{
+		unsigned int t0 = get_ticks_ms();
+
+		while (get_ticks_ms() - t0 < 3000) {
+			if (r8(REG_PHYstatus) & PHYST_LINK)
+				break;
+		}
+	}
+	wait_link(2000);
+	dbg(r8(REG_PHYstatus) & PHYST_LINK ? "link up" : "no link");
+}
+
+int r8168_init(void)
+{
+	char buf[40];
+	unsigned int i;
+
+	if (inited)
+		return present ? 0 : -1;
+	inited = 1;
+
+	/* Reserve the status row before the trail grabs rows. */
+	if (kdbg_stat_row < 0)
+		kdbg_stat_row = kdbg_info_alloc();
+
+	if (probe_pci() != 0) {
+		dbg("no 10ec:8168 found");
+		return -1;
+	}
+
+	/* "PCI 04:00.0 f8fff000 4K" */
+	i = 0;
+	i = app(buf, i, "PCI ");
+	i = apph(buf, i, pci_bus, 2);
+	buf[i++] = ':';
+	i = apph(buf, i, pci_dev, 2);
+	buf[i++] = '.';
+	buf[i++] = (char)('0' + pci_func);
+	buf[i++] = ' ';
+	i = apph(buf, i, bar_base, 8);
+	buf[i++] = ' ';
+	i = appd(buf, i, bar_size / 1024);
+	buf[i++] = 'K';
+	buf[i] = '\0';
+	dbg(buf);
+
+	process_map_mmio_all(bar_base, bar_size);
+	mmio = (unsigned char *)bar_base;
+
+	/* Master abort / unmapped window reads back all-ones. */
+	if (r32(REG_TxConfig) == 0xFFFFFFFFu) {
+		dbg("mmio read failed");
+		mmio = 0;
+		return -1;
+	}
+
+	xid = (r32(REG_TxConfig) >> 20) & 0xfcf;
+
+	if (hw_reset() != 0) {
+		dbg("reset timeout");
+		mmio = 0;
+		return -1;
+	}
+	dbg("reset ok");
+
+	read_mac();
+
+	/* Ring memory: one page each (256-byte aligned); buffers in pages. */
+	tx_ring = (struct r8168_desc *)mm_alloc_page();
+	rx_ring = (struct r8168_desc *)mm_alloc_page();
+	tx_bufs = (unsigned char *)mm_alloc_pages(R8168_NTX * R8168_BUF_SIZE / PAGE_SIZE);
+	rx_bufs = (unsigned char *)mm_alloc_pages(R8168_NRX * R8168_BUF_SIZE / PAGE_SIZE);
+	if (!tx_ring || !rx_ring || !tx_bufs || !rx_bufs) {
+		dbg("no memory for rings");
+		mmio = 0;
+		return -1;
+	}
+	dbg("ring memory ok");
+
+	hw_start();
+
+	/* "<chip> XID <xxx> <mac>" */
+	i = 0;
+	i = app(buf, i, chip_name());
+	buf[i++] = ' ';
+	i = app(buf, i, "XID ");
+	i = apph(buf, i, xid, 3);
+	buf[i++] = ' ';
+	for (unsigned int j = 0; j < 6; j++) {
+		i = apph(buf, i, mac[j], 2);
+		if (j != 5)
+			buf[i++] = ':';
+	}
+	buf[i] = '\0';
+	dbg(buf);
+
+	present = 1;
+	status_line();
+	return 0;
+}
+
+/* `netreset`: full re-init of an already-probed NIC (used to recover from an
+ * RX stall and as a bring-up experiment). */
+void r8168_reset(void)
+{
+	if (!present || !mmio || !rx_ring) {
+		dbg("reset: not initialized");
+		return;
+	}
+	if (hw_reset() != 0) {
+		dbg("reset timeout");
+		return;
+	}
+	read_mac();
+	hw_start();
+	status_line();
+	dbg("netreset done");
+}
+
+void r8168_get_mac(unsigned char out[6])
+{
+	unsigned int i;
+	for (i = 0; i < 6; i++)
+		out[i] = mac[i];
+}
+
+int r8168_tx(const unsigned char *buf, unsigned int len)
+{
+	static unsigned char pad[60];
+	struct r8168_desc *d;
+	unsigned int entry, opts1, t0;
+	const unsigned char *p = buf;
+	unsigned int txlen = len;
+
+	if (!present || !mmio)
+		return -1;
+	if (len < 14 || len > 1514)
+		return -1;
+
+	isr_poll();
+
+	if (len < 60) {
+		unsigned int i;
+		for (i = 0; i < len; i++)
+			pad[i] = buf[i];
+		for (i = len; i < 60; i++)
+			pad[i] = 0;
+		p = pad;
+		txlen = 60;
+	}
+
+	entry = tx_cur;
+	d = &tx_ring[entry];
+
+	/* Wait for a previous use of this slot to complete. */
+	t0 = get_ticks_ms();
+	while (d->opts1 & DescOwn) {
+		if (timed_out(t0, 100)) {
+			tx_err++;
+			status_line();
+			return -1;
+		}
+	}
+
+	{
+		unsigned char *dst = tx_bufs + entry * R8168_BUF_SIZE;
+		unsigned int i;
+		for (i = 0; i < txlen; i++)
+			dst[i] = p[i];
+	}
+
+	opts1 = txlen | DescFirstFrag | DescLastFrag;
+	if (entry == R8168_NTX - 1)
+		opts1 |= DescRingEnd;
+	d->addr_lo = (unsigned int)(tx_bufs + entry * R8168_BUF_SIZE);
+	d->addr_hi = 0;
+	d->opts2 = 0;
+	dma_barrier();
+	d->opts1 = opts1 | DescOwn;
+	dma_barrier();
+
+	w8(REG_TxPoll, TxPoll_NPQ);
+
+	t0 = get_ticks_ms();
+	while (d->opts1 & DescOwn) {
+		if (timed_out(t0, 100)) {
+			tx_err++;
+			status_line();
+			return -1;
+		}
+	}
+
+	tx_cur = (entry + 1) % R8168_NTX;
+	last_tx_status = d->opts1;
+	tx_ok++;
+	if ((tx_ok & 63) == 0)
+		status_line();
+	return 0;
+}
+
+/* Re-arm one RX descriptor (clears owner for the NIC). */
+static void rx_arm(unsigned int entry)
+{
+	rx_ring[entry].opts2 = 0;
+	dma_barrier();
+	rx_ring[entry].opts1 = DescOwn | R8168_RX_ARM |
+			       (entry == R8168_NRX - 1 ? DescRingEnd : 0);
+	dma_barrier();
+}
+
+int r8168_rx(unsigned char *buf, unsigned int maxlen)
+{
+	unsigned int guard = 0;
+
+	if (!present || !mmio)
+		return -1;
+
+	isr_poll();
+
+	while (guard++ < 32) {
+		unsigned int entry = rx_cur;
+		struct r8168_desc *d = &rx_ring[entry];
+		unsigned int status = d->opts1;
+		unsigned int len;
+
+		if (status & DescOwn)
+			return -1;              /* nothing pending */
+
+		dma_barrier();
+
+		if (status & RxRES) {
+			rx_err++;
+		} else if ((status & (DescFirstFrag | DescLastFrag)) !=
+			   (DescFirstFrag | DescLastFrag)) {
+			rx_drop++;              /* fragmented frame: too big */
+		} else {
+			len = status & RxPktLenMask;
+			if (len >= 4)
+				len -= 4;       /* drop the trailing FCS */
+			if (len < 14 || len > maxlen) {
+				rx_drop++;
+			} else {
+				unsigned char *src = rx_bufs + entry * R8168_BUF_SIZE;
+				unsigned int i;
+
+				for (i = 0; i < len; i++)
+					buf[i] = src[i];
+				rx_ok++;
+				if ((rx_ok & 63) == 0)
+					status_line();
+				rx_arm(entry);
+				rx_cur = (rx_cur + 1) % R8168_NRX;
+				return (int)len;
+			}
+		}
+
+		rx_arm(entry);
+		rx_cur = (rx_cur + 1) % R8168_NRX;
+	}
+	return -1;
+}
+
+/* PHY loopback for a self-test (driver op): transmitted frames are looped
+ * back into the receiver by the PHY, so TX and RX can be validated with no
+ * cable, switch or peer.  Forces 100M full duplex while enabled. */
+static int saved_bmcr = -1;
+
+int r8168_set_loopback(int on)
+{
+	if (!present || !mmio)
+		return -1;
+
+	if (on) {
+		saved_bmcr = mdio_read(MII_BMCR);
+		mdio_write(MII_BMCR, 0x2000 | 0x0100 | 0x4000);   /* 100M FD + LB */
+	} else {
+		int bmcr = saved_bmcr >= 0 ? (saved_bmcr & 0x7fff) : 0;
+		unsigned int t0;
+
+		mdio_write(MII_BMCR, bmcr | BMCR_AUTONEG | BMCR_RESTART_AN);
+		t0 = get_ticks_ms();
+		while (get_ticks_ms() - t0 < 2000) {
+			if (r8(REG_PHYstatus) & PHYST_LINK)
+				break;
+		}
+	}
+	return 0;
+}
+
+void r8168_print_info(void)
+{
+	char sp[6];
+	unsigned int st, i;
+
+	if (!present) {
+		io_putstr("r8168: no RTL8111/8168 found\n");
+		return;
+	}
+
+	io_putstr(chip_name());
+	io_putstr(" XID ");
+	put_hex4(xid);
+	io_putstr(" at ");
+	put_hex2(pci_bus);
+	io_putchar(':');
+	put_hex2(pci_dev);
+	io_putchar('.');
+	io_putchar((char)('0' + pci_func));
+	io_putchar('\n');
+
+	io_putstr("  bar ");
+	put_hex4(bar_base >> 16);
+	put_hex4(bar_base & 0xFFFF);
+	io_putstr(" (");
+	put_dec(bar_size / 1024);
+	io_putstr("K) mac=");
+	for (i = 0; i < 6; i++) {
+		if (i)
+			io_putchar(':');
+		put_hex2(mac[i]);
+	}
+	io_putchar('\n');
+
+	st = r8(REG_PHYstatus);
+	speed_string(st, sp);
+	io_putstr("  link ");
+	io_putstr((st & PHYST_LINK) ? "up " : "down ");
+	io_putstr(sp);
+	io_putstr((st & PHYST_FULLDUP) ? "F" : "H");
+	io_putstr("  tx ");
+	put_dec(tx_ok);
+	io_putchar('/');
+	put_dec(tx_err);
+	io_putstr(" rx ");
+	put_dec(rx_ok);
+	io_putchar('/');
+	put_dec(rx_err);
+	io_putchar('\n');
+}
+
+void r8168_dump_regs(void)
+{
+	static const struct {
+		const char *name;
+		unsigned int reg;
+	} regs[] = {
+		{ "MAC0", REG_MAC0 }, { "TxDescLo", REG_TxDescLow },
+		{ "TxDescHi", REG_TxDescHigh }, { "ChipCmd", REG_ChipCmd },
+		{ "IntrMask", REG_IntrMask }, { "IntrStat", REG_IntrStatus },
+		{ "TxConfig", REG_TxConfig }, { "RxConfig", REG_RxConfig },
+		{ "PHYAR", REG_PHYAR }, { "PHYstat", REG_PHYstatus },
+		{ "RxMaxSize", REG_RxMaxSize }, { "CPlusCmd", REG_CPlusCmd },
+		{ "RxDescLo", REG_RxDescLow }, { "RxDescHi", REG_RxDescHigh },
+	};
+	unsigned int i;
+
+	if (!present || !mmio) {
+		io_putstr("r8168: no NIC\n");
+		return;
+	}
+	for (i = 0; i < sizeof(regs) / sizeof(regs[0]); i++) {
+		io_putstr(regs[i].name);
+		io_putstr("=");
+		io_puthex(r32(regs[i].reg));
+		if (i & 1)
+			io_putchar('\n');
+		else
+			io_putstr("  ");
+	}
+	if (i & 1)
+		io_putchar('\n');
+	io_putstr("state tx_ok=");
+	put_dec(tx_ok);
+	io_putstr(" tx_err=");
+	put_dec(tx_err);
+	io_putstr(" rx_ok=");
+	put_dec(rx_ok);
+	io_putstr(" rx_err=");
+	put_dec(rx_err);
+	io_putstr(" rx_drop=");
+	put_dec(rx_drop);
+	io_putstr(" rx_restart=");
+	put_dec(rx_restarts);
+	io_putchar('\n');
+	io_putstr("isr ");
+	if (isr_last == 0) {
+		io_putstr("(none)");
+	} else {
+		if (isr_last & ISR_RxOK) io_putstr("RxOK ");
+		if (isr_last & ISR_RxErr) io_putstr("RxErr ");
+		if (isr_last & ISR_TxOK) io_putstr("TxOK ");
+		if (isr_last & ISR_TxErr) io_putstr("TxErr ");
+		if (isr_last & ISR_ROVW) io_putstr("ROVW ");
+		if (isr_last & ISR_LinkChg) io_putstr("LinkChg ");
+		if (isr_last & ISR_FOV) io_putstr("FOV ");
+		if (isr_last & ISR_TDU) io_putstr("TDU ");
+		if (isr_last & ISR_SWInt) io_putstr("SWInt ");
+	}
+	io_putstr("  evt rovw=");
+	put_dec(isr_rovw);
+	io_putstr(" fov=");
+	put_dec(isr_fov);
+	io_putstr(" tdu=");
+	put_dec(isr_tdu);
+	io_putchar('\n');
+	io_putstr("tx status ");
+	io_puthex(last_tx_status);
+	io_putstr("  ring tx ");
+	io_puthex((unsigned int)tx_ring);
+	io_putstr(" rx ");
+	io_puthex((unsigned int)rx_ring);
+	io_putchar('\n');
+}
+
+const struct netdev r8168_netdev = {
+	"r8168", "RTL8111/8168",
+	r8168_init, r8168_get_mac, r8168_rx, r8168_tx, r8168_print_info,
+	r8168_dump_regs, r8168_set_loopback, r8168_reset,
+};

+ 23 - 0
r8168.h

@@ -0,0 +1,23 @@
+/* Realtek RTL8111/8168 (RTL8112L) PCIe Gigabit Ethernet driver. */
+#ifndef R8168_H
+#define R8168_H
+
+/* Probe + reset + configure the NIC.  Idempotent; 0 on success, -1 if absent. */
+int r8168_init(void);
+
+void r8168_get_mac(unsigned char out[6]);
+int  r8168_rx(unsigned char *buf, unsigned int maxlen);
+int  r8168_tx(const unsigned char *buf, unsigned int len);
+
+/* Enable/disable PHY loopback for the self-test (see r8168.c). */
+int  r8168_set_loopback(int on);
+
+void r8168_print_info(void);
+void r8168_dump_regs(void);
+void r8168_reset(void);
+
+/* netdev adapter (see netdev.h). */
+#include "netdev.h"
+extern const struct netdev r8168_netdev;
+
+#endif

+ 97 - 0
terminal.c

@@ -38,6 +38,10 @@ extern void program_netinfo_main(void);
 extern void program_netrecv_main(void);
 extern void program_netsend_main(void);
 extern void program_netip_main(const char *arg);
+extern void program_netping_main(const char *arg);
+extern void program_netregs_main(void);
+extern void program_netloop_main(void);
+extern void program_netreset_main(void);
 extern void program_ping_main(void);
 
 /* Print the prompt (with the current directory) and set line_start. */
@@ -353,6 +357,57 @@ static int is_cmd_netconsole(const char *line, unsigned int line_len, char *arg_
 	return (i == line_len);
 }
 
+static int is_cmd_netregs(const char *line, unsigned int line_len)
+{
+	unsigned int i = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 7 > line_len)
+		return 0;
+	if (line[i] != 'n' || line[i+1] != 'e' || line[i+2] != 't' ||
+	    line[i+3] != 'r' || line[i+4] != 'e' || line[i+5] != 'g' ||
+	    line[i+6] != 's')
+		return 0;
+	i += 7;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
+static int is_cmd_netloop(const char *line, unsigned int line_len)
+{
+	unsigned int i = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 7 > line_len)
+		return 0;
+	if (line[i] != 'n' || line[i+1] != 'e' || line[i+2] != 't' ||
+	    line[i+3] != 'l' || line[i+4] != 'o' || line[i+5] != 'o' ||
+	    line[i+6] != 'p')
+		return 0;
+	i += 7;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
+static int is_cmd_netreset(const char *line, unsigned int line_len)
+{
+	unsigned int i = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 8 > line_len)
+		return 0;
+	if (line[i] != 'n' || line[i+1] != 'e' || line[i+2] != 't' ||
+	    line[i+3] != 'r' || line[i+4] != 'e' || line[i+5] != 's' ||
+	    line[i+6] != 'e' || line[i+7] != 't')
+		return 0;
+	i += 8;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
 static int is_cmd_netrecv(const char *line, unsigned int line_len)
 {
 	unsigned int i = 0;
@@ -415,6 +470,35 @@ static int is_cmd_netip(const char *line, unsigned int line_len, char *arg_buf,
 	return (i == line_len);
 }
 
+static int is_cmd_netping(const char *line, unsigned int line_len, char *arg_buf, unsigned int buf_size)
+{
+	unsigned int i = 0, j = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 7 > line_len)
+		return 0;
+	if (line[i] != 'n' || line[i+1] != 'e' || line[i+2] != 't' ||
+	    line[i+3] != 'p' || line[i+4] != 'i' || line[i+5] != 'n' ||
+	    line[i+6] != 'g')
+		return 0;
+	i += 7;
+	if (i < line_len && line[i] != ' ')
+		return 0;  /* "netping" must be a whole word */
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i >= line_len) {
+		if (buf_size > 0)
+			arg_buf[0] = '\0';
+		return 1;
+	}
+	while (i < line_len && j + 1 < buf_size)
+		arg_buf[j++] = line[i++];
+	arg_buf[j] = '\0';
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
 static int is_cmd_ping(const char *line, unsigned int line_len)
 {
 	unsigned int i = 0;
@@ -1037,6 +1121,7 @@ void term_run(struct term *t)
 					char ls_path[LS_PATH_MAX];
 					char format_dev[FORMAT_DEV_MAX];
 					char netip_arg[16];
+					char netping_arg[16];
 					char lspci_arg[16];
 					char peek_arg[32];
 					char resolved[VFS_PATH_MAX];
@@ -1081,6 +1166,14 @@ void term_run(struct term *t)
 						term_spawn(t, "netsend", program_netsend_main);
 					} else if (is_cmd_netip(t->line, t->line_len, netip_arg, sizeof(netip_arg))) {
 						term_spawn_arg(t, "netip", program_netip_main, netip_arg);
+					} else if (is_cmd_netping(t->line, t->line_len, netping_arg, sizeof(netping_arg))) {
+						term_spawn_arg(t, "netping", program_netping_main, netping_arg);
+					} else if (is_cmd_netregs(t->line, t->line_len)) {
+						term_spawn(t, "netregs", program_netregs_main);
+					} else if (is_cmd_netloop(t->line, t->line_len)) {
+						term_spawn(t, "netloop", program_netloop_main);
+					} else if (is_cmd_netreset(t->line, t->line_len)) {
+						term_spawn(t, "netreset", program_netreset_main);
 					} else if (is_cmd_ping(t->line, t->line_len)) {
 						term_spawn(t, "ping", program_ping_main);
 					} else if (is_cmd_storage(t->line, t->line_len)) {
@@ -1185,6 +1278,10 @@ void term_run(struct term *t)
 						io_putstr("netrecv\n");
 						io_putstr("netsend\n");
 						io_putstr("netip [a.b.c.d]\n");
+						io_putstr("netping <a.b.c.d>\n");
+						io_putstr("netregs\n");
+						io_putstr("netloop\n");
+						io_putstr("netreset\n");
 						io_putstr("ping\n");
 						io_putstr("ps\n");
 						io_putstr("kill <pid>\n");