Просмотр исходного кода

Add kernel reload over UDP and a network debug console

Johannes Zellner 1 месяц назад
Родитель
Сommit
15faa9f5c7
14 измененных файлов с 904 добавлено и 4 удалено
  1. 2 0
      .gitignore
  2. 33 3
      Makefile
  3. 4 0
      kernel.c
  4. 86 0
      netcmd.c
  5. 264 0
      netkexec.c
  6. 15 0
      netkexec.h
  7. 198 0
      netkexec_send.c
  8. 126 0
      netlog.c
  9. 34 0
      netlog.h
  10. 81 0
      netmonitor.c
  11. 3 0
      screen.c
  12. 6 0
      serial.c
  13. 39 0
      terminal.c
  14. 13 1
      wm.c

+ 2 - 0
.gitignore

@@ -4,3 +4,5 @@
 *.img
 send_serial
 kexec_send
+netkexec_send
+netmonitor

+ 33 - 3
Makefile

@@ -13,7 +13,7 @@ ASFLAGS  = --32
 BOOT_LDFLAGS   = -T linker.ld -nostdlib -m elf_i386
 KERNEL_LDFLAGS = -T kernel.ld -nostdlib -m elf_i386
 
-.PHONY: all clean run run-floppy run-usb run-serial floppy usb flash space prog bootstrap dev monitor
+.PHONY: all clean run run-floppy run-usb run-serial floppy usb flash space prog bootstrap dev net-dev netmon monitor
 
 all: floppy.img usb.img final.bin root.img
 
@@ -149,6 +149,12 @@ r8168.o: r8168.c r8168.h netdev.h io.h kdbg.h mm.h paging.h pci.h process.h seri
 netcmd.o: netcmd.c io.h timer.h netdev.h net.h
 	$(CC) $(CFLAGS) -o $@ $<
 
+netkexec.o: netkexec.c netkexec.h io.h kexec.h net.h netdev.h timer.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+netlog.o: netlog.c netlog.h net.h netdev.h timer.h
+	$(CC) $(CFLAGS) -o $@ $<
+
 netdev.o: netdev.c netdev.h ne2000.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -242,7 +248,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 r8168.o netdev.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 netkexec.o netlog.o hello_embed.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -409,6 +415,12 @@ send_serial: send_serial.c
 kexec_send: kexec_send.c
 	gcc -O2 -o $@ $<
 
+netkexec_send: netkexec_send.c
+	gcc -O2 -o $@ $<
+
+netmonitor: netmonitor.c
+	gcc -O2 -o $@ $<
+
 bootstrap: bootstrap.bin
 
 dev: kernel.bin kexec_send
@@ -417,5 +429,23 @@ dev: kernel.bin kexec_send
 	echo "Sending kernel.bin (entry 0x$$entry) via $(SERIAL_DEV) @ $(SERIAL_BAUD)..."; \
 	./kexec_send $(SERIAL_DEV) $(SERIAL_BAUD) $$entry kernel.bin
 
+# Show the board's netlog stream (kernel debug + terminal text) like `make
+# monitor` does over serial.
+netmon: netmonitor
+	@echo "Listening for netlog on UDP $(NETLOG_PORT) (Ctrl-C to exit)."
+	./netmonitor $(NETLOG_PORT)
+
+# Push a fresh kernel over Ethernet (the board auto-detects it from its idle
+# loop; no serial and no USB stick involved).
+BOARD_IP ?= 192.168.178.240
+NETLOG_PORT ?= 19290
+NETKEXEC_PORT ?= 19288
+
+net-dev: kernel.bin netkexec_send
+	@entry=$$(nm kernel.elf | awk '/ T kernel_main$$/{print $$1}'); \
+	if [ -z "$$entry" ]; then echo "error: kernel_main symbol not found"; exit 1; fi; \
+	echo "Sending kernel.bin (entry 0x$$entry) to $(BOARD_IP):$(NETKEXEC_PORT)..."; \
+	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$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 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
+	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 netkexec.o netlog.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 netkexec_send netmonitor

+ 4 - 0
kernel.c

@@ -7,6 +7,7 @@
 #include "mm.h"
 #include "mouse.h"
 #include "netdev.h"
+#include "netlog.h"
 #include "paging.h"
 #include "process.h"
 #include "timer.h"
@@ -198,5 +199,8 @@ void kernel_main(void)
 	/* 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();
+	/* Network console mirror from the very first line on; the ring holds the
+	 * early boot output until the WM loop starts flushing it. */
+	netlog_init();
 	wm_run();
 }

+ 86 - 0
netcmd.c

@@ -5,6 +5,7 @@
 #include "timer.h"
 #include "netdev.h"
 #include "net.h"
