Parcourir la source

Add a DHCP client and gateway routing

Johannes Zellner il y a 1 mois
Parent
commit
3ef50a5f7e
7 fichiers modifiés avec 624 ajouts et 28 suppressions
  1. 92 13
      AGENTS.md
  2. 5 2
      Makefile
  3. 404 0
      dhcp.c
  4. 20 0
      dhcp.h
  5. 7 3
      kernel.c
  6. 76 10
      netcmd.c
  7. 20 0
      terminal.c

+ 92 - 13
AGENTS.md

@@ -43,13 +43,13 @@ make clean
 | `0x900`   | kexec flat GDT + GDTR (built at runtime; below the kernel) |
 | `0x1000`  | E820 memory map (`struct e820_map`, written by `vesa_stage.S`, parsed by `mm.c`) |
 | `0x3000`  | UHCI frame list (1024 × 4 B, 4 KB-aligned; `uhci.c`) |
-| `0x20000` | (free — kernel upper bound used to be here, now `0x30000`) |
-| `0x30000` | ISA DMA buffer (`disk.c`) + kernel upper bound (`kernel.ld` ASSERT) |
-| `0x30800` | Protected-mode stack top (`vesa_stage.S`) |
-| `0x30F00` | Program API struct (`PROGRAM_API_ADDR`, `run_api.h`) |
-| `0x31000` | User program load address (`run.c`, `user.ld`) |
-| `0x42000` | Fallback process stack pool (8 × 4 KB; primary stacks come from the frame allocator, ≥ `0x900000`, see `process.c`/`mm.c`) |
-| `0x50000` | kexec staging buffer (received kernel image, up to 0x28200 B) |
+| `0x4000`  | ISA DMA buffer, one sector (`disk.c`) |
+| `0x40000` | Kernel upper bound (`kernel.ld` ASSERT) |
+| `0x40800` | Protected-mode stack top (`vesa_stage.S`, `kexec_tramp.S`) |
+| `0x40F00` | Program API struct (`PROGRAM_API_ADDR`, `run_api.h`) |
+| `0x41000` | User program load address (`run.c`, `user.ld`) |
+| `0x50000` | Fallback process stack pool (8 × 4 KB; primary stacks come from the frame allocator, ≥ `0x900000`, see `process.c`/`mm.c`) |
+| `0x58000` | kexec staging buffer (received kernel image, up to 0x38200 B; ends below the VGA window) |
 | `0x100000`| VGA shadow buffer (`VGA_SHADOW_BASE`, `vga.h`) |
 
 ## Key files
@@ -65,7 +65,7 @@ make clean
   1 MB and an 8 MB VGA-shadow region. `kmalloc.c/h` — a power-of-two heap
   allocator on top of the frame allocator (used for the process table). Process
   stacks (≥ `0x900000`) come from the frame allocator, with an 8-stack fallback
-  pool at `0x42000`.
+  pool at `0x50000`.
 - **Paging**: `paging.c/h` — identity-maps RAM (4 MB pages via CR4.PSE) + the
   LFB (uncacheable) and enables CR0.PG/WP. A single shared page directory for
   now (no per-process address spaces yet). The kexec trampoline
@@ -91,24 +91,53 @@ make clean
   `blkdev.c` (floppy + IDE registry), `ata.c` (ATA PIO), `disk.c` (FDC + ISA DMA ch2, retries).
 - **Serial**: `serial.c`, `serial_ring_buf.c/h`, `bin_recv.c/h`, `serial_recv.c`,
   `serial_loop.c`, `send_serial.c` — 16550 UART, IRQ-driven ring buffer, XMODEM.
+- **Network**: `netdev.c/h` — NIC driver registry (`struct netdev`, first probe
+  wins; drivers: `r8168.c` RTL8111/8168 (PCIe, polled, C+ mode) and `ne2000.c`
+  RTL8029 (QEMU/ISA)). `net.c` — ARP + ICMP echo, IPv4/UDP send + parse helpers,
+  frame decode, `net_checksum()`. `dhcp.c` — minimal DHCP client (DISCOVER →
+  OFFER → REQUEST → ACK; runs at boot when a NIC is present, 3 s budget, keeps
+  the static address when no server answers; `dhcp` re-runs it). `netcmd.c` —
+  the
+  `netinfo`/`netrecv`/`netsend`/`netip`/`dhcp`/`ping`/`netping`/`netregs`
+  commands.  Static IP default `192.168.178.240`, mask/gateway learned from
+  DHCP (off-subnet `netping` goes via the router).
 - **Hot-reload (kexec)**: `kexec.c/h`, `kexec_tramp.S`, `bootstrap.c`, and the
   host-side `kexec_send.c` — reload the kernel over serial without rebooting
   (C-light: reuses the current framebuffer, re-runs `kernel_main`).
