]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/DxeNetLib/DxeNetLib.c
MdeModulePkg: Clean up source files
[mirror_edk2.git] / MdeModulePkg / Library / DxeNetLib / DxeNetLib.c
1 /** @file
2 Network library.
3
4 Copyright (c) 2005 - 2018, Intel Corporation. All rights reserved.<BR>
5 (C) Copyright 2015 Hewlett Packard Enterprise Development LP<BR>
6 This program and the accompanying materials
7 are licensed and made available under the terms and conditions of the BSD License
8 which accompanies this distribution. The full text of the license may be found at
9 http://opensource.org/licenses/bsd-license.php
10
11 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
12 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
13 **/
14
15 #include <Uefi.h>
16
17 #include <IndustryStandard/SmBios.h>
18
19 #include <Protocol/DriverBinding.h>
20 #include <Protocol/ServiceBinding.h>
21 #include <Protocol/SimpleNetwork.h>
22 #include <Protocol/AdapterInformation.h>
23 #include <Protocol/ManagedNetwork.h>
24 #include <Protocol/Ip4Config2.h>
25 #include <Protocol/ComponentName.h>
26 #include <Protocol/ComponentName2.h>
27
28 #include <Guid/SmBios.h>
29
30 #include <Library/NetLib.h>
31 #include <Library/BaseLib.h>
32 #include <Library/DebugLib.h>
33 #include <Library/BaseMemoryLib.h>
34 #include <Library/UefiBootServicesTableLib.h>
35 #include <Library/UefiRuntimeServicesTableLib.h>
36 #include <Library/MemoryAllocationLib.h>
37 #include <Library/DevicePathLib.h>
38 #include <Library/PrintLib.h>
39 #include <Library/UefiLib.h>
40
41 #define NIC_ITEM_CONFIG_SIZE (sizeof (NIC_IP4_CONFIG_INFO) + sizeof (EFI_IP4_ROUTE_TABLE) * MAX_IP4_CONFIG_IN_VARIABLE)
42 #define DEFAULT_ZERO_START ((UINTN) ~0)
43
44 //
45 // All the supported IP4 maskes in host byte order.
46 //
47 GLOBAL_REMOVE_IF_UNREFERENCED IP4_ADDR gIp4AllMasks[IP4_MASK_NUM] = {
48 0x00000000,
49 0x80000000,
50 0xC0000000,
51 0xE0000000,
52 0xF0000000,
53 0xF8000000,
54 0xFC000000,
55 0xFE000000,
56
57 0xFF000000,
58 0xFF800000,
59 0xFFC00000,
60 0xFFE00000,
61 0xFFF00000,
62 0xFFF80000,
63 0xFFFC0000,
64 0xFFFE0000,
65
66 0xFFFF0000,
67 0xFFFF8000,
68 0xFFFFC000,
69 0xFFFFE000,
70 0xFFFFF000,
71 0xFFFFF800,
72 0xFFFFFC00,
73 0xFFFFFE00,
74
75 0xFFFFFF00,
76 0xFFFFFF80,
77 0xFFFFFFC0,
78 0xFFFFFFE0,
79 0xFFFFFFF0,
80 0xFFFFFFF8,
81 0xFFFFFFFC,
82 0xFFFFFFFE,
83 0xFFFFFFFF,
84 };
85
86 GLOBAL_REMOVE_IF_UNREFERENCED EFI_IPv4_ADDRESS mZeroIp4Addr = {{0, 0, 0, 0}};
87
88 //
89 // Any error level digitally larger than mNetDebugLevelMax
90 // will be silently discarded.
91 //
92 GLOBAL_REMOVE_IF_UNREFERENCED UINTN mNetDebugLevelMax = NETDEBUG_LEVEL_ERROR;
93 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogPacketSeq = 0xDEADBEEF;
94
95 //
96 // You can change mSyslogDstMac mSyslogDstIp and mSyslogSrcIp
97 // here to direct the syslog packets to the syslog deamon. The
98 // default is broadcast to both the ethernet and IP.
99 //
100 GLOBAL_REMOVE_IF_UNREFERENCED UINT8 mSyslogDstMac[NET_ETHER_ADDR_LEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
101 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogDstIp = 0xffffffff;
102 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogSrcIp = 0;
103
104 GLOBAL_REMOVE_IF_UNREFERENCED CHAR8 *mMonthName[] = {
105 "Jan",
106 "Feb",
107 "Mar",
108 "Apr",
109 "May",
110 "Jun",
111 "Jul",
112 "Aug",
113 "Sep",
114 "Oct",
115 "Nov",
116 "Dec"
117 };
118
119 //
120 // VLAN device path node template
121 //
122 GLOBAL_REMOVE_IF_UNREFERENCED VLAN_DEVICE_PATH mNetVlanDevicePathTemplate = {
123 {
124 MESSAGING_DEVICE_PATH,
125 MSG_VLAN_DP,
126 {
127 (UINT8) (sizeof (VLAN_DEVICE_PATH)),
128 (UINT8) ((sizeof (VLAN_DEVICE_PATH)) >> 8)
129 }
130 },
131 0
132 };
133
134 /**
135 Locate the handles that support SNP, then open one of them
136 to send the syslog packets. The caller isn't required to close
137 the SNP after use because the SNP is opened by HandleProtocol.
138
139 @return The point to SNP if one is properly openned. Otherwise NULL
140
141 **/
142 EFI_SIMPLE_NETWORK_PROTOCOL *
143 SyslogLocateSnp (
144 VOID
145 )
146 {
147 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
148 EFI_STATUS Status;
149 EFI_HANDLE *Handles;
150 UINTN HandleCount;
151 UINTN Index;
152
153 //
154 // Locate the handles which has SNP installed.
155 //
156 Handles = NULL;
157 Status = gBS->LocateHandleBuffer (
158 ByProtocol,
159 &gEfiSimpleNetworkProtocolGuid,
160 NULL,
161 &HandleCount,
162 &Handles
163 );
164
165 if (EFI_ERROR (Status) || (HandleCount == 0)) {
166 return NULL;
167 }
168
169 //
170 // Try to open one of the ethernet SNP protocol to send packet
171 //
172 Snp = NULL;
173
174 for (Index = 0; Index < HandleCount; Index++) {
175 Status = gBS->HandleProtocol (
176 Handles[Index],
177 &gEfiSimpleNetworkProtocolGuid,
178 (VOID **) &Snp
179 );
180
181 if ((Status == EFI_SUCCESS) && (Snp != NULL) &&
182 (Snp->Mode->IfType == NET_IFTYPE_ETHERNET) &&
183 (Snp->Mode->MaxPacketSize >= NET_SYSLOG_PACKET_LEN)) {
184
185 break;
186 }
187
188 Snp = NULL;
189 }
190
191 FreePool (Handles);
192 return Snp;
193 }
194
195 /**
196 Transmit a syslog packet synchronously through SNP. The Packet
197 already has the ethernet header prepended. This function should
198 fill in the source MAC because it will try to locate a SNP each
199 time it is called to avoid the problem if SNP is unloaded.
200 This code snip is copied from MNP.
201 If Packet is NULL, then ASSERT().
202
203 @param[in] Packet The Syslog packet
204 @param[in] Length The length of the packet
205
206 @retval EFI_DEVICE_ERROR Failed to locate a usable SNP protocol
207 @retval EFI_TIMEOUT Timeout happened to send the packet.
208 @retval EFI_SUCCESS Packet is sent.
209
210 **/
211 EFI_STATUS
212 SyslogSendPacket (
213 IN CHAR8 *Packet,
214 IN UINT32 Length
215 )
216 {
217 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
218 ETHER_HEAD *Ether;
219 EFI_STATUS Status;
220 EFI_EVENT TimeoutEvent;
221 UINT8 *TxBuf;
222
223 ASSERT (Packet != NULL);
224
225 Snp = SyslogLocateSnp ();
226
227 if (Snp == NULL) {
228 return EFI_DEVICE_ERROR;
229 }
230
231 Ether = (ETHER_HEAD *) Packet;
232 CopyMem (Ether->SrcMac, Snp->Mode->CurrentAddress.Addr, NET_ETHER_ADDR_LEN);
233
234 //
235 // Start the timeout event.
236 //
237 Status = gBS->CreateEvent (
238 EVT_TIMER,
239 TPL_NOTIFY,
240 NULL,
241 NULL,
242 &TimeoutEvent
243 );
244
245 if (EFI_ERROR (Status)) {
246 return Status;
247 }
248
249 Status = gBS->SetTimer (TimeoutEvent, TimerRelative, NET_SYSLOG_TX_TIMEOUT);
250
251 if (EFI_ERROR (Status)) {
252 goto ON_EXIT;
253 }
254
255 for (;;) {
256 //
257 // Transmit the packet through SNP.
258 //
259 Status = Snp->Transmit (Snp, 0, Length, Packet, NULL, NULL, NULL);
260
261 if ((Status != EFI_SUCCESS) && (Status != EFI_NOT_READY)) {
262 Status = EFI_DEVICE_ERROR;
263 break;
264 }
265
266 //
267 // If Status is EFI_SUCCESS, the packet is put in the transmit queue.
268 // if Status is EFI_NOT_READY, the transmit engine of the network
269 // interface is busy. Both need to sync SNP.
270 //
271 TxBuf = NULL;
272
273 do {
274 //
275 // Get the recycled transmit buffer status.
276 //
277 Snp->GetStatus (Snp, NULL, (VOID **) &TxBuf);
278
279 if (!EFI_ERROR (gBS->CheckEvent (TimeoutEvent))) {
280 Status = EFI_TIMEOUT;
281 break;
282 }
283
284 } while (TxBuf == NULL);
285
286 if ((Status == EFI_SUCCESS) || (Status == EFI_TIMEOUT)) {
287 break;
288 }
289
290 //
291 // Status is EFI_NOT_READY. Restart the timer event and
292 // call Snp->Transmit again.
293 //
294 gBS->SetTimer (TimeoutEvent, TimerRelative, NET_SYSLOG_TX_TIMEOUT);
295 }
296
297 gBS->SetTimer (TimeoutEvent, TimerCancel, 0);
298
299 ON_EXIT:
300 gBS->CloseEvent (TimeoutEvent);
301 return Status;
302 }
303
304 /**
305 Build a syslog packet, including the Ethernet/Ip/Udp headers
306 and user's message.
307
308 @param[in] Level Syslog severity level
309 @param[in] Module The module that generates the log
310 @param[in] File The file that contains the current log
311 @param[in] Line The line of code in the File that contains the current log
312 @param[in] Message The log message
313 @param[in] BufLen The lenght of the Buf
314 @param[out] Buf The buffer to put the packet data
315
316 @return The length of the syslog packet built, 0 represents no packet is built.
317
318 **/
319 UINT32
320 SyslogBuildPacket (
321 IN UINT32 Level,
322 IN UINT8 *Module,
323 IN UINT8 *File,
324 IN UINT32 Line,
325 IN UINT8 *Message,
326 IN UINT32 BufLen,
327 OUT CHAR8 *Buf
328 )
329 {
330 EFI_STATUS Status;
331 ETHER_HEAD *Ether;
332 IP4_HEAD *Ip4;
333 EFI_UDP_HEADER *Udp4;
334 EFI_TIME Time;
335 UINT32 Pri;
336 UINT32 Len;
337
338 //
339 // Fill in the Ethernet header. Leave alone the source MAC.
340 // SyslogSendPacket will fill in the address for us.
341 //
342 Ether = (ETHER_HEAD *) Buf;
343 CopyMem (Ether->DstMac, mSyslogDstMac, NET_ETHER_ADDR_LEN);
344 ZeroMem (Ether->SrcMac, NET_ETHER_ADDR_LEN);
345
346 Ether->EtherType = HTONS (0x0800); // IPv4 protocol
347
348 Buf += sizeof (ETHER_HEAD);
349 BufLen -= sizeof (ETHER_HEAD);
350
351 //
352 // Fill in the IP header
353 //
354 Ip4 = (IP4_HEAD *) Buf;
355 Ip4->HeadLen = 5;
356 Ip4->Ver = 4;
357 Ip4->Tos = 0;
358 Ip4->TotalLen = 0;
359 Ip4->Id = (UINT16) mSyslogPacketSeq;
360 Ip4->Fragment = 0;
361 Ip4->Ttl = 16;
362 Ip4->Protocol = 0x11;
363 Ip4->Checksum = 0;
364 Ip4->Src = mSyslogSrcIp;
365 Ip4->Dst = mSyslogDstIp;
366
367 Buf += sizeof (IP4_HEAD);
368 BufLen -= sizeof (IP4_HEAD);
369
370 //
371 // Fill in the UDP header, Udp checksum is optional. Leave it zero.
372 //
373 Udp4 = (EFI_UDP_HEADER *) Buf;
374 Udp4->SrcPort = HTONS (514);
375 Udp4->DstPort = HTONS (514);
376 Udp4->Length = 0;
377 Udp4->Checksum = 0;
378
379 Buf += sizeof (EFI_UDP_HEADER);
380 BufLen -= sizeof (EFI_UDP_HEADER);
381
382 //
383 // Build the syslog message body with <PRI> Timestamp machine module Message
384 //
385 Pri = ((NET_SYSLOG_FACILITY & 31) << 3) | (Level & 7);
386 Status = gRT->GetTime (&Time, NULL);
387 if (EFI_ERROR (Status)) {
388 return 0;
389 }
390
391 //
392 // Use %a to format the ASCII strings, %s to format UNICODE strings
393 //
394 Len = 0;
395 Len += (UINT32) AsciiSPrint (
396 Buf,
397 BufLen,
398 "<%d> %a %d %d:%d:%d ",
399 Pri,
400 mMonthName [Time.Month-1],
401 Time.Day,
402 Time.Hour,
403 Time.Minute,
404 Time.Second
405 );
406
407 Len += (UINT32) AsciiSPrint (
408 Buf + Len,
409 BufLen - Len,
410 "Tiano %a: %a (Line: %d File: %a)",
411 Module,
412 Message,
413 Line,
414 File
415 );
416 Len ++;
417
418 //
419 // OK, patch the IP length/checksum and UDP length fields.
420 //
421 Len += sizeof (EFI_UDP_HEADER);
422 Udp4->Length = HTONS ((UINT16) Len);
423
424 Len += sizeof (IP4_HEAD);
425 Ip4->TotalLen = HTONS ((UINT16) Len);
426 Ip4->Checksum = (UINT16) (~NetblockChecksum ((UINT8 *) Ip4, sizeof (IP4_HEAD)));
427
428 return Len + sizeof (ETHER_HEAD);
429 }
430
431 /**
432 Allocate a buffer, then format the message to it. This is a
433 help function for the NET_DEBUG_XXX macros. The PrintArg of
434 these macros treats the variable length print parameters as a
435 single parameter, and pass it to the NetDebugASPrint. For
436 example, NET_DEBUG_TRACE ("Tcp", ("State transit to %a\n", Name))
437 if extracted to:
438
439 NetDebugOutput (
440 NETDEBUG_LEVEL_TRACE,
441 "Tcp",
442 __FILE__,
443 __LINE__,
444 NetDebugASPrint ("State transit to %a\n", Name)
445 )
446
447 If Format is NULL, then ASSERT().
448
449 @param Format The ASCII format string.
450 @param ... The variable length parameter whose format is determined
451 by the Format string.
452
453 @return The buffer containing the formatted message,
454 or NULL if failed to allocate memory.
455
456 **/
457 CHAR8 *
458 EFIAPI
459 NetDebugASPrint (
460 IN CHAR8 *Format,
461 ...
462 )
463 {
464 VA_LIST Marker;
465 CHAR8 *Buf;
466
467 ASSERT (Format != NULL);
468
469 Buf = (CHAR8 *) AllocatePool (NET_DEBUG_MSG_LEN);
470
471 if (Buf == NULL) {
472 return NULL;
473 }
474
475 VA_START (Marker, Format);
476 AsciiVSPrint (Buf, NET_DEBUG_MSG_LEN, Format, Marker);
477 VA_END (Marker);
478
479 return Buf;
480 }
481
482 /**
483 Builds an UDP4 syslog packet and send it using SNP.
484
485 This function will locate a instance of SNP then send the message through it.
486 Because it isn't open the SNP BY_DRIVER, apply caution when using it.
487
488 @param Level The severity level of the message.
489 @param Module The Moudle that generates the log.
490 @param File The file that contains the log.
491 @param Line The exact line that contains the log.
492 @param Message The user message to log.
493
494 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
495 @retval EFI_OUT_OF_RESOURCES Failed to allocate memory for the packet.
496 @retval EFI_DEVICE_ERROR Device error occurs.
497 @retval EFI_SUCCESS The log is discard because that it is more verbose
498 than the mNetDebugLevelMax. Or, it has been sent out.
499 **/
500 EFI_STATUS
501 EFIAPI
502 NetDebugOutput (
503 IN UINT32 Level,
504 IN UINT8 *Module,
505 IN UINT8 *File,
506 IN UINT32 Line,
507 IN UINT8 *Message
508 )
509 {
510 CHAR8 *Packet;
511 UINT32 Len;
512 EFI_STATUS Status;
513
514 //
515 // Check whether the message should be sent out
516 //
517 if (Message == NULL || File == NULL || Module == NULL) {
518 return EFI_INVALID_PARAMETER;
519 }
520
521 if (Level > mNetDebugLevelMax) {
522 Status = EFI_SUCCESS;
523 goto ON_EXIT;
524 }
525
526 //
527 // Allocate a maxium of 1024 bytes, the caller should ensure
528 // that the message plus the ethernet/ip/udp header is shorter
529 // than this
530 //
531 Packet = (CHAR8 *) AllocatePool (NET_SYSLOG_PACKET_LEN);
532
533 if (Packet == NULL) {
534 Status = EFI_OUT_OF_RESOURCES;
535 goto ON_EXIT;
536 }
537
538 //
539 // Build the message: Ethernet header + IP header + Udp Header + user data
540 //
541 Len = SyslogBuildPacket (
542 Level,
543 Module,
544 File,
545 Line,
546 Message,
547 NET_SYSLOG_PACKET_LEN,
548 Packet
549 );
550 if (Len == 0) {
551 Status = EFI_DEVICE_ERROR;
552 } else {
553 mSyslogPacketSeq++;
554 Status = SyslogSendPacket (Packet, Len);
555 }
556
557 FreePool (Packet);
558
559 ON_EXIT:
560 FreePool (Message);
561 return Status;
562 }
563 /**
564 Return the length of the mask.
565
566 Return the length of the mask, the correct value is from 0 to 32.
567 If the mask is invalid, return the invalid length 33, which is IP4_MASK_NUM.
568 NetMask is in the host byte order.
569
570 @param[in] NetMask The netmask to get the length from.
571
572 @return The length of the netmask, IP4_MASK_NUM if the mask is invalid.
573
574 **/
575 INTN
576 EFIAPI
577 NetGetMaskLength (
578 IN IP4_ADDR NetMask
579 )
580 {
581 INTN Index;
582
583 for (Index = 0; Index <= IP4_MASK_MAX; Index++) {
584 if (NetMask == gIp4AllMasks[Index]) {
585 break;
586 }
587 }
588
589 return Index;
590 }
591
592
593
594 /**
595 Return the class of the IP address, such as class A, B, C.
596 Addr is in host byte order.
597
598 [ATTENTION]
599 Classful addressing (IP class A/B/C) has been deprecated according to RFC4632.
600 Caller of this function could only check the returned value against
601 IP4_ADDR_CLASSD (multicast) or IP4_ADDR_CLASSE (reserved) now.
602
603 The address of class A starts with 0.
604 If the address belong to class A, return IP4_ADDR_CLASSA.
605 The address of class B starts with 10.
606 If the address belong to class B, return IP4_ADDR_CLASSB.
607 The address of class C starts with 110.
608 If the address belong to class C, return IP4_ADDR_CLASSC.
609 The address of class D starts with 1110.
610 If the address belong to class D, return IP4_ADDR_CLASSD.
611 The address of class E starts with 1111.
612 If the address belong to class E, return IP4_ADDR_CLASSE.
613
614
615 @param[in] Addr The address to get the class from.
616
617 @return IP address class, such as IP4_ADDR_CLASSA.
618
619 **/
620 INTN
621 EFIAPI
622 NetGetIpClass (
623 IN IP4_ADDR Addr
624 )
625 {
626 UINT8 ByteOne;
627
628 ByteOne = (UINT8) (Addr >> 24);
629
630 if ((ByteOne & 0x80) == 0) {
631 return IP4_ADDR_CLASSA;
632
633 } else if ((ByteOne & 0xC0) == 0x80) {
634 return IP4_ADDR_CLASSB;
635
636 } else if ((ByteOne & 0xE0) == 0xC0) {
637 return IP4_ADDR_CLASSC;
638
639 } else if ((ByteOne & 0xF0) == 0xE0) {
640 return IP4_ADDR_CLASSD;
641
642 } else {
643 return IP4_ADDR_CLASSE;
644
645 }
646 }
647
648
649 /**
650 Check whether the IP is a valid unicast address according to
651 the netmask.
652
653 ASSERT if NetMask is zero.
654
655 If all bits of the host address of IP are 0 or 1, IP is also not a valid unicast address,
656 except when the originator is one of the endpoints of a point-to-point link with a 31-bit
657 mask (RFC3021).
658
659 @param[in] Ip The IP to check against.
660 @param[in] NetMask The mask of the IP.
661
662 @return TRUE if IP is a valid unicast address on the network, otherwise FALSE.
663
664 **/
665 BOOLEAN
666 EFIAPI
667 NetIp4IsUnicast (
668 IN IP4_ADDR Ip,
669 IN IP4_ADDR NetMask
670 )
671 {
672 ASSERT (NetMask != 0);
673
674 if (Ip == 0 || IP4_IS_LOCAL_BROADCAST (Ip)) {
675 return FALSE;
676 }
677
678 if (NetGetMaskLength (NetMask) != 31) {
679 if (((Ip &~NetMask) == ~NetMask) || ((Ip &~NetMask) == 0)) {
680 return FALSE;
681 }
682 } else {
683 return TRUE;
684 }
685
686 return TRUE;
687 }
688
689 /**
690 Check whether the incoming IPv6 address is a valid unicast address.
691
692 ASSERT if Ip6 is NULL.
693
694 If the address is a multicast address has binary 0xFF at the start, it is not
695 a valid unicast address. If the address is unspecified ::, it is not a valid
696 unicast address to be assigned to any node. If the address is loopback address
697 ::1, it is also not a valid unicast address to be assigned to any physical
698 interface.
699
700 @param[in] Ip6 The IPv6 address to check against.
701
702 @return TRUE if Ip6 is a valid unicast address on the network, otherwise FALSE.
703
704 **/
705 BOOLEAN
706 EFIAPI
707 NetIp6IsValidUnicast (
708 IN EFI_IPv6_ADDRESS *Ip6
709 )
710 {
711 UINT8 Byte;
712 UINT8 Index;
713
714 ASSERT (Ip6 != NULL);
715
716 if (Ip6->Addr[0] == 0xFF) {
717 return FALSE;
718 }
719
720 for (Index = 0; Index < 15; Index++) {
721 if (Ip6->Addr[Index] != 0) {
722 return TRUE;
723 }
724 }
725
726 Byte = Ip6->Addr[Index];
727
728 if (Byte == 0x0 || Byte == 0x1) {
729 return FALSE;
730 }
731
732 return TRUE;
733 }
734
735 /**
736 Check whether the incoming Ipv6 address is the unspecified address or not.
737
738 ASSERT if Ip6 is NULL.
739
740 @param[in] Ip6 - Ip6 address, in network order.
741
742 @retval TRUE - Yes, unspecified
743 @retval FALSE - No
744
745 **/
746 BOOLEAN
747 EFIAPI
748 NetIp6IsUnspecifiedAddr (
749 IN EFI_IPv6_ADDRESS *Ip6
750 )
751 {
752 UINT8 Index;
753
754 ASSERT (Ip6 != NULL);
755
756 for (Index = 0; Index < 16; Index++) {
757 if (Ip6->Addr[Index] != 0) {
758 return FALSE;
759 }
760 }
761
762 return TRUE;
763 }
764
765 /**
766 Check whether the incoming Ipv6 address is a link-local address.
767
768 ASSERT if Ip6 is NULL.
769
770 @param[in] Ip6 - Ip6 address, in network order.
771
772 @retval TRUE - Yes, link-local address
773 @retval FALSE - No
774
775 **/
776 BOOLEAN
777 EFIAPI
778 NetIp6IsLinkLocalAddr (
779 IN EFI_IPv6_ADDRESS *Ip6
780 )
781 {
782 UINT8 Index;
783
784 ASSERT (Ip6 != NULL);
785
786 if (Ip6->Addr[0] != 0xFE) {
787 return FALSE;
788 }
789
790 if (Ip6->Addr[1] != 0x80) {
791 return FALSE;
792 }
793
794 for (Index = 2; Index < 8; Index++) {
795 if (Ip6->Addr[Index] != 0) {
796 return FALSE;
797 }
798 }
799
800 return TRUE;
801 }
802
803 /**
804 Check whether the Ipv6 address1 and address2 are on the connected network.
805
806 ASSERT if Ip1 or Ip2 is NULL.
807 ASSERT if PrefixLength exceeds or equals to IP6_PREFIX_MAX.
808
809 @param[in] Ip1 - Ip6 address1, in network order.
810 @param[in] Ip2 - Ip6 address2, in network order.
811 @param[in] PrefixLength - The prefix length of the checking net.
812
813 @retval TRUE - Yes, connected.
814 @retval FALSE - No.
815
816 **/
817 BOOLEAN
818 EFIAPI
819 NetIp6IsNetEqual (
820 EFI_IPv6_ADDRESS *Ip1,
821 EFI_IPv6_ADDRESS *Ip2,
822 UINT8 PrefixLength
823 )
824 {
825 UINT8 Byte;
826 UINT8 Bit;
827 UINT8 Mask;
828
829 ASSERT ((Ip1 != NULL) && (Ip2 != NULL) && (PrefixLength < IP6_PREFIX_MAX));
830
831 if (PrefixLength == 0) {
832 return TRUE;
833 }
834
835 Byte = (UINT8) (PrefixLength / 8);
836 Bit = (UINT8) (PrefixLength % 8);
837
838 if (CompareMem (Ip1, Ip2, Byte) != 0) {
839 return FALSE;
840 }
841
842 if (Bit > 0) {
843 Mask = (UINT8) (0xFF << (8 - Bit));
844
845 ASSERT (Byte < 16);
846 if (Byte >= 16) {
847 return FALSE;
848 }
849 if ((Ip1->Addr[Byte] & Mask) != (Ip2->Addr[Byte] & Mask)) {
850 return FALSE;
851 }
852 }
853
854 return TRUE;
855 }
856
857
858 /**
859 Switches the endianess of an IPv6 address
860
861 ASSERT if Ip6 is NULL.
862
863 This function swaps the bytes in a 128-bit IPv6 address to switch the value
864 from little endian to big endian or vice versa. The byte swapped value is
865 returned.
866
867 @param Ip6 Points to an IPv6 address
868
869 @return The byte swapped IPv6 address.
870
871 **/
872 EFI_IPv6_ADDRESS *
873 EFIAPI
874 Ip6Swap128 (
875 EFI_IPv6_ADDRESS *Ip6
876 )
877 {
878 UINT64 High;
879 UINT64 Low;
880
881 ASSERT (Ip6 != NULL);
882
883 CopyMem (&High, Ip6, sizeof (UINT64));
884 CopyMem (&Low, &Ip6->Addr[8], sizeof (UINT64));
885
886 High = SwapBytes64 (High);
887 Low = SwapBytes64 (Low);
888
889 CopyMem (Ip6, &Low, sizeof (UINT64));
890 CopyMem (&Ip6->Addr[8], &High, sizeof (UINT64));
891
892 return Ip6;
893 }
894
895 /**
896 Initialize a random seed using current time and monotonic count.
897
898 Get current time and monotonic count first. Then initialize a random seed
899 based on some basic mathematics operation on the hour, day, minute, second,
900 nanosecond and year of the current time and the monotonic count value.
901
902 @return The random seed initialized with current time.
903
904 **/
905 UINT32
906 EFIAPI
907 NetRandomInitSeed (
908 VOID
909 )
910 {
911 EFI_TIME Time;
912 UINT32 Seed;
913 UINT64 MonotonicCount;
914
915 gRT->GetTime (&Time, NULL);
916 Seed = (Time.Hour << 24 | Time.Day << 16 | Time.Minute << 8 | Time.Second);
917 Seed ^= Time.Nanosecond;
918 Seed ^= Time.Year << 7;
919
920 gBS->GetNextMonotonicCount (&MonotonicCount);
921 Seed += (UINT32) MonotonicCount;
922
923 return Seed;
924 }
925
926
927 /**
928 Extract a UINT32 from a byte stream.
929
930 ASSERT if Buf is NULL.
931
932 Copy a UINT32 from a byte stream, then converts it from Network
933 byte order to host byte order. Use this function to avoid alignment error.
934
935 @param[in] Buf The buffer to extract the UINT32.
936
937 @return The UINT32 extracted.
938
939 **/
940 UINT32
941 EFIAPI
942 NetGetUint32 (
943 IN UINT8 *Buf
944 )
945 {
946 UINT32 Value;
947
948 ASSERT (Buf != NULL);
949
950 CopyMem (&Value, Buf, sizeof (UINT32));
951 return NTOHL (Value);
952 }
953
954
955 /**
956 Put a UINT32 to the byte stream in network byte order.
957
958 ASSERT if Buf is NULL.
959
960 Converts a UINT32 from host byte order to network byte order. Then copy it to the
961 byte stream.
962
963 @param[in, out] Buf The buffer to put the UINT32.
964 @param[in] Data The data to be converted and put into the byte stream.
965
966 **/
967 VOID
968 EFIAPI
969 NetPutUint32 (
970 IN OUT UINT8 *Buf,
971 IN UINT32 Data
972 )
973 {
974 ASSERT (Buf != NULL);
975
976 Data = HTONL (Data);
977 CopyMem (Buf, &Data, sizeof (UINT32));
978 }
979
980
981 /**
982 Remove the first node entry on the list, and return the removed node entry.
983
984 Removes the first node Entry from a doubly linked list. It is up to the caller of
985 this function to release the memory used by the first node if that is required. On
986 exit, the removed node is returned.
987
988 If Head is NULL, then ASSERT().
989 If Head was not initialized, then ASSERT().
990 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
991 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
992 then ASSERT().
993
994 @param[in, out] Head The list header.
995
996 @return The first node entry that is removed from the list, NULL if the list is empty.
997
998 **/
999 LIST_ENTRY *
1000 EFIAPI
1001 NetListRemoveHead (
1002 IN OUT LIST_ENTRY *Head
1003 )
1004 {
1005 LIST_ENTRY *First;
1006
1007 ASSERT (Head != NULL);
1008
1009 if (IsListEmpty (Head)) {
1010 return NULL;
1011 }
1012
1013 First = Head->ForwardLink;
1014 Head->ForwardLink = First->ForwardLink;
1015 First->ForwardLink->BackLink = Head;
1016
1017 DEBUG_CODE (
1018 First->ForwardLink = (LIST_ENTRY *) NULL;
1019 First->BackLink = (LIST_ENTRY *) NULL;
1020 );
1021
1022 return First;
1023 }
1024
1025
1026 /**
1027 Remove the last node entry on the list and and return the removed node entry.
1028
1029 Removes the last node entry from a doubly linked list. It is up to the caller of
1030 this function to release the memory used by the first node if that is required. On
1031 exit, the removed node is returned.
1032
1033 If Head is NULL, then ASSERT().
1034 If Head was not initialized, then ASSERT().
1035 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
1036 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
1037 then ASSERT().
1038
1039 @param[in, out] Head The list head.
1040
1041 @return The last node entry that is removed from the list, NULL if the list is empty.
1042
1043 **/
1044 LIST_ENTRY *
1045 EFIAPI
1046 NetListRemoveTail (
1047 IN OUT LIST_ENTRY *Head
1048 )
1049 {
1050 LIST_ENTRY *Last;
1051
1052 ASSERT (Head != NULL);
1053
1054 if (IsListEmpty (Head)) {
1055 return NULL;
1056 }
1057
1058 Last = Head->BackLink;
1059 Head->BackLink = Last->BackLink;
1060 Last->BackLink->ForwardLink = Head;
1061
1062 DEBUG_CODE (
1063 Last->ForwardLink = (LIST_ENTRY *) NULL;
1064 Last->BackLink = (LIST_ENTRY *) NULL;
1065 );
1066
1067 return Last;
1068 }
1069
1070
1071 /**
1072 Insert a new node entry after a designated node entry of a doubly linked list.
1073
1074 ASSERT if PrevEntry or NewEntry is NULL.
1075
1076 Inserts a new node entry donated by NewEntry after the node entry donated by PrevEntry
1077 of the doubly linked list.
1078
1079 @param[in, out] PrevEntry The previous entry to insert after.
1080 @param[in, out] NewEntry The new entry to insert.
1081
1082 **/
1083 VOID
1084 EFIAPI
1085 NetListInsertAfter (
1086 IN OUT LIST_ENTRY *PrevEntry,
1087 IN OUT LIST_ENTRY *NewEntry
1088 )
1089 {
1090 ASSERT (PrevEntry != NULL && NewEntry != NULL);
1091
1092 NewEntry->BackLink = PrevEntry;
1093 NewEntry->ForwardLink = PrevEntry->ForwardLink;
1094 PrevEntry->ForwardLink->BackLink = NewEntry;
1095 PrevEntry->ForwardLink = NewEntry;
1096 }
1097
1098
1099 /**
1100 Insert a new node entry before a designated node entry of a doubly linked list.
1101
1102 ASSERT if PostEntry or NewEntry is NULL.
1103
1104 Inserts a new node entry donated by NewEntry after the node entry donated by PostEntry
1105 of the doubly linked list.
1106
1107 @param[in, out] PostEntry The entry to insert before.
1108 @param[in, out] NewEntry The new entry to insert.
1109
1110 **/
1111 VOID
1112 EFIAPI
1113 NetListInsertBefore (
1114 IN OUT LIST_ENTRY *PostEntry,
1115 IN OUT LIST_ENTRY *NewEntry
1116 )
1117 {
1118 ASSERT (PostEntry != NULL && NewEntry != NULL);
1119
1120 NewEntry->ForwardLink = PostEntry;
1121 NewEntry->BackLink = PostEntry->BackLink;
1122 PostEntry->BackLink->ForwardLink = NewEntry;
1123 PostEntry->BackLink = NewEntry;
1124 }
1125
1126 /**
1127 Safe destroy nodes in a linked list, and return the length of the list after all possible operations finished.
1128
1129 Destroy network child instance list by list traversals is not safe due to graph dependencies between nodes.
1130 This function performs a safe traversal to destroy these nodes by checking to see if the node being destroyed
1131 has been removed from the list or not.
1132 If it has been removed, then restart the traversal from the head.
1133 If it hasn't been removed, then continue with the next node directly.
1134 This function will end the iterate and return the CallBack's last return value if error happens,
1135 or retrun EFI_SUCCESS if 2 complete passes are made with no changes in the number of children in the list.
1136
1137 @param[in] List The head of the list.
1138 @param[in] CallBack Pointer to the callback function to destroy one node in the list.
1139 @param[in] Context Pointer to the callback function's context: corresponds to the
1140 parameter Context in NET_DESTROY_LINK_LIST_CALLBACK.
1141 @param[out] ListLength The length of the link list if the function returns successfully.
1142
1143 @retval EFI_SUCCESS Two complete passes are made with no changes in the number of children.
1144 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
1145 @retval Others Return the CallBack's last return value.
1146
1147 **/
1148 EFI_STATUS
1149 EFIAPI
1150 NetDestroyLinkList (
1151 IN LIST_ENTRY *List,
1152 IN NET_DESTROY_LINK_LIST_CALLBACK CallBack,
1153 IN VOID *Context, OPTIONAL
1154 OUT UINTN *ListLength OPTIONAL
1155 )
1156 {
1157 UINTN PreviousLength;
1158 LIST_ENTRY *Entry;
1159 LIST_ENTRY *Ptr;
1160 UINTN Length;
1161 EFI_STATUS Status;
1162
1163 if (List == NULL || CallBack == NULL) {
1164 return EFI_INVALID_PARAMETER;
1165 }
1166
1167 Length = 0;
1168 do {
1169 PreviousLength = Length;
1170 Entry = GetFirstNode (List);
1171 while (!IsNull (List, Entry)) {
1172 Status = CallBack (Entry, Context);
1173 if (EFI_ERROR (Status)) {
1174 return Status;
1175 }
1176 //
1177 // Walk through the list to see whether the Entry has been removed or not.
1178 // If the Entry still exists, just try to destroy the next one.
1179 // If not, go back to the start point to iterate the list again.
1180 //
1181 for (Ptr = List->ForwardLink; Ptr != List; Ptr = Ptr->ForwardLink) {
1182 if (Ptr == Entry) {
1183 break;
1184 }
1185 }
1186 if (Ptr == Entry) {
1187 Entry = GetNextNode (List, Entry);
1188 } else {
1189 Entry = GetFirstNode (List);
1190 }
1191 }
1192 for (Length = 0, Ptr = List->ForwardLink; Ptr != List; Length++, Ptr = Ptr->ForwardLink);
1193 } while (Length != PreviousLength);
1194
1195 if (ListLength != NULL) {
1196 *ListLength = Length;
1197 }
1198 return EFI_SUCCESS;
1199 }
1200
1201 /**
1202 This function checks the input Handle to see if it's one of these handles in ChildHandleBuffer.
1203
1204 @param[in] Handle Handle to be checked.
1205 @param[in] NumberOfChildren Number of Handles in ChildHandleBuffer.
1206 @param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
1207 if NumberOfChildren is 0.
1208
1209 @retval TRUE Found the input Handle in ChildHandleBuffer.
1210 @retval FALSE Can't find the input Handle in ChildHandleBuffer.
1211
1212 **/
1213 BOOLEAN
1214 EFIAPI
1215 NetIsInHandleBuffer (
1216 IN EFI_HANDLE Handle,
1217 IN UINTN NumberOfChildren,
1218 IN EFI_HANDLE *ChildHandleBuffer OPTIONAL
1219 )
1220 {
1221 UINTN Index;
1222
1223 if (NumberOfChildren == 0 || ChildHandleBuffer == NULL) {
1224 return FALSE;
1225 }
1226
1227 for (Index = 0; Index < NumberOfChildren; Index++) {
1228 if (Handle == ChildHandleBuffer[Index]) {
1229 return TRUE;
1230 }
1231 }
1232
1233 return FALSE;
1234 }
1235
1236
1237 /**
1238 Initialize the netmap. Netmap is a reposity to keep the <Key, Value> pairs.
1239
1240 Initialize the forward and backward links of two head nodes donated by Map->Used
1241 and Map->Recycled of two doubly linked lists.
1242 Initializes the count of the <Key, Value> pairs in the netmap to zero.
1243
1244 If Map is NULL, then ASSERT().
1245 If the address of Map->Used is NULL, then ASSERT().
1246 If the address of Map->Recycled is NULl, then ASSERT().
1247
1248 @param[in, out] Map The netmap to initialize.
1249
1250 **/
1251 VOID
1252 EFIAPI
1253 NetMapInit (
1254 IN OUT NET_MAP *Map
1255 )
1256 {
1257 ASSERT (Map != NULL);
1258
1259 InitializeListHead (&Map->Used);
1260 InitializeListHead (&Map->Recycled);
1261 Map->Count = 0;
1262 }
1263
1264
1265 /**
1266 To clean up the netmap, that is, release allocated memories.
1267
1268 Removes all nodes of the Used doubly linked list and free memory of all related netmap items.
1269 Removes all nodes of the Recycled doubly linked list and free memory of all related netmap items.
1270 The number of the <Key, Value> pairs in the netmap is set to be zero.
1271
1272 If Map is NULL, then ASSERT().
1273
1274 @param[in, out] Map The netmap to clean up.
1275
1276 **/
1277 VOID
1278 EFIAPI
1279 NetMapClean (
1280 IN OUT NET_MAP *Map
1281 )
1282 {
1283 NET_MAP_ITEM *Item;
1284 LIST_ENTRY *Entry;
1285 LIST_ENTRY *Next;
1286
1287 ASSERT (Map != NULL);
1288
1289 NET_LIST_FOR_EACH_SAFE (Entry, Next, &Map->Used) {
1290 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1291
1292 RemoveEntryList (&Item->Link);
1293 Map->Count--;
1294
1295 gBS->FreePool (Item);
1296 }
1297
1298 ASSERT ((Map->Count == 0) && IsListEmpty (&Map->Used));
1299
1300 NET_LIST_FOR_EACH_SAFE (Entry, Next, &Map->Recycled) {
1301 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1302
1303 RemoveEntryList (&Item->Link);
1304 gBS->FreePool (Item);
1305 }
1306
1307 ASSERT (IsListEmpty (&Map->Recycled));
1308 }
1309
1310
1311 /**
1312 Test whether the netmap is empty and return true if it is.
1313
1314 If the number of the <Key, Value> pairs in the netmap is zero, return TRUE.
1315
1316 If Map is NULL, then ASSERT().
1317
1318 @param[in] Map The net map to test.
1319
1320 @return TRUE if the netmap is empty, otherwise FALSE.
1321
1322 **/
1323 BOOLEAN
1324 EFIAPI
1325 NetMapIsEmpty (
1326 IN NET_MAP *Map
1327 )
1328 {
1329 ASSERT (Map != NULL);
1330 return (BOOLEAN) (Map->Count == 0);
1331 }
1332
1333
1334 /**
1335 Return the number of the <Key, Value> pairs in the netmap.
1336
1337 If Map is NULL, then ASSERT().
1338
1339 @param[in] Map The netmap to get the entry number.
1340
1341 @return The entry number in the netmap.
1342
1343 **/
1344 UINTN
1345 EFIAPI
1346 NetMapGetCount (
1347 IN NET_MAP *Map
1348 )
1349 {
1350 ASSERT (Map != NULL);
1351 return Map->Count;
1352 }
1353
1354
1355 /**
1356 Return one allocated item.
1357
1358 If the Recycled doubly linked list of the netmap is empty, it will try to allocate
1359 a batch of items if there are enough resources and add corresponding nodes to the begining
1360 of the Recycled doubly linked list of the netmap. Otherwise, it will directly remove
1361 the fist node entry of the Recycled doubly linked list and return the corresponding item.
1362
1363 If Map is NULL, then ASSERT().
1364
1365 @param[in, out] Map The netmap to allocate item for.
1366
1367 @return The allocated item. If NULL, the
1368 allocation failed due to resource limit.
1369
1370 **/
1371 NET_MAP_ITEM *
1372 NetMapAllocItem (
1373 IN OUT NET_MAP *Map
1374 )
1375 {
1376 NET_MAP_ITEM *Item;
1377 LIST_ENTRY *Head;
1378 UINTN Index;
1379
1380 ASSERT (Map != NULL);
1381
1382 Head = &Map->Recycled;
1383
1384 if (IsListEmpty (Head)) {
1385 for (Index = 0; Index < NET_MAP_INCREAMENT; Index++) {
1386 Item = AllocatePool (sizeof (NET_MAP_ITEM));
1387
1388 if (Item == NULL) {
1389 if (Index == 0) {
1390 return NULL;
1391 }
1392
1393 break;
1394 }
1395
1396 InsertHeadList (Head, &Item->Link);
1397 }
1398 }
1399
1400 Item = NET_LIST_HEAD (Head, NET_MAP_ITEM, Link);
1401 NetListRemoveHead (Head);
1402
1403 return Item;
1404 }
1405
1406
1407 /**
1408 Allocate an item to save the <Key, Value> pair to the head of the netmap.
1409
1410 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1411 to the beginning of the Used doubly linked list. The number of the <Key, Value>
1412 pairs in the netmap increase by 1.
1413
1414 If Map is NULL, then ASSERT().
1415 If Key is NULL, then ASSERT().
1416
1417 @param[in, out] Map The netmap to insert into.
1418 @param[in] Key The user's key.
1419 @param[in] Value The user's value for the key.
1420
1421 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1422 @retval EFI_SUCCESS The item is inserted to the head.
1423
1424 **/
1425 EFI_STATUS
1426 EFIAPI
1427 NetMapInsertHead (
1428 IN OUT NET_MAP *Map,
1429 IN VOID *Key,
1430 IN VOID *Value OPTIONAL
1431 )
1432 {
1433 NET_MAP_ITEM *Item;
1434
1435 ASSERT (Map != NULL && Key != NULL);
1436
1437 Item = NetMapAllocItem (Map);
1438
1439 if (Item == NULL) {
1440 return EFI_OUT_OF_RESOURCES;
1441 }
1442
1443 Item->Key = Key;
1444 Item->Value = Value;
1445 InsertHeadList (&Map->Used, &Item->Link);
1446
1447 Map->Count++;
1448 return EFI_SUCCESS;
1449 }
1450
1451
1452 /**
1453 Allocate an item to save the <Key, Value> pair to the tail of the netmap.
1454
1455 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1456 to the tail of the Used doubly linked list. The number of the <Key, Value>
1457 pairs in the netmap increase by 1.
1458
1459 If Map is NULL, then ASSERT().
1460 If Key is NULL, then ASSERT().
1461
1462 @param[in, out] Map The netmap to insert into.
1463 @param[in] Key The user's key.
1464 @param[in] Value The user's value for the key.
1465
1466 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1467 @retval EFI_SUCCESS The item is inserted to the tail.
1468
1469 **/
1470 EFI_STATUS
1471 EFIAPI
1472 NetMapInsertTail (
1473 IN OUT NET_MAP *Map,
1474 IN VOID *Key,
1475 IN VOID *Value OPTIONAL
1476 )
1477 {
1478 NET_MAP_ITEM *Item;
1479
1480 ASSERT (Map != NULL && Key != NULL);
1481
1482 Item = NetMapAllocItem (Map);
1483
1484 if (Item == NULL) {
1485 return EFI_OUT_OF_RESOURCES;
1486 }
1487
1488 Item->Key = Key;
1489 Item->Value = Value;
1490 InsertTailList (&Map->Used, &Item->Link);
1491
1492 Map->Count++;
1493
1494 return EFI_SUCCESS;
1495 }
1496
1497
1498 /**
1499 Check whether the item is in the Map and return TRUE if it is.
1500
1501 If Map is NULL, then ASSERT().
1502 If Item is NULL, then ASSERT().
1503
1504 @param[in] Map The netmap to search within.
1505 @param[in] Item The item to search.
1506
1507 @return TRUE if the item is in the netmap, otherwise FALSE.
1508
1509 **/
1510 BOOLEAN
1511 NetItemInMap (
1512 IN NET_MAP *Map,
1513 IN NET_MAP_ITEM *Item
1514 )
1515 {
1516 LIST_ENTRY *ListEntry;
1517
1518 ASSERT (Map != NULL && Item != NULL);
1519
1520 NET_LIST_FOR_EACH (ListEntry, &Map->Used) {
1521 if (ListEntry == &Item->Link) {
1522 return TRUE;
1523 }
1524 }
1525
1526 return FALSE;
1527 }
1528
1529
1530 /**
1531 Find the key in the netmap and returns the point to the item contains the Key.
1532
1533 Iterate the Used doubly linked list of the netmap to get every item. Compare the key of every
1534 item with the key to search. It returns the point to the item contains the Key if found.
1535
1536 If Map is NULL, then ASSERT().
1537 If Key is NULL, then ASSERT().
1538
1539 @param[in] Map The netmap to search within.
1540 @param[in] Key The key to search.
1541
1542 @return The point to the item contains the Key, or NULL if Key isn't in the map.
1543
1544 **/
1545 NET_MAP_ITEM *
1546 EFIAPI
1547 NetMapFindKey (
1548 IN NET_MAP *Map,
1549 IN VOID *Key
1550 )
1551 {
1552 LIST_ENTRY *Entry;
1553 NET_MAP_ITEM *Item;
1554
1555 ASSERT (Map != NULL && Key != NULL);
1556
1557 NET_LIST_FOR_EACH (Entry, &Map->Used) {
1558 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1559
1560 if (Item->Key == Key) {
1561 return Item;
1562 }
1563 }
1564
1565 return NULL;
1566 }
1567
1568
1569 /**
1570 Remove the node entry of the item from the netmap and return the key of the removed item.
1571
1572 Remove the node entry of the item from the Used doubly linked list of the netmap.
1573 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1574 entry of the item to the Recycled doubly linked list of the netmap. If Value is not NULL,
1575 Value will point to the value of the item. It returns the key of the removed item.
1576
1577 If Map is NULL, then ASSERT().
1578 If Item is NULL, then ASSERT().
1579 if item in not in the netmap, then ASSERT().
1580
1581 @param[in, out] Map The netmap to remove the item from.
1582 @param[in, out] Item The item to remove.
1583 @param[out] Value The variable to receive the value if not NULL.
1584
1585 @return The key of the removed item.
1586
1587 **/
1588 VOID *
1589 EFIAPI
1590 NetMapRemoveItem (
1591 IN OUT NET_MAP *Map,
1592 IN OUT NET_MAP_ITEM *Item,
1593 OUT VOID **Value OPTIONAL
1594 )
1595 {
1596 ASSERT ((Map != NULL) && (Item != NULL));
1597 ASSERT (NetItemInMap (Map, Item));
1598
1599 RemoveEntryList (&Item->Link);
1600 Map->Count--;
1601 InsertHeadList (&Map->Recycled, &Item->Link);
1602
1603 if (Value != NULL) {
1604 *Value = Item->Value;
1605 }
1606
1607 return Item->Key;
1608 }
1609
1610
1611 /**
1612 Remove the first node entry on the netmap and return the key of the removed item.
1613
1614 Remove the first node entry from the Used doubly linked list of the netmap.
1615 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1616 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1617 parameter Value will point to the value of the item. It returns the key of the removed item.
1618
1619 If Map is NULL, then ASSERT().
1620 If the Used doubly linked list is empty, then ASSERT().
1621
1622 @param[in, out] Map The netmap to remove the head from.
1623 @param[out] Value The variable to receive the value if not NULL.
1624
1625 @return The key of the item removed.
1626
1627 **/
1628 VOID *
1629 EFIAPI
1630 NetMapRemoveHead (
1631 IN OUT NET_MAP *Map,
1632 OUT VOID **Value OPTIONAL
1633 )
1634 {
1635 NET_MAP_ITEM *Item;
1636
1637 //
1638 // Often, it indicates a programming error to remove
1639 // the first entry in an empty list
1640 //
1641 ASSERT (Map && !IsListEmpty (&Map->Used));
1642
1643 Item = NET_LIST_HEAD (&Map->Used, NET_MAP_ITEM, Link);
1644 RemoveEntryList (&Item->Link);
1645 Map->Count--;
1646 InsertHeadList (&Map->Recycled, &Item->Link);
1647
1648 if (Value != NULL) {
1649 *Value = Item->Value;
1650 }
1651
1652 return Item->Key;
1653 }
1654
1655
1656 /**
1657 Remove the last node entry on the netmap and return the key of the removed item.
1658
1659 Remove the last node entry from the Used doubly linked list of the netmap.
1660 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1661 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1662 parameter Value will point to the value of the item. It returns the key of the removed item.
1663
1664 If Map is NULL, then ASSERT().
1665 If the Used doubly linked list is empty, then ASSERT().
1666
1667 @param[in, out] Map The netmap to remove the tail from.
1668 @param[out] Value The variable to receive the value if not NULL.
1669
1670 @return The key of the item removed.
1671
1672 **/
1673 VOID *
1674 EFIAPI
1675 NetMapRemoveTail (
1676 IN OUT NET_MAP *Map,
1677 OUT VOID **Value OPTIONAL
1678 )
1679 {
1680 NET_MAP_ITEM *Item;
1681
1682 //
1683 // Often, it indicates a programming error to remove
1684 // the last entry in an empty list
1685 //
1686 ASSERT (Map && !IsListEmpty (&Map->Used));
1687
1688 Item = NET_LIST_TAIL (&Map->Used, NET_MAP_ITEM, Link);
1689 RemoveEntryList (&Item->Link);
1690 Map->Count--;
1691 InsertHeadList (&Map->Recycled, &Item->Link);
1692
1693 if (Value != NULL) {
1694 *Value = Item->Value;
1695 }
1696
1697 return Item->Key;
1698 }
1699
1700
1701 /**
1702 Iterate through the netmap and call CallBack for each item.
1703
1704 It will continue the traverse if CallBack returns EFI_SUCCESS, otherwise, break
1705 from the loop. It returns the CallBack's last return value. This function is
1706 delete safe for the current item.
1707
1708 If Map is NULL, then ASSERT().
1709 If CallBack is NULL, then ASSERT().
1710
1711 @param[in] Map The Map to iterate through.
1712 @param[in] CallBack The callback function to call for each item.
1713 @param[in] Arg The opaque parameter to the callback.
1714
1715 @retval EFI_SUCCESS There is no item in the netmap or CallBack for each item
1716 return EFI_SUCCESS.
1717 @retval Others It returns the CallBack's last return value.
1718
1719 **/
1720 EFI_STATUS
1721 EFIAPI
1722 NetMapIterate (
1723 IN NET_MAP *Map,
1724 IN NET_MAP_CALLBACK CallBack,
1725 IN VOID *Arg OPTIONAL
1726 )
1727 {
1728
1729 LIST_ENTRY *Entry;
1730 LIST_ENTRY *Next;
1731 LIST_ENTRY *Head;
1732 NET_MAP_ITEM *Item;
1733 EFI_STATUS Result;
1734
1735 ASSERT ((Map != NULL) && (CallBack != NULL));
1736
1737 Head = &Map->Used;
1738
1739 if (IsListEmpty (Head)) {
1740 return EFI_SUCCESS;
1741 }
1742
1743 NET_LIST_FOR_EACH_SAFE (Entry, Next, Head) {
1744 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1745 Result = CallBack (Map, Item, Arg);
1746
1747 if (EFI_ERROR (Result)) {
1748 return Result;
1749 }
1750 }
1751
1752 return EFI_SUCCESS;
1753 }
1754
1755
1756 /**
1757 This is the default unload handle for all the network drivers.
1758
1759 Disconnect the driver specified by ImageHandle from all the devices in the handle database.
1760 Uninstall all the protocols installed in the driver entry point.
1761
1762 @param[in] ImageHandle The drivers' driver image.
1763
1764 @retval EFI_SUCCESS The image is unloaded.
1765 @retval Others Failed to unload the image.
1766
1767 **/
1768 EFI_STATUS
1769 EFIAPI
1770 NetLibDefaultUnload (
1771 IN EFI_HANDLE ImageHandle
1772 )
1773 {
1774 EFI_STATUS Status;
1775 EFI_HANDLE *DeviceHandleBuffer;
1776 UINTN DeviceHandleCount;
1777 UINTN Index;
1778 UINTN Index2;
1779 EFI_DRIVER_BINDING_PROTOCOL *DriverBinding;
1780 EFI_COMPONENT_NAME_PROTOCOL *ComponentName;
1781 EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2;
1782
1783 //
1784 // Get the list of all the handles in the handle database.
1785 // If there is an error getting the list, then the unload
1786 // operation fails.
1787 //
1788 Status = gBS->LocateHandleBuffer (
1789 AllHandles,
1790 NULL,
1791 NULL,
1792 &DeviceHandleCount,
1793 &DeviceHandleBuffer
1794 );
1795
1796 if (EFI_ERROR (Status)) {
1797 return Status;
1798 }
1799
1800 for (Index = 0; Index < DeviceHandleCount; Index++) {
1801 Status = gBS->HandleProtocol (
1802 DeviceHandleBuffer[Index],
1803 &gEfiDriverBindingProtocolGuid,
1804 (VOID **) &DriverBinding
1805 );
1806 if (EFI_ERROR (Status)) {
1807 continue;
1808 }
1809
1810 if (DriverBinding->ImageHandle != ImageHandle) {
1811 continue;
1812 }
1813
1814 //
1815 // Disconnect the driver specified by ImageHandle from all
1816 // the devices in the handle database.
1817 //
1818 for (Index2 = 0; Index2 < DeviceHandleCount; Index2++) {
1819 Status = gBS->DisconnectController (
1820 DeviceHandleBuffer[Index2],
1821 DriverBinding->DriverBindingHandle,
1822 NULL
1823 );
1824 }
1825
1826 //
1827 // Uninstall all the protocols installed in the driver entry point
1828 //
1829 gBS->UninstallProtocolInterface (
1830 DriverBinding->DriverBindingHandle,
1831 &gEfiDriverBindingProtocolGuid,
1832 DriverBinding
1833 );
1834
1835 Status = gBS->HandleProtocol (
1836 DeviceHandleBuffer[Index],
1837 &gEfiComponentNameProtocolGuid,
1838 (VOID **) &ComponentName
1839 );
1840 if (!EFI_ERROR (Status)) {
1841 gBS->UninstallProtocolInterface (
1842 DriverBinding->DriverBindingHandle,
1843 &gEfiComponentNameProtocolGuid,
1844 ComponentName
1845 );
1846 }
1847
1848 Status = gBS->HandleProtocol (
1849 DeviceHandleBuffer[Index],
1850 &gEfiComponentName2ProtocolGuid,
1851 (VOID **) &ComponentName2
1852 );
1853 if (!EFI_ERROR (Status)) {
1854 gBS->UninstallProtocolInterface (
1855 DriverBinding->DriverBindingHandle,
1856 &gEfiComponentName2ProtocolGuid,
1857 ComponentName2
1858 );
1859 }
1860 }
1861
1862 //
1863 // Free the buffer containing the list of handles from the handle database
1864 //
1865 if (DeviceHandleBuffer != NULL) {
1866 gBS->FreePool (DeviceHandleBuffer);
1867 }
1868
1869 return EFI_SUCCESS;
1870 }
1871
1872
1873
1874 /**
1875 Create a child of the service that is identified by ServiceBindingGuid.
1876
1877 Get the ServiceBinding Protocol first, then use it to create a child.
1878
1879 If ServiceBindingGuid is NULL, then ASSERT().
1880 If ChildHandle is NULL, then ASSERT().
1881
1882 @param[in] Controller The controller which has the service installed.
1883 @param[in] Image The image handle used to open service.
1884 @param[in] ServiceBindingGuid The service's Guid.
1885 @param[in, out] ChildHandle The handle to receive the create child.
1886
1887 @retval EFI_SUCCESS The child is successfully created.
1888 @retval Others Failed to create the child.
1889
1890 **/
1891 EFI_STATUS
1892 EFIAPI
1893 NetLibCreateServiceChild (
1894 IN EFI_HANDLE Controller,
1895 IN EFI_HANDLE Image,
1896 IN EFI_GUID *ServiceBindingGuid,
1897 IN OUT EFI_HANDLE *ChildHandle
1898 )
1899 {
1900 EFI_STATUS Status;
1901 EFI_SERVICE_BINDING_PROTOCOL *Service;
1902
1903
1904 ASSERT ((ServiceBindingGuid != NULL) && (ChildHandle != NULL));
1905
1906 //
1907 // Get the ServiceBinding Protocol
1908 //
1909 Status = gBS->OpenProtocol (
1910 Controller,
1911 ServiceBindingGuid,
1912 (VOID **) &Service,
1913 Image,
1914 Controller,
1915 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1916 );
1917
1918 if (EFI_ERROR (Status)) {
1919 return Status;
1920 }
1921
1922 //
1923 // Create a child
1924 //
1925 Status = Service->CreateChild (Service, ChildHandle);
1926 return Status;
1927 }
1928
1929
1930 /**
1931 Destroy a child of the service that is identified by ServiceBindingGuid.
1932
1933 Get the ServiceBinding Protocol first, then use it to destroy a child.
1934
1935 If ServiceBindingGuid is NULL, then ASSERT().
1936
1937 @param[in] Controller The controller which has the service installed.
1938 @param[in] Image The image handle used to open service.
1939 @param[in] ServiceBindingGuid The service's Guid.
1940 @param[in] ChildHandle The child to destroy.
1941
1942 @retval EFI_SUCCESS The child is successfully destroyed.
1943 @retval Others Failed to destroy the child.
1944
1945 **/
1946 EFI_STATUS
1947 EFIAPI
1948 NetLibDestroyServiceChild (
1949 IN EFI_HANDLE Controller,
1950 IN EFI_HANDLE Image,
1951 IN EFI_GUID *ServiceBindingGuid,
1952 IN EFI_HANDLE ChildHandle
1953 )
1954 {
1955 EFI_STATUS Status;
1956 EFI_SERVICE_BINDING_PROTOCOL *Service;
1957
1958 ASSERT (ServiceBindingGuid != NULL);
1959
1960 //
1961 // Get the ServiceBinding Protocol
1962 //
1963 Status = gBS->OpenProtocol (
1964 Controller,
1965 ServiceBindingGuid,
1966 (VOID **) &Service,
1967 Image,
1968 Controller,
1969 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1970 );
1971
1972 if (EFI_ERROR (Status)) {
1973 return Status;
1974 }
1975
1976 //
1977 // destroy the child
1978 //
1979 Status = Service->DestroyChild (Service, ChildHandle);
1980 return Status;
1981 }
1982
1983 /**
1984 Get handle with Simple Network Protocol installed on it.
1985
1986 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
1987 If Simple Network Protocol is already installed on the ServiceHandle, the
1988 ServiceHandle will be returned. If SNP is not installed on the ServiceHandle,
1989 try to find its parent handle with SNP installed.
1990
1991 @param[in] ServiceHandle The handle where network service binding protocols are
1992 installed on.
1993 @param[out] Snp The pointer to store the address of the SNP instance.
1994 This is an optional parameter that may be NULL.
1995
1996 @return The SNP handle, or NULL if not found.
1997
1998 **/
1999 EFI_HANDLE
2000 EFIAPI
2001 NetLibGetSnpHandle (
2002 IN EFI_HANDLE ServiceHandle,
2003 OUT EFI_SIMPLE_NETWORK_PROTOCOL **Snp OPTIONAL
2004 )
2005 {
2006 EFI_STATUS Status;
2007 EFI_SIMPLE_NETWORK_PROTOCOL *SnpInstance;
2008 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2009 EFI_HANDLE SnpHandle;
2010
2011 //
2012 // Try to open SNP from ServiceHandle
2013 //
2014 SnpInstance = NULL;
2015 Status = gBS->HandleProtocol (ServiceHandle, &gEfiSimpleNetworkProtocolGuid, (VOID **) &SnpInstance);
2016 if (!EFI_ERROR (Status)) {
2017 if (Snp != NULL) {
2018 *Snp = SnpInstance;
2019 }
2020 return ServiceHandle;
2021 }
2022
2023 //
2024 // Failed to open SNP, try to get SNP handle by LocateDevicePath()
2025 //
2026 DevicePath = DevicePathFromHandle (ServiceHandle);
2027 if (DevicePath == NULL) {
2028 return NULL;
2029 }
2030
2031 SnpHandle = NULL;
2032 Status = gBS->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid, &DevicePath, &SnpHandle);
2033 if (EFI_ERROR (Status)) {
2034 //
2035 // Failed to find SNP handle
2036 //
2037 return NULL;
2038 }
2039
2040 Status = gBS->HandleProtocol (SnpHandle, &gEfiSimpleNetworkProtocolGuid, (VOID **) &SnpInstance);
2041 if (!EFI_ERROR (Status)) {
2042 if (Snp != NULL) {
2043 *Snp = SnpInstance;
2044 }
2045 return SnpHandle;
2046 }
2047
2048 return NULL;
2049 }
2050
2051 /**
2052 Retrieve VLAN ID of a VLAN device handle.
2053
2054 Search VLAN device path node in Device Path of specified ServiceHandle and
2055 return its VLAN ID. If no VLAN device path node found, then this ServiceHandle
2056 is not a VLAN device handle, and 0 will be returned.
2057
2058 @param[in] ServiceHandle The handle where network service binding protocols are
2059 installed on.
2060
2061 @return VLAN ID of the device handle, or 0 if not a VLAN device.
2062
2063 **/
2064 UINT16
2065 EFIAPI
2066 NetLibGetVlanId (
2067 IN EFI_HANDLE ServiceHandle
2068 )
2069 {
2070 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2071 EFI_DEVICE_PATH_PROTOCOL *Node;
2072
2073 DevicePath = DevicePathFromHandle (ServiceHandle);
2074 if (DevicePath == NULL) {
2075 return 0;
2076 }
2077
2078 Node = DevicePath;
2079 while (!IsDevicePathEnd (Node)) {
2080 if (Node->Type == MESSAGING_DEVICE_PATH && Node->SubType == MSG_VLAN_DP) {
2081 return ((VLAN_DEVICE_PATH *) Node)->VlanId;
2082 }
2083 Node = NextDevicePathNode (Node);
2084 }
2085
2086 return 0;
2087 }
2088
2089 /**
2090 Find VLAN device handle with specified VLAN ID.
2091
2092 The VLAN child device handle is created by VLAN Config Protocol on ControllerHandle.
2093 This function will append VLAN device path node to the parent device path,
2094 and then use LocateDevicePath() to find the correct VLAN device handle.
2095
2096 @param[in] ControllerHandle The handle where network service binding protocols are
2097 installed on.
2098 @param[in] VlanId The configured VLAN ID for the VLAN device.
2099
2100 @return The VLAN device handle, or NULL if not found.
2101
2102 **/
2103 EFI_HANDLE
2104 EFIAPI
2105 NetLibGetVlanHandle (
2106 IN EFI_HANDLE ControllerHandle,
2107 IN UINT16 VlanId
2108 )
2109 {
2110 EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath;
2111 EFI_DEVICE_PATH_PROTOCOL *VlanDevicePath;
2112 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2113 VLAN_DEVICE_PATH VlanNode;
2114 EFI_HANDLE Handle;
2115
2116 ParentDevicePath = DevicePathFromHandle (ControllerHandle);
2117 if (ParentDevicePath == NULL) {
2118 return NULL;
2119 }
2120
2121 //
2122 // Construct VLAN device path
2123 //
2124 CopyMem (&VlanNode, &mNetVlanDevicePathTemplate, sizeof (VLAN_DEVICE_PATH));
2125 VlanNode.VlanId = VlanId;
2126 VlanDevicePath = AppendDevicePathNode (
2127 ParentDevicePath,
2128 (EFI_DEVICE_PATH_PROTOCOL *) &VlanNode
2129 );
2130 if (VlanDevicePath == NULL) {
2131 return NULL;
2132 }
2133
2134 //
2135 // Find VLAN device handle
2136 //
2137 Handle = NULL;
2138 DevicePath = VlanDevicePath;
2139 gBS->LocateDevicePath (
2140 &gEfiDevicePathProtocolGuid,
2141 &DevicePath,
2142 &Handle
2143 );
2144 if (!IsDevicePathEnd (DevicePath)) {
2145 //
2146 // Device path is not exactly match
2147 //
2148 Handle = NULL;
2149 }
2150
2151 FreePool (VlanDevicePath);
2152 return Handle;
2153 }
2154
2155 /**
2156 Get MAC address associated with the network service handle.
2157
2158 If MacAddress is NULL, then ASSERT().
2159 If AddressSize is NULL, then ASSERT().
2160
2161 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
2162 If SNP is installed on the ServiceHandle or its parent handle, MAC address will
2163 be retrieved from SNP. If no SNP found, try to get SNP mode data use MNP.
2164
2165 @param[in] ServiceHandle The handle where network service binding protocols are
2166 installed on.
2167 @param[out] MacAddress The pointer to store the returned MAC address.
2168 @param[out] AddressSize The length of returned MAC address.
2169
2170 @retval EFI_SUCCESS MAC address is returned successfully.
2171 @retval Others Failed to get SNP mode data.
2172
2173 **/
2174 EFI_STATUS
2175 EFIAPI
2176 NetLibGetMacAddress (
2177 IN EFI_HANDLE ServiceHandle,
2178 OUT EFI_MAC_ADDRESS *MacAddress,
2179 OUT UINTN *AddressSize
2180 )
2181 {
2182 EFI_STATUS Status;
2183 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
2184 EFI_SIMPLE_NETWORK_MODE *SnpMode;
2185 EFI_SIMPLE_NETWORK_MODE SnpModeData;
2186 EFI_MANAGED_NETWORK_PROTOCOL *Mnp;
2187 EFI_SERVICE_BINDING_PROTOCOL *MnpSb;
2188 EFI_HANDLE *SnpHandle;
2189 EFI_HANDLE MnpChildHandle;
2190
2191 ASSERT (MacAddress != NULL);
2192 ASSERT (AddressSize != NULL);
2193
2194 //
2195 // Try to get SNP handle
2196 //
2197 Snp = NULL;
2198 SnpHandle = NetLibGetSnpHandle (ServiceHandle, &Snp);
2199 if (SnpHandle != NULL) {
2200 //
2201 // SNP found, use it directly
2202 //
2203 SnpMode = Snp->Mode;
2204 } else {
2205 //
2206 // Failed to get SNP handle, try to get MAC address from MNP
2207 //
2208 MnpChildHandle = NULL;
2209 Status = gBS->HandleProtocol (
2210 ServiceHandle,
2211 &gEfiManagedNetworkServiceBindingProtocolGuid,
2212 (VOID **) &MnpSb
2213 );
2214 if (EFI_ERROR (Status)) {
2215 return Status;
2216 }
2217
2218 //
2219 // Create a MNP child
2220 //
2221 Status = MnpSb->CreateChild (MnpSb, &MnpChildHandle);
2222 if (EFI_ERROR (Status)) {
2223 return Status;
2224 }
2225
2226 //
2227 // Open MNP protocol
2228 //
2229 Status = gBS->HandleProtocol (
2230 MnpChildHandle,
2231 &gEfiManagedNetworkProtocolGuid,
2232 (VOID **) &Mnp
2233 );
2234 if (EFI_ERROR (Status)) {
2235 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2236 return Status;
2237 }
2238
2239 //
2240 // Try to get SNP mode from MNP
2241 //
2242 Status = Mnp->GetModeData (Mnp, NULL, &SnpModeData);
2243 if (EFI_ERROR (Status) && (Status != EFI_NOT_STARTED)) {
2244 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2245 return Status;
2246 }
2247 SnpMode = &SnpModeData;
2248
2249 //
2250 // Destroy the MNP child
2251 //
2252 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2253 }
2254
2255 *AddressSize = SnpMode->HwAddressSize;
2256 CopyMem (MacAddress->Addr, SnpMode->CurrentAddress.Addr, SnpMode->HwAddressSize);
2257
2258 return EFI_SUCCESS;
2259 }
2260
2261 /**
2262 Convert MAC address of the NIC associated with specified Service Binding Handle
2263 to a unicode string. Callers are responsible for freeing the string storage.
2264
2265 If MacString is NULL, then ASSERT().
2266
2267 Locate simple network protocol associated with the Service Binding Handle and
2268 get the mac address from SNP. Then convert the mac address into a unicode
2269 string. It takes 2 unicode characters to represent a 1 byte binary buffer.
2270 Plus one unicode character for the null-terminator.
2271
2272 @param[in] ServiceHandle The handle where network service binding protocol is
2273 installed on.
2274 @param[in] ImageHandle The image handle used to act as the agent handle to
2275 get the simple network protocol. This parameter is
2276 optional and may be NULL.
2277 @param[out] MacString The pointer to store the address of the string
2278 representation of the mac address.
2279
2280 @retval EFI_SUCCESS Convert the mac address a unicode string successfully.
2281 @retval EFI_OUT_OF_RESOURCES There are not enough memory resource.
2282 @retval Others Failed to open the simple network protocol.
2283
2284 **/
2285 EFI_STATUS
2286 EFIAPI
2287 NetLibGetMacString (
2288 IN EFI_HANDLE ServiceHandle,
2289 IN EFI_HANDLE ImageHandle, OPTIONAL
2290 OUT CHAR16 **MacString
2291 )
2292 {
2293 EFI_STATUS Status;
2294 EFI_MAC_ADDRESS MacAddress;
2295 UINT8 *HwAddress;
2296 UINTN HwAddressSize;
2297 UINT16 VlanId;
2298 CHAR16 *String;
2299 UINTN Index;
2300 UINTN BufferSize;
2301
2302 ASSERT (MacString != NULL);
2303
2304 //
2305 // Get MAC address of the network device
2306 //
2307 Status = NetLibGetMacAddress (ServiceHandle, &MacAddress, &HwAddressSize);
2308 if (EFI_ERROR (Status)) {
2309 return Status;
2310 }
2311
2312 //
2313 // It takes 2 unicode characters to represent a 1 byte binary buffer.
2314 // If VLAN is configured, it will need extra 5 characters like "\0005".
2315 // Plus one unicode character for the null-terminator.
2316 //
2317 BufferSize = (2 * HwAddressSize + 5 + 1) * sizeof (CHAR16);
2318 String = AllocateZeroPool (BufferSize);
2319 if (String == NULL) {
2320 return EFI_OUT_OF_RESOURCES;
2321 }
2322 *MacString = String;
2323
2324 //
2325 // Convert the MAC address into a unicode string.
2326 //
2327 HwAddress = &MacAddress.Addr[0];
2328 for (Index = 0; Index < HwAddressSize; Index++) {
2329 UnicodeValueToStringS (
2330 String,
2331 BufferSize - ((UINTN)String - (UINTN)*MacString),
2332 PREFIX_ZERO | RADIX_HEX,
2333 *(HwAddress++),
2334 2
2335 );
2336 String += StrnLenS (String, (BufferSize - ((UINTN)String - (UINTN)*MacString)) / sizeof (CHAR16));
2337 }
2338
2339 //
2340 // Append VLAN ID if any
2341 //
2342 VlanId = NetLibGetVlanId (ServiceHandle);
2343 if (VlanId != 0) {
2344 *String++ = L'\\';
2345 UnicodeValueToStringS (
2346 String,
2347 BufferSize - ((UINTN)String - (UINTN)*MacString),
2348 PREFIX_ZERO | RADIX_HEX,
2349 VlanId,
2350 4
2351 );
2352 String += StrnLenS (String, (BufferSize - ((UINTN)String - (UINTN)*MacString)) / sizeof (CHAR16));
2353 }
2354
2355 //
2356 // Null terminate the Unicode string
2357 //
2358 *String = L'\0';
2359
2360 return EFI_SUCCESS;
2361 }
2362
2363 /**
2364 Detect media status for specified network device.
2365
2366 If MediaPresent is NULL, then ASSERT().
2367
2368 The underlying UNDI driver may or may not support reporting media status from
2369 GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine
2370 will try to invoke Snp->GetStatus() to get the media status: if media already
2371 present, it return directly; if media not present, it will stop SNP and then
2372 restart SNP to get the latest media status, this give chance to get the correct
2373 media status for old UNDI driver which doesn't support reporting media status
2374 from GET_STATUS command.
2375 Note: there will be two limitations for current algorithm:
2376 1) for UNDI with this capability, in case of cable is not attached, there will
2377 be an redundant Stop/Start() process;
2378 2) for UNDI without this capability, in case that network cable is attached when
2379 Snp->Initialize() is invoked while network cable is unattached later,
2380 NetLibDetectMedia() will report MediaPresent as TRUE, causing upper layer
2381 apps to wait for timeout time.
2382
2383 @param[in] ServiceHandle The handle where network service binding protocols are
2384 installed on.
2385 @param[out] MediaPresent The pointer to store the media status.
2386
2387 @retval EFI_SUCCESS Media detection success.
2388 @retval EFI_INVALID_PARAMETER ServiceHandle is not valid network device handle.
2389 @retval EFI_UNSUPPORTED Network device does not support media detection.
2390 @retval EFI_DEVICE_ERROR SNP is in unknown state.
2391
2392 **/
2393 EFI_STATUS
2394 EFIAPI
2395 NetLibDetectMedia (
2396 IN EFI_HANDLE ServiceHandle,
2397 OUT BOOLEAN *MediaPresent
2398 )
2399 {
2400 EFI_STATUS Status;
2401 EFI_HANDLE SnpHandle;
2402 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
2403 UINT32 InterruptStatus;
2404 UINT32 OldState;
2405 EFI_MAC_ADDRESS *MCastFilter;
2406 UINT32 MCastFilterCount;
2407 UINT32 EnableFilterBits;
2408 UINT32 DisableFilterBits;
2409 BOOLEAN ResetMCastFilters;
2410
2411 ASSERT (MediaPresent != NULL);
2412
2413 //
2414 // Get SNP handle
2415 //
2416 Snp = NULL;
2417 SnpHandle = NetLibGetSnpHandle (ServiceHandle, &Snp);
2418 if (SnpHandle == NULL) {
2419 return EFI_INVALID_PARAMETER;
2420 }
2421
2422 //
2423 // Check whether SNP support media detection
2424 //
2425 if (!Snp->Mode->MediaPresentSupported) {
2426 return EFI_UNSUPPORTED;
2427 }
2428
2429 //
2430 // Invoke Snp->GetStatus() to refresh MediaPresent field in SNP mode data
2431 //
2432 Status = Snp->GetStatus (Snp, &InterruptStatus, NULL);
2433 if (EFI_ERROR (Status)) {
2434 return Status;
2435 }
2436
2437 if (Snp->Mode->MediaPresent) {
2438 //
2439 // Media is present, return directly
2440 //
2441 *MediaPresent = TRUE;
2442 return EFI_SUCCESS;
2443 }
2444
2445 //
2446 // Till now, GetStatus() report no media; while, in case UNDI not support
2447 // reporting media status from GetStatus(), this media status may be incorrect.
2448 // So, we will stop SNP and then restart it to get the correct media status.
2449 //
2450 OldState = Snp->Mode->State;
2451 if (OldState >= EfiSimpleNetworkMaxState) {
2452 return EFI_DEVICE_ERROR;
2453 }
2454
2455 MCastFilter = NULL;
2456
2457 if (OldState == EfiSimpleNetworkInitialized) {
2458 //
2459 // SNP is already in use, need Shutdown/Stop and then Start/Initialize
2460 //
2461
2462 //
2463 // Backup current SNP receive filter settings
2464 //
2465 EnableFilterBits = Snp->Mode->ReceiveFilterSetting;
2466 DisableFilterBits = Snp->Mode->ReceiveFilterMask ^ EnableFilterBits;
2467
2468 ResetMCastFilters = TRUE;
2469 MCastFilterCount = Snp->Mode->MCastFilterCount;
2470 if (MCastFilterCount != 0) {
2471 MCastFilter = AllocateCopyPool (
2472 MCastFilterCount * sizeof (EFI_MAC_ADDRESS),
2473 Snp->Mode->MCastFilter
2474 );
2475 ASSERT (MCastFilter != NULL);
2476 if (MCastFilter == NULL) {
2477 Status = EFI_OUT_OF_RESOURCES;
2478 goto Exit;
2479 }
2480
2481 ResetMCastFilters = FALSE;
2482 }
2483
2484 //
2485 // Shutdown/Stop the simple network
2486 //
2487 Status = Snp->Shutdown (Snp);
2488 if (!EFI_ERROR (Status)) {
2489 Status = Snp->Stop (Snp);
2490 }
2491 if (EFI_ERROR (Status)) {
2492 goto Exit;
2493 }
2494
2495 //
2496 // Start/Initialize the simple network
2497 //
2498 Status = Snp->Start (Snp);
2499 if (!EFI_ERROR (Status)) {
2500 Status = Snp->Initialize (Snp, 0, 0);
2501 }
2502 if (EFI_ERROR (Status)) {
2503 goto Exit;
2504 }
2505
2506 //
2507 // Here we get the correct media status
2508 //
2509 *MediaPresent = Snp->Mode->MediaPresent;
2510
2511 //
2512 // Restore SNP receive filter settings
2513 //
2514 Status = Snp->ReceiveFilters (
2515 Snp,
2516 EnableFilterBits,
2517 DisableFilterBits,
2518 ResetMCastFilters,
2519 MCastFilterCount,
2520 MCastFilter
2521 );
2522
2523 if (MCastFilter != NULL) {
2524 FreePool (MCastFilter);
2525 }
2526
2527 return Status;
2528 }
2529
2530 //
2531 // SNP is not in use, it's in state of EfiSimpleNetworkStopped or EfiSimpleNetworkStarted
2532 //
2533 if (OldState == EfiSimpleNetworkStopped) {
2534 //
2535 // SNP not start yet, start it
2536 //
2537 Status = Snp->Start (Snp);
2538 if (EFI_ERROR (Status)) {
2539 goto Exit;
2540 }
2541 }
2542
2543 //
2544 // Initialize the simple network
2545 //
2546 Status = Snp->Initialize (Snp, 0, 0);
2547 if (EFI_ERROR (Status)) {
2548 Status = EFI_DEVICE_ERROR;
2549 goto Exit;
2550 }
2551
2552 //
2553 // Here we get the correct media status
2554 //
2555 *MediaPresent = Snp->Mode->MediaPresent;
2556
2557 //
2558 // Shut down the simple network
2559 //
2560 Snp->Shutdown (Snp);
2561
2562 Exit:
2563 if (OldState == EfiSimpleNetworkStopped) {
2564 //
2565 // Original SNP sate is Stopped, restore to original state
2566 //
2567 Snp->Stop (Snp);
2568 }
2569
2570 if (MCastFilter != NULL) {
2571 FreePool (MCastFilter);
2572 }
2573
2574 return Status;
2575 }
2576
2577 /**
2578
2579 Detect media state for a network device. This routine will wait for a period of time at
2580 a specified checking interval when a certain network is under connecting until connection
2581 process finishs or timeout. If Aip protocol is supported by low layer drivers, three kinds
2582 of media states can be detected: EFI_SUCCESS, EFI_NOT_READY and EFI_NO_MEDIA, represents
2583 connected state, connecting state and no media state respectively. When function detects
2584 the current state is EFI_NOT_READY, it will loop to wait for next time's check until state
2585 turns to be EFI_SUCCESS or EFI_NO_MEDIA. If Aip protocol is not supported, function will
2586 call NetLibDetectMedia() and return state directly.
2587
2588 @param[in] ServiceHandle The handle where network service binding protocols are
2589 installed on.
2590 @param[in] Timeout The maximum number of 100ns units to wait when network
2591 is connecting. Zero value means detect once and return
2592 immediately.
2593 @param[out] MediaState The pointer to the detected media state.
2594
2595 @retval EFI_SUCCESS Media detection success.
2596 @retval EFI_INVALID_PARAMETER ServiceHandle is not a valid network device handle or
2597 MediaState pointer is NULL.
2598 @retval EFI_DEVICE_ERROR A device error occurred.
2599 @retval EFI_TIMEOUT Network is connecting but timeout.
2600
2601 **/
2602 EFI_STATUS
2603 EFIAPI
2604 NetLibDetectMediaWaitTimeout (
2605 IN EFI_HANDLE ServiceHandle,
2606 IN UINT64 Timeout,
2607 OUT EFI_STATUS *MediaState
2608 )
2609 {
2610 EFI_STATUS Status;
2611 EFI_HANDLE SnpHandle;
2612 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
2613 EFI_ADAPTER_INFORMATION_PROTOCOL *Aip;
2614 EFI_ADAPTER_INFO_MEDIA_STATE *MediaInfo;
2615 BOOLEAN MediaPresent;
2616 UINTN DataSize;
2617 EFI_STATUS TimerStatus;
2618 EFI_EVENT Timer;
2619 UINT64 TimeRemained;
2620
2621 if (MediaState == NULL) {
2622 return EFI_INVALID_PARAMETER;
2623 }
2624 *MediaState = EFI_SUCCESS;
2625 MediaInfo = NULL;
2626
2627 //
2628 // Get SNP handle
2629 //
2630 Snp = NULL;
2631 SnpHandle = NetLibGetSnpHandle (ServiceHandle, &Snp);
2632 if (SnpHandle == NULL) {
2633 return EFI_INVALID_PARAMETER;
2634 }
2635
2636 Status = gBS->HandleProtocol (
2637 SnpHandle,
2638 &gEfiAdapterInformationProtocolGuid,
2639 (VOID *) &Aip
2640 );
2641 if (EFI_ERROR (Status)) {
2642
2643 MediaPresent = TRUE;
2644 Status = NetLibDetectMedia (ServiceHandle, &MediaPresent);
2645 if (!EFI_ERROR (Status)) {
2646 if (MediaPresent) {
2647 *MediaState = EFI_SUCCESS;
2648 } else {
2649 *MediaState = EFI_NO_MEDIA;
2650 }
2651 }
2652
2653 //
2654 // NetLibDetectMedia doesn't support EFI_NOT_READY status, return now!
2655 //
2656 return Status;
2657 }
2658
2659 Status = Aip->GetInformation (
2660 Aip,
2661 &gEfiAdapterInfoMediaStateGuid,
2662 (VOID **) &MediaInfo,
2663 &DataSize
2664 );
2665 if (!EFI_ERROR (Status)) {
2666
2667 *MediaState = MediaInfo->MediaState;
2668 FreePool (MediaInfo);
2669 if (*MediaState != EFI_NOT_READY || Timeout < MEDIA_STATE_DETECT_TIME_INTERVAL) {
2670
2671 return EFI_SUCCESS;
2672 }
2673 } else {
2674
2675 if (MediaInfo != NULL) {
2676 FreePool (MediaInfo);
2677 }
2678
2679 if (Status == EFI_UNSUPPORTED) {
2680
2681 //
2682 // If gEfiAdapterInfoMediaStateGuid is not supported, call NetLibDetectMedia to get media state!
2683 //
2684 MediaPresent = TRUE;
2685 Status = NetLibDetectMedia (ServiceHandle, &MediaPresent);
2686 if (!EFI_ERROR (Status)) {
2687 if (MediaPresent) {
2688 *MediaState = EFI_SUCCESS;
2689 } else {
2690 *MediaState = EFI_NO_MEDIA;
2691 }
2692 }
2693 return Status;
2694 }
2695
2696 return Status;
2697 }
2698
2699 //
2700 // Loop to check media state
2701 //
2702
2703 Timer = NULL;
2704 TimeRemained = Timeout;
2705 Status = gBS->CreateEvent (EVT_TIMER, TPL_CALLBACK, NULL, NULL, &Timer);
2706 if (EFI_ERROR (Status)) {
2707 return EFI_DEVICE_ERROR;
2708 }
2709
2710 do {
2711 Status = gBS->SetTimer (
2712 Timer,
2713 TimerRelative,
2714 MEDIA_STATE_DETECT_TIME_INTERVAL
2715 );
2716 if (EFI_ERROR (Status)) {
2717 gBS->CloseEvent(Timer);
2718 return EFI_DEVICE_ERROR;
2719 }
2720
2721 do {
2722 TimerStatus = gBS->CheckEvent (Timer);
2723 if (!EFI_ERROR (TimerStatus)) {
2724
2725 TimeRemained -= MEDIA_STATE_DETECT_TIME_INTERVAL;
2726 Status = Aip->GetInformation (
2727 Aip,
2728 &gEfiAdapterInfoMediaStateGuid,
2729 (VOID **) &MediaInfo,
2730 &DataSize
2731 );
2732 if (!EFI_ERROR (Status)) {
2733
2734 *MediaState = MediaInfo->MediaState;
2735 FreePool (MediaInfo);
2736 } else {
2737
2738 if (MediaInfo != NULL) {
2739 FreePool (MediaInfo);
2740 }
2741 gBS->CloseEvent(Timer);
2742 return Status;
2743 }
2744 }
2745 } while (TimerStatus == EFI_NOT_READY);
2746 } while (*MediaState == EFI_NOT_READY && TimeRemained >= MEDIA_STATE_DETECT_TIME_INTERVAL);
2747
2748 gBS->CloseEvent(Timer);
2749 if (*MediaState == EFI_NOT_READY && TimeRemained < MEDIA_STATE_DETECT_TIME_INTERVAL) {
2750 return EFI_TIMEOUT;
2751 } else {
2752 return EFI_SUCCESS;
2753 }
2754 }
2755
2756 /**
2757 Check the default address used by the IPv4 driver is static or dynamic (acquired
2758 from DHCP).
2759
2760 If the controller handle does not have the EFI_IP4_CONFIG2_PROTOCOL installed, the
2761 default address is static. If failed to get the policy from Ip4 Config2 Protocol,
2762 the default address is static. Otherwise, get the result from Ip4 Config2 Protocol.
2763
2764 @param[in] Controller The controller handle which has the EFI_IP4_CONFIG2_PROTOCOL
2765 relative with the default address to judge.
2766
2767 @retval TRUE If the default address is static.
2768 @retval FALSE If the default address is acquired from DHCP.
2769
2770 **/
2771 BOOLEAN
2772 NetLibDefaultAddressIsStatic (
2773 IN EFI_HANDLE Controller
2774 )
2775 {
2776 EFI_STATUS Status;
2777 EFI_IP4_CONFIG2_PROTOCOL *Ip4Config2;
2778 UINTN DataSize;
2779 EFI_IP4_CONFIG2_POLICY Policy;
2780 BOOLEAN IsStatic;
2781
2782 Ip4Config2 = NULL;
2783
2784 DataSize = sizeof (EFI_IP4_CONFIG2_POLICY);
2785
2786 IsStatic = TRUE;
2787
2788 //
2789 // Get Ip4Config2 policy.
2790 //
2791 Status = gBS->HandleProtocol (Controller, &gEfiIp4Config2ProtocolGuid, (VOID **) &Ip4Config2);
2792 if (EFI_ERROR (Status)) {
2793 goto ON_EXIT;
2794 }
2795
2796 Status = Ip4Config2->GetData (Ip4Config2, Ip4Config2DataTypePolicy, &DataSize, &Policy);
2797 if (EFI_ERROR (Status)) {
2798 goto ON_EXIT;
2799 }
2800
2801 IsStatic = (BOOLEAN) (Policy == Ip4Config2PolicyStatic);
2802
2803 ON_EXIT:
2804
2805 return IsStatic;
2806 }
2807
2808 /**
2809 Create an IPv4 device path node.
2810
2811 If Node is NULL, then ASSERT().
2812
2813 The header type of IPv4 device path node is MESSAGING_DEVICE_PATH.
2814 The header subtype of IPv4 device path node is MSG_IPv4_DP.
2815 Get other info from parameters to make up the whole IPv4 device path node.
2816
2817 @param[in, out] Node Pointer to the IPv4 device path node.
2818 @param[in] Controller The controller handle.
2819 @param[in] LocalIp The local IPv4 address.
2820 @param[in] LocalPort The local port.
2821 @param[in] RemoteIp The remote IPv4 address.
2822 @param[in] RemotePort The remote port.
2823 @param[in] Protocol The protocol type in the IP header.
2824 @param[in] UseDefaultAddress Whether this instance is using default address or not.
2825
2826 **/
2827 VOID
2828 EFIAPI
2829 NetLibCreateIPv4DPathNode (
2830 IN OUT IPv4_DEVICE_PATH *Node,
2831 IN EFI_HANDLE Controller,
2832 IN IP4_ADDR LocalIp,
2833 IN UINT16 LocalPort,
2834 IN IP4_ADDR RemoteIp,
2835 IN UINT16 RemotePort,
2836 IN UINT16 Protocol,
2837 IN BOOLEAN UseDefaultAddress
2838 )
2839 {
2840 ASSERT (Node != NULL);
2841
2842 Node->Header.Type = MESSAGING_DEVICE_PATH;
2843 Node->Header.SubType = MSG_IPv4_DP;
2844 SetDevicePathNodeLength (&Node->Header, sizeof (IPv4_DEVICE_PATH));
2845
2846 CopyMem (&Node->LocalIpAddress, &LocalIp, sizeof (EFI_IPv4_ADDRESS));
2847 CopyMem (&Node->RemoteIpAddress, &RemoteIp, sizeof (EFI_IPv4_ADDRESS));
2848
2849 Node->LocalPort = LocalPort;
2850 Node->RemotePort = RemotePort;
2851
2852 Node->Protocol = Protocol;
2853
2854 if (!UseDefaultAddress) {
2855 Node->StaticIpAddress = TRUE;
2856 } else {
2857 Node->StaticIpAddress = NetLibDefaultAddressIsStatic (Controller);
2858 }
2859
2860 //
2861 // Set the Gateway IP address to default value 0:0:0:0.
2862 // Set the Subnet mask to default value 255:255:255:0.
2863 //
2864 ZeroMem (&Node->GatewayIpAddress, sizeof (EFI_IPv4_ADDRESS));
2865 SetMem (&Node->SubnetMask, sizeof (EFI_IPv4_ADDRESS), 0xff);
2866 Node->SubnetMask.Addr[3] = 0;
2867 }
2868
2869 /**
2870 Create an IPv6 device path node.
2871
2872 If Node is NULL, then ASSERT().
2873 If LocalIp is NULL, then ASSERT().
2874 If RemoteIp is NULL, then ASSERT().
2875
2876 The header type of IPv6 device path node is MESSAGING_DEVICE_PATH.
2877 The header subtype of IPv6 device path node is MSG_IPv6_DP.
2878 Get other info from parameters to make up the whole IPv6 device path node.
2879
2880 @param[in, out] Node Pointer to the IPv6 device path node.
2881 @param[in] Controller The controller handle.
2882 @param[in] LocalIp The local IPv6 address.
2883 @param[in] LocalPort The local port.
2884 @param[in] RemoteIp The remote IPv6 address.
2885 @param[in] RemotePort The remote port.
2886 @param[in] Protocol The protocol type in the IP header.
2887
2888 **/
2889 VOID
2890 EFIAPI
2891 NetLibCreateIPv6DPathNode (
2892 IN OUT IPv6_DEVICE_PATH *Node,
2893 IN EFI_HANDLE Controller,
2894 IN EFI_IPv6_ADDRESS *LocalIp,
2895 IN UINT16 LocalPort,
2896 IN EFI_IPv6_ADDRESS *RemoteIp,
2897 IN UINT16 RemotePort,
2898 IN UINT16 Protocol
2899 )
2900 {
2901 ASSERT (Node != NULL && LocalIp != NULL && RemoteIp != NULL);
2902
2903 Node->Header.Type = MESSAGING_DEVICE_PATH;
2904 Node->Header.SubType = MSG_IPv6_DP;
2905 SetDevicePathNodeLength (&Node->Header, sizeof (IPv6_DEVICE_PATH));
2906
2907 CopyMem (&Node->LocalIpAddress, LocalIp, sizeof (EFI_IPv6_ADDRESS));
2908 CopyMem (&Node->RemoteIpAddress, RemoteIp, sizeof (EFI_IPv6_ADDRESS));
2909
2910 Node->LocalPort = LocalPort;
2911 Node->RemotePort = RemotePort;
2912
2913 Node->Protocol = Protocol;
2914
2915 //
2916 // Set default value to IPAddressOrigin, PrefixLength.
2917 // Set the Gateway IP address to unspecified address.
2918 //
2919 Node->IpAddressOrigin = 0;
2920 Node->PrefixLength = IP6_PREFIX_LENGTH;
2921 ZeroMem (&Node->GatewayIpAddress, sizeof (EFI_IPv6_ADDRESS));
2922 }
2923
2924 /**
2925 Find the UNDI/SNP handle from controller and protocol GUID.
2926
2927 If ProtocolGuid is NULL, then ASSERT().
2928
2929 For example, IP will open a MNP child to transmit/receive
2930 packets, when MNP is stopped, IP should also be stopped. IP
2931 needs to find its own private data which is related the IP's
2932 service binding instance that is install on UNDI/SNP handle.
2933 Now, the controller is either a MNP or ARP child handle. But
2934 IP opens these handle BY_DRIVER, use that info, we can get the
2935 UNDI/SNP handle.
2936
2937 @param[in] Controller Then protocol handle to check.
2938 @param[in] ProtocolGuid The protocol that is related with the handle.
2939
2940 @return The UNDI/SNP handle or NULL for errors.
2941
2942 **/
2943 EFI_HANDLE
2944 EFIAPI
2945 NetLibGetNicHandle (
2946 IN EFI_HANDLE Controller,
2947 IN EFI_GUID *ProtocolGuid
2948 )
2949 {
2950 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenBuffer;
2951 EFI_HANDLE Handle;
2952 EFI_STATUS Status;
2953 UINTN OpenCount;
2954 UINTN Index;
2955
2956 ASSERT (ProtocolGuid != NULL);
2957
2958 Status = gBS->OpenProtocolInformation (
2959 Controller,
2960 ProtocolGuid,
2961 &OpenBuffer,
2962 &OpenCount
2963 );
2964
2965 if (EFI_ERROR (Status)) {
2966 return NULL;
2967 }
2968
2969 Handle = NULL;
2970
2971 for (Index = 0; Index < OpenCount; Index++) {
2972 if ((OpenBuffer[Index].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) {
2973 Handle = OpenBuffer[Index].ControllerHandle;
2974 break;
2975 }
2976 }
2977
2978 gBS->FreePool (OpenBuffer);
2979 return Handle;
2980 }
2981
2982 /**
2983 Convert one Null-terminated ASCII string (decimal dotted) to EFI_IPv4_ADDRESS.
2984
2985 @param[in] String The pointer to the Ascii string.
2986 @param[out] Ip4Address The pointer to the converted IPv4 address.
2987
2988 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2989 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2990
2991 **/
2992 EFI_STATUS
2993 EFIAPI
2994 NetLibAsciiStrToIp4 (
2995 IN CONST CHAR8 *String,
2996 OUT EFI_IPv4_ADDRESS *Ip4Address
2997 )
2998 {
2999 RETURN_STATUS Status;
3000 CHAR8 *EndPointer;
3001
3002 Status = AsciiStrToIpv4Address (String, &EndPointer, Ip4Address, NULL);
3003 if (RETURN_ERROR (Status) || (*EndPointer != '\0')) {
3004 return EFI_INVALID_PARAMETER;
3005 } else {
3006 return EFI_SUCCESS;
3007 }
3008 }
3009
3010
3011 /**
3012 Convert one Null-terminated ASCII string to EFI_IPv6_ADDRESS. The format of the
3013 string is defined in RFC 4291 - Text Representation of Addresses.
3014
3015 @param[in] String The pointer to the Ascii string.
3016 @param[out] Ip6Address The pointer to the converted IPv6 address.
3017
3018 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3019 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3020
3021 **/
3022 EFI_STATUS
3023 EFIAPI
3024 NetLibAsciiStrToIp6 (
3025 IN CONST CHAR8 *String,
3026 OUT EFI_IPv6_ADDRESS *Ip6Address
3027 )
3028 {
3029 RETURN_STATUS Status;
3030 CHAR8 *EndPointer;
3031
3032 Status = AsciiStrToIpv6Address (String, &EndPointer, Ip6Address, NULL);
3033 if (RETURN_ERROR (Status) || (*EndPointer != '\0')) {
3034 return EFI_INVALID_PARAMETER;
3035 } else {
3036 return EFI_SUCCESS;
3037 }
3038 }
3039
3040
3041 /**
3042 Convert one Null-terminated Unicode string (decimal dotted) to EFI_IPv4_ADDRESS.
3043
3044 @param[in] String The pointer to the Ascii string.
3045 @param[out] Ip4Address The pointer to the converted IPv4 address.
3046
3047 @retval EFI_SUCCESS Convert to IPv4 address successfully.
3048 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
3049
3050 **/
3051 EFI_STATUS
3052 EFIAPI
3053 NetLibStrToIp4 (
3054 IN CONST CHAR16 *String,
3055 OUT EFI_IPv4_ADDRESS *Ip4Address
3056 )
3057 {
3058 RETURN_STATUS Status;
3059 CHAR16 *EndPointer;
3060
3061 Status = StrToIpv4Address (String, &EndPointer, Ip4Address, NULL);
3062 if (RETURN_ERROR (Status) || (*EndPointer != L'\0')) {
3063 return EFI_INVALID_PARAMETER;
3064 } else {
3065 return EFI_SUCCESS;
3066 }
3067 }
3068
3069
3070 /**
3071 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS. The format of
3072 the string is defined in RFC 4291 - Text Representation of Addresses.
3073
3074 @param[in] String The pointer to the Ascii string.
3075 @param[out] Ip6Address The pointer to the converted IPv6 address.
3076
3077 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3078 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3079
3080 **/
3081 EFI_STATUS
3082 EFIAPI
3083 NetLibStrToIp6 (
3084 IN CONST CHAR16 *String,
3085 OUT EFI_IPv6_ADDRESS *Ip6Address
3086 )
3087 {
3088 RETURN_STATUS Status;
3089 CHAR16 *EndPointer;
3090
3091 Status = StrToIpv6Address (String, &EndPointer, Ip6Address, NULL);
3092 if (RETURN_ERROR (Status) || (*EndPointer != L'\0')) {
3093 return EFI_INVALID_PARAMETER;
3094 } else {
3095 return EFI_SUCCESS;
3096 }
3097 }
3098
3099 /**
3100 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS and prefix length.
3101 The format of the string is defined in RFC 4291 - Text Representation of Addresses
3102 Prefixes: ipv6-address/prefix-length.
3103
3104 @param[in] String The pointer to the Ascii string.
3105 @param[out] Ip6Address The pointer to the converted IPv6 address.
3106 @param[out] PrefixLength The pointer to the converted prefix length.
3107
3108 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3109 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3110
3111 **/
3112 EFI_STATUS
3113 EFIAPI
3114 NetLibStrToIp6andPrefix (
3115 IN CONST CHAR16 *String,
3116 OUT EFI_IPv6_ADDRESS *Ip6Address,
3117 OUT UINT8 *PrefixLength
3118 )
3119 {
3120 RETURN_STATUS Status;
3121 CHAR16 *EndPointer;
3122
3123 Status = StrToIpv6Address (String, &EndPointer, Ip6Address, PrefixLength);
3124 if (RETURN_ERROR (Status) || (*EndPointer != L'\0')) {
3125 return EFI_INVALID_PARAMETER;
3126 } else {
3127 return EFI_SUCCESS;
3128 }
3129 }
3130
3131 /**
3132
3133 Convert one EFI_IPv6_ADDRESS to Null-terminated Unicode string.
3134 The text representation of address is defined in RFC 4291.
3135
3136 @param[in] Ip6Address The pointer to the IPv6 address.
3137 @param[out] String The buffer to return the converted string.
3138 @param[in] StringSize The length in bytes of the input String.
3139
3140 @retval EFI_SUCCESS Convert to string successfully.
3141 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
3142 @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small for the result. BufferSize has been
3143 updated with the size needed to complete the request.
3144 **/
3145 EFI_STATUS
3146 EFIAPI
3147 NetLibIp6ToStr (
3148 IN EFI_IPv6_ADDRESS *Ip6Address,
3149 OUT CHAR16 *String,
3150 IN UINTN StringSize
3151 )
3152 {
3153 UINT16 Ip6Addr[8];
3154 UINTN Index;
3155 UINTN LongestZerosStart;
3156 UINTN LongestZerosLength;
3157 UINTN CurrentZerosStart;
3158 UINTN CurrentZerosLength;
3159 CHAR16 Buffer[sizeof"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"];
3160 CHAR16 *Ptr;
3161
3162 if (Ip6Address == NULL || String == NULL || StringSize == 0) {
3163 return EFI_INVALID_PARAMETER;
3164 }
3165
3166 //
3167 // Convert the UINT8 array to an UINT16 array for easy handling.
3168 //
3169 ZeroMem (Ip6Addr, sizeof (Ip6Addr));
3170 for (Index = 0; Index < 16; Index++) {
3171 Ip6Addr[Index / 2] |= (Ip6Address->Addr[Index] << ((1 - (Index % 2)) << 3));
3172 }
3173
3174 //
3175 // Find the longest zeros and mark it.
3176 //
3177 CurrentZerosStart = DEFAULT_ZERO_START;
3178 CurrentZerosLength = 0;
3179 LongestZerosStart = DEFAULT_ZERO_START;
3180 LongestZerosLength = 0;
3181 for (Index = 0; Index < 8; Index++) {
3182 if (Ip6Addr[Index] == 0) {
3183 if (CurrentZerosStart == DEFAULT_ZERO_START) {
3184 CurrentZerosStart = Index;
3185 CurrentZerosLength = 1;
3186 } else {
3187 CurrentZerosLength++;
3188 }
3189 } else {
3190 if (CurrentZerosStart != DEFAULT_ZERO_START) {
3191 if (CurrentZerosLength > 2 && (LongestZerosStart == (DEFAULT_ZERO_START) || CurrentZerosLength > LongestZerosLength)) {
3192 LongestZerosStart = CurrentZerosStart;
3193 LongestZerosLength = CurrentZerosLength;
3194 }
3195 CurrentZerosStart = DEFAULT_ZERO_START;
3196 CurrentZerosLength = 0;
3197 }
3198 }
3199 }
3200
3201 if (CurrentZerosStart != DEFAULT_ZERO_START && CurrentZerosLength > 2) {
3202 if (LongestZerosStart == DEFAULT_ZERO_START || LongestZerosLength < CurrentZerosLength) {
3203 LongestZerosStart = CurrentZerosStart;
3204 LongestZerosLength = CurrentZerosLength;
3205 }
3206 }
3207
3208 Ptr = Buffer;
3209 for (Index = 0; Index < 8; Index++) {
3210 if (LongestZerosStart != DEFAULT_ZERO_START && Index >= LongestZerosStart && Index < LongestZerosStart + LongestZerosLength) {
3211 if (Index == LongestZerosStart) {
3212 *Ptr++ = L':';
3213 }
3214 continue;
3215 }
3216 if (Index != 0) {
3217 *Ptr++ = L':';
3218 }
3219 Ptr += UnicodeSPrint(Ptr, 10, L"%x", Ip6Addr[Index]);
3220 }
3221
3222 if (LongestZerosStart != DEFAULT_ZERO_START && LongestZerosStart + LongestZerosLength == 8) {
3223 *Ptr++ = L':';
3224 }
3225 *Ptr = L'\0';
3226
3227 if ((UINTN)Ptr - (UINTN)Buffer > StringSize) {
3228 return EFI_BUFFER_TOO_SMALL;
3229 }
3230
3231 StrCpyS (String, StringSize / sizeof (CHAR16), Buffer);
3232
3233 return EFI_SUCCESS;
3234 }
3235
3236 /**
3237 This function obtains the system guid from the smbios table.
3238
3239 If SystemGuid is NULL, then ASSERT().
3240
3241 @param[out] SystemGuid The pointer of the returned system guid.
3242
3243 @retval EFI_SUCCESS Successfully obtained the system guid.
3244 @retval EFI_NOT_FOUND Did not find the SMBIOS table.
3245
3246 **/
3247 EFI_STATUS
3248 EFIAPI
3249 NetLibGetSystemGuid (
3250 OUT EFI_GUID *SystemGuid
3251 )
3252 {
3253 EFI_STATUS Status;
3254 SMBIOS_TABLE_ENTRY_POINT *SmbiosTable;
3255 SMBIOS_TABLE_3_0_ENTRY_POINT *Smbios30Table;
3256 SMBIOS_STRUCTURE_POINTER Smbios;
3257 SMBIOS_STRUCTURE_POINTER SmbiosEnd;
3258 CHAR8 *String;
3259
3260 ASSERT (SystemGuid != NULL);
3261
3262 SmbiosTable = NULL;
3263 Status = EfiGetSystemConfigurationTable (&gEfiSmbios3TableGuid, (VOID **) &Smbios30Table);
3264 if (!(EFI_ERROR (Status) || Smbios30Table == NULL)) {
3265 Smbios.Hdr = (SMBIOS_STRUCTURE *) (UINTN) Smbios30Table->TableAddress;
3266 SmbiosEnd.Raw = (UINT8 *) (UINTN) (Smbios30Table->TableAddress + Smbios30Table->TableMaximumSize);
3267 } else {
3268 Status = EfiGetSystemConfigurationTable (&gEfiSmbiosTableGuid, (VOID **) &SmbiosTable);
3269 if (EFI_ERROR (Status) || SmbiosTable == NULL) {
3270 return EFI_NOT_FOUND;
3271 }
3272 Smbios.Hdr = (SMBIOS_STRUCTURE *) (UINTN) SmbiosTable->TableAddress;
3273 SmbiosEnd.Raw = (UINT8 *) ((UINTN) SmbiosTable->TableAddress + SmbiosTable->TableLength);
3274 }
3275
3276 do {
3277 if (Smbios.Hdr->Type == 1) {
3278 if (Smbios.Hdr->Length < 0x19) {
3279 //
3280 // Older version did not support UUID.
3281 //
3282 return EFI_NOT_FOUND;
3283 }
3284
3285 //
3286 // SMBIOS tables are byte packed so we need to do a byte copy to
3287 // prevend alignment faults on Itanium-based platform.
3288 //
3289 CopyMem (SystemGuid, &Smbios.Type1->Uuid, sizeof (EFI_GUID));
3290 return EFI_SUCCESS;
3291 }
3292
3293 //
3294 // Go to the next SMBIOS structure. Each SMBIOS structure may include 2 parts:
3295 // 1. Formatted section; 2. Unformatted string section. So, 2 steps are needed
3296 // to skip one SMBIOS structure.
3297 //
3298
3299 //
3300 // Step 1: Skip over formatted section.
3301 //
3302 String = (CHAR8 *) (Smbios.Raw + Smbios.Hdr->Length);
3303
3304 //
3305 // Step 2: Skip over unformated string section.
3306 //
3307 do {
3308 //
3309 // Each string is terminated with a NULL(00h) BYTE and the sets of strings
3310 // is terminated with an additional NULL(00h) BYTE.
3311 //
3312 for ( ; *String != 0; String++) {
3313 }
3314
3315 if (*(UINT8*)++String == 0) {
3316 //
3317 // Pointer to the next SMBIOS structure.
3318 //
3319 Smbios.Raw = (UINT8 *)++String;
3320 break;
3321 }
3322 } while (TRUE);
3323 } while (Smbios.Raw < SmbiosEnd.Raw);
3324 return EFI_NOT_FOUND;
3325 }
3326
3327 /**
3328 Create Dns QName according the queried domain name.
3329
3330 If DomainName is NULL, then ASSERT().
3331
3332 QName is a domain name represented as a sequence of labels,
3333 where each label consists of a length octet followed by that
3334 number of octets. The QName terminates with the zero
3335 length octet for the null label of the root. Caller should
3336 take responsibility to free the buffer in returned pointer.
3337
3338 @param DomainName The pointer to the queried domain name string.
3339
3340 @retval NULL Failed to fill QName.
3341 @return QName filled successfully.
3342
3343 **/
3344 CHAR8 *
3345 EFIAPI
3346 NetLibCreateDnsQName (
3347 IN CHAR16 *DomainName
3348 )
3349 {
3350 CHAR8 *QueryName;
3351 UINTN QueryNameSize;
3352 CHAR8 *Header;
3353 CHAR8 *Tail;
3354 UINTN Len;
3355 UINTN Index;
3356
3357 ASSERT (DomainName != NULL);
3358
3359 QueryName = NULL;
3360 QueryNameSize = 0;
3361 Header = NULL;
3362 Tail = NULL;
3363
3364 //
3365 // One byte for first label length, one byte for terminated length zero.
3366 //
3367 QueryNameSize = StrLen (DomainName) + 2;
3368
3369 if (QueryNameSize > DNS_MAX_NAME_SIZE) {
3370 return NULL;
3371 }
3372
3373 QueryName = AllocateZeroPool (QueryNameSize);
3374 if (QueryName == NULL) {
3375 return NULL;
3376 }
3377
3378 Header = QueryName;
3379 Tail = Header + 1;
3380 Len = 0;
3381 for (Index = 0; DomainName[Index] != 0; Index++) {
3382 *Tail = (CHAR8) DomainName[Index];
3383 if (*Tail == '.') {
3384 *Header = (CHAR8) Len;
3385 Header = Tail;
3386 Tail ++;
3387 Len = 0;
3388 } else {
3389 Tail++;
3390 Len++;
3391 }
3392 }
3393 *Header = (CHAR8) Len;
3394 *Tail = 0;
3395
3396 return QueryName;
3397 }