+#include "netlog.h"
 
 /* Shared frame buffers (file scope, not stack: the 4 KB process stack can't
    hold a full-size frame, and keeping them out of BSS-as-much-as-possible
@@ -253,6 +254,91 @@ void program_ping_main(void)
 	netdev_release();
 }
 
+/* ---- netlog: send a text line to the LAN as a UDP datagram ---- */
+
+void program_netlog_main(const char *arg)
+{
+	static const unsigned char bcast_mac[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
+	unsigned char dst[4];
+	unsigned int len = 0;
+
+	if (arg[0] == '\0') {
+		io_putstr("netlog: usage netlog <text>\n");
+		return;
+	}
+	while (arg[len] && len < NET_UDP_MAX)
+		len++;
+
+	netlog_get_host(dst);
+	if (net_udp_send(bcast_mac, dst, NETLOG_PORT, NETLOG_PORT,
+			 arg, len) != 0) {
+		io_putstr("netlog: send failed\n");
+		return;
+	}
+	io_putstr("netlog: sent ");
+	put_dec(len);
+	io_putstr(" bytes to UDP port ");
+	put_dec(NETLOG_PORT);
+	io_putchar('\n');
+}
+
+/* ---- netconsole: the debug-output mirror (see netlog.c) ---- */
+
+static int arg_is(const char *arg, const char *word)
+{
+	unsigned int i = 0;
+
+	while (arg[i] && word[i] && arg[i] == word[i])
+		i++;
+	return arg[i] == '\0' && word[i] == '\0';
+}
+
+void program_netconsole_main(const char *arg)
+{
+	unsigned char ip[4];
+
+	if (arg[0] == '\0') {
+		io_putstr("netconsole: mirror ");
+		io_putstr(netlog_get_enabled() ? "on" : "off");
+		io_putstr(", host ");
+		netlog_get_host(ip);
+		put_ip(ip);
+		io_putstr(", udp port ");
+		put_dec(NETLOG_PORT);
+		io_putchar('\n');
+		io_putstr("netconsole: usage netconsole on|off|host <a.b.c.d>\n");
+		return;
+	}
+
+	if (arg_is(arg, "on")) {
+		netlog_set_enabled(1);
+		io_putstr("netconsole: mirror on\n");
+		return;
+	}
+	if (arg_is(arg, "off")) {
+		netlog_set_enabled(0);
+		io_putstr("netconsole: mirror off\n");
+		return;
+	}
+	if (arg[0] == 'h' && arg[1] == 'o' && arg[2] == 's' && arg[3] == 't') {
+		const char *p = arg + 4;
+
+		while (*p == ' ')
+			p++;
+		if (*p == '\0' || net_parse_ip(p, ip) != 0) {
+			io_putstr("netconsole: usage netconsole host <a.b.c.d>\n");
+			return;
+		}
+		netlog_set_host(ip);
+		io_putstr("netconsole: host ");
+		put_ip(ip);
+		io_putchar('\n');
+		return;
+	}
+
+	io_putstr("netconsole: usage netconsole on|off|host <a.b.c.d>\n");
+}
+
 /* ---- netreset: ask the driver for a full NIC re-init ---- */
 
 void program_netreset_main(void)

+ 264 - 0
netkexec.c

@@ -0,0 +1,264 @@
+/* Kernel hot-reload over UDP: the host pushes kernel.bin as datagrams, the
+ * board writes them into the kexec staging buffer, verifies the checksum and
+ * jumps (kexec.c has the serial variant).
+ *
+ * Protocol (little-endian; UDP to NETKEXEC_PORT; the board replies to the
+ * sender's IP/MAC/port):
+ *
+ *   host -> board  header   "KXNU" entry size csum          (16 bytes)
+ *   host -> board  data     "KXND" offset len payload...    (12 + len)
+ *   board -> host  ack      "KXNA" next_offset status       (12 bytes)
+ *                           status 0 = keep going, 1 = done, 2 = bad checksum
+ *
+ * The board auto-detects the header from the WM loop (netkexec_pending());
+ * program_netkexec_main() then runs stop-and-wait: every datagram is acked
+ * with the next expected offset, so a lost or duplicated datagram costs one
+ * retransmit.  Datagrams addressed to the broadcast IP are accepted too, so
+ * the host can push without knowing whether the board is up yet.
+ */
+
+#include "io.h"
+#include "kexec.h"
+#include "net.h"
+#include "netdev.h"
+#include "serial.h"
+#include "timer.h"
+#include "netkexec.h"
+
+#define NETKEXEC_PORT       19288
+#define NETKEXEC_DATA_MAX   1400
+
+#define X_MAGIC_HDR   0x554E584Bu   /* "KXNU" */
+#define X_MAGIC_DATA  0x444E584Bu   /* "KXND" */
+#define X_MAGIC_ACK   0x414E584Bu   /* "KXNA" */
+
+#define ACK_CONTINUE  0
+#define ACK_DONE      1
+#define ACK_BADSUM    2
+
+static unsigned char rxbuf[1520];       /* one full Ethernet frame */
+static unsigned char replybuf[1520];
+static unsigned char ackbuf[12];
+
+/* Pending transfer (filled by netkexec_pending). */
+static int have_header;
+static unsigned int x_entry, x_size, x_csum;
+static unsigned char peer_mac[6], peer_ip[4];
+static unsigned int peer_port;
+
+static unsigned int rd32(const unsigned char *p)
+{
+	return (unsigned int)p[0] | ((unsigned int)p[1] << 8) |
+	       ((unsigned int)p[2] << 16) | ((unsigned int)p[3] << 24);
+}
+
+static void wr32(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)(v & 0xFF);
+	p[1] = (unsigned char)((v >> 8) & 0xFF);
+	p[2] = (unsigned char)((v >> 16) & 0xFF);
+	p[3] = (unsigned char)((v >> 24) & 0xFF);
+}
+
+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];
+}
+
+static int ip_is_bcast(const unsigned char *ip)
+{
+	return ip[0] == 0xFF && ip[1] == 0xFF && ip[2] == 0xFF && ip[3] == 0xFF;
+}
+
+/* Parse `f` as a UDP datagram to NETKEXEC_PORT; fill payload + peer address.
+ * Returns 1 on match. */
+static int parse_udp(const unsigned char *f, unsigned int len,
+		     const unsigned char **payload, unsigned int *plen,
+		     unsigned char p_mac[6], unsigned char p_ip[4],
+		     unsigned int *p_port)
+{
+	const unsigned char *ip = f + 14;
+	const unsigned char *udp;
+	unsigned char my_ip[4];
+	unsigned int i, ihl, ip_len;
+
+	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;
+
+	net_get_ip(my_ip);
+	if (!ip_eq(ip + 16, my_ip) && !ip_is_bcast(ip + 16))
+		return 0;
+
+	udp = ip + ihl;
+	if ((((unsigned int)udp[2] << 8) | udp[3]) != NETKEXEC_PORT)
+		return 0;
+
+	for (i = 0; i < 6; i++)
+		p_mac[i] = f[6 + i];
+	for (i = 0; i < 4; i++)
+		p_ip[i] = ip[12 + i];
+	*p_port = ((unsigned int)udp[0] << 8) | udp[1];
+	*payload = udp + 8;
+	*plen = ip_len - ihl - 8;
+	return *plen > 0;
+}
+
+int netkexec_pending(void)
+{
+	const struct netdev *nd;
+	const unsigned char *payload;
+	unsigned int plen, port;
+	int len;
+
+	if (kexec_busy || netdev_in_use())
+		return 0;
+	nd = netdev_active();
+	if (!nd)
+		return 0;
+
+	/* One frame per call; anything else is dropped (this also keeps the RX
+	 * ring drained while the system idles at a prompt). */
+	len = nd->rx(rxbuf, sizeof(rxbuf));
+	if (len < 0)
+		return 0;
+
+	if (!parse_udp(rxbuf, (unsigned int)len, &payload, &plen,
+		       peer_mac, peer_ip, &port)) {
+		/* Not a kexec datagram: stay reachable by answering ARP and ICMP
+		 * echo requests for our IP (so the board can be pinged, and a
+		 * host can resolve its MAC, without running a command).  Until
+		 * an address is configured there is nothing to answer for. */
+		int rlen;
+
+		if (!net_is_configured())
+			return 0;
+		rlen = net_build_reply(rxbuf, (unsigned int)len,
+				       replybuf, sizeof(replybuf));
+		if (rlen > 0)
+			nd->tx(replybuf, (unsigned int)rlen);
+		return 0;
+	}
+	if (plen < 16 || rd32(payload) != X_MAGIC_HDR)
+		return 0;
+	if (plen < 16 || rd32(payload) != X_MAGIC_HDR)
+		return 0;
+
+	x_entry = rd32(payload + 4);
+	x_size = rd32(payload + 8);
+	x_csum = rd32(payload + 12);
+	if (x_size == 0 || x_size > KEXEC_MAX)
+		return 0;
+
+	peer_port = port;
+	have_header = 1;
+	return 1;
+}
+
+static void send_ack(unsigned int next_offset, unsigned int status)
+{
+	wr32(ackbuf, X_MAGIC_ACK);
+	wr32(ackbuf + 4, next_offset);
+	wr32(ackbuf + 8, status);
+	net_udp_send(peer_mac, peer_ip, NETKEXEC_PORT, peer_port,
+		     ackbuf, sizeof(ackbuf));
+}
+
+static int netkexec_recv(void)
+{
+	volatile unsigned char *stage = (volatile unsigned char *)KEXEC_STAGE;
+	unsigned int offset = 0, retries = 0, sum = 0;
+	unsigned int deadline = get_ticks_ms() + 3000;
+
+	kexec_total = x_size;
+	kexec_progress = 0;
+	send_ack(0, ACK_CONTINUE);          /* header ok, send from offset 0 */
+
+	while (offset < x_size) {
+		const unsigned char *payload;
+		unsigned int plen, port, doff, dlen;
+		int len, i;
+
+		if ((int)(get_ticks_ms() - deadline) > 0) {
+			if (++retries > 10)
+				return -1;      /* host gave up */
+			send_ack(offset, ACK_CONTINUE);
+			deadline = get_ticks_ms() + 1000;
+			continue;
+		}
+
+		len = netdev_active()->rx(rxbuf, sizeof(rxbuf));
+		if (len < 0)
+			continue;
+		if (!parse_udp(rxbuf, (unsigned int)len, &payload, &plen,
+			       peer_mac, peer_ip, &port))
+			continue;
+		if (plen < 12 || rd32(payload) != X_MAGIC_DATA)
+			continue;
+
+		doff = rd32(payload + 4);
+		dlen = rd32(payload + 8);
+		if (dlen > NETKEXEC_DATA_MAX || plen < 12 + dlen)
+			continue;
+
+		if (doff == offset) {
+			for (i = 0; i < (int)dlen; i++) {
+				stage[offset + i] = payload[12 + i];
+				sum += payload[12 + i];
+			}
+			offset += dlen;
+			kexec_progress = offset;
+			retries = 0;
+			deadline = get_ticks_ms() + 1000;
+			if ((offset & 0x3FFF) == 0)
+				io_putchar('.');
+		}
+		send_ack(offset, ACK_CONTINUE);   /* also acks duplicates */
+	}
+
+	if (sum != x_csum) {
+		send_ack(offset, ACK_BADSUM);
+		return -1;
+	}
+	send_ack(x_size, ACK_DONE);
+	return 0;
+}
+
+void program_netkexec_main(void)
+{
+	if (!have_header) {
+		io_putstr("netkexec: no transfer pending\n");
+		kexec_busy = 0;
+		return;
+	}
+	have_header = 0;
+	netdev_acquire();
+
+	io_putstr("netkexec: receiving ");
+	io_puthex(x_size);
+	io_putstr(" bytes over UDP...\n");
+
+	if (netkexec_recv() != 0) {
+		io_putstr("\nnetkexec: aborted (timeout or checksum)\n");
+		netdev_release();
+		kexec_busy = 0;
+		return;
+	}
+
+	io_putstr("\nnetkexec: received ");
+	io_puthex(x_size);
+	io_putstr(" bytes, entry ");
+	io_puthex(x_entry);
+	io_putstr(" -> jumping\n");
+
+	kexec_jump(x_entry, x_size);     /* never returns */
+}