+  `netkexec.c/h` + host-side `netkexec_send.c` do the same over UDP
+  (`make net-dev BOARD_IP=…`): the WM loop auto-detects the header, the board
+  acks every datagram with the next expected offset, verifies the checksum and
+  jumps. While idle the same loop answers ARP/ICMP for our IP, so the board is
+  reachable (and MAC-resolvable) without running any command.
 - **Mouse**: `mouse.c` — PS/2 + IntelliMouse, hardware cursor.
 - **USB**: `uhci.c/h`, `usb.c/h`, `lsusb.c` — UHCI host controller (PCI scan,
   polling transfers, no IRQ), USB core enumeration with hub recursion, and the
   `lsusb` command.
 - **Power/idle**: `idle.c` — `mwait` C-states, `hlt` fallback.
 - **User programs**: `run.c`, `run_api.h`, `prog.c`, `space.c` — raw binaries at
-  `0x31000`, API function-pointer struct at `0x30F00`. `space` = Space Invaders.
+  `0x41000`, API function-pointer struct at `0x40F00`. `space` = Space Invaders.
 
 ## Shell commands
 
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`, `run <file>`, `space`,
-`clock`, `colors`, `display`, `cpuinfo`, `mouseinfo`, `lsusb`, `storage`, `mem`, `format <device>`,
+`clock`, `colors`, `display`, `cpuinfo`, `mouseinfo`, `lsusb`, `lspci [id]`, `peek <addr> [len]`, `storage`, `mem`, `format <device>`,
 `ps`, `kill <pid>`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`.
 
+Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
+DHCP client), `ping` (responds to ARP/ICMP for our IP for 30 s),
+`netping <a.b.c.d>` (active ARP + ICMP echo with RTT, via the gateway when the
+target is off-subnet), `netloop` (PHY loopback TX/RX self-test), `netreset`
+(full NIC re-init), `netlog <text>` (one UDP datagram to port 19290),
+`netconsole on|off|host <a.b.c.d>` (the debug-output mirror, see below) and
+`netregs` (register dump, decoded ISR + counters).  On boot, if a NIC is
+present, a DHCP client runs with a 3 s budget (requesting the current address)
+and falls back to the static default when no server answers.  The board also
+answers ARP/ICMP for its IP while idle.
+`lspci` lists every PCI function (one line each); with a filter (`lspci 8168`,
+`lspci 02`) it also prints BAR details, type and size for matching functions.
+`peek <addr> [len]` hex-dumps memory (identity map, so MMIO registers too).
+
 Each terminal has a current working directory (shown in the prompt as `[dir] > `),
 changed with `cd`; paths may be absolute (`/floppy1/…`) or relative (`.`, `..`,
 nested). `/` is the read-only VFS root listing the mounted filesystems (the
@@ -161,6 +190,54 @@ lives inside the overwritten kernel region), so it's safe to edit any file,
 including `vesa_stage.S`/`boot.S` layout — but the video *mode* itself is only
 re-applied on a full floppy/USB boot (C-light reuses the current LFB).
 
