SchOS/kernel/dev/device.c
Nexoniarz 20cc673a41 net: a network *class*, so the stack stops knowing what an e1000 is
The TCP/IP stack reached straight into the first driver anyone wrote.
net.c called e1000_present(), the lwIP glue was named netif_e1000.c and
called e1000_transmit(), and include/defs.h declared the driver's
internals to the whole kernel. The second NIC driver would therefore
have arrived with a near-identical copy of the glue file and a patch to
the protocol stack, which is the arrangement include/device.h was
written to prevent -- the e1000 even said so, with `.ops = 0, // no
class vtable yet; there is no net class`.

There is now. A driver publishes a struct netdev_ops -- transmit,
receive, mac, link_up -- and is finished: it never mentions lwIP, and
nothing above it learns its name. The display class was already this
shape; this is the same shape for networking, and the two now read the
same way in kernel/dev/device.c.

What that made possible immediately:

  - One netif per bound device instead of one per driver. lwIP's glue is
    netif_eth.c, it takes a struct device, and it holds up to NETIF_MAX
    interfaces. net.c attaches every network device it finds and starts
    DHCP on each, because which interface the network answers on is not
    ours to decide.
  - /proc/netif lists all of them, one block of fields each, with the
    interface name and the driver that claimed it.
  - The ARP self-test moved from the e1000 to the class. Nothing in it
    was chip-specific, and it is the first thing anyone will want to run
    against the next driver. Still `echo n > /proc/sysrq`.
  - Private headers live with their driver: e1000.h was in include/,
    where exactly one file could use it. The driver build now adds the
    driver's own directory to the include path.

The e1000 also drives more than one card. Its probe() refused the second
outright, because there was a single static instance -- so a machine
with two of them drove one and silently ignored the other. Instances are
an array now, and the instance is hung on dev->priv by a new optional
`attached` hook that the bus calls once the device exists. probe() runs
before device_add(), so there was previously nowhere to put it; that is
the whole reason the hook exists rather than a line inside probe.

QEMU gets an explicit NIC on every target (QEMU_NET). The default device
happens to be an e1000 on this machine type today, which is exactly the
sort of thing that stays true until a QEMU release changes it and the
network stops being exercised without anyone noticing.

Verified:
  - bootcheck -Net passes, 48 [ok], no failures -- including the moved
    self-test and two new checks that /proc/netif names both the
    interface and the driver behind it, which together say the stack
    went through the class rather than through a driver it was compiled
    to know.
  - Two NICs attached by hand (-device e1000 twice, second with its own
    MAC): eth0 and eth1 both attach, each reports its own MAC in
    /proc/netif, and each gets its own DHCP lease. Before this commit
    the same machine produced one interface.
  - make schfs-check still passes in full.

One trap worth recording: moving a header broke the build for anyone
with stale .d files -- make stopped with "No rule to make target
'include/e1000.h'". CFLAGS gains -MP, which emits a phony target per
header so a moved or deleted one can never wedge the build again.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 16:42:34 +02:00

467 lines
14 KiB
C