+ 15 - 0
netkexec.h

@@ -0,0 +1,15 @@
+/* Kernel hot-reload over UDP (see netkexec.c). */
+#ifndef NETKEXEC_H
+#define NETKEXEC_H
+
+/* 1 if a kernel-reload header datagram is waiting (auto-detected from the WM
+ * loop).  Returns 0 while a kexec is already running or a net command owns
+ * the receiver.  While idle it also answers ARP/ICMP for our IP, so the board
+ * stays reachable without running a command. */
+int netkexec_pending(void);
+
+/* Process entry: receive the pending image into the kexec staging buffer,
+ * verify it and jump.  Never returns on success. */
+void program_netkexec_main(void);
+
+#endif

+ 198 - 0
netkexec_send.c

@@ -0,0 +1,198 @@
+/* Push kernel.bin to a Nebs OS board over UDP (the board's WM loop
+ * auto-detects the header and jumps into the new kernel).
+ *
+ *   netkexec_send <board-ip> <port> <entry-hex> <file>
+ *
+ * Protocol: see netkexec.c.  Stop-and-wait: every datagram (except the
+ * header) is acked with the next expected offset; lost datagrams are
+ * retransmitted, so a slow or busy board just slows the transfer down.
+ */
+
+#include <arpa/inet.h>
+#include <errno.h>
+#include <netinet/in.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <unistd.h>
+
+#define DATA_MAX   1400
+#define MAGIC_HDR  0x554E584Bu   /* "KXNU" */
+#define MAGIC_DATA 0x444E584Bu   /* "KXND" */
+#define MAGIC_ACK  0x414E584Bu   /* "KXNA" */
+#define ACK_DONE   1
+
+static uint32_t rd32(const unsigned char *p)
+{
+	return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
+	       ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
+}
+
+static void wr32(unsigned char *p, uint32_t v)
+{
+	p[0] = (unsigned char)(v & 0xFF);
+	p[1] = (unsigned char)((v >> 8) & 0xFF);
+	p[2] = (unsigned char)((v >> 16) & 0xFF);
+	p[3] = (unsigned char)((v >> 24) & 0xFF);
+}
+
+static int send_packet(int fd, const struct sockaddr_in *dst,
+		       const unsigned char *buf, size_t len)
+{
+	return sendto(fd, buf, len, 0, (const struct sockaddr *)dst,
+		      sizeof(*dst)) == (ssize_t)len ? 0 : -1;
+}
+
+/* Wait for an ACK ("KXNA" next_offset status).  Returns next_offset, or -1
+ * on timeout. */
+static long wait_ack(int fd, unsigned int timeout_ms, uint32_t *status)
+{
+	struct timeval tv = { timeout_ms / 1000, (timeout_ms % 1000) * 1000 };
+	unsigned char buf[512];
+	uint32_t next_offset;
+
+	setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+	for (;;) {
+		ssize_t n = recv(fd, buf, sizeof(buf), 0);
+
+		if (n < 0)
+			return -1;                 /* timeout */
+		if (n < 12 || rd32(buf) != MAGIC_ACK)
+			continue;                  /* not ours */
+		next_offset = rd32(buf + 4);
+		*status = rd32(buf + 8);
+		return (long)next_offset;
+	}
+}
+
+int main(int argc, char **argv)
+{
+	const char *ip, *path;
+	unsigned int port;
+	unsigned int entry;
+	unsigned char *data, *pkt;
+	long size;
+	FILE *f;
+	unsigned int offset = 0, sum = 0;
+	int fd, i, fails = 0;
+	struct sockaddr_in dst;
+
+	if (argc != 5) {
+		fprintf(stderr, "usage: %s <board-ip> <port> <entry-hex> <file>\n", argv[0]);
+		return 2;
+	}
+	ip = argv[1];
+	port = (unsigned int)strtoul(argv[2], NULL, 0);
+	entry = (unsigned int)strtoul(argv[3], NULL, 16);
+	path = argv[4];
+
+	f = fopen(path, "rb");
+	if (!f) {
+		fprintf(stderr, "netkexec_send: %s: %s\n", path, strerror(errno));
+		return 1;
+	}
+	fseek(f, 0, SEEK_END);
+	size = ftell(f);
+	fseek(f, 0, SEEK_SET);
+	if (size <= 0 || size > 0x38200) {
+		fprintf(stderr, "netkexec_send: bad size %ld\n", size);
+		fclose(f);
+		return 1;
+	}
+	data = malloc((size_t)size);
+	if (!data || fread(data, 1, (size_t)size, f) != (size_t)size) {
+		fprintf(stderr, "netkexec_send: read failed\n");
+		fclose(f);
+		return 1;
+	}
+	fclose(f);
+	for (i = 0; i < size; i++)
+		sum += data[i];
+
+	fd = socket(AF_INET, SOCK_DGRAM, 0);
+	if (fd < 0) {
+		perror("socket");
+		return 1;
+	}
+	memset(&dst, 0, sizeof(dst));
+	dst.sin_family = AF_INET;
+	dst.sin_port = htons((uint16_t)port);
+	if (inet_pton(AF_INET, ip, &dst.sin_addr) != 1) {
+		fprintf(stderr, "netkexec_send: bad address %s\n", ip);
+		return 1;
+	}
+
+	pkt = malloc(12 + DATA_MAX);
+	printf("netkexec: %s:%u, %ld bytes, entry 0x%08x\n", ip, port, size, entry);
+
+	/* Header first: the board answers with the first expected offset. */
+	wr32(pkt, MAGIC_HDR);
+	wr32(pkt + 4, entry);
+	wr32(pkt + 8, (uint32_t)size);
+	wr32(pkt + 12, (uint32_t)sum);
+	for (i = 0; i < 20; i++) {
+		uint32_t status;
+		long ack;
+
+		if (send_packet(fd, &dst, pkt, 16) != 0) {
+			perror("sendto");
+			return 1;
+		}
+		ack = wait_ack(fd, 500, &status);
+		if (ack == 0)
+			break;
+		if (ack > 0) {
+			fprintf(stderr, "netkexec: unexpected ack offset %ld\n", ack);
+			return 1;
+		}
+	}
+	if (i == 20) {
+		fprintf(stderr, "netkexec: no ack from the board (is it running and idle?)\n");
+		return 1;
+	}
+
+	/* Stop-and-wait data transfer. */
+	while (offset < (unsigned int)size) {
+		unsigned int chunk = (unsigned int)size - offset;
+		uint32_t status = 0;
+		long ack;
+
+		if (chunk > DATA_MAX)
+			chunk = DATA_MAX;
+		wr32(pkt, MAGIC_DATA);
+		wr32(pkt + 4, offset);
+		wr32(pkt + 8, chunk);
+		memcpy(pkt + 12, data + offset, chunk);
+
+		if (send_packet(fd, &dst, pkt, 12 + chunk) != 0) {
+			perror("sendto");
+			return 1;
+		}
+		ack = wait_ack(fd, 500, &status);
+		if (ack < 0) {
+			if (++fails > 40) {
+				fprintf(stderr, "\nnetkexec: giving up at offset %u\n", offset);
+				return 1;
+			}
+			continue;                  /* retransmit */
+		}
+		fails = 0;
+		if (status == ACK_DONE && (unsigned int)ack == (unsigned int)size) {
+			offset = (unsigned int)ack;
+			break;
+		}
+		if (ack > (long)offset && (unsigned int)ack <= (unsigned int)size)
+			offset = (unsigned int)ack;
+		printf("\rnetkexec: %3u%% (%u/%ld bytes)", offset * 100 / (unsigned)size,
+		       offset, size);
+		fflush(stdout);
+	}
+	printf("\rnetkexec: 100%% (%ld bytes) - image accepted, board is jumping\n", size);
+	close(fd);
+	free(pkt);
+	free(data);
+	return 0;
+}