+## Network hot-reload (net-dev) workflow
+
+For boards without a serial console (the ASUS AT3IONT-I), the same reload runs
+over the network instead:
+
+```sh
+make net-dev                    # pushes kernel.bin to BOARD_IP (default 192.168.178.240)
+make net-dev BOARD_IP=192.168.178.42
+```
+
+The board must be idle at a shell prompt: the WM loop polls the NIC, answers
+ARP/ICMP for its IP, and auto-detects the `"KXNU"` header datagram (UDP port
+19288).  The host tool (`netkexec_send.c`) then does a stop-and-wait transfer:
+the board acks every datagram with the next expected offset, verifies the
+32-bit checksum and jumps.  ~130 KB takes about a second on a wired LAN.
+While a net command owns the receiver (`netrecv`/`ping`/`netping`/`netloop`)
+or a kexec is in progress, the auto-detect pauses.
+
+The board's address comes from DHCP when a server is present (the DHCP client
+runs at boot; `netinfo` shows ip/mask/gateway and the lease), so use
+`make net-dev BOARD_IP=<leased address>` — or `netip` on the board to pin one.
+
+## Network console (`make netmon`)
+
+The serial console is mirrored to UDP port 19290, so a board without a serial
+port gets the same visibility as `make monitor`:
+
+- everything written to COM1 (`serial_puts` — driver bring-up trails, MTRR
+  dumps, kexec progress) and
+- everything written to a terminal screen (`io_putstr` — shell output, command
+  results, `netrecv` dumps)
+
+is buffered in RAM as it is produced and flushed from the WM loop as
+line-sized datagrams.  On the host:
+
+```sh
+make netmon                 # builds + runs netmonitor (Ctrl-C to exit)
+make netmon | tee board.log
+./netmonitor 19290          # different port
+```
+
+The mirror is **on** by default and broadcasts; `netconsole host <laptop-ip>`
+narrows it to one host (datagrams carry the broadcast MAC, so the board needs
+no ARP entry for it), `netconsole off`/`on` toggles it, and `netlog <text>`
+sends an ad-hoc line.  Nothing is sent before the NIC is up, the producer
+never blocks (a full buffer drops characters and reports it), and the flush
+pauses while a net command owns the receiver.
+
 ## Serial debug monitor (`dbg`)
 
 A ring-0 debugger driven over the serial link. On the PC type `dbg`, then drive
