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/ManagedNetwork.h>
23 #include <Protocol/Ip4Config2.h>
24 #include <Protocol/ComponentName.h>
25 #include <Protocol/ComponentName2.h>
27 #include <Guid/SmBios.h>
29 #include <Library/NetLib.h>
30 #include <Library/BaseLib.h>
31 #include <Library/DebugLib.h>
32 #include <Library/BaseMemoryLib.h>
33 #include <Library/UefiBootServicesTableLib.h>
34 #include <Library/UefiRuntimeServicesTableLib.h>
35 #include <Library/MemoryAllocationLib.h>
36 #include <Library/DevicePathLib.h>
37 #include <Library/PrintLib.h>
38 #include <Library/UefiLib.h>
40 #define NIC_ITEM_CONFIG_SIZE sizeof (NIC_IP4_CONFIG_INFO) + sizeof (EFI_IP4_ROUTE_TABLE) * MAX_IP4_CONFIG_IN_VARIABLE
41 #define DEFAULT_ZERO_START ((UINTN) ~0)
44 // All the supported IP4 maskes in host byte order.
46 GLOBAL_REMOVE_IF_UNREFERENCED IP4_ADDR gIp4AllMasks
[IP4_MASK_NUM
] = {
85 GLOBAL_REMOVE_IF_UNREFERENCED EFI_IPv4_ADDRESS mZeroIp4Addr
= {{0, 0, 0, 0}};
88 // Any error level digitally larger than mNetDebugLevelMax
89 // will be silently discarded.
91 GLOBAL_REMOVE_IF_UNREFERENCED UINTN mNetDebugLevelMax
= NETDEBUG_LEVEL_ERROR
;
92 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogPacketSeq
= 0xDEADBEEF;
95 // You can change mSyslogDstMac mSyslogDstIp and mSyslogSrcIp
96 // here to direct the syslog packets to the syslog deamon. The
97 // default is broadcast to both the ethernet and IP.
99 GLOBAL_REMOVE_IF_UNREFERENCED UINT8 mSyslogDstMac
[NET_ETHER_ADDR_LEN
] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
100 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogDstIp
= 0xffffffff;
101 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogSrcIp
= 0;
103 GLOBAL_REMOVE_IF_UNREFERENCED CHAR8
*mMonthName
[] = {
119 // VLAN device path node template
121 GLOBAL_REMOVE_IF_UNREFERENCED VLAN_DEVICE_PATH mNetVlanDevicePathTemplate
= {
123 MESSAGING_DEVICE_PATH
,
126 (UINT8
) (sizeof (VLAN_DEVICE_PATH
)),
127 (UINT8
) ((sizeof (VLAN_DEVICE_PATH
)) >> 8)
134 Locate the handles that support SNP, then open one of them
135 to send the syslog packets. The caller isn't required to close
136 the SNP after use because the SNP is opened by HandleProtocol.
138 @return The point to SNP if one is properly openned. Otherwise NULL
141 EFI_SIMPLE_NETWORK_PROTOCOL
*
146 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
153 // Locate the handles which has SNP installed.
156 Status
= gBS
->LocateHandleBuffer (
158 &gEfiSimpleNetworkProtocolGuid
,
164 if (EFI_ERROR (Status
) || (HandleCount
== 0)) {
169 // Try to open one of the ethernet SNP protocol to send packet
173 for (Index
= 0; Index
< HandleCount
; Index
++) {
174 Status
= gBS
->HandleProtocol (
176 &gEfiSimpleNetworkProtocolGuid
,
180 if ((Status
== EFI_SUCCESS
) && (Snp
!= NULL
) &&
181 (Snp
->Mode
->IfType
== NET_IFTYPE_ETHERNET
) &&
182 (Snp
->Mode
->MaxPacketSize
>= NET_SYSLOG_PACKET_LEN
)) {
195 Transmit a syslog packet synchronously through SNP. The Packet
196 already has the ethernet header prepended. This function should
197 fill in the source MAC because it will try to locate a SNP each
198 time it is called to avoid the problem if SNP is unloaded.
199 This code snip is copied from MNP.
201 @param[in] Packet The Syslog packet
202 @param[in] Length The length of the packet
204 @retval EFI_DEVICE_ERROR Failed to locate a usable SNP protocol
205 @retval EFI_TIMEOUT Timeout happened to send the packet.
206 @retval EFI_SUCCESS Packet is sent.
215 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
218 EFI_EVENT TimeoutEvent
;
221 Snp
= SyslogLocateSnp ();
224 return EFI_DEVICE_ERROR
;
227 Ether
= (ETHER_HEAD
*) Packet
;
228 CopyMem (Ether
->SrcMac
, Snp
->Mode
->CurrentAddress
.Addr
, NET_ETHER_ADDR_LEN
);
231 // Start the timeout event.
233 Status
= gBS
->CreateEvent (
241 if (EFI_ERROR (Status
)) {
245 Status
= gBS
->SetTimer (TimeoutEvent
, TimerRelative
, NET_SYSLOG_TX_TIMEOUT
);
247 if (EFI_ERROR (Status
)) {
253 // Transmit the packet through SNP.
255 Status
= Snp
->Transmit (Snp
, 0, Length
, Packet
, NULL
, NULL
, NULL
);
257 if ((Status
!= EFI_SUCCESS
) && (Status
!= EFI_NOT_READY
)) {
258 Status
= EFI_DEVICE_ERROR
;
263 // If Status is EFI_SUCCESS, the packet is put in the transmit queue.
264 // if Status is EFI_NOT_READY, the transmit engine of the network
265 // interface is busy. Both need to sync SNP.
271 // Get the recycled transmit buffer status.
273 Snp
->GetStatus (Snp
, NULL
, (VOID
**) &TxBuf
);
275 if (!EFI_ERROR (gBS
->CheckEvent (TimeoutEvent
))) {
276 Status
= EFI_TIMEOUT
;
280 } while (TxBuf
== NULL
);
282 if ((Status
== EFI_SUCCESS
) || (Status
== EFI_TIMEOUT
)) {
287 // Status is EFI_NOT_READY. Restart the timer event and
288 // call Snp->Transmit again.
290 gBS
->SetTimer (TimeoutEvent
, TimerRelative
, NET_SYSLOG_TX_TIMEOUT
);
293 gBS
->SetTimer (TimeoutEvent
, TimerCancel
, 0);
296 gBS
->CloseEvent (TimeoutEvent
);
301 Build a syslog packet, including the Ethernet/Ip/Udp headers
304 @param[in] Level Syslog severity level
305 @param[in] Module The module that generates the log
306 @param[in] File The file that contains the current log
307 @param[in] Line The line of code in the File that contains the current log
308 @param[in] Message The log message
309 @param[in] BufLen The lenght of the Buf
310 @param[out] Buf The buffer to put the packet data
312 @return The length of the syslog packet built.
328 EFI_UDP_HEADER
*Udp4
;
334 // Fill in the Ethernet header. Leave alone the source MAC.
335 // SyslogSendPacket will fill in the address for us.
337 Ether
= (ETHER_HEAD
*) Buf
;
338 CopyMem (Ether
->DstMac
, mSyslogDstMac
, NET_ETHER_ADDR_LEN
);
339 ZeroMem (Ether
->SrcMac
, NET_ETHER_ADDR_LEN
);
341 Ether
->EtherType
= HTONS (0x0800); // IPv4 protocol
343 Buf
+= sizeof (ETHER_HEAD
);
344 BufLen
-= sizeof (ETHER_HEAD
);
347 // Fill in the IP header
349 Ip4
= (IP4_HEAD
*) Buf
;
354 Ip4
->Id
= (UINT16
) mSyslogPacketSeq
;
357 Ip4
->Protocol
= 0x11;
359 Ip4
->Src
= mSyslogSrcIp
;
360 Ip4
->Dst
= mSyslogDstIp
;
362 Buf
+= sizeof (IP4_HEAD
);
363 BufLen
-= sizeof (IP4_HEAD
);
366 // Fill in the UDP header, Udp checksum is optional. Leave it zero.
368 Udp4
= (EFI_UDP_HEADER
*) Buf
;
369 Udp4
->SrcPort
= HTONS (514);
370 Udp4
->DstPort
= HTONS (514);
374 Buf
+= sizeof (EFI_UDP_HEADER
);
375 BufLen
-= sizeof (EFI_UDP_HEADER
);
378 // Build the syslog message body with <PRI> Timestamp machine module Message
380 Pri
= ((NET_SYSLOG_FACILITY
& 31) << 3) | (Level
& 7);
381 gRT
->GetTime (&Time
, NULL
);
382 ASSERT ((Time
.Month
<= 12) && (Time
.Month
>= 1));
385 // Use %a to format the ASCII strings, %s to format UNICODE strings
388 Len
+= (UINT32
) AsciiSPrint (
391 "<%d> %a %d %d:%d:%d ",
393 mMonthName
[Time
.Month
-1],
401 Len
+= (UINT32
) AsciiSPrint (
404 "Tiano %a: %a (Line: %d File: %a)",
413 // OK, patch the IP length/checksum and UDP length fields.
415 Len
+= sizeof (EFI_UDP_HEADER
);
416 Udp4
->Length
= HTONS ((UINT16
) Len
);
418 Len
+= sizeof (IP4_HEAD
);
419 Ip4
->TotalLen
= HTONS ((UINT16
) Len
);
420 Ip4
->Checksum
= (UINT16
) (~NetblockChecksum ((UINT8
*) Ip4
, sizeof (IP4_HEAD
)));
422 return Len
+ sizeof (ETHER_HEAD
);
426 Allocate a buffer, then format the message to it. This is a
427 help function for the NET_DEBUG_XXX macros. The PrintArg of
428 these macros treats the variable length print parameters as a
429 single parameter, and pass it to the NetDebugASPrint. For
430 example, NET_DEBUG_TRACE ("Tcp", ("State transit to %a\n", Name))
434 NETDEBUG_LEVEL_TRACE,
438 NetDebugASPrint ("State transit to %a\n", Name)
441 @param Format The ASCII format string.
442 @param ... The variable length parameter whose format is determined
443 by the Format string.
445 @return The buffer containing the formatted message,
446 or NULL if failed to allocate memory.
459 Buf
= (CHAR8
*) AllocatePool (NET_DEBUG_MSG_LEN
);
465 VA_START (Marker
, Format
);
466 AsciiVSPrint (Buf
, NET_DEBUG_MSG_LEN
, Format
, Marker
);
473 Builds an UDP4 syslog packet and send it using SNP.
475 This function will locate a instance of SNP then send the message through it.
476 Because it isn't open the SNP BY_DRIVER, apply caution when using it.
478 @param Level The severity level of the message.
479 @param Module The Moudle that generates the log.
480 @param File The file that contains the log.
481 @param Line The exact line that contains the log.
482 @param Message The user message to log.
484 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
485 @retval EFI_OUT_OF_RESOURCES Failed to allocate memory for the packet
486 @retval EFI_SUCCESS The log is discard because that it is more verbose
487 than the mNetDebugLevelMax. Or, it has been sent out.
504 // Check whether the message should be sent out
506 if (Message
== NULL
) {
507 return EFI_INVALID_PARAMETER
;
510 if (Level
> mNetDebugLevelMax
) {
511 Status
= EFI_SUCCESS
;
516 // Allocate a maxium of 1024 bytes, the caller should ensure
517 // that the message plus the ethernet/ip/udp header is shorter
520 Packet
= (CHAR8
*) AllocatePool (NET_SYSLOG_PACKET_LEN
);
522 if (Packet
== NULL
) {
523 Status
= EFI_OUT_OF_RESOURCES
;
528 // Build the message: Ethernet header + IP header + Udp Header + user data
530 Len
= SyslogBuildPacket (
536 NET_SYSLOG_PACKET_LEN
,
541 Status
= SyslogSendPacket (Packet
, Len
);
549 Return the length of the mask.
551 Return the length of the mask, the correct value is from 0 to 32.
552 If the mask is invalid, return the invalid length 33, which is IP4_MASK_NUM.
553 NetMask is in the host byte order.
555 @param[in] NetMask The netmask to get the length from.
557 @return The length of the netmask, IP4_MASK_NUM if the mask is invalid.
568 for (Index
= 0; Index
<= IP4_MASK_MAX
; Index
++) {
569 if (NetMask
== gIp4AllMasks
[Index
]) {
580 Return the class of the IP address, such as class A, B, C.
581 Addr is in host byte order.
584 Classful addressing (IP class A/B/C) has been deprecated according to RFC4632.
585 Caller of this function could only check the returned value against
586 IP4_ADDR_CLASSD (multicast) or IP4_ADDR_CLASSE (reserved) now.
588 The address of class A starts with 0.
589 If the address belong to class A, return IP4_ADDR_CLASSA.
590 The address of class B starts with 10.
591 If the address belong to class B, return IP4_ADDR_CLASSB.
592 The address of class C starts with 110.
593 If the address belong to class C, return IP4_ADDR_CLASSC.
594 The address of class D starts with 1110.
595 If the address belong to class D, return IP4_ADDR_CLASSD.
596 The address of class E starts with 1111.
597 If the address belong to class E, return IP4_ADDR_CLASSE.
600 @param[in] Addr The address to get the class from.
602 @return IP address class, such as IP4_ADDR_CLASSA.
613 ByteOne
= (UINT8
) (Addr
>> 24);
615 if ((ByteOne
& 0x80) == 0) {
616 return IP4_ADDR_CLASSA
;
618 } else if ((ByteOne
& 0xC0) == 0x80) {
619 return IP4_ADDR_CLASSB
;
621 } else if ((ByteOne
& 0xE0) == 0xC0) {
622 return IP4_ADDR_CLASSC
;
624 } else if ((ByteOne
& 0xF0) == 0xE0) {
625 return IP4_ADDR_CLASSD
;
628 return IP4_ADDR_CLASSE
;
635 Check whether the IP is a valid unicast address according to
638 ASSERT if NetMask is zero.
640 If all bits of the host address of IP are 0 or 1, IP is also not a valid unicast address,
641 except when the originator is one of the endpoints of a point-to-point link with a 31-bit
644 @param[in] Ip The IP to check against.
645 @param[in] NetMask The mask of the IP.
647 @return TRUE if IP is a valid unicast address on the network, otherwise FALSE.
657 ASSERT (NetMask
!= 0);
659 if (Ip
== 0 || IP4_IS_LOCAL_BROADCAST (Ip
)) {
663 if (NetGetMaskLength (NetMask
) != 31) {
664 if (((Ip
&~NetMask
) == ~NetMask
) || ((Ip
&~NetMask
) == 0)) {
675 Check whether the incoming IPv6 address is a valid unicast address.
677 If the address is a multicast address has binary 0xFF at the start, it is not
678 a valid unicast address. If the address is unspecified ::, it is not a valid
679 unicast address to be assigned to any node. If the address is loopback address
680 ::1, it is also not a valid unicast address to be assigned to any physical
683 @param[in] Ip6 The IPv6 address to check against.
685 @return TRUE if Ip6 is a valid unicast address on the network, otherwise FALSE.
690 NetIp6IsValidUnicast (
691 IN EFI_IPv6_ADDRESS
*Ip6
697 if (Ip6
->Addr
[0] == 0xFF) {
701 for (Index
= 0; Index
< 15; Index
++) {
702 if (Ip6
->Addr
[Index
] != 0) {
707 Byte
= Ip6
->Addr
[Index
];
709 if (Byte
== 0x0 || Byte
== 0x1) {
717 Check whether the incoming Ipv6 address is the unspecified address or not.
719 @param[in] Ip6 - Ip6 address, in network order.
721 @retval TRUE - Yes, unspecified
727 NetIp6IsUnspecifiedAddr (
728 IN EFI_IPv6_ADDRESS
*Ip6
733 for (Index
= 0; Index
< 16; Index
++) {
734 if (Ip6
->Addr
[Index
] != 0) {
743 Check whether the incoming Ipv6 address is a link-local address.
745 @param[in] Ip6 - Ip6 address, in network order.
747 @retval TRUE - Yes, link-local address
753 NetIp6IsLinkLocalAddr (
754 IN EFI_IPv6_ADDRESS
*Ip6
759 ASSERT (Ip6
!= NULL
);
761 if (Ip6
->Addr
[0] != 0xFE) {
765 if (Ip6
->Addr
[1] != 0x80) {
769 for (Index
= 2; Index
< 8; Index
++) {
770 if (Ip6
->Addr
[Index
] != 0) {
779 Check whether the Ipv6 address1 and address2 are on the connected network.
781 @param[in] Ip1 - Ip6 address1, in network order.
782 @param[in] Ip2 - Ip6 address2, in network order.
783 @param[in] PrefixLength - The prefix length of the checking net.
785 @retval TRUE - Yes, connected.
792 EFI_IPv6_ADDRESS
*Ip1
,
793 EFI_IPv6_ADDRESS
*Ip2
,
801 ASSERT ((Ip1
!= NULL
) && (Ip2
!= NULL
) && (PrefixLength
<= IP6_PREFIX_MAX
));
803 if (PrefixLength
== 0) {
807 Byte
= (UINT8
) (PrefixLength
/ 8);
808 Bit
= (UINT8
) (PrefixLength
% 8);
810 if (CompareMem (Ip1
, Ip2
, Byte
) != 0) {
815 Mask
= (UINT8
) (0xFF << (8 - Bit
));
818 if ((Ip1
->Addr
[Byte
] & Mask
) != (Ip2
->Addr
[Byte
] & Mask
)) {
828 Switches the endianess of an IPv6 address
830 This function swaps the bytes in a 128-bit IPv6 address to switch the value
831 from little endian to big endian or vice versa. The byte swapped value is
834 @param Ip6 Points to an IPv6 address
836 @return The byte swapped IPv6 address.
842 EFI_IPv6_ADDRESS
*Ip6
848 CopyMem (&High
, Ip6
, sizeof (UINT64
));
849 CopyMem (&Low
, &Ip6
->Addr
[8], sizeof (UINT64
));
851 High
= SwapBytes64 (High
);
852 Low
= SwapBytes64 (Low
);
854 CopyMem (Ip6
, &Low
, sizeof (UINT64
));
855 CopyMem (&Ip6
->Addr
[8], &High
, sizeof (UINT64
));
861 Initialize a random seed using current time and monotonic count.
863 Get current time and monotonic count first. Then initialize a random seed
864 based on some basic mathematics operation on the hour, day, minute, second,
865 nanosecond and year of the current time and the monotonic count value.
867 @return The random seed initialized with current time.
878 UINT64 MonotonicCount
;
880 gRT
->GetTime (&Time
, NULL
);
881 Seed
= (Time
.Hour
<< 24 | Time
.Day
<< 16 | Time
.Minute
<< 8 | Time
.Second
);
882 Seed
^= Time
.Nanosecond
;
883 Seed
^= Time
.Year
<< 7;
885 gBS
->GetNextMonotonicCount (&MonotonicCount
);
886 Seed
+= (UINT32
) MonotonicCount
;
893 Extract a UINT32 from a byte stream.
895 Copy a UINT32 from a byte stream, then converts it from Network
896 byte order to host byte order. Use this function to avoid alignment error.
898 @param[in] Buf The buffer to extract the UINT32.
900 @return The UINT32 extracted.
911 CopyMem (&Value
, Buf
, sizeof (UINT32
));
912 return NTOHL (Value
);
917 Put a UINT32 to the byte stream in network byte order.
919 Converts a UINT32 from host byte order to network byte order. Then copy it to the
922 @param[in, out] Buf The buffer to put the UINT32.
923 @param[in] Data The data to be converted and put into the byte stream.
934 CopyMem (Buf
, &Data
, sizeof (UINT32
));
939 Remove the first node entry on the list, and return the removed node entry.
941 Removes the first node Entry from a doubly linked list. It is up to the caller of
942 this function to release the memory used by the first node if that is required. On
943 exit, the removed node is returned.
945 If Head is NULL, then ASSERT().
946 If Head was not initialized, then ASSERT().
947 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
948 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
951 @param[in, out] Head The list header.
953 @return The first node entry that is removed from the list, NULL if the list is empty.
959 IN OUT LIST_ENTRY
*Head
964 ASSERT (Head
!= NULL
);
966 if (IsListEmpty (Head
)) {
970 First
= Head
->ForwardLink
;
971 Head
->ForwardLink
= First
->ForwardLink
;
972 First
->ForwardLink
->BackLink
= Head
;
975 First
->ForwardLink
= (LIST_ENTRY
*) NULL
;
976 First
->BackLink
= (LIST_ENTRY
*) NULL
;
984 Remove the last node entry on the list and and return the removed node entry.
986 Removes the last node entry from a doubly linked list. It is up to the caller of
987 this function to release the memory used by the first node if that is required. On
988 exit, the removed node is returned.
990 If Head is NULL, then ASSERT().
991 If Head was not initialized, then ASSERT().
992 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
993 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
996 @param[in, out] Head The list head.
998 @return The last node entry that is removed from the list, NULL if the list is empty.
1004 IN OUT LIST_ENTRY
*Head
1009 ASSERT (Head
!= NULL
);
1011 if (IsListEmpty (Head
)) {
1015 Last
= Head
->BackLink
;
1016 Head
->BackLink
= Last
->BackLink
;
1017 Last
->BackLink
->ForwardLink
= Head
;
1020 Last
->ForwardLink
= (LIST_ENTRY
*) NULL
;
1021 Last
->BackLink
= (LIST_ENTRY
*) NULL
;
1029 Insert a new node entry after a designated node entry of a doubly linked list.
1031 Inserts a new node entry donated by NewEntry after the node entry donated by PrevEntry
1032 of the doubly linked list.
1034 @param[in, out] PrevEntry The previous entry to insert after.
1035 @param[in, out] NewEntry The new entry to insert.
1040 NetListInsertAfter (
1041 IN OUT LIST_ENTRY
*PrevEntry
,
1042 IN OUT LIST_ENTRY
*NewEntry
1045 NewEntry
->BackLink
= PrevEntry
;
1046 NewEntry
->ForwardLink
= PrevEntry
->ForwardLink
;
1047 PrevEntry
->ForwardLink
->BackLink
= NewEntry
;
1048 PrevEntry
->ForwardLink
= NewEntry
;
1053 Insert a new node entry before a designated node entry of a doubly linked list.
1055 Inserts a new node entry donated by NewEntry after the node entry donated by PostEntry
1056 of the doubly linked list.
1058 @param[in, out] PostEntry The entry to insert before.
1059 @param[in, out] NewEntry The new entry to insert.
1064 NetListInsertBefore (
1065 IN OUT LIST_ENTRY
*PostEntry
,
1066 IN OUT LIST_ENTRY
*NewEntry
1069 NewEntry
->ForwardLink
= PostEntry
;
1070 NewEntry
->BackLink
= PostEntry
->BackLink
;
1071 PostEntry
->BackLink
->ForwardLink
= NewEntry
;
1072 PostEntry
->BackLink
= NewEntry
;
1076 Safe destroy nodes in a linked list, and return the length of the list after all possible operations finished.
1078 Destroy network child instance list by list traversals is not safe due to graph dependencies between nodes.
1079 This function performs a safe traversal to destroy these nodes by checking to see if the node being destroyed
1080 has been removed from the list or not.
1081 If it has been removed, then restart the traversal from the head.
1082 If it hasn't been removed, then continue with the next node directly.
1083 This function will end the iterate and return the CallBack's last return value if error happens,
1084 or retrun EFI_SUCCESS if 2 complete passes are made with no changes in the number of children in the list.
1086 @param[in] List The head of the list.
1087 @param[in] CallBack Pointer to the callback function to destroy one node in the list.
1088 @param[in] Context Pointer to the callback function's context: corresponds to the
1089 parameter Context in NET_DESTROY_LINK_LIST_CALLBACK.
1090 @param[out] ListLength The length of the link list if the function returns successfully.
1092 @retval EFI_SUCCESS Two complete passes are made with no changes in the number of children.
1093 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
1094 @retval Others Return the CallBack's last return value.
1099 NetDestroyLinkList (
1100 IN LIST_ENTRY
*List
,
1101 IN NET_DESTROY_LINK_LIST_CALLBACK CallBack
,
1102 IN VOID
*Context
, OPTIONAL
1103 OUT UINTN
*ListLength OPTIONAL
1106 UINTN PreviousLength
;
1112 if (List
== NULL
|| CallBack
== NULL
) {
1113 return EFI_INVALID_PARAMETER
;
1118 PreviousLength
= Length
;
1119 Entry
= GetFirstNode (List
);
1120 while (!IsNull (List
, Entry
)) {
1121 Status
= CallBack (Entry
, Context
);
1122 if (EFI_ERROR (Status
)) {
1126 // Walk through the list to see whether the Entry has been removed or not.
1127 // If the Entry still exists, just try to destroy the next one.
1128 // If not, go back to the start point to iterate the list again.
1130 for (Ptr
= List
->ForwardLink
; Ptr
!= List
; Ptr
= Ptr
->ForwardLink
) {
1136 Entry
= GetNextNode (List
, Entry
);
1138 Entry
= GetFirstNode (List
);
1141 for (Length
= 0, Ptr
= List
->ForwardLink
; Ptr
!= List
; Length
++, Ptr
= Ptr
->ForwardLink
);
1142 } while (Length
!= PreviousLength
);
1144 if (ListLength
!= NULL
) {
1145 *ListLength
= Length
;
1151 This function checks the input Handle to see if it's one of these handles in ChildHandleBuffer.
1153 @param[in] Handle Handle to be checked.
1154 @param[in] NumberOfChildren Number of Handles in ChildHandleBuffer.
1155 @param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
1156 if NumberOfChildren is 0.
1158 @retval TRUE Found the input Handle in ChildHandleBuffer.
1159 @retval FALSE Can't find the input Handle in ChildHandleBuffer.
1164 NetIsInHandleBuffer (
1165 IN EFI_HANDLE Handle
,
1166 IN UINTN NumberOfChildren
,
1167 IN EFI_HANDLE
*ChildHandleBuffer OPTIONAL
1172 if (NumberOfChildren
== 0 || ChildHandleBuffer
== NULL
) {
1176 for (Index
= 0; Index
< NumberOfChildren
; Index
++) {
1177 if (Handle
== ChildHandleBuffer
[Index
]) {
1187 Initialize the netmap. Netmap is a reposity to keep the <Key, Value> pairs.
1189 Initialize the forward and backward links of two head nodes donated by Map->Used
1190 and Map->Recycled of two doubly linked lists.
1191 Initializes the count of the <Key, Value> pairs in the netmap to zero.
1193 If Map is NULL, then ASSERT().
1194 If the address of Map->Used is NULL, then ASSERT().
1195 If the address of Map->Recycled is NULl, then ASSERT().
1197 @param[in, out] Map The netmap to initialize.
1206 ASSERT (Map
!= NULL
);
1208 InitializeListHead (&Map
->Used
);
1209 InitializeListHead (&Map
->Recycled
);
1215 To clean up the netmap, that is, release allocated memories.
1217 Removes all nodes of the Used doubly linked list and free memory of all related netmap items.
1218 Removes all nodes of the Recycled doubly linked list and free memory of all related netmap items.
1219 The number of the <Key, Value> pairs in the netmap is set to be zero.
1221 If Map is NULL, then ASSERT().
1223 @param[in, out] Map The netmap to clean up.
1236 ASSERT (Map
!= NULL
);
1238 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, &Map
->Used
) {
1239 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1241 RemoveEntryList (&Item
->Link
);
1244 gBS
->FreePool (Item
);
1247 ASSERT ((Map
->Count
== 0) && IsListEmpty (&Map
->Used
));
1249 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, &Map
->Recycled
) {
1250 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1252 RemoveEntryList (&Item
->Link
);
1253 gBS
->FreePool (Item
);
1256 ASSERT (IsListEmpty (&Map
->Recycled
));
1261 Test whether the netmap is empty and return true if it is.
1263 If the number of the <Key, Value> pairs in the netmap is zero, return TRUE.
1265 If Map is NULL, then ASSERT().
1268 @param[in] Map The net map to test.
1270 @return TRUE if the netmap is empty, otherwise FALSE.
1279 ASSERT (Map
!= NULL
);
1280 return (BOOLEAN
) (Map
->Count
== 0);
1285 Return the number of the <Key, Value> pairs in the netmap.
1287 @param[in] Map The netmap to get the entry number.
1289 @return The entry number in the netmap.
1303 Return one allocated item.
1305 If the Recycled doubly linked list of the netmap is empty, it will try to allocate
1306 a batch of items if there are enough resources and add corresponding nodes to the begining
1307 of the Recycled doubly linked list of the netmap. Otherwise, it will directly remove
1308 the fist node entry of the Recycled doubly linked list and return the corresponding item.
1310 If Map is NULL, then ASSERT().
1312 @param[in, out] Map The netmap to allocate item for.
1314 @return The allocated item. If NULL, the
1315 allocation failed due to resource limit.
1327 ASSERT (Map
!= NULL
);
1329 Head
= &Map
->Recycled
;
1331 if (IsListEmpty (Head
)) {
1332 for (Index
= 0; Index
< NET_MAP_INCREAMENT
; Index
++) {
1333 Item
= AllocatePool (sizeof (NET_MAP_ITEM
));
1343 InsertHeadList (Head
, &Item
->Link
);
1347 Item
= NET_LIST_HEAD (Head
, NET_MAP_ITEM
, Link
);
1348 NetListRemoveHead (Head
);
1355 Allocate an item to save the <Key, Value> pair to the head of the netmap.
1357 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1358 to the beginning of the Used doubly linked list. The number of the <Key, Value>
1359 pairs in the netmap increase by 1.
1361 If Map is NULL, then ASSERT().
1363 @param[in, out] Map The netmap to insert into.
1364 @param[in] Key The user's key.
1365 @param[in] Value The user's value for the key.
1367 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1368 @retval EFI_SUCCESS The item is inserted to the head.
1374 IN OUT NET_MAP
*Map
,
1376 IN VOID
*Value OPTIONAL
1381 ASSERT (Map
!= NULL
);
1383 Item
= NetMapAllocItem (Map
);
1386 return EFI_OUT_OF_RESOURCES
;
1390 Item
->Value
= Value
;
1391 InsertHeadList (&Map
->Used
, &Item
->Link
);
1399 Allocate an item to save the <Key, Value> pair to the tail of the netmap.
1401 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1402 to the tail of the Used doubly linked list. The number of the <Key, Value>
1403 pairs in the netmap increase by 1.
1405 If Map is NULL, then ASSERT().
1407 @param[in, out] Map The netmap to insert into.
1408 @param[in] Key The user's key.
1409 @param[in] Value The user's value for the key.
1411 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1412 @retval EFI_SUCCESS The item is inserted to the tail.
1418 IN OUT NET_MAP
*Map
,
1420 IN VOID
*Value OPTIONAL
1425 ASSERT (Map
!= NULL
);
1427 Item
= NetMapAllocItem (Map
);
1430 return EFI_OUT_OF_RESOURCES
;
1434 Item
->Value
= Value
;
1435 InsertTailList (&Map
->Used
, &Item
->Link
);
1444 Check whether the item is in the Map and return TRUE if it is.
1446 @param[in] Map The netmap to search within.
1447 @param[in] Item The item to search.
1449 @return TRUE if the item is in the netmap, otherwise FALSE.
1455 IN NET_MAP_ITEM
*Item
1458 LIST_ENTRY
*ListEntry
;
1460 NET_LIST_FOR_EACH (ListEntry
, &Map
->Used
) {
1461 if (ListEntry
== &Item
->Link
) {
1471 Find the key in the netmap and returns the point to the item contains the Key.
1473 Iterate the Used doubly linked list of the netmap to get every item. Compare the key of every
1474 item with the key to search. It returns the point to the item contains the Key if found.
1476 If Map is NULL, then ASSERT().
1478 @param[in] Map The netmap to search within.
1479 @param[in] Key The key to search.
1481 @return The point to the item contains the Key, or NULL if Key isn't in the map.
1494 ASSERT (Map
!= NULL
);
1496 NET_LIST_FOR_EACH (Entry
, &Map
->Used
) {
1497 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1499 if (Item
->Key
== Key
) {
1509 Remove the node entry of the item from the netmap and return the key of the removed item.
1511 Remove the node entry of the item from the Used doubly linked list of the netmap.
1512 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1513 entry of the item to the Recycled doubly linked list of the netmap. If Value is not NULL,
1514 Value will point to the value of the item. It returns the key of the removed item.
1516 If Map is NULL, then ASSERT().
1517 If Item is NULL, then ASSERT().
1518 if item in not in the netmap, then ASSERT().
1520 @param[in, out] Map The netmap to remove the item from.
1521 @param[in, out] Item The item to remove.
1522 @param[out] Value The variable to receive the value if not NULL.
1524 @return The key of the removed item.
1530 IN OUT NET_MAP
*Map
,
1531 IN OUT NET_MAP_ITEM
*Item
,
1532 OUT VOID
**Value OPTIONAL
1535 ASSERT ((Map
!= NULL
) && (Item
!= NULL
));
1536 ASSERT (NetItemInMap (Map
, Item
));
1538 RemoveEntryList (&Item
->Link
);
1540 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1542 if (Value
!= NULL
) {
1543 *Value
= Item
->Value
;
1551 Remove the first node entry on the netmap and return the key of the removed item.
1553 Remove the first node entry from the Used doubly linked list of the netmap.
1554 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1555 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1556 parameter Value will point to the value of the item. It returns the key of the removed item.
1558 If Map is NULL, then ASSERT().
1559 If the Used doubly linked list is empty, then ASSERT().
1561 @param[in, out] Map The netmap to remove the head from.
1562 @param[out] Value The variable to receive the value if not NULL.
1564 @return The key of the item removed.
1570 IN OUT NET_MAP
*Map
,
1571 OUT VOID
**Value OPTIONAL
1577 // Often, it indicates a programming error to remove
1578 // the first entry in an empty list
1580 ASSERT (Map
&& !IsListEmpty (&Map
->Used
));
1582 Item
= NET_LIST_HEAD (&Map
->Used
, NET_MAP_ITEM
, Link
);
1583 RemoveEntryList (&Item
->Link
);
1585 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1587 if (Value
!= NULL
) {
1588 *Value
= Item
->Value
;
1596 Remove the last node entry on the netmap and return the key of the removed item.
1598 Remove the last node entry from the Used doubly linked list of the netmap.
1599 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1600 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1601 parameter Value will point to the value of the item. It returns the key of the removed item.
1603 If Map is NULL, then ASSERT().
1604 If the Used doubly linked list is empty, then ASSERT().
1606 @param[in, out] Map The netmap to remove the tail from.
1607 @param[out] Value The variable to receive the value if not NULL.
1609 @return The key of the item removed.
1615 IN OUT NET_MAP
*Map
,
1616 OUT VOID
**Value OPTIONAL
1622 // Often, it indicates a programming error to remove
1623 // the last entry in an empty list
1625 ASSERT (Map
&& !IsListEmpty (&Map
->Used
));
1627 Item
= NET_LIST_TAIL (&Map
->Used
, NET_MAP_ITEM
, Link
);
1628 RemoveEntryList (&Item
->Link
);
1630 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1632 if (Value
!= NULL
) {
1633 *Value
= Item
->Value
;
1641 Iterate through the netmap and call CallBack for each item.
1643 It will continue the traverse if CallBack returns EFI_SUCCESS, otherwise, break
1644 from the loop. It returns the CallBack's last return value. This function is
1645 delete safe for the current item.
1647 If Map is NULL, then ASSERT().
1648 If CallBack is NULL, then ASSERT().
1650 @param[in] Map The Map to iterate through.
1651 @param[in] CallBack The callback function to call for each item.
1652 @param[in] Arg The opaque parameter to the callback.
1654 @retval EFI_SUCCESS There is no item in the netmap or CallBack for each item
1656 @retval Others It returns the CallBack's last return value.
1663 IN NET_MAP_CALLBACK CallBack
,
1664 IN VOID
*Arg OPTIONAL
1674 ASSERT ((Map
!= NULL
) && (CallBack
!= NULL
));
1678 if (IsListEmpty (Head
)) {
1682 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, Head
) {
1683 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1684 Result
= CallBack (Map
, Item
, Arg
);
1686 if (EFI_ERROR (Result
)) {
1696 This is the default unload handle for all the network drivers.
1698 Disconnect the driver specified by ImageHandle from all the devices in the handle database.
1699 Uninstall all the protocols installed in the driver entry point.
1701 @param[in] ImageHandle The drivers' driver image.
1703 @retval EFI_SUCCESS The image is unloaded.
1704 @retval Others Failed to unload the image.
1709 NetLibDefaultUnload (
1710 IN EFI_HANDLE ImageHandle
1714 EFI_HANDLE
*DeviceHandleBuffer
;
1715 UINTN DeviceHandleCount
;
1718 EFI_DRIVER_BINDING_PROTOCOL
*DriverBinding
;
1719 EFI_COMPONENT_NAME_PROTOCOL
*ComponentName
;
1720 EFI_COMPONENT_NAME2_PROTOCOL
*ComponentName2
;
1723 // Get the list of all the handles in the handle database.
1724 // If there is an error getting the list, then the unload
1727 Status
= gBS
->LocateHandleBuffer (
1735 if (EFI_ERROR (Status
)) {
1739 for (Index
= 0; Index
< DeviceHandleCount
; Index
++) {
1740 Status
= gBS
->HandleProtocol (
1741 DeviceHandleBuffer
[Index
],
1742 &gEfiDriverBindingProtocolGuid
,
1743 (VOID
**) &DriverBinding
1745 if (EFI_ERROR (Status
)) {
1749 if (DriverBinding
->ImageHandle
!= ImageHandle
) {
1754 // Disconnect the driver specified by ImageHandle from all
1755 // the devices in the handle database.
1757 for (Index2
= 0; Index2
< DeviceHandleCount
; Index2
++) {
1758 Status
= gBS
->DisconnectController (
1759 DeviceHandleBuffer
[Index2
],
1760 DriverBinding
->DriverBindingHandle
,
1766 // Uninstall all the protocols installed in the driver entry point
1768 gBS
->UninstallProtocolInterface (
1769 DriverBinding
->DriverBindingHandle
,
1770 &gEfiDriverBindingProtocolGuid
,
1774 Status
= gBS
->HandleProtocol (
1775 DeviceHandleBuffer
[Index
],
1776 &gEfiComponentNameProtocolGuid
,
1777 (VOID
**) &ComponentName
1779 if (!EFI_ERROR (Status
)) {
1780 gBS
->UninstallProtocolInterface (
1781 DriverBinding
->DriverBindingHandle
,
1782 &gEfiComponentNameProtocolGuid
,
1787 Status
= gBS
->HandleProtocol (
1788 DeviceHandleBuffer
[Index
],
1789 &gEfiComponentName2ProtocolGuid
,
1790 (VOID
**) &ComponentName2
1792 if (!EFI_ERROR (Status
)) {
1793 gBS
->UninstallProtocolInterface (
1794 DriverBinding
->DriverBindingHandle
,
1795 &gEfiComponentName2ProtocolGuid
,
1802 // Free the buffer containing the list of handles from the handle database
1804 if (DeviceHandleBuffer
!= NULL
) {
1805 gBS
->FreePool (DeviceHandleBuffer
);
1814 Create a child of the service that is identified by ServiceBindingGuid.
1816 Get the ServiceBinding Protocol first, then use it to create a child.
1818 If ServiceBindingGuid is NULL, then ASSERT().
1819 If ChildHandle is NULL, then ASSERT().
1821 @param[in] Controller The controller which has the service installed.
1822 @param[in] Image The image handle used to open service.
1823 @param[in] ServiceBindingGuid The service's Guid.
1824 @param[in, out] ChildHandle The handle to receive the create child.
1826 @retval EFI_SUCCESS The child is successfully created.
1827 @retval Others Failed to create the child.
1832 NetLibCreateServiceChild (
1833 IN EFI_HANDLE Controller
,
1834 IN EFI_HANDLE Image
,
1835 IN EFI_GUID
*ServiceBindingGuid
,
1836 IN OUT EFI_HANDLE
*ChildHandle
1840 EFI_SERVICE_BINDING_PROTOCOL
*Service
;
1843 ASSERT ((ServiceBindingGuid
!= NULL
) && (ChildHandle
!= NULL
));
1846 // Get the ServiceBinding Protocol
1848 Status
= gBS
->OpenProtocol (
1854 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1857 if (EFI_ERROR (Status
)) {
1864 Status
= Service
->CreateChild (Service
, ChildHandle
);
1870 Destroy a child of the service that is identified by ServiceBindingGuid.
1872 Get the ServiceBinding Protocol first, then use it to destroy a child.
1874 If ServiceBindingGuid is NULL, then ASSERT().
1876 @param[in] Controller The controller which has the service installed.
1877 @param[in] Image The image handle used to open service.
1878 @param[in] ServiceBindingGuid The service's Guid.
1879 @param[in] ChildHandle The child to destroy.
1881 @retval EFI_SUCCESS The child is successfully destroyed.
1882 @retval Others Failed to destroy the child.
1887 NetLibDestroyServiceChild (
1888 IN EFI_HANDLE Controller
,
1889 IN EFI_HANDLE Image
,
1890 IN EFI_GUID
*ServiceBindingGuid
,
1891 IN EFI_HANDLE ChildHandle
1895 EFI_SERVICE_BINDING_PROTOCOL
*Service
;
1897 ASSERT (ServiceBindingGuid
!= NULL
);
1900 // Get the ServiceBinding Protocol
1902 Status
= gBS
->OpenProtocol (
1908 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1911 if (EFI_ERROR (Status
)) {
1916 // destroy the child
1918 Status
= Service
->DestroyChild (Service
, ChildHandle
);
1923 Get handle with Simple Network Protocol installed on it.
1925 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
1926 If Simple Network Protocol is already installed on the ServiceHandle, the
1927 ServiceHandle will be returned. If SNP is not installed on the ServiceHandle,
1928 try to find its parent handle with SNP installed.
1930 @param[in] ServiceHandle The handle where network service binding protocols are
1932 @param[out] Snp The pointer to store the address of the SNP instance.
1933 This is an optional parameter that may be NULL.
1935 @return The SNP handle, or NULL if not found.
1940 NetLibGetSnpHandle (
1941 IN EFI_HANDLE ServiceHandle
,
1942 OUT EFI_SIMPLE_NETWORK_PROTOCOL
**Snp OPTIONAL
1946 EFI_SIMPLE_NETWORK_PROTOCOL
*SnpInstance
;
1947 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
1948 EFI_HANDLE SnpHandle
;
1951 // Try to open SNP from ServiceHandle
1954 Status
= gBS
->HandleProtocol (ServiceHandle
, &gEfiSimpleNetworkProtocolGuid
, (VOID
**) &SnpInstance
);
1955 if (!EFI_ERROR (Status
)) {
1959 return ServiceHandle
;
1963 // Failed to open SNP, try to get SNP handle by LocateDevicePath()
1965 DevicePath
= DevicePathFromHandle (ServiceHandle
);
1966 if (DevicePath
== NULL
) {
1971 Status
= gBS
->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid
, &DevicePath
, &SnpHandle
);
1972 if (EFI_ERROR (Status
)) {
1974 // Failed to find SNP handle
1979 Status
= gBS
->HandleProtocol (SnpHandle
, &gEfiSimpleNetworkProtocolGuid
, (VOID
**) &SnpInstance
);
1980 if (!EFI_ERROR (Status
)) {
1991 Retrieve VLAN ID of a VLAN device handle.
1993 Search VLAN device path node in Device Path of specified ServiceHandle and
1994 return its VLAN ID. If no VLAN device path node found, then this ServiceHandle
1995 is not a VLAN device handle, and 0 will be returned.
1997 @param[in] ServiceHandle The handle where network service binding protocols are
2000 @return VLAN ID of the device handle, or 0 if not a VLAN device.
2006 IN EFI_HANDLE ServiceHandle
2009 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2010 EFI_DEVICE_PATH_PROTOCOL
*Node
;
2012 DevicePath
= DevicePathFromHandle (ServiceHandle
);
2013 if (DevicePath
== NULL
) {
2018 while (!IsDevicePathEnd (Node
)) {
2019 if (Node
->Type
== MESSAGING_DEVICE_PATH
&& Node
->SubType
== MSG_VLAN_DP
) {
2020 return ((VLAN_DEVICE_PATH
*) Node
)->VlanId
;
2022 Node
= NextDevicePathNode (Node
);
2029 Find VLAN device handle with specified VLAN ID.
2031 The VLAN child device handle is created by VLAN Config Protocol on ControllerHandle.
2032 This function will append VLAN device path node to the parent device path,
2033 and then use LocateDevicePath() to find the correct VLAN device handle.
2035 @param[in] ControllerHandle The handle where network service binding protocols are
2037 @param[in] VlanId The configured VLAN ID for the VLAN device.
2039 @return The VLAN device handle, or NULL if not found.
2044 NetLibGetVlanHandle (
2045 IN EFI_HANDLE ControllerHandle
,
2049 EFI_DEVICE_PATH_PROTOCOL
*ParentDevicePath
;
2050 EFI_DEVICE_PATH_PROTOCOL
*VlanDevicePath
;
2051 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2052 VLAN_DEVICE_PATH VlanNode
;
2055 ParentDevicePath
= DevicePathFromHandle (ControllerHandle
);
2056 if (ParentDevicePath
== NULL
) {
2061 // Construct VLAN device path
2063 CopyMem (&VlanNode
, &mNetVlanDevicePathTemplate
, sizeof (VLAN_DEVICE_PATH
));
2064 VlanNode
.VlanId
= VlanId
;
2065 VlanDevicePath
= AppendDevicePathNode (
2067 (EFI_DEVICE_PATH_PROTOCOL
*) &VlanNode
2069 if (VlanDevicePath
== NULL
) {
2074 // Find VLAN device handle
2077 DevicePath
= VlanDevicePath
;
2078 gBS
->LocateDevicePath (
2079 &gEfiDevicePathProtocolGuid
,
2083 if (!IsDevicePathEnd (DevicePath
)) {
2085 // Device path is not exactly match
2090 FreePool (VlanDevicePath
);
2095 Get MAC address associated with the network service handle.
2097 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
2098 If SNP is installed on the ServiceHandle or its parent handle, MAC address will
2099 be retrieved from SNP. If no SNP found, try to get SNP mode data use MNP.
2101 @param[in] ServiceHandle The handle where network service binding protocols are
2103 @param[out] MacAddress The pointer to store the returned MAC address.
2104 @param[out] AddressSize The length of returned MAC address.
2106 @retval EFI_SUCCESS MAC address is returned successfully.
2107 @retval Others Failed to get SNP mode data.
2112 NetLibGetMacAddress (
2113 IN EFI_HANDLE ServiceHandle
,
2114 OUT EFI_MAC_ADDRESS
*MacAddress
,
2115 OUT UINTN
*AddressSize
2119 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2120 EFI_SIMPLE_NETWORK_MODE
*SnpMode
;
2121 EFI_SIMPLE_NETWORK_MODE SnpModeData
;
2122 EFI_MANAGED_NETWORK_PROTOCOL
*Mnp
;
2123 EFI_SERVICE_BINDING_PROTOCOL
*MnpSb
;
2124 EFI_HANDLE
*SnpHandle
;
2125 EFI_HANDLE MnpChildHandle
;
2127 ASSERT (MacAddress
!= NULL
);
2128 ASSERT (AddressSize
!= NULL
);
2131 // Try to get SNP handle
2134 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2135 if (SnpHandle
!= NULL
) {
2137 // SNP found, use it directly
2139 SnpMode
= Snp
->Mode
;
2142 // Failed to get SNP handle, try to get MAC address from MNP
2144 MnpChildHandle
= NULL
;
2145 Status
= gBS
->HandleProtocol (
2147 &gEfiManagedNetworkServiceBindingProtocolGuid
,
2150 if (EFI_ERROR (Status
)) {
2155 // Create a MNP child
2157 Status
= MnpSb
->CreateChild (MnpSb
, &MnpChildHandle
);
2158 if (EFI_ERROR (Status
)) {
2163 // Open MNP protocol
2165 Status
= gBS
->HandleProtocol (
2167 &gEfiManagedNetworkProtocolGuid
,
2170 if (EFI_ERROR (Status
)) {
2171 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2176 // Try to get SNP mode from MNP
2178 Status
= Mnp
->GetModeData (Mnp
, NULL
, &SnpModeData
);
2179 if (EFI_ERROR (Status
) && (Status
!= EFI_NOT_STARTED
)) {
2180 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2183 SnpMode
= &SnpModeData
;
2186 // Destroy the MNP child
2188 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2191 *AddressSize
= SnpMode
->HwAddressSize
;
2192 CopyMem (MacAddress
->Addr
, SnpMode
->CurrentAddress
.Addr
, SnpMode
->HwAddressSize
);
2198 Convert MAC address of the NIC associated with specified Service Binding Handle
2199 to a unicode string. Callers are responsible for freeing the string storage.
2201 Locate simple network protocol associated with the Service Binding Handle and
2202 get the mac address from SNP. Then convert the mac address into a unicode
2203 string. It takes 2 unicode characters to represent a 1 byte binary buffer.
2204 Plus one unicode character for the null-terminator.
2206 @param[in] ServiceHandle The handle where network service binding protocol is
2208 @param[in] ImageHandle The image handle used to act as the agent handle to
2209 get the simple network protocol. This parameter is
2210 optional and may be NULL.
2211 @param[out] MacString The pointer to store the address of the string
2212 representation of the mac address.
2214 @retval EFI_SUCCESS Convert the mac address a unicode string successfully.
2215 @retval EFI_OUT_OF_RESOURCES There are not enough memory resource.
2216 @retval Others Failed to open the simple network protocol.
2221 NetLibGetMacString (
2222 IN EFI_HANDLE ServiceHandle
,
2223 IN EFI_HANDLE ImageHandle
, OPTIONAL
2224 OUT CHAR16
**MacString
2228 EFI_MAC_ADDRESS MacAddress
;
2230 UINTN HwAddressSize
;
2236 ASSERT (MacString
!= NULL
);
2239 // Get MAC address of the network device
2241 Status
= NetLibGetMacAddress (ServiceHandle
, &MacAddress
, &HwAddressSize
);
2242 if (EFI_ERROR (Status
)) {
2247 // It takes 2 unicode characters to represent a 1 byte binary buffer.
2248 // If VLAN is configured, it will need extra 5 characters like "\0005".
2249 // Plus one unicode character for the null-terminator.
2251 BufferSize
= (2 * HwAddressSize
+ 5 + 1) * sizeof (CHAR16
);
2252 String
= AllocateZeroPool (BufferSize
);
2253 if (String
== NULL
) {
2254 return EFI_OUT_OF_RESOURCES
;
2256 *MacString
= String
;
2259 // Convert the MAC address into a unicode string.
2261 HwAddress
= &MacAddress
.Addr
[0];
2262 for (Index
= 0; Index
< HwAddressSize
; Index
++) {
2263 UnicodeValueToStringS (
2265 BufferSize
- ((UINTN
)String
- (UINTN
)*MacString
),
2266 PREFIX_ZERO
| RADIX_HEX
,
2270 String
+= StrnLenS (String
, (BufferSize
- ((UINTN
)String
- (UINTN
)*MacString
)) / sizeof (CHAR16
));
2274 // Append VLAN ID if any
2276 VlanId
= NetLibGetVlanId (ServiceHandle
);
2279 UnicodeValueToStringS (
2281 BufferSize
- ((UINTN
)String
- (UINTN
)*MacString
),
2282 PREFIX_ZERO
| RADIX_HEX
,
2286 String
+= StrnLenS (String
, (BufferSize
- ((UINTN
)String
- (UINTN
)*MacString
)) / sizeof (CHAR16
));
2290 // Null terminate the Unicode string
2298 Detect media status for specified network device.
2300 The underlying UNDI driver may or may not support reporting media status from
2301 GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine
2302 will try to invoke Snp->GetStatus() to get the media status: if media already
2303 present, it return directly; if media not present, it will stop SNP and then
2304 restart SNP to get the latest media status, this give chance to get the correct
2305 media status for old UNDI driver which doesn't support reporting media status
2306 from GET_STATUS command.
2307 Note: there will be two limitations for current algorithm:
2308 1) for UNDI with this capability, in case of cable is not attached, there will
2309 be an redundant Stop/Start() process;
2310 2) for UNDI without this capability, in case that network cable is attached when
2311 Snp->Initialize() is invoked while network cable is unattached later,
2312 NetLibDetectMedia() will report MediaPresent as TRUE, causing upper layer
2313 apps to wait for timeout time.
2315 @param[in] ServiceHandle The handle where network service binding protocols are
2317 @param[out] MediaPresent The pointer to store the media status.
2319 @retval EFI_SUCCESS Media detection success.
2320 @retval EFI_INVALID_PARAMETER ServiceHandle is not valid network device handle.
2321 @retval EFI_UNSUPPORTED Network device does not support media detection.
2322 @retval EFI_DEVICE_ERROR SNP is in unknown state.
2328 IN EFI_HANDLE ServiceHandle
,
2329 OUT BOOLEAN
*MediaPresent
2333 EFI_HANDLE SnpHandle
;
2334 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2335 UINT32 InterruptStatus
;
2337 EFI_MAC_ADDRESS
*MCastFilter
;
2338 UINT32 MCastFilterCount
;
2339 UINT32 EnableFilterBits
;
2340 UINT32 DisableFilterBits
;
2341 BOOLEAN ResetMCastFilters
;
2343 ASSERT (MediaPresent
!= NULL
);
2349 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2350 if (SnpHandle
== NULL
) {
2351 return EFI_INVALID_PARAMETER
;
2355 // Check whether SNP support media detection
2357 if (!Snp
->Mode
->MediaPresentSupported
) {
2358 return EFI_UNSUPPORTED
;
2362 // Invoke Snp->GetStatus() to refresh MediaPresent field in SNP mode data
2364 Status
= Snp
->GetStatus (Snp
, &InterruptStatus
, NULL
);
2365 if (EFI_ERROR (Status
)) {
2369 if (Snp
->Mode
->MediaPresent
) {
2371 // Media is present, return directly
2373 *MediaPresent
= TRUE
;
2378 // Till now, GetStatus() report no media; while, in case UNDI not support
2379 // reporting media status from GetStatus(), this media status may be incorrect.
2380 // So, we will stop SNP and then restart it to get the correct media status.
2382 OldState
= Snp
->Mode
->State
;
2383 if (OldState
>= EfiSimpleNetworkMaxState
) {
2384 return EFI_DEVICE_ERROR
;
2389 if (OldState
== EfiSimpleNetworkInitialized
) {
2391 // SNP is already in use, need Shutdown/Stop and then Start/Initialize
2395 // Backup current SNP receive filter settings
2397 EnableFilterBits
= Snp
->Mode
->ReceiveFilterSetting
;
2398 DisableFilterBits
= Snp
->Mode
->ReceiveFilterMask
^ EnableFilterBits
;
2400 ResetMCastFilters
= TRUE
;
2401 MCastFilterCount
= Snp
->Mode
->MCastFilterCount
;
2402 if (MCastFilterCount
!= 0) {
2403 MCastFilter
= AllocateCopyPool (
2404 MCastFilterCount
* sizeof (EFI_MAC_ADDRESS
),
2405 Snp
->Mode
->MCastFilter
2407 ASSERT (MCastFilter
!= NULL
);
2409 ResetMCastFilters
= FALSE
;
2413 // Shutdown/Stop the simple network
2415 Status
= Snp
->Shutdown (Snp
);
2416 if (!EFI_ERROR (Status
)) {
2417 Status
= Snp
->Stop (Snp
);
2419 if (EFI_ERROR (Status
)) {
2424 // Start/Initialize the simple network
2426 Status
= Snp
->Start (Snp
);
2427 if (!EFI_ERROR (Status
)) {
2428 Status
= Snp
->Initialize (Snp
, 0, 0);
2430 if (EFI_ERROR (Status
)) {
2435 // Here we get the correct media status
2437 *MediaPresent
= Snp
->Mode
->MediaPresent
;
2440 // Restore SNP receive filter settings
2442 Status
= Snp
->ReceiveFilters (
2451 if (MCastFilter
!= NULL
) {
2452 FreePool (MCastFilter
);
2459 // SNP is not in use, it's in state of EfiSimpleNetworkStopped or EfiSimpleNetworkStarted
2461 if (OldState
== EfiSimpleNetworkStopped
) {
2463 // SNP not start yet, start it
2465 Status
= Snp
->Start (Snp
);
2466 if (EFI_ERROR (Status
)) {
2472 // Initialize the simple network
2474 Status
= Snp
->Initialize (Snp
, 0, 0);
2475 if (EFI_ERROR (Status
)) {
2476 Status
= EFI_DEVICE_ERROR
;
2481 // Here we get the correct media status
2483 *MediaPresent
= Snp
->Mode
->MediaPresent
;
2486 // Shut down the simple network
2488 Snp
->Shutdown (Snp
);
2491 if (OldState
== EfiSimpleNetworkStopped
) {
2493 // Original SNP sate is Stopped, restore to original state
2498 if (MCastFilter
!= NULL
) {
2499 FreePool (MCastFilter
);
2506 Check the default address used by the IPv4 driver is static or dynamic (acquired
2509 If the controller handle does not have the EFI_IP4_CONFIG2_PROTOCOL installed, the
2510 default address is static. If failed to get the policy from Ip4 Config2 Protocol,
2511 the default address is static. Otherwise, get the result from Ip4 Config2 Protocol.
2513 @param[in] Controller The controller handle which has the EFI_IP4_CONFIG2_PROTOCOL
2514 relative with the default address to judge.
2516 @retval TRUE If the default address is static.
2517 @retval FALSE If the default address is acquired from DHCP.
2521 NetLibDefaultAddressIsStatic (
2522 IN EFI_HANDLE Controller
2526 EFI_IP4_CONFIG2_PROTOCOL
*Ip4Config2
;
2528 EFI_IP4_CONFIG2_POLICY Policy
;
2533 DataSize
= sizeof (EFI_IP4_CONFIG2_POLICY
);
2538 // Get Ip4Config2 policy.
2540 Status
= gBS
->HandleProtocol (Controller
, &gEfiIp4Config2ProtocolGuid
, (VOID
**) &Ip4Config2
);
2541 if (EFI_ERROR (Status
)) {
2545 Status
= Ip4Config2
->GetData (Ip4Config2
, Ip4Config2DataTypePolicy
, &DataSize
, &Policy
);
2546 if (EFI_ERROR (Status
)) {
2550 IsStatic
= (BOOLEAN
) (Policy
== Ip4Config2PolicyStatic
);
2558 Create an IPv4 device path node.
2560 The header type of IPv4 device path node is MESSAGING_DEVICE_PATH.
2561 The header subtype of IPv4 device path node is MSG_IPv4_DP.
2562 Get other info from parameters to make up the whole IPv4 device path node.
2564 @param[in, out] Node Pointer to the IPv4 device path node.
2565 @param[in] Controller The controller handle.
2566 @param[in] LocalIp The local IPv4 address.
2567 @param[in] LocalPort The local port.
2568 @param[in] RemoteIp The remote IPv4 address.
2569 @param[in] RemotePort The remote port.
2570 @param[in] Protocol The protocol type in the IP header.
2571 @param[in] UseDefaultAddress Whether this instance is using default address or not.
2576 NetLibCreateIPv4DPathNode (
2577 IN OUT IPv4_DEVICE_PATH
*Node
,
2578 IN EFI_HANDLE Controller
,
2579 IN IP4_ADDR LocalIp
,
2580 IN UINT16 LocalPort
,
2581 IN IP4_ADDR RemoteIp
,
2582 IN UINT16 RemotePort
,
2584 IN BOOLEAN UseDefaultAddress
2587 Node
->Header
.Type
= MESSAGING_DEVICE_PATH
;
2588 Node
->Header
.SubType
= MSG_IPv4_DP
;
2589 SetDevicePathNodeLength (&Node
->Header
, sizeof (IPv4_DEVICE_PATH
));
2591 CopyMem (&Node
->LocalIpAddress
, &LocalIp
, sizeof (EFI_IPv4_ADDRESS
));
2592 CopyMem (&Node
->RemoteIpAddress
, &RemoteIp
, sizeof (EFI_IPv4_ADDRESS
));
2594 Node
->LocalPort
= LocalPort
;
2595 Node
->RemotePort
= RemotePort
;
2597 Node
->Protocol
= Protocol
;
2599 if (!UseDefaultAddress
) {
2600 Node
->StaticIpAddress
= TRUE
;
2602 Node
->StaticIpAddress
= NetLibDefaultAddressIsStatic (Controller
);
2606 // Set the Gateway IP address to default value 0:0:0:0.
2607 // Set the Subnet mask to default value 255:255:255:0.
2609 ZeroMem (&Node
->GatewayIpAddress
, sizeof (EFI_IPv4_ADDRESS
));
2610 SetMem (&Node
->SubnetMask
, sizeof (EFI_IPv4_ADDRESS
), 0xff);
2611 Node
->SubnetMask
.Addr
[3] = 0;
2615 Create an IPv6 device path node.
2617 The header type of IPv6 device path node is MESSAGING_DEVICE_PATH.
2618 The header subtype of IPv6 device path node is MSG_IPv6_DP.
2619 Get other info from parameters to make up the whole IPv6 device path node.
2621 @param[in, out] Node Pointer to the IPv6 device path node.
2622 @param[in] Controller The controller handle.
2623 @param[in] LocalIp The local IPv6 address.
2624 @param[in] LocalPort The local port.
2625 @param[in] RemoteIp The remote IPv6 address.
2626 @param[in] RemotePort The remote port.
2627 @param[in] Protocol The protocol type in the IP header.
2632 NetLibCreateIPv6DPathNode (
2633 IN OUT IPv6_DEVICE_PATH
*Node
,
2634 IN EFI_HANDLE Controller
,
2635 IN EFI_IPv6_ADDRESS
*LocalIp
,
2636 IN UINT16 LocalPort
,
2637 IN EFI_IPv6_ADDRESS
*RemoteIp
,
2638 IN UINT16 RemotePort
,
2642 Node
->Header
.Type
= MESSAGING_DEVICE_PATH
;
2643 Node
->Header
.SubType
= MSG_IPv6_DP
;
2644 SetDevicePathNodeLength (&Node
->Header
, sizeof (IPv6_DEVICE_PATH
));
2646 CopyMem (&Node
->LocalIpAddress
, LocalIp
, sizeof (EFI_IPv6_ADDRESS
));
2647 CopyMem (&Node
->RemoteIpAddress
, RemoteIp
, sizeof (EFI_IPv6_ADDRESS
));
2649 Node
->LocalPort
= LocalPort
;
2650 Node
->RemotePort
= RemotePort
;
2652 Node
->Protocol
= Protocol
;
2655 // Set default value to IPAddressOrigin, PrefixLength.
2656 // Set the Gateway IP address to unspecified address.
2658 Node
->IpAddressOrigin
= 0;
2659 Node
->PrefixLength
= IP6_PREFIX_LENGTH
;
2660 ZeroMem (&Node
->GatewayIpAddress
, sizeof (EFI_IPv6_ADDRESS
));
2664 Find the UNDI/SNP handle from controller and protocol GUID.
2666 For example, IP will open a MNP child to transmit/receive
2667 packets, when MNP is stopped, IP should also be stopped. IP
2668 needs to find its own private data which is related the IP's
2669 service binding instance that is install on UNDI/SNP handle.
2670 Now, the controller is either a MNP or ARP child handle. But
2671 IP opens these handle BY_DRIVER, use that info, we can get the
2674 @param[in] Controller Then protocol handle to check.
2675 @param[in] ProtocolGuid The protocol that is related with the handle.
2677 @return The UNDI/SNP handle or NULL for errors.
2682 NetLibGetNicHandle (
2683 IN EFI_HANDLE Controller
,
2684 IN EFI_GUID
*ProtocolGuid
2687 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY
*OpenBuffer
;
2693 Status
= gBS
->OpenProtocolInformation (
2700 if (EFI_ERROR (Status
)) {
2706 for (Index
= 0; Index
< OpenCount
; Index
++) {
2707 if ((OpenBuffer
[Index
].Attributes
& EFI_OPEN_PROTOCOL_BY_DRIVER
) != 0) {
2708 Handle
= OpenBuffer
[Index
].ControllerHandle
;
2713 gBS
->FreePool (OpenBuffer
);
2718 Convert one Null-terminated ASCII string (decimal dotted) to EFI_IPv4_ADDRESS.
2720 @param[in] String The pointer to the Ascii string.
2721 @param[out] Ip4Address The pointer to the converted IPv4 address.
2723 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2724 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2729 NetLibAsciiStrToIp4 (
2730 IN CONST CHAR8
*String
,
2731 OUT EFI_IPv4_ADDRESS
*Ip4Address
2734 RETURN_STATUS Status
;
2737 Status
= AsciiStrToIpv4Address (String
, &EndPointer
, Ip4Address
, NULL
);
2738 if (RETURN_ERROR (Status
) || (*EndPointer
!= '\0')) {
2739 return EFI_INVALID_PARAMETER
;
2747 Convert one Null-terminated ASCII string to EFI_IPv6_ADDRESS. The format of the
2748 string is defined in RFC 4291 - Text Representation of Addresses.
2750 @param[in] String The pointer to the Ascii string.
2751 @param[out] Ip6Address The pointer to the converted IPv6 address.
2753 @retval EFI_SUCCESS Convert to IPv6 address successfully.
2754 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
2759 NetLibAsciiStrToIp6 (
2760 IN CONST CHAR8
*String
,
2761 OUT EFI_IPv6_ADDRESS
*Ip6Address
2764 RETURN_STATUS Status
;
2767 Status
= AsciiStrToIpv6Address (String
, &EndPointer
, Ip6Address
, NULL
);
2768 if (RETURN_ERROR (Status
) || (*EndPointer
!= '\0')) {
2769 return EFI_INVALID_PARAMETER
;
2777 Convert one Null-terminated Unicode string (decimal dotted) to EFI_IPv4_ADDRESS.
2779 @param[in] String The pointer to the Ascii string.
2780 @param[out] Ip4Address The pointer to the converted IPv4 address.
2782 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2783 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2789 IN CONST CHAR16
*String
,
2790 OUT EFI_IPv4_ADDRESS
*Ip4Address
2793 RETURN_STATUS Status
;
2796 Status
= StrToIpv4Address (String
, &EndPointer
, Ip4Address
, NULL
);
2797 if (RETURN_ERROR (Status
) || (*EndPointer
!= L
'\0')) {
2798 return EFI_INVALID_PARAMETER
;
2806 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS. The format of
2807 the string is defined in RFC 4291 - Text Representation of Addresses.
2809 @param[in] String The pointer to the Ascii string.
2810 @param[out] Ip6Address The pointer to the converted IPv6 address.
2812 @retval EFI_SUCCESS Convert to IPv6 address successfully.
2813 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
2819 IN CONST CHAR16
*String
,
2820 OUT EFI_IPv6_ADDRESS
*Ip6Address
2823 RETURN_STATUS Status
;
2826 Status
= StrToIpv6Address (String
, &EndPointer
, Ip6Address
, NULL
);
2827 if (RETURN_ERROR (Status
) || (*EndPointer
!= L
'\0')) {
2828 return EFI_INVALID_PARAMETER
;
2835 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS and prefix length.
2836 The format of the string is defined in RFC 4291 - Text Representation of Addresses
2837 Prefixes: ipv6-address/prefix-length.
2839 @param[in] String The pointer to the Ascii string.
2840 @param[out] Ip6Address The pointer to the converted IPv6 address.
2841 @param[out] PrefixLength The pointer to the converted prefix length.
2843 @retval EFI_SUCCESS Convert to IPv6 address successfully.
2844 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
2849 NetLibStrToIp6andPrefix (
2850 IN CONST CHAR16
*String
,
2851 OUT EFI_IPv6_ADDRESS
*Ip6Address
,
2852 OUT UINT8
*PrefixLength
2855 RETURN_STATUS Status
;
2858 Status
= StrToIpv6Address (String
, &EndPointer
, Ip6Address
, PrefixLength
);
2859 if (RETURN_ERROR (Status
) || (*EndPointer
!= L
'\0')) {
2860 return EFI_INVALID_PARAMETER
;
2868 Convert one EFI_IPv6_ADDRESS to Null-terminated Unicode string.
2869 The text representation of address is defined in RFC 4291.
2871 @param[in] Ip6Address The pointer to the IPv6 address.
2872 @param[out] String The buffer to return the converted string.
2873 @param[in] StringSize The length in bytes of the input String.
2875 @retval EFI_SUCCESS Convert to string successfully.
2876 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
2877 @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small for the result. BufferSize has been
2878 updated with the size needed to complete the request.
2883 IN EFI_IPv6_ADDRESS
*Ip6Address
,
2890 UINTN LongestZerosStart
;
2891 UINTN LongestZerosLength
;
2892 UINTN CurrentZerosStart
;
2893 UINTN CurrentZerosLength
;
2894 CHAR16 Buffer
[sizeof"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"];
2897 if (Ip6Address
== NULL
|| String
== NULL
|| StringSize
== 0) {
2898 return EFI_INVALID_PARAMETER
;
2902 // Convert the UINT8 array to an UINT16 array for easy handling.
2904 ZeroMem (Ip6Addr
, sizeof (Ip6Addr
));
2905 for (Index
= 0; Index
< 16; Index
++) {
2906 Ip6Addr
[Index
/ 2] |= (Ip6Address
->Addr
[Index
] << ((1 - (Index
% 2)) << 3));
2910 // Find the longest zeros and mark it.
2912 CurrentZerosStart
= DEFAULT_ZERO_START
;
2913 CurrentZerosLength
= 0;
2914 LongestZerosStart
= DEFAULT_ZERO_START
;
2915 LongestZerosLength
= 0;
2916 for (Index
= 0; Index
< 8; Index
++) {
2917 if (Ip6Addr
[Index
] == 0) {
2918 if (CurrentZerosStart
== DEFAULT_ZERO_START
) {
2919 CurrentZerosStart
= Index
;
2920 CurrentZerosLength
= 1;
2922 CurrentZerosLength
++;
2925 if (CurrentZerosStart
!= DEFAULT_ZERO_START
) {
2926 if (CurrentZerosLength
> 2 && (LongestZerosStart
== (DEFAULT_ZERO_START
) || CurrentZerosLength
> LongestZerosLength
)) {
2927 LongestZerosStart
= CurrentZerosStart
;
2928 LongestZerosLength
= CurrentZerosLength
;
2930 CurrentZerosStart
= DEFAULT_ZERO_START
;
2931 CurrentZerosLength
= 0;
2936 if (CurrentZerosStart
!= DEFAULT_ZERO_START
&& CurrentZerosLength
> 2) {
2937 if (LongestZerosStart
== DEFAULT_ZERO_START
|| LongestZerosLength
< CurrentZerosLength
) {
2938 LongestZerosStart
= CurrentZerosStart
;
2939 LongestZerosLength
= CurrentZerosLength
;
2944 for (Index
= 0; Index
< 8; Index
++) {
2945 if (LongestZerosStart
!= DEFAULT_ZERO_START
&& Index
>= LongestZerosStart
&& Index
< LongestZerosStart
+ LongestZerosLength
) {
2946 if (Index
== LongestZerosStart
) {
2954 Ptr
+= UnicodeSPrint(Ptr
, 10, L
"%x", Ip6Addr
[Index
]);
2957 if (LongestZerosStart
!= DEFAULT_ZERO_START
&& LongestZerosStart
+ LongestZerosLength
== 8) {
2962 if ((UINTN
)Ptr
- (UINTN
)Buffer
> StringSize
) {
2963 return EFI_BUFFER_TOO_SMALL
;
2966 StrCpyS (String
, StringSize
/ sizeof (CHAR16
), Buffer
);
2972 This function obtains the system guid from the smbios table.
2974 @param[out] SystemGuid The pointer of the returned system guid.
2976 @retval EFI_SUCCESS Successfully obtained the system guid.
2977 @retval EFI_NOT_FOUND Did not find the SMBIOS table.
2982 NetLibGetSystemGuid (
2983 OUT EFI_GUID
*SystemGuid
2987 SMBIOS_TABLE_ENTRY_POINT
*SmbiosTable
;
2988 SMBIOS_TABLE_3_0_ENTRY_POINT
*Smbios30Table
;
2989 SMBIOS_STRUCTURE_POINTER Smbios
;
2990 SMBIOS_STRUCTURE_POINTER SmbiosEnd
;
2994 Status
= EfiGetSystemConfigurationTable (&gEfiSmbios3TableGuid
, (VOID
**) &Smbios30Table
);
2995 if (!(EFI_ERROR (Status
) || Smbios30Table
== NULL
)) {
2996 Smbios
.Hdr
= (SMBIOS_STRUCTURE
*) (UINTN
) Smbios30Table
->TableAddress
;
2997 SmbiosEnd
.Raw
= (UINT8
*) (UINTN
) (Smbios30Table
->TableAddress
+ Smbios30Table
->TableMaximumSize
);
2999 Status
= EfiGetSystemConfigurationTable (&gEfiSmbiosTableGuid
, (VOID
**) &SmbiosTable
);
3000 if (EFI_ERROR (Status
) || SmbiosTable
== NULL
) {
3001 return EFI_NOT_FOUND
;
3003 Smbios
.Hdr
= (SMBIOS_STRUCTURE
*) (UINTN
) SmbiosTable
->TableAddress
;
3004 SmbiosEnd
.Raw
= (UINT8
*) ((UINTN
) SmbiosTable
->TableAddress
+ SmbiosTable
->TableLength
);
3008 if (Smbios
.Hdr
->Type
== 1) {
3009 if (Smbios
.Hdr
->Length
< 0x19) {
3011 // Older version did not support UUID.
3013 return EFI_NOT_FOUND
;
3017 // SMBIOS tables are byte packed so we need to do a byte copy to
3018 // prevend alignment faults on Itanium-based platform.
3020 CopyMem (SystemGuid
, &Smbios
.Type1
->Uuid
, sizeof (EFI_GUID
));
3025 // Go to the next SMBIOS structure. Each SMBIOS structure may include 2 parts:
3026 // 1. Formatted section; 2. Unformatted string section. So, 2 steps are needed
3027 // to skip one SMBIOS structure.
3031 // Step 1: Skip over formatted section.
3033 String
= (CHAR8
*) (Smbios
.Raw
+ Smbios
.Hdr
->Length
);
3036 // Step 2: Skip over unformated string section.
3040 // Each string is terminated with a NULL(00h) BYTE and the sets of strings
3041 // is terminated with an additional NULL(00h) BYTE.
3043 for ( ; *String
!= 0; String
++) {
3046 if (*(UINT8
*)++String
== 0) {
3048 // Pointer to the next SMBIOS structure.
3050 Smbios
.Raw
= (UINT8
*)++String
;
3054 } while (Smbios
.Raw
< SmbiosEnd
.Raw
);
3055 return EFI_NOT_FOUND
;
3059 Create Dns QName according the queried domain name.
3060 QName is a domain name represented as a sequence of labels,
3061 where each label consists of a length octet followed by that
3062 number of octets. The QName terminates with the zero
3063 length octet for the null label of the root. Caller should
3064 take responsibility to free the buffer in returned pointer.
3066 @param DomainName The pointer to the queried domain name string.
3068 @retval NULL Failed to fill QName.
3069 @return QName filled successfully.
3074 NetLibCreateDnsQName (
3075 IN CHAR16
*DomainName
3079 UINTN QueryNameSize
;
3091 // One byte for first label length, one byte for terminated length zero.
3093 QueryNameSize
= StrLen (DomainName
) + 2;
3095 if (QueryNameSize
> DNS_MAX_NAME_SIZE
) {
3099 QueryName
= AllocateZeroPool (QueryNameSize
);
3100 if (QueryName
== NULL
) {
3107 for (Index
= 0; DomainName
[Index
] != 0; Index
++) {
3108 *Tail
= (CHAR8
) DomainName
[Index
];
3110 *Header
= (CHAR8
) Len
;
3119 *Header
= (CHAR8
) Len
;