4 Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
5 (C) Copyright 2015 Hewlett Packard Enterprise Development LP<BR>
6 This program and the accompanying materials
7 are licensed and made available under the terms and conditions of the BSD License
8 which accompanies this distribution. The full text of the license may be found at
9 http://opensource.org/licenses/bsd-license.php
11 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
12 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
17 #include <IndustryStandard/SmBios.h>
19 #include <Protocol/DriverBinding.h>
20 #include <Protocol/ServiceBinding.h>
21 #include <Protocol/SimpleNetwork.h>
22 #include <Protocol/AdapterInformation.h>
23 #include <Protocol/ManagedNetwork.h>
24 #include <Protocol/Ip4Config2.h>
25 #include <Protocol/ComponentName.h>
26 #include <Protocol/ComponentName2.h>
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/PrintLib.h>
39 #include <Library/UefiLib.h>
41 #define NIC_ITEM_CONFIG_SIZE (sizeof (NIC_IP4_CONFIG_INFO) + sizeof (EFI_IP4_ROUTE_TABLE) * MAX_IP4_CONFIG_IN_VARIABLE)
42 #define DEFAULT_ZERO_START ((UINTN) ~0)
45 // All the supported IP4 maskes in host byte order.
47 GLOBAL_REMOVE_IF_UNREFERENCED IP4_ADDR gIp4AllMasks
[IP4_MASK_NUM
] = {
86 GLOBAL_REMOVE_IF_UNREFERENCED EFI_IPv4_ADDRESS mZeroIp4Addr
= {{0, 0, 0, 0}};
89 // Any error level digitally larger than mNetDebugLevelMax
90 // will be silently discarded.
92 GLOBAL_REMOVE_IF_UNREFERENCED UINTN mNetDebugLevelMax
= NETDEBUG_LEVEL_ERROR
;
93 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogPacketSeq
= 0xDEADBEEF;
96 // You can change mSyslogDstMac mSyslogDstIp and mSyslogSrcIp
97 // here to direct the syslog packets to the syslog deamon. The
98 // default is broadcast to both the ethernet and IP.
100 GLOBAL_REMOVE_IF_UNREFERENCED UINT8 mSyslogDstMac
[NET_ETHER_ADDR_LEN
] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
101 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogDstIp
= 0xffffffff;
102 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogSrcIp
= 0;
104 GLOBAL_REMOVE_IF_UNREFERENCED CHAR8
*mMonthName
[] = {
120 // VLAN device path node template
122 GLOBAL_REMOVE_IF_UNREFERENCED VLAN_DEVICE_PATH mNetVlanDevicePathTemplate
= {
124 MESSAGING_DEVICE_PATH
,
127 (UINT8
) (sizeof (VLAN_DEVICE_PATH
)),
128 (UINT8
) ((sizeof (VLAN_DEVICE_PATH
)) >> 8)
135 Locate the handles that support SNP, then open one of them
136 to send the syslog packets. The caller isn't required to close
137 the SNP after use because the SNP is opened by HandleProtocol.
139 @return The point to SNP if one is properly openned. Otherwise NULL
142 EFI_SIMPLE_NETWORK_PROTOCOL
*
147 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
154 // Locate the handles which has SNP installed.
157 Status
= gBS
->LocateHandleBuffer (
159 &gEfiSimpleNetworkProtocolGuid
,
165 if (EFI_ERROR (Status
) || (HandleCount
== 0)) {
170 // Try to open one of the ethernet SNP protocol to send packet
174 for (Index
= 0; Index
< HandleCount
; Index
++) {
175 Status
= gBS
->HandleProtocol (
177 &gEfiSimpleNetworkProtocolGuid
,
181 if ((Status
== EFI_SUCCESS
) && (Snp
!= NULL
) &&
182 (Snp
->Mode
->IfType
== NET_IFTYPE_ETHERNET
) &&
183 (Snp
->Mode
->MaxPacketSize
>= NET_SYSLOG_PACKET_LEN
)) {
196 Transmit a syslog packet synchronously through SNP. The Packet
197 already has the ethernet header prepended. This function should
198 fill in the source MAC because it will try to locate a SNP each
199 time it is called to avoid the problem if SNP is unloaded.
200 This code snip is copied from MNP.
202 @param[in] Packet The Syslog packet
203 @param[in] Length The length of the packet
205 @retval EFI_DEVICE_ERROR Failed to locate a usable SNP protocol
206 @retval EFI_TIMEOUT Timeout happened to send the packet.
207 @retval EFI_SUCCESS Packet is sent.
216 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
219 EFI_EVENT TimeoutEvent
;
222 Snp
= SyslogLocateSnp ();
225 return EFI_DEVICE_ERROR
;
228 Ether
= (ETHER_HEAD
*) Packet
;
229 CopyMem (Ether
->SrcMac
, Snp
->Mode
->CurrentAddress
.Addr
, NET_ETHER_ADDR_LEN
);
232 // Start the timeout event.
234 Status
= gBS
->CreateEvent (
242 if (EFI_ERROR (Status
)) {
246 Status
= gBS
->SetTimer (TimeoutEvent
, TimerRelative
, NET_SYSLOG_TX_TIMEOUT
);
248 if (EFI_ERROR (Status
)) {
254 // Transmit the packet through SNP.
256 Status
= Snp
->Transmit (Snp
, 0, Length
, Packet
, NULL
, NULL
, NULL
);
258 if ((Status
!= EFI_SUCCESS
) && (Status
!= EFI_NOT_READY
)) {
259 Status
= EFI_DEVICE_ERROR
;
264 // If Status is EFI_SUCCESS, the packet is put in the transmit queue.
265 // if Status is EFI_NOT_READY, the transmit engine of the network
266 // interface is busy. Both need to sync SNP.
272 // Get the recycled transmit buffer status.
274 Snp
->GetStatus (Snp
, NULL
, (VOID
**) &TxBuf
);
276 if (!EFI_ERROR (gBS
->CheckEvent (TimeoutEvent
))) {
277 Status
= EFI_TIMEOUT
;
281 } while (TxBuf
== NULL
);
283 if ((Status
== EFI_SUCCESS
) || (Status
== EFI_TIMEOUT
)) {
288 // Status is EFI_NOT_READY. Restart the timer event and
289 // call Snp->Transmit again.
291 gBS
->SetTimer (TimeoutEvent
, TimerRelative
, NET_SYSLOG_TX_TIMEOUT
);
294 gBS
->SetTimer (TimeoutEvent
, TimerCancel
, 0);
297 gBS
->CloseEvent (TimeoutEvent
);
302 Build a syslog packet, including the Ethernet/Ip/Udp headers
305 @param[in] Level Syslog severity level
306 @param[in] Module The module that generates the log
307 @param[in] File The file that contains the current log
308 @param[in] Line The line of code in the File that contains the current log
309 @param[in] Message The log message
310 @param[in] BufLen The lenght of the Buf
311 @param[out] Buf The buffer to put the packet data
313 @return The length of the syslog packet built.
329 EFI_UDP_HEADER
*Udp4
;
335 // Fill in the Ethernet header. Leave alone the source MAC.
336 // SyslogSendPacket will fill in the address for us.
338 Ether
= (ETHER_HEAD
*) Buf
;
339 CopyMem (Ether
->DstMac
, mSyslogDstMac
, NET_ETHER_ADDR_LEN
);
340 ZeroMem (Ether
->SrcMac
, NET_ETHER_ADDR_LEN
);
342 Ether
->EtherType
= HTONS (0x0800); // IPv4 protocol
344 Buf
+= sizeof (ETHER_HEAD
);
345 BufLen
-= sizeof (ETHER_HEAD
);
348 // Fill in the IP header
350 Ip4
= (IP4_HEAD
*) Buf
;
355 Ip4
->Id
= (UINT16
) mSyslogPacketSeq
;
358 Ip4
->Protocol
= 0x11;
360 Ip4
->Src
= mSyslogSrcIp
;
361 Ip4
->Dst
= mSyslogDstIp
;
363 Buf
+= sizeof (IP4_HEAD
);
364 BufLen
-= sizeof (IP4_HEAD
);
367 // Fill in the UDP header, Udp checksum is optional. Leave it zero.
369 Udp4
= (EFI_UDP_HEADER
*) Buf
;
370 Udp4
->SrcPort
= HTONS (514);
371 Udp4
->DstPort
= HTONS (514);
375 Buf
+= sizeof (EFI_UDP_HEADER
);
376 BufLen
-= sizeof (EFI_UDP_HEADER
);
379 // Build the syslog message body with <PRI> Timestamp machine module Message
381 Pri
= ((NET_SYSLOG_FACILITY
& 31) << 3) | (Level
& 7);
382 gRT
->GetTime (&Time
, NULL
);
383 ASSERT ((Time
.Month
<= 12) && (Time
.Month
>= 1));
386 // Use %a to format the ASCII strings, %s to format UNICODE strings
389 Len
+= (UINT32
) AsciiSPrint (
392 "<%d> %a %d %d:%d:%d ",
394 mMonthName
[Time
.Month
-1],
402 Len
+= (UINT32
) AsciiSPrint (
405 "Tiano %a: %a (Line: %d File: %a)",
414 // OK, patch the IP length/checksum and UDP length fields.
416 Len
+= sizeof (EFI_UDP_HEADER
);
417 Udp4
->Length
= HTONS ((UINT16
) Len
);
419 Len
+= sizeof (IP4_HEAD
);
420 Ip4
->TotalLen
= HTONS ((UINT16
) Len
);
421 Ip4
->Checksum
= (UINT16
) (~NetblockChecksum ((UINT8
*) Ip4
, sizeof (IP4_HEAD
)));
423 return Len
+ sizeof (ETHER_HEAD
);
427 Allocate a buffer, then format the message to it. This is a
428 help function for the NET_DEBUG_XXX macros. The PrintArg of
429 these macros treats the variable length print parameters as a
430 single parameter, and pass it to the NetDebugASPrint. For
431 example, NET_DEBUG_TRACE ("Tcp", ("State transit to %a\n", Name))
435 NETDEBUG_LEVEL_TRACE,
439 NetDebugASPrint ("State transit to %a\n", Name)
442 @param Format The ASCII format string.
443 @param ... The variable length parameter whose format is determined
444 by the Format string.
446 @return The buffer containing the formatted message,
447 or NULL if failed to allocate memory.
460 Buf
= (CHAR8
*) AllocatePool (NET_DEBUG_MSG_LEN
);
466 VA_START (Marker
, Format
);
467 AsciiVSPrint (Buf
, NET_DEBUG_MSG_LEN
, Format
, Marker
);
474 Builds an UDP4 syslog packet and send it using SNP.
476 This function will locate a instance of SNP then send the message through it.
477 Because it isn't open the SNP BY_DRIVER, apply caution when using it.
479 @param Level The severity level of the message.
480 @param Module The Moudle that generates the log.
481 @param File The file that contains the log.
482 @param Line The exact line that contains the log.
483 @param Message The user message to log.
485 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
486 @retval EFI_OUT_OF_RESOURCES Failed to allocate memory for the packet
487 @retval EFI_SUCCESS The log is discard because that it is more verbose
488 than the mNetDebugLevelMax. Or, it has been sent out.
505 // Check whether the message should be sent out
507 if (Message
== NULL
) {
508 return EFI_INVALID_PARAMETER
;
511 if (Level
> mNetDebugLevelMax
) {
512 Status
= EFI_SUCCESS
;
517 // Allocate a maxium of 1024 bytes, the caller should ensure
518 // that the message plus the ethernet/ip/udp header is shorter
521 Packet
= (CHAR8
*) AllocatePool (NET_SYSLOG_PACKET_LEN
);
523 if (Packet
== NULL
) {
524 Status
= EFI_OUT_OF_RESOURCES
;
529 // Build the message: Ethernet header + IP header + Udp Header + user data
531 Len
= SyslogBuildPacket (
537 NET_SYSLOG_PACKET_LEN
,
542 Status
= SyslogSendPacket (Packet
, Len
);
550 Return the length of the mask.
552 Return the length of the mask, the correct value is from 0 to 32.
553 If the mask is invalid, return the invalid length 33, which is IP4_MASK_NUM.
554 NetMask is in the host byte order.
556 @param[in] NetMask The netmask to get the length from.
558 @return The length of the netmask, IP4_MASK_NUM if the mask is invalid.
569 for (Index
= 0; Index
<= IP4_MASK_MAX
; Index
++) {
570 if (NetMask
== gIp4AllMasks
[Index
]) {
581 Return the class of the IP address, such as class A, B, C.
582 Addr is in host byte order.
585 Classful addressing (IP class A/B/C) has been deprecated according to RFC4632.
586 Caller of this function could only check the returned value against
587 IP4_ADDR_CLASSD (multicast) or IP4_ADDR_CLASSE (reserved) now.
589 The address of class A starts with 0.
590 If the address belong to class A, return IP4_ADDR_CLASSA.
591 The address of class B starts with 10.
592 If the address belong to class B, return IP4_ADDR_CLASSB.
593 The address of class C starts with 110.
594 If the address belong to class C, return IP4_ADDR_CLASSC.
595 The address of class D starts with 1110.
596 If the address belong to class D, return IP4_ADDR_CLASSD.
597 The address of class E starts with 1111.
598 If the address belong to class E, return IP4_ADDR_CLASSE.
601 @param[in] Addr The address to get the class from.
603 @return IP address class, such as IP4_ADDR_CLASSA.
614 ByteOne
= (UINT8
) (Addr
>> 24);
616 if ((ByteOne
& 0x80) == 0) {
617 return IP4_ADDR_CLASSA
;
619 } else if ((ByteOne
& 0xC0) == 0x80) {
620 return IP4_ADDR_CLASSB
;
622 } else if ((ByteOne
& 0xE0) == 0xC0) {
623 return IP4_ADDR_CLASSC
;
625 } else if ((ByteOne
& 0xF0) == 0xE0) {
626 return IP4_ADDR_CLASSD
;
629 return IP4_ADDR_CLASSE
;
636 Check whether the IP is a valid unicast address according to
639 ASSERT if NetMask is zero.
641 If all bits of the host address of IP are 0 or 1, IP is also not a valid unicast address,
642 except when the originator is one of the endpoints of a point-to-point link with a 31-bit
645 @param[in] Ip The IP to check against.
646 @param[in] NetMask The mask of the IP.
648 @return TRUE if IP is a valid unicast address on the network, otherwise FALSE.
658 ASSERT (NetMask
!= 0);
660 if (Ip
== 0 || IP4_IS_LOCAL_BROADCAST (Ip
)) {
664 if (NetGetMaskLength (NetMask
) != 31) {
665 if (((Ip
&~NetMask
) == ~NetMask
) || ((Ip
&~NetMask
) == 0)) {
676 Check whether the incoming IPv6 address is a valid unicast address.
678 If the address is a multicast address has binary 0xFF at the start, it is not
679 a valid unicast address. If the address is unspecified ::, it is not a valid
680 unicast address to be assigned to any node. If the address is loopback address
681 ::1, it is also not a valid unicast address to be assigned to any physical
684 @param[in] Ip6 The IPv6 address to check against.
686 @return TRUE if Ip6 is a valid unicast address on the network, otherwise FALSE.
691 NetIp6IsValidUnicast (
692 IN EFI_IPv6_ADDRESS
*Ip6
698 if (Ip6
->Addr
[0] == 0xFF) {
702 for (Index
= 0; Index
< 15; Index
++) {
703 if (Ip6
->Addr
[Index
] != 0) {
708 Byte
= Ip6
->Addr
[Index
];
710 if (Byte
== 0x0 || Byte
== 0x1) {
718 Check whether the incoming Ipv6 address is the unspecified address or not.
720 @param[in] Ip6 - Ip6 address, in network order.
722 @retval TRUE - Yes, unspecified
728 NetIp6IsUnspecifiedAddr (
729 IN EFI_IPv6_ADDRESS
*Ip6
734 for (Index
= 0; Index
< 16; Index
++) {
735 if (Ip6
->Addr
[Index
] != 0) {
744 Check whether the incoming Ipv6 address is a link-local address.
746 @param[in] Ip6 - Ip6 address, in network order.
748 @retval TRUE - Yes, link-local address
754 NetIp6IsLinkLocalAddr (
755 IN EFI_IPv6_ADDRESS
*Ip6
760 ASSERT (Ip6
!= NULL
);
762 if (Ip6
->Addr
[0] != 0xFE) {
766 if (Ip6
->Addr
[1] != 0x80) {
770 for (Index
= 2; Index
< 8; Index
++) {
771 if (Ip6
->Addr
[Index
] != 0) {
780 Check whether the Ipv6 address1 and address2 are on the connected network.
782 @param[in] Ip1 - Ip6 address1, in network order.
783 @param[in] Ip2 - Ip6 address2, in network order.
784 @param[in] PrefixLength - The prefix length of the checking net.
786 @retval TRUE - Yes, connected.
793 EFI_IPv6_ADDRESS
*Ip1
,
794 EFI_IPv6_ADDRESS
*Ip2
,
802 ASSERT ((Ip1
!= NULL
) && (Ip2
!= NULL
) && (PrefixLength
<= IP6_PREFIX_MAX
));
804 if (PrefixLength
== 0) {
808 Byte
= (UINT8
) (PrefixLength
/ 8);
809 Bit
= (UINT8
) (PrefixLength
% 8);
811 if (CompareMem (Ip1
, Ip2
, Byte
) != 0) {
816 Mask
= (UINT8
) (0xFF << (8 - Bit
));
819 if ((Ip1
->Addr
[Byte
] & Mask
) != (Ip2
->Addr
[Byte
] & Mask
)) {
829 Switches the endianess of an IPv6 address
831 This function swaps the bytes in a 128-bit IPv6 address to switch the value
832 from little endian to big endian or vice versa. The byte swapped value is
835 @param Ip6 Points to an IPv6 address
837 @return The byte swapped IPv6 address.
843 EFI_IPv6_ADDRESS
*Ip6
849 CopyMem (&High
, Ip6
, sizeof (UINT64
));
850 CopyMem (&Low
, &Ip6
->Addr
[8], sizeof (UINT64
));
852 High
= SwapBytes64 (High
);
853 Low
= SwapBytes64 (Low
);
855 CopyMem (Ip6
, &Low
, sizeof (UINT64
));
856 CopyMem (&Ip6
->Addr
[8], &High
, sizeof (UINT64
));
862 Initialize a random seed using current time and monotonic count.
864 Get current time and monotonic count first. Then initialize a random seed
865 based on some basic mathematics operation on the hour, day, minute, second,
866 nanosecond and year of the current time and the monotonic count value.
868 @return The random seed initialized with current time.
879 UINT64 MonotonicCount
;
881 gRT
->GetTime (&Time
, NULL
);
882 Seed
= (Time
.Hour
<< 24 | Time
.Day
<< 16 | Time
.Minute
<< 8 | Time
.Second
);
883 Seed
^= Time
.Nanosecond
;
884 Seed
^= Time
.Year
<< 7;
886 gBS
->GetNextMonotonicCount (&MonotonicCount
);
887 Seed
+= (UINT32
) MonotonicCount
;
894 Extract a UINT32 from a byte stream.
896 Copy a UINT32 from a byte stream, then converts it from Network
897 byte order to host byte order. Use this function to avoid alignment error.
899 @param[in] Buf The buffer to extract the UINT32.
901 @return The UINT32 extracted.
912 CopyMem (&Value
, Buf
, sizeof (UINT32
));
913 return NTOHL (Value
);
918 Put a UINT32 to the byte stream in network byte order.
920 Converts a UINT32 from host byte order to network byte order. Then copy it to the
923 @param[in, out] Buf The buffer to put the UINT32.
924 @param[in] Data The data to be converted and put into the byte stream.
935 CopyMem (Buf
, &Data
, sizeof (UINT32
));
940 Remove the first node entry on the list, and return the removed node entry.
942 Removes the first node Entry from a doubly linked list. It is up to the caller of
943 this function to release the memory used by the first node if that is required. On
944 exit, the removed node is returned.
946 If Head is NULL, then ASSERT().
947 If Head was not initialized, then ASSERT().
948 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
949 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
952 @param[in, out] Head The list header.
954 @return The first node entry that is removed from the list, NULL if the list is empty.
960 IN OUT LIST_ENTRY
*Head
965 ASSERT (Head
!= NULL
);
967 if (IsListEmpty (Head
)) {
971 First
= Head
->ForwardLink
;
972 Head
->ForwardLink
= First
->ForwardLink
;
973 First
->ForwardLink
->BackLink
= Head
;
976 First
->ForwardLink
= (LIST_ENTRY
*) NULL
;
977 First
->BackLink
= (LIST_ENTRY
*) NULL
;
985 Remove the last node entry on the list and and return the removed node entry.
987 Removes the last node entry from a doubly linked list. It is up to the caller of
988 this function to release the memory used by the first node if that is required. On
989 exit, the removed node is returned.
991 If Head is NULL, then ASSERT().
992 If Head was not initialized, then ASSERT().
993 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
994 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
997 @param[in, out] Head The list head.
999 @return The last node entry that is removed from the list, NULL if the list is empty.
1005 IN OUT LIST_ENTRY
*Head
1010 ASSERT (Head
!= NULL
);
1012 if (IsListEmpty (Head
)) {
1016 Last
= Head
->BackLink
;
1017 Head
->BackLink
= Last
->BackLink
;
1018 Last
->BackLink
->ForwardLink
= Head
;
1021 Last
->ForwardLink
= (LIST_ENTRY
*) NULL
;
1022 Last
->BackLink
= (LIST_ENTRY
*) NULL
;
1030 Insert a new node entry after a designated node entry of a doubly linked list.
1032 Inserts a new node entry donated by NewEntry after the node entry donated by PrevEntry
1033 of the doubly linked list.
1035 @param[in, out] PrevEntry The previous entry to insert after.
1036 @param[in, out] NewEntry The new entry to insert.
1041 NetListInsertAfter (
1042 IN OUT LIST_ENTRY
*PrevEntry
,
1043 IN OUT LIST_ENTRY
*NewEntry
1046 NewEntry
->BackLink
= PrevEntry
;
1047 NewEntry
->ForwardLink
= PrevEntry
->ForwardLink
;
1048 PrevEntry
->ForwardLink
->BackLink
= NewEntry
;
1049 PrevEntry
->ForwardLink
= NewEntry
;
1054 Insert a new node entry before a designated node entry of a doubly linked list.
1056 Inserts a new node entry donated by NewEntry after the node entry donated by PostEntry
1057 of the doubly linked list.
1059 @param[in, out] PostEntry The entry to insert before.
1060 @param[in, out] NewEntry The new entry to insert.
1065 NetListInsertBefore (
1066 IN OUT LIST_ENTRY
*PostEntry
,
1067 IN OUT LIST_ENTRY
*NewEntry
1070 NewEntry
->ForwardLink
= PostEntry
;
1071 NewEntry
->BackLink
= PostEntry
->BackLink
;
1072 PostEntry
->BackLink
->ForwardLink
= NewEntry
;
1073 PostEntry
->BackLink
= NewEntry
;
1077 Safe destroy nodes in a linked list, and return the length of the list after all possible operations finished.
1079 Destroy network child instance list by list traversals is not safe due to graph dependencies between nodes.
1080 This function performs a safe traversal to destroy these nodes by checking to see if the node being destroyed
1081 has been removed from the list or not.
1082 If it has been removed, then restart the traversal from the head.
1083 If it hasn't been removed, then continue with the next node directly.
1084 This function will end the iterate and return the CallBack's last return value if error happens,
1085 or retrun EFI_SUCCESS if 2 complete passes are made with no changes in the number of children in the list.
1087 @param[in] List The head of the list.
1088 @param[in] CallBack Pointer to the callback function to destroy one node in the list.
1089 @param[in] Context Pointer to the callback function's context: corresponds to the
1090 parameter Context in NET_DESTROY_LINK_LIST_CALLBACK.
1091 @param[out] ListLength The length of the link list if the function returns successfully.
1093 @retval EFI_SUCCESS Two complete passes are made with no changes in the number of children.
1094 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
1095 @retval Others Return the CallBack's last return value.
1100 NetDestroyLinkList (
1101 IN LIST_ENTRY
*List
,
1102 IN NET_DESTROY_LINK_LIST_CALLBACK CallBack
,
1103 IN VOID
*Context
, OPTIONAL
1104 OUT UINTN
*ListLength OPTIONAL
1107 UINTN PreviousLength
;
1113 if (List
== NULL
|| CallBack
== NULL
) {
1114 return EFI_INVALID_PARAMETER
;
1119 PreviousLength
= Length
;
1120 Entry
= GetFirstNode (List
);
1121 while (!IsNull (List
, Entry
)) {
1122 Status
= CallBack (Entry
, Context
);
1123 if (EFI_ERROR (Status
)) {
1127 // Walk through the list to see whether the Entry has been removed or not.
1128 // If the Entry still exists, just try to destroy the next one.
1129 // If not, go back to the start point to iterate the list again.
1131 for (Ptr
= List
->ForwardLink
; Ptr
!= List
; Ptr
= Ptr
->ForwardLink
) {
1137 Entry
= GetNextNode (List
, Entry
);
1139 Entry
= GetFirstNode (List
);
1142 for (Length
= 0, Ptr
= List
->ForwardLink
; Ptr
!= List
; Length
++, Ptr
= Ptr
->ForwardLink
);
1143 } while (Length
!= PreviousLength
);
1145 if (ListLength
!= NULL
) {
1146 *ListLength
= Length
;
1152 This function checks the input Handle to see if it's one of these handles in ChildHandleBuffer.
1154 @param[in] Handle Handle to be checked.
1155 @param[in] NumberOfChildren Number of Handles in ChildHandleBuffer.
1156 @param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
1157 if NumberOfChildren is 0.
1159 @retval TRUE Found the input Handle in ChildHandleBuffer.
1160 @retval FALSE Can't find the input Handle in ChildHandleBuffer.
1165 NetIsInHandleBuffer (
1166 IN EFI_HANDLE Handle
,
1167 IN UINTN NumberOfChildren
,
1168 IN EFI_HANDLE
*ChildHandleBuffer OPTIONAL
1173 if (NumberOfChildren
== 0 || ChildHandleBuffer
== NULL
) {
1177 for (Index
= 0; Index
< NumberOfChildren
; Index
++) {
1178 if (Handle
== ChildHandleBuffer
[Index
]) {
1188 Initialize the netmap. Netmap is a reposity to keep the <Key, Value> pairs.
1190 Initialize the forward and backward links of two head nodes donated by Map->Used
1191 and Map->Recycled of two doubly linked lists.
1192 Initializes the count of the <Key, Value> pairs in the netmap to zero.
1194 If Map is NULL, then ASSERT().
1195 If the address of Map->Used is NULL, then ASSERT().
1196 If the address of Map->Recycled is NULl, then ASSERT().
1198 @param[in, out] Map The netmap to initialize.
1207 ASSERT (Map
!= NULL
);
1209 InitializeListHead (&Map
->Used
);
1210 InitializeListHead (&Map
->Recycled
);
1216 To clean up the netmap, that is, release allocated memories.
1218 Removes all nodes of the Used doubly linked list and free memory of all related netmap items.
1219 Removes all nodes of the Recycled doubly linked list and free memory of all related netmap items.
1220 The number of the <Key, Value> pairs in the netmap is set to be zero.
1222 If Map is NULL, then ASSERT().
1224 @param[in, out] Map The netmap to clean up.
1237 ASSERT (Map
!= NULL
);
1239 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, &Map
->Used
) {
1240 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1242 RemoveEntryList (&Item
->Link
);
1245 gBS
->FreePool (Item
);
1248 ASSERT ((Map
->Count
== 0) && IsListEmpty (&Map
->Used
));
1250 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, &Map
->Recycled
) {
1251 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1253 RemoveEntryList (&Item
->Link
);
1254 gBS
->FreePool (Item
);
1257 ASSERT (IsListEmpty (&Map
->Recycled
));
1262 Test whether the netmap is empty and return true if it is.
1264 If the number of the <Key, Value> pairs in the netmap is zero, return TRUE.
1266 If Map is NULL, then ASSERT().
1269 @param[in] Map The net map to test.
1271 @return TRUE if the netmap is empty, otherwise FALSE.
1280 ASSERT (Map
!= NULL
);
1281 return (BOOLEAN
) (Map
->Count
== 0);
1286 Return the number of the <Key, Value> pairs in the netmap.
1288 @param[in] Map The netmap to get the entry number.
1290 @return The entry number in the netmap.
1304 Return one allocated item.
1306 If the Recycled doubly linked list of the netmap is empty, it will try to allocate
1307 a batch of items if there are enough resources and add corresponding nodes to the begining
1308 of the Recycled doubly linked list of the netmap. Otherwise, it will directly remove
1309 the fist node entry of the Recycled doubly linked list and return the corresponding item.
1311 If Map is NULL, then ASSERT().
1313 @param[in, out] Map The netmap to allocate item for.
1315 @return The allocated item. If NULL, the
1316 allocation failed due to resource limit.
1328 ASSERT (Map
!= NULL
);
1330 Head
= &Map
->Recycled
;
1332 if (IsListEmpty (Head
)) {
1333 for (Index
= 0; Index
< NET_MAP_INCREAMENT
; Index
++) {
1334 Item
= AllocatePool (sizeof (NET_MAP_ITEM
));
1344 InsertHeadList (Head
, &Item
->Link
);
1348 Item
= NET_LIST_HEAD (Head
, NET_MAP_ITEM
, Link
);
1349 NetListRemoveHead (Head
);
1356 Allocate an item to save the <Key, Value> pair to the head of the netmap.
1358 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1359 to the beginning of the Used doubly linked list. The number of the <Key, Value>
1360 pairs in the netmap increase by 1.
1362 If Map is NULL, then ASSERT().
1364 @param[in, out] Map The netmap to insert into.
1365 @param[in] Key The user's key.
1366 @param[in] Value The user's value for the key.
1368 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1369 @retval EFI_SUCCESS The item is inserted to the head.
1375 IN OUT NET_MAP
*Map
,
1377 IN VOID
*Value OPTIONAL
1382 ASSERT (Map
!= NULL
);
1384 Item
= NetMapAllocItem (Map
);
1387 return EFI_OUT_OF_RESOURCES
;
1391 Item
->Value
= Value
;
1392 InsertHeadList (&Map
->Used
, &Item
->Link
);
1400 Allocate an item to save the <Key, Value> pair to the tail of the netmap.
1402 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1403 to the tail of the Used doubly linked list. The number of the <Key, Value>
1404 pairs in the netmap increase by 1.
1406 If Map is NULL, then ASSERT().
1408 @param[in, out] Map The netmap to insert into.
1409 @param[in] Key The user's key.
1410 @param[in] Value The user's value for the key.
1412 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1413 @retval EFI_SUCCESS The item is inserted to the tail.
1419 IN OUT NET_MAP
*Map
,
1421 IN VOID
*Value OPTIONAL
1426 ASSERT (Map
!= NULL
);
1428 Item
= NetMapAllocItem (Map
);
1431 return EFI_OUT_OF_RESOURCES
;
1435 Item
->Value
= Value
;
1436 InsertTailList (&Map
->Used
, &Item
->Link
);
1445 Check whether the item is in the Map and return TRUE if it is.
1447 @param[in] Map The netmap to search within.
1448 @param[in] Item The item to search.
1450 @return TRUE if the item is in the netmap, otherwise FALSE.
1456 IN NET_MAP_ITEM
*Item
1459 LIST_ENTRY
*ListEntry
;
1461 NET_LIST_FOR_EACH (ListEntry
, &Map
->Used
) {
1462 if (ListEntry
== &Item
->Link
) {
1472 Find the key in the netmap and returns the point to the item contains the Key.
1474 Iterate the Used doubly linked list of the netmap to get every item. Compare the key of every
1475 item with the key to search. It returns the point to the item contains the Key if found.
1477 If Map is NULL, then ASSERT().
1479 @param[in] Map The netmap to search within.
1480 @param[in] Key The key to search.
1482 @return The point to the item contains the Key, or NULL if Key isn't in the map.
1495 ASSERT (Map
!= NULL
);
1497 NET_LIST_FOR_EACH (Entry
, &Map
->Used
) {
1498 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1500 if (Item
->Key
== Key
) {
1510 Remove the node entry of the item from the netmap and return the key of the removed item.
1512 Remove the node entry of the item from the Used doubly linked list of the netmap.
1513 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1514 entry of the item to the Recycled doubly linked list of the netmap. If Value is not NULL,
1515 Value will point to the value of the item. It returns the key of the removed item.
1517 If Map is NULL, then ASSERT().
1518 If Item is NULL, then ASSERT().
1519 if item in not in the netmap, then ASSERT().
1521 @param[in, out] Map The netmap to remove the item from.
1522 @param[in, out] Item The item to remove.
1523 @param[out] Value The variable to receive the value if not NULL.
1525 @return The key of the removed item.
1531 IN OUT NET_MAP
*Map
,
1532 IN OUT NET_MAP_ITEM
*Item
,
1533 OUT VOID
**Value OPTIONAL
1536 ASSERT ((Map
!= NULL
) && (Item
!= NULL
));
1537 ASSERT (NetItemInMap (Map
, Item
));
1539 RemoveEntryList (&Item
->Link
);
1541 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1543 if (Value
!= NULL
) {
1544 *Value
= Item
->Value
;
1552 Remove the first node entry on the netmap and return the key of the removed item.
1554 Remove the first node entry from the Used doubly linked list of the netmap.
1555 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1556 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1557 parameter Value will point to the value of the item. It returns the key of the removed item.
1559 If Map is NULL, then ASSERT().
1560 If the Used doubly linked list is empty, then ASSERT().
1562 @param[in, out] Map The netmap to remove the head from.
1563 @param[out] Value The variable to receive the value if not NULL.
1565 @return The key of the item removed.
1571 IN OUT NET_MAP
*Map
,
1572 OUT VOID
**Value OPTIONAL
1578 // Often, it indicates a programming error to remove
1579 // the first entry in an empty list
1581 ASSERT (Map
&& !IsListEmpty (&Map
->Used
));
1583 Item
= NET_LIST_HEAD (&Map
->Used
, NET_MAP_ITEM
, Link
);
1584 RemoveEntryList (&Item
->Link
);
1586 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1588 if (Value
!= NULL
) {
1589 *Value
= Item
->Value
;
1597 Remove the last node entry on the netmap and return the key of the removed item.
1599 Remove the last node entry from the Used doubly linked list of the netmap.
1600 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1601 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1602 parameter Value will point to the value of the item. It returns the key of the removed item.
1604 If Map is NULL, then ASSERT().
1605 If the Used doubly linked list is empty, then ASSERT().
1607 @param[in, out] Map The netmap to remove the tail from.
1608 @param[out] Value The variable to receive the value if not NULL.
1610 @return The key of the item removed.
1616 IN OUT NET_MAP
*Map
,
1617 OUT VOID
**Value OPTIONAL
1623 // Often, it indicates a programming error to remove
1624 // the last entry in an empty list
1626 ASSERT (Map
&& !IsListEmpty (&Map
->Used
));
1628 Item
= NET_LIST_TAIL (&Map
->Used
, NET_MAP_ITEM
, Link
);
1629 RemoveEntryList (&Item
->Link
);
1631 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1633 if (Value
!= NULL
) {
1634 *Value
= Item
->Value
;
1642 Iterate through the netmap and call CallBack for each item.
1644 It will continue the traverse if CallBack returns EFI_SUCCESS, otherwise, break
1645 from the loop. It returns the CallBack's last return value. This function is
1646 delete safe for the current item.
1648 If Map is NULL, then ASSERT().
1649 If CallBack is NULL, then ASSERT().
1651 @param[in] Map The Map to iterate through.
1652 @param[in] CallBack The callback function to call for each item.
1653 @param[in] Arg The opaque parameter to the callback.
1655 @retval EFI_SUCCESS There is no item in the netmap or CallBack for each item
1657 @retval Others It returns the CallBack's last return value.
1664 IN NET_MAP_CALLBACK CallBack
,
1665 IN VOID
*Arg OPTIONAL
1675 ASSERT ((Map
!= NULL
) && (CallBack
!= NULL
));
1679 if (IsListEmpty (Head
)) {
1683 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, Head
) {
1684 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1685 Result
= CallBack (Map
, Item
, Arg
);
1687 if (EFI_ERROR (Result
)) {
1697 This is the default unload handle for all the network drivers.
1699 Disconnect the driver specified by ImageHandle from all the devices in the handle database.
1700 Uninstall all the protocols installed in the driver entry point.
1702 @param[in] ImageHandle The drivers' driver image.
1704 @retval EFI_SUCCESS The image is unloaded.
1705 @retval Others Failed to unload the image.
1710 NetLibDefaultUnload (
1711 IN EFI_HANDLE ImageHandle
1715 EFI_HANDLE
*DeviceHandleBuffer
;
1716 UINTN DeviceHandleCount
;
1719 EFI_DRIVER_BINDING_PROTOCOL
*DriverBinding
;
1720 EFI_COMPONENT_NAME_PROTOCOL
*ComponentName
;
1721 EFI_COMPONENT_NAME2_PROTOCOL
*ComponentName2
;
1724 // Get the list of all the handles in the handle database.
1725 // If there is an error getting the list, then the unload
1728 Status
= gBS
->LocateHandleBuffer (
1736 if (EFI_ERROR (Status
)) {
1740 for (Index
= 0; Index
< DeviceHandleCount
; Index
++) {
1741 Status
= gBS
->HandleProtocol (
1742 DeviceHandleBuffer
[Index
],
1743 &gEfiDriverBindingProtocolGuid
,
1744 (VOID
**) &DriverBinding
1746 if (EFI_ERROR (Status
)) {
1750 if (DriverBinding
->ImageHandle
!= ImageHandle
) {
1755 // Disconnect the driver specified by ImageHandle from all
1756 // the devices in the handle database.
1758 for (Index2
= 0; Index2
< DeviceHandleCount
; Index2
++) {
1759 Status
= gBS
->DisconnectController (
1760 DeviceHandleBuffer
[Index2
],
1761 DriverBinding
->DriverBindingHandle
,
1767 // Uninstall all the protocols installed in the driver entry point
1769 gBS
->UninstallProtocolInterface (
1770 DriverBinding
->DriverBindingHandle
,
1771 &gEfiDriverBindingProtocolGuid
,
1775 Status
= gBS
->HandleProtocol (
1776 DeviceHandleBuffer
[Index
],
1777 &gEfiComponentNameProtocolGuid
,
1778 (VOID
**) &ComponentName
1780 if (!EFI_ERROR (Status
)) {
1781 gBS
->UninstallProtocolInterface (
1782 DriverBinding
->DriverBindingHandle
,
1783 &gEfiComponentNameProtocolGuid
,
1788 Status
= gBS
->HandleProtocol (
1789 DeviceHandleBuffer
[Index
],
1790 &gEfiComponentName2ProtocolGuid
,
1791 (VOID
**) &ComponentName2
1793 if (!EFI_ERROR (Status
)) {
1794 gBS
->UninstallProtocolInterface (
1795 DriverBinding
->DriverBindingHandle
,
1796 &gEfiComponentName2ProtocolGuid
,
1803 // Free the buffer containing the list of handles from the handle database
1805 if (DeviceHandleBuffer
!= NULL
) {
1806 gBS
->FreePool (DeviceHandleBuffer
);
1815 Create a child of the service that is identified by ServiceBindingGuid.
1817 Get the ServiceBinding Protocol first, then use it to create a child.
1819 If ServiceBindingGuid is NULL, then ASSERT().
1820 If ChildHandle is NULL, then ASSERT().
1822 @param[in] Controller The controller which has the service installed.
1823 @param[in] Image The image handle used to open service.
1824 @param[in] ServiceBindingGuid The service's Guid.
1825 @param[in, out] ChildHandle The handle to receive the create child.
1827 @retval EFI_SUCCESS The child is successfully created.
1828 @retval Others Failed to create the child.
1833 NetLibCreateServiceChild (
1834 IN EFI_HANDLE Controller
,
1835 IN EFI_HANDLE Image
,
1836 IN EFI_GUID
*ServiceBindingGuid
,
1837 IN OUT EFI_HANDLE
*ChildHandle
1841 EFI_SERVICE_BINDING_PROTOCOL
*Service
;
1844 ASSERT ((ServiceBindingGuid
!= NULL
) && (ChildHandle
!= NULL
));
1847 // Get the ServiceBinding Protocol
1849 Status
= gBS
->OpenProtocol (
1855 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1858 if (EFI_ERROR (Status
)) {
1865 Status
= Service
->CreateChild (Service
, ChildHandle
);
1871 Destroy a child of the service that is identified by ServiceBindingGuid.
1873 Get the ServiceBinding Protocol first, then use it to destroy a child.
1875 If ServiceBindingGuid is NULL, then ASSERT().
1877 @param[in] Controller The controller which has the service installed.
1878 @param[in] Image The image handle used to open service.
1879 @param[in] ServiceBindingGuid The service's Guid.
1880 @param[in] ChildHandle The child to destroy.
1882 @retval EFI_SUCCESS The child is successfully destroyed.
1883 @retval Others Failed to destroy the child.
1888 NetLibDestroyServiceChild (
1889 IN EFI_HANDLE Controller
,
1890 IN EFI_HANDLE Image
,
1891 IN EFI_GUID
*ServiceBindingGuid
,
1892 IN EFI_HANDLE ChildHandle
1896 EFI_SERVICE_BINDING_PROTOCOL
*Service
;
1898 ASSERT (ServiceBindingGuid
!= NULL
);
1901 // Get the ServiceBinding Protocol
1903 Status
= gBS
->OpenProtocol (
1909 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1912 if (EFI_ERROR (Status
)) {
1917 // destroy the child
1919 Status
= Service
->DestroyChild (Service
, ChildHandle
);
1924 Get handle with Simple Network Protocol installed on it.
1926 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
1927 If Simple Network Protocol is already installed on the ServiceHandle, the
1928 ServiceHandle will be returned. If SNP is not installed on the ServiceHandle,
1929 try to find its parent handle with SNP installed.
1931 @param[in] ServiceHandle The handle where network service binding protocols are
1933 @param[out] Snp The pointer to store the address of the SNP instance.
1934 This is an optional parameter that may be NULL.
1936 @return The SNP handle, or NULL if not found.
1941 NetLibGetSnpHandle (
1942 IN EFI_HANDLE ServiceHandle
,
1943 OUT EFI_SIMPLE_NETWORK_PROTOCOL
**Snp OPTIONAL
1947 EFI_SIMPLE_NETWORK_PROTOCOL
*SnpInstance
;
1948 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
1949 EFI_HANDLE SnpHandle
;
1952 // Try to open SNP from ServiceHandle
1955 Status
= gBS
->HandleProtocol (ServiceHandle
, &gEfiSimpleNetworkProtocolGuid
, (VOID
**) &SnpInstance
);
1956 if (!EFI_ERROR (Status
)) {
1960 return ServiceHandle
;
1964 // Failed to open SNP, try to get SNP handle by LocateDevicePath()
1966 DevicePath
= DevicePathFromHandle (ServiceHandle
);
1967 if (DevicePath
== NULL
) {
1972 Status
= gBS
->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid
, &DevicePath
, &SnpHandle
);
1973 if (EFI_ERROR (Status
)) {
1975 // Failed to find SNP handle
1980 Status
= gBS
->HandleProtocol (SnpHandle
, &gEfiSimpleNetworkProtocolGuid
, (VOID
**) &SnpInstance
);
1981 if (!EFI_ERROR (Status
)) {
1992 Retrieve VLAN ID of a VLAN device handle.
1994 Search VLAN device path node in Device Path of specified ServiceHandle and
1995 return its VLAN ID. If no VLAN device path node found, then this ServiceHandle
1996 is not a VLAN device handle, and 0 will be returned.
1998 @param[in] ServiceHandle The handle where network service binding protocols are
2001 @return VLAN ID of the device handle, or 0 if not a VLAN device.
2007 IN EFI_HANDLE ServiceHandle
2010 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2011 EFI_DEVICE_PATH_PROTOCOL
*Node
;
2013 DevicePath
= DevicePathFromHandle (ServiceHandle
);
2014 if (DevicePath
== NULL
) {
2019 while (!IsDevicePathEnd (Node
)) {
2020 if (Node
->Type
== MESSAGING_DEVICE_PATH
&& Node
->SubType
== MSG_VLAN_DP
) {
2021 return ((VLAN_DEVICE_PATH
*) Node
)->VlanId
;
2023 Node
= NextDevicePathNode (Node
);
2030 Find VLAN device handle with specified VLAN ID.
2032 The VLAN child device handle is created by VLAN Config Protocol on ControllerHandle.
2033 This function will append VLAN device path node to the parent device path,
2034 and then use LocateDevicePath() to find the correct VLAN device handle.
2036 @param[in] ControllerHandle The handle where network service binding protocols are
2038 @param[in] VlanId The configured VLAN ID for the VLAN device.
2040 @return The VLAN device handle, or NULL if not found.
2045 NetLibGetVlanHandle (
2046 IN EFI_HANDLE ControllerHandle
,
2050 EFI_DEVICE_PATH_PROTOCOL
*ParentDevicePath
;
2051 EFI_DEVICE_PATH_PROTOCOL
*VlanDevicePath
;
2052 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2053 VLAN_DEVICE_PATH VlanNode
;
2056 ParentDevicePath
= DevicePathFromHandle (ControllerHandle
);
2057 if (ParentDevicePath
== NULL
) {
2062 // Construct VLAN device path
2064 CopyMem (&VlanNode
, &mNetVlanDevicePathTemplate
, sizeof (VLAN_DEVICE_PATH
));
2065 VlanNode
.VlanId
= VlanId
;
2066 VlanDevicePath
= AppendDevicePathNode (
2068 (EFI_DEVICE_PATH_PROTOCOL
*) &VlanNode
2070 if (VlanDevicePath
== NULL
) {
2075 // Find VLAN device handle
2078 DevicePath
= VlanDevicePath
;
2079 gBS
->LocateDevicePath (
2080 &gEfiDevicePathProtocolGuid
,
2084 if (!IsDevicePathEnd (DevicePath
)) {
2086 // Device path is not exactly match
2091 FreePool (VlanDevicePath
);
2096 Get MAC address associated with the network service handle.
2098 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
2099 If SNP is installed on the ServiceHandle or its parent handle, MAC address will
2100 be retrieved from SNP. If no SNP found, try to get SNP mode data use MNP.
2102 @param[in] ServiceHandle The handle where network service binding protocols are
2104 @param[out] MacAddress The pointer to store the returned MAC address.
2105 @param[out] AddressSize The length of returned MAC address.
2107 @retval EFI_SUCCESS MAC address is returned successfully.
2108 @retval Others Failed to get SNP mode data.
2113 NetLibGetMacAddress (
2114 IN EFI_HANDLE ServiceHandle
,
2115 OUT EFI_MAC_ADDRESS
*MacAddress
,
2116 OUT UINTN
*AddressSize
2120 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2121 EFI_SIMPLE_NETWORK_MODE
*SnpMode
;
2122 EFI_SIMPLE_NETWORK_MODE SnpModeData
;
2123 EFI_MANAGED_NETWORK_PROTOCOL
*Mnp
;
2124 EFI_SERVICE_BINDING_PROTOCOL
*MnpSb
;
2125 EFI_HANDLE
*SnpHandle
;
2126 EFI_HANDLE MnpChildHandle
;
2128 ASSERT (MacAddress
!= NULL
);
2129 ASSERT (AddressSize
!= NULL
);
2132 // Try to get SNP handle
2135 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2136 if (SnpHandle
!= NULL
) {
2138 // SNP found, use it directly
2140 SnpMode
= Snp
->Mode
;
2143 // Failed to get SNP handle, try to get MAC address from MNP
2145 MnpChildHandle
= NULL
;
2146 Status
= gBS
->HandleProtocol (
2148 &gEfiManagedNetworkServiceBindingProtocolGuid
,
2151 if (EFI_ERROR (Status
)) {
2156 // Create a MNP child
2158 Status
= MnpSb
->CreateChild (MnpSb
, &MnpChildHandle
);
2159 if (EFI_ERROR (Status
)) {
2164 // Open MNP protocol
2166 Status
= gBS
->HandleProtocol (
2168 &gEfiManagedNetworkProtocolGuid
,
2171 if (EFI_ERROR (Status
)) {
2172 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2177 // Try to get SNP mode from MNP
2179 Status
= Mnp
->GetModeData (Mnp
, NULL
, &SnpModeData
);
2180 if (EFI_ERROR (Status
) && (Status
!= EFI_NOT_STARTED
)) {
2181 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2184 SnpMode
= &SnpModeData
;
2187 // Destroy the MNP child
2189 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2192 *AddressSize
= SnpMode
->HwAddressSize
;
2193 CopyMem (MacAddress
->Addr
, SnpMode
->CurrentAddress
.Addr
, SnpMode
->HwAddressSize
);
2199 Convert MAC address of the NIC associated with specified Service Binding Handle
2200 to a unicode string. Callers are responsible for freeing the string storage.
2202 Locate simple network protocol associated with the Service Binding Handle and
2203 get the mac address from SNP. Then convert the mac address into a unicode
2204 string. It takes 2 unicode characters to represent a 1 byte binary buffer.
2205 Plus one unicode character for the null-terminator.
2207 @param[in] ServiceHandle The handle where network service binding protocol is
2209 @param[in] ImageHandle The image handle used to act as the agent handle to
2210 get the simple network protocol. This parameter is
2211 optional and may be NULL.
2212 @param[out] MacString The pointer to store the address of the string
2213 representation of the mac address.
2215 @retval EFI_SUCCESS Convert the mac address a unicode string successfully.
2216 @retval EFI_OUT_OF_RESOURCES There are not enough memory resource.
2217 @retval Others Failed to open the simple network protocol.
2222 NetLibGetMacString (
2223 IN EFI_HANDLE ServiceHandle
,
2224 IN EFI_HANDLE ImageHandle
, OPTIONAL
2225 OUT CHAR16
**MacString
2229 EFI_MAC_ADDRESS MacAddress
;
2231 UINTN HwAddressSize
;
2237 ASSERT (MacString
!= NULL
);
2240 // Get MAC address of the network device
2242 Status
= NetLibGetMacAddress (ServiceHandle
, &MacAddress
, &HwAddressSize
);
2243 if (EFI_ERROR (Status
)) {
2248 // It takes 2 unicode characters to represent a 1 byte binary buffer.
2249 // If VLAN is configured, it will need extra 5 characters like "\0005".
2250 // Plus one unicode character for the null-terminator.
2252 BufferSize
= (2 * HwAddressSize
+ 5 + 1) * sizeof (CHAR16
);
2253 String
= AllocateZeroPool (BufferSize
);
2254 if (String
== NULL
) {
2255 return EFI_OUT_OF_RESOURCES
;
2257 *MacString
= String
;
2260 // Convert the MAC address into a unicode string.
2262 HwAddress
= &MacAddress
.Addr
[0];
2263 for (Index
= 0; Index
< HwAddressSize
; Index
++) {
2264 UnicodeValueToStringS (
2266 BufferSize
- ((UINTN
)String
- (UINTN
)*MacString
),
2267 PREFIX_ZERO
| RADIX_HEX
,
2271 String
+= StrnLenS (String
, (BufferSize
- ((UINTN
)String
- (UINTN
)*MacString
)) / sizeof (CHAR16
));
2275 // Append VLAN ID if any
2277 VlanId
= NetLibGetVlanId (ServiceHandle
);
2280 UnicodeValueToStringS (
2282 BufferSize
- ((UINTN
)String
- (UINTN
)*MacString
),
2283 PREFIX_ZERO
| RADIX_HEX
,
2287 String
+= StrnLenS (String
, (BufferSize
- ((UINTN
)String
- (UINTN
)*MacString
)) / sizeof (CHAR16
));
2291 // Null terminate the Unicode string
2299 Detect media status for specified network device.
2301 The underlying UNDI driver may or may not support reporting media status from
2302 GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine
2303 will try to invoke Snp->GetStatus() to get the media status: if media already
2304 present, it return directly; if media not present, it will stop SNP and then
2305 restart SNP to get the latest media status, this give chance to get the correct
2306 media status for old UNDI driver which doesn't support reporting media status
2307 from GET_STATUS command.
2308 Note: there will be two limitations for current algorithm:
2309 1) for UNDI with this capability, in case of cable is not attached, there will
2310 be an redundant Stop/Start() process;
2311 2) for UNDI without this capability, in case that network cable is attached when
2312 Snp->Initialize() is invoked while network cable is unattached later,
2313 NetLibDetectMedia() will report MediaPresent as TRUE, causing upper layer
2314 apps to wait for timeout time.
2316 @param[in] ServiceHandle The handle where network service binding protocols are
2318 @param[out] MediaPresent The pointer to store the media status.
2320 @retval EFI_SUCCESS Media detection success.
2321 @retval EFI_INVALID_PARAMETER ServiceHandle is not valid network device handle.
2322 @retval EFI_UNSUPPORTED Network device does not support media detection.
2323 @retval EFI_DEVICE_ERROR SNP is in unknown state.
2329 IN EFI_HANDLE ServiceHandle
,
2330 OUT BOOLEAN
*MediaPresent
2334 EFI_HANDLE SnpHandle
;
2335 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2336 UINT32 InterruptStatus
;
2338 EFI_MAC_ADDRESS
*MCastFilter
;
2339 UINT32 MCastFilterCount
;
2340 UINT32 EnableFilterBits
;
2341 UINT32 DisableFilterBits
;
2342 BOOLEAN ResetMCastFilters
;
2344 ASSERT (MediaPresent
!= NULL
);
2350 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2351 if (SnpHandle
== NULL
) {
2352 return EFI_INVALID_PARAMETER
;
2356 // Check whether SNP support media detection
2358 if (!Snp
->Mode
->MediaPresentSupported
) {
2359 return EFI_UNSUPPORTED
;
2363 // Invoke Snp->GetStatus() to refresh MediaPresent field in SNP mode data
2365 Status
= Snp
->GetStatus (Snp
, &InterruptStatus
, NULL
);
2366 if (EFI_ERROR (Status
)) {
2370 if (Snp
->Mode
->MediaPresent
) {
2372 // Media is present, return directly
2374 *MediaPresent
= TRUE
;
2379 // Till now, GetStatus() report no media; while, in case UNDI not support
2380 // reporting media status from GetStatus(), this media status may be incorrect.
2381 // So, we will stop SNP and then restart it to get the correct media status.
2383 OldState
= Snp
->Mode
->State
;
2384 if (OldState
>= EfiSimpleNetworkMaxState
) {
2385 return EFI_DEVICE_ERROR
;
2390 if (OldState
== EfiSimpleNetworkInitialized
) {
2392 // SNP is already in use, need Shutdown/Stop and then Start/Initialize
2396 // Backup current SNP receive filter settings
2398 EnableFilterBits
= Snp
->Mode
->ReceiveFilterSetting
;
2399 DisableFilterBits
= Snp
->Mode
->ReceiveFilterMask
^ EnableFilterBits
;
2401 ResetMCastFilters
= TRUE
;
2402 MCastFilterCount
= Snp
->Mode
->MCastFilterCount
;
2403 if (MCastFilterCount
!= 0) {
2404 MCastFilter
= AllocateCopyPool (
2405 MCastFilterCount
* sizeof (EFI_MAC_ADDRESS
),
2406 Snp
->Mode
->MCastFilter
2408 ASSERT (MCastFilter
!= NULL
);
2410 ResetMCastFilters
= FALSE
;
2414 // Shutdown/Stop the simple network
2416 Status
= Snp
->Shutdown (Snp
);
2417 if (!EFI_ERROR (Status
)) {
2418 Status
= Snp
->Stop (Snp
);
2420 if (EFI_ERROR (Status
)) {
2425 // Start/Initialize the simple network
2427 Status
= Snp
->Start (Snp
);
2428 if (!EFI_ERROR (Status
)) {
2429 Status
= Snp
->Initialize (Snp
, 0, 0);
2431 if (EFI_ERROR (Status
)) {
2436 // Here we get the correct media status
2438 *MediaPresent
= Snp
->Mode
->MediaPresent
;
2441 // Restore SNP receive filter settings
2443 Status
= Snp
->ReceiveFilters (
2452 if (MCastFilter
!= NULL
) {
2453 FreePool (MCastFilter
);
2460 // SNP is not in use, it's in state of EfiSimpleNetworkStopped or EfiSimpleNetworkStarted
2462 if (OldState
== EfiSimpleNetworkStopped
) {
2464 // SNP not start yet, start it
2466 Status
= Snp
->Start (Snp
);
2467 if (EFI_ERROR (Status
)) {
2473 // Initialize the simple network
2475 Status
= Snp
->Initialize (Snp
, 0, 0);
2476 if (EFI_ERROR (Status
)) {
2477 Status
= EFI_DEVICE_ERROR
;
2482 // Here we get the correct media status
2484 *MediaPresent
= Snp
->Mode
->MediaPresent
;
2487 // Shut down the simple network
2489 Snp
->Shutdown (Snp
);
2492 if (OldState
== EfiSimpleNetworkStopped
) {
2494 // Original SNP sate is Stopped, restore to original state
2499 if (MCastFilter
!= NULL
) {
2500 FreePool (MCastFilter
);
2508 Detect media state for a network device. This routine will wait for a period of time at
2509 a specified checking interval when a certain network is under connecting until connection
2510 process finishs or timeout. If Aip protocol is supported by low layer drivers, three kinds
2511 of media states can be detected: EFI_SUCCESS, EFI_NOT_READY and EFI_NO_MEDIA, represents
2512 connected state, connecting state and no media state respectively. When function detects
2513 the current state is EFI_NOT_READY, it will loop to wait for next time's check until state
2514 turns to be EFI_SUCCESS or EFI_NO_MEDIA. If Aip protocol is not supported, function will
2515 call NetLibDetectMedia() and return state directly.
2517 @param[in] ServiceHandle The handle where network service binding protocols are
2519 @param[in] Timeout The maximum number of 100ns units to wait when network
2520 is connecting. Zero value means detect once and return
2522 @param[out] MediaState The pointer to the detected media state.
2524 @retval EFI_SUCCESS Media detection success.
2525 @retval EFI_INVALID_PARAMETER ServiceHandle is not a valid network device handle or
2526 MediaState pointer is NULL.
2527 @retval EFI_DEVICE_ERROR A device error occurred.
2528 @retval EFI_TIMEOUT Network is connecting but timeout.
2533 NetLibDetectMediaWaitTimeout (
2534 IN EFI_HANDLE ServiceHandle
,
2536 OUT EFI_STATUS
*MediaState
2540 EFI_HANDLE SnpHandle
;
2541 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2542 EFI_ADAPTER_INFORMATION_PROTOCOL
*Aip
;
2543 EFI_ADAPTER_INFO_MEDIA_STATE
*MediaInfo
;
2544 BOOLEAN MediaPresent
;
2546 EFI_STATUS TimerStatus
;
2548 UINT64 TimeRemained
;
2550 if (MediaState
== NULL
) {
2551 return EFI_INVALID_PARAMETER
;
2553 *MediaState
= EFI_SUCCESS
;
2560 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2561 if (SnpHandle
== NULL
) {
2562 return EFI_INVALID_PARAMETER
;
2565 Status
= gBS
->HandleProtocol (
2567 &gEfiAdapterInformationProtocolGuid
,
2570 if (EFI_ERROR (Status
)) {
2572 MediaPresent
= TRUE
;
2573 Status
= NetLibDetectMedia (ServiceHandle
, &MediaPresent
);
2574 if (!EFI_ERROR (Status
)) {
2576 *MediaState
= EFI_SUCCESS
;
2578 *MediaState
= EFI_NO_MEDIA
;
2583 // NetLibDetectMedia doesn't support EFI_NOT_READY status, return now!
2588 Status
= Aip
->GetInformation (
2590 &gEfiAdapterInfoMediaStateGuid
,
2591 (VOID
**) &MediaInfo
,
2594 if (!EFI_ERROR (Status
)) {
2596 *MediaState
= MediaInfo
->MediaState
;
2597 FreePool (MediaInfo
);
2598 if (*MediaState
!= EFI_NOT_READY
|| Timeout
< MEDIA_STATE_DETECT_TIME_INTERVAL
) {
2604 if (MediaInfo
!= NULL
) {
2605 FreePool (MediaInfo
);
2608 if (Status
== EFI_UNSUPPORTED
) {
2611 // If gEfiAdapterInfoMediaStateGuid is not supported, call NetLibDetectMedia to get media state!
2613 MediaPresent
= TRUE
;
2614 Status
= NetLibDetectMedia (ServiceHandle
, &MediaPresent
);
2615 if (!EFI_ERROR (Status
)) {
2617 *MediaState
= EFI_SUCCESS
;
2619 *MediaState
= EFI_NO_MEDIA
;
2629 // Loop to check media state
2633 TimeRemained
= Timeout
;
2634 Status
= gBS
->CreateEvent (EVT_TIMER
, TPL_CALLBACK
, NULL
, NULL
, &Timer
);
2635 if (EFI_ERROR (Status
)) {
2636 return EFI_DEVICE_ERROR
;
2640 Status
= gBS
->SetTimer (
2643 MEDIA_STATE_DETECT_TIME_INTERVAL
2645 if (EFI_ERROR (Status
)) {
2646 gBS
->CloseEvent(Timer
);
2647 return EFI_DEVICE_ERROR
;
2651 TimerStatus
= gBS
->CheckEvent (Timer
);
2652 if (!EFI_ERROR (TimerStatus
)) {
2654 TimeRemained
-= MEDIA_STATE_DETECT_TIME_INTERVAL
;
2655 Status
= Aip
->GetInformation (
2657 &gEfiAdapterInfoMediaStateGuid
,
2658 (VOID
**) &MediaInfo
,
2661 if (!EFI_ERROR (Status
)) {
2663 *MediaState
= MediaInfo
->MediaState
;
2664 FreePool (MediaInfo
);
2667 if (MediaInfo
!= NULL
) {
2668 FreePool (MediaInfo
);
2670 gBS
->CloseEvent(Timer
);
2674 } while (TimerStatus
== EFI_NOT_READY
);
2675 } while (*MediaState
== EFI_NOT_READY
&& TimeRemained
>= MEDIA_STATE_DETECT_TIME_INTERVAL
);
2677 gBS
->CloseEvent(Timer
);
2678 if (*MediaState
== EFI_NOT_READY
&& TimeRemained
< MEDIA_STATE_DETECT_TIME_INTERVAL
) {
2686 Check the default address used by the IPv4 driver is static or dynamic (acquired
2689 If the controller handle does not have the EFI_IP4_CONFIG2_PROTOCOL installed, the
2690 default address is static. If failed to get the policy from Ip4 Config2 Protocol,
2691 the default address is static. Otherwise, get the result from Ip4 Config2 Protocol.
2693 @param[in] Controller The controller handle which has the EFI_IP4_CONFIG2_PROTOCOL
2694 relative with the default address to judge.
2696 @retval TRUE If the default address is static.
2697 @retval FALSE If the default address is acquired from DHCP.
2701 NetLibDefaultAddressIsStatic (
2702 IN EFI_HANDLE Controller
2706 EFI_IP4_CONFIG2_PROTOCOL
*Ip4Config2
;
2708 EFI_IP4_CONFIG2_POLICY Policy
;
2713 DataSize
= sizeof (EFI_IP4_CONFIG2_POLICY
);
2718 // Get Ip4Config2 policy.
2720 Status
= gBS
->HandleProtocol (Controller
, &gEfiIp4Config2ProtocolGuid
, (VOID
**) &Ip4Config2
);
2721 if (EFI_ERROR (Status
)) {
2725 Status
= Ip4Config2
->GetData (Ip4Config2
, Ip4Config2DataTypePolicy
, &DataSize
, &Policy
);
2726 if (EFI_ERROR (Status
)) {
2730 IsStatic
= (BOOLEAN
) (Policy
== Ip4Config2PolicyStatic
);
2738 Create an IPv4 device path node.
2740 The header type of IPv4 device path node is MESSAGING_DEVICE_PATH.
2741 The header subtype of IPv4 device path node is MSG_IPv4_DP.
2742 Get other info from parameters to make up the whole IPv4 device path node.
2744 @param[in, out] Node Pointer to the IPv4 device path node.
2745 @param[in] Controller The controller handle.
2746 @param[in] LocalIp The local IPv4 address.
2747 @param[in] LocalPort The local port.
2748 @param[in] RemoteIp The remote IPv4 address.
2749 @param[in] RemotePort The remote port.
2750 @param[in] Protocol The protocol type in the IP header.
2751 @param[in] UseDefaultAddress Whether this instance is using default address or not.
2756 NetLibCreateIPv4DPathNode (
2757 IN OUT IPv4_DEVICE_PATH
*Node
,
2758 IN EFI_HANDLE Controller
,
2759 IN IP4_ADDR LocalIp
,
2760 IN UINT16 LocalPort
,
2761 IN IP4_ADDR RemoteIp
,
2762 IN UINT16 RemotePort
,
2764 IN BOOLEAN UseDefaultAddress
2767 Node
->Header
.Type
= MESSAGING_DEVICE_PATH
;
2768 Node
->Header
.SubType
= MSG_IPv4_DP
;
2769 SetDevicePathNodeLength (&Node
->Header
, sizeof (IPv4_DEVICE_PATH
));
2771 CopyMem (&Node
->LocalIpAddress
, &LocalIp
, sizeof (EFI_IPv4_ADDRESS
));
2772 CopyMem (&Node
->RemoteIpAddress
, &RemoteIp
, sizeof (EFI_IPv4_ADDRESS
));
2774 Node
->LocalPort
= LocalPort
;
2775 Node
->RemotePort
= RemotePort
;
2777 Node
->Protocol
= Protocol
;
2779 if (!UseDefaultAddress
) {
2780 Node
->StaticIpAddress
= TRUE
;
2782 Node
->StaticIpAddress
= NetLibDefaultAddressIsStatic (Controller
);
2786 // Set the Gateway IP address to default value 0:0:0:0.
2787 // Set the Subnet mask to default value 255:255:255:0.
2789 ZeroMem (&Node
->GatewayIpAddress
, sizeof (EFI_IPv4_ADDRESS
));
2790 SetMem (&Node
->SubnetMask
, sizeof (EFI_IPv4_ADDRESS
), 0xff);
2791 Node
->SubnetMask
.Addr
[3] = 0;
2795 Create an IPv6 device path node.
2797 The header type of IPv6 device path node is MESSAGING_DEVICE_PATH.
2798 The header subtype of IPv6 device path node is MSG_IPv6_DP.
2799 Get other info from parameters to make up the whole IPv6 device path node.
2801 @param[in, out] Node Pointer to the IPv6 device path node.
2802 @param[in] Controller The controller handle.
2803 @param[in] LocalIp The local IPv6 address.
2804 @param[in] LocalPort The local port.
2805 @param[in] RemoteIp The remote IPv6 address.
2806 @param[in] RemotePort The remote port.
2807 @param[in] Protocol The protocol type in the IP header.
2812 NetLibCreateIPv6DPathNode (
2813 IN OUT IPv6_DEVICE_PATH
*Node
,
2814 IN EFI_HANDLE Controller
,
2815 IN EFI_IPv6_ADDRESS
*LocalIp
,
2816 IN UINT16 LocalPort
,
2817 IN EFI_IPv6_ADDRESS
*RemoteIp
,
2818 IN UINT16 RemotePort
,
2822 Node
->Header
.Type
= MESSAGING_DEVICE_PATH
;
2823 Node
->Header
.SubType
= MSG_IPv6_DP
;
2824 SetDevicePathNodeLength (&Node
->Header
, sizeof (IPv6_DEVICE_PATH
));
2826 CopyMem (&Node
->LocalIpAddress
, LocalIp
, sizeof (EFI_IPv6_ADDRESS
));
2827 CopyMem (&Node
->RemoteIpAddress
, RemoteIp
, sizeof (EFI_IPv6_ADDRESS
));
2829 Node
->LocalPort
= LocalPort
;
2830 Node
->RemotePort
= RemotePort
;
2832 Node
->Protocol
= Protocol
;
2835 // Set default value to IPAddressOrigin, PrefixLength.
2836 // Set the Gateway IP address to unspecified address.
2838 Node
->IpAddressOrigin
= 0;
2839 Node
->PrefixLength
= IP6_PREFIX_LENGTH
;
2840 ZeroMem (&Node
->GatewayIpAddress
, sizeof (EFI_IPv6_ADDRESS
));
2844 Find the UNDI/SNP handle from controller and protocol GUID.
2846 For example, IP will open a MNP child to transmit/receive
2847 packets, when MNP is stopped, IP should also be stopped. IP
2848 needs to find its own private data which is related the IP's
2849 service binding instance that is install on UNDI/SNP handle.
2850 Now, the controller is either a MNP or ARP child handle. But
2851 IP opens these handle BY_DRIVER, use that info, we can get the
2854 @param[in] Controller Then protocol handle to check.
2855 @param[in] ProtocolGuid The protocol that is related with the handle.
2857 @return The UNDI/SNP handle or NULL for errors.
2862 NetLibGetNicHandle (
2863 IN EFI_HANDLE Controller
,
2864 IN EFI_GUID
*ProtocolGuid
2867 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY
*OpenBuffer
;
2873 Status
= gBS
->OpenProtocolInformation (
2880 if (EFI_ERROR (Status
)) {
2886 for (Index
= 0; Index
< OpenCount
; Index
++) {
2887 if ((OpenBuffer
[Index
].Attributes
& EFI_OPEN_PROTOCOL_BY_DRIVER
) != 0) {
2888 Handle
= OpenBuffer
[Index
].ControllerHandle
;
2893 gBS
->FreePool (OpenBuffer
);
2898 Convert one Null-terminated ASCII string (decimal dotted) to EFI_IPv4_ADDRESS.
2900 @param[in] String The pointer to the Ascii string.
2901 @param[out] Ip4Address The pointer to the converted IPv4 address.
2903 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2904 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2909 NetLibAsciiStrToIp4 (
2910 IN CONST CHAR8
*String
,
2911 OUT EFI_IPv4_ADDRESS
*Ip4Address
2914 RETURN_STATUS Status
;
2917 Status
= AsciiStrToIpv4Address (String
, &EndPointer
, Ip4Address
, NULL
);
2918 if (RETURN_ERROR (Status
) || (*EndPointer
!= '\0')) {
2919 return EFI_INVALID_PARAMETER
;
2927 Convert one Null-terminated ASCII string to EFI_IPv6_ADDRESS. The format of the
2928 string is defined in RFC 4291 - Text Representation of Addresses.
2930 @param[in] String The pointer to the Ascii string.
2931 @param[out] Ip6Address The pointer to the converted IPv6 address.
2933 @retval EFI_SUCCESS Convert to IPv6 address successfully.
2934 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
2939 NetLibAsciiStrToIp6 (
2940 IN CONST CHAR8
*String
,
2941 OUT EFI_IPv6_ADDRESS
*Ip6Address
2944 RETURN_STATUS Status
;
2947 Status
= AsciiStrToIpv6Address (String
, &EndPointer
, Ip6Address
, NULL
);
2948 if (RETURN_ERROR (Status
) || (*EndPointer
!= '\0')) {
2949 return EFI_INVALID_PARAMETER
;
2957 Convert one Null-terminated Unicode string (decimal dotted) to EFI_IPv4_ADDRESS.
2959 @param[in] String The pointer to the Ascii string.
2960 @param[out] Ip4Address The pointer to the converted IPv4 address.
2962 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2963 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2969 IN CONST CHAR16
*String
,
2970 OUT EFI_IPv4_ADDRESS
*Ip4Address
2973 RETURN_STATUS Status
;
2976 Status
= StrToIpv4Address (String
, &EndPointer
, Ip4Address
, NULL
);
2977 if (RETURN_ERROR (Status
) || (*EndPointer
!= L
'\0')) {
2978 return EFI_INVALID_PARAMETER
;
2986 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS. The format of
2987 the string is defined in RFC 4291 - Text Representation of Addresses.
2989 @param[in] String The pointer to the Ascii string.
2990 @param[out] Ip6Address The pointer to the converted IPv6 address.
2992 @retval EFI_SUCCESS Convert to IPv6 address successfully.
2993 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
2999 IN CONST CHAR16
*String
,
3000 OUT EFI_IPv6_ADDRESS
*Ip6Address
3003 RETURN_STATUS Status
;
3006 Status
= StrToIpv6Address (String
, &EndPointer
, Ip6Address
, NULL
);
3007 if (RETURN_ERROR (Status
) || (*EndPointer
!= L
'\0')) {
3008 return EFI_INVALID_PARAMETER
;
3015 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS and prefix length.
3016 The format of the string is defined in RFC 4291 - Text Representation of Addresses
3017 Prefixes: ipv6-address/prefix-length.
3019 @param[in] String The pointer to the Ascii string.
3020 @param[out] Ip6Address The pointer to the converted IPv6 address.
3021 @param[out] PrefixLength The pointer to the converted prefix length.
3023 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3024 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3029 NetLibStrToIp6andPrefix (
3030 IN CONST CHAR16
*String
,
3031 OUT EFI_IPv6_ADDRESS
*Ip6Address
,
3032 OUT UINT8
*PrefixLength
3035 RETURN_STATUS Status
;
3038 Status
= StrToIpv6Address (String
, &EndPointer
, Ip6Address
, PrefixLength
);
3039 if (RETURN_ERROR (Status
) || (*EndPointer
!= L
'\0')) {
3040 return EFI_INVALID_PARAMETER
;
3048 Convert one EFI_IPv6_ADDRESS to Null-terminated Unicode string.
3049 The text representation of address is defined in RFC 4291.
3051 @param[in] Ip6Address The pointer to the IPv6 address.
3052 @param[out] String The buffer to return the converted string.
3053 @param[in] StringSize The length in bytes of the input String.
3055 @retval EFI_SUCCESS Convert to string successfully.
3056 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
3057 @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small for the result. BufferSize has been
3058 updated with the size needed to complete the request.
3063 IN EFI_IPv6_ADDRESS
*Ip6Address
,
3070 UINTN LongestZerosStart
;
3071 UINTN LongestZerosLength
;
3072 UINTN CurrentZerosStart
;
3073 UINTN CurrentZerosLength
;
3074 CHAR16 Buffer
[sizeof"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"];
3077 if (Ip6Address
== NULL
|| String
== NULL
|| StringSize
== 0) {
3078 return EFI_INVALID_PARAMETER
;
3082 // Convert the UINT8 array to an UINT16 array for easy handling.
3084 ZeroMem (Ip6Addr
, sizeof (Ip6Addr
));
3085 for (Index
= 0; Index
< 16; Index
++) {
3086 Ip6Addr
[Index
/ 2] |= (Ip6Address
->Addr
[Index
] << ((1 - (Index
% 2)) << 3));
3090 // Find the longest zeros and mark it.
3092 CurrentZerosStart
= DEFAULT_ZERO_START
;
3093 CurrentZerosLength
= 0;
3094 LongestZerosStart
= DEFAULT_ZERO_START
;
3095 LongestZerosLength
= 0;
3096 for (Index
= 0; Index
< 8; Index
++) {
3097 if (Ip6Addr
[Index
] == 0) {
3098 if (CurrentZerosStart
== DEFAULT_ZERO_START
) {
3099 CurrentZerosStart
= Index
;
3100 CurrentZerosLength
= 1;
3102 CurrentZerosLength
++;
3105 if (CurrentZerosStart
!= DEFAULT_ZERO_START
) {
3106 if (CurrentZerosLength
> 2 && (LongestZerosStart
== (DEFAULT_ZERO_START
) || CurrentZerosLength
> LongestZerosLength
)) {
3107 LongestZerosStart
= CurrentZerosStart
;
3108 LongestZerosLength
= CurrentZerosLength
;
3110 CurrentZerosStart
= DEFAULT_ZERO_START
;
3111 CurrentZerosLength
= 0;
3116 if (CurrentZerosStart
!= DEFAULT_ZERO_START
&& CurrentZerosLength
> 2) {
3117 if (LongestZerosStart
== DEFAULT_ZERO_START
|| LongestZerosLength
< CurrentZerosLength
) {
3118 LongestZerosStart
= CurrentZerosStart
;
3119 LongestZerosLength
= CurrentZerosLength
;
3124 for (Index
= 0; Index
< 8; Index
++) {
3125 if (LongestZerosStart
!= DEFAULT_ZERO_START
&& Index
>= LongestZerosStart
&& Index
< LongestZerosStart
+ LongestZerosLength
) {
3126 if (Index
== LongestZerosStart
) {
3134 Ptr
+= UnicodeSPrint(Ptr
, 10, L
"%x", Ip6Addr
[Index
]);
3137 if (LongestZerosStart
!= DEFAULT_ZERO_START
&& LongestZerosStart
+ LongestZerosLength
== 8) {
3142 if ((UINTN
)Ptr
- (UINTN
)Buffer
> StringSize
) {
3143 return EFI_BUFFER_TOO_SMALL
;
3146 StrCpyS (String
, StringSize
/ sizeof (CHAR16
), Buffer
);
3152 This function obtains the system guid from the smbios table.
3154 @param[out] SystemGuid The pointer of the returned system guid.
3156 @retval EFI_SUCCESS Successfully obtained the system guid.
3157 @retval EFI_NOT_FOUND Did not find the SMBIOS table.
3162 NetLibGetSystemGuid (
3163 OUT EFI_GUID
*SystemGuid
3167 SMBIOS_TABLE_ENTRY_POINT
*SmbiosTable
;
3168 SMBIOS_TABLE_3_0_ENTRY_POINT
*Smbios30Table
;
3169 SMBIOS_STRUCTURE_POINTER Smbios
;
3170 SMBIOS_STRUCTURE_POINTER SmbiosEnd
;
3174 Status
= EfiGetSystemConfigurationTable (&gEfiSmbios3TableGuid
, (VOID
**) &Smbios30Table
);
3175 if (!(EFI_ERROR (Status
) || Smbios30Table
== NULL
)) {
3176 Smbios
.Hdr
= (SMBIOS_STRUCTURE
*) (UINTN
) Smbios30Table
->TableAddress
;
3177 SmbiosEnd
.Raw
= (UINT8
*) (UINTN
) (Smbios30Table
->TableAddress
+ Smbios30Table
->TableMaximumSize
);
3179 Status
= EfiGetSystemConfigurationTable (&gEfiSmbiosTableGuid
, (VOID
**) &SmbiosTable
);
3180 if (EFI_ERROR (Status
) || SmbiosTable
== NULL
) {
3181 return EFI_NOT_FOUND
;
3183 Smbios
.Hdr
= (SMBIOS_STRUCTURE
*) (UINTN
) SmbiosTable
->TableAddress
;
3184 SmbiosEnd
.Raw
= (UINT8
*) ((UINTN
) SmbiosTable
->TableAddress
+ SmbiosTable
->TableLength
);
3188 if (Smbios
.Hdr
->Type
== 1) {
3189 if (Smbios
.Hdr
->Length
< 0x19) {
3191 // Older version did not support UUID.
3193 return EFI_NOT_FOUND
;
3197 // SMBIOS tables are byte packed so we need to do a byte copy to
3198 // prevend alignment faults on Itanium-based platform.
3200 CopyMem (SystemGuid
, &Smbios
.Type1
->Uuid
, sizeof (EFI_GUID
));
3205 // Go to the next SMBIOS structure. Each SMBIOS structure may include 2 parts:
3206 // 1. Formatted section; 2. Unformatted string section. So, 2 steps are needed
3207 // to skip one SMBIOS structure.
3211 // Step 1: Skip over formatted section.
3213 String
= (CHAR8
*) (Smbios
.Raw
+ Smbios
.Hdr
->Length
);
3216 // Step 2: Skip over unformated string section.
3220 // Each string is terminated with a NULL(00h) BYTE and the sets of strings
3221 // is terminated with an additional NULL(00h) BYTE.
3223 for ( ; *String
!= 0; String
++) {
3226 if (*(UINT8
*)++String
== 0) {
3228 // Pointer to the next SMBIOS structure.
3230 Smbios
.Raw
= (UINT8
*)++String
;
3234 } while (Smbios
.Raw
< SmbiosEnd
.Raw
);
3235 return EFI_NOT_FOUND
;
3239 Create Dns QName according the queried domain name.
3240 QName is a domain name represented as a sequence of labels,
3241 where each label consists of a length octet followed by that
3242 number of octets. The QName terminates with the zero
3243 length octet for the null label of the root. Caller should
3244 take responsibility to free the buffer in returned pointer.
3246 @param DomainName The pointer to the queried domain name string.
3248 @retval NULL Failed to fill QName.
3249 @return QName filled successfully.
3254 NetLibCreateDnsQName (
3255 IN CHAR16
*DomainName
3259 UINTN QueryNameSize
;
3271 // One byte for first label length, one byte for terminated length zero.
3273 QueryNameSize
= StrLen (DomainName
) + 2;
3275 if (QueryNameSize
> DNS_MAX_NAME_SIZE
) {
3279 QueryName
= AllocateZeroPool (QueryNameSize
);
3280 if (QueryName
== NULL
) {
3287 for (Index
= 0; DomainName
[Index
] != 0; Index
++) {
3288 *Tail
= (CHAR8
) DomainName
[Index
];
3290 *Header
= (CHAR8
) Len
;
3299 *Header
= (CHAR8
) Len
;