@@ -234,7 +311,7 @@ was wedged in firmware/SMM before IRQ1 was delivered.
 Layout (bottom-left, and a heartbeat square bottom-right):
 
 ```
-MTRRdef 00000E06 vcnt 8            <- boot info rows (yellow), up to 10
+MTRRdef 00000E06 vcnt 8            <- boot info rows (yellow), up to 14
 M0 b=00000000 m=FF000800 WB
 ...
 WC=e7 b=FD000000 s=00800000
@@ -269,9 +346,11 @@ API / wiring:
 
 - `kdbg_init()` — cache LFB geometry; call after `vga_shadow_init()`.
 - `kdbg_status()` — redraw the live rows; called from key paths and the PIT.
-- `kdbg_info(row, s)` — set one of 10 info rows (row 0 = lowest, at
+- `kdbg_info(row, s)` — set one of 14 info rows (row 0 = lowest, at
   `fb_h-31`). Text is **copied**, so stack buffers are fine, and it is safe to
   call before `kdbg_init()` (stored, drawn once the framebuffer is up).
+- `kdbg_info_alloc()` — claim the next free info row (`-1` when full); boot
+  subsystems (MTRR dump, NIC) take rows in init order without colliding.
 - `kdbg_pit_tick()` — called from the PIT stub (`switch.S`); blinks the
   heartbeat and refreshes the overlay every second.
 - Counters live in `kdbg.c`, bumped from `io.c` (`kbd_irq`,
@@ -282,7 +361,7 @@ Caveats:
 
 - Pixels are written directly to the LFB; WM full redraws overwrite them but
   the 1 Hz refresh brings them back.
-- Info rows cost ~0.5 KB BSS; the kernel must stay under the `0x30000`
+- Info rows cost ~0.5 KB BSS; the kernel must stay under the `0x40000`
   boundary (`kernel.ld` ASSERT).
 
 ## Conventions & gotchas

+ 5 - 2
Makefile

@@ -155,6 +155,9 @@ netkexec.o: netkexec.c netkexec.h io.h kexec.h net.h netdev.h timer.h
 netlog.o: netlog.c netlog.h net.h netdev.h timer.h
 	$(CC) $(CFLAGS) -o $@ $<
 
+dhcp.o: dhcp.c dhcp.h io.h net.h netdev.h timer.h
+	$(CC) $(CFLAGS) -o $@ $<
+
 netdev.o: netdev.c netdev.h ne2000.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -248,7 +251,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 netkexec.o netlog.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 dhcp.o hello_embed.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -448,4 +451,4 @@ net-dev: kernel.bin netkexec_send
 	./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 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
+	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 dhcp.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

+ 404 - 0
dhcp.c

@@ -0,0 +1,404 @@
+/* Minimal DHCP client: see dhcp.h. */
+
+#include "io.h"
+#include "net.h"
+#include "netdev.h"
+#include "timer.h"
+#include "dhcp.h"
+
+#define DHCP_SERVER_PORT 67
+#define DHCP_CLIENT_PORT 68
+
+#define DHCP_OP_REQUEST  1
+#define DHCP_OP_REPLY    2
+
+#define DHCP_DISCOVER    1
+#define DHCP_OFFER       2
+#define DHCP_REQUEST     3
+#define DHCP_ACK         5
+#define DHCP_NAK         6
+
+/* BOOTP header (236 bytes) + cookie + options, padded to a 300-byte DHCP
+ * message (RFC 2131 minimum). */
+#define DHCP_MSG_LEN     300
+#define DHCP_HDR_LEN     236
+#define DHCP_MAGIC_OFF   236
+#define DHCP_OPT_OFF     240
+
+static unsigned char msg[DHCP_MSG_LEN];
+static unsigned char rxbuf[1520];
+
+/* Last successful lease (for `netinfo`). */
+static int have_info;
+static unsigned char last_server[4];
+static unsigned int last_lease;
+
+static void put_ip(const unsigned char *ip)
+{
+	unsigned int i;
+
+	for (i = 0; i < 4; i++) {
+		unsigned int v = ip[i];
+
+		if (i)
+			io_putchar('.');
+		if (v >= 100) {
+			io_putchar((char)('0' + v / 100));
+			v %= 100;
+			io_putchar((char)('0' + v / 10));
+			v %= 10;
+		} else if (v >= 10) {
+			io_putchar((char)('0' + v / 10));
+			v %= 10;
+		}
+		io_putchar((char)('0' + v));
+	}
+}
+
+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]);
+}
+
+static unsigned int rd32be(const unsigned char *p)
+{
+	return ((unsigned int)p[0] << 24) | ((unsigned int)p[1] << 16) |
+	       ((unsigned int)p[2] << 8) | p[3];
+}
+
+static void wr32be(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)(v >> 24);
+	p[1] = (unsigned char)(v >> 16);
+	p[2] = (unsigned char)(v >> 8);
+	p[3] = (unsigned char)v;
+}
+
+/* Build a DHCP message of the given type.  `requested` (may be NULL) goes
+ * into option 50 so the router tends to hand back the address we ask for. */
+static void dhcp_build(unsigned char type, const unsigned char *my_mac,
+		       unsigned int xid, unsigned int secs,
+		       const unsigned char *requested,
+		       const unsigned char *server_id)
+{
+	unsigned int i, o;
+
+	for (i = 0; i < DHCP_MSG_LEN; i++)
+		msg[i] = 0;
+
+	msg[0] = DHCP_OP_REQUEST;
+	msg[1] = 1;                    /* htype: Ethernet */
+	msg[2] = 6;                    /* hlen */
+	msg[3] = 0;                    /* hops */
+	wr32be(msg + 4, xid);
+	msg[8] = (unsigned char)(secs >> 8);
+	msg[9] = (unsigned char)secs;
+	msg[10] = 0x80;                /* flags: broadcast replies */
+	msg[11] = 0;
+	/* ciaddr/yiaddr/siaddr/giaddr stay zero */
+	for (i = 0; i < 6; i++)
+		msg[28 + i] = my_mac[i];   /* chaddr */
+	msg[DHCP_MAGIC_OFF + 0] = 0x63;
+	msg[DHCP_MAGIC_OFF + 1] = 0x82;
+	msg[DHCP_MAGIC_OFF + 2] = 0x53;
+	msg[DHCP_MAGIC_OFF + 3] = 0x63;
+
+	o = DHCP_OPT_OFF;
+	msg[o++] = 53; msg[o++] = 1; msg[o++] = type;           /* message type */
+	msg[o++] = 61; msg[o++] = 7; msg[o++] = 1;               /* client id */
+	for (i = 0; i < 6; i++)
+		msg[o++] = my_mac[i];
+	{
+		static const char hostname[] = "nebos";
+		unsigned int n = sizeof(hostname) - 1;
+
+		msg[o++] = 12;                                  /* host name */
+		msg[o++] = (unsigned char)n;
+		for (i = 0; i < n; i++)
+			msg[o++] = (unsigned char)hostname[i];
+	}
+	msg[o++] = 55; msg[o++] = 4;                            /* param request */
+	msg[o++] = 1; msg[o++] = 3; msg[o++] = 6; msg[o++] = 51;
+	if (requested) {
+		msg[o++] = 50; msg[o++] = 4;
+		for (i = 0; i < 4; i++)
+			msg[o++] = requested[i];
+	}
+	if (server_id) {
+		msg[o++] = 54; msg[o++] = 4;
+		for (i = 0; i < 4; i++)
+			msg[o++] = server_id[i];
+	}
+	msg[o++] = 255;                                         /* end */
+}
+
+/* Parse a reply; returns 1 for "ours" and fills the option values. */
+static int dhcp_parse(const unsigned char *frame, unsigned int len,
+		      unsigned int xid, const unsigned char *my_mac,
+		      unsigned char *type, unsigned char yiaddr[4],
+		      unsigned char mask[4], unsigned char gw[4],
+		      unsigned int *lease, unsigned char server[4])
+{
+	const unsigned char *p;
+	unsigned char s_ip[4], d_ip[4];
+	unsigned int sport, dport, plen, i, o;
+
+	if (!net_udp_parse(frame, len, s_ip, d_ip, &sport, &dport, &p, &plen))
+		return 0;
+	if (dport != DHCP_CLIENT_PORT)
+		return 0;
+	if (plen < DHCP_OPT_OFF || p[0] != DHCP_OP_REPLY)
+		return 0;
+	if (p[DHCP_MAGIC_OFF] != 0x63 || p[DHCP_MAGIC_OFF + 1] != 0x82 ||
+	    p[DHCP_MAGIC_OFF + 2] != 0x53 || p[DHCP_MAGIC_OFF + 3] != 0x63)
+		return 0;
+	if (rd32be(p + 4) != xid)
+		return 0;
+	for (i = 0; i < 6; i++) {
+		if (p[28 + i] != my_mac[i])
+			return 0;
+	}
+
+	*type = 0;
+	for (i = 0; i < 4; i++) {
+		yiaddr[i] = p[16 + i];
+		mask[i] = 0;
+		gw[i] = 0;
+		server[i] = 0;
+	}
+	*lease = 0;
+
+	/* Option walk. */
+	o = DHCP_OPT_OFF;
+	while (o + 1 < plen) {
+		unsigned char code = p[o];
+		unsigned int olen;
+
+		if (code == 0) {        /* pad */
+			o++;
+			continue;
+		}
+		if (code == 255)        /* end */
+			break;
+		if (o + 1 >= plen)
+			break;
+		olen = p[o + 1];
+		if (o + 2 + olen > plen)
+			break;
+		switch (code) {
+		case 53:
+			if (olen >= 1)
+				*type = p[o + 2];
+			break;
+		case 1:
+			if (olen >= 4)
+				for (i = 0; i < 4; i++)
+					mask[i] = p[o + 2 + i];
+			break;
+		case 3:
+			if (olen >= 4)
+				for (i = 0; i < 4; i++)
+					gw[i] = p[o + 2 + i];
+			break;
+		case 51:
+			if (olen >= 4)
+				*lease = rd32be(p + o + 2);
+			break;
+		case 54:
+			if (olen >= 4)
+				for (i = 0; i < 4; i++)
+					server[i] = p[o + 2 + i];
+			break;
+		default:
+			break;
+		}
+		o += 2 + olen;
+	}
+	(void)sport;
+	return *type != 0;
+}
+
+/* Wait for a reply of the wanted type until `deadline`. */
+static int dhcp_wait(const struct netdev *nd, unsigned int xid,
+		     const unsigned char *my_mac, unsigned int deadline,
+		     unsigned char want, unsigned char yiaddr[4],
+		     unsigned char mask[4], unsigned char gw[4],
+		     unsigned int *lease, unsigned char server[4])
+{
+	while ((int)(get_ticks_ms() - deadline) < 0) {
+		unsigned char type;
+		unsigned char ryi[4], rmask[4], rgw[4], rserver[4];
+		unsigned int rlease;
+		int len = nd->rx(rxbuf, sizeof(rxbuf));
+
+		if (len < 0)
+			continue;
+		if (!dhcp_parse(rxbuf, (unsigned int)len, xid, my_mac, &type,
+				ryi, rmask, rgw, &rlease, rserver))
+			continue;
+		if (type == DHCP_NAK)
+			return -2;
+		if (type != want)
+			continue;
+		{
+			unsigned int i;
+
+			for (i = 0; i < 4; i++) {
+				yiaddr[i] = ryi[i];
+				mask[i] = rmask[i];
+				gw[i] = rgw[i];
+				server[i] = rserver[i];
+			}
+		}
+		*lease = rlease;
+		return 0;
+	}
+	return -1;
+}
+
+int dhcp_run(unsigned int timeout_ms)
+{
+	static const unsigned char bcast_mac[6] = {
+		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
+	};
+	static const unsigned char bcast_ip[4] = { 255, 255, 255, 255 };
+	static const unsigned char zero_ip[4] = { 0, 0, 0, 0 };
+	const struct netdev *nd = netdev_active();
+	unsigned char my_mac[6], want_ip[4], current[4];
+	unsigned char yiaddr[4], mask[4], gw[4], server[4];
+	unsigned int xid, start, deadline, tries;
+	unsigned int lease = 0;
+
+	if (!nd || !nd->get_mac)
+		return -2;
+	nd->get_mac(my_mac);
+	net_get_ip(current);
+	/* Try to get the address we would use anyway (static default or the
+	 * previous lease): most routers honour option 50. */
+	for (tries = 0; tries < 4; tries++)
+		want_ip[tries] = current[tries];
+
+	xid = (get_ticks_ms() << 8) ^ ((unsigned int)my_mac[3] << 16) ^
+	      ((unsigned int)my_mac[4] << 8) ^ my_mac[5];
+	start = get_ticks_ms();
+	deadline = start + timeout_ms;
+
+	netdev_acquire();
+	io_putstr("dhcp: DISCOVER\n");
+
+	/* DISCOVER -> OFFER */
+	for (tries = 0; tries < 3; tries++) {
+		unsigned int wait_until = get_ticks_ms() + 600;
+
+		if ((int)(wait_until - deadline) > 0)
+			wait_until = deadline;
+		dhcp_build(DHCP_DISCOVER, my_mac, xid,
+			   get_ticks_ms() - start, want_ip, 0);
+		if (net_udp_send_from(zero_ip, bcast_mac, bcast_ip,
+				      DHCP_CLIENT_PORT, DHCP_SERVER_PORT,
+				      msg, DHCP_MSG_LEN) != 0) {
+			netdev_release();
+			return -2;
+		}
+		if (dhcp_wait(nd, xid, my_mac, wait_until, DHCP_OFFER,
+			      yiaddr, mask, gw, &lease, server) == 0)
+			break;
+		if ((int)(get_ticks_ms() - deadline) >= 0)
+			break;
+	}
+	if (tries == 3) {
+		netdev_release();
+		io_putstr("dhcp: no server, keeping ");
+		put_ip(current);
+		io_putchar('\n');
+		return -1;
+	}
+
+	io_putstr("dhcp: offer ");
+	put_ip(yiaddr);
+	io_putstr(" from ");
+	put_ip(server);
+	io_putchar('\n');
+
+	/* REQUEST -> ACK */
+	for (tries = 0; tries < 3; tries++) {
+		unsigned int wait_until = get_ticks_ms() + 600;
+		int r;
+
+		if ((int)(wait_until - deadline) > 0)
+			wait_until = deadline;
+		dhcp_build(DHCP_REQUEST, my_mac, xid,
+			   get_ticks_ms() - start, yiaddr, server);
+		if (net_udp_send_from(zero_ip, bcast_mac, bcast_ip,
+				      DHCP_CLIENT_PORT, DHCP_SERVER_PORT,
+				      msg, DHCP_MSG_LEN) != 0) {
+			netdev_release();
+			return -2;
+		}
+		r = dhcp_wait(nd, xid, my_mac, wait_until, DHCP_ACK,
+			      yiaddr, mask, gw, &lease, server);
+		if (r == 0)
+			break;
+		if (r == -2) {          /* NAK: start over */
+			netdev_release();
+			io_putstr("dhcp: NAK, retrying\n");
+			return dhcp_run(timeout_ms);
+		}
+		if ((int)(get_ticks_ms() - deadline) >= 0)
+			break;
+	}
+	if (tries == 3) {
+		netdev_release();
+		io_putstr("dhcp: no ACK, keeping ");
+		put_ip(current);
+		io_putchar('\n');
+		return -1;
+	}
+
+	net_configure(yiaddr, mask, gw);
+	have_info = 1;
+	{
+		unsigned int i;
+
+		for (i = 0; i < 4; i++)
+			last_server[i] = server[i];
+	}
+	last_lease = lease;
+
+	io_putstr("dhcp: ack ");
+	put_ip(yiaddr);
+	io_putstr("/");
+	put_ip(mask);
+	io_putstr(" gw ");
+	put_ip(gw);
+	io_putstr(" lease ");
+	put_dec(lease);
+	io_putstr("s\n");
+
+	netdev_release();
+	return 0;
+}
+
+int dhcp_last_info(unsigned char server[4], unsigned int *lease_s)
+{
+	unsigned int i;
+
+	if (!have_info)
+		return 0;
+	for (i = 0; i < 4; i++)
+		server[i] = last_server[i];
+	*lease_s = last_lease;
+	return 1;
+}

+ 20 - 0
dhcp.h

@@ -0,0 +1,20 @@
+/* Minimal DHCP client (RFC 2131): DISCOVER -> OFFER -> REQUEST -> ACK over
+ * UDP broadcast, so a board with a NIC gets an address at boot.
+ *
+ * Runs before the WM loop (bounded to a few seconds) and on demand with the
+ * `dhcp` command.  On failure the previously configured address is kept (the
+ * static default), so nothing depends on a DHCP server being present. */
+#ifndef DHCP_H
+#define DHCP_H
+
+/* Run the client with an overall time budget.  Returns:
+ *   0  = an address was obtained and applied (net_configure),
+ *  -1  = no server answered (configuration unchanged),
+ *  -2  = protocol error / no NIC. */
+int dhcp_run(unsigned int timeout_ms);
+
+/* Info from the last successful run (server id + lease seconds).  Returns 1
+ * if a lease has been obtained. */
+int dhcp_last_info(unsigned char server[4], unsigned int *lease_s);
+
+#endif

+ 7 - 3
kernel.c

@@ -7,6 +7,7 @@
 #include "mm.h"
 #include "mouse.h"
 #include "netdev.h"
+#include "dhcp.h"
 #include "netlog.h"
 #include "paging.h"
 #include "process.h"
@@ -175,6 +176,9 @@ void kernel_main(void)
 
 	serial_init(SERIAL_COM1);
 	serial_ring_init();
+	/* 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();
 	serial_puts(SERIAL_COM1, "\n" OS_NAME " v" OS_VERSION " booted\n");
 	mm_init();
 	mm_dump();
@@ -199,8 +203,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();
+	/* With a NIC present, try DHCP; on failure the static default stays. */
+	if (netdev_active())
+		dhcp_run(3000);
 	wm_run();
 }

+ 76 - 10
netcmd.c

@@ -5,6 +5,7 @@
 #include "timer.h"
 #include "netdev.h"
 #include "net.h"
+#include "dhcp.h"
 #include "netlog.h"
 
 /* Shared frame buffers (file scope, not stack: the 4 KB process stack can't
@@ -69,6 +70,8 @@ static int ip_eq(const unsigned char *a, const unsigned char *b)
 void program_netinfo_main(void)
 {
 	const struct netdev *nd = netdev_active();
+	unsigned char ip[4], mask[4], gw[4], server[4];
+	unsigned int lease = 0;
 
 	if (!nd) {
 		io_putstr("netinfo: no NIC found\n");
@@ -80,9 +83,45 @@ void program_netinfo_main(void)
 	io_putstr(nd->chip);
 	io_putstr(")\n");
 	nd->print_info();
+
+	net_get_ip(ip);
+	net_get_mask(mask);
+	net_get_gateway(gw);
 	io_putstr("ip=");
-	net_print_ip();
+	put_ip(ip);
+	if (mask[0] || mask[1] || mask[2] || mask[3]) {
+		io_putstr("/");
+		put_ip(mask);
+	}
 	io_putchar('\n');
+	if (gw[0] || gw[1] || gw[2] || gw[3]) {
+		io_putstr("gw=");
+		put_ip(gw);
+		io_putchar('\n');
+	}
+	if (dhcp_last_info(server, &lease)) {
+		io_putstr("dhcp: server ");
+		put_ip(server);
+		io_putstr(" lease ");
+		put_dec(lease);
+		io_putstr("s\n");
+	}
+}
+
+/* ---- dhcp ---- */
+
+void program_dhcp_main(void)
+{
+	switch (dhcp_run(4000)) {
+	case 0:
+		break;                  /* dhcp_run() printed the lease */
+	case -1:
+		/* message already printed */
+		break;
+	default:
+		io_putstr("dhcp: no NIC\n");
+		break;
+	}
 }
 
 /* ---- netregs: driver register dump ---- */
@@ -643,21 +682,48 @@ static void netping_run(const char *arg)
 	nd->get_mac(my_mac);
 	net_get_ip(my_ip);
 
+	/* With a mask and gateway known, off-subnet targets go via the router;
+	 * we can only ARP for the next hop. */
 	{
-		int r = netping_arp(nd, my_mac, my_ip, target, target_mac);
-
-		if (r == -2) {
-			io_putstr("netping: transmit failed (see netregs)\n");
-			return;
+		unsigned char mask[4], gw[4], hop[4];
+		unsigned int j, off = 0;
+
+		net_get_mask(mask);
+		net_get_gateway(gw);
+		for (j = 0; j < 4; j++)
+			hop[j] = target[j];
+		if ((mask[0] || mask[1] || mask[2] || mask[3]) &&
+		    (gw[0] || gw[1] || gw[2] || gw[3])) {
+			for (j = 0; j < 4; j++) {
+				if ((target[j] & mask[j]) != (my_ip[j] & mask[j]))
+					off = 1;
+			}
 		}
-		if (r != 0) {
-			io_putstr("netping: no ARP reply from ");
+		if (off) {
+			for (j = 0; j < 4; j++)
+				hop[j] = gw[j];
+			io_putstr("netping: ");
 			put_ip(target);
+			io_putstr(" via ");
+			put_ip(hop);
 			io_putchar('\n');
-			return;
 		}
-	}
 
+		{
+			int r = netping_arp(nd, my_mac, my_ip, hop, 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(hop);
+				io_putchar('\n');
+				return;
+			}
+		}
+	}
 	io_putstr("netping: ");
 	put_ip(target);
 	io_putstr(" is-at ");

+ 20 - 0
terminal.c

@@ -41,6 +41,7 @@ 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_dhcp_main(void);
 extern void program_netregs_main(void);
 extern void program_netloop_main(void);
 extern void program_netreset_main(void);
@@ -387,6 +388,22 @@ static int is_cmd_netconsole(const char *line, unsigned int line_len, char *arg_
 	return (i == line_len);
 }
 
+static int is_cmd_dhcp(const char *line, unsigned int line_len)
+{
+	unsigned int i = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 4 > line_len)
+		return 0;
+	if (line[i] != 'd' || line[i+1] != 'h' || line[i+2] != 'c' ||
+	    line[i+3] != 'p')
+		return 0;
+	i += 4;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
 static int is_cmd_netregs(const char *line, unsigned int line_len)
 {
 	unsigned int i = 0;
@@ -1205,6 +1222,8 @@ void term_run(struct term *t)
 						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_dhcp(t->line, t->line_len)) {
+						term_spawn(t, "dhcp", program_dhcp_main);
 					} 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)) {
@@ -1318,6 +1337,7 @@ void term_run(struct term *t)
 						io_putstr("netping <a.b.c.d>\n");
 						io_putstr("netlog <text>\n");
 						io_putstr("netconsole [on|off|host <ip>]\n");
+						io_putstr("dhcp\n");
 						io_putstr("netregs\n");
 						io_putstr("netloop\n");
 						io_putstr("netreset\n");