xref: /freebsd/stand/efi/libefi/efinet.c (revision 495826f69d96857bf0559516502e058ecab4ee4d)
1 /*-
2  * Copyright (c) 2001 Doug Rabson
3  * Copyright (c) 2002, 2006 Marcel Moolenaar
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/param.h>
29 #include <net/ethernet.h>
30 #include <netinet/in.h>
31 #include <netinet/in_systm.h>
32 
33 #include <stand.h>
34 #include <net.h>
35 #include <netif.h>
36 #include <bootp.h>
37 
38 #include <efi.h>
39 #include <efilib.h>
40 #include <Protocol/SimpleNetwork.h>
41 #include <Protocol/PxeBaseCode.h>
42 
43 #include "dev_net.h"
44 
45 static EFI_GUID sn_guid = EFI_SIMPLE_NETWORK_PROTOCOL_GUID;
46 static EFI_GUID pxe_guid = EFI_PXE_BASE_CODE_PROTOCOL_GUID;
47 
48 /*
49  * Snapshot of the UEFI PXE Base Code Protocol's cached DhcpAck taken
50  * at device enumeration time, before efinet_probe() opens the Simple
51  * Network Protocol with EFI_OPEN_PROTOCOL_EXCLUSIVE.  The EXCLUSIVE
52  * open forces the firmware to disconnect any driver holding the SNP
53  * handle BY_DRIVER (including the UEFI PXE stack), which uninstalls
54  * the PXE Base Code Protocol from that handle.  We capture the ACK
55  * here so it survives that disconnect.
56  *
57  * Per PXE 2.1, ProxyOffer's siaddr is the authoritative PXE boot
58  * server and overrides any siaddr in the primary DhcpAck.  We splice
59  * it into dhcp_ack.Dhcpv4.BootpSiAddr at snapshot time, so downstream
60  * only sees one merged packet — no need to store ProxyOffer separately.
61  *
62  * Indexed by netif unit; allocated in efi_pxe_snapshot_all().
63  */
64 struct pxe_cache_entry {
65 	bool				valid;
66 	EFI_PXE_BASE_CODE_PACKET	dhcp_ack;
67 };
68 
69 static struct pxe_cache_entry *pxe_cache;
70 
71 static void efinet_end(struct netif *);
72 static ssize_t efinet_get(struct iodesc *, void **, time_t);
73 static void efinet_init(struct iodesc *, void *);
74 static int efinet_match(struct netif *, void *);
75 static int efinet_probe(struct netif *, void *);
76 static ssize_t efinet_put(struct iodesc *, void *, size_t);
77 
78 struct netif_driver efinetif = {
79 	.netif_bname = "efinet",
80 	.netif_match = efinet_match,
81 	.netif_probe = efinet_probe,
82 	.netif_init = efinet_init,
83 	.netif_get = efinet_get,
84 	.netif_put = efinet_put,
85 	.netif_end = efinet_end,
86 	.netif_ifs = NULL,
87 	.netif_nifs = 0
88 };
89 
90 #ifdef EFINET_DEBUG
91 static void
dump_mode(EFI_SIMPLE_NETWORK_MODE * mode)92 dump_mode(EFI_SIMPLE_NETWORK_MODE *mode)
93 {
94 	int i;
95 
96 	printf("State                 = %x\n", mode->State);
97 	printf("HwAddressSize         = %u\n", mode->HwAddressSize);
98 	printf("MediaHeaderSize       = %u\n", mode->MediaHeaderSize);
99 	printf("MaxPacketSize         = %u\n", mode->MaxPacketSize);
100 	printf("NvRamSize             = %u\n", mode->NvRamSize);
101 	printf("NvRamAccessSize       = %u\n", mode->NvRamAccessSize);
102 	printf("ReceiveFilterMask     = %x\n", mode->ReceiveFilterMask);
103 	printf("ReceiveFilterSetting  = %u\n", mode->ReceiveFilterSetting);
104 	printf("MaxMCastFilterCount   = %u\n", mode->MaxMCastFilterCount);
105 	printf("MCastFilterCount      = %u\n", mode->MCastFilterCount);
106 	printf("MCastFilter           = {");
107 	for (i = 0; i < mode->MCastFilterCount; i++)
108 		printf(" %s", ether_sprintf(mode->MCastFilter[i].Addr));
109 	printf(" }\n");
110 	printf("CurrentAddress        = %s\n",
111 	    ether_sprintf(mode->CurrentAddress.Addr));
112 	printf("BroadcastAddress      = %s\n",
113 	    ether_sprintf(mode->BroadcastAddress.Addr));
114 	printf("PermanentAddress      = %s\n",
115 	    ether_sprintf(mode->PermanentAddress.Addr));
116 	printf("IfType                = %u\n", mode->IfType);
117 	printf("MacAddressChangeable  = %d\n", mode->MacAddressChangeable);
118 	printf("MultipleTxSupported   = %d\n", mode->MultipleTxSupported);
119 	printf("MediaPresentSupported = %d\n", mode->MediaPresentSupported);
120 	printf("MediaPresent          = %d\n", mode->MediaPresent);
121 }
122 #endif
123 
124 static int
efinet_match(struct netif * nif,void * machdep_hint)125 efinet_match(struct netif *nif, void *machdep_hint)
126 {
127 	struct devdesc *dev = machdep_hint;
128 
129 	if (dev->d_unit == nif->nif_unit)
130 		return (1);
131 	return(0);
132 }
133 
134 static int
efinet_probe(struct netif * nif,void * machdep_hint)135 efinet_probe(struct netif *nif, void *machdep_hint)
136 {
137 	EFI_SIMPLE_NETWORK *net;
138 	EFI_HANDLE h;
139 	EFI_STATUS status;
140 
141 	h = nif->nif_driver->netif_ifs[nif->nif_unit].dif_private;
142 	/*
143 	 * Open the network device in exclusive mode. Without this
144 	 * we will be racing with the UEFI network stack. It will
145 	 * pull packets off the network leading to lost packets.
146 	 */
147 	status = BS->OpenProtocol(h, &sn_guid, (void **)&net,
148 	    IH, NULL, EFI_OPEN_PROTOCOL_EXCLUSIVE);
149 	if (status != EFI_SUCCESS) {
150 		printf("Unable to open network interface %d for "
151 		    "exclusive access: %lu\n", nif->nif_unit,
152 		    DECODE_ERROR(status));
153 		return (efi_status_to_errno(status));
154 	}
155 
156 	return (0);
157 }
158 
159 static ssize_t
efinet_put(struct iodesc * desc,void * pkt,size_t len)160 efinet_put(struct iodesc *desc, void *pkt, size_t len)
161 {
162 	struct netif *nif = desc->io_netif;
163 	EFI_SIMPLE_NETWORK *net;
164 	EFI_STATUS status;
165 	void *buf;
166 
167 	net = nif->nif_devdata;
168 	if (net == NULL)
169 		return (-1);
170 
171 	status = net->Transmit(net, 0, len, pkt, NULL, NULL, NULL);
172 	if (status != EFI_SUCCESS)
173 		return (-1);
174 
175 	/* Wait for the buffer to be transmitted */
176 	do {
177 		buf = NULL;	/* XXX Is this needed? */
178 		status = net->GetStatus(net, NULL, &buf);
179 		/*
180 		 * XXX EFI1.1 and the E1000 card returns a different
181 		 * address than we gave.  Sigh.
182 		 */
183 	} while (status == EFI_SUCCESS && buf == NULL);
184 
185 	/* XXX How do we deal with status != EFI_SUCCESS now? */
186 	return ((status == EFI_SUCCESS) ? len : -1);
187 }
188 
189 static ssize_t
efinet_get(struct iodesc * desc,void ** pkt,time_t timeout)190 efinet_get(struct iodesc *desc, void **pkt, time_t timeout)
191 {
192 	struct netif *nif = desc->io_netif;
193 	EFI_SIMPLE_NETWORK *net;
194 	EFI_STATUS status;
195 	UINTN bufsz;
196 	time_t t;
197 	char *buf, *ptr;
198 	ssize_t ret = -1;
199 
200 	net = nif->nif_devdata;
201 	if (net == NULL)
202 		return (ret);
203 
204 	bufsz = net->Mode->MaxPacketSize + ETHER_HDR_LEN + ETHER_CRC_LEN;
205 	buf = malloc(bufsz + ETHER_ALIGN);
206 	if (buf == NULL)
207 		return (ret);
208 	ptr = buf + ETHER_ALIGN;
209 
210 	t = getsecs();
211 	while ((getsecs() - t) < timeout) {
212 		status = net->Receive(net, NULL, &bufsz, ptr, NULL, NULL, NULL);
213 		if (status == EFI_SUCCESS) {
214 			*pkt = buf;
215 			ret = (ssize_t)bufsz;
216 			break;
217 		}
218 		if (status != EFI_NOT_READY)
219 			break;
220 	}
221 
222 	if (ret == -1)
223 		free(buf);
224 	return (ret);
225 }
226 
227 /*
228  * Snapshot the UEFI PXE Base Code Protocol's cached DhcpAck for handle
229  * h (which must carry EFI_PXE_BASE_CODE_PROTOCOL) into pce, splicing
230  * ProxyOffer's siaddr into it if present (per PXE 2.1, ProxyOffer's
231  * siaddr is the authoritative boot server and overrides DhcpAck's).
232  *
233  * Silently leaves pce->valid = false if the protocol is absent, the
234  * PXE base code is not Started on this handle (i.e. it wasn't the
235  * interface used to network-boot), or no DhcpAck was received.
236  */
237 static void
efi_pxe_snapshot(EFI_HANDLE h,struct pxe_cache_entry * pce)238 efi_pxe_snapshot(EFI_HANDLE h, struct pxe_cache_entry *pce)
239 {
240 	EFI_PXE_BASE_CODE_PROTOCOL *pxe;
241 	EFI_PXE_BASE_CODE_MODE *mode;
242 	EFI_STATUS status;
243 
244 	status = BS->OpenProtocol(h, &pxe_guid, (void **)&pxe,
245 	    IH, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
246 	if (EFI_ERROR(status))
247 		return;
248 
249 	mode = pxe->Mode;
250 	if (mode->Started && mode->DhcpAckReceived) {
251 		memcpy(&pce->dhcp_ack, &mode->DhcpAck, sizeof(pce->dhcp_ack));
252 
253 		if (mode->ProxyOfferReceived) {
254 			uint32_t proxy_siaddr = 0;
255 
256 			memcpy(&proxy_siaddr,
257 			    mode->ProxyOffer.Dhcpv4.BootpSiAddr, 4);
258 			if (proxy_siaddr != 0)
259 				memcpy(pce->dhcp_ack.Dhcpv4.BootpSiAddr,
260 				    &proxy_siaddr, 4);
261 		}
262 		pce->valid = true;
263 	}
264 
265 	BS->CloseProtocol(h, &pxe_guid, IH, NULL);
266 }
267 
268 /*
269  * Walk a device path looking for the first MSG_MAC_ADDR_DP node and
270  * copy its 6-byte Ethernet MAC into out.  Returns true on success.
271  * Used to correlate a PXE Base Code Protocol handle back to an SNP
272  * unit when the two protocols live on different handles (typical for
273  * UEFI: PXE Base Code is installed on a child handle whose device
274  * path ends in Ipv4()/Ipv6(), extending the SNP's MAC-terminated path).
275  */
276 static bool
efi_devpath_get_mac(EFI_DEVICE_PATH * dp,uint8_t out[6])277 efi_devpath_get_mac(EFI_DEVICE_PATH *dp, uint8_t out[6])
278 {
279 	MAC_ADDR_DEVICE_PATH *mac;
280 
281 	if (dp == NULL)
282 		return (false);
283 	while (!IsDevicePathEnd(dp)) {
284 		if (DevicePathType(dp) == MESSAGING_DEVICE_PATH &&
285 		    DevicePathSubType(dp) == MSG_MAC_ADDR_DP) {
286 			mac = (MAC_ADDR_DEVICE_PATH *)dp;
287 			memcpy(out, &mac->MacAddress, 6);
288 			return (true);
289 		}
290 		dp = NextDevicePathNode(dp);
291 	}
292 	return (false);
293 }
294 
295 /*
296  * Populate the pxe_cache[] array for all nifs SNP units.  Runs during
297  * efinet_dev_init() before any SNP is opened EXCLUSIVE, so the UEFI
298  * PXE driver is still bound and its Mode data is intact.
299  *
300  * Per the UEFI 2.x network-stack architecture, EFI_PXE_BASE_CODE_PROTOCOL
301  * lives on an upper-layer child handle whose device path extends the
302  * SNP's MAC-terminated path with Ipv4()/Ipv6() nodes.  Enumerate all
303  * handles carrying PXE Base Code Protocol via LocateHandle() and match
304  * each back to an SNP unit by MAC address extracted from the handle's
305  * device path.  This also transparently covers the legacy single-handle
306  * case where PXE Base Code is installed on the SNP handle itself:
307  * LocateHandle() returns that handle, whose device path ends in a MAC
308  * node that trivially matches the same SNP unit.
309  */
310 static void
efi_pxe_snapshot_all(int nifs)311 efi_pxe_snapshot_all(int nifs)
312 {
313 	EFI_HANDLE *pxe_handles;
314 	EFI_STATUS status;
315 	UINTN sz;
316 	int i, j, npxe;
317 
318 	sz = 0;
319 	status = BS->LocateHandle(ByProtocol, &pxe_guid, NULL, &sz, NULL);
320 	if (status != EFI_BUFFER_TOO_SMALL)
321 		return;
322 	pxe_handles = malloc(sz);
323 	if (pxe_handles == NULL)
324 		return;
325 	status = BS->LocateHandle(ByProtocol, &pxe_guid, NULL, &sz,
326 	    pxe_handles);
327 	if (EFI_ERROR(status)) {
328 		free(pxe_handles);
329 		return;
330 	}
331 	npxe = sz / sizeof(EFI_HANDLE);
332 
333 	/*
334 	 * PXE is present on this system; allocate the per-unit cache
335 	 * only now.  Non-PXE UEFI boots pay nothing for this feature.
336 	 */
337 	pxe_cache = calloc(nifs, sizeof(struct pxe_cache_entry));
338 	if (pxe_cache == NULL) {
339 		free(pxe_handles);
340 		return;
341 	}
342 
343 	for (i = 0; i < npxe; i++) {
344 		EFI_DEVICE_PATH *dp;
345 		uint8_t pxe_mac[6];
346 
347 		dp = efi_lookup_devpath(pxe_handles[i]);
348 		if (!efi_devpath_get_mac(dp, pxe_mac))
349 			continue;
350 
351 		for (j = 0; j < nifs; j++) {
352 			EFI_DEVICE_PATH *snp_dp, *node;
353 			MAC_ADDR_DEVICE_PATH *snp_mac;
354 
355 			if (pxe_cache[j].valid)
356 				continue;
357 			snp_dp = efi_lookup_devpath(
358 			    efinetif.netif_ifs[j].dif_private);
359 			if ((node = efi_devpath_last_node(snp_dp)) == NULL)
360 				continue;
361 			snp_mac = (MAC_ADDR_DEVICE_PATH *)node;
362 			if (memcmp(&snp_mac->MacAddress, pxe_mac, 6) != 0)
363 				continue;
364 			efi_pxe_snapshot(pxe_handles[i], &pxe_cache[j]);
365 			break;
366 		}
367 	}
368 
369 	free(pxe_handles);
370 }
371 
372 /*
373  * Publish the UEFI PXE Base Code snapshot to the shared bootp_response
374  * global so that the loader's DHCP client (stand/libsa/bootp.c) can
375  * pick it up and enter RFC 2131 INIT-REBOOT instead of running a full
376  * DISCOVER/OFFER/REQUEST/ACK cycle.  Also seed servip from the
377  * ProxyOffer's siaddr, which is the authoritative PXE boot server on
378  * setups where the primary DHCP is not PXE-aware (its DhcpAck siaddr
379  * is zero).  bootp()'s post-processing preserves this pre-set servip
380  * when the INIT-REBOOT ACK arrives with siaddr == 0.
381  */
382 static void
efi_pxe_publish_cache(int unit)383 efi_pxe_publish_cache(int unit)
384 {
385 	const struct pxe_cache_entry *pce;
386 
387 	if (pxe_cache == NULL)
388 		return;
389 	pce = &pxe_cache[unit];
390 	if (!pce->valid)
391 		return;
392 
393 	free(bootp_response);
394 	bootp_response_size = 0;
395 	bootp_response = malloc(sizeof(pce->dhcp_ack));
396 	if (bootp_response == NULL)
397 		return;
398 	memcpy(bootp_response, &pce->dhcp_ack, sizeof(pce->dhcp_ack));
399 	bootp_response_size = sizeof(pce->dhcp_ack);
400 
401 	DEBUG_PRINTF(1, ("%s: bootp_response=%p size=%zu\n",
402 	    __func__, bootp_response, bootp_response_size));
403 }
404 
405 /*
406  * Loader uses BOOTP/DHCP and also uses RARP as a fallback to populate
407  * network parameters and problems with DHCP servers can cause the loader
408  * to fail to populate them. Allow the device to ask about the basic
409  * network parameters and if present use them.
410  */
411 static void
efi_env_net_params(struct iodesc * desc)412 efi_env_net_params(struct iodesc *desc)
413 {
414 	char *envstr;
415 	in_addr_t ipaddr, mask, gwaddr, serveraddr;
416 	n_long rootaddr;
417 
418 	if ((envstr = getenv("rootpath")) != NULL)
419 		strlcpy(rootpath, envstr, sizeof(rootpath));
420 
421 	/*
422 	 * Get network parameters.
423 	 */
424 	envstr = getenv("ipaddr");
425 	ipaddr = (envstr != NULL) ? inet_addr(envstr) : 0;
426 
427 	envstr = getenv("netmask");
428 	mask = (envstr != NULL) ? inet_addr(envstr) : 0;
429 
430 	envstr = getenv("gatewayip");
431 	gwaddr = (envstr != NULL) ? inet_addr(envstr) : 0;
432 
433 	envstr = getenv("serverip");
434 	serveraddr = (envstr != NULL) ? inet_addr(envstr) : 0;
435 
436 	/* No network params. */
437 	if (ipaddr == 0 && mask == 0 && gwaddr == 0 && serveraddr == 0)
438 		return;
439 
440 	/* Partial network params. */
441 	if (ipaddr == 0 || mask == 0 || gwaddr == 0 || serveraddr == 0) {
442 		printf("Incomplete network settings from U-Boot\n");
443 		return;
444 	}
445 
446 	/*
447 	 * Set network parameters.
448 	 */
449 	myip.s_addr = ipaddr;
450 	netmask = mask;
451 	gateip.s_addr = gwaddr;
452 	servip.s_addr = serveraddr;
453 
454 	/*
455 	 * There must be a rootpath. It may be ip:/path or it may be just the
456 	 * path in which case the ip needs to be serverip.
457 	 */
458 	rootaddr = net_parse_rootpath();
459 	if (rootaddr == INADDR_NONE)
460 		rootaddr = serveraddr;
461 	rootip.s_addr = rootaddr;
462 
463 #ifdef EFINET_DEBUG
464 	printf("%s: proto=%d\n", __func__, netproto);
465 	printf("%s: ip=%s\n", __func__, inet_ntoa(myip));
466 	printf("%s: mask=%s\n", __func__, intoa(netmask));
467 	printf("%s: gateway=%s\n", __func__, inet_ntoa(gateip));
468 	printf("%s: server=%s\n", __func__, inet_ntoa(servip));
469 #endif
470 
471 	desc->myip = myip;
472 }
473 
474 static void
efinet_init(struct iodesc * desc,void * machdep_hint)475 efinet_init(struct iodesc *desc, void *machdep_hint)
476 {
477 	struct netif *nif = desc->io_netif;
478 	EFI_SIMPLE_NETWORK *net;
479 	EFI_HANDLE h;
480 	EFI_STATUS status;
481 	UINT32 mask;
482 
483 	/* Attempt to get netboot params from env */
484 	efi_env_net_params(desc);
485 
486 	if (nif->nif_driver->netif_ifs[nif->nif_unit].dif_unit < 0) {
487 		printf("Invalid network interface %d\n", nif->nif_unit);
488 		return;
489 	}
490 
491 	h = nif->nif_driver->netif_ifs[nif->nif_unit].dif_private;
492 	if (rootip.s_addr == 0)
493 		efi_pxe_publish_cache(nif->nif_unit);
494 	status = OpenProtocolByHandle(h, &sn_guid, (void **)&nif->nif_devdata);
495 	if (status != EFI_SUCCESS) {
496 		printf("net%d: cannot fetch interface data (status=%lu)\n",
497 		    nif->nif_unit, DECODE_ERROR(status));
498 		return;
499 	}
500 
501 	net = nif->nif_devdata;
502 	if (net->Mode->State == EfiSimpleNetworkStopped) {
503 		status = net->Start(net);
504 		if (status != EFI_SUCCESS) {
505 			printf("net%d: cannot start interface (status=%lu)\n",
506 			    nif->nif_unit, DECODE_ERROR(status));
507 			return;
508 		}
509 	}
510 
511 	if (net->Mode->State != EfiSimpleNetworkInitialized) {
512 		status = net->Initialize(net, 0, 0);
513 		if (status != EFI_SUCCESS) {
514 			printf("net%d: cannot init. interface (status=%lu)\n",
515 			    nif->nif_unit, DECODE_ERROR(status));
516 			return;
517 		}
518 	}
519 
520 	mask = EFI_SIMPLE_NETWORK_RECEIVE_UNICAST |
521 	    EFI_SIMPLE_NETWORK_RECEIVE_BROADCAST;
522 
523 	status = net->ReceiveFilters(net, mask, 0, FALSE, 0, NULL);
524 	if (status != EFI_SUCCESS)
525 		printf("net%d: cannot set rx. filters (status=%lu)\n",
526 		    nif->nif_unit, DECODE_ERROR(status));
527 
528 #ifdef EFINET_DEBUG
529 	dump_mode(net->Mode);
530 #endif
531 
532 	bcopy(net->Mode->CurrentAddress.Addr, desc->myea, 6);
533 }
534 
535 static void
efinet_end(struct netif * nif)536 efinet_end(struct netif *nif)
537 {
538 	EFI_SIMPLE_NETWORK *net = nif->nif_devdata;
539 
540 	if (net == NULL)
541 		return;
542 
543 	net->Shutdown(net);
544 }
545 
546 static int efinet_dev_init(void);
547 static int efinet_dev_print(int);
548 
549 struct devsw efinet_dev = {
550 	.dv_name = "net",
551 	.dv_type = DEVT_NET,
552 	.dv_init = efinet_dev_init,
553 	.dv_strategy = NULL,		/* Will be set in efinet_dev_init */
554 	.dv_open = NULL,		/* Will be set in efinet_dev_init */
555 	.dv_close = NULL,		/* Will be set in efinet_dev_init */
556 	.dv_ioctl = noioctl,
557 	.dv_print = efinet_dev_print,
558 	.dv_cleanup = nullsys,
559 };
560 
561 static int
efinet_dev_init(void)562 efinet_dev_init(void)
563 {
564 	struct netif_dif *dif;
565 	struct netif_stats *stats;
566 	EFI_DEVICE_PATH *devpath, *node;
567 	EFI_HANDLE *handles, *handles2;
568 	EFI_STATUS status;
569 	UINTN sz;
570 	int err, i, nifs;
571 	extern struct devsw netdev;
572 
573 	/*
574 	 * Advertise our DHCP Client-System Architecture (RFC 4578).  Many
575 	 * x86_64 UEFI firmwares report themselves as "EFI BC" (0x0007)
576 	 * rather than "EFI x86-64" (0x0009); match that convention for
577 	 * best DHCP-server config compatibility.
578 	 */
579 #if defined(__amd64__)
580 	bootp_client_arch = 0x0007;	/* EFI BC */
581 #elif defined(__i386__)
582 	bootp_client_arch = 0x0006;	/* EFI IA32 */
583 #elif defined(__aarch64__)
584 	bootp_client_arch = 0x000b;	/* EFI 64-bit ARM */
585 #elif defined(__arm__)
586 	bootp_client_arch = 0x000a;	/* EFI 32-bit ARM */
587 #elif defined(__riscv)
588 	bootp_client_arch = 0x001b;	/* EFI 64-bit RISC-V */
589 #endif
590 
591 	sz = 0;
592 	handles = NULL;
593 	status = BS->LocateHandle(ByProtocol, &sn_guid, NULL, &sz, NULL);
594 	if (status == EFI_BUFFER_TOO_SMALL) {
595 		handles = (EFI_HANDLE *)malloc(sz);
596 		if (handles == NULL)
597 			return (ENOMEM);
598 		status = BS->LocateHandle(ByProtocol, &sn_guid, NULL, &sz,
599 		    handles);
600 		if (EFI_ERROR(status))
601 			free(handles);
602 	}
603 	if (EFI_ERROR(status))
604 		return (efi_status_to_errno(status));
605 	handles2 = (EFI_HANDLE *)malloc(sz);
606 	if (handles2 == NULL) {
607 		free(handles);
608 		return (ENOMEM);
609 	}
610 	nifs = 0;
611 	for (i = 0; i < sz / sizeof(EFI_HANDLE); i++) {
612 		devpath = efi_lookup_devpath(handles[i]);
613 		if (devpath == NULL)
614 			continue;
615 		if ((node = efi_devpath_last_node(devpath)) == NULL)
616 			continue;
617 
618 		if (DevicePathType(node) != MESSAGING_DEVICE_PATH ||
619 		    DevicePathSubType(node) != MSG_MAC_ADDR_DP)
620 			continue;
621 
622 		handles2[nifs] = handles[i];
623 		nifs++;
624 	}
625 	free(handles);
626 	if (nifs == 0) {
627 		err = ENOENT;
628 		goto done;
629 	}
630 
631 	err = efi_register_handles(&efinet_dev, handles2, NULL, nifs);
632 	if (err != 0)
633 		goto done;
634 
635 	efinetif.netif_ifs = calloc(nifs, sizeof(struct netif_dif));
636 	stats = calloc(nifs, sizeof(struct netif_stats));
637 	if (efinetif.netif_ifs == NULL || stats == NULL) {
638 		free(efinetif.netif_ifs);
639 		free(stats);
640 		efinetif.netif_ifs = NULL;
641 		err = ENOMEM;
642 		goto done;
643 	}
644 	efinetif.netif_nifs = nifs;
645 
646 	for (i = 0; i < nifs; i++) {
647 
648 		dif = &efinetif.netif_ifs[i];
649 		dif->dif_unit = i;
650 		dif->dif_nsel = 1;
651 		dif->dif_stats = &stats[i];
652 		dif->dif_private = handles2[i];
653 	}
654 
655 	/*
656 	 * Snapshot the PXE Base Code cache now, before any code path
657 	 * opens the SNP with EFI_OPEN_PROTOCOL_EXCLUSIVE (efinet_probe()).
658 	 * An EXCLUSIVE open causes the firmware to disconnect the UEFI
659 	 * PXE driver, which uninstalls the PXE Base Code Protocol and
660 	 * loses the cached DhcpAck/ProxyOffer packets.
661 	 */
662 	efi_pxe_snapshot_all(nifs);
663 
664 	efinet_dev.dv_cleanup = netdev.dv_cleanup;
665 	efinet_dev.dv_open = netdev.dv_open;
666 	efinet_dev.dv_close = netdev.dv_close;
667 	efinet_dev.dv_strategy = netdev.dv_strategy;
668 
669 done:
670 	free(handles2);
671 	return (err);
672 }
673 
674 static int
efinet_dev_print(int verbose)675 efinet_dev_print(int verbose)
676 {
677 	CHAR16 *text;
678 	EFI_HANDLE h;
679 	int unit, ret = 0;
680 
681 	printf("%s devices:", efinet_dev.dv_name);
682 	if ((ret = pager_output("\n")) != 0)
683 		return (ret);
684 
685 	for (unit = 0, h = efi_find_handle(&efinet_dev, 0);
686 	    h != NULL; h = efi_find_handle(&efinet_dev, ++unit)) {
687 		printf("    %s%d:", efinet_dev.dv_name, unit);
688 		if (verbose) {
689 			text = efi_devpath_name(efi_lookup_devpath(h));
690 			if (text != NULL) {
691 				printf("    %S", text);
692 				efi_free_devpath_name(text);
693 			}
694 		}
695 		if ((ret = pager_output("\n")) != 0)
696 			break;
697 	}
698 	return (ret);
699 }
700