// The device model. See include/device.h for why it exists.
//
// A fixed table rather than a linked list: this is populated once during boot
// by whichever bus found each device, and read afterwards. Nothing is removed
// yet -- hot-unplug would need it, and when that arrives the in_use flag is
// already the hook for it.
//
// No lock. Every device_add() happens during single-threaded boot, before
// userspace exists, and every reader afterwards only walks. If a bus ever
// enumerates at runtime -- USB hotplug is the obvious one -- this needs a
// spinlock, and the reader in procfs needs to take it.
#include "types.h"
#include "defs.h"
#include "param.h"
#include "device.h"
#include "display.h"
#include "netdev.h"
#include "theme.h"
#include "text.h"
static struct device devices[NDEVICE];
static int ndevices;
static const char *bus_names[DEVBUS_NBUS] = {
[DEVBUS_PLATFORM] = "platform",
[DEVBUS_PCI] = "pci",
[DEVBUS_USB] = "usb",
};
static const char *class_names[DEVCLASS_NCLASS] = {
[DEVCLASS_OTHER] = "other",
[DEVCLASS_DISPLAY] = "display",
[DEVCLASS_INPUT] = "input",
[DEVCLASS_STORAGE] = "storage",
[DEVCLASS_NET] = "net",
[DEVCLASS_BUS] = "bus",
};
const char *
dev_bus_name(enum dev_bus b)
{
if (b < 0 || b >= DEVBUS_NBUS || !bus_names[b])
return "?";
return bus_names[b];
}
const char *
dev_class_name(enum dev_class c)
{
if (c < 0 || c >= DEVCLASS_NCLASS || !class_names[c])
return "?";
return class_names[c];
}
// How many devices already share this base name, so "vga" becomes vga0, vga1.
static int
count_base(const char *base)
{
int n = 0;
for (int i = 0; i < ndevices; i++) {
const char *a = devices[i].name, *b = base;
while (*b && *a == *b) { a++; b++; }
// Matched the whole base and the rest is the index we appended.
if (*b == '\0' && *a >= '0' && *a <= '9')
n++;
}
return n;
}
struct device *
device_add(const char *base, enum dev_bus bus, enum dev_class class,
const char *driver)
{
if (ndevices >= NDEVICE)
return 0;
struct device *d = &devices[ndevices++];
d->bus = bus;
d->class = class;
d->driver = driver;
d->in_use = 1;
int idx = count_base(base);
int n = 0;
while (base[n] && n < DEV_NAMELEN - 3) {
d->name[n] = base[n];
n++;
}
// Single digit is enough for NDEVICE of 32 per base name, and a two-digit
// path that is never taken is a two-digit path that is never tested.
if (idx > 9)
idx = 9;
d->name[n++] = (char)('0' + idx);
d->name[n] = '\0';
return d;
}
void
device_set_desc(struct device *d, const char *s)
{
if (!d)
return;
int n = 0;
while (s[n] && n < (int)sizeof(d->desc) - 1) {
d->desc[n] = s[n];
n++;
}
d->desc[n] = '\0';
}
struct device *
device_at(int i)
{
if (i < 0 || i >= ndevices)
return 0;
return &devices[i];
}
int
device_count(void)
{
return ndevices;
}
struct device *
device_find_class(enum dev_class class)
{
for (int i = 0; i < ndevices; i++)
// Unclaimed devices are deliberately skipped. A display nobody drives is
// not a display you can draw on, and returning it would push the "is there
// a driver" check out to every caller.
if (devices[i].class == class && devices[i].driver)
return &devices[i];
return 0;
}
// --- the display class -----------------------------------------------------
//
// Thin wrappers over device_find_class() plus a null check on each op. They
// exist so that consumers are not each written around a vtable that may be
// absent -- a compositor asking to present on a machine with no display driver
// should be a no-op, not a null dereference in the middle of a frame.
struct device *
display_get(void)
{
return device_find_class(DEVCLASS_DISPLAY);
}
int
display_mode(struct display_mode *out)
{
struct device *d = display_get();
if (!d || !d->ops || !((struct display_ops *)d->ops)->mode)
return -1;
((struct display_ops *)d->ops)->mode(d, out);
return 0;
}
void *
display_acquire(uint32 *stride_out)
{
struct device *d = display_get();
if (!d || !d->ops || !((struct display_ops *)d->ops)->acquire)
return 0;
return ((struct display_ops *)d->ops)->acquire(d, stride_out);
}
void
display_present(int x, int y, int w, int h)
{
struct device *d = display_get();
if (!d || !d->ops || !((struct display_ops *)d->ops)->present)
return;
((struct display_ops *)d->ops)->present(d, x, y, w, h);
}
void
display_wait_vblank(void)
{
struct device *d = display_get();
if (!d || !d->ops || !((struct display_ops *)d->ops)->wait_vblank)
return;
((struct display_ops *)d->ops)->wait_vblank(d);
}
// Drive the whole display path once and report what happened: find the class,
// read the mode, acquire a back buffer, draw into RAM, present it.
//
// A self-test rather than a unit test because none of this can be checked
// without a display: the assertion is "did the right pixels reach the screen",
// and the only instrument for that is a screendump. Triggered with
// `echo d > /proc/sysrq` and photographed by tools/dispshot.ps1.
//
// The pattern is chosen to be wrong in visible ways. Four solid quadrants in
// theme colours catch a stride error (the bands would slant) and a bpp error
// (the colours would be wrong); the white frame one pixel inside the edge
// catches an off-by-one in the present rectangle; and the fact that it is
// drawn entirely into RAM before a single byte reaches the framebuffer is what
// double buffering means.
void
display_selftest(void)
{
struct display_mode m;
uint32 stride;
if (display_mode(&m) != 0) {
cprintf("display: no display bound\n");
return;
}
cprintf("display: %dx%d %dbpp stride %d\n", m.width, m.height, m.bpp, m.stride);
unsigned char *b = display_acquire(&stride);
if (!b) {
cprintf("display: no back buffer available\n");
return;
}
static const uint32 quad[4] = {
SCH_ACCENT, SCH_ACCENT_DIM, SCH_DIM, SCH_BG
};
for (int y = 0; y < m.height; y++) {
uint32 *row = (uint32 *)(b + (uint64)y * stride);
int top = y < m.height / 2;
for (int x = 0; x < m.width; x++) {
int left = x < m.width / 2;
row[x] = quad[(top ? 0 : 2) + (left ? 0 : 1)];
}
}
for (int x = 1; x < m.width - 1; x++) {
*(uint32 *)(b + 1 * (uint64)stride + x * 4) = SCH_FG;
*(uint32 *)(b + (uint64)(m.height - 2) * stride + x * 4) = SCH_FG;
}
for (int y = 1; y < m.height - 1; y++) {
*(uint32 *)(b + (uint64)y * stride + 1 * 4) = SCH_FG;
*(uint32 *)(b + (uint64)y * stride + (m.width - 2) * 4) = SCH_FG;
}
// Between frames, so the blit does not land halfway down a scan-out.
display_wait_vblank();
display_present(0, 0, m.width, m.height);
cprintf("display: presented a full frame\n");
}
// Draw a text specimen through the display class. `echo t > /proc/sysrq`.
//
// It exercises the three things a character-cell console cannot do, so a
// screenshot says whether the layer works rather than whether it compiled:
// glyphs on a common baseline at arbitrary x (not multiples of eight), text
// blended over an existing background rather than drawn into cleared cells, and
// codepoints above 255.
void
text_selftest(void)
{
struct display_mode m;
uint32 stride;
if (display_mode(&m) != 0) {
cprintf("text: no display\n");
return;
}
unsigned char *b = display_acquire(&stride);
if (!b) {
cprintf("text: no back buffer\n");
return;
}
struct surface s = { b, stride, m.width, m.height };
struct font *f = font_builtin();
// A background with structure in it, so blending is visible as blending
// rather than as drawing onto a flat colour.
for (int y = 0; y < m.height; y++) {
uint32 *row = (uint32 *)(b + (uint64)y * stride);
for (int x = 0; x < m.width; x++)
row[x] = ((x / 32 + y / 32) & 1) ? SCH_BG : SCH_ACCENT_DIM;
}
int base = f->ops->baseline(f);
int line = f->ops->height(f) + 6;
int y = 80;
text_draw(&s, f, 60, y + base, "SchOS text rendering", SCH_FG);
y += line * 2;
// Deliberately not on a multiple of eight. On the old console this string
// could only start at x = 56 or x = 64.
text_draw(&s, f, 61, y + base, "positioned at x=61, off the cell grid", SCH_DIM);
y += line;
text_draw(&s, f, 63, y + base, "and here at x=63", SCH_DIM);
y += line * 2;
// Above U+00FF, which a 256-entry table cannot index at all.
text_draw(&s, f, 60, y + base,
"utf-8: \xe2\x94\x8c\xe2\x94\x80\xe2\x94\x90 "
"\xe2\x96\x88\xe2\x96\x93\xe2\x96\x92\xe2\x96\x91 "
"\xc2\xb0 \xc2\xb1 \xe2\x86\x92 \xe2\x80\xa2", SCH_ACCENT);
y += line * 2;
// Measure, then centre on it -- the thing you cannot do without metrics.
const char *msg = "measured and centred";
int w = text_measure(f, msg);
text_draw(&s, f, (m.width - w) / 2, y + base, msg, SCH_FG);
display_present(0, 0, m.width, m.height);
cprintf("text: drew a specimen, \"%s\" measures %d px\n", msg, w);
}
// ---------------------------------------------------------------------------
// The network class. See include/netdev.h.
//
// Plural where the display class is singular: a machine with two NICs is
// ordinary, and "the network" is not a thing a stack can ask for the way a
// compositor asks for "the display". So this walks, and the caller decides
// what to do with each interface it finds.
struct device *
netdev_at(int i)
{
int seen = 0;
for (int k = 0; k < device_count(); k++) {
struct device *d = device_at(k);
if (!d || d->class != DEVCLASS_NET || !d->driver || !d->ops)
continue;
if (seen++ == i)
return d;
}
return 0;
}
int
netdev_count(void)
{
int n = 0;
while (netdev_at(n))
n++;
return n;
}
int
netdev_transmit(struct device *d, const void *frame, int len)
{
if (!d || !d->ops || !((struct netdev_ops *)d->ops)->transmit)
return -1;
return ((struct netdev_ops *)d->ops)->transmit(d, frame, len);
}
int
netdev_receive(struct device *d, void *out, int cap)
{
if (!d || !d->ops || !((struct netdev_ops *)d->ops)->receive)
return 0;
return ((struct netdev_ops *)d->ops)->receive(d, out, cap);
}
const unsigned char *
netdev_mac(struct device *d)
{
if (!d || !d->ops || !((struct netdev_ops *)d->ops)->mac)
return 0;
return ((struct netdev_ops *)d->ops)->mac(d);
}
int
netdev_link_up(struct device *d)
{
// A driver that cannot tell is treated as up. Reporting "down" for a link
// whose state is simply unknown would stop the stack on hardware that works.
if (!d || !d->ops || !((struct netdev_ops *)d->ops)->link_up)
return 1;
return ((struct netdev_ops *)d->ops)->link_up(d);
}
static void
put_be16(uint8 *p, uint16 v)
{
p[0] = (uint8)(v >> 8);
p[1] = (uint8)v;
}
// The ARP probe. Written for the e1000 when it was the only driver and there
// was no stack to test it with; it belongs here because it is the first thing
// anyone will want to run against the *next* driver, and none of it is
// specific to a chip.
//
// Under QEMU's user-mode networking the guest is 10.0.2.15 and the gateway is
// 10.0.2.2. SLIRP is silent until spoken to, which is why this has to transmit
// before it can expect to receive anything.
void
netdev_selftest(void)
{
struct device *d = netdev_at(0);
uint8 frame[42];
uint8 reply[2048];
if (!d) {
cprintf("netdev: no interface\n");
return;
}
const unsigned char *mac = netdev_mac(d);
if (!mac) {
cprintf("netdev: %s has no station address\n", d->name);
return;
}
static const uint8 me[4] = { 10, 0, 2, 15 }; // QEMU SLIRP guest address
static const uint8 them[4] = { 10, 0, 2, 2 }; // and its gateway
memset(frame, 0, sizeof(frame));
for (int i = 0; i < 6; i++)
frame[i] = 0xFF; // broadcast
for (int i = 0; i < 6; i++)
frame[6 + i] = mac[i];
put_be16(&frame[12], 0x0806); // ARP
put_be16(&frame[14], 1); // Ethernet
put_be16(&frame[16], 0x0800); // IPv4
frame[18] = 6; // hardware address length
frame[19] = 4; // protocol address length
put_be16(&frame[20], 1); // request
for (int i = 0; i < 6; i++)
frame[22 + i] = mac[i]; // sender hardware address
for (int i = 0; i < 4; i++)
frame[28 + i] = me[i]; // sender protocol address
// target hardware address stays zero -- that is what is being asked
for (int i = 0; i < 4; i++)
frame[38 + i] = them[i];
cprintf("netdev: %s asking who has %d.%d.%d.%d\n",
d->name, them[0], them[1], them[2], them[3]);
if (netdev_transmit(d, frame, sizeof(frame)) != 0) {
cprintf("netdev: %s transmit ring full\n", d->name);
return;
}
// Bounded poll. This runs from a sysrq write and there is nothing to sleep
// on that would be woken by a raw frame, so spinning briefly is honest.
//
// It will also swallow whatever else is on the wire, including the stack's
// own traffic if it is running -- which is why a non-ARP frame is reported
// rather than treated as a failure.
for (int spin = 0; spin < 20000000; spin++) {
int n = netdev_receive(d, reply, sizeof(reply));
if (n <= 0)
continue;
cprintf("netdev: %d bytes from %x:%x:%x:%x:%x:%x type %x\n",
n, reply[6], reply[7], reply[8], reply[9], reply[10], reply[11],
((uint32)reply[12] << 8) | reply[13]);
if (n >= 42 && reply[12] == 0x08 && reply[13] == 0x06 &&
reply[20] == 0 && reply[21] == 2) {
cprintf("netdev: ARP reply -- %d.%d.%d.%d is at %x:%x:%x:%x:%x:%x\n",
reply[28], reply[29], reply[30], reply[31],
reply[22], reply[23], reply[24], reply[25],
reply[26], reply[27]);
cprintf("netdev: %s self-test passed\n", d->name);
return;
}
}
cprintf("netdev: %s no reply\n", d->name);
}