+ 126 - 0
netlog.c

@@ -0,0 +1,126 @@
+/* netlog: see netlog.h. */
+
+#include "net.h"
+#include "netdev.h"
+#include "timer.h"
+#include "netlog.h"
+
+#define NETLOG_RING      2048   /* producer/consumer byte ring */
+#define NETLOG_FLUSH_MIN 256    /* flush even without a newline at this size */
+#define NETLOG_IDLE_MS   100    /* flush a partial line after this idle time */
+
+static volatile unsigned char ring[NETLOG_RING];
+static volatile unsigned int head;
+static volatile unsigned int tail;
+static volatile unsigned int dropped;
+static volatile unsigned int last_append_ms;
+
+static int enabled;
+static unsigned char host_ip[4] = { 255, 255, 255, 255 };
+
+void netlog_init(void)
+{
+	head = tail = 0;
+	dropped = 0;
+	last_append_ms = get_ticks_ms();
+	enabled = 1;
+}
+
+void netlog_set_enabled(int on)
+{
+	enabled = on ? 1 : 0;
+}
+
+int netlog_get_enabled(void)
+{
+	return enabled;
+}
+
+void netlog_set_host(const unsigned char ip[4])
+{
+	unsigned int i;
+
+	for (i = 0; i < 4; i++)
+		host_ip[i] = ip[i];
+}
+
+void netlog_get_host(unsigned char ip[4])
+{
+	unsigned int i;
+
+	for (i = 0; i < 4; i++)
+		ip[i] = host_ip[i];
+}
+
+void netlog_char(char c)
+{
+	unsigned int next;
+
+	if (!enabled)
+		return;
+	next = (head + 1) % NETLOG_RING;
+	if (next == tail) {
+		dropped++;              /* full: drop, never block */
+		return;
+	}
+	ring[head] = (unsigned char)c;
+	head = next;
+	last_append_ms = get_ticks_ms();
+}
+
+static unsigned int pending(void)
+{
+	if (head >= tail)
+		return head - tail;
+	return NETLOG_RING - tail + head;
+}
+
+static void send_line(const unsigned char *buf, unsigned int len)
+{
+	static const unsigned char bcast_mac[6] = {
+		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
+	};
+	unsigned char dst[4];
+
+	netlog_get_host(dst);
+	net_udp_send(bcast_mac, dst, NETLOG_PORT, NETLOG_PORT, buf, len);
+}
+
+void netlog_flush(void)
+{
+	unsigned char buf[NET_UDP_MAX];
+	unsigned int n = 0, avail, idle, now;
+	static const char dropmsg[] = "[netlog: output dropped, buffer full]\n";
+	unsigned int i;
+
+	if (!enabled || netdev_in_use() || !netdev_active())
+		return;
+
+	avail = pending();
+	if (avail == 0)
+		return;
+
+	now = get_ticks_ms();
+	idle = now - last_append_ms;
+	if (avail < NETLOG_FLUSH_MIN && idle < NETLOG_IDLE_MS)
+		return;                 /* wait for a complete line */
+
+	if (dropped) {
+		send_line((const unsigned char *)dropmsg, sizeof(dropmsg) - 1);
+		dropped = 0;
+	}
+
+	/* One datagram, ending at a newline when possible. */
+	while (n < NET_UDP_MAX && tail != head) {
+		unsigned char c = ring[tail];
+
+		tail = (tail + 1) % NETLOG_RING;
+		buf[n++] = c;
+		if (c == '\n')
+			break;
+	}
+	if (n == 0)
+		return;
+	send_line(buf, n);
+	(void)i;
+}

