interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / native / boot / net_loader.c

655 lines · 26996 bytes Raw Blame History
1/* net_loader.c -- NETLDR.EFI: the AIENOS lab network loader for the 2017 iMac
2 * (x86_64 UEFI application; wire format netboot_proto.h).
3 *
4 * Lives on the USB stick as EFI/BOOT/BOOTX64.EFI so the stick never has to
5 * move again. At every power-on it asks the LAN for a kernel, verifies it and
6 * starts it:
7 * 1. Network: the firmware's Simple Network Protocol (UEFI 2.10 section
8 * 24.1), opened EXCLUSIVE so the firmware's own network stack lets go of
9 * the receive queue. No SNP handle: ConnectController on every handle
10 * once, then look again. Every handle is tried (the iMac also has a Wi-Fi
11 * SNP that looks like Ethernet): the first with its cable link up wins;
12 * with none reporting a link, each gets a 10 s turn before the fallback.
13 * 2. HELLO every second. WAIT: the server is there with nothing queued; ask
14 * again after the seconds it names. OFFER: fetch the object (signed slot
15 * manifest + image) in NB_WINDOW-chunk windows, re-asking for gaps.
16 * 3. ck_slot_verify (slot_select.c, the SLOTLDR verifier): Ed25519 manifest
17 * signature by a key baked in at build time (CK_NETLDR_KEYS), SHA-512 of
18 * the image, image_len == the bytes received. Refused: DONE status 1 with
19 * the reason, nothing runs, back to step 2.
20 * 4. Verified: DONE status 0, SNP Shutdown + Stop + CloseProtocol (no
21 * firmware DMA into memory the kernel will own), LoadImage from the
22 * verified buffer, StartImage, with LoadOptions = struct nb_pass
23 * (netboot_proto.h): the loader's clock stamps and where the verified
24 * object lies, so the kernel can install it on its own disk.
25 * No answer at all for CK_NETLDR_FALLBACK_S seconds: start the kernel on the
26 * stick itself (\EFI\AIENOS\IMACKERN.EFI on this loader's volume), so the
27 * iMac still runs AIENOS with the Spark disconnected. That file is trusted
28 * as the stick is: whoever can write the stick can replace this loader too.
29 *
30 * The UEFI watchdog is re-armed to NETLDR_WATCHDOG_S on every server answer
31 * and before StartImage, so a hung loader or kernel (before ExitBootServices)
32 * resets the machine instead of waiting for a hand on the power button.
33 * Never: UEFI variables, runtime services, ExitBootServices, disk writes.
34 * Freestanding C with the x86 kernel's flags; no kernel objects are linked. */
35#include <stdarg.h>
36#include "efi.h"
37#include "slot_format.h"
38#include "netboot_proto.h"
39#include "aienos_net.h"
40#include "../kernel/core/fmt.h"
41
42#ifndef AIENOS_COMMIT
43#define AIENOS_COMMIT "unknown"
44#endif
45#ifndef CK_NETLDR_FALLBACK_S
46#define CK_NETLDR_FALLBACK_S 30u
47#endif
48#define NETLDR_WATCHDOG_S 600u
49#define LOCAL_KERNEL u"\\EFI\\AIENOS\\IMACKERN.EFI"
50#define LOCAL_MAX (16ull << 20)
51#define PAGE 4096ull
52
53void *memcpy(void *dst, const void *src, size_t n);
54void *memset(void *dst, int c, size_t n);
55int memcmp(const void *a, const void *b, size_t n);
56
57/* Generated at build time (native/kernel/Makefile, ck_slot_tool keys-c). */
58extern const uint8_t ck_slot_loader_keys[][32];
59extern const unsigned ck_slot_loader_nkeys;
60
61#define EFI_LOAD_ERROR EFI_ERR(1)
62#define EFI_NOT_READY EFI_ERR(6)
63#define EFI_ALREADY_STARTED EFI_ERR(20)
64
65/* ---- Simple Network Protocol (UEFI 2.10 section 24.1; r-efi 6.0.0
66 * protocols/simple_network.rs) ---- */
67#define SNP_GUID_INIT { 0xa19832b9, 0xac25, 0x11d3, { 0x9a, 0x2d, 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d } }
68#define LOADED_IMAGE_DEVICE_PATH_GUID_INIT \
69 { 0xbc62157e, 0x3e33, 0x4fec, { 0x99, 0x20, 0x2d, 0x3b, 0x36, 0xd7, 0x50, 0xdf } }
70enum { SNP_STOPPED, SNP_STARTED, SNP_INITIALIZED };
71#define SNP_RX_UNICAST 1u
72#define SNP_RX_BROADCAST 4u
73#define OPEN_BY_HANDLE 0x1u
74#define OPEN_EXCLUSIVE 0x20u
75
76typedef struct { uint8_t addr[32]; } EFI_MAC_ADDRESS;
77typedef struct {
78 uint32_t State, HwAddressSize, MediaHeaderSize, MaxPacketSize, NvRamSize, NvRamAccessSize;
79 uint32_t ReceiveFilterMask, ReceiveFilterSetting, MaxMCastFilterCount, MCastFilterCount;
80 EFI_MAC_ADDRESS MCastFilter[16];
81 EFI_MAC_ADDRESS CurrentAddress, BroadcastAddress, PermanentAddress;
82 uint8_t IfType, MacAddressChangeable, MultipleTxSupported, MediaPresentSupported, MediaPresent;
83} SNP_MODE;
84_Static_assert(offsetof(SNP_MODE, CurrentAddress) == 552, "SNP_MODE CurrentAddress");
85_Static_assert(offsetof(SNP_MODE, MediaPresent) == 652, "SNP_MODE MediaPresent");
86
87typedef struct SNP {
88 uint64_t Revision;
89 EFI_STATUS (*Start)(struct SNP *);
90 EFI_STATUS (*Stop)(struct SNP *);
91 EFI_STATUS (*Initialize)(struct SNP *, uint64_t extra_rx, uint64_t extra_tx);
92 EFI_STATUS (*Reset)(struct SNP *, uint8_t extended);
93 EFI_STATUS (*Shutdown)(struct SNP *);
94 EFI_STATUS (*ReceiveFilters)(struct SNP *, uint32_t enable, uint32_t disable, uint8_t reset_mcast,
95 uint64_t mcast_count, EFI_MAC_ADDRESS *mcast);
96 void *StationAddress, *Statistics, *MCastIpToMac, *NvData;
97 EFI_STATUS (*GetStatus)(struct SNP *, uint32_t *irq, void **tx_buf);
98 EFI_STATUS (*Transmit)(struct SNP *, uint64_t header_size, uint64_t size, void *buf, EFI_MAC_ADDRESS *src,
99 EFI_MAC_ADDRESS *dst, uint16_t *proto);
100 EFI_STATUS (*Receive)(struct SNP *, uint64_t *header_size, uint64_t *size, void *buf, EFI_MAC_ADDRESS *src,
101 EFI_MAC_ADDRESS *dst, uint16_t *proto);
102 void *WaitForPacket;
103 SNP_MODE *Mode;
104} SNP;
105_Static_assert(offsetof(SNP, GetStatus) == 0x58, "SNP GetStatus");
106_Static_assert(offsetof(SNP, Receive) == 0x68, "SNP Receive");
107_Static_assert(offsetof(SNP, Mode) == 0x78, "SNP Mode");
108
109/* Boot-services members efi.h keeps as placeholders (UEFI 2.10 section 7). */
110typedef EFI_STATUS (*load_image_fn)(uint8_t boot_policy, EFI_HANDLE parent, void *device_path, void *source,
111 uint64_t source_size, EFI_HANDLE *out);
112typedef EFI_STATUS (*start_image_fn)(EFI_HANDLE image, uint64_t *exit_data_size, CHAR16 **exit_data);
113typedef EFI_STATUS (*connect_fn)(EFI_HANDLE controller, EFI_HANDLE *driver, void *remaining, uint8_t recursive);
114typedef EFI_STATUS (*open_protocol_fn)(EFI_HANDLE handle, const EFI_GUID *protocol, void **iface, EFI_HANDLE agent,
115 EFI_HANDLE controller, uint32_t attributes);
116typedef EFI_STATUS (*close_protocol_fn)(EFI_HANDLE handle, const EFI_GUID *protocol, EFI_HANDLE agent,
117 EFI_HANDLE controller);
118_Static_assert(offsetof(EFI_BOOT_SERVICES, LoadImage) == 0xc8, "LoadImage");
119_Static_assert(offsetof(EFI_BOOT_SERVICES, ConnectController) == 0x108, "ConnectController");
120_Static_assert(offsetof(EFI_BOOT_SERVICES, OpenProtocol) == 0x118, "OpenProtocol");
121
122static const EFI_GUID snp_guid = SNP_GUID_INIT;
123static EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *conout;
124static EFI_BOOT_SERVICES *bs;
125static EFI_HANDLE self;
126static SNP *snp;
127static EFI_HANDLE snp_handle;
128static int snp_exclusive;
129static uint8_t mac[6];
130static uint8_t tx[1600], rx[2048];
131static uint8_t have[NB_OBJECT_MAX / NB_CHUNK / 8];
132static uint64_t tsc_per_ms;
133
134/* ---- console -------------------------------------------------------------- */
135struct line {
136 char b[256];
137 size_t n;
138};
139
140static void line_emit(void *ctx, char c)
141{
142 struct line *l = ctx;
143 if (l->n < sizeof l->b - 1)
144 l->b[l->n++] = c;
145}
146
147static void say(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
148static void say(const char *fmt, ...)
149{
150 struct line l;
151 CHAR16 w[2 * sizeof l.b + 1];
152 size_t k = 0;
153 va_list ap;
154 l.n = 0;
155 va_start(ap, fmt);
156 ck_vformat(line_emit, &l, fmt, ap);
157 va_end(ap);
158 for (size_t i = 0; i < l.n; i++) {
159 if (l.b[i] == '\n')
160 w[k++] = '\r';
161 w[k++] = (uint8_t)l.b[i];
162 }
163 w[k] = 0;
164 if (conout)
165 conout->OutputString(conout, w);
166}
167
168/* ---- time ------------------------------------------------------------------- */
169static uint64_t rdtsc(void)
170{
171 uint32_t lo, hi;
172 __asm__ volatile("rdtsc" : "=a"(lo), "=d"(hi));
173 return (uint64_t)hi << 32 | lo;
174}
175
176static uint64_t now_ms(void) { return rdtsc() / tsc_per_ms; }
177
178static void watchdog(uint64_t seconds) { bs->SetWatchdogTimer(seconds, 0x10000, 0, 0); }
179
180/* ---- network ---------------------------------------------------------------- */
181static void net_close(void)
182{
183 if (!snp)
184 return;
185 snp->Shutdown(snp);
186 snp->Stop(snp);
187 if (snp_exclusive)
188 ((close_protocol_fn)bs->CloseProtocol)(snp_handle, &snp_guid, self, 0);
189 snp = 0;
190}
191
192/* Every SNP handle, in firmware order. The iMac firmware carries a Wi-Fi driver (Internet
193 * Recovery) beside the wired one, and an 802.11 SNP reports IfType 1 like Ethernet, so the
194 * first handle is not necessarily the cable. */
195#define NIC_MAX 8
196static EFI_HANDLE nics[NIC_MAX];
197static unsigned n_nics, nic_tries = 1;
198
199static int find_nics(void)
200{
201 EFI_HANDLE *h = 0;
202 uint64_t n = 0;
203 if (bs->LocateHandleBuffer(ByProtocol, &snp_guid, 0, &n, &h) != EFI_SUCCESS || n == 0) {
204 EFI_HANDLE *all = 0;
205 uint64_t na = 0;
206 say("netldr: no network interface yet; connecting firmware drivers\n");
207 if (bs->LocateHandleBuffer(AllHandles, 0, 0, &na, &all) == EFI_SUCCESS) {
208 for (uint64_t i = 0; i < na; i++)
209 ((connect_fn)bs->ConnectController)(all[i], 0, 0, 1);
210 bs->FreePool(all);
211 }
212 if (bs->LocateHandleBuffer(ByProtocol, &snp_guid, 0, &n, &h) != EFI_SUCCESS || n == 0) {
213 say("netldr: no network interface (Simple Network Protocol) in this firmware\n");
214 return -1;
215 }
216 }
217 n_nics = n < NIC_MAX ? (unsigned)n : NIC_MAX;
218 for (unsigned i = 0; i < n_nics; i++)
219 nics[i] = h[i];
220 bs->FreePool(h);
221 return 0;
222}
223
224enum { LINK_UNUSABLE = -1, LINK_DOWN, LINK_UNKNOWN, LINK_UP };
225
226/* Open nics[i] (exclusive if the firmware lets go), bring it to Initialized with unicast +
227 * broadcast receive, wait up to 10 s for the cable link. Leaves it open as snp unless
228 * LINK_UNUSABLE; the caller closes the ones it does not keep. */
229static int use_nic(unsigned i, int quiet)
230{
231 EFI_STATUS s;
232 SNP *p = 0;
233 int ex = 1;
234 if (((open_protocol_fn)bs->OpenProtocol)(nics[i], &snp_guid, (void **)&p, self, 0, OPEN_EXCLUSIVE) !=
235 EFI_SUCCESS) {
236 ex = 0;
237 if (bs->HandleProtocol(nics[i], &snp_guid, (void **)&p) != EFI_SUCCESS)
238 p = 0;
239 }
240 if (!p || !p->Mode) {
241 say("netldr: nic %u unusable (no protocol)\n", i);
242 return LINK_UNUSABLE;
243 }
244 SNP_MODE *m = p->Mode;
245 if (!quiet)
246 say("netldr: nic %u of %u mac=%02x:%02x:%02x:%02x:%02x:%02x type=%u state=%u open=%s\n", i, n_nics,
247 m->CurrentAddress.addr[0], m->CurrentAddress.addr[1], m->CurrentAddress.addr[2], m->CurrentAddress.addr[3],
248 m->CurrentAddress.addr[4], m->CurrentAddress.addr[5], m->IfType, m->State, ex ? "exclusive" : "shared");
249 snp = p;
250 snp_handle = nics[i];
251 snp_exclusive = ex;
252 if (m->IfType != 1 || m->HwAddressSize != 6) {
253 net_close();
254 return LINK_UNUSABLE;
255 }
256 memcpy(mac, m->CurrentAddress.addr, 6);
257 if (m->State == SNP_STOPPED && (s = p->Start(p)) != EFI_SUCCESS && s != EFI_ALREADY_STARTED) {
258 say("netldr: nic %u Start status=0x%llx\n", i, (unsigned long long)s);
259 net_close();
260 return LINK_UNUSABLE;
261 }
262 if (m->State == SNP_STARTED && (s = p->Initialize(p, 0, 0)) != EFI_SUCCESS) {
263 say("netldr: nic %u Initialize status=0x%llx\n", i, (unsigned long long)s);
264 net_close();
265 return LINK_UNUSABLE;
266 }
267 uint32_t want = (SNP_RX_UNICAST | SNP_RX_BROADCAST) & m->ReceiveFilterMask;
268 if (!(want & SNP_RX_BROADCAST) || (s = p->ReceiveFilters(p, want, 0, 0, 0, 0)) != EFI_SUCCESS) {
269 say("netldr: nic %u cannot receive broadcasts (mask=0x%x status=0x%llx)\n", i, m->ReceiveFilterMask,
270 (unsigned long long)(want & SNP_RX_BROADCAST ? s : EFI_ERR(3)));
271 net_close();
272 return LINK_UNUSABLE;
273 }
274 if (!m->MediaPresentSupported) {
275 if (!quiet)
276 say("netldr: nic %u link: not reported\n", i);
277 return LINK_UNKNOWN;
278 }
279 for (uint64_t t = now_ms() + 10000; !m->MediaPresent && now_ms() < t;) {
280 uint32_t irq;
281 p->GetStatus(p, &irq, 0);
282 bs->Stall(100000);
283 }
284 if (!quiet)
285 say("netldr: nic %u link %s\n", i, m->MediaPresent ? "up" : "down");
286 return m->MediaPresent ? LINK_UP : LINK_DOWN;
287}
288
289/* Keep the first interface with its cable link up. With none up, round number `round` picks
290 * among the rest (link not reported first, then link down), so a caller that moves to the
291 * next round after a silent window tries each in turn; nic_tries says how many there are. */
292static int net_open(unsigned round)
293{
294 unsigned cand[2 * NIC_MAX], nc = 0, down[NIC_MAX], nd = 0;
295 if (find_nics() != 0)
296 return -1;
297 for (unsigned i = 0; i < n_nics; i++) {
298 int r = use_nic(i, round != 0);
299 if (r == LINK_UP) {
300 nic_tries = 1;
301 return 0;
302 }
303 if (r == LINK_UNUSABLE)
304 continue;
305 net_close();
306 if (r == LINK_UNKNOWN)
307 cand[nc++] = i;
308 else
309 down[nd++] = i;
310 }
311 for (unsigned k = 0; k < nd; k++)
312 cand[nc++] = down[k];
313 if (nc == 0) {
314 say("netldr: no usable network interface\n");
315 return -1;
316 }
317 nic_tries = nc;
318 unsigned pick = cand[round % nc];
319 say("netldr: no interface reports a cable link; trying nic %u (%u of %u)\n", pick, round % nc + 1, nc);
320 return use_nic(pick, 1) == LINK_UNUSABLE ? -1 : 0;
321}
322
323/* Why the last net_send failed (for the DONE report). */
324static const char *tx_why;
325static EFI_STATUS tx_status;
326
327static int net_send(const struct nb_msg *m)
328{
329 static uint8_t msg[NB_MSG_MAX], udp[8 + NB_MSG_MAX], ip[20 + sizeof udp];
330 const net_ipv4 any = {{0, 0, 0, 0}}, bcast = {{255, 255, 255, 255}};
331 net_udp_header uh = {NB_PORT_LOADER, NB_PORT_SERVER};
332 net_ipv4_header ih = {0, 0, 1, NET_IPPROTO_UDP, any, bcast};
333 net_eth_frame e;
334 size_t n = nb_build(m, msg, sizeof msg), uw = 0, iw = 0, ew = 0;
335 tx_why = "frame build";
336 if (!n || net_udp_build(&uh, msg, n, any, bcast, udp, sizeof udp, &uw) != NET_OK ||
337 net_ipv4_build(&ih, udp, uw, ip, sizeof ip, &iw) != NET_OK)
338 return -1;
339 memset(e.destination.b, 0xff, 6);
340 memcpy(e.source.b, mac, 6);
341 e.ethertype = NET_ETHERTYPE_IPV4;
342 e.payload = ip;
343 e.payload_len = iw;
344 if (net_eth_build(&e, tx, sizeof tx, &ew) != NET_OK)
345 return -1;
346 tx_why = "Transmit";
347 if ((tx_status = snp->Transmit(snp, 0, ew, tx, 0, 0, 0)) != EFI_SUCCESS)
348 return -1;
349 /* The frame buffer is the firmware's until GetStatus hands it back. A driver that never
350 * reports the completion still sent the frame: go on and listen (the next frame is built
351 * a second or more later), and say so if nothing ever answers. */
352 for (uint64_t t = now_ms() + 100; now_ms() < t;) {
353 uint32_t irq;
354 void *done = 0;
355 if (snp->GetStatus(snp, &irq, &done) == EFI_SUCCESS && done) {
356 tx_why = "frames sent, nothing came back";
357 return 0;
358 }
359 }
360 tx_why = "frames handed to the card, completion never reported";
361 return 0;
362}
363
364/* Next netboot message with our nonce before deadline (ms). 0 or -1. */
365static int net_recv(const uint8_t nonce[16], uint64_t deadline, struct nb_msg *out)
366{
367 do {
368 uint64_t size = sizeof rx;
369 EFI_STATUS s = snp->Receive(snp, 0, &size, rx, 0, 0, 0);
370 if (s == EFI_NOT_READY)
371 continue;
372 if (s != EFI_SUCCESS || size > sizeof rx)
373 continue;
374 net_eth_frame e;
375 net_ipv4_header ih;
376 net_udp_header uh;
377 const uint8_t *ipp, *up;
378 size_t ipn, un;
379 if (net_eth_parse(rx, size, &e) != NET_OK || e.ethertype != NET_ETHERTYPE_IPV4 ||
380 net_ipv4_parse(e.payload, e.payload_len, &ih, &ipp, &ipn) != NET_OK || ih.protocol != NET_IPPROTO_UDP ||
381 net_udp_parse(ipp, ipn, ih.source, ih.destination, &uh, &up, &un) != NET_OK ||
382 uh.destination_port != NB_PORT_LOADER || uh.source_port != NB_PORT_SERVER)
383 continue;
384 if (nb_parse(up, un, out) != 0 || memcmp(out->nonce, nonce, 16) != 0)
385 continue;
386 return 0;
387 } while (now_ms() < deadline);
388 return -1;
389}
390
391/* ---- starting a kernel ------------------------------------------------------ */
392static struct nb_pass pass; /* the kernel copies it before it leaves boot services */
393
394/* obj: the verified object (manifest + image) for a network kernel, 0 for the local one */
395static void start_image(const char *what, void *buf, uint64_t len, const uint8_t *obj, uint64_t obj_len)
396{
397 static const EFI_GUID lidp_guid = LOADED_IMAGE_DEVICE_PATH_GUID_INIT;
398 static const EFI_GUID li_guid = EFI_LOADED_IMAGE_PROTOCOL_GUID_INIT;
399 void *dp = 0;
400 EFI_HANDLE child = 0;
401 EFI_LOADED_IMAGE_PROTOCOL *li = 0;
402 bs->HandleProtocol(self, &lidp_guid, &dp);
403 EFI_STATUS s = ((load_image_fn)bs->LoadImage)(0, self, dp, buf, len, &child);
404 if (s != EFI_SUCCESS) {
405 say("netldr: LoadImage of the %s kernel status=0x%llx: not started\n", what, (unsigned long long)s);
406 return;
407 }
408 say("netldr: starting the %s kernel (%llu bytes)\n", what, (unsigned long long)len);
409 watchdog(300);
410 memcpy(pass.magic, NB_PASS_MAGIC, 8);
411 pass.object = (uint64_t)(uintptr_t)obj;
412 pass.object_len = obj ? obj_len : 0;
413 if (bs->HandleProtocol(child, &li_guid, (void **)&li) == EFI_SUCCESS && li) {
414 li->LoadOptions = &pass;
415 li->LoadOptionsSize = sizeof pass;
416 }
417 pass.start_tsc = rdtsc();
418 s = ((start_image_fn)bs->StartImage)(child, 0, 0);
419 say("netldr: the %s kernel returned status=0x%llx\n", what, (unsigned long long)s);
420}
421
422/* The kernel on the stick itself, for when no server answers. */
423static void start_local(void)
424{
425 static const EFI_GUID li_guid = EFI_LOADED_IMAGE_PROTOCOL_GUID_INIT;
426 static const EFI_GUID sfs_guid = EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID_INIT;
427 EFI_LOADED_IMAGE_PROTOCOL *li = 0;
428 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *fs = 0;
429 EFI_FILE_PROTOCOL *root = 0, *f = 0;
430 uint64_t pa = 0, got = 0;
431 if (bs->HandleProtocol(self, &li_guid, (void **)&li) != EFI_SUCCESS || !li ||
432 bs->HandleProtocol(li->DeviceHandle, &sfs_guid, (void **)&fs) != EFI_SUCCESS || !fs ||
433 fs->OpenVolume(fs, &root) != EFI_SUCCESS) {
434 say("netldr: cannot open this stick's volume: no local kernel\n");
435 return;
436 }
437 if (root->Open(root, &f, (CHAR16 *)LOCAL_KERNEL, 1 /* read */, 0) != EFI_SUCCESS) {
438 say("netldr: no \\EFI\\AIENOS\\IMACKERN.EFI on this stick\n");
439 root->Close(root);
440 return;
441 }
442 if (bs->AllocatePages(AllocateAnyPages, EfiLoaderData, LOCAL_MAX / PAGE, &pa) != EFI_SUCCESS) {
443 say("netldr: no memory for the local kernel\n");
444 } else {
445 for (;;) {
446 uint64_t n = LOCAL_MAX - got;
447 if (n == 0 || f->Read(f, &n, (uint8_t *)(uintptr_t)pa + got) != EFI_SUCCESS || n == 0)
448 break;
449 got += n;
450 }
451 }
452 f->Close(f);
453 root->Close(root);
454 if (pa && got > 0 && got < LOCAL_MAX)
455 start_image("local", (void *)(uintptr_t)pa, got, 0, 0);
456 else if (pa)
457 say("netldr: local kernel unreadable or larger than %llu bytes\n", (unsigned long long)LOCAL_MAX);
458 if (pa)
459 bs->FreePages(pa, LOCAL_MAX / PAGE);
460}
461
462/* ---- one netboot exchange --------------------------------------------------- */
463enum { R_SILENT, R_ANSWERED, R_BOOT };
464
465static void new_nonce(uint8_t nonce[16])
466{
467 static uint64_t ctr;
468 uint64_t a = rdtsc() ^ (++ctr << 48), b = a * 0x9e3779b97f4a7c15ull ^ ((uint64_t)mac[5] << 8 | mac[4]);
469 memcpy(nonce, &a, 8);
470 memcpy(nonce + 8, &b, 8);
471}
472
473static void done(const uint8_t nonce[16], uint8_t status, const char *text)
474{
475 struct nb_msg m = {0};
476 size_t n = nb_text_len(text);
477 m.type = NB_DONE;
478 memcpy(m.nonce, nonce, 16);
479 m.status = status;
480 m.len = (uint16_t)n;
481 m.data = (const uint8_t *)text;
482 int sent = 0;
483 for (int i = 0; i < 3; i++)
484 sent += net_send(&m) == 0;
485 if (sent)
486 say("netldr: told the Spark: %s (%d/3 sent)\n", text, sent);
487 else
488 say("netldr: could not tell the Spark (%s, status 0x%llx)\n", tx_why, (unsigned long long)tx_status);
489}
490
491/* Fetch total bytes into obj. 0 complete, -1 gave up. */
492static int fetch(const uint8_t nonce[16], uint8_t *obj, uint32_t total)
493{
494 uint32_t chunks = nb_chunks(total), got = 0, next = 0, strikes = 0, shown = 0;
495 memset(have, 0, (chunks + 7) / 8);
496 while (got < chunks) {
497 while (have[next / 8] & (1u << (next % 8)))
498 next++;
499 struct nb_msg g = {0}, d;
500 g.type = NB_GET;
501 memcpy(g.nonce, nonce, 16);
502 g.offset = next * NB_CHUNK;
503 g.count = (uint16_t)(chunks - next < NB_WINDOW ? chunks - next : NB_WINDOW);
504 uint32_t before = got;
505 if (net_send(&g) == 0) {
506 uint64_t deadline = now_ms() + 300;
507 while (net_recv(nonce, deadline, &d) == 0) {
508 if (d.type != NB_DATA)
509 continue;
510 uint32_t c = d.offset / NB_CHUNK;
511 uint32_t want = total - d.offset < NB_CHUNK ? total - d.offset : NB_CHUNK;
512 if (d.offset >= total || d.len != want || (have[c / 8] & (1u << (c % 8))))
513 continue;
514 memcpy(obj + d.offset, d.data, d.len);
515 have[c / 8] |= (uint8_t)(1u << (c % 8));
516 got++;
517 deadline = now_ms() + 300;
518 if (got == chunks || c == next + g.count - 1u)
519 break;
520 }
521 }
522 if (got == before) {
523 if (++strikes >= 20) {
524 say("netldr: transfer stalled at %u of %u pieces; starting over\n", got, chunks);
525 return -1;
526 }
527 } else {
528 strikes = 0;
529 watchdog(NETLDR_WATCHDOG_S);
530 }
531 if (got * 10 / chunks > shown) {
532 shown = got * 10 / chunks;
533 say("netldr: received %u%%\n", shown * 10);
534 }
535 }
536 return 0;
537}
538
539static int exchange(void)
540{
541 static unsigned last_wait;
542 uint8_t nonce[16];
543 struct nb_msg h = {0}, r;
544 new_nonce(nonce);
545 h.type = NB_HELLO;
546 memcpy(h.nonce, nonce, 16);
547 memcpy(h.mac, mac, 6);
548 if (net_send(&h) != 0 || net_recv(nonce, now_ms() + 1000, &r) != 0)
549 return R_SILENT;
550 if (r.type != NB_WAIT && r.type != NB_OFFER)
551 return R_SILENT;
552 watchdog(NETLDR_WATCHDOG_S);
553 if (r.type == NB_WAIT) {
554 if (last_wait != r.seconds)
555 say("netldr: the Spark answered: nothing queued; asking again every %u s\n", r.seconds);
556 last_wait = r.seconds;
557 bs->Stall((uint64_t)r.seconds * 1000000u);
558 return R_ANSWERED;
559 }
560 last_wait = 0;
561 uint32_t total = r.total;
562 uint64_t pages = (total + PAGE - 1) / PAGE, pa = 0;
563 say("netldr: the Spark offers a kernel: %u bytes\n", total);
564 if (bs->AllocatePages(AllocateAnyPages, EfiLoaderData, pages, &pa) != EFI_SUCCESS) {
565 say("netldr: no memory for %u bytes\n", total);
566 done(nonce, 1, "loader out of memory");
567 return R_ANSWERED;
568 }
569 uint8_t *obj = (uint8_t *)(uintptr_t)pa;
570 if (fetch(nonce, obj, total) != 0) {
571 bs->FreePages(pa, pages);
572 return R_ANSWERED;
573 }
574 const struct ck_slot_manifest *m = (const struct ck_slot_manifest *)obj;
575 struct ck_slot_eval ev;
576 ck_slot_verify(m, obj + CK_SLOT_UNIT, total - CK_SLOT_UNIT, ck_slot_loader_keys, ck_slot_loader_nkeys, &ev);
577 if (ev.valid && m->image_len != total - CK_SLOT_UNIT) {
578 ev.valid = 0;
579 ev.why = "image_len differs from the bytes received";
580 }
581 if (!ev.valid) {
582 say("netldr: REFUSED the network kernel (%s): nothing was started\n", ev.why ? ev.why : "invalid");
583 done(nonce, 1, ev.why ? ev.why : "invalid");
584 bs->FreePages(pa, pages);
585 bs->Stall(5000000);
586 return R_ANSWERED;
587 }
588 char commit[13];
589 memcpy(commit, m->commit, 12);
590 commit[12] = 0;
591 say("netldr: signature and SHA-512 verified: gen=%llu commit=%s len=%llu\n",
592 (unsigned long long)m->generation, commit, (unsigned long long)m->image_len);
593 done(nonce, 0, "verified, starting");
594 bs->Stall(200000); /* let the last frames leave before the NIC is stopped */
595 net_close();
596 start_image("network", obj + CK_SLOT_UNIT, m->image_len, obj, total);
597 bs->FreePages(pa, pages);
598 return R_BOOT;
599}
600
601EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *st)
602{
603 pass.loader_tsc = rdtsc();
604 conout = st->ConOut;
605 bs = st->BootServices;
606 self = image;
607 say("netldr: AIENOS NETLDR v1 commit=%s keys=%u fallback=%us\n", AIENOS_COMMIT, ck_slot_loader_nkeys,
608 (unsigned)CK_NETLDR_FALLBACK_S);
609 uint64_t t0 = rdtsc();
610 bs->Stall(20000);
611 tsc_per_ms = (rdtsc() - t0) / 20;
612 if (!tsc_per_ms)
613 tsc_per_ms = 1;
614 watchdog(NETLDR_WATCHDOG_S);
615 unsigned round = 0;
616 for (;;) {
617 if (ck_slot_loader_nkeys == 0 || net_open(round) != 0) {
618 say("netldr: %s; starting the kernel on this stick in 10 s\n",
619 ck_slot_loader_nkeys == 0 ? "no trusted keys built in" : "no usable network");
620 bs->Stall(10000000); /* time to read (or photograph) the lines above */
621 start_local();
622 say("netldr: nothing started; trying again in 10 s\n");
623 bs->Stall(10000000);
624 continue;
625 }
626 /* With several candidate interfaces and no cable link reported, each gets a share. */
627 uint64_t window = (uint64_t)(nic_tries > 1 ? 10u : CK_NETLDR_FALLBACK_S) * 1000u;
628 say("netldr: asking the Spark for a kernel from %02x:%02x:%02x:%02x:%02x:%02x (ports %u/%u)\n", mac[0],
629 mac[1], mac[2], mac[3], mac[4], mac[5], NB_PORT_SERVER, NB_PORT_LOADER);
630 uint64_t last = now_ms();
631 int r = R_SILENT;
632 while (snp && now_ms() - last < window) {
633 r = exchange();
634 if (r == R_BOOT)
635 break;
636 if (r == R_ANSWERED)
637 last = now_ms();
638 }
639 if (r == R_BOOT) { /* the network kernel returned: open the network again */
640 round = 0;
641 continue;
642 }
643 net_close();
644 if (++round < nic_tries) {
645 say("netldr: no answer on this interface; trying the next one\n");
646 continue;
647 }
648 round = 0;
649 say("netldr: no answer from the Spark (%s); starting the kernel on this stick in 10 s\n",
650 tx_why ? tx_why : "frames sent");
651 bs->Stall(10000000); /* time to read (or photograph) the lines above */
652 start_local();
653 say("netldr: back from the local kernel; asking the network again\n");
654 }
655}