4 Copyright (c) 2005 - 2012, 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/HiiConfigRouting.h>
23 #include <Protocol/ComponentName.h>
24 #include <Protocol/ComponentName2.h>
25 #include <Protocol/HiiConfigAccess.h>
27 #include <Guid/NicIp4ConfigNvData.h>
28 #include <Guid/SmBios.h>
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/HiiLib.h>
39 #include <Library/PrintLib.h>
40 #include <Library/UefiLib.h>
42 #define NIC_ITEM_CONFIG_SIZE sizeof (NIC_IP4_CONFIG_INFO) + sizeof (EFI_IP4_ROUTE_TABLE) * MAX_IP4_CONFIG_IN_VARIABLE
43 #define DEFAULT_ZERO_START ((UINTN) ~0)
46 // All the supported IP4 maskes in host byte order.
48 GLOBAL_REMOVE_IF_UNREFERENCED IP4_ADDR gIp4AllMasks
[IP4_MASK_NUM
] = {
87 GLOBAL_REMOVE_IF_UNREFERENCED EFI_IPv4_ADDRESS mZeroIp4Addr
= {{0, 0, 0, 0}};
90 // Any error level digitally larger than mNetDebugLevelMax
91 // will be silently discarded.
93 GLOBAL_REMOVE_IF_UNREFERENCED UINTN mNetDebugLevelMax
= NETDEBUG_LEVEL_ERROR
;
94 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogPacketSeq
= 0xDEADBEEF;
97 // You can change mSyslogDstMac mSyslogDstIp and mSyslogSrcIp
98 // here to direct the syslog packets to the syslog deamon. The
99 // default is broadcast to both the ethernet and IP.
101 GLOBAL_REMOVE_IF_UNREFERENCED UINT8 mSyslogDstMac
[NET_ETHER_ADDR_LEN
] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
102 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogDstIp
= 0xffffffff;
103 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogSrcIp
= 0;
105 GLOBAL_REMOVE_IF_UNREFERENCED CHAR8
*mMonthName
[] = {
121 // VLAN device path node template
123 GLOBAL_REMOVE_IF_UNREFERENCED VLAN_DEVICE_PATH mNetVlanDevicePathTemplate
= {
125 MESSAGING_DEVICE_PATH
,
128 (UINT8
) (sizeof (VLAN_DEVICE_PATH
)),
129 (UINT8
) ((sizeof (VLAN_DEVICE_PATH
)) >> 8)
136 Locate the handles that support SNP, then open one of them
137 to send the syslog packets. The caller isn't required to close
138 the SNP after use because the SNP is opened by HandleProtocol.
140 @return The point to SNP if one is properly openned. Otherwise NULL
143 EFI_SIMPLE_NETWORK_PROTOCOL
*
148 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
155 // Locate the handles which has SNP installed.
158 Status
= gBS
->LocateHandleBuffer (
160 &gEfiSimpleNetworkProtocolGuid
,
166 if (EFI_ERROR (Status
) || (HandleCount
== 0)) {
171 // Try to open one of the ethernet SNP protocol to send packet
175 for (Index
= 0; Index
< HandleCount
; Index
++) {
176 Status
= gBS
->HandleProtocol (
178 &gEfiSimpleNetworkProtocolGuid
,
182 if ((Status
== EFI_SUCCESS
) && (Snp
!= NULL
) &&
183 (Snp
->Mode
->IfType
== NET_IFTYPE_ETHERNET
) &&
184 (Snp
->Mode
->MaxPacketSize
>= NET_SYSLOG_PACKET_LEN
)) {
197 Transmit a syslog packet synchronously through SNP. The Packet
198 already has the ethernet header prepended. This function should
199 fill in the source MAC because it will try to locate a SNP each
200 time it is called to avoid the problem if SNP is unloaded.
201 This code snip is copied from MNP.
203 @param[in] Packet The Syslog packet
204 @param[in] Length The length of the packet
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.
217 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
220 EFI_EVENT TimeoutEvent
;
223 Snp
= SyslogLocateSnp ();
226 return EFI_DEVICE_ERROR
;
229 Ether
= (ETHER_HEAD
*) Packet
;
230 CopyMem (Ether
->SrcMac
, Snp
->Mode
->CurrentAddress
.Addr
, NET_ETHER_ADDR_LEN
);
233 // Start the timeout event.
235 Status
= gBS
->CreateEvent (
243 if (EFI_ERROR (Status
)) {
247 Status
= gBS
->SetTimer (TimeoutEvent
, TimerRelative
, NET_SYSLOG_TX_TIMEOUT
);
249 if (EFI_ERROR (Status
)) {
255 // Transmit the packet through SNP.
257 Status
= Snp
->Transmit (Snp
, 0, Length
, Packet
, NULL
, NULL
, NULL
);
259 if ((Status
!= EFI_SUCCESS
) && (Status
!= EFI_NOT_READY
)) {
260 Status
= EFI_DEVICE_ERROR
;
265 // If Status is EFI_SUCCESS, the packet is put in the transmit queue.
266 // if Status is EFI_NOT_READY, the transmit engine of the network
267 // interface is busy. Both need to sync SNP.
273 // Get the recycled transmit buffer status.
275 Snp
->GetStatus (Snp
, NULL
, (VOID
**) &TxBuf
);
277 if (!EFI_ERROR (gBS
->CheckEvent (TimeoutEvent
))) {
278 Status
= EFI_TIMEOUT
;
282 } while (TxBuf
== NULL
);
284 if ((Status
== EFI_SUCCESS
) || (Status
== EFI_TIMEOUT
)) {
289 // Status is EFI_NOT_READY. Restart the timer event and
290 // call Snp->Transmit again.
292 gBS
->SetTimer (TimeoutEvent
, TimerRelative
, NET_SYSLOG_TX_TIMEOUT
);
295 gBS
->SetTimer (TimeoutEvent
, TimerCancel
, 0);
298 gBS
->CloseEvent (TimeoutEvent
);
303 Build a syslog packet, including the Ethernet/Ip/Udp headers
306 @param[in] Level Syslog servity level
307 @param[in] Module The module that generates the log
308 @param[in] File The file that contains the current log
309 @param[in] Line The line of code in the File that contains the current log
310 @param[in] Message The log message
311 @param[in] BufLen The lenght of the Buf
312 @param[out] Buf The buffer to put the packet data
314 @return The length of the syslog packet built.
330 EFI_UDP_HEADER
*Udp4
;
336 // Fill in the Ethernet header. Leave alone the source MAC.
337 // SyslogSendPacket will fill in the address for us.
339 Ether
= (ETHER_HEAD
*) Buf
;
340 CopyMem (Ether
->DstMac
, mSyslogDstMac
, NET_ETHER_ADDR_LEN
);
341 ZeroMem (Ether
->SrcMac
, NET_ETHER_ADDR_LEN
);
343 Ether
->EtherType
= HTONS (0x0800); // IPv4 protocol
345 Buf
+= sizeof (ETHER_HEAD
);
346 BufLen
-= sizeof (ETHER_HEAD
);
349 // Fill in the IP header
351 Ip4
= (IP4_HEAD
*) Buf
;
356 Ip4
->Id
= (UINT16
) mSyslogPacketSeq
;
359 Ip4
->Protocol
= 0x11;
361 Ip4
->Src
= mSyslogSrcIp
;
362 Ip4
->Dst
= mSyslogDstIp
;
364 Buf
+= sizeof (IP4_HEAD
);
365 BufLen
-= sizeof (IP4_HEAD
);
368 // Fill in the UDP header, Udp checksum is optional. Leave it zero.
370 Udp4
= (EFI_UDP_HEADER
*) Buf
;
371 Udp4
->SrcPort
= HTONS (514);
372 Udp4
->DstPort
= HTONS (514);
376 Buf
+= sizeof (EFI_UDP_HEADER
);
377 BufLen
-= sizeof (EFI_UDP_HEADER
);
380 // Build the syslog message body with <PRI> Timestamp machine module Message
382 Pri
= ((NET_SYSLOG_FACILITY
& 31) << 3) | (Level
& 7);
383 gRT
->GetTime (&Time
, NULL
);
384 ASSERT ((Time
.Month
<= 12) && (Time
.Month
>= 1));
387 // Use %a to format the ASCII strings, %s to format UNICODE strings
390 Len
+= (UINT32
) AsciiSPrint (
393 "<%d> %a %d %d:%d:%d ",
395 mMonthName
[Time
.Month
-1],
403 Len
+= (UINT32
) AsciiSPrint (
406 "Tiano %a: %a (Line: %d File: %a)",
415 // OK, patch the IP length/checksum and UDP length fields.
417 Len
+= sizeof (EFI_UDP_HEADER
);
418 Udp4
->Length
= HTONS ((UINT16
) Len
);
420 Len
+= sizeof (IP4_HEAD
);
421 Ip4
->TotalLen
= HTONS ((UINT16
) Len
);
422 Ip4
->Checksum
= (UINT16
) (~NetblockChecksum ((UINT8
*) Ip4
, sizeof (IP4_HEAD
)));
424 return Len
+ sizeof (ETHER_HEAD
);
428 Allocate a buffer, then format the message to it. This is a
429 help function for the NET_DEBUG_XXX macros. The PrintArg of
430 these macros treats the variable length print parameters as a
431 single parameter, and pass it to the NetDebugASPrint. For
432 example, NET_DEBUG_TRACE ("Tcp", ("State transit to %a\n", Name))
436 NETDEBUG_LEVEL_TRACE,
440 NetDebugASPrint ("State transit to %a\n", Name)
443 @param Format The ASCII format string.
444 @param ... The variable length parameter whose format is determined
445 by the Format string.
447 @return The buffer containing the formatted message,
448 or NULL if failed to allocate memory.
461 Buf
= (CHAR8
*) AllocatePool (NET_DEBUG_MSG_LEN
);
467 VA_START (Marker
, Format
);
468 AsciiVSPrint (Buf
, NET_DEBUG_MSG_LEN
, Format
, Marker
);
475 Builds an UDP4 syslog packet and send it using SNP.
477 This function will locate a instance of SNP then send the message through it.
478 Because it isn't open the SNP BY_DRIVER, apply caution when using it.
480 @param Level The servity level of the message.
481 @param Module The Moudle that generates the log.
482 @param File The file that contains the log.
483 @param Line The exact line that contains the log.
484 @param Message The user message to log.
486 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
487 @retval EFI_OUT_OF_RESOURCES Failed to allocate memory for the packet
488 @retval EFI_SUCCESS The log is discard because that it is more verbose
489 than the mNetDebugLevelMax. Or, it has been sent out.
506 // Check whether the message should be sent out
508 if (Message
== NULL
) {
509 return EFI_INVALID_PARAMETER
;
512 if (Level
> mNetDebugLevelMax
) {
513 Status
= EFI_SUCCESS
;
518 // Allocate a maxium of 1024 bytes, the caller should ensure
519 // that the message plus the ethernet/ip/udp header is shorter
522 Packet
= (CHAR8
*) AllocatePool (NET_SYSLOG_PACKET_LEN
);
524 if (Packet
== NULL
) {
525 Status
= EFI_OUT_OF_RESOURCES
;
530 // Build the message: Ethernet header + IP header + Udp Header + user data
532 Len
= SyslogBuildPacket (
538 NET_SYSLOG_PACKET_LEN
,
543 Status
= SyslogSendPacket (Packet
, Len
);
551 Return the length of the mask.
553 Return the length of the mask, the correct value is from 0 to 32.
554 If the mask is invalid, return the invalid length 33, which is IP4_MASK_NUM.
555 NetMask is in the host byte order.
557 @param[in] NetMask The netmask to get the length from.
559 @return The length of the netmask, IP4_MASK_NUM if the mask is invalid.
570 for (Index
= 0; Index
< IP4_MASK_NUM
; Index
++) {
571 if (NetMask
== gIp4AllMasks
[Index
]) {
582 Return the class of the IP address, such as class A, B, C.
583 Addr is in host byte order.
585 The address of class A starts with 0.
586 If the address belong to class A, return IP4_ADDR_CLASSA.
587 The address of class B starts with 10.
588 If the address belong to class B, return IP4_ADDR_CLASSB.
589 The address of class C starts with 110.
590 If the address belong to class C, return IP4_ADDR_CLASSC.
591 The address of class D starts with 1110.
592 If the address belong to class D, return IP4_ADDR_CLASSD.
593 The address of class E starts with 1111.
594 If the address belong to class E, return IP4_ADDR_CLASSE.
597 @param[in] Addr The address to get the class from.
599 @return IP address class, such as IP4_ADDR_CLASSA.
610 ByteOne
= (UINT8
) (Addr
>> 24);
612 if ((ByteOne
& 0x80) == 0) {
613 return IP4_ADDR_CLASSA
;
615 } else if ((ByteOne
& 0xC0) == 0x80) {
616 return IP4_ADDR_CLASSB
;
618 } else if ((ByteOne
& 0xE0) == 0xC0) {
619 return IP4_ADDR_CLASSC
;
621 } else if ((ByteOne
& 0xF0) == 0xE0) {
622 return IP4_ADDR_CLASSD
;
625 return IP4_ADDR_CLASSE
;
632 Check whether the IP is a valid unicast address according to
633 the netmask. If NetMask is zero, use the IP address's class to get the default mask.
635 If Ip is 0, IP is not a valid unicast address.
636 Class D address is used for multicasting and class E address is reserved for future. If Ip
637 belongs to class D or class E, IP is not a valid unicast address.
638 If all bits of the host address of IP are 0 or 1, IP is also not a valid unicast address.
640 @param[in] Ip The IP to check against.
641 @param[in] NetMask The mask of the IP.
643 @return TRUE if IP is a valid unicast address on the network, otherwise FALSE.
655 Class
= NetGetIpClass (Ip
);
657 if ((Ip
== 0) || (Class
>= IP4_ADDR_CLASSD
)) {
662 NetMask
= gIp4AllMasks
[Class
<< 3];
665 if (((Ip
&~NetMask
) == ~NetMask
) || ((Ip
&~NetMask
) == 0)) {
673 Check whether the incoming IPv6 address is a valid unicast address.
675 If the address is a multicast address has binary 0xFF at the start, it is not
676 a valid unicast address. If the address is unspecified ::, it is not a valid
677 unicast address to be assigned to any node. If the address is loopback address
678 ::1, it is also not a valid unicast address to be assigned to any physical
681 @param[in] Ip6 The IPv6 address to check against.
683 @return TRUE if Ip6 is a valid unicast address on the network, otherwise FALSE.
688 NetIp6IsValidUnicast (
689 IN EFI_IPv6_ADDRESS
*Ip6
695 if (Ip6
->Addr
[0] == 0xFF) {
699 for (Index
= 0; Index
< 15; Index
++) {
700 if (Ip6
->Addr
[Index
] != 0) {
705 Byte
= Ip6
->Addr
[Index
];
707 if (Byte
== 0x0 || Byte
== 0x1) {
715 Check whether the incoming Ipv6 address is the unspecified address or not.
717 @param[in] Ip6 - Ip6 address, in network order.
719 @retval TRUE - Yes, unspecified
725 NetIp6IsUnspecifiedAddr (
726 IN EFI_IPv6_ADDRESS
*Ip6
731 for (Index
= 0; Index
< 16; Index
++) {
732 if (Ip6
->Addr
[Index
] != 0) {
741 Check whether the incoming Ipv6 address is a link-local address.
743 @param[in] Ip6 - Ip6 address, in network order.
745 @retval TRUE - Yes, link-local address
751 NetIp6IsLinkLocalAddr (
752 IN EFI_IPv6_ADDRESS
*Ip6
757 ASSERT (Ip6
!= NULL
);
759 if (Ip6
->Addr
[0] != 0xFE) {
763 if (Ip6
->Addr
[1] != 0x80) {
767 for (Index
= 2; Index
< 8; Index
++) {
768 if (Ip6
->Addr
[Index
] != 0) {
777 Check whether the Ipv6 address1 and address2 are on the connected network.
779 @param[in] Ip1 - Ip6 address1, in network order.
780 @param[in] Ip2 - Ip6 address2, in network order.
781 @param[in] PrefixLength - The prefix length of the checking net.
783 @retval TRUE - Yes, connected.
790 EFI_IPv6_ADDRESS
*Ip1
,
791 EFI_IPv6_ADDRESS
*Ip2
,
799 ASSERT ((Ip1
!= NULL
) && (Ip2
!= NULL
) && (PrefixLength
< IP6_PREFIX_NUM
));
801 if (PrefixLength
== 0) {
805 Byte
= (UINT8
) (PrefixLength
/ 8);
806 Bit
= (UINT8
) (PrefixLength
% 8);
808 if (CompareMem (Ip1
, Ip2
, Byte
) != 0) {
813 Mask
= (UINT8
) (0xFF << (8 - Bit
));
816 if ((Ip1
->Addr
[Byte
] & Mask
) != (Ip2
->Addr
[Byte
] & Mask
)) {
826 Switches the endianess of an IPv6 address
828 This function swaps the bytes in a 128-bit IPv6 address to switch the value
829 from little endian to big endian or vice versa. The byte swapped value is
832 @param Ip6 Points to an IPv6 address
834 @return The byte swapped IPv6 address.
840 EFI_IPv6_ADDRESS
*Ip6
846 CopyMem (&High
, Ip6
, sizeof (UINT64
));
847 CopyMem (&Low
, &Ip6
->Addr
[8], sizeof (UINT64
));
849 High
= SwapBytes64 (High
);
850 Low
= SwapBytes64 (Low
);
852 CopyMem (Ip6
, &Low
, sizeof (UINT64
));
853 CopyMem (&Ip6
->Addr
[8], &High
, sizeof (UINT64
));
859 Initialize a random seed using current time.
861 Get current time first. Then initialize a random seed based on some basic
862 mathematics operation on the hour, day, minute, second, nanosecond and year
865 @return The random seed initialized with current time.
877 gRT
->GetTime (&Time
, NULL
);
878 Seed
= (~Time
.Hour
<< 24 | Time
.Day
<< 16 | Time
.Minute
<< 8 | Time
.Second
);
879 Seed
^= Time
.Nanosecond
;
880 Seed
^= Time
.Year
<< 7;
887 Extract a UINT32 from a byte stream.
889 Copy a UINT32 from a byte stream, then converts it from Network
890 byte order to host byte order. Use this function to avoid alignment error.
892 @param[in] Buf The buffer to extract the UINT32.
894 @return The UINT32 extracted.
905 CopyMem (&Value
, Buf
, sizeof (UINT32
));
906 return NTOHL (Value
);
911 Put a UINT32 to the byte stream in network byte order.
913 Converts a UINT32 from host byte order to network byte order. Then copy it to the
916 @param[in, out] Buf The buffer to put the UINT32.
917 @param[in] Data The data to be converted and put into the byte stream.
928 CopyMem (Buf
, &Data
, sizeof (UINT32
));
933 Remove the first node entry on the list, and return the removed node entry.
935 Removes the first node Entry from a doubly linked list. It is up to the caller of
936 this function to release the memory used by the first node if that is required. On
937 exit, the removed node is returned.
939 If Head is NULL, then ASSERT().
940 If Head was not initialized, then ASSERT().
941 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
942 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
945 @param[in, out] Head The list header.
947 @return The first node entry that is removed from the list, NULL if the list is empty.
953 IN OUT LIST_ENTRY
*Head
958 ASSERT (Head
!= NULL
);
960 if (IsListEmpty (Head
)) {
964 First
= Head
->ForwardLink
;
965 Head
->ForwardLink
= First
->ForwardLink
;
966 First
->ForwardLink
->BackLink
= Head
;
969 First
->ForwardLink
= (LIST_ENTRY
*) NULL
;
970 First
->BackLink
= (LIST_ENTRY
*) NULL
;
978 Remove the last node entry on the list and and return the removed node entry.
980 Removes the last node entry from a doubly linked list. It is up to the caller of
981 this function to release the memory used by the first node if that is required. On
982 exit, the removed node is returned.
984 If Head is NULL, then ASSERT().
985 If Head was not initialized, then ASSERT().
986 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
987 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
990 @param[in, out] Head The list head.
992 @return The last node entry that is removed from the list, NULL if the list is empty.
998 IN OUT LIST_ENTRY
*Head
1003 ASSERT (Head
!= NULL
);
1005 if (IsListEmpty (Head
)) {
1009 Last
= Head
->BackLink
;
1010 Head
->BackLink
= Last
->BackLink
;
1011 Last
->BackLink
->ForwardLink
= Head
;
1014 Last
->ForwardLink
= (LIST_ENTRY
*) NULL
;
1015 Last
->BackLink
= (LIST_ENTRY
*) NULL
;
1023 Insert a new node entry after a designated node entry of a doubly linked list.
1025 Inserts a new node entry donated by NewEntry after the node entry donated by PrevEntry
1026 of the doubly linked list.
1028 @param[in, out] PrevEntry The previous entry to insert after.
1029 @param[in, out] NewEntry The new entry to insert.
1034 NetListInsertAfter (
1035 IN OUT LIST_ENTRY
*PrevEntry
,
1036 IN OUT LIST_ENTRY
*NewEntry
1039 NewEntry
->BackLink
= PrevEntry
;
1040 NewEntry
->ForwardLink
= PrevEntry
->ForwardLink
;
1041 PrevEntry
->ForwardLink
->BackLink
= NewEntry
;
1042 PrevEntry
->ForwardLink
= NewEntry
;
1047 Insert a new node entry before a designated node entry of a doubly linked list.
1049 Inserts a new node entry donated by NewEntry after the node entry donated by PostEntry
1050 of the doubly linked list.
1052 @param[in, out] PostEntry The entry to insert before.
1053 @param[in, out] NewEntry The new entry to insert.
1058 NetListInsertBefore (
1059 IN OUT LIST_ENTRY
*PostEntry
,
1060 IN OUT LIST_ENTRY
*NewEntry
1063 NewEntry
->ForwardLink
= PostEntry
;
1064 NewEntry
->BackLink
= PostEntry
->BackLink
;
1065 PostEntry
->BackLink
->ForwardLink
= NewEntry
;
1066 PostEntry
->BackLink
= NewEntry
;
1070 Safe destroy nodes in a linked list, and return the length of the list after all possible operations finished.
1072 Destroy network child instance list by list traversals is not safe due to graph dependencies between nodes.
1073 This function performs a safe traversal to destroy these nodes by checking to see if the node being destroyed
1074 has been removed from the list or not.
1075 If it has been removed, then restart the traversal from the head.
1076 If it hasn't been removed, then continue with the next node directly.
1077 This function will end the iterate and return the CallBack's last return value if error happens,
1078 or retrun EFI_SUCCESS if 2 complete passes are made with no changes in the number of children in the list.
1080 @param[in] List The head of the list.
1081 @param[in] CallBack Pointer to the callback function to destroy one node in the list.
1082 @param[in] Context Pointer to the callback function's context: corresponds to the
1083 parameter Context in NET_DESTROY_LINK_LIST_CALLBACK.
1084 @param[out] ListLength The length of the link list if the function returns successfully.
1086 @retval EFI_SUCCESS Two complete passes are made with no changes in the number of children.
1087 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
1088 @retval Others Return the CallBack's last return value.
1093 NetDestroyLinkList (
1094 IN LIST_ENTRY
*List
,
1095 IN NET_DESTROY_LINK_LIST_CALLBACK CallBack
,
1096 IN VOID
*Context
, OPTIONAL
1097 OUT UINTN
*ListLength OPTIONAL
1100 UINTN PreviousLength
;
1106 if (List
== NULL
|| CallBack
== NULL
) {
1107 return EFI_INVALID_PARAMETER
;
1112 PreviousLength
= Length
;
1113 Entry
= GetFirstNode (List
);
1114 while (!IsNull (List
, Entry
)) {
1115 Status
= CallBack (Entry
, Context
);
1116 if (EFI_ERROR (Status
)) {
1120 // Walk through the list to see whether the Entry has been removed or not.
1121 // If the Entry still exists, just try to destroy the next one.
1122 // If not, go back to the start point to iterate the list again.
1124 for (Ptr
= List
->ForwardLink
; Ptr
!= List
; Ptr
= Ptr
->ForwardLink
) {
1130 Entry
= GetNextNode (List
, Entry
);
1132 Entry
= GetFirstNode (List
);
1135 for (Length
= 0, Ptr
= List
->ForwardLink
; Ptr
!= List
; Length
++, Ptr
= Ptr
->ForwardLink
);
1136 } while (Length
!= PreviousLength
);
1138 if (ListLength
!= NULL
) {
1139 *ListLength
= Length
;
1145 This function checks the input Handle to see if it's one of these handles in ChildHandleBuffer.
1147 @param[in] Handle Handle to be checked.
1148 @param[in] NumberOfChildren Number of Handles in ChildHandleBuffer.
1149 @param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
1150 if NumberOfChildren is 0.
1152 @retval TURE Found the input Handle in ChildHandleBuffer.
1153 @retval FALSE Can't find the input Handle in ChildHandleBuffer.
1157 NetIsInHandleBuffer (
1158 IN EFI_HANDLE Handle
,
1159 IN UINTN NumberOfChildren
,
1160 IN EFI_HANDLE
*ChildHandleBuffer OPTIONAL
1165 if (NumberOfChildren
== 0 || ChildHandleBuffer
== NULL
) {
1169 for (Index
= 0; Index
< NumberOfChildren
; Index
++) {
1170 if (Handle
== ChildHandleBuffer
[Index
]) {
1180 Initialize the netmap. Netmap is a reposity to keep the <Key, Value> pairs.
1182 Initialize the forward and backward links of two head nodes donated by Map->Used
1183 and Map->Recycled of two doubly linked lists.
1184 Initializes the count of the <Key, Value> pairs in the netmap to zero.
1186 If Map is NULL, then ASSERT().
1187 If the address of Map->Used is NULL, then ASSERT().
1188 If the address of Map->Recycled is NULl, then ASSERT().
1190 @param[in, out] Map The netmap to initialize.
1199 ASSERT (Map
!= NULL
);
1201 InitializeListHead (&Map
->Used
);
1202 InitializeListHead (&Map
->Recycled
);
1208 To clean up the netmap, that is, release allocated memories.
1210 Removes all nodes of the Used doubly linked list and free memory of all related netmap items.
1211 Removes all nodes of the Recycled doubly linked list and free memory of all related netmap items.
1212 The number of the <Key, Value> pairs in the netmap is set to be zero.
1214 If Map is NULL, then ASSERT().
1216 @param[in, out] Map The netmap to clean up.
1229 ASSERT (Map
!= NULL
);
1231 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, &Map
->Used
) {
1232 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1234 RemoveEntryList (&Item
->Link
);
1237 gBS
->FreePool (Item
);
1240 ASSERT ((Map
->Count
== 0) && IsListEmpty (&Map
->Used
));
1242 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, &Map
->Recycled
) {
1243 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1245 RemoveEntryList (&Item
->Link
);
1246 gBS
->FreePool (Item
);
1249 ASSERT (IsListEmpty (&Map
->Recycled
));
1254 Test whether the netmap is empty and return true if it is.
1256 If the number of the <Key, Value> pairs in the netmap is zero, return TRUE.
1258 If Map is NULL, then ASSERT().
1261 @param[in] Map The net map to test.
1263 @return TRUE if the netmap is empty, otherwise FALSE.
1272 ASSERT (Map
!= NULL
);
1273 return (BOOLEAN
) (Map
->Count
== 0);
1278 Return the number of the <Key, Value> pairs in the netmap.
1280 @param[in] Map The netmap to get the entry number.
1282 @return The entry number in the netmap.
1296 Return one allocated item.
1298 If the Recycled doubly linked list of the netmap is empty, it will try to allocate
1299 a batch of items if there are enough resources and add corresponding nodes to the begining
1300 of the Recycled doubly linked list of the netmap. Otherwise, it will directly remove
1301 the fist node entry of the Recycled doubly linked list and return the corresponding item.
1303 If Map is NULL, then ASSERT().
1305 @param[in, out] Map The netmap to allocate item for.
1307 @return The allocated item. If NULL, the
1308 allocation failed due to resource limit.
1320 ASSERT (Map
!= NULL
);
1322 Head
= &Map
->Recycled
;
1324 if (IsListEmpty (Head
)) {
1325 for (Index
= 0; Index
< NET_MAP_INCREAMENT
; Index
++) {
1326 Item
= AllocatePool (sizeof (NET_MAP_ITEM
));
1336 InsertHeadList (Head
, &Item
->Link
);
1340 Item
= NET_LIST_HEAD (Head
, NET_MAP_ITEM
, Link
);
1341 NetListRemoveHead (Head
);
1348 Allocate an item to save the <Key, Value> pair to the head of the netmap.
1350 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1351 to the beginning of the Used doubly linked list. The number of the <Key, Value>
1352 pairs in the netmap increase by 1.
1354 If Map is NULL, then ASSERT().
1356 @param[in, out] Map The netmap to insert into.
1357 @param[in] Key The user's key.
1358 @param[in] Value The user's value for the key.
1360 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1361 @retval EFI_SUCCESS The item is inserted to the head.
1367 IN OUT NET_MAP
*Map
,
1369 IN VOID
*Value OPTIONAL
1374 ASSERT (Map
!= NULL
);
1376 Item
= NetMapAllocItem (Map
);
1379 return EFI_OUT_OF_RESOURCES
;
1383 Item
->Value
= Value
;
1384 InsertHeadList (&Map
->Used
, &Item
->Link
);
1392 Allocate an item to save the <Key, Value> pair to the tail of the netmap.
1394 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1395 to the tail of the Used doubly linked list. The number of the <Key, Value>
1396 pairs in the netmap increase by 1.
1398 If Map is NULL, then ASSERT().
1400 @param[in, out] Map The netmap to insert into.
1401 @param[in] Key The user's key.
1402 @param[in] Value The user's value for the key.
1404 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1405 @retval EFI_SUCCESS The item is inserted to the tail.
1411 IN OUT NET_MAP
*Map
,
1413 IN VOID
*Value OPTIONAL
1418 ASSERT (Map
!= NULL
);
1420 Item
= NetMapAllocItem (Map
);
1423 return EFI_OUT_OF_RESOURCES
;
1427 Item
->Value
= Value
;
1428 InsertTailList (&Map
->Used
, &Item
->Link
);
1437 Check whether the item is in the Map and return TRUE if it is.
1439 @param[in] Map The netmap to search within.
1440 @param[in] Item The item to search.
1442 @return TRUE if the item is in the netmap, otherwise FALSE.
1448 IN NET_MAP_ITEM
*Item
1451 LIST_ENTRY
*ListEntry
;
1453 NET_LIST_FOR_EACH (ListEntry
, &Map
->Used
) {
1454 if (ListEntry
== &Item
->Link
) {
1464 Find the key in the netmap and returns the point to the item contains the Key.
1466 Iterate the Used doubly linked list of the netmap to get every item. Compare the key of every
1467 item with the key to search. It returns the point to the item contains the Key if found.
1469 If Map is NULL, then ASSERT().
1471 @param[in] Map The netmap to search within.
1472 @param[in] Key The key to search.
1474 @return The point to the item contains the Key, or NULL if Key isn't in the map.
1487 ASSERT (Map
!= NULL
);
1489 NET_LIST_FOR_EACH (Entry
, &Map
->Used
) {
1490 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1492 if (Item
->Key
== Key
) {
1502 Remove the node entry of the item from the netmap and return the key of the removed item.
1504 Remove the node entry of the item from the Used doubly linked list of the netmap.
1505 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1506 entry of the item to the Recycled doubly linked list of the netmap. If Value is not NULL,
1507 Value will point to the value of the item. It returns the key of the removed item.
1509 If Map is NULL, then ASSERT().
1510 If Item is NULL, then ASSERT().
1511 if item in not in the netmap, then ASSERT().
1513 @param[in, out] Map The netmap to remove the item from.
1514 @param[in, out] Item The item to remove.
1515 @param[out] Value The variable to receive the value if not NULL.
1517 @return The key of the removed item.
1523 IN OUT NET_MAP
*Map
,
1524 IN OUT NET_MAP_ITEM
*Item
,
1525 OUT VOID
**Value OPTIONAL
1528 ASSERT ((Map
!= NULL
) && (Item
!= NULL
));
1529 ASSERT (NetItemInMap (Map
, Item
));
1531 RemoveEntryList (&Item
->Link
);
1533 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1535 if (Value
!= NULL
) {
1536 *Value
= Item
->Value
;
1544 Remove the first node entry on the netmap and return the key of the removed item.
1546 Remove the first node entry from the Used doubly linked list of the netmap.
1547 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1548 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1549 parameter Value will point to the value of the item. It returns the key of the removed item.
1551 If Map is NULL, then ASSERT().
1552 If the Used doubly linked list is empty, then ASSERT().
1554 @param[in, out] Map The netmap to remove the head from.
1555 @param[out] Value The variable to receive the value if not NULL.
1557 @return The key of the item removed.
1563 IN OUT NET_MAP
*Map
,
1564 OUT VOID
**Value OPTIONAL
1570 // Often, it indicates a programming error to remove
1571 // the first entry in an empty list
1573 ASSERT (Map
&& !IsListEmpty (&Map
->Used
));
1575 Item
= NET_LIST_HEAD (&Map
->Used
, NET_MAP_ITEM
, Link
);
1576 RemoveEntryList (&Item
->Link
);
1578 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1580 if (Value
!= NULL
) {
1581 *Value
= Item
->Value
;
1589 Remove the last node entry on the netmap and return the key of the removed item.
1591 Remove the last node entry from the Used doubly linked list of the netmap.
1592 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1593 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1594 parameter Value will point to the value of the item. It returns the key of the removed item.
1596 If Map is NULL, then ASSERT().
1597 If the Used doubly linked list is empty, then ASSERT().
1599 @param[in, out] Map The netmap to remove the tail from.
1600 @param[out] Value The variable to receive the value if not NULL.
1602 @return The key of the item removed.
1608 IN OUT NET_MAP
*Map
,
1609 OUT VOID
**Value OPTIONAL
1615 // Often, it indicates a programming error to remove
1616 // the last entry in an empty list
1618 ASSERT (Map
&& !IsListEmpty (&Map
->Used
));
1620 Item
= NET_LIST_TAIL (&Map
->Used
, NET_MAP_ITEM
, Link
);
1621 RemoveEntryList (&Item
->Link
);
1623 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1625 if (Value
!= NULL
) {
1626 *Value
= Item
->Value
;
1634 Iterate through the netmap and call CallBack for each item.
1636 It will contiue the traverse if CallBack returns EFI_SUCCESS, otherwise, break
1637 from the loop. It returns the CallBack's last return value. This function is
1638 delete safe for the current item.
1640 If Map is NULL, then ASSERT().
1641 If CallBack is NULL, then ASSERT().
1643 @param[in] Map The Map to iterate through.
1644 @param[in] CallBack The callback function to call for each item.
1645 @param[in] Arg The opaque parameter to the callback.
1647 @retval EFI_SUCCESS There is no item in the netmap or CallBack for each item
1649 @retval Others It returns the CallBack's last return value.
1656 IN NET_MAP_CALLBACK CallBack
,
1657 IN VOID
*Arg OPTIONAL
1667 ASSERT ((Map
!= NULL
) && (CallBack
!= NULL
));
1671 if (IsListEmpty (Head
)) {
1675 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, Head
) {
1676 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1677 Result
= CallBack (Map
, Item
, Arg
);
1679 if (EFI_ERROR (Result
)) {
1689 Internal function to get the child handle of the NIC handle.
1691 @param[in] Controller NIC controller handle.
1692 @param[out] ChildHandle Returned child handle.
1694 @retval EFI_SUCCESS Successfully to get child handle.
1695 @retval Others Failed to get child handle.
1700 IN EFI_HANDLE Controller
,
1701 OUT EFI_HANDLE
*ChildHandle
1705 EFI_HANDLE
*Handles
;
1708 EFI_DEVICE_PATH_PROTOCOL
*ChildDeviceDevicePath
;
1709 VENDOR_DEVICE_PATH
*VendorDeviceNode
;
1712 // Locate all EFI Hii Config Access protocols
1714 Status
= gBS
->LocateHandleBuffer (
1716 &gEfiHiiConfigAccessProtocolGuid
,
1721 if (EFI_ERROR (Status
) || (HandleCount
== 0)) {
1725 Status
= EFI_NOT_FOUND
;
1727 for (Index
= 0; Index
< HandleCount
; Index
++) {
1729 Status
= EfiTestChildHandle (Controller
, Handles
[Index
], &gEfiManagedNetworkServiceBindingProtocolGuid
);
1730 if (!EFI_ERROR (Status
)) {
1732 // Get device path on the child handle
1734 Status
= gBS
->HandleProtocol (
1736 &gEfiDevicePathProtocolGuid
,
1737 (VOID
**) &ChildDeviceDevicePath
1740 if (!EFI_ERROR (Status
)) {
1741 while (!IsDevicePathEnd (ChildDeviceDevicePath
)) {
1742 ChildDeviceDevicePath
= NextDevicePathNode (ChildDeviceDevicePath
);
1744 // Parse one instance
1746 if (ChildDeviceDevicePath
->Type
== HARDWARE_DEVICE_PATH
&&
1747 ChildDeviceDevicePath
->SubType
== HW_VENDOR_DP
) {
1748 VendorDeviceNode
= (VENDOR_DEVICE_PATH
*) ChildDeviceDevicePath
;
1749 if (CompareMem (&VendorDeviceNode
->Guid
, &gEfiNicIp4ConfigVariableGuid
, sizeof (EFI_GUID
)) == 0) {
1751 // Found item matched gEfiNicIp4ConfigVariableGuid
1753 *ChildHandle
= Handles
[Index
];
1769 This is the default unload handle for all the network drivers.
1771 Disconnect the driver specified by ImageHandle from all the devices in the handle database.
1772 Uninstall all the protocols installed in the driver entry point.
1774 @param[in] ImageHandle The drivers' driver image.
1776 @retval EFI_SUCCESS The image is unloaded.
1777 @retval Others Failed to unload the image.
1782 NetLibDefaultUnload (
1783 IN EFI_HANDLE ImageHandle
1787 EFI_HANDLE
*DeviceHandleBuffer
;
1788 UINTN DeviceHandleCount
;
1790 EFI_DRIVER_BINDING_PROTOCOL
*DriverBinding
;
1791 EFI_COMPONENT_NAME_PROTOCOL
*ComponentName
;
1792 EFI_COMPONENT_NAME2_PROTOCOL
*ComponentName2
;
1795 // Get the list of all the handles in the handle database.
1796 // If there is an error getting the list, then the unload
1799 Status
= gBS
->LocateHandleBuffer (
1807 if (EFI_ERROR (Status
)) {
1812 // Disconnect the driver specified by ImageHandle from all
1813 // the devices in the handle database.
1815 for (Index
= 0; Index
< DeviceHandleCount
; Index
++) {
1816 Status
= gBS
->DisconnectController (
1817 DeviceHandleBuffer
[Index
],
1824 // Uninstall all the protocols installed in the driver entry point
1826 for (Index
= 0; Index
< DeviceHandleCount
; Index
++) {
1827 Status
= gBS
->HandleProtocol (
1828 DeviceHandleBuffer
[Index
],
1829 &gEfiDriverBindingProtocolGuid
,
1830 (VOID
**) &DriverBinding
1833 if (EFI_ERROR (Status
)) {
1837 if (DriverBinding
->ImageHandle
!= ImageHandle
) {
1841 gBS
->UninstallProtocolInterface (
1843 &gEfiDriverBindingProtocolGuid
,
1846 Status
= gBS
->HandleProtocol (
1847 DeviceHandleBuffer
[Index
],
1848 &gEfiComponentNameProtocolGuid
,
1849 (VOID
**) &ComponentName
1851 if (!EFI_ERROR (Status
)) {
1852 gBS
->UninstallProtocolInterface (
1854 &gEfiComponentNameProtocolGuid
,
1859 Status
= gBS
->HandleProtocol (
1860 DeviceHandleBuffer
[Index
],
1861 &gEfiComponentName2ProtocolGuid
,
1862 (VOID
**) &ComponentName2
1864 if (!EFI_ERROR (Status
)) {
1865 gBS
->UninstallProtocolInterface (
1867 &gEfiComponentName2ProtocolGuid
,
1874 // Free the buffer containing the list of handles from the handle database
1876 if (DeviceHandleBuffer
!= NULL
) {
1877 gBS
->FreePool (DeviceHandleBuffer
);
1886 Create a child of the service that is identified by ServiceBindingGuid.
1888 Get the ServiceBinding Protocol first, then use it to create a child.
1890 If ServiceBindingGuid is NULL, then ASSERT().
1891 If ChildHandle is NULL, then ASSERT().
1893 @param[in] Controller The controller which has the service installed.
1894 @param[in] Image The image handle used to open service.
1895 @param[in] ServiceBindingGuid The service's Guid.
1896 @param[in, out] ChildHandle The handle to receive the create child.
1898 @retval EFI_SUCCESS The child is successfully created.
1899 @retval Others Failed to create the child.
1904 NetLibCreateServiceChild (
1905 IN EFI_HANDLE Controller
,
1906 IN EFI_HANDLE Image
,
1907 IN EFI_GUID
*ServiceBindingGuid
,
1908 IN OUT EFI_HANDLE
*ChildHandle
1912 EFI_SERVICE_BINDING_PROTOCOL
*Service
;
1915 ASSERT ((ServiceBindingGuid
!= NULL
) && (ChildHandle
!= NULL
));
1918 // Get the ServiceBinding Protocol
1920 Status
= gBS
->OpenProtocol (
1926 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1929 if (EFI_ERROR (Status
)) {
1936 Status
= Service
->CreateChild (Service
, ChildHandle
);
1942 Destroy a child of the service that is identified by ServiceBindingGuid.
1944 Get the ServiceBinding Protocol first, then use it to destroy a child.
1946 If ServiceBindingGuid is NULL, then ASSERT().
1948 @param[in] Controller The controller which has the service installed.
1949 @param[in] Image The image handle used to open service.
1950 @param[in] ServiceBindingGuid The service's Guid.
1951 @param[in] ChildHandle The child to destroy.
1953 @retval EFI_SUCCESS The child is successfully destroyed.
1954 @retval Others Failed to destroy the child.
1959 NetLibDestroyServiceChild (
1960 IN EFI_HANDLE Controller
,
1961 IN EFI_HANDLE Image
,
1962 IN EFI_GUID
*ServiceBindingGuid
,
1963 IN EFI_HANDLE ChildHandle
1967 EFI_SERVICE_BINDING_PROTOCOL
*Service
;
1969 ASSERT (ServiceBindingGuid
!= NULL
);
1972 // Get the ServiceBinding Protocol
1974 Status
= gBS
->OpenProtocol (
1980 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1983 if (EFI_ERROR (Status
)) {
1988 // destroy the child
1990 Status
= Service
->DestroyChild (Service
, ChildHandle
);
1995 Get handle with Simple Network Protocol installed on it.
1997 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
1998 If Simple Network Protocol is already installed on the ServiceHandle, the
1999 ServiceHandle will be returned. If SNP is not installed on the ServiceHandle,
2000 try to find its parent handle with SNP installed.
2002 @param[in] ServiceHandle The handle where network service binding protocols are
2004 @param[out] Snp The pointer to store the address of the SNP instance.
2005 This is an optional parameter that may be NULL.
2007 @return The SNP handle, or NULL if not found.
2012 NetLibGetSnpHandle (
2013 IN EFI_HANDLE ServiceHandle
,
2014 OUT EFI_SIMPLE_NETWORK_PROTOCOL
**Snp OPTIONAL
2018 EFI_SIMPLE_NETWORK_PROTOCOL
*SnpInstance
;
2019 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2020 EFI_HANDLE SnpHandle
;
2023 // Try to open SNP from ServiceHandle
2026 Status
= gBS
->HandleProtocol (ServiceHandle
, &gEfiSimpleNetworkProtocolGuid
, (VOID
**) &SnpInstance
);
2027 if (!EFI_ERROR (Status
)) {
2031 return ServiceHandle
;
2035 // Failed to open SNP, try to get SNP handle by LocateDevicePath()
2037 DevicePath
= DevicePathFromHandle (ServiceHandle
);
2038 if (DevicePath
== NULL
) {
2043 Status
= gBS
->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid
, &DevicePath
, &SnpHandle
);
2044 if (EFI_ERROR (Status
)) {
2046 // Failed to find SNP handle
2051 Status
= gBS
->HandleProtocol (SnpHandle
, &gEfiSimpleNetworkProtocolGuid
, (VOID
**) &SnpInstance
);
2052 if (!EFI_ERROR (Status
)) {
2063 Retrieve VLAN ID of a VLAN device handle.
2065 Search VLAN device path node in Device Path of specified ServiceHandle and
2066 return its VLAN ID. If no VLAN device path node found, then this ServiceHandle
2067 is not a VLAN device handle, and 0 will be returned.
2069 @param[in] ServiceHandle The handle where network service binding protocols are
2072 @return VLAN ID of the device handle, or 0 if not a VLAN device.
2078 IN EFI_HANDLE ServiceHandle
2081 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2082 EFI_DEVICE_PATH_PROTOCOL
*Node
;
2084 DevicePath
= DevicePathFromHandle (ServiceHandle
);
2085 if (DevicePath
== NULL
) {
2090 while (!IsDevicePathEnd (Node
)) {
2091 if (Node
->Type
== MESSAGING_DEVICE_PATH
&& Node
->SubType
== MSG_VLAN_DP
) {
2092 return ((VLAN_DEVICE_PATH
*) Node
)->VlanId
;
2094 Node
= NextDevicePathNode (Node
);
2101 Find VLAN device handle with specified VLAN ID.
2103 The VLAN child device handle is created by VLAN Config Protocol on ControllerHandle.
2104 This function will append VLAN device path node to the parent device path,
2105 and then use LocateDevicePath() to find the correct VLAN device handle.
2107 @param[in] ControllerHandle The handle where network service binding protocols are
2109 @param[in] VlanId The configured VLAN ID for the VLAN device.
2111 @return The VLAN device handle, or NULL if not found.
2116 NetLibGetVlanHandle (
2117 IN EFI_HANDLE ControllerHandle
,
2121 EFI_DEVICE_PATH_PROTOCOL
*ParentDevicePath
;
2122 EFI_DEVICE_PATH_PROTOCOL
*VlanDevicePath
;
2123 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2124 VLAN_DEVICE_PATH VlanNode
;
2127 ParentDevicePath
= DevicePathFromHandle (ControllerHandle
);
2128 if (ParentDevicePath
== NULL
) {
2133 // Construct VLAN device path
2135 CopyMem (&VlanNode
, &mNetVlanDevicePathTemplate
, sizeof (VLAN_DEVICE_PATH
));
2136 VlanNode
.VlanId
= VlanId
;
2137 VlanDevicePath
= AppendDevicePathNode (
2139 (EFI_DEVICE_PATH_PROTOCOL
*) &VlanNode
2141 if (VlanDevicePath
== NULL
) {
2146 // Find VLAN device handle
2149 DevicePath
= VlanDevicePath
;
2150 gBS
->LocateDevicePath (
2151 &gEfiDevicePathProtocolGuid
,
2155 if (!IsDevicePathEnd (DevicePath
)) {
2157 // Device path is not exactly match
2162 FreePool (VlanDevicePath
);
2167 Get MAC address associated with the network service handle.
2169 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
2170 If SNP is installed on the ServiceHandle or its parent handle, MAC address will
2171 be retrieved from SNP. If no SNP found, try to get SNP mode data use MNP.
2173 @param[in] ServiceHandle The handle where network service binding protocols are
2175 @param[out] MacAddress The pointer to store the returned MAC address.
2176 @param[out] AddressSize The length of returned MAC address.
2178 @retval EFI_SUCCESS MAC address is returned successfully.
2179 @retval Others Failed to get SNP mode data.
2184 NetLibGetMacAddress (
2185 IN EFI_HANDLE ServiceHandle
,
2186 OUT EFI_MAC_ADDRESS
*MacAddress
,
2187 OUT UINTN
*AddressSize
2191 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2192 EFI_SIMPLE_NETWORK_MODE
*SnpMode
;
2193 EFI_SIMPLE_NETWORK_MODE SnpModeData
;
2194 EFI_MANAGED_NETWORK_PROTOCOL
*Mnp
;
2195 EFI_SERVICE_BINDING_PROTOCOL
*MnpSb
;
2196 EFI_HANDLE
*SnpHandle
;
2197 EFI_HANDLE MnpChildHandle
;
2199 ASSERT (MacAddress
!= NULL
);
2200 ASSERT (AddressSize
!= NULL
);
2203 // Try to get SNP handle
2206 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2207 if (SnpHandle
!= NULL
) {
2209 // SNP found, use it directly
2211 SnpMode
= Snp
->Mode
;
2214 // Failed to get SNP handle, try to get MAC address from MNP
2216 MnpChildHandle
= NULL
;
2217 Status
= gBS
->HandleProtocol (
2219 &gEfiManagedNetworkServiceBindingProtocolGuid
,
2222 if (EFI_ERROR (Status
)) {
2227 // Create a MNP child
2229 Status
= MnpSb
->CreateChild (MnpSb
, &MnpChildHandle
);
2230 if (EFI_ERROR (Status
)) {
2235 // Open MNP protocol
2237 Status
= gBS
->HandleProtocol (
2239 &gEfiManagedNetworkProtocolGuid
,
2242 if (EFI_ERROR (Status
)) {
2243 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2248 // Try to get SNP mode from MNP
2250 Status
= Mnp
->GetModeData (Mnp
, NULL
, &SnpModeData
);
2251 if (EFI_ERROR (Status
)) {
2252 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2255 SnpMode
= &SnpModeData
;
2258 // Destroy the MNP child
2260 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2263 *AddressSize
= SnpMode
->HwAddressSize
;
2264 CopyMem (MacAddress
->Addr
, SnpMode
->CurrentAddress
.Addr
, SnpMode
->HwAddressSize
);
2270 Convert MAC address of the NIC associated with specified Service Binding Handle
2271 to a unicode string. Callers are responsible for freeing the string storage.
2273 Locate simple network protocol associated with the Service Binding Handle and
2274 get the mac address from SNP. Then convert the mac address into a unicode
2275 string. It takes 2 unicode characters to represent a 1 byte binary buffer.
2276 Plus one unicode character for the null-terminator.
2278 @param[in] ServiceHandle The handle where network service binding protocol is
2280 @param[in] ImageHandle The image handle used to act as the agent handle to
2281 get the simple network protocol. This parameter is
2282 optional and may be NULL.
2283 @param[out] MacString The pointer to store the address of the string
2284 representation of the mac address.
2286 @retval EFI_SUCCESS Convert the mac address a unicode string successfully.
2287 @retval EFI_OUT_OF_RESOURCES There are not enough memory resource.
2288 @retval Others Failed to open the simple network protocol.
2293 NetLibGetMacString (
2294 IN EFI_HANDLE ServiceHandle
,
2295 IN EFI_HANDLE ImageHandle
, OPTIONAL
2296 OUT CHAR16
**MacString
2300 EFI_MAC_ADDRESS MacAddress
;
2302 UINTN HwAddressSize
;
2307 ASSERT (MacString
!= NULL
);
2310 // Get MAC address of the network device
2312 Status
= NetLibGetMacAddress (ServiceHandle
, &MacAddress
, &HwAddressSize
);
2313 if (EFI_ERROR (Status
)) {
2318 // It takes 2 unicode characters to represent a 1 byte binary buffer.
2319 // If VLAN is configured, it will need extra 5 characters like "\0005".
2320 // Plus one unicode character for the null-terminator.
2322 String
= AllocateZeroPool ((2 * HwAddressSize
+ 5 + 1) * sizeof (CHAR16
));
2323 if (String
== NULL
) {
2324 return EFI_OUT_OF_RESOURCES
;
2326 *MacString
= String
;
2329 // Convert the MAC address into a unicode string.
2331 HwAddress
= &MacAddress
.Addr
[0];
2332 for (Index
= 0; Index
< HwAddressSize
; Index
++) {
2333 String
+= UnicodeValueToString (String
, PREFIX_ZERO
| RADIX_HEX
, *(HwAddress
++), 2);
2337 // Append VLAN ID if any
2339 VlanId
= NetLibGetVlanId (ServiceHandle
);
2342 String
+= UnicodeValueToString (String
, PREFIX_ZERO
| RADIX_HEX
, VlanId
, 4);
2346 // Null terminate the Unicode string
2354 Detect media status for specified network device.
2356 The underlying UNDI driver may or may not support reporting media status from
2357 GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine
2358 will try to invoke Snp->GetStatus() to get the media status: if media already
2359 present, it return directly; if media not present, it will stop SNP and then
2360 restart SNP to get the latest media status, this give chance to get the correct
2361 media status for old UNDI driver which doesn't support reporting media status
2362 from GET_STATUS command.
2363 Note: there will be two limitations for current algorithm:
2364 1) for UNDI with this capability, in case of cable is not attached, there will
2365 be an redundant Stop/Start() process;
2366 2) for UNDI without this capability, in case that network cable is attached when
2367 Snp->Initialize() is invoked while network cable is unattached later,
2368 NetLibDetectMedia() will report MediaPresent as TRUE, causing upper layer
2369 apps to wait for timeout time.
2371 @param[in] ServiceHandle The handle where network service binding protocols are
2373 @param[out] MediaPresent The pointer to store the media status.
2375 @retval EFI_SUCCESS Media detection success.
2376 @retval EFI_INVALID_PARAMETER ServiceHandle is not valid network device handle.
2377 @retval EFI_UNSUPPORTED Network device does not support media detection.
2378 @retval EFI_DEVICE_ERROR SNP is in unknown state.
2384 IN EFI_HANDLE ServiceHandle
,
2385 OUT BOOLEAN
*MediaPresent
2389 EFI_HANDLE SnpHandle
;
2390 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2391 UINT32 InterruptStatus
;
2393 EFI_MAC_ADDRESS
*MCastFilter
;
2394 UINT32 MCastFilterCount
;
2395 UINT32 EnableFilterBits
;
2396 UINT32 DisableFilterBits
;
2397 BOOLEAN ResetMCastFilters
;
2399 ASSERT (MediaPresent
!= NULL
);
2405 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2406 if (SnpHandle
== NULL
) {
2407 return EFI_INVALID_PARAMETER
;
2411 // Check whether SNP support media detection
2413 if (!Snp
->Mode
->MediaPresentSupported
) {
2414 return EFI_UNSUPPORTED
;
2418 // Invoke Snp->GetStatus() to refresh MediaPresent field in SNP mode data
2420 Status
= Snp
->GetStatus (Snp
, &InterruptStatus
, NULL
);
2421 if (EFI_ERROR (Status
)) {
2425 if (Snp
->Mode
->MediaPresent
) {
2427 // Media is present, return directly
2429 *MediaPresent
= TRUE
;
2434 // Till now, GetStatus() report no media; while, in case UNDI not support
2435 // reporting media status from GetStatus(), this media status may be incorrect.
2436 // So, we will stop SNP and then restart it to get the correct media status.
2438 OldState
= Snp
->Mode
->State
;
2439 if (OldState
>= EfiSimpleNetworkMaxState
) {
2440 return EFI_DEVICE_ERROR
;
2445 if (OldState
== EfiSimpleNetworkInitialized
) {
2447 // SNP is already in use, need Shutdown/Stop and then Start/Initialize
2451 // Backup current SNP receive filter settings
2453 EnableFilterBits
= Snp
->Mode
->ReceiveFilterSetting
;
2454 DisableFilterBits
= Snp
->Mode
->ReceiveFilterMask
^ EnableFilterBits
;
2456 ResetMCastFilters
= TRUE
;
2457 MCastFilterCount
= Snp
->Mode
->MCastFilterCount
;
2458 if (MCastFilterCount
!= 0) {
2459 MCastFilter
= AllocateCopyPool (
2460 MCastFilterCount
* sizeof (EFI_MAC_ADDRESS
),
2461 Snp
->Mode
->MCastFilter
2463 ASSERT (MCastFilter
!= NULL
);
2465 ResetMCastFilters
= FALSE
;
2469 // Shutdown/Stop the simple network
2471 Status
= Snp
->Shutdown (Snp
);
2472 if (!EFI_ERROR (Status
)) {
2473 Status
= Snp
->Stop (Snp
);
2475 if (EFI_ERROR (Status
)) {
2480 // Start/Initialize the simple network
2482 Status
= Snp
->Start (Snp
);
2483 if (!EFI_ERROR (Status
)) {
2484 Status
= Snp
->Initialize (Snp
, 0, 0);
2486 if (EFI_ERROR (Status
)) {
2491 // Here we get the correct media status
2493 *MediaPresent
= Snp
->Mode
->MediaPresent
;
2496 // Restore SNP receive filter settings
2498 Status
= Snp
->ReceiveFilters (
2507 if (MCastFilter
!= NULL
) {
2508 FreePool (MCastFilter
);
2515 // SNP is not in use, it's in state of EfiSimpleNetworkStopped or EfiSimpleNetworkStarted
2517 if (OldState
== EfiSimpleNetworkStopped
) {
2519 // SNP not start yet, start it
2521 Status
= Snp
->Start (Snp
);
2522 if (EFI_ERROR (Status
)) {
2528 // Initialize the simple network
2530 Status
= Snp
->Initialize (Snp
, 0, 0);
2531 if (EFI_ERROR (Status
)) {
2532 Status
= EFI_DEVICE_ERROR
;
2537 // Here we get the correct media status
2539 *MediaPresent
= Snp
->Mode
->MediaPresent
;
2542 // Shut down the simple network
2544 Snp
->Shutdown (Snp
);
2547 if (OldState
== EfiSimpleNetworkStopped
) {
2549 // Original SNP sate is Stopped, restore to original state
2554 if (MCastFilter
!= NULL
) {
2555 FreePool (MCastFilter
);
2562 Check the default address used by the IPv4 driver is static or dynamic (acquired
2565 If the controller handle does not have the NIC Ip4 Config Protocol installed, the
2566 default address is static. If the EFI variable to save the configuration is not found,
2567 the default address is static. Otherwise, get the result from the EFI variable which
2568 saving the configuration.
2570 @param[in] Controller The controller handle which has the NIC Ip4 Config Protocol
2571 relative with the default address to judge.
2573 @retval TRUE If the default address is static.
2574 @retval FALSE If the default address is acquired from DHCP.
2578 NetLibDefaultAddressIsStatic (
2579 IN EFI_HANDLE Controller
2583 EFI_HII_CONFIG_ROUTING_PROTOCOL
*HiiConfigRouting
;
2585 NIC_IP4_CONFIG_INFO
*ConfigInfo
;
2587 EFI_STRING ConfigHdr
;
2588 EFI_STRING ConfigResp
;
2589 EFI_STRING AccessProgress
;
2590 EFI_STRING AccessResults
;
2592 EFI_HANDLE ChildHandle
;
2597 AccessProgress
= NULL
;
2598 AccessResults
= NULL
;
2601 Status
= gBS
->LocateProtocol (
2602 &gEfiHiiConfigRoutingProtocolGuid
,
2604 (VOID
**) &HiiConfigRouting
2606 if (EFI_ERROR (Status
)) {
2610 Status
= NetGetChildHandle (Controller
, &ChildHandle
);
2611 if (EFI_ERROR (Status
)) {
2616 // Construct config request string header
2618 ConfigHdr
= HiiConstructConfigHdr (&gEfiNicIp4ConfigVariableGuid
, EFI_NIC_IP4_CONFIG_VARIABLE
, ChildHandle
);
2619 if (ConfigHdr
== NULL
) {
2623 Len
= StrLen (ConfigHdr
);
2624 ConfigResp
= AllocateZeroPool ((Len
+ NIC_ITEM_CONFIG_SIZE
* 2 + 100) * sizeof (CHAR16
));
2625 if (ConfigResp
== NULL
) {
2628 StrCpy (ConfigResp
, ConfigHdr
);
2630 String
= ConfigResp
+ Len
;
2633 (8 + 4 + 7 + 4 + 1) * sizeof (CHAR16
),
2634 L
"&OFFSET=%04X&WIDTH=%04X",
2635 OFFSET_OF (NIC_IP4_CONFIG_INFO
, Source
),
2639 Status
= HiiConfigRouting
->ExtractConfig (
2645 if (EFI_ERROR (Status
)) {
2649 ConfigInfo
= AllocateZeroPool (NIC_ITEM_CONFIG_SIZE
);
2650 if (ConfigInfo
== NULL
) {
2654 ConfigInfo
->Source
= IP4_CONFIG_SOURCE_STATIC
;
2655 Len
= NIC_ITEM_CONFIG_SIZE
;
2656 Status
= HiiConfigRouting
->ConfigToBlock (
2659 (UINT8
*) ConfigInfo
,
2663 if (EFI_ERROR (Status
)) {
2667 IsStatic
= (BOOLEAN
) (ConfigInfo
->Source
== IP4_CONFIG_SOURCE_STATIC
);
2671 if (AccessResults
!= NULL
) {
2672 FreePool (AccessResults
);
2674 if (ConfigInfo
!= NULL
) {
2675 FreePool (ConfigInfo
);
2677 if (ConfigResp
!= NULL
) {
2678 FreePool (ConfigResp
);
2680 if (ConfigHdr
!= NULL
) {
2681 FreePool (ConfigHdr
);
2688 Create an IPv4 device path node.
2690 The header type of IPv4 device path node is MESSAGING_DEVICE_PATH.
2691 The header subtype of IPv4 device path node is MSG_IPv4_DP.
2692 Get other info from parameters to make up the whole IPv4 device path node.
2694 @param[in, out] Node Pointer to the IPv4 device path node.
2695 @param[in] Controller The controller handle.
2696 @param[in] LocalIp The local IPv4 address.
2697 @param[in] LocalPort The local port.
2698 @param[in] RemoteIp The remote IPv4 address.
2699 @param[in] RemotePort The remote port.
2700 @param[in] Protocol The protocol type in the IP header.
2701 @param[in] UseDefaultAddress Whether this instance is using default address or not.
2706 NetLibCreateIPv4DPathNode (
2707 IN OUT IPv4_DEVICE_PATH
*Node
,
2708 IN EFI_HANDLE Controller
,
2709 IN IP4_ADDR LocalIp
,
2710 IN UINT16 LocalPort
,
2711 IN IP4_ADDR RemoteIp
,
2712 IN UINT16 RemotePort
,
2714 IN BOOLEAN UseDefaultAddress
2717 Node
->Header
.Type
= MESSAGING_DEVICE_PATH
;
2718 Node
->Header
.SubType
= MSG_IPv4_DP
;
2719 SetDevicePathNodeLength (&Node
->Header
, sizeof (IPv4_DEVICE_PATH
));
2721 CopyMem (&Node
->LocalIpAddress
, &LocalIp
, sizeof (EFI_IPv4_ADDRESS
));
2722 CopyMem (&Node
->RemoteIpAddress
, &RemoteIp
, sizeof (EFI_IPv4_ADDRESS
));
2724 Node
->LocalPort
= LocalPort
;
2725 Node
->RemotePort
= RemotePort
;
2727 Node
->Protocol
= Protocol
;
2729 if (!UseDefaultAddress
) {
2730 Node
->StaticIpAddress
= TRUE
;
2732 Node
->StaticIpAddress
= NetLibDefaultAddressIsStatic (Controller
);
2736 // Set the Gateway IP address to default value 0:0:0:0.
2737 // Set the Subnet mask to default value 255:255:255:0.
2739 ZeroMem (&Node
->GatewayIpAddress
, sizeof (EFI_IPv4_ADDRESS
));
2740 SetMem (&Node
->SubnetMask
, sizeof (EFI_IPv4_ADDRESS
), 0xff);
2741 Node
->SubnetMask
.Addr
[3] = 0;
2745 Create an IPv6 device path node.
2747 The header type of IPv6 device path node is MESSAGING_DEVICE_PATH.
2748 The header subtype of IPv6 device path node is MSG_IPv6_DP.
2749 Get other info from parameters to make up the whole IPv6 device path node.
2751 @param[in, out] Node Pointer to the IPv6 device path node.
2752 @param[in] Controller The controller handle.
2753 @param[in] LocalIp The local IPv6 address.
2754 @param[in] LocalPort The local port.
2755 @param[in] RemoteIp The remote IPv6 address.
2756 @param[in] RemotePort The remote port.
2757 @param[in] Protocol The protocol type in the IP header.
2762 NetLibCreateIPv6DPathNode (
2763 IN OUT IPv6_DEVICE_PATH
*Node
,
2764 IN EFI_HANDLE Controller
,
2765 IN EFI_IPv6_ADDRESS
*LocalIp
,
2766 IN UINT16 LocalPort
,
2767 IN EFI_IPv6_ADDRESS
*RemoteIp
,
2768 IN UINT16 RemotePort
,
2772 Node
->Header
.Type
= MESSAGING_DEVICE_PATH
;
2773 Node
->Header
.SubType
= MSG_IPv6_DP
;
2774 SetDevicePathNodeLength (&Node
->Header
, sizeof (IPv6_DEVICE_PATH
));
2776 CopyMem (&Node
->LocalIpAddress
, LocalIp
, sizeof (EFI_IPv6_ADDRESS
));
2777 CopyMem (&Node
->RemoteIpAddress
, RemoteIp
, sizeof (EFI_IPv6_ADDRESS
));
2779 Node
->LocalPort
= LocalPort
;
2780 Node
->RemotePort
= RemotePort
;
2782 Node
->Protocol
= Protocol
;
2785 // Set default value to IPAddressOrigin, PrefixLength.
2786 // Set the Gateway IP address to unspecified address.
2788 Node
->IpAddressOrigin
= 0;
2789 Node
->PrefixLength
= IP6_PREFIX_LENGTH
;
2790 ZeroMem (&Node
->GatewayIpAddress
, sizeof (EFI_IPv6_ADDRESS
));
2794 Find the UNDI/SNP handle from controller and protocol GUID.
2796 For example, IP will open a MNP child to transmit/receive
2797 packets, when MNP is stopped, IP should also be stopped. IP
2798 needs to find its own private data which is related the IP's
2799 service binding instance that is install on UNDI/SNP handle.
2800 Now, the controller is either a MNP or ARP child handle. But
2801 IP opens these handle BY_DRIVER, use that info, we can get the
2804 @param[in] Controller Then protocol handle to check.
2805 @param[in] ProtocolGuid The protocol that is related with the handle.
2807 @return The UNDI/SNP handle or NULL for errors.
2812 NetLibGetNicHandle (
2813 IN EFI_HANDLE Controller
,
2814 IN EFI_GUID
*ProtocolGuid
2817 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY
*OpenBuffer
;
2823 Status
= gBS
->OpenProtocolInformation (
2830 if (EFI_ERROR (Status
)) {
2836 for (Index
= 0; Index
< OpenCount
; Index
++) {
2837 if ((OpenBuffer
[Index
].Attributes
& EFI_OPEN_PROTOCOL_BY_DRIVER
) != 0) {
2838 Handle
= OpenBuffer
[Index
].ControllerHandle
;
2843 gBS
->FreePool (OpenBuffer
);
2848 Convert one Null-terminated ASCII string (decimal dotted) to EFI_IPv4_ADDRESS.
2850 @param[in] String The pointer to the Ascii string.
2851 @param[out] Ip4Address The pointer to the converted IPv4 address.
2853 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2854 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2859 NetLibAsciiStrToIp4 (
2860 IN CONST CHAR8
*String
,
2861 OUT EFI_IPv4_ADDRESS
*Ip4Address
2869 if ((String
== NULL
) || (Ip4Address
== NULL
)) {
2870 return EFI_INVALID_PARAMETER
;
2873 Ip4Str
= (CHAR8
*) String
;
2875 for (Index
= 0; Index
< 4; Index
++) {
2878 while ((*Ip4Str
!= '\0') && (*Ip4Str
!= '.')) {
2883 // The IPv4 address is X.X.X.X
2885 if (*Ip4Str
== '.') {
2887 return EFI_INVALID_PARAMETER
;
2891 return EFI_INVALID_PARAMETER
;
2896 // Convert the string to IPv4 address. AsciiStrDecimalToUintn stops at the
2897 // first character that is not a valid decimal character, '.' or '\0' here.
2899 NodeVal
= AsciiStrDecimalToUintn (TempStr
);
2900 if (NodeVal
> 0xFF) {
2901 return EFI_INVALID_PARAMETER
;
2904 Ip4Address
->Addr
[Index
] = (UINT8
) NodeVal
;
2914 Convert one Null-terminated ASCII string to EFI_IPv6_ADDRESS. The format of the
2915 string is defined in RFC 4291 - Text Pepresentation of Addresses.
2917 @param[in] String The pointer to the Ascii string.
2918 @param[out] Ip6Address The pointer to the converted IPv6 address.
2920 @retval EFI_SUCCESS Convert to IPv6 address successfully.
2921 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
2926 NetLibAsciiStrToIp6 (
2927 IN CONST CHAR8
*String
,
2928 OUT EFI_IPv6_ADDRESS
*Ip6Address
2945 if ((String
== NULL
) || (Ip6Address
== NULL
)) {
2946 return EFI_INVALID_PARAMETER
;
2949 Ip6Str
= (CHAR8
*) String
;
2954 // An IPv6 address leading with : looks strange.
2956 if (*Ip6Str
== ':') {
2957 if (*(Ip6Str
+ 1) != ':') {
2958 return EFI_INVALID_PARAMETER
;
2964 ZeroMem (Ip6Address
, sizeof (EFI_IPv6_ADDRESS
));
2972 for (Index
= 0; Index
< 15; Index
= (UINT8
) (Index
+ 2)) {
2975 while ((*Ip6Str
!= '\0') && (*Ip6Str
!= ':')) {
2979 if ((*Ip6Str
== '\0') && (Index
!= 14)) {
2980 return EFI_INVALID_PARAMETER
;
2983 if (*Ip6Str
== ':') {
2984 if (*(Ip6Str
+ 1) == ':') {
2985 if ((NodeCnt
> 6) ||
2986 ((*(Ip6Str
+ 2) != '\0') && (AsciiStrHexToUintn (Ip6Str
+ 2) == 0))) {
2988 // ::0 looks strange. report error to user.
2990 return EFI_INVALID_PARAMETER
;
2992 if ((NodeCnt
== 6) && (*(Ip6Str
+ 2) != '\0') &&
2993 (AsciiStrHexToUintn (Ip6Str
+ 2) != 0)) {
2994 return EFI_INVALID_PARAMETER
;
2998 // Skip the abbreviation part of IPv6 address.
3000 TempStr2
= Ip6Str
+ 2;
3001 while ((*TempStr2
!= '\0')) {
3002 if (*TempStr2
== ':') {
3003 if (*(TempStr2
+ 1) == ':') {
3005 // :: can only appear once in IPv6 address.
3007 return EFI_INVALID_PARAMETER
;
3011 if (TailNodeCnt
>= (AllowedCnt
- NodeCnt
)) {
3013 // :: indicates one or more groups of 16 bits of zeros.
3015 return EFI_INVALID_PARAMETER
;
3025 Ip6Str
= Ip6Str
+ 2;
3027 if (*(Ip6Str
+ 1) == '\0') {
3028 return EFI_INVALID_PARAMETER
;
3032 if ((Short
&& (NodeCnt
> 6)) || (!Short
&& (NodeCnt
> 7))) {
3034 // There are more than 8 groups of 16 bits of zeros.
3036 return EFI_INVALID_PARAMETER
;
3042 // Convert the string to IPv6 address. AsciiStrHexToUintn stops at the first
3043 // character that is not a valid hexadecimal character, ':' or '\0' here.
3045 NodeVal
= AsciiStrHexToUintn (TempStr
);
3046 if ((NodeVal
> 0xFFFF) || (Index
> 14)) {
3047 return EFI_INVALID_PARAMETER
;
3050 if ((*TempStr
== '0') &&
3051 ((*(TempStr
+ 2) == ':') || (*(TempStr
+ 3) == ':') ||
3052 (*(TempStr
+ 2) == '\0') || (*(TempStr
+ 3) == '\0'))) {
3053 return EFI_INVALID_PARAMETER
;
3055 if ((*TempStr
== '0') && (*(TempStr
+ 4) != '\0') &&
3056 (*(TempStr
+ 4) != ':')) {
3057 return EFI_INVALID_PARAMETER
;
3060 if (((*TempStr
== '0') && (*(TempStr
+ 1) == '0') &&
3061 ((*(TempStr
+ 2) == ':') || (*(TempStr
+ 2) == '\0'))) ||
3062 ((*TempStr
== '0') && (*(TempStr
+ 1) == '0') && (*(TempStr
+ 2) == '0') &&
3063 ((*(TempStr
+ 3) == ':') || (*(TempStr
+ 3) == '\0')))) {
3064 return EFI_INVALID_PARAMETER
;
3069 while ((TempStr
[Cnt
] != ':') && (TempStr
[Cnt
] != '\0')) {
3072 if (LeadZeroCnt
== 0) {
3073 if ((Cnt
== 4) && (*TempStr
== '0')) {
3077 if ((Cnt
!= 0) && (Cnt
< 4)) {
3082 if ((Cnt
== 4) && (*TempStr
== '0') && !LeadZero
) {
3083 return EFI_INVALID_PARAMETER
;
3085 if ((Cnt
!= 0) && (Cnt
< 4) && LeadZero
) {
3086 return EFI_INVALID_PARAMETER
;
3090 Ip6Address
->Addr
[Index
] = (UINT8
) (NodeVal
>> 8);
3091 Ip6Address
->Addr
[Index
+ 1] = (UINT8
) (NodeVal
& 0xFF);
3094 // Skip the groups of zeros by ::
3096 if (Short
&& Update
) {
3097 Index
= (UINT8
) (16 - (TailNodeCnt
+ 2) * 2);
3102 if ((!Short
&& Index
!= 16) || (*Ip6Str
!= '\0')) {
3103 return EFI_INVALID_PARAMETER
;
3111 Convert one Null-terminated Unicode string (decimal dotted) to EFI_IPv4_ADDRESS.
3113 @param[in] String The pointer to the Ascii string.
3114 @param[out] Ip4Address The pointer to the converted IPv4 address.
3116 @retval EFI_SUCCESS Convert to IPv4 address successfully.
3117 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
3118 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3124 IN CONST CHAR16
*String
,
3125 OUT EFI_IPv4_ADDRESS
*Ip4Address
3131 if ((String
== NULL
) || (Ip4Address
== NULL
)) {
3132 return EFI_INVALID_PARAMETER
;
3135 Ip4Str
= (CHAR8
*) AllocatePool ((StrLen (String
) + 1) * sizeof (CHAR8
));
3136 if (Ip4Str
== NULL
) {
3137 return EFI_OUT_OF_RESOURCES
;
3140 UnicodeStrToAsciiStr (String
, Ip4Str
);
3142 Status
= NetLibAsciiStrToIp4 (Ip4Str
, Ip4Address
);
3151 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS. The format of
3152 the string is defined in RFC 4291 - Text Pepresentation of Addresses.
3154 @param[in] String The pointer to the Ascii string.
3155 @param[out] Ip6Address The pointer to the converted IPv6 address.
3157 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3158 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3159 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3165 IN CONST CHAR16
*String
,
3166 OUT EFI_IPv6_ADDRESS
*Ip6Address
3172 if ((String
== NULL
) || (Ip6Address
== NULL
)) {
3173 return EFI_INVALID_PARAMETER
;
3176 Ip6Str
= (CHAR8
*) AllocatePool ((StrLen (String
) + 1) * sizeof (CHAR8
));
3177 if (Ip6Str
== NULL
) {
3178 return EFI_OUT_OF_RESOURCES
;
3181 UnicodeStrToAsciiStr (String
, Ip6Str
);
3183 Status
= NetLibAsciiStrToIp6 (Ip6Str
, Ip6Address
);
3191 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS and prefix length.
3192 The format of the string is defined in RFC 4291 - Text Pepresentation of Addresses
3193 Prefixes: ipv6-address/prefix-length.
3195 @param[in] String The pointer to the Ascii string.
3196 @param[out] Ip6Address The pointer to the converted IPv6 address.
3197 @param[out] PrefixLength The pointer to the converted prefix length.
3199 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3200 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3201 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3206 NetLibStrToIp6andPrefix (
3207 IN CONST CHAR16
*String
,
3208 OUT EFI_IPv6_ADDRESS
*Ip6Address
,
3209 OUT UINT8
*PrefixLength
3218 if ((String
== NULL
) || (Ip6Address
== NULL
) || (PrefixLength
== NULL
)) {
3219 return EFI_INVALID_PARAMETER
;
3222 Ip6Str
= (CHAR8
*) AllocatePool ((StrLen (String
) + 1) * sizeof (CHAR8
));
3223 if (Ip6Str
== NULL
) {
3224 return EFI_OUT_OF_RESOURCES
;
3227 UnicodeStrToAsciiStr (String
, Ip6Str
);
3230 // Get the sub string describing prefix length.
3233 while (*TempStr
!= '\0' && (*TempStr
!= '/')) {
3237 if (*TempStr
== '/') {
3238 PrefixStr
= TempStr
+ 1;
3244 // Get the sub string describing IPv6 address and convert it.
3248 Status
= NetLibAsciiStrToIp6 (Ip6Str
, Ip6Address
);
3249 if (EFI_ERROR (Status
)) {
3254 // If input string doesn't indicate the prefix length, return 0xff.
3259 // Convert the string to prefix length
3261 if (PrefixStr
!= NULL
) {
3263 Status
= EFI_INVALID_PARAMETER
;
3265 while (*PrefixStr
!= '\0') {
3266 if (NET_IS_DIGIT (*PrefixStr
)) {
3267 Length
= (UINT8
) (Length
* 10 + (*PrefixStr
- '0'));
3268 if (Length
>= IP6_PREFIX_NUM
) {
3279 *PrefixLength
= Length
;
3280 Status
= EFI_SUCCESS
;
3290 Convert one EFI_IPv6_ADDRESS to Null-terminated Unicode string.
3291 The text representation of address is defined in RFC 4291.
3293 @param[in] Ip6Address The pointer to the IPv6 address.
3294 @param[out] String The buffer to return the converted string.
3295 @param[in] StringSize The length in bytes of the input String.
3297 @retval EFI_SUCCESS Convert to string successfully.
3298 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
3299 @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small for the result. BufferSize has been
3300 updated with the size needed to complete the request.
3305 IN EFI_IPv6_ADDRESS
*Ip6Address
,
3312 UINTN LongestZerosStart
;
3313 UINTN LongestZerosLength
;
3314 UINTN CurrentZerosStart
;
3315 UINTN CurrentZerosLength
;
3316 CHAR16 Buffer
[sizeof"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"];
3319 if (Ip6Address
== NULL
|| String
== NULL
|| StringSize
== 0) {
3320 return EFI_INVALID_PARAMETER
;
3324 // Convert the UINT8 array to an UINT16 array for easy handling.
3326 ZeroMem (Ip6Addr
, sizeof (Ip6Addr
));
3327 for (Index
= 0; Index
< 16; Index
++) {
3328 Ip6Addr
[Index
/ 2] |= (Ip6Address
->Addr
[Index
] << ((1 - (Index
% 2)) << 3));
3332 // Find the longest zeros and mark it.
3334 CurrentZerosStart
= DEFAULT_ZERO_START
;
3335 CurrentZerosLength
= 0;
3336 LongestZerosStart
= DEFAULT_ZERO_START
;
3337 LongestZerosLength
= 0;
3338 for (Index
= 0; Index
< 8; Index
++) {
3339 if (Ip6Addr
[Index
] == 0) {
3340 if (CurrentZerosStart
== DEFAULT_ZERO_START
) {
3341 CurrentZerosStart
= Index
;
3342 CurrentZerosLength
= 1;
3344 CurrentZerosLength
++;
3347 if (CurrentZerosStart
!= DEFAULT_ZERO_START
) {
3348 if (CurrentZerosLength
> 2 && (LongestZerosStart
== (DEFAULT_ZERO_START
) || CurrentZerosLength
> LongestZerosLength
)) {
3349 LongestZerosStart
= CurrentZerosStart
;
3350 LongestZerosLength
= CurrentZerosLength
;
3352 CurrentZerosStart
= DEFAULT_ZERO_START
;
3353 CurrentZerosLength
= 0;
3358 if (CurrentZerosStart
!= DEFAULT_ZERO_START
&& CurrentZerosLength
> 2) {
3359 if (LongestZerosStart
== DEFAULT_ZERO_START
|| LongestZerosLength
< CurrentZerosLength
) {
3360 LongestZerosStart
= CurrentZerosStart
;
3361 LongestZerosLength
= CurrentZerosLength
;
3366 for (Index
= 0; Index
< 8; Index
++) {
3367 if (LongestZerosStart
!= DEFAULT_ZERO_START
&& Index
>= LongestZerosStart
&& Index
< LongestZerosStart
+ LongestZerosLength
) {
3368 if (Index
== LongestZerosStart
) {
3376 Ptr
+= UnicodeSPrint(Ptr
, 10, L
"%x", Ip6Addr
[Index
]);
3379 if (LongestZerosStart
!= DEFAULT_ZERO_START
&& LongestZerosStart
+ LongestZerosLength
== 8) {
3384 if ((UINTN
)Ptr
- (UINTN
)Buffer
> StringSize
) {
3385 return EFI_BUFFER_TOO_SMALL
;
3388 StrCpy (String
, Buffer
);
3394 This function obtains the system guid from the smbios table.
3396 @param[out] SystemGuid The pointer of the returned system guid.
3398 @retval EFI_SUCCESS Successfully obtained the system guid.
3399 @retval EFI_NOT_FOUND Did not find the SMBIOS table.
3404 NetLibGetSystemGuid (
3405 OUT EFI_GUID
*SystemGuid
3409 SMBIOS_TABLE_ENTRY_POINT
*SmbiosTable
;
3410 SMBIOS_STRUCTURE_POINTER Smbios
;
3411 SMBIOS_STRUCTURE_POINTER SmbiosEnd
;
3415 Status
= EfiGetSystemConfigurationTable (&gEfiSmbiosTableGuid
, (VOID
**) &SmbiosTable
);
3417 if (EFI_ERROR (Status
) || SmbiosTable
== NULL
) {
3418 return EFI_NOT_FOUND
;
3421 Smbios
.Hdr
= (SMBIOS_STRUCTURE
*) (UINTN
) SmbiosTable
->TableAddress
;
3422 SmbiosEnd
.Raw
= (UINT8
*) (UINTN
) (SmbiosTable
->TableAddress
+ SmbiosTable
->TableLength
);
3425 if (Smbios
.Hdr
->Type
== 1) {
3426 if (Smbios
.Hdr
->Length
< 0x19) {
3428 // Older version did not support UUID.
3430 return EFI_NOT_FOUND
;
3434 // SMBIOS tables are byte packed so we need to do a byte copy to
3435 // prevend alignment faults on Itanium-based platform.
3437 CopyMem (SystemGuid
, &Smbios
.Type1
->Uuid
, sizeof (EFI_GUID
));
3442 // Go to the next SMBIOS structure. Each SMBIOS structure may include 2 parts:
3443 // 1. Formatted section; 2. Unformatted string section. So, 2 steps are needed
3444 // to skip one SMBIOS structure.
3448 // Step 1: Skip over formatted section.
3450 String
= (CHAR8
*) (Smbios
.Raw
+ Smbios
.Hdr
->Length
);
3453 // Step 2: Skip over unformated string section.
3457 // Each string is terminated with a NULL(00h) BYTE and the sets of strings
3458 // is terminated with an additional NULL(00h) BYTE.
3460 for ( ; *String
!= 0; String
++) {
3463 if (*(UINT8
*)++String
== 0) {
3465 // Pointer to the next SMBIOS structure.
3467 Smbios
.Raw
= (UINT8
*)++String
;
3471 } while (Smbios
.Raw
< SmbiosEnd
.Raw
);
3472 return EFI_NOT_FOUND
;