+ 34 - 0
netlog.h

@@ -0,0 +1,34 @@
+/* netlog: mirror kernel debug output (COM1) and terminal text to UDP, so a
+ * serial-less board has a `make monitor` equivalent (`make netmon`).
+ *
+ * Producers (serial_putc / screen_putchar) only append to a RAM ring buffer;
+ * the WM loop flushes complete lines (or after a short idle delay) as UDP
+ * datagrams.  Nothing is sent before the NIC is up, and nothing blocks the
+ * producer. */
+#ifndef NETLOG_H
+#define NETLOG_H
+
+/* UDP port both the mirror and the `netlog` command use. */
+#define NETLOG_PORT 19290
+
+/* Enable the mirror and clear the buffer; call at boot (before the NIC is
+ * initialized, so the driver's bring-up trail is captured). */
+void netlog_init(void);
+
+/* Producer: append one character.  Cheap and safe from any context (IRQ,
+ * boot, process); drops the character when the ring is full. */
+void netlog_char(char c);
+
+/* Consumer: send pending text as one datagram (call from the WM loop). */
+void netlog_flush(void);
+
+void netlog_set_enabled(int on);
+int  netlog_get_enabled(void);
+
+/* Destination: all-0xFF (default) broadcasts; otherwise datagrams carry the
+ * broadcast MAC and this IP, so no ARP cache is needed (the switch floods
+ * them and the host with that address presents them to its sockets). */
+void netlog_set_host(const unsigned char ip[4]);
+void netlog_get_host(unsigned char ip[4]);
+
+#endif

