4 Copyright (c) 2005 - 2015, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
16 #include <IndustryStandard/SmBios.h>
18 #include <Protocol/DriverBinding.h>
19 #include <Protocol/ServiceBinding.h>
20 #include <Protocol/SimpleNetwork.h>
21 #include <Protocol/ManagedNetwork.h>
22 #include <Protocol/Ip4Config2.h>
23 #include <Protocol/ComponentName.h>
24 #include <Protocol/ComponentName2.h>
26 #include <Guid/SmBios.h>
28 #include <Library/NetLib.h>
29 #include <Library/BaseLib.h>
30 #include <Library/DebugLib.h>
31 #include <Library/BaseMemoryLib.h>
32 #include <Library/UefiBootServicesTableLib.h>
33 #include <Library/UefiRuntimeServicesTableLib.h>
34 #include <Library/MemoryAllocationLib.h>
35 #include <Library/DevicePathLib.h>
36 #include <Library/PrintLib.h>
37 #include <Library/UefiLib.h>
39 #define NIC_ITEM_CONFIG_SIZE sizeof (NIC_IP4_CONFIG_INFO) + sizeof (EFI_IP4_ROUTE_TABLE) * MAX_IP4_CONFIG_IN_VARIABLE
40 #define DEFAULT_ZERO_START ((UINTN) ~0)
43 // All the supported IP4 maskes in host byte order.
45 GLOBAL_REMOVE_IF_UNREFERENCED IP4_ADDR gIp4AllMasks
[IP4_MASK_NUM
] = {
84 GLOBAL_REMOVE_IF_UNREFERENCED EFI_IPv4_ADDRESS mZeroIp4Addr
= {{0, 0, 0, 0}};
87 // Any error level digitally larger than mNetDebugLevelMax
88 // will be silently discarded.
90 GLOBAL_REMOVE_IF_UNREFERENCED UINTN mNetDebugLevelMax
= NETDEBUG_LEVEL_ERROR
;
91 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogPacketSeq
= 0xDEADBEEF;
94 // You can change mSyslogDstMac mSyslogDstIp and mSyslogSrcIp
95 // here to direct the syslog packets to the syslog deamon. The
96 // default is broadcast to both the ethernet and IP.
98 GLOBAL_REMOVE_IF_UNREFERENCED UINT8 mSyslogDstMac
[NET_ETHER_ADDR_LEN
] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
99 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogDstIp
= 0xffffffff;
100 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogSrcIp
= 0;
102 GLOBAL_REMOVE_IF_UNREFERENCED CHAR8
*mMonthName
[] = {
118 // VLAN device path node template
120 GLOBAL_REMOVE_IF_UNREFERENCED VLAN_DEVICE_PATH mNetVlanDevicePathTemplate
= {
122 MESSAGING_DEVICE_PATH
,
125 (UINT8
) (sizeof (VLAN_DEVICE_PATH
)),
126 (UINT8
) ((sizeof (VLAN_DEVICE_PATH
)) >> 8)
133 Locate the handles that support SNP, then open one of them
134 to send the syslog packets. The caller isn't required to close
135 the SNP after use because the SNP is opened by HandleProtocol.
137 @return The point to SNP if one is properly openned. Otherwise NULL
140 EFI_SIMPLE_NETWORK_PROTOCOL
*
145 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
152 // Locate the handles which has SNP installed.
155 Status
= gBS
->LocateHandleBuffer (
157 &gEfiSimpleNetworkProtocolGuid
,
163 if (EFI_ERROR (Status
) || (HandleCount
== 0)) {
168 // Try to open one of the ethernet SNP protocol to send packet
172 for (Index
= 0; Index
< HandleCount
; Index
++) {
173 Status
= gBS
->HandleProtocol (
175 &gEfiSimpleNetworkProtocolGuid
,
179 if ((Status
== EFI_SUCCESS
) && (Snp
!= NULL
) &&
180 (Snp
->Mode
->IfType
== NET_IFTYPE_ETHERNET
) &&
181 (Snp
->Mode
->MaxPacketSize
>= NET_SYSLOG_PACKET_LEN
)) {
194 Transmit a syslog packet synchronously through SNP. The Packet
195 already has the ethernet header prepended. This function should
196 fill in the source MAC because it will try to locate a SNP each
197 time it is called to avoid the problem if SNP is unloaded.
198 This code snip is copied from MNP.
200 @param[in] Packet The Syslog packet
201 @param[in] Length The length of the packet
203 @retval EFI_DEVICE_ERROR Failed to locate a usable SNP protocol
204 @retval EFI_TIMEOUT Timeout happened to send the packet.
205 @retval EFI_SUCCESS Packet is sent.
214 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
217 EFI_EVENT TimeoutEvent
;
220 Snp
= SyslogLocateSnp ();
223 return EFI_DEVICE_ERROR
;
226 Ether
= (ETHER_HEAD
*) Packet
;
227 CopyMem (Ether
->SrcMac
, Snp
->Mode
->CurrentAddress
.Addr
, NET_ETHER_ADDR_LEN
);
230 // Start the timeout event.
232 Status
= gBS
->CreateEvent (
240 if (EFI_ERROR (Status
)) {
244 Status
= gBS
->SetTimer (TimeoutEvent
, TimerRelative
, NET_SYSLOG_TX_TIMEOUT
);
246 if (EFI_ERROR (Status
)) {
252 // Transmit the packet through SNP.
254 Status
= Snp
->Transmit (Snp
, 0, Length
, Packet
, NULL
, NULL
, NULL
);
256 if ((Status
!= EFI_SUCCESS
) && (Status
!= EFI_NOT_READY
)) {
257 Status
= EFI_DEVICE_ERROR
;
262 // If Status is EFI_SUCCESS, the packet is put in the transmit queue.
263 // if Status is EFI_NOT_READY, the transmit engine of the network
264 // interface is busy. Both need to sync SNP.
270 // Get the recycled transmit buffer status.
272 Snp
->GetStatus (Snp
, NULL
, (VOID
**) &TxBuf
);
274 if (!EFI_ERROR (gBS
->CheckEvent (TimeoutEvent
))) {
275 Status
= EFI_TIMEOUT
;
279 } while (TxBuf
== NULL
);
281 if ((Status
== EFI_SUCCESS
) || (Status
== EFI_TIMEOUT
)) {
286 // Status is EFI_NOT_READY. Restart the timer event and
287 // call Snp->Transmit again.
289 gBS
->SetTimer (TimeoutEvent
, TimerRelative
, NET_SYSLOG_TX_TIMEOUT
);
292 gBS
->SetTimer (TimeoutEvent
, TimerCancel
, 0);
295 gBS
->CloseEvent (TimeoutEvent
);
300 Build a syslog packet, including the Ethernet/Ip/Udp headers
303 @param[in] Level Syslog servity level
304 @param[in] Module The module that generates the log
305 @param[in] File The file that contains the current log
306 @param[in] Line The line of code in the File that contains the current log
307 @param[in] Message The log message
308 @param[in] BufLen The lenght of the Buf
309 @param[out] Buf The buffer to put the packet data
311 @return The length of the syslog packet built.
327 EFI_UDP_HEADER
*Udp4
;
333 // Fill in the Ethernet header. Leave alone the source MAC.
334 // SyslogSendPacket will fill in the address for us.
336 Ether
= (ETHER_HEAD
*) Buf
;
337 CopyMem (Ether
->DstMac
, mSyslogDstMac
, NET_ETHER_ADDR_LEN
);
338 ZeroMem (Ether
->SrcMac
, NET_ETHER_ADDR_LEN
);
340 Ether
->EtherType
= HTONS (0x0800); // IPv4 protocol
342 Buf
+= sizeof (ETHER_HEAD
);
343 BufLen
-= sizeof (ETHER_HEAD
);
346 // Fill in the IP header
348 Ip4
= (IP4_HEAD
*) Buf
;
353 Ip4
->Id
= (UINT16
) mSyslogPacketSeq
;
356 Ip4
->Protocol
= 0x11;
358 Ip4
->Src
= mSyslogSrcIp
;
359 Ip4
->Dst
= mSyslogDstIp
;
361 Buf
+= sizeof (IP4_HEAD
);
362 BufLen
-= sizeof (IP4_HEAD
);
365 // Fill in the UDP header, Udp checksum is optional. Leave it zero.
367 Udp4
= (EFI_UDP_HEADER
*) Buf
;
368 Udp4
->SrcPort
= HTONS (514);
369 Udp4
->DstPort
= HTONS (514);
373 Buf
+= sizeof (EFI_UDP_HEADER
);
374 BufLen
-= sizeof (EFI_UDP_HEADER
);
377 // Build the syslog message body with <PRI> Timestamp machine module Message
379 Pri
= ((NET_SYSLOG_FACILITY
& 31) << 3) | (Level
& 7);
380 gRT
->GetTime (&Time
, NULL
);
381 ASSERT ((Time
.Month
<= 12) && (Time
.Month
>= 1));
384 // Use %a to format the ASCII strings, %s to format UNICODE strings
387 Len
+= (UINT32
) AsciiSPrint (
390 "<%d> %a %d %d:%d:%d ",
392 mMonthName
[Time
.Month
-1],
400 Len
+= (UINT32
) AsciiSPrint (
403 "Tiano %a: %a (Line: %d File: %a)",
412 // OK, patch the IP length/checksum and UDP length fields.
414 Len
+= sizeof (EFI_UDP_HEADER
);
415 Udp4
->Length
= HTONS ((UINT16
) Len
);
417 Len
+= sizeof (IP4_HEAD
);
418 Ip4
->TotalLen
= HTONS ((UINT16
) Len
);
419 Ip4
->Checksum
= (UINT16
) (~NetblockChecksum ((UINT8
*) Ip4
, sizeof (IP4_HEAD
)));
421 return Len
+ sizeof (ETHER_HEAD
);
425 Allocate a buffer, then format the message to it. This is a
426 help function for the NET_DEBUG_XXX macros. The PrintArg of
427 these macros treats the variable length print parameters as a
428 single parameter, and pass it to the NetDebugASPrint. For
429 example, NET_DEBUG_TRACE ("Tcp", ("State transit to %a\n", Name))
433 NETDEBUG_LEVEL_TRACE,
437 NetDebugASPrint ("State transit to %a\n", Name)
440 @param Format The ASCII format string.
441 @param ... The variable length parameter whose format is determined
442 by the Format string.
444 @return The buffer containing the formatted message,
445 or NULL if failed to allocate memory.
458 Buf
= (CHAR8
*) AllocatePool (NET_DEBUG_MSG_LEN
);
464 VA_START (Marker
, Format
);
465 AsciiVSPrint (Buf
, NET_DEBUG_MSG_LEN
, Format
, Marker
);
472 Builds an UDP4 syslog packet and send it using SNP.
474 This function will locate a instance of SNP then send the message through it.
475 Because it isn't open the SNP BY_DRIVER, apply caution when using it.
477 @param Level The servity level of the message.
478 @param Module The Moudle that generates the log.
479 @param File The file that contains the log.
480 @param Line The exact line that contains the log.
481 @param Message The user message to log.
483 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
484 @retval EFI_OUT_OF_RESOURCES Failed to allocate memory for the packet
485 @retval EFI_SUCCESS The log is discard because that it is more verbose
486 than the mNetDebugLevelMax. Or, it has been sent out.
503 // Check whether the message should be sent out
505 if (Message
== NULL
) {
506 return EFI_INVALID_PARAMETER
;
509 if (Level
> mNetDebugLevelMax
) {
510 Status
= EFI_SUCCESS
;
515 // Allocate a maxium of 1024 bytes, the caller should ensure
516 // that the message plus the ethernet/ip/udp header is shorter
519 Packet
= (CHAR8
*) AllocatePool (NET_SYSLOG_PACKET_LEN
);
521 if (Packet
== NULL
) {
522 Status
= EFI_OUT_OF_RESOURCES
;
527 // Build the message: Ethernet header + IP header + Udp Header + user data
529 Len
= SyslogBuildPacket (
535 NET_SYSLOG_PACKET_LEN
,
540 Status
= SyslogSendPacket (Packet
, Len
);
548 Return the length of the mask.
550 Return the length of the mask, the correct value is from 0 to 32.
551 If the mask is invalid, return the invalid length 33, which is IP4_MASK_NUM.
552 NetMask is in the host byte order.
554 @param[in] NetMask The netmask to get the length from.
556 @return The length of the netmask, IP4_MASK_NUM if the mask is invalid.
567 for (Index
= 0; Index
< IP4_MASK_NUM
; Index
++) {
568 if (NetMask
== gIp4AllMasks
[Index
]) {
579 Return the class of the IP address, such as class A, B, C.
580 Addr is in host byte order.
582 The address of class A starts with 0.
583 If the address belong to class A, return IP4_ADDR_CLASSA.
584 The address of class B starts with 10.
585 If the address belong to class B, return IP4_ADDR_CLASSB.
586 The address of class C starts with 110.
587 If the address belong to class C, return IP4_ADDR_CLASSC.
588 The address of class D starts with 1110.
589 If the address belong to class D, return IP4_ADDR_CLASSD.
590 The address of class E starts with 1111.
591 If the address belong to class E, return IP4_ADDR_CLASSE.
594 @param[in] Addr The address to get the class from.
596 @return IP address class, such as IP4_ADDR_CLASSA.
607 ByteOne
= (UINT8
) (Addr
>> 24);
609 if ((ByteOne
& 0x80) == 0) {
610 return IP4_ADDR_CLASSA
;
612 } else if ((ByteOne
& 0xC0) == 0x80) {
613 return IP4_ADDR_CLASSB
;
615 } else if ((ByteOne
& 0xE0) == 0xC0) {
616 return IP4_ADDR_CLASSC
;
618 } else if ((ByteOne
& 0xF0) == 0xE0) {
619 return IP4_ADDR_CLASSD
;
622 return IP4_ADDR_CLASSE
;
629 Check whether the IP is a valid unicast address according to
630 the netmask. If NetMask is zero, use the IP address's class to get the default mask.
632 If Ip is 0, IP is not a valid unicast address.
633 Class D address is used for multicasting and class E address is reserved for future. If Ip
634 belongs to class D or class E, IP is not a valid unicast address.
635 If all bits of the host address of IP are 0 or 1, IP is also not a valid unicast address.
637 @param[in] Ip The IP to check against.
638 @param[in] NetMask The mask of the IP.
640 @return TRUE if IP is a valid unicast address on the network, otherwise FALSE.
652 Class
= NetGetIpClass (Ip
);
654 if ((Ip
== 0) || (Class
>= IP4_ADDR_CLASSD
)) {
659 NetMask
= gIp4AllMasks
[Class
<< 3];
662 if (((Ip
&~NetMask
) == ~NetMask
) || ((Ip
&~NetMask
) == 0)) {
670 Check whether the incoming IPv6 address is a valid unicast address.
672 If the address is a multicast address has binary 0xFF at the start, it is not
673 a valid unicast address. If the address is unspecified ::, it is not a valid
674 unicast address to be assigned to any node. If the address is loopback address
675 ::1, it is also not a valid unicast address to be assigned to any physical
678 @param[in] Ip6 The IPv6 address to check against.
680 @return TRUE if Ip6 is a valid unicast address on the network, otherwise FALSE.
685 NetIp6IsValidUnicast (
686 IN EFI_IPv6_ADDRESS
*Ip6
692 if (Ip6
->Addr
[0] == 0xFF) {
696 for (Index
= 0; Index
< 15; Index
++) {
697 if (Ip6
->Addr
[Index
] != 0) {
702 Byte
= Ip6
->Addr
[Index
];
704 if (Byte
== 0x0 || Byte
== 0x1) {
712 Check whether the incoming Ipv6 address is the unspecified address or not.
714 @param[in] Ip6 - Ip6 address, in network order.
716 @retval TRUE - Yes, unspecified
722 NetIp6IsUnspecifiedAddr (
723 IN EFI_IPv6_ADDRESS
*Ip6
728 for (Index
= 0; Index
< 16; Index
++) {
729 if (Ip6
->Addr
[Index
] != 0) {
738 Check whether the incoming Ipv6 address is a link-local address.
740 @param[in] Ip6 - Ip6 address, in network order.
742 @retval TRUE - Yes, link-local address
748 NetIp6IsLinkLocalAddr (
749 IN EFI_IPv6_ADDRESS
*Ip6
754 ASSERT (Ip6
!= NULL
);
756 if (Ip6
->Addr
[0] != 0xFE) {
760 if (Ip6
->Addr
[1] != 0x80) {
764 for (Index
= 2; Index
< 8; Index
++) {
765 if (Ip6
->Addr
[Index
] != 0) {
774 Check whether the Ipv6 address1 and address2 are on the connected network.
776 @param[in] Ip1 - Ip6 address1, in network order.
777 @param[in] Ip2 - Ip6 address2, in network order.
778 @param[in] PrefixLength - The prefix length of the checking net.
780 @retval TRUE - Yes, connected.
787 EFI_IPv6_ADDRESS
*Ip1
,
788 EFI_IPv6_ADDRESS
*Ip2
,
796 ASSERT ((Ip1
!= NULL
) && (Ip2
!= NULL
) && (PrefixLength
< IP6_PREFIX_NUM
));
798 if (PrefixLength
== 0) {
802 Byte
= (UINT8
) (PrefixLength
/ 8);
803 Bit
= (UINT8
) (PrefixLength
% 8);
805 if (CompareMem (Ip1
, Ip2
, Byte
) != 0) {
810 Mask
= (UINT8
) (0xFF << (8 - Bit
));
813 if ((Ip1
->Addr
[Byte
] & Mask
) != (Ip2
->Addr
[Byte
] & Mask
)) {
823 Switches the endianess of an IPv6 address
825 This function swaps the bytes in a 128-bit IPv6 address to switch the value
826 from little endian to big endian or vice versa. The byte swapped value is
829 @param Ip6 Points to an IPv6 address
831 @return The byte swapped IPv6 address.
837 EFI_IPv6_ADDRESS
*Ip6
843 CopyMem (&High
, Ip6
, sizeof (UINT64
));
844 CopyMem (&Low
, &Ip6
->Addr
[8], sizeof (UINT64
));
846 High
= SwapBytes64 (High
);
847 Low
= SwapBytes64 (Low
);
849 CopyMem (Ip6
, &Low
, sizeof (UINT64
));
850 CopyMem (&Ip6
->Addr
[8], &High
, sizeof (UINT64
));
856 Initialize a random seed using current time and monotonic count.
858 Get current time and monotonic count first. Then initialize a random seed
859 based on some basic mathematics operation on the hour, day, minute, second,
860 nanosecond and year of the current time and the monotonic count value.
862 @return The random seed initialized with current time.
873 UINT64 MonotonicCount
;
875 gRT
->GetTime (&Time
, NULL
);
876 Seed
= (~Time
.Hour
<< 24 | Time
.Day
<< 16 | Time
.Minute
<< 8 | Time
.Second
);
877 Seed
^= Time
.Nanosecond
;
878 Seed
^= Time
.Year
<< 7;
880 gBS
->GetNextMonotonicCount (&MonotonicCount
);
881 Seed
+= (UINT32
) MonotonicCount
;
888 Extract a UINT32 from a byte stream.
890 Copy a UINT32 from a byte stream, then converts it from Network
891 byte order to host byte order. Use this function to avoid alignment error.
893 @param[in] Buf The buffer to extract the UINT32.
895 @return The UINT32 extracted.
906 CopyMem (&Value
, Buf
, sizeof (UINT32
));
907 return NTOHL (Value
);
912 Put a UINT32 to the byte stream in network byte order.
914 Converts a UINT32 from host byte order to network byte order. Then copy it to the
917 @param[in, out] Buf The buffer to put the UINT32.
918 @param[in] Data The data to be converted and put into the byte stream.
929 CopyMem (Buf
, &Data
, sizeof (UINT32
));
934 Remove the first node entry on the list, and return the removed node entry.
936 Removes the first node Entry from a doubly linked list. It is up to the caller of
937 this function to release the memory used by the first node if that is required. On
938 exit, the removed node is returned.
940 If Head is NULL, then ASSERT().
941 If Head was not initialized, then ASSERT().
942 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
943 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
946 @param[in, out] Head The list header.
948 @return The first node entry that is removed from the list, NULL if the list is empty.
954 IN OUT LIST_ENTRY
*Head
959 ASSERT (Head
!= NULL
);
961 if (IsListEmpty (Head
)) {
965 First
= Head
->ForwardLink
;
966 Head
->ForwardLink
= First
->ForwardLink
;
967 First
->ForwardLink
->BackLink
= Head
;
970 First
->ForwardLink
= (LIST_ENTRY
*) NULL
;
971 First
->BackLink
= (LIST_ENTRY
*) NULL
;
979 Remove the last node entry on the list and and return the removed node entry.
981 Removes the last node entry from a doubly linked list. It is up to the caller of
982 this function to release the memory used by the first node if that is required. On
983 exit, the removed node is returned.
985 If Head is NULL, then ASSERT().
986 If Head was not initialized, then ASSERT().
987 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
988 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
991 @param[in, out] Head The list head.
993 @return The last node entry that is removed from the list, NULL if the list is empty.
999 IN OUT LIST_ENTRY
*Head
1004 ASSERT (Head
!= NULL
);
1006 if (IsListEmpty (Head
)) {
1010 Last
= Head
->BackLink
;
1011 Head
->BackLink
= Last
->BackLink
;
1012 Last
->BackLink
->ForwardLink
= Head
;
1015 Last
->ForwardLink
= (LIST_ENTRY
*) NULL
;
1016 Last
->BackLink
= (LIST_ENTRY
*) NULL
;
1024 Insert a new node entry after a designated node entry of a doubly linked list.
1026 Inserts a new node entry donated by NewEntry after the node entry donated by PrevEntry
1027 of the doubly linked list.
1029 @param[in, out] PrevEntry The previous entry to insert after.
1030 @param[in, out] NewEntry The new entry to insert.
1035 NetListInsertAfter (
1036 IN OUT LIST_ENTRY
*PrevEntry
,
1037 IN OUT LIST_ENTRY
*NewEntry
1040 NewEntry
->BackLink
= PrevEntry
;
1041 NewEntry
->ForwardLink
= PrevEntry
->ForwardLink
;
1042 PrevEntry
->ForwardLink
->BackLink
= NewEntry
;
1043 PrevEntry
->ForwardLink
= NewEntry
;
1048 Insert a new node entry before a designated node entry of a doubly linked list.
1050 Inserts a new node entry donated by NewEntry after the node entry donated by PostEntry
1051 of the doubly linked list.
1053 @param[in, out] PostEntry The entry to insert before.
1054 @param[in, out] NewEntry The new entry to insert.
1059 NetListInsertBefore (
1060 IN OUT LIST_ENTRY
*PostEntry
,
1061 IN OUT LIST_ENTRY
*NewEntry
1064 NewEntry
->ForwardLink
= PostEntry
;
1065 NewEntry
->BackLink
= PostEntry
->BackLink
;
1066 PostEntry
->BackLink
->ForwardLink
= NewEntry
;
1067 PostEntry
->BackLink
= NewEntry
;
1071 Safe destroy nodes in a linked list, and return the length of the list after all possible operations finished.
1073 Destroy network child instance list by list traversals is not safe due to graph dependencies between nodes.
1074 This function performs a safe traversal to destroy these nodes by checking to see if the node being destroyed
1075 has been removed from the list or not.
1076 If it has been removed, then restart the traversal from the head.
1077 If it hasn't been removed, then continue with the next node directly.
1078 This function will end the iterate and return the CallBack's last return value if error happens,
1079 or retrun EFI_SUCCESS if 2 complete passes are made with no changes in the number of children in the list.
1081 @param[in] List The head of the list.
1082 @param[in] CallBack Pointer to the callback function to destroy one node in the list.
1083 @param[in] Context Pointer to the callback function's context: corresponds to the
1084 parameter Context in NET_DESTROY_LINK_LIST_CALLBACK.
1085 @param[out] ListLength The length of the link list if the function returns successfully.
1087 @retval EFI_SUCCESS Two complete passes are made with no changes in the number of children.
1088 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
1089 @retval Others Return the CallBack's last return value.
1094 NetDestroyLinkList (
1095 IN LIST_ENTRY
*List
,
1096 IN NET_DESTROY_LINK_LIST_CALLBACK CallBack
,
1097 IN VOID
*Context
, OPTIONAL
1098 OUT UINTN
*ListLength OPTIONAL
1101 UINTN PreviousLength
;
1107 if (List
== NULL
|| CallBack
== NULL
) {
1108 return EFI_INVALID_PARAMETER
;
1113 PreviousLength
= Length
;
1114 Entry
= GetFirstNode (List
);
1115 while (!IsNull (List
, Entry
)) {
1116 Status
= CallBack (Entry
, Context
);
1117 if (EFI_ERROR (Status
)) {
1121 // Walk through the list to see whether the Entry has been removed or not.
1122 // If the Entry still exists, just try to destroy the next one.
1123 // If not, go back to the start point to iterate the list again.
1125 for (Ptr
= List
->ForwardLink
; Ptr
!= List
; Ptr
= Ptr
->ForwardLink
) {
1131 Entry
= GetNextNode (List
, Entry
);
1133 Entry
= GetFirstNode (List
);
1136 for (Length
= 0, Ptr
= List
->ForwardLink
; Ptr
!= List
; Length
++, Ptr
= Ptr
->ForwardLink
);
1137 } while (Length
!= PreviousLength
);
1139 if (ListLength
!= NULL
) {
1140 *ListLength
= Length
;
1146 This function checks the input Handle to see if it's one of these handles in ChildHandleBuffer.
1148 @param[in] Handle Handle to be checked.
1149 @param[in] NumberOfChildren Number of Handles in ChildHandleBuffer.
1150 @param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
1151 if NumberOfChildren is 0.
1153 @retval TURE Found the input Handle in ChildHandleBuffer.
1154 @retval FALSE Can't find the input Handle in ChildHandleBuffer.
1159 NetIsInHandleBuffer (
1160 IN EFI_HANDLE Handle
,
1161 IN UINTN NumberOfChildren
,
1162 IN EFI_HANDLE
*ChildHandleBuffer OPTIONAL
1167 if (NumberOfChildren
== 0 || ChildHandleBuffer
== NULL
) {
1171 for (Index
= 0; Index
< NumberOfChildren
; Index
++) {
1172 if (Handle
== ChildHandleBuffer
[Index
]) {
1182 Initialize the netmap. Netmap is a reposity to keep the <Key, Value> pairs.
1184 Initialize the forward and backward links of two head nodes donated by Map->Used
1185 and Map->Recycled of two doubly linked lists.
1186 Initializes the count of the <Key, Value> pairs in the netmap to zero.
1188 If Map is NULL, then ASSERT().
1189 If the address of Map->Used is NULL, then ASSERT().
1190 If the address of Map->Recycled is NULl, then ASSERT().
1192 @param[in, out] Map The netmap to initialize.
1201 ASSERT (Map
!= NULL
);
1203 InitializeListHead (&Map
->Used
);
1204 InitializeListHead (&Map
->Recycled
);
1210 To clean up the netmap, that is, release allocated memories.
1212 Removes all nodes of the Used doubly linked list and free memory of all related netmap items.
1213 Removes all nodes of the Recycled doubly linked list and free memory of all related netmap items.
1214 The number of the <Key, Value> pairs in the netmap is set to be zero.
1216 If Map is NULL, then ASSERT().
1218 @param[in, out] Map The netmap to clean up.
1231 ASSERT (Map
!= NULL
);
1233 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, &Map
->Used
) {
1234 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1236 RemoveEntryList (&Item
->Link
);
1239 gBS
->FreePool (Item
);
1242 ASSERT ((Map
->Count
== 0) && IsListEmpty (&Map
->Used
));
1244 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, &Map
->Recycled
) {
1245 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1247 RemoveEntryList (&Item
->Link
);
1248 gBS
->FreePool (Item
);
1251 ASSERT (IsListEmpty (&Map
->Recycled
));
1256 Test whether the netmap is empty and return true if it is.
1258 If the number of the <Key, Value> pairs in the netmap is zero, return TRUE.
1260 If Map is NULL, then ASSERT().
1263 @param[in] Map The net map to test.
1265 @return TRUE if the netmap is empty, otherwise FALSE.
1274 ASSERT (Map
!= NULL
);
1275 return (BOOLEAN
) (Map
->Count
== 0);
1280 Return the number of the <Key, Value> pairs in the netmap.
1282 @param[in] Map The netmap to get the entry number.
1284 @return The entry number in the netmap.
1298 Return one allocated item.
1300 If the Recycled doubly linked list of the netmap is empty, it will try to allocate
1301 a batch of items if there are enough resources and add corresponding nodes to the begining
1302 of the Recycled doubly linked list of the netmap. Otherwise, it will directly remove
1303 the fist node entry of the Recycled doubly linked list and return the corresponding item.
1305 If Map is NULL, then ASSERT().
1307 @param[in, out] Map The netmap to allocate item for.
1309 @return The allocated item. If NULL, the
1310 allocation failed due to resource limit.
1322 ASSERT (Map
!= NULL
);
1324 Head
= &Map
->Recycled
;
1326 if (IsListEmpty (Head
)) {
1327 for (Index
= 0; Index
< NET_MAP_INCREAMENT
; Index
++) {
1328 Item
= AllocatePool (sizeof (NET_MAP_ITEM
));
1338 InsertHeadList (Head
, &Item
->Link
);
1342 Item
= NET_LIST_HEAD (Head
, NET_MAP_ITEM
, Link
);
1343 NetListRemoveHead (Head
);
1350 Allocate an item to save the <Key, Value> pair to the head of the netmap.
1352 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1353 to the beginning of the Used doubly linked list. The number of the <Key, Value>
1354 pairs in the netmap increase by 1.
1356 If Map is NULL, then ASSERT().
1358 @param[in, out] Map The netmap to insert into.
1359 @param[in] Key The user's key.
1360 @param[in] Value The user's value for the key.
1362 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1363 @retval EFI_SUCCESS The item is inserted to the head.
1369 IN OUT NET_MAP
*Map
,
1371 IN VOID
*Value OPTIONAL
1376 ASSERT (Map
!= NULL
);
1378 Item
= NetMapAllocItem (Map
);
1381 return EFI_OUT_OF_RESOURCES
;
1385 Item
->Value
= Value
;
1386 InsertHeadList (&Map
->Used
, &Item
->Link
);
1394 Allocate an item to save the <Key, Value> pair to the tail of the netmap.
1396 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1397 to the tail of the Used doubly linked list. The number of the <Key, Value>
1398 pairs in the netmap increase by 1.
1400 If Map is NULL, then ASSERT().
1402 @param[in, out] Map The netmap to insert into.
1403 @param[in] Key The user's key.
1404 @param[in] Value The user's value for the key.
1406 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1407 @retval EFI_SUCCESS The item is inserted to the tail.
1413 IN OUT NET_MAP
*Map
,
1415 IN VOID
*Value OPTIONAL
1420 ASSERT (Map
!= NULL
);
1422 Item
= NetMapAllocItem (Map
);
1425 return EFI_OUT_OF_RESOURCES
;
1429 Item
->Value
= Value
;
1430 InsertTailList (&Map
->Used
, &Item
->Link
);
1439 Check whether the item is in the Map and return TRUE if it is.
1441 @param[in] Map The netmap to search within.
1442 @param[in] Item The item to search.
1444 @return TRUE if the item is in the netmap, otherwise FALSE.
1450 IN NET_MAP_ITEM
*Item
1453 LIST_ENTRY
*ListEntry
;
1455 NET_LIST_FOR_EACH (ListEntry
, &Map
->Used
) {
1456 if (ListEntry
== &Item
->Link
) {
1466 Find the key in the netmap and returns the point to the item contains the Key.
1468 Iterate the Used doubly linked list of the netmap to get every item. Compare the key of every
1469 item with the key to search. It returns the point to the item contains the Key if found.
1471 If Map is NULL, then ASSERT().
1473 @param[in] Map The netmap to search within.
1474 @param[in] Key The key to search.
1476 @return The point to the item contains the Key, or NULL if Key isn't in the map.
1489 ASSERT (Map
!= NULL
);
1491 NET_LIST_FOR_EACH (Entry
, &Map
->Used
) {
1492 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1494 if (Item
->Key
== Key
) {
1504 Remove the node entry of the item from the netmap and return the key of the removed item.
1506 Remove the node entry of the item from the Used doubly linked list of the netmap.
1507 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1508 entry of the item to the Recycled doubly linked list of the netmap. If Value is not NULL,
1509 Value will point to the value of the item. It returns the key of the removed item.
1511 If Map is NULL, then ASSERT().
1512 If Item is NULL, then ASSERT().
1513 if item in not in the netmap, then ASSERT().
1515 @param[in, out] Map The netmap to remove the item from.
1516 @param[in, out] Item The item to remove.
1517 @param[out] Value The variable to receive the value if not NULL.
1519 @return The key of the removed item.
1525 IN OUT NET_MAP
*Map
,
1526 IN OUT NET_MAP_ITEM
*Item
,
1527 OUT VOID
**Value OPTIONAL
1530 ASSERT ((Map
!= NULL
) && (Item
!= NULL
));
1531 ASSERT (NetItemInMap (Map
, Item
));
1533 RemoveEntryList (&Item
->Link
);
1535 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1537 if (Value
!= NULL
) {
1538 *Value
= Item
->Value
;
1546 Remove the first node entry on the netmap and return the key of the removed item.
1548 Remove the first node entry from the Used doubly linked list of the netmap.
1549 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1550 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1551 parameter Value will point to the value of the item. It returns the key of the removed item.
1553 If Map is NULL, then ASSERT().
1554 If the Used doubly linked list is empty, then ASSERT().
1556 @param[in, out] Map The netmap to remove the head from.
1557 @param[out] Value The variable to receive the value if not NULL.
1559 @return The key of the item removed.
1565 IN OUT NET_MAP
*Map
,
1566 OUT VOID
**Value OPTIONAL
1572 // Often, it indicates a programming error to remove
1573 // the first entry in an empty list
1575 ASSERT (Map
&& !IsListEmpty (&Map
->Used
));
1577 Item
= NET_LIST_HEAD (&Map
->Used
, NET_MAP_ITEM
, Link
);
1578 RemoveEntryList (&Item
->Link
);
1580 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1582 if (Value
!= NULL
) {
1583 *Value
= Item
->Value
;
1591 Remove the last node entry on the netmap and return the key of the removed item.
1593 Remove the last node entry from the Used doubly linked list of the netmap.
1594 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1595 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1596 parameter Value will point to the value of the item. It returns the key of the removed item.
1598 If Map is NULL, then ASSERT().
1599 If the Used doubly linked list is empty, then ASSERT().
1601 @param[in, out] Map The netmap to remove the tail from.
1602 @param[out] Value The variable to receive the value if not NULL.
1604 @return The key of the item removed.
1610 IN OUT NET_MAP
*Map
,
1611 OUT VOID
**Value OPTIONAL
1617 // Often, it indicates a programming error to remove
1618 // the last entry in an empty list
1620 ASSERT (Map
&& !IsListEmpty (&Map
->Used
));
1622 Item
= NET_LIST_TAIL (&Map
->Used
, NET_MAP_ITEM
, Link
);
1623 RemoveEntryList (&Item
->Link
);
1625 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1627 if (Value
!= NULL
) {
1628 *Value
= Item
->Value
;
1636 Iterate through the netmap and call CallBack for each item.
1638 It will contiue the traverse if CallBack returns EFI_SUCCESS, otherwise, break
1639 from the loop. It returns the CallBack's last return value. This function is
1640 delete safe for the current item.
1642 If Map is NULL, then ASSERT().
1643 If CallBack is NULL, then ASSERT().
1645 @param[in] Map The Map to iterate through.
1646 @param[in] CallBack The callback function to call for each item.
1647 @param[in] Arg The opaque parameter to the callback.
1649 @retval EFI_SUCCESS There is no item in the netmap or CallBack for each item
1651 @retval Others It returns the CallBack's last return value.
1658 IN NET_MAP_CALLBACK CallBack
,
1659 IN VOID
*Arg OPTIONAL
1669 ASSERT ((Map
!= NULL
) && (CallBack
!= NULL
));
1673 if (IsListEmpty (Head
)) {
1677 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, Head
) {
1678 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1679 Result
= CallBack (Map
, Item
, Arg
);
1681 if (EFI_ERROR (Result
)) {
1691 This is the default unload handle for all the network drivers.
1693 Disconnect the driver specified by ImageHandle from all the devices in the handle database.
1694 Uninstall all the protocols installed in the driver entry point.
1696 @param[in] ImageHandle The drivers' driver image.
1698 @retval EFI_SUCCESS The image is unloaded.
1699 @retval Others Failed to unload the image.
1704 NetLibDefaultUnload (
1705 IN EFI_HANDLE ImageHandle
1709 EFI_HANDLE
*DeviceHandleBuffer
;
1710 UINTN DeviceHandleCount
;
1713 EFI_DRIVER_BINDING_PROTOCOL
*DriverBinding
;
1714 EFI_COMPONENT_NAME_PROTOCOL
*ComponentName
;
1715 EFI_COMPONENT_NAME2_PROTOCOL
*ComponentName2
;
1718 // Get the list of all the handles in the handle database.
1719 // If there is an error getting the list, then the unload
1722 Status
= gBS
->LocateHandleBuffer (
1730 if (EFI_ERROR (Status
)) {
1734 for (Index
= 0; Index
< DeviceHandleCount
; Index
++) {
1735 Status
= gBS
->HandleProtocol (
1736 DeviceHandleBuffer
[Index
],
1737 &gEfiDriverBindingProtocolGuid
,
1738 (VOID
**) &DriverBinding
1740 if (EFI_ERROR (Status
)) {
1744 if (DriverBinding
->ImageHandle
!= ImageHandle
) {
1749 // Disconnect the driver specified by ImageHandle from all
1750 // the devices in the handle database.
1752 for (Index2
= 0; Index2
< DeviceHandleCount
; Index2
++) {
1753 Status
= gBS
->DisconnectController (
1754 DeviceHandleBuffer
[Index2
],
1755 DriverBinding
->DriverBindingHandle
,
1761 // Uninstall all the protocols installed in the driver entry point
1763 gBS
->UninstallProtocolInterface (
1764 DriverBinding
->DriverBindingHandle
,
1765 &gEfiDriverBindingProtocolGuid
,
1769 Status
= gBS
->HandleProtocol (
1770 DeviceHandleBuffer
[Index
],
1771 &gEfiComponentNameProtocolGuid
,
1772 (VOID
**) &ComponentName
1774 if (!EFI_ERROR (Status
)) {
1775 gBS
->UninstallProtocolInterface (
1776 DriverBinding
->DriverBindingHandle
,
1777 &gEfiComponentNameProtocolGuid
,
1782 Status
= gBS
->HandleProtocol (
1783 DeviceHandleBuffer
[Index
],
1784 &gEfiComponentName2ProtocolGuid
,
1785 (VOID
**) &ComponentName2
1787 if (!EFI_ERROR (Status
)) {
1788 gBS
->UninstallProtocolInterface (
1789 DriverBinding
->DriverBindingHandle
,
1790 &gEfiComponentName2ProtocolGuid
,
1797 // Free the buffer containing the list of handles from the handle database
1799 if (DeviceHandleBuffer
!= NULL
) {
1800 gBS
->FreePool (DeviceHandleBuffer
);
1809 Create a child of the service that is identified by ServiceBindingGuid.
1811 Get the ServiceBinding Protocol first, then use it to create a child.
1813 If ServiceBindingGuid is NULL, then ASSERT().
1814 If ChildHandle is NULL, then ASSERT().
1816 @param[in] Controller The controller which has the service installed.
1817 @param[in] Image The image handle used to open service.
1818 @param[in] ServiceBindingGuid The service's Guid.
1819 @param[in, out] ChildHandle The handle to receive the create child.
1821 @retval EFI_SUCCESS The child is successfully created.
1822 @retval Others Failed to create the child.
1827 NetLibCreateServiceChild (
1828 IN EFI_HANDLE Controller
,
1829 IN EFI_HANDLE Image
,
1830 IN EFI_GUID
*ServiceBindingGuid
,
1831 IN OUT EFI_HANDLE
*ChildHandle
1835 EFI_SERVICE_BINDING_PROTOCOL
*Service
;
1838 ASSERT ((ServiceBindingGuid
!= NULL
) && (ChildHandle
!= NULL
));
1841 // Get the ServiceBinding Protocol
1843 Status
= gBS
->OpenProtocol (
1849 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1852 if (EFI_ERROR (Status
)) {
1859 Status
= Service
->CreateChild (Service
, ChildHandle
);
1865 Destroy a child of the service that is identified by ServiceBindingGuid.
1867 Get the ServiceBinding Protocol first, then use it to destroy a child.
1869 If ServiceBindingGuid is NULL, then ASSERT().
1871 @param[in] Controller The controller which has the service installed.
1872 @param[in] Image The image handle used to open service.
1873 @param[in] ServiceBindingGuid The service's Guid.
1874 @param[in] ChildHandle The child to destroy.
1876 @retval EFI_SUCCESS The child is successfully destroyed.
1877 @retval Others Failed to destroy the child.
1882 NetLibDestroyServiceChild (
1883 IN EFI_HANDLE Controller
,
1884 IN EFI_HANDLE Image
,
1885 IN EFI_GUID
*ServiceBindingGuid
,
1886 IN EFI_HANDLE ChildHandle
1890 EFI_SERVICE_BINDING_PROTOCOL
*Service
;
1892 ASSERT (ServiceBindingGuid
!= NULL
);
1895 // Get the ServiceBinding Protocol
1897 Status
= gBS
->OpenProtocol (
1903 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1906 if (EFI_ERROR (Status
)) {
1911 // destroy the child
1913 Status
= Service
->DestroyChild (Service
, ChildHandle
);
1918 Get handle with Simple Network Protocol installed on it.
1920 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
1921 If Simple Network Protocol is already installed on the ServiceHandle, the
1922 ServiceHandle will be returned. If SNP is not installed on the ServiceHandle,
1923 try to find its parent handle with SNP installed.
1925 @param[in] ServiceHandle The handle where network service binding protocols are
1927 @param[out] Snp The pointer to store the address of the SNP instance.
1928 This is an optional parameter that may be NULL.
1930 @return The SNP handle, or NULL if not found.
1935 NetLibGetSnpHandle (
1936 IN EFI_HANDLE ServiceHandle
,
1937 OUT EFI_SIMPLE_NETWORK_PROTOCOL
**Snp OPTIONAL
1941 EFI_SIMPLE_NETWORK_PROTOCOL
*SnpInstance
;
1942 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
1943 EFI_HANDLE SnpHandle
;
1946 // Try to open SNP from ServiceHandle
1949 Status
= gBS
->HandleProtocol (ServiceHandle
, &gEfiSimpleNetworkProtocolGuid
, (VOID
**) &SnpInstance
);
1950 if (!EFI_ERROR (Status
)) {
1954 return ServiceHandle
;
1958 // Failed to open SNP, try to get SNP handle by LocateDevicePath()
1960 DevicePath
= DevicePathFromHandle (ServiceHandle
);
1961 if (DevicePath
== NULL
) {
1966 Status
= gBS
->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid
, &DevicePath
, &SnpHandle
);
1967 if (EFI_ERROR (Status
)) {
1969 // Failed to find SNP handle
1974 Status
= gBS
->HandleProtocol (SnpHandle
, &gEfiSimpleNetworkProtocolGuid
, (VOID
**) &SnpInstance
);
1975 if (!EFI_ERROR (Status
)) {
1986 Retrieve VLAN ID of a VLAN device handle.
1988 Search VLAN device path node in Device Path of specified ServiceHandle and
1989 return its VLAN ID. If no VLAN device path node found, then this ServiceHandle
1990 is not a VLAN device handle, and 0 will be returned.
1992 @param[in] ServiceHandle The handle where network service binding protocols are
1995 @return VLAN ID of the device handle, or 0 if not a VLAN device.
2001 IN EFI_HANDLE ServiceHandle
2004 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2005 EFI_DEVICE_PATH_PROTOCOL
*Node
;
2007 DevicePath
= DevicePathFromHandle (ServiceHandle
);
2008 if (DevicePath
== NULL
) {
2013 while (!IsDevicePathEnd (Node
)) {
2014 if (Node
->Type
== MESSAGING_DEVICE_PATH
&& Node
->SubType
== MSG_VLAN_DP
) {
2015 return ((VLAN_DEVICE_PATH
*) Node
)->VlanId
;
2017 Node
= NextDevicePathNode (Node
);
2024 Find VLAN device handle with specified VLAN ID.
2026 The VLAN child device handle is created by VLAN Config Protocol on ControllerHandle.
2027 This function will append VLAN device path node to the parent device path,
2028 and then use LocateDevicePath() to find the correct VLAN device handle.
2030 @param[in] ControllerHandle The handle where network service binding protocols are
2032 @param[in] VlanId The configured VLAN ID for the VLAN device.
2034 @return The VLAN device handle, or NULL if not found.
2039 NetLibGetVlanHandle (
2040 IN EFI_HANDLE ControllerHandle
,
2044 EFI_DEVICE_PATH_PROTOCOL
*ParentDevicePath
;
2045 EFI_DEVICE_PATH_PROTOCOL
*VlanDevicePath
;
2046 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2047 VLAN_DEVICE_PATH VlanNode
;
2050 ParentDevicePath
= DevicePathFromHandle (ControllerHandle
);
2051 if (ParentDevicePath
== NULL
) {
2056 // Construct VLAN device path
2058 CopyMem (&VlanNode
, &mNetVlanDevicePathTemplate
, sizeof (VLAN_DEVICE_PATH
));
2059 VlanNode
.VlanId
= VlanId
;
2060 VlanDevicePath
= AppendDevicePathNode (
2062 (EFI_DEVICE_PATH_PROTOCOL
*) &VlanNode
2064 if (VlanDevicePath
== NULL
) {
2069 // Find VLAN device handle
2072 DevicePath
= VlanDevicePath
;
2073 gBS
->LocateDevicePath (
2074 &gEfiDevicePathProtocolGuid
,
2078 if (!IsDevicePathEnd (DevicePath
)) {
2080 // Device path is not exactly match
2085 FreePool (VlanDevicePath
);
2090 Get MAC address associated with the network service handle.
2092 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
2093 If SNP is installed on the ServiceHandle or its parent handle, MAC address will
2094 be retrieved from SNP. If no SNP found, try to get SNP mode data use MNP.
2096 @param[in] ServiceHandle The handle where network service binding protocols are
2098 @param[out] MacAddress The pointer to store the returned MAC address.
2099 @param[out] AddressSize The length of returned MAC address.
2101 @retval EFI_SUCCESS MAC address is returned successfully.
2102 @retval Others Failed to get SNP mode data.
2107 NetLibGetMacAddress (
2108 IN EFI_HANDLE ServiceHandle
,
2109 OUT EFI_MAC_ADDRESS
*MacAddress
,
2110 OUT UINTN
*AddressSize
2114 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2115 EFI_SIMPLE_NETWORK_MODE
*SnpMode
;
2116 EFI_SIMPLE_NETWORK_MODE SnpModeData
;
2117 EFI_MANAGED_NETWORK_PROTOCOL
*Mnp
;
2118 EFI_SERVICE_BINDING_PROTOCOL
*MnpSb
;
2119 EFI_HANDLE
*SnpHandle
;
2120 EFI_HANDLE MnpChildHandle
;
2122 ASSERT (MacAddress
!= NULL
);
2123 ASSERT (AddressSize
!= NULL
);
2126 // Try to get SNP handle
2129 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2130 if (SnpHandle
!= NULL
) {
2132 // SNP found, use it directly
2134 SnpMode
= Snp
->Mode
;
2137 // Failed to get SNP handle, try to get MAC address from MNP
2139 MnpChildHandle
= NULL
;
2140 Status
= gBS
->HandleProtocol (
2142 &gEfiManagedNetworkServiceBindingProtocolGuid
,
2145 if (EFI_ERROR (Status
)) {
2150 // Create a MNP child
2152 Status
= MnpSb
->CreateChild (MnpSb
, &MnpChildHandle
);
2153 if (EFI_ERROR (Status
)) {
2158 // Open MNP protocol
2160 Status
= gBS
->HandleProtocol (
2162 &gEfiManagedNetworkProtocolGuid
,
2165 if (EFI_ERROR (Status
)) {
2166 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2171 // Try to get SNP mode from MNP
2173 Status
= Mnp
->GetModeData (Mnp
, NULL
, &SnpModeData
);
2174 if (EFI_ERROR (Status
) && (Status
!= EFI_NOT_STARTED
)) {
2175 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2178 SnpMode
= &SnpModeData
;
2181 // Destroy the MNP child
2183 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2186 *AddressSize
= SnpMode
->HwAddressSize
;
2187 CopyMem (MacAddress
->Addr
, SnpMode
->CurrentAddress
.Addr
, SnpMode
->HwAddressSize
);
2193 Convert MAC address of the NIC associated with specified Service Binding Handle
2194 to a unicode string. Callers are responsible for freeing the string storage.
2196 Locate simple network protocol associated with the Service Binding Handle and
2197 get the mac address from SNP. Then convert the mac address into a unicode
2198 string. It takes 2 unicode characters to represent a 1 byte binary buffer.
2199 Plus one unicode character for the null-terminator.
2201 @param[in] ServiceHandle The handle where network service binding protocol is
2203 @param[in] ImageHandle The image handle used to act as the agent handle to
2204 get the simple network protocol. This parameter is
2205 optional and may be NULL.
2206 @param[out] MacString The pointer to store the address of the string
2207 representation of the mac address.
2209 @retval EFI_SUCCESS Convert the mac address a unicode string successfully.
2210 @retval EFI_OUT_OF_RESOURCES There are not enough memory resource.
2211 @retval Others Failed to open the simple network protocol.
2216 NetLibGetMacString (
2217 IN EFI_HANDLE ServiceHandle
,
2218 IN EFI_HANDLE ImageHandle
, OPTIONAL
2219 OUT CHAR16
**MacString
2223 EFI_MAC_ADDRESS MacAddress
;
2225 UINTN HwAddressSize
;
2230 ASSERT (MacString
!= NULL
);
2233 // Get MAC address of the network device
2235 Status
= NetLibGetMacAddress (ServiceHandle
, &MacAddress
, &HwAddressSize
);
2236 if (EFI_ERROR (Status
)) {
2241 // It takes 2 unicode characters to represent a 1 byte binary buffer.
2242 // If VLAN is configured, it will need extra 5 characters like "\0005".
2243 // Plus one unicode character for the null-terminator.
2245 String
= AllocateZeroPool ((2 * HwAddressSize
+ 5 + 1) * sizeof (CHAR16
));
2246 if (String
== NULL
) {
2247 return EFI_OUT_OF_RESOURCES
;
2249 *MacString
= String
;
2252 // Convert the MAC address into a unicode string.
2254 HwAddress
= &MacAddress
.Addr
[0];
2255 for (Index
= 0; Index
< HwAddressSize
; Index
++) {
2256 String
+= UnicodeValueToString (String
, PREFIX_ZERO
| RADIX_HEX
, *(HwAddress
++), 2);
2260 // Append VLAN ID if any
2262 VlanId
= NetLibGetVlanId (ServiceHandle
);
2265 String
+= UnicodeValueToString (String
, PREFIX_ZERO
| RADIX_HEX
, VlanId
, 4);
2269 // Null terminate the Unicode string
2277 Detect media status for specified network device.
2279 The underlying UNDI driver may or may not support reporting media status from
2280 GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine
2281 will try to invoke Snp->GetStatus() to get the media status: if media already
2282 present, it return directly; if media not present, it will stop SNP and then
2283 restart SNP to get the latest media status, this give chance to get the correct
2284 media status for old UNDI driver which doesn't support reporting media status
2285 from GET_STATUS command.
2286 Note: there will be two limitations for current algorithm:
2287 1) for UNDI with this capability, in case of cable is not attached, there will
2288 be an redundant Stop/Start() process;
2289 2) for UNDI without this capability, in case that network cable is attached when
2290 Snp->Initialize() is invoked while network cable is unattached later,
2291 NetLibDetectMedia() will report MediaPresent as TRUE, causing upper layer
2292 apps to wait for timeout time.
2294 @param[in] ServiceHandle The handle where network service binding protocols are
2296 @param[out] MediaPresent The pointer to store the media status.
2298 @retval EFI_SUCCESS Media detection success.
2299 @retval EFI_INVALID_PARAMETER ServiceHandle is not valid network device handle.
2300 @retval EFI_UNSUPPORTED Network device does not support media detection.
2301 @retval EFI_DEVICE_ERROR SNP is in unknown state.
2307 IN EFI_HANDLE ServiceHandle
,
2308 OUT BOOLEAN
*MediaPresent
2312 EFI_HANDLE SnpHandle
;
2313 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2314 UINT32 InterruptStatus
;
2316 EFI_MAC_ADDRESS
*MCastFilter
;
2317 UINT32 MCastFilterCount
;
2318 UINT32 EnableFilterBits
;
2319 UINT32 DisableFilterBits
;
2320 BOOLEAN ResetMCastFilters
;
2322 ASSERT (MediaPresent
!= NULL
);
2328 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2329 if (SnpHandle
== NULL
) {
2330 return EFI_INVALID_PARAMETER
;
2334 // Check whether SNP support media detection
2336 if (!Snp
->Mode
->MediaPresentSupported
) {
2337 return EFI_UNSUPPORTED
;
2341 // Invoke Snp->GetStatus() to refresh MediaPresent field in SNP mode data
2343 Status
= Snp
->GetStatus (Snp
, &InterruptStatus
, NULL
);
2344 if (EFI_ERROR (Status
)) {
2348 if (Snp
->Mode
->MediaPresent
) {
2350 // Media is present, return directly
2352 *MediaPresent
= TRUE
;
2357 // Till now, GetStatus() report no media; while, in case UNDI not support
2358 // reporting media status from GetStatus(), this media status may be incorrect.
2359 // So, we will stop SNP and then restart it to get the correct media status.
2361 OldState
= Snp
->Mode
->State
;
2362 if (OldState
>= EfiSimpleNetworkMaxState
) {
2363 return EFI_DEVICE_ERROR
;
2368 if (OldState
== EfiSimpleNetworkInitialized
) {
2370 // SNP is already in use, need Shutdown/Stop and then Start/Initialize
2374 // Backup current SNP receive filter settings
2376 EnableFilterBits
= Snp
->Mode
->ReceiveFilterSetting
;
2377 DisableFilterBits
= Snp
->Mode
->ReceiveFilterMask
^ EnableFilterBits
;
2379 ResetMCastFilters
= TRUE
;
2380 MCastFilterCount
= Snp
->Mode
->MCastFilterCount
;
2381 if (MCastFilterCount
!= 0) {
2382 MCastFilter
= AllocateCopyPool (
2383 MCastFilterCount
* sizeof (EFI_MAC_ADDRESS
),
2384 Snp
->Mode
->MCastFilter
2386 ASSERT (MCastFilter
!= NULL
);
2388 ResetMCastFilters
= FALSE
;
2392 // Shutdown/Stop the simple network
2394 Status
= Snp
->Shutdown (Snp
);
2395 if (!EFI_ERROR (Status
)) {
2396 Status
= Snp
->Stop (Snp
);
2398 if (EFI_ERROR (Status
)) {
2403 // Start/Initialize the simple network
2405 Status
= Snp
->Start (Snp
);
2406 if (!EFI_ERROR (Status
)) {
2407 Status
= Snp
->Initialize (Snp
, 0, 0);
2409 if (EFI_ERROR (Status
)) {
2414 // Here we get the correct media status
2416 *MediaPresent
= Snp
->Mode
->MediaPresent
;
2419 // Restore SNP receive filter settings
2421 Status
= Snp
->ReceiveFilters (
2430 if (MCastFilter
!= NULL
) {
2431 FreePool (MCastFilter
);
2438 // SNP is not in use, it's in state of EfiSimpleNetworkStopped or EfiSimpleNetworkStarted
2440 if (OldState
== EfiSimpleNetworkStopped
) {
2442 // SNP not start yet, start it
2444 Status
= Snp
->Start (Snp
);
2445 if (EFI_ERROR (Status
)) {
2451 // Initialize the simple network
2453 Status
= Snp
->Initialize (Snp
, 0, 0);
2454 if (EFI_ERROR (Status
)) {
2455 Status
= EFI_DEVICE_ERROR
;
2460 // Here we get the correct media status
2462 *MediaPresent
= Snp
->Mode
->MediaPresent
;
2465 // Shut down the simple network
2467 Snp
->Shutdown (Snp
);
2470 if (OldState
== EfiSimpleNetworkStopped
) {
2472 // Original SNP sate is Stopped, restore to original state
2477 if (MCastFilter
!= NULL
) {
2478 FreePool (MCastFilter
);
2485 Check the default address used by the IPv4 driver is static or dynamic (acquired
2488 If the controller handle does not have the EFI_IP4_CONFIG2_PROTOCOL installed, the
2489 default address is static. If failed to get the policy from Ip4 Config2 Protocol,
2490 the default address is static. Otherwise, get the result from Ip4 Config2 Protocol.
2492 @param[in] Controller The controller handle which has the EFI_IP4_CONFIG2_PROTOCOL
2493 relative with the default address to judge.
2495 @retval TRUE If the default address is static.
2496 @retval FALSE If the default address is acquired from DHCP.
2500 NetLibDefaultAddressIsStatic (
2501 IN EFI_HANDLE Controller
2505 EFI_IP4_CONFIG2_PROTOCOL
*Ip4Config2
;
2507 EFI_IP4_CONFIG2_POLICY Policy
;
2512 DataSize
= sizeof (EFI_IP4_CONFIG2_POLICY
);
2517 // Get Ip4Config2 policy.
2519 Status
= gBS
->HandleProtocol (Controller
, &gEfiIp4Config2ProtocolGuid
, (VOID
**) &Ip4Config2
);
2520 if (EFI_ERROR (Status
)) {
2524 Status
= Ip4Config2
->GetData (Ip4Config2
, Ip4Config2DataTypePolicy
, &DataSize
, &Policy
);
2525 if (EFI_ERROR (Status
)) {
2529 IsStatic
= (BOOLEAN
) (Policy
== Ip4Config2PolicyStatic
);
2537 Create an IPv4 device path node.
2539 The header type of IPv4 device path node is MESSAGING_DEVICE_PATH.
2540 The header subtype of IPv4 device path node is MSG_IPv4_DP.
2541 Get other info from parameters to make up the whole IPv4 device path node.
2543 @param[in, out] Node Pointer to the IPv4 device path node.
2544 @param[in] Controller The controller handle.
2545 @param[in] LocalIp The local IPv4 address.
2546 @param[in] LocalPort The local port.
2547 @param[in] RemoteIp The remote IPv4 address.
2548 @param[in] RemotePort The remote port.
2549 @param[in] Protocol The protocol type in the IP header.
2550 @param[in] UseDefaultAddress Whether this instance is using default address or not.
2555 NetLibCreateIPv4DPathNode (
2556 IN OUT IPv4_DEVICE_PATH
*Node
,
2557 IN EFI_HANDLE Controller
,
2558 IN IP4_ADDR LocalIp
,
2559 IN UINT16 LocalPort
,
2560 IN IP4_ADDR RemoteIp
,
2561 IN UINT16 RemotePort
,
2563 IN BOOLEAN UseDefaultAddress
2566 Node
->Header
.Type
= MESSAGING_DEVICE_PATH
;
2567 Node
->Header
.SubType
= MSG_IPv4_DP
;
2568 SetDevicePathNodeLength (&Node
->Header
, sizeof (IPv4_DEVICE_PATH
));
2570 CopyMem (&Node
->LocalIpAddress
, &LocalIp
, sizeof (EFI_IPv4_ADDRESS
));
2571 CopyMem (&Node
->RemoteIpAddress
, &RemoteIp
, sizeof (EFI_IPv4_ADDRESS
));
2573 Node
->LocalPort
= LocalPort
;
2574 Node
->RemotePort
= RemotePort
;
2576 Node
->Protocol
= Protocol
;
2578 if (!UseDefaultAddress
) {
2579 Node
->StaticIpAddress
= TRUE
;
2581 Node
->StaticIpAddress
= NetLibDefaultAddressIsStatic (Controller
);
2585 // Set the Gateway IP address to default value 0:0:0:0.
2586 // Set the Subnet mask to default value 255:255:255:0.
2588 ZeroMem (&Node
->GatewayIpAddress
, sizeof (EFI_IPv4_ADDRESS
));
2589 SetMem (&Node
->SubnetMask
, sizeof (EFI_IPv4_ADDRESS
), 0xff);
2590 Node
->SubnetMask
.Addr
[3] = 0;
2594 Create an IPv6 device path node.
2596 The header type of IPv6 device path node is MESSAGING_DEVICE_PATH.
2597 The header subtype of IPv6 device path node is MSG_IPv6_DP.
2598 Get other info from parameters to make up the whole IPv6 device path node.
2600 @param[in, out] Node Pointer to the IPv6 device path node.
2601 @param[in] Controller The controller handle.
2602 @param[in] LocalIp The local IPv6 address.
2603 @param[in] LocalPort The local port.
2604 @param[in] RemoteIp The remote IPv6 address.
2605 @param[in] RemotePort The remote port.
2606 @param[in] Protocol The protocol type in the IP header.
2611 NetLibCreateIPv6DPathNode (
2612 IN OUT IPv6_DEVICE_PATH
*Node
,
2613 IN EFI_HANDLE Controller
,
2614 IN EFI_IPv6_ADDRESS
*LocalIp
,
2615 IN UINT16 LocalPort
,
2616 IN EFI_IPv6_ADDRESS
*RemoteIp
,
2617 IN UINT16 RemotePort
,
2621 Node
->Header
.Type
= MESSAGING_DEVICE_PATH
;
2622 Node
->Header
.SubType
= MSG_IPv6_DP
;
2623 SetDevicePathNodeLength (&Node
->Header
, sizeof (IPv6_DEVICE_PATH
));
2625 CopyMem (&Node
->LocalIpAddress
, LocalIp
, sizeof (EFI_IPv6_ADDRESS
));
2626 CopyMem (&Node
->RemoteIpAddress
, RemoteIp
, sizeof (EFI_IPv6_ADDRESS
));
2628 Node
->LocalPort
= LocalPort
;
2629 Node
->RemotePort
= RemotePort
;
2631 Node
->Protocol
= Protocol
;
2634 // Set default value to IPAddressOrigin, PrefixLength.
2635 // Set the Gateway IP address to unspecified address.
2637 Node
->IpAddressOrigin
= 0;
2638 Node
->PrefixLength
= IP6_PREFIX_LENGTH
;
2639 ZeroMem (&Node
->GatewayIpAddress
, sizeof (EFI_IPv6_ADDRESS
));
2643 Find the UNDI/SNP handle from controller and protocol GUID.
2645 For example, IP will open a MNP child to transmit/receive
2646 packets, when MNP is stopped, IP should also be stopped. IP
2647 needs to find its own private data which is related the IP's
2648 service binding instance that is install on UNDI/SNP handle.
2649 Now, the controller is either a MNP or ARP child handle. But
2650 IP opens these handle BY_DRIVER, use that info, we can get the
2653 @param[in] Controller Then protocol handle to check.
2654 @param[in] ProtocolGuid The protocol that is related with the handle.
2656 @return The UNDI/SNP handle or NULL for errors.
2661 NetLibGetNicHandle (
2662 IN EFI_HANDLE Controller
,
2663 IN EFI_GUID
*ProtocolGuid
2666 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY
*OpenBuffer
;
2672 Status
= gBS
->OpenProtocolInformation (
2679 if (EFI_ERROR (Status
)) {
2685 for (Index
= 0; Index
< OpenCount
; Index
++) {
2686 if ((OpenBuffer
[Index
].Attributes
& EFI_OPEN_PROTOCOL_BY_DRIVER
) != 0) {
2687 Handle
= OpenBuffer
[Index
].ControllerHandle
;
2692 gBS
->FreePool (OpenBuffer
);
2697 Convert one Null-terminated ASCII string (decimal dotted) to EFI_IPv4_ADDRESS.
2699 @param[in] String The pointer to the Ascii string.
2700 @param[out] Ip4Address The pointer to the converted IPv4 address.
2702 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2703 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2708 NetLibAsciiStrToIp4 (
2709 IN CONST CHAR8
*String
,
2710 OUT EFI_IPv4_ADDRESS
*Ip4Address
2718 if ((String
== NULL
) || (Ip4Address
== NULL
)) {
2719 return EFI_INVALID_PARAMETER
;
2722 Ip4Str
= (CHAR8
*) String
;
2724 for (Index
= 0; Index
< 4; Index
++) {
2727 while ((*Ip4Str
!= '\0') && (*Ip4Str
!= '.')) {
2732 // The IPv4 address is X.X.X.X
2734 if (*Ip4Str
== '.') {
2736 return EFI_INVALID_PARAMETER
;
2740 return EFI_INVALID_PARAMETER
;
2745 // Convert the string to IPv4 address. AsciiStrDecimalToUintn stops at the
2746 // first character that is not a valid decimal character, '.' or '\0' here.
2748 NodeVal
= AsciiStrDecimalToUintn (TempStr
);
2749 if (NodeVal
> 0xFF) {
2750 return EFI_INVALID_PARAMETER
;
2753 Ip4Address
->Addr
[Index
] = (UINT8
) NodeVal
;
2763 Convert one Null-terminated ASCII string to EFI_IPv6_ADDRESS. The format of the
2764 string is defined in RFC 4291 - Text Pepresentation of Addresses.
2766 @param[in] String The pointer to the Ascii string.
2767 @param[out] Ip6Address The pointer to the converted IPv6 address.
2769 @retval EFI_SUCCESS Convert to IPv6 address successfully.
2770 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
2775 NetLibAsciiStrToIp6 (
2776 IN CONST CHAR8
*String
,
2777 OUT EFI_IPv6_ADDRESS
*Ip6Address
2794 if ((String
== NULL
) || (Ip6Address
== NULL
)) {
2795 return EFI_INVALID_PARAMETER
;
2798 Ip6Str
= (CHAR8
*) String
;
2803 // An IPv6 address leading with : looks strange.
2805 if (*Ip6Str
== ':') {
2806 if (*(Ip6Str
+ 1) != ':') {
2807 return EFI_INVALID_PARAMETER
;
2813 ZeroMem (Ip6Address
, sizeof (EFI_IPv6_ADDRESS
));
2821 for (Index
= 0; Index
< 15; Index
= (UINT8
) (Index
+ 2)) {
2824 while ((*Ip6Str
!= '\0') && (*Ip6Str
!= ':')) {
2828 if ((*Ip6Str
== '\0') && (Index
!= 14)) {
2829 return EFI_INVALID_PARAMETER
;
2832 if (*Ip6Str
== ':') {
2833 if (*(Ip6Str
+ 1) == ':') {
2834 if ((NodeCnt
> 6) ||
2835 ((*(Ip6Str
+ 2) != '\0') && (AsciiStrHexToUintn (Ip6Str
+ 2) == 0))) {
2837 // ::0 looks strange. report error to user.
2839 return EFI_INVALID_PARAMETER
;
2841 if ((NodeCnt
== 6) && (*(Ip6Str
+ 2) != '\0') &&
2842 (AsciiStrHexToUintn (Ip6Str
+ 2) != 0)) {
2843 return EFI_INVALID_PARAMETER
;
2847 // Skip the abbreviation part of IPv6 address.
2849 TempStr2
= Ip6Str
+ 2;
2850 while ((*TempStr2
!= '\0')) {
2851 if (*TempStr2
== ':') {
2852 if (*(TempStr2
+ 1) == ':') {
2854 // :: can only appear once in IPv6 address.
2856 return EFI_INVALID_PARAMETER
;
2860 if (TailNodeCnt
>= (AllowedCnt
- NodeCnt
)) {
2862 // :: indicates one or more groups of 16 bits of zeros.
2864 return EFI_INVALID_PARAMETER
;
2874 Ip6Str
= Ip6Str
+ 2;
2876 if (*(Ip6Str
+ 1) == '\0') {
2877 return EFI_INVALID_PARAMETER
;
2881 if ((Short
&& (NodeCnt
> 6)) || (!Short
&& (NodeCnt
> 7))) {
2883 // There are more than 8 groups of 16 bits of zeros.
2885 return EFI_INVALID_PARAMETER
;
2891 // Convert the string to IPv6 address. AsciiStrHexToUintn stops at the first
2892 // character that is not a valid hexadecimal character, ':' or '\0' here.
2894 NodeVal
= AsciiStrHexToUintn (TempStr
);
2895 if ((NodeVal
> 0xFFFF) || (Index
> 14)) {
2896 return EFI_INVALID_PARAMETER
;
2899 if ((*TempStr
== '0') &&
2900 ((*(TempStr
+ 2) == ':') || (*(TempStr
+ 3) == ':') ||
2901 (*(TempStr
+ 2) == '\0') || (*(TempStr
+ 3) == '\0'))) {
2902 return EFI_INVALID_PARAMETER
;
2904 if ((*TempStr
== '0') && (*(TempStr
+ 4) != '\0') &&
2905 (*(TempStr
+ 4) != ':')) {
2906 return EFI_INVALID_PARAMETER
;
2909 if (((*TempStr
== '0') && (*(TempStr
+ 1) == '0') &&
2910 ((*(TempStr
+ 2) == ':') || (*(TempStr
+ 2) == '\0'))) ||
2911 ((*TempStr
== '0') && (*(TempStr
+ 1) == '0') && (*(TempStr
+ 2) == '0') &&
2912 ((*(TempStr
+ 3) == ':') || (*(TempStr
+ 3) == '\0')))) {
2913 return EFI_INVALID_PARAMETER
;
2918 while ((TempStr
[Cnt
] != ':') && (TempStr
[Cnt
] != '\0')) {
2921 if (LeadZeroCnt
== 0) {
2922 if ((Cnt
== 4) && (*TempStr
== '0')) {
2926 if ((Cnt
!= 0) && (Cnt
< 4)) {
2931 if ((Cnt
== 4) && (*TempStr
== '0') && !LeadZero
) {
2932 return EFI_INVALID_PARAMETER
;
2934 if ((Cnt
!= 0) && (Cnt
< 4) && LeadZero
) {
2935 return EFI_INVALID_PARAMETER
;
2939 Ip6Address
->Addr
[Index
] = (UINT8
) (NodeVal
>> 8);
2940 Ip6Address
->Addr
[Index
+ 1] = (UINT8
) (NodeVal
& 0xFF);
2943 // Skip the groups of zeros by ::
2945 if (Short
&& Update
) {
2946 Index
= (UINT8
) (16 - (TailNodeCnt
+ 2) * 2);
2951 if ((!Short
&& Index
!= 16) || (*Ip6Str
!= '\0')) {
2952 return EFI_INVALID_PARAMETER
;
2960 Convert one Null-terminated Unicode string (decimal dotted) to EFI_IPv4_ADDRESS.
2962 @param[in] String The pointer to the Ascii string.
2963 @param[out] Ip4Address The pointer to the converted IPv4 address.
2965 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2966 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2967 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
2973 IN CONST CHAR16
*String
,
2974 OUT EFI_IPv4_ADDRESS
*Ip4Address
2980 if ((String
== NULL
) || (Ip4Address
== NULL
)) {
2981 return EFI_INVALID_PARAMETER
;
2984 Ip4Str
= (CHAR8
*) AllocatePool ((StrLen (String
) + 1) * sizeof (CHAR8
));
2985 if (Ip4Str
== NULL
) {
2986 return EFI_OUT_OF_RESOURCES
;
2989 UnicodeStrToAsciiStr (String
, Ip4Str
);
2991 Status
= NetLibAsciiStrToIp4 (Ip4Str
, Ip4Address
);
3000 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS. The format of
3001 the string is defined in RFC 4291 - Text Pepresentation of Addresses.
3003 @param[in] String The pointer to the Ascii string.
3004 @param[out] Ip6Address The pointer to the converted IPv6 address.
3006 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3007 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3008 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3014 IN CONST CHAR16
*String
,
3015 OUT EFI_IPv6_ADDRESS
*Ip6Address
3021 if ((String
== NULL
) || (Ip6Address
== NULL
)) {
3022 return EFI_INVALID_PARAMETER
;
3025 Ip6Str
= (CHAR8
*) AllocatePool ((StrLen (String
) + 1) * sizeof (CHAR8
));
3026 if (Ip6Str
== NULL
) {
3027 return EFI_OUT_OF_RESOURCES
;
3030 UnicodeStrToAsciiStr (String
, Ip6Str
);
3032 Status
= NetLibAsciiStrToIp6 (Ip6Str
, Ip6Address
);
3040 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS and prefix length.
3041 The format of the string is defined in RFC 4291 - Text Pepresentation of Addresses
3042 Prefixes: ipv6-address/prefix-length.
3044 @param[in] String The pointer to the Ascii string.
3045 @param[out] Ip6Address The pointer to the converted IPv6 address.
3046 @param[out] PrefixLength The pointer to the converted prefix length.
3048 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3049 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3050 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3055 NetLibStrToIp6andPrefix (
3056 IN CONST CHAR16
*String
,
3057 OUT EFI_IPv6_ADDRESS
*Ip6Address
,
3058 OUT UINT8
*PrefixLength
3067 if ((String
== NULL
) || (Ip6Address
== NULL
) || (PrefixLength
== NULL
)) {
3068 return EFI_INVALID_PARAMETER
;
3071 Ip6Str
= (CHAR8
*) AllocatePool ((StrLen (String
) + 1) * sizeof (CHAR8
));
3072 if (Ip6Str
== NULL
) {
3073 return EFI_OUT_OF_RESOURCES
;
3076 UnicodeStrToAsciiStr (String
, Ip6Str
);
3079 // Get the sub string describing prefix length.
3082 while (*TempStr
!= '\0' && (*TempStr
!= '/')) {
3086 if (*TempStr
== '/') {
3087 PrefixStr
= TempStr
+ 1;
3093 // Get the sub string describing IPv6 address and convert it.
3097 Status
= NetLibAsciiStrToIp6 (Ip6Str
, Ip6Address
);
3098 if (EFI_ERROR (Status
)) {
3103 // If input string doesn't indicate the prefix length, return 0xff.
3108 // Convert the string to prefix length
3110 if (PrefixStr
!= NULL
) {
3112 Status
= EFI_INVALID_PARAMETER
;
3114 while (*PrefixStr
!= '\0') {
3115 if (NET_IS_DIGIT (*PrefixStr
)) {
3116 Length
= (UINT8
) (Length
* 10 + (*PrefixStr
- '0'));
3117 if (Length
>= IP6_PREFIX_NUM
) {
3128 *PrefixLength
= Length
;
3129 Status
= EFI_SUCCESS
;
3139 Convert one EFI_IPv6_ADDRESS to Null-terminated Unicode string.
3140 The text representation of address is defined in RFC 4291.
3142 @param[in] Ip6Address The pointer to the IPv6 address.
3143 @param[out] String The buffer to return the converted string.
3144 @param[in] StringSize The length in bytes of the input String.
3146 @retval EFI_SUCCESS Convert to string successfully.
3147 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
3148 @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small for the result. BufferSize has been
3149 updated with the size needed to complete the request.
3154 IN EFI_IPv6_ADDRESS
*Ip6Address
,
3161 UINTN LongestZerosStart
;
3162 UINTN LongestZerosLength
;
3163 UINTN CurrentZerosStart
;
3164 UINTN CurrentZerosLength
;
3165 CHAR16 Buffer
[sizeof"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"];
3168 if (Ip6Address
== NULL
|| String
== NULL
|| StringSize
== 0) {
3169 return EFI_INVALID_PARAMETER
;
3173 // Convert the UINT8 array to an UINT16 array for easy handling.
3175 ZeroMem (Ip6Addr
, sizeof (Ip6Addr
));
3176 for (Index
= 0; Index
< 16; Index
++) {
3177 Ip6Addr
[Index
/ 2] |= (Ip6Address
->Addr
[Index
] << ((1 - (Index
% 2)) << 3));
3181 // Find the longest zeros and mark it.
3183 CurrentZerosStart
= DEFAULT_ZERO_START
;
3184 CurrentZerosLength
= 0;
3185 LongestZerosStart
= DEFAULT_ZERO_START
;
3186 LongestZerosLength
= 0;
3187 for (Index
= 0; Index
< 8; Index
++) {
3188 if (Ip6Addr
[Index
] == 0) {
3189 if (CurrentZerosStart
== DEFAULT_ZERO_START
) {
3190 CurrentZerosStart
= Index
;
3191 CurrentZerosLength
= 1;
3193 CurrentZerosLength
++;
3196 if (CurrentZerosStart
!= DEFAULT_ZERO_START
) {
3197 if (CurrentZerosLength
> 2 && (LongestZerosStart
== (DEFAULT_ZERO_START
) || CurrentZerosLength
> LongestZerosLength
)) {
3198 LongestZerosStart
= CurrentZerosStart
;
3199 LongestZerosLength
= CurrentZerosLength
;
3201 CurrentZerosStart
= DEFAULT_ZERO_START
;
3202 CurrentZerosLength
= 0;
3207 if (CurrentZerosStart
!= DEFAULT_ZERO_START
&& CurrentZerosLength
> 2) {
3208 if (LongestZerosStart
== DEFAULT_ZERO_START
|| LongestZerosLength
< CurrentZerosLength
) {
3209 LongestZerosStart
= CurrentZerosStart
;
3210 LongestZerosLength
= CurrentZerosLength
;
3215 for (Index
= 0; Index
< 8; Index
++) {
3216 if (LongestZerosStart
!= DEFAULT_ZERO_START
&& Index
>= LongestZerosStart
&& Index
< LongestZerosStart
+ LongestZerosLength
) {
3217 if (Index
== LongestZerosStart
) {
3225 Ptr
+= UnicodeSPrint(Ptr
, 10, L
"%x", Ip6Addr
[Index
]);
3228 if (LongestZerosStart
!= DEFAULT_ZERO_START
&& LongestZerosStart
+ LongestZerosLength
== 8) {
3233 if ((UINTN
)Ptr
- (UINTN
)Buffer
> StringSize
) {
3234 return EFI_BUFFER_TOO_SMALL
;
3237 StrCpyS (String
, StringSize
/ sizeof (CHAR16
), Buffer
);
3243 This function obtains the system guid from the smbios table.
3245 @param[out] SystemGuid The pointer of the returned system guid.
3247 @retval EFI_SUCCESS Successfully obtained the system guid.
3248 @retval EFI_NOT_FOUND Did not find the SMBIOS table.
3253 NetLibGetSystemGuid (
3254 OUT EFI_GUID
*SystemGuid
3258 SMBIOS_TABLE_ENTRY_POINT
*SmbiosTable
;
3259 SMBIOS_STRUCTURE_POINTER Smbios
;
3260 SMBIOS_STRUCTURE_POINTER SmbiosEnd
;
3264 Status
= EfiGetSystemConfigurationTable (&gEfiSmbiosTableGuid
, (VOID
**) &SmbiosTable
);
3266 if (EFI_ERROR (Status
) || SmbiosTable
== NULL
) {
3267 return EFI_NOT_FOUND
;
3270 Smbios
.Hdr
= (SMBIOS_STRUCTURE
*) (UINTN
) SmbiosTable
->TableAddress
;
3271 SmbiosEnd
.Raw
= (UINT8
*) (UINTN
) (SmbiosTable
->TableAddress
+ SmbiosTable
->TableLength
);
3274 if (Smbios
.Hdr
->Type
== 1) {
3275 if (Smbios
.Hdr
->Length
< 0x19) {
3277 // Older version did not support UUID.
3279 return EFI_NOT_FOUND
;
3283 // SMBIOS tables are byte packed so we need to do a byte copy to
3284 // prevend alignment faults on Itanium-based platform.
3286 CopyMem (SystemGuid
, &Smbios
.Type1
->Uuid
, sizeof (EFI_GUID
));
3291 // Go to the next SMBIOS structure. Each SMBIOS structure may include 2 parts:
3292 // 1. Formatted section; 2. Unformatted string section. So, 2 steps are needed
3293 // to skip one SMBIOS structure.
3297 // Step 1: Skip over formatted section.
3299 String
= (CHAR8
*) (Smbios
.Raw
+ Smbios
.Hdr
->Length
);
3302 // Step 2: Skip over unformated string section.
3306 // Each string is terminated with a NULL(00h) BYTE and the sets of strings
3307 // is terminated with an additional NULL(00h) BYTE.
3309 for ( ; *String
!= 0; String
++) {
3312 if (*(UINT8
*)++String
== 0) {
3314 // Pointer to the next SMBIOS structure.
3316 Smbios
.Raw
= (UINT8
*)++String
;
3320 } while (Smbios
.Raw
< SmbiosEnd
.Raw
);
3321 return EFI_NOT_FOUND
;