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.
858 Get current time first. Then initialize a random seed based on some basic
859 mathematics operation on the hour, day, minute, second, nanosecond and year
862 @return The random seed initialized with current time.
874 gRT
->GetTime (&Time
, NULL
);
875 Seed
= (~Time
.Hour
<< 24 | Time
.Day
<< 16 | Time
.Minute
<< 8 | Time
.Second
);
876 Seed
^= Time
.Nanosecond
;
877 Seed
^= Time
.Year
<< 7;
884 Extract a UINT32 from a byte stream.
886 Copy a UINT32 from a byte stream, then converts it from Network
887 byte order to host byte order. Use this function to avoid alignment error.
889 @param[in] Buf The buffer to extract the UINT32.
891 @return The UINT32 extracted.
902 CopyMem (&Value
, Buf
, sizeof (UINT32
));
903 return NTOHL (Value
);
908 Put a UINT32 to the byte stream in network byte order.
910 Converts a UINT32 from host byte order to network byte order. Then copy it to the
913 @param[in, out] Buf The buffer to put the UINT32.
914 @param[in] Data The data to be converted and put into the byte stream.
925 CopyMem (Buf
, &Data
, sizeof (UINT32
));
930 Remove the first node entry on the list, and return the removed node entry.
932 Removes the first node Entry from a doubly linked list. It is up to the caller of
933 this function to release the memory used by the first node if that is required. On
934 exit, the removed node is returned.
936 If Head is NULL, then ASSERT().
937 If Head was not initialized, then ASSERT().
938 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
939 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
942 @param[in, out] Head The list header.
944 @return The first node entry that is removed from the list, NULL if the list is empty.
950 IN OUT LIST_ENTRY
*Head
955 ASSERT (Head
!= NULL
);
957 if (IsListEmpty (Head
)) {
961 First
= Head
->ForwardLink
;
962 Head
->ForwardLink
= First
->ForwardLink
;
963 First
->ForwardLink
->BackLink
= Head
;
966 First
->ForwardLink
= (LIST_ENTRY
*) NULL
;
967 First
->BackLink
= (LIST_ENTRY
*) NULL
;
975 Remove the last node entry on the list and and return the removed node entry.
977 Removes the last node entry from a doubly linked list. It is up to the caller of
978 this function to release the memory used by the first node if that is required. On
979 exit, the removed node is returned.
981 If Head is NULL, then ASSERT().
982 If Head was not initialized, then ASSERT().
983 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
984 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
987 @param[in, out] Head The list head.
989 @return The last node entry that is removed from the list, NULL if the list is empty.
995 IN OUT LIST_ENTRY
*Head
1000 ASSERT (Head
!= NULL
);
1002 if (IsListEmpty (Head
)) {
1006 Last
= Head
->BackLink
;
1007 Head
->BackLink
= Last
->BackLink
;
1008 Last
->BackLink
->ForwardLink
= Head
;
1011 Last
->ForwardLink
= (LIST_ENTRY
*) NULL
;
1012 Last
->BackLink
= (LIST_ENTRY
*) NULL
;
1020 Insert a new node entry after a designated node entry of a doubly linked list.
1022 Inserts a new node entry donated by NewEntry after the node entry donated by PrevEntry
1023 of the doubly linked list.
1025 @param[in, out] PrevEntry The previous entry to insert after.
1026 @param[in, out] NewEntry The new entry to insert.
1031 NetListInsertAfter (
1032 IN OUT LIST_ENTRY
*PrevEntry
,
1033 IN OUT LIST_ENTRY
*NewEntry
1036 NewEntry
->BackLink
= PrevEntry
;
1037 NewEntry
->ForwardLink
= PrevEntry
->ForwardLink
;
1038 PrevEntry
->ForwardLink
->BackLink
= NewEntry
;
1039 PrevEntry
->ForwardLink
= NewEntry
;
1044 Insert a new node entry before a designated node entry of a doubly linked list.
1046 Inserts a new node entry donated by NewEntry after the node entry donated by PostEntry
1047 of the doubly linked list.
1049 @param[in, out] PostEntry The entry to insert before.
1050 @param[in, out] NewEntry The new entry to insert.
1055 NetListInsertBefore (
1056 IN OUT LIST_ENTRY
*PostEntry
,
1057 IN OUT LIST_ENTRY
*NewEntry
1060 NewEntry
->ForwardLink
= PostEntry
;
1061 NewEntry
->BackLink
= PostEntry
->BackLink
;
1062 PostEntry
->BackLink
->ForwardLink
= NewEntry
;
1063 PostEntry
->BackLink
= NewEntry
;
1067 Safe destroy nodes in a linked list, and return the length of the list after all possible operations finished.
1069 Destroy network child instance list by list traversals is not safe due to graph dependencies between nodes.
1070 This function performs a safe traversal to destroy these nodes by checking to see if the node being destroyed
1071 has been removed from the list or not.
1072 If it has been removed, then restart the traversal from the head.
1073 If it hasn't been removed, then continue with the next node directly.
1074 This function will end the iterate and return the CallBack's last return value if error happens,
1075 or retrun EFI_SUCCESS if 2 complete passes are made with no changes in the number of children in the list.
1077 @param[in] List The head of the list.
1078 @param[in] CallBack Pointer to the callback function to destroy one node in the list.
1079 @param[in] Context Pointer to the callback function's context: corresponds to the
1080 parameter Context in NET_DESTROY_LINK_LIST_CALLBACK.
1081 @param[out] ListLength The length of the link list if the function returns successfully.
1083 @retval EFI_SUCCESS Two complete passes are made with no changes in the number of children.
1084 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
1085 @retval Others Return the CallBack's last return value.
1090 NetDestroyLinkList (
1091 IN LIST_ENTRY
*List
,
1092 IN NET_DESTROY_LINK_LIST_CALLBACK CallBack
,
1093 IN VOID
*Context
, OPTIONAL
1094 OUT UINTN
*ListLength OPTIONAL
1097 UINTN PreviousLength
;
1103 if (List
== NULL
|| CallBack
== NULL
) {
1104 return EFI_INVALID_PARAMETER
;
1109 PreviousLength
= Length
;
1110 Entry
= GetFirstNode (List
);
1111 while (!IsNull (List
, Entry
)) {
1112 Status
= CallBack (Entry
, Context
);
1113 if (EFI_ERROR (Status
)) {
1117 // Walk through the list to see whether the Entry has been removed or not.
1118 // If the Entry still exists, just try to destroy the next one.
1119 // If not, go back to the start point to iterate the list again.
1121 for (Ptr
= List
->ForwardLink
; Ptr
!= List
; Ptr
= Ptr
->ForwardLink
) {
1127 Entry
= GetNextNode (List
, Entry
);
1129 Entry
= GetFirstNode (List
);
1132 for (Length
= 0, Ptr
= List
->ForwardLink
; Ptr
!= List
; Length
++, Ptr
= Ptr
->ForwardLink
);
1133 } while (Length
!= PreviousLength
);
1135 if (ListLength
!= NULL
) {
1136 *ListLength
= Length
;
1142 This function checks the input Handle to see if it's one of these handles in ChildHandleBuffer.
1144 @param[in] Handle Handle to be checked.
1145 @param[in] NumberOfChildren Number of Handles in ChildHandleBuffer.
1146 @param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
1147 if NumberOfChildren is 0.
1149 @retval TURE Found the input Handle in ChildHandleBuffer.
1150 @retval FALSE Can't find the input Handle in ChildHandleBuffer.
1155 NetIsInHandleBuffer (
1156 IN EFI_HANDLE Handle
,
1157 IN UINTN NumberOfChildren
,
1158 IN EFI_HANDLE
*ChildHandleBuffer OPTIONAL
1163 if (NumberOfChildren
== 0 || ChildHandleBuffer
== NULL
) {
1167 for (Index
= 0; Index
< NumberOfChildren
; Index
++) {
1168 if (Handle
== ChildHandleBuffer
[Index
]) {
1178 Initialize the netmap. Netmap is a reposity to keep the <Key, Value> pairs.
1180 Initialize the forward and backward links of two head nodes donated by Map->Used
1181 and Map->Recycled of two doubly linked lists.
1182 Initializes the count of the <Key, Value> pairs in the netmap to zero.
1184 If Map is NULL, then ASSERT().
1185 If the address of Map->Used is NULL, then ASSERT().
1186 If the address of Map->Recycled is NULl, then ASSERT().
1188 @param[in, out] Map The netmap to initialize.
1197 ASSERT (Map
!= NULL
);
1199 InitializeListHead (&Map
->Used
);
1200 InitializeListHead (&Map
->Recycled
);
1206 To clean up the netmap, that is, release allocated memories.
1208 Removes all nodes of the Used doubly linked list and free memory of all related netmap items.
1209 Removes all nodes of the Recycled doubly linked list and free memory of all related netmap items.
1210 The number of the <Key, Value> pairs in the netmap is set to be zero.
1212 If Map is NULL, then ASSERT().
1214 @param[in, out] Map The netmap to clean up.
1227 ASSERT (Map
!= NULL
);
1229 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, &Map
->Used
) {
1230 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1232 RemoveEntryList (&Item
->Link
);
1235 gBS
->FreePool (Item
);
1238 ASSERT ((Map
->Count
== 0) && IsListEmpty (&Map
->Used
));
1240 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, &Map
->Recycled
) {
1241 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1243 RemoveEntryList (&Item
->Link
);
1244 gBS
->FreePool (Item
);
1247 ASSERT (IsListEmpty (&Map
->Recycled
));
1252 Test whether the netmap is empty and return true if it is.
1254 If the number of the <Key, Value> pairs in the netmap is zero, return TRUE.
1256 If Map is NULL, then ASSERT().
1259 @param[in] Map The net map to test.
1261 @return TRUE if the netmap is empty, otherwise FALSE.
1270 ASSERT (Map
!= NULL
);
1271 return (BOOLEAN
) (Map
->Count
== 0);
1276 Return the number of the <Key, Value> pairs in the netmap.
1278 @param[in] Map The netmap to get the entry number.
1280 @return The entry number in the netmap.
1294 Return one allocated item.
1296 If the Recycled doubly linked list of the netmap is empty, it will try to allocate
1297 a batch of items if there are enough resources and add corresponding nodes to the begining
1298 of the Recycled doubly linked list of the netmap. Otherwise, it will directly remove
1299 the fist node entry of the Recycled doubly linked list and return the corresponding item.
1301 If Map is NULL, then ASSERT().
1303 @param[in, out] Map The netmap to allocate item for.
1305 @return The allocated item. If NULL, the
1306 allocation failed due to resource limit.
1318 ASSERT (Map
!= NULL
);
1320 Head
= &Map
->Recycled
;
1322 if (IsListEmpty (Head
)) {
1323 for (Index
= 0; Index
< NET_MAP_INCREAMENT
; Index
++) {
1324 Item
= AllocatePool (sizeof (NET_MAP_ITEM
));
1334 InsertHeadList (Head
, &Item
->Link
);
1338 Item
= NET_LIST_HEAD (Head
, NET_MAP_ITEM
, Link
);
1339 NetListRemoveHead (Head
);
1346 Allocate an item to save the <Key, Value> pair to the head of the netmap.
1348 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1349 to the beginning of the Used doubly linked list. The number of the <Key, Value>
1350 pairs in the netmap increase by 1.
1352 If Map is NULL, then ASSERT().
1354 @param[in, out] Map The netmap to insert into.
1355 @param[in] Key The user's key.
1356 @param[in] Value The user's value for the key.
1358 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1359 @retval EFI_SUCCESS The item is inserted to the head.
1365 IN OUT NET_MAP
*Map
,
1367 IN VOID
*Value OPTIONAL
1372 ASSERT (Map
!= NULL
);
1374 Item
= NetMapAllocItem (Map
);
1377 return EFI_OUT_OF_RESOURCES
;
1381 Item
->Value
= Value
;
1382 InsertHeadList (&Map
->Used
, &Item
->Link
);
1390 Allocate an item to save the <Key, Value> pair to the tail of the netmap.
1392 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1393 to the tail of the Used doubly linked list. The number of the <Key, Value>
1394 pairs in the netmap increase by 1.
1396 If Map is NULL, then ASSERT().
1398 @param[in, out] Map The netmap to insert into.
1399 @param[in] Key The user's key.
1400 @param[in] Value The user's value for the key.
1402 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1403 @retval EFI_SUCCESS The item is inserted to the tail.
1409 IN OUT NET_MAP
*Map
,
1411 IN VOID
*Value OPTIONAL
1416 ASSERT (Map
!= NULL
);
1418 Item
= NetMapAllocItem (Map
);
1421 return EFI_OUT_OF_RESOURCES
;
1425 Item
->Value
= Value
;
1426 InsertTailList (&Map
->Used
, &Item
->Link
);
1435 Check whether the item is in the Map and return TRUE if it is.
1437 @param[in] Map The netmap to search within.
1438 @param[in] Item The item to search.
1440 @return TRUE if the item is in the netmap, otherwise FALSE.
1446 IN NET_MAP_ITEM
*Item
1449 LIST_ENTRY
*ListEntry
;
1451 NET_LIST_FOR_EACH (ListEntry
, &Map
->Used
) {
1452 if (ListEntry
== &Item
->Link
) {
1462 Find the key in the netmap and returns the point to the item contains the Key.
1464 Iterate the Used doubly linked list of the netmap to get every item. Compare the key of every
1465 item with the key to search. It returns the point to the item contains the Key if found.
1467 If Map is NULL, then ASSERT().
1469 @param[in] Map The netmap to search within.
1470 @param[in] Key The key to search.
1472 @return The point to the item contains the Key, or NULL if Key isn't in the map.
1485 ASSERT (Map
!= NULL
);
1487 NET_LIST_FOR_EACH (Entry
, &Map
->Used
) {
1488 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1490 if (Item
->Key
== Key
) {
1500 Remove the node entry of the item from the netmap and return the key of the removed item.
1502 Remove the node entry of the item from the Used doubly linked list of the netmap.
1503 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1504 entry of the item to the Recycled doubly linked list of the netmap. If Value is not NULL,
1505 Value will point to the value of the item. It returns the key of the removed item.
1507 If Map is NULL, then ASSERT().
1508 If Item is NULL, then ASSERT().
1509 if item in not in the netmap, then ASSERT().
1511 @param[in, out] Map The netmap to remove the item from.
1512 @param[in, out] Item The item to remove.
1513 @param[out] Value The variable to receive the value if not NULL.
1515 @return The key of the removed item.
1521 IN OUT NET_MAP
*Map
,
1522 IN OUT NET_MAP_ITEM
*Item
,
1523 OUT VOID
**Value OPTIONAL
1526 ASSERT ((Map
!= NULL
) && (Item
!= NULL
));
1527 ASSERT (NetItemInMap (Map
, Item
));
1529 RemoveEntryList (&Item
->Link
);
1531 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1533 if (Value
!= NULL
) {
1534 *Value
= Item
->Value
;
1542 Remove the first node entry on the netmap and return the key of the removed item.
1544 Remove the first node entry from the Used doubly linked list of the netmap.
1545 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1546 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1547 parameter Value will point to the value of the item. It returns the key of the removed item.
1549 If Map is NULL, then ASSERT().
1550 If the Used doubly linked list is empty, then ASSERT().
1552 @param[in, out] Map The netmap to remove the head from.
1553 @param[out] Value The variable to receive the value if not NULL.
1555 @return The key of the item removed.
1561 IN OUT NET_MAP
*Map
,
1562 OUT VOID
**Value OPTIONAL
1568 // Often, it indicates a programming error to remove
1569 // the first entry in an empty list
1571 ASSERT (Map
&& !IsListEmpty (&Map
->Used
));
1573 Item
= NET_LIST_HEAD (&Map
->Used
, NET_MAP_ITEM
, Link
);
1574 RemoveEntryList (&Item
->Link
);
1576 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1578 if (Value
!= NULL
) {
1579 *Value
= Item
->Value
;
1587 Remove the last node entry on the netmap and return the key of the removed item.
1589 Remove the last node entry from the Used doubly linked list of the netmap.
1590 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1591 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1592 parameter Value will point to the value of the item. It returns the key of the removed item.
1594 If Map is NULL, then ASSERT().
1595 If the Used doubly linked list is empty, then ASSERT().
1597 @param[in, out] Map The netmap to remove the tail from.
1598 @param[out] Value The variable to receive the value if not NULL.
1600 @return The key of the item removed.
1606 IN OUT NET_MAP
*Map
,
1607 OUT VOID
**Value OPTIONAL
1613 // Often, it indicates a programming error to remove
1614 // the last entry in an empty list
1616 ASSERT (Map
&& !IsListEmpty (&Map
->Used
));
1618 Item
= NET_LIST_TAIL (&Map
->Used
, NET_MAP_ITEM
, Link
);
1619 RemoveEntryList (&Item
->Link
);
1621 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1623 if (Value
!= NULL
) {
1624 *Value
= Item
->Value
;
1632 Iterate through the netmap and call CallBack for each item.
1634 It will contiue the traverse if CallBack returns EFI_SUCCESS, otherwise, break
1635 from the loop. It returns the CallBack's last return value. This function is
1636 delete safe for the current item.
1638 If Map is NULL, then ASSERT().
1639 If CallBack is NULL, then ASSERT().
1641 @param[in] Map The Map to iterate through.
1642 @param[in] CallBack The callback function to call for each item.
1643 @param[in] Arg The opaque parameter to the callback.
1645 @retval EFI_SUCCESS There is no item in the netmap or CallBack for each item
1647 @retval Others It returns the CallBack's last return value.
1654 IN NET_MAP_CALLBACK CallBack
,
1655 IN VOID
*Arg OPTIONAL
1665 ASSERT ((Map
!= NULL
) && (CallBack
!= NULL
));
1669 if (IsListEmpty (Head
)) {
1673 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, Head
) {
1674 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1675 Result
= CallBack (Map
, Item
, Arg
);
1677 if (EFI_ERROR (Result
)) {
1687 This is the default unload handle for all the network drivers.
1689 Disconnect the driver specified by ImageHandle from all the devices in the handle database.
1690 Uninstall all the protocols installed in the driver entry point.
1692 @param[in] ImageHandle The drivers' driver image.
1694 @retval EFI_SUCCESS The image is unloaded.
1695 @retval Others Failed to unload the image.
1700 NetLibDefaultUnload (
1701 IN EFI_HANDLE ImageHandle
1705 EFI_HANDLE
*DeviceHandleBuffer
;
1706 UINTN DeviceHandleCount
;
1709 EFI_DRIVER_BINDING_PROTOCOL
*DriverBinding
;
1710 EFI_COMPONENT_NAME_PROTOCOL
*ComponentName
;
1711 EFI_COMPONENT_NAME2_PROTOCOL
*ComponentName2
;
1714 // Get the list of all the handles in the handle database.
1715 // If there is an error getting the list, then the unload
1718 Status
= gBS
->LocateHandleBuffer (
1726 if (EFI_ERROR (Status
)) {
1730 for (Index
= 0; Index
< DeviceHandleCount
; Index
++) {
1731 Status
= gBS
->HandleProtocol (
1732 DeviceHandleBuffer
[Index
],
1733 &gEfiDriverBindingProtocolGuid
,
1734 (VOID
**) &DriverBinding
1736 if (EFI_ERROR (Status
)) {
1740 if (DriverBinding
->ImageHandle
!= ImageHandle
) {
1745 // Disconnect the driver specified by ImageHandle from all
1746 // the devices in the handle database.
1748 for (Index2
= 0; Index2
< DeviceHandleCount
; Index2
++) {
1749 Status
= gBS
->DisconnectController (
1750 DeviceHandleBuffer
[Index2
],
1751 DriverBinding
->DriverBindingHandle
,
1757 // Uninstall all the protocols installed in the driver entry point
1759 gBS
->UninstallProtocolInterface (
1760 DriverBinding
->DriverBindingHandle
,
1761 &gEfiDriverBindingProtocolGuid
,
1765 Status
= gBS
->HandleProtocol (
1766 DeviceHandleBuffer
[Index
],
1767 &gEfiComponentNameProtocolGuid
,
1768 (VOID
**) &ComponentName
1770 if (!EFI_ERROR (Status
)) {
1771 gBS
->UninstallProtocolInterface (
1772 DriverBinding
->DriverBindingHandle
,
1773 &gEfiComponentNameProtocolGuid
,
1778 Status
= gBS
->HandleProtocol (
1779 DeviceHandleBuffer
[Index
],
1780 &gEfiComponentName2ProtocolGuid
,
1781 (VOID
**) &ComponentName2
1783 if (!EFI_ERROR (Status
)) {
1784 gBS
->UninstallProtocolInterface (
1785 DriverBinding
->DriverBindingHandle
,
1786 &gEfiComponentName2ProtocolGuid
,
1793 // Free the buffer containing the list of handles from the handle database
1795 if (DeviceHandleBuffer
!= NULL
) {
1796 gBS
->FreePool (DeviceHandleBuffer
);
1805 Create a child of the service that is identified by ServiceBindingGuid.
1807 Get the ServiceBinding Protocol first, then use it to create a child.
1809 If ServiceBindingGuid is NULL, then ASSERT().
1810 If ChildHandle is NULL, then ASSERT().
1812 @param[in] Controller The controller which has the service installed.
1813 @param[in] Image The image handle used to open service.
1814 @param[in] ServiceBindingGuid The service's Guid.
1815 @param[in, out] ChildHandle The handle to receive the create child.
1817 @retval EFI_SUCCESS The child is successfully created.
1818 @retval Others Failed to create the child.
1823 NetLibCreateServiceChild (
1824 IN EFI_HANDLE Controller
,
1825 IN EFI_HANDLE Image
,
1826 IN EFI_GUID
*ServiceBindingGuid
,
1827 IN OUT EFI_HANDLE
*ChildHandle
1831 EFI_SERVICE_BINDING_PROTOCOL
*Service
;
1834 ASSERT ((ServiceBindingGuid
!= NULL
) && (ChildHandle
!= NULL
));
1837 // Get the ServiceBinding Protocol
1839 Status
= gBS
->OpenProtocol (
1845 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1848 if (EFI_ERROR (Status
)) {
1855 Status
= Service
->CreateChild (Service
, ChildHandle
);
1861 Destroy a child of the service that is identified by ServiceBindingGuid.
1863 Get the ServiceBinding Protocol first, then use it to destroy a child.
1865 If ServiceBindingGuid is NULL, then ASSERT().
1867 @param[in] Controller The controller which has the service installed.
1868 @param[in] Image The image handle used to open service.
1869 @param[in] ServiceBindingGuid The service's Guid.
1870 @param[in] ChildHandle The child to destroy.
1872 @retval EFI_SUCCESS The child is successfully destroyed.
1873 @retval Others Failed to destroy the child.
1878 NetLibDestroyServiceChild (
1879 IN EFI_HANDLE Controller
,
1880 IN EFI_HANDLE Image
,
1881 IN EFI_GUID
*ServiceBindingGuid
,
1882 IN EFI_HANDLE ChildHandle
1886 EFI_SERVICE_BINDING_PROTOCOL
*Service
;
1888 ASSERT (ServiceBindingGuid
!= NULL
);
1891 // Get the ServiceBinding Protocol
1893 Status
= gBS
->OpenProtocol (
1899 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1902 if (EFI_ERROR (Status
)) {
1907 // destroy the child
1909 Status
= Service
->DestroyChild (Service
, ChildHandle
);
1914 Get handle with Simple Network Protocol installed on it.
1916 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
1917 If Simple Network Protocol is already installed on the ServiceHandle, the
1918 ServiceHandle will be returned. If SNP is not installed on the ServiceHandle,
1919 try to find its parent handle with SNP installed.
1921 @param[in] ServiceHandle The handle where network service binding protocols are
1923 @param[out] Snp The pointer to store the address of the SNP instance.
1924 This is an optional parameter that may be NULL.
1926 @return The SNP handle, or NULL if not found.
1931 NetLibGetSnpHandle (
1932 IN EFI_HANDLE ServiceHandle
,
1933 OUT EFI_SIMPLE_NETWORK_PROTOCOL
**Snp OPTIONAL
1937 EFI_SIMPLE_NETWORK_PROTOCOL
*SnpInstance
;
1938 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
1939 EFI_HANDLE SnpHandle
;
1942 // Try to open SNP from ServiceHandle
1945 Status
= gBS
->HandleProtocol (ServiceHandle
, &gEfiSimpleNetworkProtocolGuid
, (VOID
**) &SnpInstance
);
1946 if (!EFI_ERROR (Status
)) {
1950 return ServiceHandle
;
1954 // Failed to open SNP, try to get SNP handle by LocateDevicePath()
1956 DevicePath
= DevicePathFromHandle (ServiceHandle
);
1957 if (DevicePath
== NULL
) {
1962 Status
= gBS
->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid
, &DevicePath
, &SnpHandle
);
1963 if (EFI_ERROR (Status
)) {
1965 // Failed to find SNP handle
1970 Status
= gBS
->HandleProtocol (SnpHandle
, &gEfiSimpleNetworkProtocolGuid
, (VOID
**) &SnpInstance
);
1971 if (!EFI_ERROR (Status
)) {
1982 Retrieve VLAN ID of a VLAN device handle.
1984 Search VLAN device path node in Device Path of specified ServiceHandle and
1985 return its VLAN ID. If no VLAN device path node found, then this ServiceHandle
1986 is not a VLAN device handle, and 0 will be returned.
1988 @param[in] ServiceHandle The handle where network service binding protocols are
1991 @return VLAN ID of the device handle, or 0 if not a VLAN device.
1997 IN EFI_HANDLE ServiceHandle
2000 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2001 EFI_DEVICE_PATH_PROTOCOL
*Node
;
2003 DevicePath
= DevicePathFromHandle (ServiceHandle
);
2004 if (DevicePath
== NULL
) {
2009 while (!IsDevicePathEnd (Node
)) {
2010 if (Node
->Type
== MESSAGING_DEVICE_PATH
&& Node
->SubType
== MSG_VLAN_DP
) {
2011 return ((VLAN_DEVICE_PATH
*) Node
)->VlanId
;
2013 Node
= NextDevicePathNode (Node
);
2020 Find VLAN device handle with specified VLAN ID.
2022 The VLAN child device handle is created by VLAN Config Protocol on ControllerHandle.
2023 This function will append VLAN device path node to the parent device path,
2024 and then use LocateDevicePath() to find the correct VLAN device handle.
2026 @param[in] ControllerHandle The handle where network service binding protocols are
2028 @param[in] VlanId The configured VLAN ID for the VLAN device.
2030 @return The VLAN device handle, or NULL if not found.
2035 NetLibGetVlanHandle (
2036 IN EFI_HANDLE ControllerHandle
,
2040 EFI_DEVICE_PATH_PROTOCOL
*ParentDevicePath
;
2041 EFI_DEVICE_PATH_PROTOCOL
*VlanDevicePath
;
2042 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2043 VLAN_DEVICE_PATH VlanNode
;
2046 ParentDevicePath
= DevicePathFromHandle (ControllerHandle
);
2047 if (ParentDevicePath
== NULL
) {
2052 // Construct VLAN device path
2054 CopyMem (&VlanNode
, &mNetVlanDevicePathTemplate
, sizeof (VLAN_DEVICE_PATH
));
2055 VlanNode
.VlanId
= VlanId
;
2056 VlanDevicePath
= AppendDevicePathNode (
2058 (EFI_DEVICE_PATH_PROTOCOL
*) &VlanNode
2060 if (VlanDevicePath
== NULL
) {
2065 // Find VLAN device handle
2068 DevicePath
= VlanDevicePath
;
2069 gBS
->LocateDevicePath (
2070 &gEfiDevicePathProtocolGuid
,
2074 if (!IsDevicePathEnd (DevicePath
)) {
2076 // Device path is not exactly match
2081 FreePool (VlanDevicePath
);
2086 Get MAC address associated with the network service handle.
2088 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
2089 If SNP is installed on the ServiceHandle or its parent handle, MAC address will
2090 be retrieved from SNP. If no SNP found, try to get SNP mode data use MNP.
2092 @param[in] ServiceHandle The handle where network service binding protocols are
2094 @param[out] MacAddress The pointer to store the returned MAC address.
2095 @param[out] AddressSize The length of returned MAC address.
2097 @retval EFI_SUCCESS MAC address is returned successfully.
2098 @retval Others Failed to get SNP mode data.
2103 NetLibGetMacAddress (
2104 IN EFI_HANDLE ServiceHandle
,
2105 OUT EFI_MAC_ADDRESS
*MacAddress
,
2106 OUT UINTN
*AddressSize
2110 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2111 EFI_SIMPLE_NETWORK_MODE
*SnpMode
;
2112 EFI_SIMPLE_NETWORK_MODE SnpModeData
;
2113 EFI_MANAGED_NETWORK_PROTOCOL
*Mnp
;
2114 EFI_SERVICE_BINDING_PROTOCOL
*MnpSb
;
2115 EFI_HANDLE
*SnpHandle
;
2116 EFI_HANDLE MnpChildHandle
;
2118 ASSERT (MacAddress
!= NULL
);
2119 ASSERT (AddressSize
!= NULL
);
2122 // Try to get SNP handle
2125 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2126 if (SnpHandle
!= NULL
) {
2128 // SNP found, use it directly
2130 SnpMode
= Snp
->Mode
;
2133 // Failed to get SNP handle, try to get MAC address from MNP
2135 MnpChildHandle
= NULL
;
2136 Status
= gBS
->HandleProtocol (
2138 &gEfiManagedNetworkServiceBindingProtocolGuid
,
2141 if (EFI_ERROR (Status
)) {
2146 // Create a MNP child
2148 Status
= MnpSb
->CreateChild (MnpSb
, &MnpChildHandle
);
2149 if (EFI_ERROR (Status
)) {
2154 // Open MNP protocol
2156 Status
= gBS
->HandleProtocol (
2158 &gEfiManagedNetworkProtocolGuid
,
2161 if (EFI_ERROR (Status
)) {
2162 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2167 // Try to get SNP mode from MNP
2169 Status
= Mnp
->GetModeData (Mnp
, NULL
, &SnpModeData
);
2170 if (EFI_ERROR (Status
) && (Status
!= EFI_NOT_STARTED
)) {
2171 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2174 SnpMode
= &SnpModeData
;
2177 // Destroy the MNP child
2179 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2182 *AddressSize
= SnpMode
->HwAddressSize
;
2183 CopyMem (MacAddress
->Addr
, SnpMode
->CurrentAddress
.Addr
, SnpMode
->HwAddressSize
);
2189 Convert MAC address of the NIC associated with specified Service Binding Handle
2190 to a unicode string. Callers are responsible for freeing the string storage.
2192 Locate simple network protocol associated with the Service Binding Handle and
2193 get the mac address from SNP. Then convert the mac address into a unicode
2194 string. It takes 2 unicode characters to represent a 1 byte binary buffer.
2195 Plus one unicode character for the null-terminator.
2197 @param[in] ServiceHandle The handle where network service binding protocol is
2199 @param[in] ImageHandle The image handle used to act as the agent handle to
2200 get the simple network protocol. This parameter is
2201 optional and may be NULL.
2202 @param[out] MacString The pointer to store the address of the string
2203 representation of the mac address.
2205 @retval EFI_SUCCESS Convert the mac address a unicode string successfully.
2206 @retval EFI_OUT_OF_RESOURCES There are not enough memory resource.
2207 @retval Others Failed to open the simple network protocol.
2212 NetLibGetMacString (
2213 IN EFI_HANDLE ServiceHandle
,
2214 IN EFI_HANDLE ImageHandle
, OPTIONAL
2215 OUT CHAR16
**MacString
2219 EFI_MAC_ADDRESS MacAddress
;
2221 UINTN HwAddressSize
;
2226 ASSERT (MacString
!= NULL
);
2229 // Get MAC address of the network device
2231 Status
= NetLibGetMacAddress (ServiceHandle
, &MacAddress
, &HwAddressSize
);
2232 if (EFI_ERROR (Status
)) {
2237 // It takes 2 unicode characters to represent a 1 byte binary buffer.
2238 // If VLAN is configured, it will need extra 5 characters like "\0005".
2239 // Plus one unicode character for the null-terminator.
2241 String
= AllocateZeroPool ((2 * HwAddressSize
+ 5 + 1) * sizeof (CHAR16
));
2242 if (String
== NULL
) {
2243 return EFI_OUT_OF_RESOURCES
;
2245 *MacString
= String
;
2248 // Convert the MAC address into a unicode string.
2250 HwAddress
= &MacAddress
.Addr
[0];
2251 for (Index
= 0; Index
< HwAddressSize
; Index
++) {
2252 String
+= UnicodeValueToString (String
, PREFIX_ZERO
| RADIX_HEX
, *(HwAddress
++), 2);
2256 // Append VLAN ID if any
2258 VlanId
= NetLibGetVlanId (ServiceHandle
);
2261 String
+= UnicodeValueToString (String
, PREFIX_ZERO
| RADIX_HEX
, VlanId
, 4);
2265 // Null terminate the Unicode string
2273 Detect media status for specified network device.
2275 The underlying UNDI driver may or may not support reporting media status from
2276 GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine
2277 will try to invoke Snp->GetStatus() to get the media status: if media already
2278 present, it return directly; if media not present, it will stop SNP and then
2279 restart SNP to get the latest media status, this give chance to get the correct
2280 media status for old UNDI driver which doesn't support reporting media status
2281 from GET_STATUS command.
2282 Note: there will be two limitations for current algorithm:
2283 1) for UNDI with this capability, in case of cable is not attached, there will
2284 be an redundant Stop/Start() process;
2285 2) for UNDI without this capability, in case that network cable is attached when
2286 Snp->Initialize() is invoked while network cable is unattached later,
2287 NetLibDetectMedia() will report MediaPresent as TRUE, causing upper layer
2288 apps to wait for timeout time.
2290 @param[in] ServiceHandle The handle where network service binding protocols are
2292 @param[out] MediaPresent The pointer to store the media status.
2294 @retval EFI_SUCCESS Media detection success.
2295 @retval EFI_INVALID_PARAMETER ServiceHandle is not valid network device handle.
2296 @retval EFI_UNSUPPORTED Network device does not support media detection.
2297 @retval EFI_DEVICE_ERROR SNP is in unknown state.
2303 IN EFI_HANDLE ServiceHandle
,
2304 OUT BOOLEAN
*MediaPresent
2308 EFI_HANDLE SnpHandle
;
2309 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2310 UINT32 InterruptStatus
;
2312 EFI_MAC_ADDRESS
*MCastFilter
;
2313 UINT32 MCastFilterCount
;
2314 UINT32 EnableFilterBits
;
2315 UINT32 DisableFilterBits
;
2316 BOOLEAN ResetMCastFilters
;
2318 ASSERT (MediaPresent
!= NULL
);
2324 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2325 if (SnpHandle
== NULL
) {
2326 return EFI_INVALID_PARAMETER
;
2330 // Check whether SNP support media detection
2332 if (!Snp
->Mode
->MediaPresentSupported
) {
2333 return EFI_UNSUPPORTED
;
2337 // Invoke Snp->GetStatus() to refresh MediaPresent field in SNP mode data
2339 Status
= Snp
->GetStatus (Snp
, &InterruptStatus
, NULL
);
2340 if (EFI_ERROR (Status
)) {
2344 if (Snp
->Mode
->MediaPresent
) {
2346 // Media is present, return directly
2348 *MediaPresent
= TRUE
;
2353 // Till now, GetStatus() report no media; while, in case UNDI not support
2354 // reporting media status from GetStatus(), this media status may be incorrect.
2355 // So, we will stop SNP and then restart it to get the correct media status.
2357 OldState
= Snp
->Mode
->State
;
2358 if (OldState
>= EfiSimpleNetworkMaxState
) {
2359 return EFI_DEVICE_ERROR
;
2364 if (OldState
== EfiSimpleNetworkInitialized
) {
2366 // SNP is already in use, need Shutdown/Stop and then Start/Initialize
2370 // Backup current SNP receive filter settings
2372 EnableFilterBits
= Snp
->Mode
->ReceiveFilterSetting
;
2373 DisableFilterBits
= Snp
->Mode
->ReceiveFilterMask
^ EnableFilterBits
;
2375 ResetMCastFilters
= TRUE
;
2376 MCastFilterCount
= Snp
->Mode
->MCastFilterCount
;
2377 if (MCastFilterCount
!= 0) {
2378 MCastFilter
= AllocateCopyPool (
2379 MCastFilterCount
* sizeof (EFI_MAC_ADDRESS
),
2380 Snp
->Mode
->MCastFilter
2382 ASSERT (MCastFilter
!= NULL
);
2384 ResetMCastFilters
= FALSE
;
2388 // Shutdown/Stop the simple network
2390 Status
= Snp
->Shutdown (Snp
);
2391 if (!EFI_ERROR (Status
)) {
2392 Status
= Snp
->Stop (Snp
);
2394 if (EFI_ERROR (Status
)) {
2399 // Start/Initialize the simple network
2401 Status
= Snp
->Start (Snp
);
2402 if (!EFI_ERROR (Status
)) {
2403 Status
= Snp
->Initialize (Snp
, 0, 0);
2405 if (EFI_ERROR (Status
)) {
2410 // Here we get the correct media status
2412 *MediaPresent
= Snp
->Mode
->MediaPresent
;
2415 // Restore SNP receive filter settings
2417 Status
= Snp
->ReceiveFilters (
2426 if (MCastFilter
!= NULL
) {
2427 FreePool (MCastFilter
);
2434 // SNP is not in use, it's in state of EfiSimpleNetworkStopped or EfiSimpleNetworkStarted
2436 if (OldState
== EfiSimpleNetworkStopped
) {
2438 // SNP not start yet, start it
2440 Status
= Snp
->Start (Snp
);
2441 if (EFI_ERROR (Status
)) {
2447 // Initialize the simple network
2449 Status
= Snp
->Initialize (Snp
, 0, 0);
2450 if (EFI_ERROR (Status
)) {
2451 Status
= EFI_DEVICE_ERROR
;
2456 // Here we get the correct media status
2458 *MediaPresent
= Snp
->Mode
->MediaPresent
;
2461 // Shut down the simple network
2463 Snp
->Shutdown (Snp
);
2466 if (OldState
== EfiSimpleNetworkStopped
) {
2468 // Original SNP sate is Stopped, restore to original state
2473 if (MCastFilter
!= NULL
) {
2474 FreePool (MCastFilter
);
2481 Check the default address used by the IPv4 driver is static or dynamic (acquired
2484 If the controller handle does not have the EFI_IP4_CONFIG2_PROTOCOL installed, the
2485 default address is static. If failed to get the policy from Ip4 Config2 Protocol,
2486 the default address is static. Otherwise, get the result from Ip4 Config2 Protocol.
2488 @param[in] Controller The controller handle which has the EFI_IP4_CONFIG2_PROTOCOL
2489 relative with the default address to judge.
2491 @retval TRUE If the default address is static.
2492 @retval FALSE If the default address is acquired from DHCP.
2496 NetLibDefaultAddressIsStatic (
2497 IN EFI_HANDLE Controller
2501 EFI_IP4_CONFIG2_PROTOCOL
*Ip4Config2
;
2503 EFI_IP4_CONFIG2_POLICY Policy
;
2508 DataSize
= sizeof (EFI_IP4_CONFIG2_POLICY
);
2513 // Get Ip4Config2 policy.
2515 Status
= gBS
->HandleProtocol (Controller
, &gEfiIp4Config2ProtocolGuid
, (VOID
**) &Ip4Config2
);
2516 if (EFI_ERROR (Status
)) {
2520 Status
= Ip4Config2
->GetData (Ip4Config2
, Ip4Config2DataTypePolicy
, &DataSize
, &Policy
);
2521 if (EFI_ERROR (Status
)) {
2525 IsStatic
= (BOOLEAN
) (Policy
== Ip4Config2PolicyStatic
);
2533 Create an IPv4 device path node.
2535 The header type of IPv4 device path node is MESSAGING_DEVICE_PATH.
2536 The header subtype of IPv4 device path node is MSG_IPv4_DP.
2537 Get other info from parameters to make up the whole IPv4 device path node.
2539 @param[in, out] Node Pointer to the IPv4 device path node.
2540 @param[in] Controller The controller handle.
2541 @param[in] LocalIp The local IPv4 address.
2542 @param[in] LocalPort The local port.
2543 @param[in] RemoteIp The remote IPv4 address.
2544 @param[in] RemotePort The remote port.
2545 @param[in] Protocol The protocol type in the IP header.
2546 @param[in] UseDefaultAddress Whether this instance is using default address or not.
2551 NetLibCreateIPv4DPathNode (
2552 IN OUT IPv4_DEVICE_PATH
*Node
,
2553 IN EFI_HANDLE Controller
,
2554 IN IP4_ADDR LocalIp
,
2555 IN UINT16 LocalPort
,
2556 IN IP4_ADDR RemoteIp
,
2557 IN UINT16 RemotePort
,
2559 IN BOOLEAN UseDefaultAddress
2562 Node
->Header
.Type
= MESSAGING_DEVICE_PATH
;
2563 Node
->Header
.SubType
= MSG_IPv4_DP
;
2564 SetDevicePathNodeLength (&Node
->Header
, sizeof (IPv4_DEVICE_PATH
));
2566 CopyMem (&Node
->LocalIpAddress
, &LocalIp
, sizeof (EFI_IPv4_ADDRESS
));
2567 CopyMem (&Node
->RemoteIpAddress
, &RemoteIp
, sizeof (EFI_IPv4_ADDRESS
));
2569 Node
->LocalPort
= LocalPort
;
2570 Node
->RemotePort
= RemotePort
;
2572 Node
->Protocol
= Protocol
;
2574 if (!UseDefaultAddress
) {
2575 Node
->StaticIpAddress
= TRUE
;
2577 Node
->StaticIpAddress
= NetLibDefaultAddressIsStatic (Controller
);
2581 // Set the Gateway IP address to default value 0:0:0:0.
2582 // Set the Subnet mask to default value 255:255:255:0.
2584 ZeroMem (&Node
->GatewayIpAddress
, sizeof (EFI_IPv4_ADDRESS
));
2585 SetMem (&Node
->SubnetMask
, sizeof (EFI_IPv4_ADDRESS
), 0xff);
2586 Node
->SubnetMask
.Addr
[3] = 0;
2590 Create an IPv6 device path node.
2592 The header type of IPv6 device path node is MESSAGING_DEVICE_PATH.
2593 The header subtype of IPv6 device path node is MSG_IPv6_DP.
2594 Get other info from parameters to make up the whole IPv6 device path node.
2596 @param[in, out] Node Pointer to the IPv6 device path node.
2597 @param[in] Controller The controller handle.
2598 @param[in] LocalIp The local IPv6 address.
2599 @param[in] LocalPort The local port.
2600 @param[in] RemoteIp The remote IPv6 address.
2601 @param[in] RemotePort The remote port.
2602 @param[in] Protocol The protocol type in the IP header.
2607 NetLibCreateIPv6DPathNode (
2608 IN OUT IPv6_DEVICE_PATH
*Node
,
2609 IN EFI_HANDLE Controller
,
2610 IN EFI_IPv6_ADDRESS
*LocalIp
,
2611 IN UINT16 LocalPort
,
2612 IN EFI_IPv6_ADDRESS
*RemoteIp
,
2613 IN UINT16 RemotePort
,
2617 Node
->Header
.Type
= MESSAGING_DEVICE_PATH
;
2618 Node
->Header
.SubType
= MSG_IPv6_DP
;
2619 SetDevicePathNodeLength (&Node
->Header
, sizeof (IPv6_DEVICE_PATH
));
2621 CopyMem (&Node
->LocalIpAddress
, LocalIp
, sizeof (EFI_IPv6_ADDRESS
));
2622 CopyMem (&Node
->RemoteIpAddress
, RemoteIp
, sizeof (EFI_IPv6_ADDRESS
));
2624 Node
->LocalPort
= LocalPort
;
2625 Node
->RemotePort
= RemotePort
;
2627 Node
->Protocol
= Protocol
;
2630 // Set default value to IPAddressOrigin, PrefixLength.
2631 // Set the Gateway IP address to unspecified address.
2633 Node
->IpAddressOrigin
= 0;
2634 Node
->PrefixLength
= IP6_PREFIX_LENGTH
;
2635 ZeroMem (&Node
->GatewayIpAddress
, sizeof (EFI_IPv6_ADDRESS
));
2639 Find the UNDI/SNP handle from controller and protocol GUID.
2641 For example, IP will open a MNP child to transmit/receive
2642 packets, when MNP is stopped, IP should also be stopped. IP
2643 needs to find its own private data which is related the IP's
2644 service binding instance that is install on UNDI/SNP handle.
2645 Now, the controller is either a MNP or ARP child handle. But
2646 IP opens these handle BY_DRIVER, use that info, we can get the
2649 @param[in] Controller Then protocol handle to check.
2650 @param[in] ProtocolGuid The protocol that is related with the handle.
2652 @return The UNDI/SNP handle or NULL for errors.
2657 NetLibGetNicHandle (
2658 IN EFI_HANDLE Controller
,
2659 IN EFI_GUID
*ProtocolGuid
2662 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY
*OpenBuffer
;
2668 Status
= gBS
->OpenProtocolInformation (
2675 if (EFI_ERROR (Status
)) {
2681 for (Index
= 0; Index
< OpenCount
; Index
++) {
2682 if ((OpenBuffer
[Index
].Attributes
& EFI_OPEN_PROTOCOL_BY_DRIVER
) != 0) {
2683 Handle
= OpenBuffer
[Index
].ControllerHandle
;
2688 gBS
->FreePool (OpenBuffer
);
2693 Convert one Null-terminated ASCII string (decimal dotted) to EFI_IPv4_ADDRESS.
2695 @param[in] String The pointer to the Ascii string.
2696 @param[out] Ip4Address The pointer to the converted IPv4 address.
2698 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2699 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2704 NetLibAsciiStrToIp4 (
2705 IN CONST CHAR8
*String
,
2706 OUT EFI_IPv4_ADDRESS
*Ip4Address
2714 if ((String
== NULL
) || (Ip4Address
== NULL
)) {
2715 return EFI_INVALID_PARAMETER
;
2718 Ip4Str
= (CHAR8
*) String
;
2720 for (Index
= 0; Index
< 4; Index
++) {
2723 while ((*Ip4Str
!= '\0') && (*Ip4Str
!= '.')) {
2728 // The IPv4 address is X.X.X.X
2730 if (*Ip4Str
== '.') {
2732 return EFI_INVALID_PARAMETER
;
2736 return EFI_INVALID_PARAMETER
;
2741 // Convert the string to IPv4 address. AsciiStrDecimalToUintn stops at the
2742 // first character that is not a valid decimal character, '.' or '\0' here.
2744 NodeVal
= AsciiStrDecimalToUintn (TempStr
);
2745 if (NodeVal
> 0xFF) {
2746 return EFI_INVALID_PARAMETER
;
2749 Ip4Address
->Addr
[Index
] = (UINT8
) NodeVal
;
2759 Convert one Null-terminated ASCII string to EFI_IPv6_ADDRESS. The format of the
2760 string is defined in RFC 4291 - Text Pepresentation of Addresses.
2762 @param[in] String The pointer to the Ascii string.
2763 @param[out] Ip6Address The pointer to the converted IPv6 address.
2765 @retval EFI_SUCCESS Convert to IPv6 address successfully.
2766 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
2771 NetLibAsciiStrToIp6 (
2772 IN CONST CHAR8
*String
,
2773 OUT EFI_IPv6_ADDRESS
*Ip6Address
2790 if ((String
== NULL
) || (Ip6Address
== NULL
)) {
2791 return EFI_INVALID_PARAMETER
;
2794 Ip6Str
= (CHAR8
*) String
;
2799 // An IPv6 address leading with : looks strange.
2801 if (*Ip6Str
== ':') {
2802 if (*(Ip6Str
+ 1) != ':') {
2803 return EFI_INVALID_PARAMETER
;
2809 ZeroMem (Ip6Address
, sizeof (EFI_IPv6_ADDRESS
));
2817 for (Index
= 0; Index
< 15; Index
= (UINT8
) (Index
+ 2)) {
2820 while ((*Ip6Str
!= '\0') && (*Ip6Str
!= ':')) {
2824 if ((*Ip6Str
== '\0') && (Index
!= 14)) {
2825 return EFI_INVALID_PARAMETER
;
2828 if (*Ip6Str
== ':') {
2829 if (*(Ip6Str
+ 1) == ':') {
2830 if ((NodeCnt
> 6) ||
2831 ((*(Ip6Str
+ 2) != '\0') && (AsciiStrHexToUintn (Ip6Str
+ 2) == 0))) {
2833 // ::0 looks strange. report error to user.
2835 return EFI_INVALID_PARAMETER
;
2837 if ((NodeCnt
== 6) && (*(Ip6Str
+ 2) != '\0') &&
2838 (AsciiStrHexToUintn (Ip6Str
+ 2) != 0)) {
2839 return EFI_INVALID_PARAMETER
;
2843 // Skip the abbreviation part of IPv6 address.
2845 TempStr2
= Ip6Str
+ 2;
2846 while ((*TempStr2
!= '\0')) {
2847 if (*TempStr2
== ':') {
2848 if (*(TempStr2
+ 1) == ':') {
2850 // :: can only appear once in IPv6 address.
2852 return EFI_INVALID_PARAMETER
;
2856 if (TailNodeCnt
>= (AllowedCnt
- NodeCnt
)) {
2858 // :: indicates one or more groups of 16 bits of zeros.
2860 return EFI_INVALID_PARAMETER
;
2870 Ip6Str
= Ip6Str
+ 2;
2872 if (*(Ip6Str
+ 1) == '\0') {
2873 return EFI_INVALID_PARAMETER
;
2877 if ((Short
&& (NodeCnt
> 6)) || (!Short
&& (NodeCnt
> 7))) {
2879 // There are more than 8 groups of 16 bits of zeros.
2881 return EFI_INVALID_PARAMETER
;
2887 // Convert the string to IPv6 address. AsciiStrHexToUintn stops at the first
2888 // character that is not a valid hexadecimal character, ':' or '\0' here.
2890 NodeVal
= AsciiStrHexToUintn (TempStr
);
2891 if ((NodeVal
> 0xFFFF) || (Index
> 14)) {
2892 return EFI_INVALID_PARAMETER
;
2895 if ((*TempStr
== '0') &&
2896 ((*(TempStr
+ 2) == ':') || (*(TempStr
+ 3) == ':') ||
2897 (*(TempStr
+ 2) == '\0') || (*(TempStr
+ 3) == '\0'))) {
2898 return EFI_INVALID_PARAMETER
;
2900 if ((*TempStr
== '0') && (*(TempStr
+ 4) != '\0') &&
2901 (*(TempStr
+ 4) != ':')) {
2902 return EFI_INVALID_PARAMETER
;
2905 if (((*TempStr
== '0') && (*(TempStr
+ 1) == '0') &&
2906 ((*(TempStr
+ 2) == ':') || (*(TempStr
+ 2) == '\0'))) ||
2907 ((*TempStr
== '0') && (*(TempStr
+ 1) == '0') && (*(TempStr
+ 2) == '0') &&
2908 ((*(TempStr
+ 3) == ':') || (*(TempStr
+ 3) == '\0')))) {
2909 return EFI_INVALID_PARAMETER
;
2914 while ((TempStr
[Cnt
] != ':') && (TempStr
[Cnt
] != '\0')) {
2917 if (LeadZeroCnt
== 0) {
2918 if ((Cnt
== 4) && (*TempStr
== '0')) {
2922 if ((Cnt
!= 0) && (Cnt
< 4)) {
2927 if ((Cnt
== 4) && (*TempStr
== '0') && !LeadZero
) {
2928 return EFI_INVALID_PARAMETER
;
2930 if ((Cnt
!= 0) && (Cnt
< 4) && LeadZero
) {
2931 return EFI_INVALID_PARAMETER
;
2935 Ip6Address
->Addr
[Index
] = (UINT8
) (NodeVal
>> 8);
2936 Ip6Address
->Addr
[Index
+ 1] = (UINT8
) (NodeVal
& 0xFF);
2939 // Skip the groups of zeros by ::
2941 if (Short
&& Update
) {
2942 Index
= (UINT8
) (16 - (TailNodeCnt
+ 2) * 2);
2947 if ((!Short
&& Index
!= 16) || (*Ip6Str
!= '\0')) {
2948 return EFI_INVALID_PARAMETER
;
2956 Convert one Null-terminated Unicode string (decimal dotted) to EFI_IPv4_ADDRESS.
2958 @param[in] String The pointer to the Ascii string.
2959 @param[out] Ip4Address The pointer to the converted IPv4 address.
2961 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2962 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2963 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
2969 IN CONST CHAR16
*String
,
2970 OUT EFI_IPv4_ADDRESS
*Ip4Address
2976 if ((String
== NULL
) || (Ip4Address
== NULL
)) {
2977 return EFI_INVALID_PARAMETER
;
2980 Ip4Str
= (CHAR8
*) AllocatePool ((StrLen (String
) + 1) * sizeof (CHAR8
));
2981 if (Ip4Str
== NULL
) {
2982 return EFI_OUT_OF_RESOURCES
;
2985 UnicodeStrToAsciiStr (String
, Ip4Str
);
2987 Status
= NetLibAsciiStrToIp4 (Ip4Str
, Ip4Address
);
2996 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS. The format of
2997 the string is defined in RFC 4291 - Text Pepresentation of Addresses.
2999 @param[in] String The pointer to the Ascii string.
3000 @param[out] Ip6Address The pointer to the converted IPv6 address.
3002 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3003 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3004 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3010 IN CONST CHAR16
*String
,
3011 OUT EFI_IPv6_ADDRESS
*Ip6Address
3017 if ((String
== NULL
) || (Ip6Address
== NULL
)) {
3018 return EFI_INVALID_PARAMETER
;
3021 Ip6Str
= (CHAR8
*) AllocatePool ((StrLen (String
) + 1) * sizeof (CHAR8
));
3022 if (Ip6Str
== NULL
) {
3023 return EFI_OUT_OF_RESOURCES
;
3026 UnicodeStrToAsciiStr (String
, Ip6Str
);
3028 Status
= NetLibAsciiStrToIp6 (Ip6Str
, Ip6Address
);
3036 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS and prefix length.
3037 The format of the string is defined in RFC 4291 - Text Pepresentation of Addresses
3038 Prefixes: ipv6-address/prefix-length.
3040 @param[in] String The pointer to the Ascii string.
3041 @param[out] Ip6Address The pointer to the converted IPv6 address.
3042 @param[out] PrefixLength The pointer to the converted prefix length.
3044 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3045 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3046 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3051 NetLibStrToIp6andPrefix (
3052 IN CONST CHAR16
*String
,
3053 OUT EFI_IPv6_ADDRESS
*Ip6Address
,
3054 OUT UINT8
*PrefixLength
3063 if ((String
== NULL
) || (Ip6Address
== NULL
) || (PrefixLength
== NULL
)) {
3064 return EFI_INVALID_PARAMETER
;
3067 Ip6Str
= (CHAR8
*) AllocatePool ((StrLen (String
) + 1) * sizeof (CHAR8
));
3068 if (Ip6Str
== NULL
) {
3069 return EFI_OUT_OF_RESOURCES
;
3072 UnicodeStrToAsciiStr (String
, Ip6Str
);
3075 // Get the sub string describing prefix length.
3078 while (*TempStr
!= '\0' && (*TempStr
!= '/')) {
3082 if (*TempStr
== '/') {
3083 PrefixStr
= TempStr
+ 1;
3089 // Get the sub string describing IPv6 address and convert it.
3093 Status
= NetLibAsciiStrToIp6 (Ip6Str
, Ip6Address
);
3094 if (EFI_ERROR (Status
)) {
3099 // If input string doesn't indicate the prefix length, return 0xff.
3104 // Convert the string to prefix length
3106 if (PrefixStr
!= NULL
) {
3108 Status
= EFI_INVALID_PARAMETER
;
3110 while (*PrefixStr
!= '\0') {
3111 if (NET_IS_DIGIT (*PrefixStr
)) {
3112 Length
= (UINT8
) (Length
* 10 + (*PrefixStr
- '0'));
3113 if (Length
>= IP6_PREFIX_NUM
) {
3124 *PrefixLength
= Length
;
3125 Status
= EFI_SUCCESS
;
3135 Convert one EFI_IPv6_ADDRESS to Null-terminated Unicode string.
3136 The text representation of address is defined in RFC 4291.
3138 @param[in] Ip6Address The pointer to the IPv6 address.
3139 @param[out] String The buffer to return the converted string.
3140 @param[in] StringSize The length in bytes of the input String.
3142 @retval EFI_SUCCESS Convert to string successfully.
3143 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
3144 @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small for the result. BufferSize has been
3145 updated with the size needed to complete the request.
3150 IN EFI_IPv6_ADDRESS
*Ip6Address
,
3157 UINTN LongestZerosStart
;
3158 UINTN LongestZerosLength
;
3159 UINTN CurrentZerosStart
;
3160 UINTN CurrentZerosLength
;
3161 CHAR16 Buffer
[sizeof"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"];
3164 if (Ip6Address
== NULL
|| String
== NULL
|| StringSize
== 0) {
3165 return EFI_INVALID_PARAMETER
;
3169 // Convert the UINT8 array to an UINT16 array for easy handling.
3171 ZeroMem (Ip6Addr
, sizeof (Ip6Addr
));
3172 for (Index
= 0; Index
< 16; Index
++) {
3173 Ip6Addr
[Index
/ 2] |= (Ip6Address
->Addr
[Index
] << ((1 - (Index
% 2)) << 3));
3177 // Find the longest zeros and mark it.
3179 CurrentZerosStart
= DEFAULT_ZERO_START
;
3180 CurrentZerosLength
= 0;
3181 LongestZerosStart
= DEFAULT_ZERO_START
;
3182 LongestZerosLength
= 0;
3183 for (Index
= 0; Index
< 8; Index
++) {
3184 if (Ip6Addr
[Index
] == 0) {
3185 if (CurrentZerosStart
== DEFAULT_ZERO_START
) {
3186 CurrentZerosStart
= Index
;
3187 CurrentZerosLength
= 1;
3189 CurrentZerosLength
++;
3192 if (CurrentZerosStart
!= DEFAULT_ZERO_START
) {
3193 if (CurrentZerosLength
> 2 && (LongestZerosStart
== (DEFAULT_ZERO_START
) || CurrentZerosLength
> LongestZerosLength
)) {
3194 LongestZerosStart
= CurrentZerosStart
;
3195 LongestZerosLength
= CurrentZerosLength
;
3197 CurrentZerosStart
= DEFAULT_ZERO_START
;
3198 CurrentZerosLength
= 0;
3203 if (CurrentZerosStart
!= DEFAULT_ZERO_START
&& CurrentZerosLength
> 2) {
3204 if (LongestZerosStart
== DEFAULT_ZERO_START
|| LongestZerosLength
< CurrentZerosLength
) {
3205 LongestZerosStart
= CurrentZerosStart
;
3206 LongestZerosLength
= CurrentZerosLength
;
3211 for (Index
= 0; Index
< 8; Index
++) {
3212 if (LongestZerosStart
!= DEFAULT_ZERO_START
&& Index
>= LongestZerosStart
&& Index
< LongestZerosStart
+ LongestZerosLength
) {
3213 if (Index
== LongestZerosStart
) {
3221 Ptr
+= UnicodeSPrint(Ptr
, 10, L
"%x", Ip6Addr
[Index
]);
3224 if (LongestZerosStart
!= DEFAULT_ZERO_START
&& LongestZerosStart
+ LongestZerosLength
== 8) {
3229 if ((UINTN
)Ptr
- (UINTN
)Buffer
> StringSize
) {
3230 return EFI_BUFFER_TOO_SMALL
;
3233 StrCpy (String
, Buffer
);
3239 This function obtains the system guid from the smbios table.
3241 @param[out] SystemGuid The pointer of the returned system guid.
3243 @retval EFI_SUCCESS Successfully obtained the system guid.
3244 @retval EFI_NOT_FOUND Did not find the SMBIOS table.
3249 NetLibGetSystemGuid (
3250 OUT EFI_GUID
*SystemGuid
3254 SMBIOS_TABLE_ENTRY_POINT
*SmbiosTable
;
3255 SMBIOS_STRUCTURE_POINTER Smbios
;
3256 SMBIOS_STRUCTURE_POINTER SmbiosEnd
;
3260 Status
= EfiGetSystemConfigurationTable (&gEfiSmbiosTableGuid
, (VOID
**) &SmbiosTable
);
3262 if (EFI_ERROR (Status
) || SmbiosTable
== NULL
) {
3263 return EFI_NOT_FOUND
;
3266 Smbios
.Hdr
= (SMBIOS_STRUCTURE
*) (UINTN
) SmbiosTable
->TableAddress
;
3267 SmbiosEnd
.Raw
= (UINT8
*) (UINTN
) (SmbiosTable
->TableAddress
+ SmbiosTable
->TableLength
);
3270 if (Smbios
.Hdr
->Type
== 1) {
3271 if (Smbios
.Hdr
->Length
< 0x19) {
3273 // Older version did not support UUID.
3275 return EFI_NOT_FOUND
;
3279 // SMBIOS tables are byte packed so we need to do a byte copy to
3280 // prevend alignment faults on Itanium-based platform.
3282 CopyMem (SystemGuid
, &Smbios
.Type1
->Uuid
, sizeof (EFI_GUID
));
3287 // Go to the next SMBIOS structure. Each SMBIOS structure may include 2 parts:
3288 // 1. Formatted section; 2. Unformatted string section. So, 2 steps are needed
3289 // to skip one SMBIOS structure.
3293 // Step 1: Skip over formatted section.
3295 String
= (CHAR8
*) (Smbios
.Raw
+ Smbios
.Hdr
->Length
);
3298 // Step 2: Skip over unformated string section.
3302 // Each string is terminated with a NULL(00h) BYTE and the sets of strings
3303 // is terminated with an additional NULL(00h) BYTE.
3305 for ( ; *String
!= 0; String
++) {
3308 if (*(UINT8
*)++String
== 0) {
3310 // Pointer to the next SMBIOS structure.
3312 Smbios
.Raw
= (UINT8
*)++String
;
3316 } while (Smbios
.Raw
< SmbiosEnd
.Raw
);
3317 return EFI_NOT_FOUND
;