+ 81 - 0
netmonitor.c

@@ -0,0 +1,81 @@
+/* Show the board's netlog stream (UDP, default port 19290) on the host: the
+ * network equivalent of `make monitor`.
+ *
+ *   netmonitor [port]
+ *
+ * Prints one line per datagram with a timestamp, so it plays well with
+ * `make netmon | tee board.log`.
+ */
+
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <time.h>
+#include <unistd.h>
+
+#define DEF_PORT 19290
+
+int main(int argc, char **argv)
+{
+	unsigned int port = DEF_PORT;
+	struct sockaddr_in addr;
+	unsigned char buf[4096];
+	int fd, on = 1;
+
+	if (argc > 2) {
+		fprintf(stderr, "usage: %s [port]\n", argv[0]);
+		return 2;
+	}
+	if (argc == 2)
+		port = (unsigned int)strtoul(argv[1], NULL, 0);
+
+	fd = socket(AF_INET, SOCK_DGRAM, 0);
+	if (fd < 0) {
+		perror("socket");
+		return 1;
+	}
+	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
+	memset(&addr, 0, sizeof(addr));
+	addr.sin_family = AF_INET;
+	addr.sin_addr.s_addr = htonl(INADDR_ANY);
+	addr.sin_port = htons((uint16_t)port);
+	if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
+		perror("bind");
+		return 1;
+	}
+
+	fprintf(stderr, "netmonitor: listening on UDP %u (Ctrl-C to exit)\n", port);
+	for (;;) {
+		struct sockaddr_in from;
+		socklen_t fromlen = sizeof(from);
+		ssize_t n = recvfrom(fd, buf, sizeof(buf) - 1, 0,
+				     (struct sockaddr *)&from, &fromlen);
+		time_t now;
+		struct tm tm;
+		char stamp[16];
+		const char *ip;
+		unsigned int i;
+
+		if (n < 0)
+			continue;
+		buf[n] = '\0';
+		now = time(NULL);
+		localtime_r(&now, &tm);
+		strftime(stamp, sizeof(stamp), "%H:%M:%S", &tm);
+		ip = inet_ntoa(from.sin_addr);
+
+		/* Prefix the first line; keep continuation lines readable. */
+		printf("[%s %s] ", stamp, ip);
+		for (i = 0; i < (unsigned int)n; i++) {
+			putchar(buf[i]);
+			if (buf[i] == '\n' && i + 1 < (unsigned int)n)
+				printf("[%s %s] ", stamp, ip);
+		}
+		if (n == 0 || buf[n - 1] != '\n')
+			putchar('\n');
+		fflush(stdout);
+	}
+}

+ 3 - 0
screen.c

@@ -1,6 +1,7 @@
 /* Text screen: cell-buffer text output (no framebuffer access). */
 
 #include "screen.h"
+#include "netlog.h"
 
 #define SCREEN_ATTR 0x0A  /* light green on black */
 
@@ -43,6 +44,8 @@ void screen_putchar(struct text_screen *s, char c)
 	unsigned int ncols = s->cols;
 	unsigned int total = s->cols * s->rows;
 
+	netlog_char(c);   /* terminal text also goes to the netlog mirror */
+
 	if (c == '\n') {
 		s->cursor = (s->cursor / ncols + 1) * ncols;
 		if (s->cursor >= total) {

+ 6 - 0
serial.c

@@ -1,5 +1,6 @@
 #include "serial.h"
 #include "serial_ring_buf.h"
+#include "netlog.h"
 #include "pci.h"
 #include "timer.h"
 
@@ -16,6 +17,11 @@ void serial_init(unsigned int port)
 
 void serial_putc(unsigned int port, char c)
 {
+	/* Mirror the debug console to the network (netlog; a no-op until the
+	 * mirror is enabled and the NIC is up). */
+	if (port == SERIAL_COM1)
+		netlog_char(c);
+
 	while (!(port_inb(port + 5) & 0x20))
 		;
 	port_outb(port, (unsigned char)c);

+ 39 - 0
terminal.c

@@ -39,6 +39,8 @@ 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_netlog_main(const char *arg);
+extern void program_netconsole_main(const char *arg);
 extern void program_netregs_main(void);
 extern void program_netloop_main(void);
 extern void program_netreset_main(void);
@@ -327,6 +329,34 @@ static int is_cmd_netinfo(const char *line, unsigned int line_len)
 	return (i == line_len);
 }
 
+static int is_cmd_netlog(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 + 6 > 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] != 'g')
+		return 0;
+	i += 6;
+	if (i < line_len && line[i] != ' ')
+		return 0;  /* "netlog" 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_netconsole(const char *line, unsigned int line_len, char *arg_buf, unsigned int buf_size)
 {
 	unsigned int i = 0, j = 0;
@@ -530,6 +560,7 @@ static int is_cmd_space(const char *line, unsigned int line_len)
 	return (i == line_len);
 }
 
+#define NET_UDP_ARG_MAX 128
 #define CAT_FNAME_MAX 64
 static int is_cmd_cat(const char *line, unsigned int line_len, char *filename_buf, unsigned int buf_size)
 {
@@ -1122,6 +1153,8 @@ void term_run(struct term *t)
 					char format_dev[FORMAT_DEV_MAX];
 					char netip_arg[16];
 					char netping_arg[16];
+					char netlog_arg[NET_UDP_ARG_MAX];
+					char netconsole_arg[NET_UDP_ARG_MAX];
 					char lspci_arg[16];
 					char peek_arg[32];
 					char resolved[VFS_PATH_MAX];
@@ -1168,6 +1201,10 @@ void term_run(struct term *t)
 						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_netlog(t->line, t->line_len, netlog_arg, sizeof(netlog_arg))) {
+						term_spawn_arg(t, "netlog", program_netlog_main, netlog_arg);
+					} else if (is_cmd_netconsole(t->line, t->line_len, netconsole_arg, sizeof(netconsole_arg))) {
+						term_spawn_arg(t, "netconsole", program_netconsole_main, netconsole_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)) {
@@ -1279,6 +1316,8 @@ void term_run(struct term *t)
 						io_putstr("netsend\n");
 						io_putstr("netip [a.b.c.d]\n");
 						io_putstr("netping <a.b.c.d>\n");
+						io_putstr("netlog <text>\n");
+						io_putstr("netconsole [on|off|host <ip>]\n");
 						io_putstr("netregs\n");
 						io_putstr("netloop\n");
 						io_putstr("netreset\n");

+ 13 - 1
wm.c

@@ -9,6 +9,8 @@
 #include "kdbg.h"
 #include "kexec.h"
 #include "mouse.h"
+#include "netkexec.h"
+#include "netlog.h"
 #include "process.h"
 #include "rtc.h"
 #include "timer.h"
@@ -592,10 +594,19 @@ static void wm_blink_cursor(void)
 
 static void wm_handle_kexec(void)
 {
-	if (!kexec_busy && kexec_pending()) {
+	if (kexec_busy)
+		return;
+	if (kexec_pending()) {
 		kexec_busy = 1;
 		if (process_create("kexec", program_kexec_main) < 0)
 			kexec_busy = 0;
+		return;
+	}
+	/* Same over UDP: the host's `make net-dev` is picked up from here. */
+	if (netkexec_pending()) {
+		kexec_busy = 1;
+		if (process_create("netkexec", program_netkexec_main) < 0)
+			kexec_busy = 0;
 	}
 }
 
@@ -607,6 +618,7 @@ void wm_run(void)
 		wm_handle_mouse();
 		wm_handle_keyboard();
 		wm_blink_cursor();
+		netlog_flush();
 		wm_handle_kexec();
 		wm_redraw_if_needed();
 		vga_fb_flush_pending_check();