4 Copyright (c) 2005 - 2018, 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.
201 If Packet is NULL, then ASSERT().
203 @param[in] Packet The Syslog packet
204 @param[in] Length The length of the packet
206 @retval EFI_DEVICE_ERROR Failed to locate a usable SNP protocol
207 @retval EFI_TIMEOUT Timeout happened to send the packet.
208 @retval EFI_SUCCESS Packet is sent.
217 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
220 EFI_EVENT TimeoutEvent
;
223 ASSERT (Packet
!= NULL
);
225 Snp
= SyslogLocateSnp ();
228 return EFI_DEVICE_ERROR
;
231 Ether
= (ETHER_HEAD
*) Packet
;
232 CopyMem (Ether
->SrcMac
, Snp
->Mode
->CurrentAddress
.Addr
, NET_ETHER_ADDR_LEN
);
235 // Start the timeout event.
237 Status
= gBS
->CreateEvent (
245 if (EFI_ERROR (Status
)) {
249 Status
= gBS
->SetTimer (TimeoutEvent
, TimerRelative
, NET_SYSLOG_TX_TIMEOUT
);
251 if (EFI_ERROR (Status
)) {
257 // Transmit the packet through SNP.
259 Status
= Snp
->Transmit (Snp
, 0, Length
, Packet
, NULL
, NULL
, NULL
);
261 if ((Status
!= EFI_SUCCESS
) && (Status
!= EFI_NOT_READY
)) {
262 Status
= EFI_DEVICE_ERROR
;
267 // If Status is EFI_SUCCESS, the packet is put in the transmit queue.
268 // if Status is EFI_NOT_READY, the transmit engine of the network
269 // interface is busy. Both need to sync SNP.
275 // Get the recycled transmit buffer status.
277 Snp
->GetStatus (Snp
, NULL
, (VOID
**) &TxBuf
);
279 if (!EFI_ERROR (gBS
->CheckEvent (TimeoutEvent
))) {
280 Status
= EFI_TIMEOUT
;
284 } while (TxBuf
== NULL
);
286 if ((Status
== EFI_SUCCESS
) || (Status
== EFI_TIMEOUT
)) {
291 // Status is EFI_NOT_READY. Restart the timer event and
292 // call Snp->Transmit again.
294 gBS
->SetTimer (TimeoutEvent
, TimerRelative
, NET_SYSLOG_TX_TIMEOUT
);
297 gBS
->SetTimer (TimeoutEvent
, TimerCancel
, 0);
300 gBS
->CloseEvent (TimeoutEvent
);
305 Build a syslog packet, including the Ethernet/Ip/Udp headers
308 @param[in] Level Syslog severity level
309 @param[in] Module The module that generates the log
310 @param[in] File The file that contains the current log
311 @param[in] Line The line of code in the File that contains the current log
312 @param[in] Message The log message
313 @param[in] BufLen The lenght of the Buf
314 @param[out] Buf The buffer to put the packet data
316 @return The length of the syslog packet built, 0 represents no packet is built.
333 EFI_UDP_HEADER
*Udp4
;
339 // Fill in the Ethernet header. Leave alone the source MAC.
340 // SyslogSendPacket will fill in the address for us.
342 Ether
= (ETHER_HEAD
*) Buf
;
343 CopyMem (Ether
->DstMac
, mSyslogDstMac
, NET_ETHER_ADDR_LEN
);
344 ZeroMem (Ether
->SrcMac
, NET_ETHER_ADDR_LEN
);
346 Ether
->EtherType
= HTONS (0x0800); // IPv4 protocol
348 Buf
+= sizeof (ETHER_HEAD
);
349 BufLen
-= sizeof (ETHER_HEAD
);
352 // Fill in the IP header
354 Ip4
= (IP4_HEAD
*) Buf
;
359 Ip4
->Id
= (UINT16
) mSyslogPacketSeq
;
362 Ip4
->Protocol
= 0x11;
364 Ip4
->Src
= mSyslogSrcIp
;
365 Ip4
->Dst
= mSyslogDstIp
;
367 Buf
+= sizeof (IP4_HEAD
);
368 BufLen
-= sizeof (IP4_HEAD
);
371 // Fill in the UDP header, Udp checksum is optional. Leave it zero.
373 Udp4
= (EFI_UDP_HEADER
*) Buf
;
374 Udp4
->SrcPort
= HTONS (514);
375 Udp4
->DstPort
= HTONS (514);
379 Buf
+= sizeof (EFI_UDP_HEADER
);
380 BufLen
-= sizeof (EFI_UDP_HEADER
);
383 // Build the syslog message body with <PRI> Timestamp machine module Message
385 Pri
= ((NET_SYSLOG_FACILITY
& 31) << 3) | (Level
& 7);
386 Status
= gRT
->GetTime (&Time
, NULL
);
387 if (EFI_ERROR (Status
)) {
392 // Use %a to format the ASCII strings, %s to format UNICODE strings
395 Len
+= (UINT32
) AsciiSPrint (
398 "<%d> %a %d %d:%d:%d ",
400 mMonthName
[Time
.Month
-1],
407 Len
+= (UINT32
) AsciiSPrint (
410 "Tiano %a: %a (Line: %d File: %a)",
419 // OK, patch the IP length/checksum and UDP length fields.
421 Len
+= sizeof (EFI_UDP_HEADER
);
422 Udp4
->Length
= HTONS ((UINT16
) Len
);
424 Len
+= sizeof (IP4_HEAD
);
425 Ip4
->TotalLen
= HTONS ((UINT16
) Len
);
426 Ip4
->Checksum
= (UINT16
) (~NetblockChecksum ((UINT8
*) Ip4
, sizeof (IP4_HEAD
)));
428 return Len
+ sizeof (ETHER_HEAD
);
432 Allocate a buffer, then format the message to it. This is a
433 help function for the NET_DEBUG_XXX macros. The PrintArg of
434 these macros treats the variable length print parameters as a
435 single parameter, and pass it to the NetDebugASPrint. For
436 example, NET_DEBUG_TRACE ("Tcp", ("State transit to %a\n", Name))
440 NETDEBUG_LEVEL_TRACE,
444 NetDebugASPrint ("State transit to %a\n", Name)
447 If Format is NULL, then ASSERT().
449 @param Format The ASCII format string.
450 @param ... The variable length parameter whose format is determined
451 by the Format string.
453 @return The buffer containing the formatted message,
454 or NULL if failed to allocate memory.
467 ASSERT (Format
!= NULL
);
469 Buf
= (CHAR8
*) AllocatePool (NET_DEBUG_MSG_LEN
);
475 VA_START (Marker
, Format
);
476 AsciiVSPrint (Buf
, NET_DEBUG_MSG_LEN
, Format
, Marker
);
483 Builds an UDP4 syslog packet and send it using SNP.
485 This function will locate a instance of SNP then send the message through it.
486 Because it isn't open the SNP BY_DRIVER, apply caution when using it.
488 @param Level The severity level of the message.
489 @param Module The Moudle that generates the log.
490 @param File The file that contains the log.
491 @param Line The exact line that contains the log.
492 @param Message The user message to log.
494 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
495 @retval EFI_OUT_OF_RESOURCES Failed to allocate memory for the packet.
496 @retval EFI_DEVICE_ERROR Device error occurs.
497 @retval EFI_SUCCESS The log is discard because that it is more verbose
498 than the mNetDebugLevelMax. Or, it has been sent out.
515 // Check whether the message should be sent out
517 if (Message
== NULL
|| File
== NULL
|| Module
== NULL
) {
518 return EFI_INVALID_PARAMETER
;
521 if (Level
> mNetDebugLevelMax
) {
522 Status
= EFI_SUCCESS
;
527 // Allocate a maxium of 1024 bytes, the caller should ensure
528 // that the message plus the ethernet/ip/udp header is shorter
531 Packet
= (CHAR8
*) AllocatePool (NET_SYSLOG_PACKET_LEN
);
533 if (Packet
== NULL
) {
534 Status
= EFI_OUT_OF_RESOURCES
;
539 // Build the message: Ethernet header + IP header + Udp Header + user data
541 Len
= SyslogBuildPacket (
547 NET_SYSLOG_PACKET_LEN
,
551 Status
= EFI_DEVICE_ERROR
;
554 Status
= SyslogSendPacket (Packet
, Len
);
564 Return the length of the mask.
566 Return the length of the mask, the correct value is from 0 to 32.
567 If the mask is invalid, return the invalid length 33, which is IP4_MASK_NUM.
568 NetMask is in the host byte order.
570 @param[in] NetMask The netmask to get the length from.
572 @return The length of the netmask, IP4_MASK_NUM if the mask is invalid.
583 for (Index
= 0; Index
<= IP4_MASK_MAX
; Index
++) {
584 if (NetMask
== gIp4AllMasks
[Index
]) {
595 Return the class of the IP address, such as class A, B, C.
596 Addr is in host byte order.
599 Classful addressing (IP class A/B/C) has been deprecated according to RFC4632.
600 Caller of this function could only check the returned value against
601 IP4_ADDR_CLASSD (multicast) or IP4_ADDR_CLASSE (reserved) now.
603 The address of class A starts with 0.
604 If the address belong to class A, return IP4_ADDR_CLASSA.
605 The address of class B starts with 10.
606 If the address belong to class B, return IP4_ADDR_CLASSB.
607 The address of class C starts with 110.
608 If the address belong to class C, return IP4_ADDR_CLASSC.
609 The address of class D starts with 1110.
610 If the address belong to class D, return IP4_ADDR_CLASSD.
611 The address of class E starts with 1111.
612 If the address belong to class E, return IP4_ADDR_CLASSE.
615 @param[in] Addr The address to get the class from.
617 @return IP address class, such as IP4_ADDR_CLASSA.
628 ByteOne
= (UINT8
) (Addr
>> 24);
630 if ((ByteOne
& 0x80) == 0) {
631 return IP4_ADDR_CLASSA
;
633 } else if ((ByteOne
& 0xC0) == 0x80) {
634 return IP4_ADDR_CLASSB
;
636 } else if ((ByteOne
& 0xE0) == 0xC0) {
637 return IP4_ADDR_CLASSC
;
639 } else if ((ByteOne
& 0xF0) == 0xE0) {
640 return IP4_ADDR_CLASSD
;
643 return IP4_ADDR_CLASSE
;
650 Check whether the IP is a valid unicast address according to
653 ASSERT if NetMask is zero.
655 If all bits of the host address of IP are 0 or 1, IP is also not a valid unicast address,
656 except when the originator is one of the endpoints of a point-to-point link with a 31-bit
659 @param[in] Ip The IP to check against.
660 @param[in] NetMask The mask of the IP.
662 @return TRUE if IP is a valid unicast address on the network, otherwise FALSE.
672 ASSERT (NetMask
!= 0);
674 if (Ip
== 0 || IP4_IS_LOCAL_BROADCAST (Ip
)) {
678 if (NetGetMaskLength (NetMask
) != 31) {
679 if (((Ip
&~NetMask
) == ~NetMask
) || ((Ip
&~NetMask
) == 0)) {
690 Check whether the incoming IPv6 address is a valid unicast address.
692 ASSERT if Ip6 is NULL.
694 If the address is a multicast address has binary 0xFF at the start, it is not
695 a valid unicast address. If the address is unspecified ::, it is not a valid
696 unicast address to be assigned to any node. If the address is loopback address
697 ::1, it is also not a valid unicast address to be assigned to any physical
700 @param[in] Ip6 The IPv6 address to check against.
702 @return TRUE if Ip6 is a valid unicast address on the network, otherwise FALSE.
707 NetIp6IsValidUnicast (
708 IN EFI_IPv6_ADDRESS
*Ip6
714 ASSERT (Ip6
!= NULL
);
716 if (Ip6
->Addr
[0] == 0xFF) {
720 for (Index
= 0; Index
< 15; Index
++) {
721 if (Ip6
->Addr
[Index
] != 0) {
726 Byte
= Ip6
->Addr
[Index
];
728 if (Byte
== 0x0 || Byte
== 0x1) {
736 Check whether the incoming Ipv6 address is the unspecified address or not.
738 ASSERT if Ip6 is NULL.
740 @param[in] Ip6 - Ip6 address, in network order.
742 @retval TRUE - Yes, unspecified
748 NetIp6IsUnspecifiedAddr (
749 IN EFI_IPv6_ADDRESS
*Ip6
754 ASSERT (Ip6
!= NULL
);
756 for (Index
= 0; Index
< 16; Index
++) {
757 if (Ip6
->Addr
[Index
] != 0) {
766 Check whether the incoming Ipv6 address is a link-local address.
768 ASSERT if Ip6 is NULL.
770 @param[in] Ip6 - Ip6 address, in network order.
772 @retval TRUE - Yes, link-local address
778 NetIp6IsLinkLocalAddr (
779 IN EFI_IPv6_ADDRESS
*Ip6
784 ASSERT (Ip6
!= NULL
);
786 if (Ip6
->Addr
[0] != 0xFE) {
790 if (Ip6
->Addr
[1] != 0x80) {
794 for (Index
= 2; Index
< 8; Index
++) {
795 if (Ip6
->Addr
[Index
] != 0) {
804 Check whether the Ipv6 address1 and address2 are on the connected network.
806 ASSERT if Ip1 or Ip2 is NULL.
807 ASSERT if PrefixLength exceeds or equals to IP6_PREFIX_MAX.
809 @param[in] Ip1 - Ip6 address1, in network order.
810 @param[in] Ip2 - Ip6 address2, in network order.
811 @param[in] PrefixLength - The prefix length of the checking net.
813 @retval TRUE - Yes, connected.
820 EFI_IPv6_ADDRESS
*Ip1
,
821 EFI_IPv6_ADDRESS
*Ip2
,
829 ASSERT ((Ip1
!= NULL
) && (Ip2
!= NULL
) && (PrefixLength
< IP6_PREFIX_MAX
));
831 if (PrefixLength
== 0) {
835 Byte
= (UINT8
) (PrefixLength
/ 8);
836 Bit
= (UINT8
) (PrefixLength
% 8);
838 if (CompareMem (Ip1
, Ip2
, Byte
) != 0) {
843 Mask
= (UINT8
) (0xFF << (8 - Bit
));
849 if ((Ip1
->Addr
[Byte
] & Mask
) != (Ip2
->Addr
[Byte
] & Mask
)) {
859 Switches the endianess of an IPv6 address
861 ASSERT if Ip6 is NULL.
863 This function swaps the bytes in a 128-bit IPv6 address to switch the value
864 from little endian to big endian or vice versa. The byte swapped value is
867 @param Ip6 Points to an IPv6 address
869 @return The byte swapped IPv6 address.
875 EFI_IPv6_ADDRESS
*Ip6
881 ASSERT (Ip6
!= NULL
);
883 CopyMem (&High
, Ip6
, sizeof (UINT64
));
884 CopyMem (&Low
, &Ip6
->Addr
[8], sizeof (UINT64
));
886 High
= SwapBytes64 (High
);
887 Low
= SwapBytes64 (Low
);
889 CopyMem (Ip6
, &Low
, sizeof (UINT64
));
890 CopyMem (&Ip6
->Addr
[8], &High
, sizeof (UINT64
));
896 Initialize a random seed using current time and monotonic count.
898 Get current time and monotonic count first. Then initialize a random seed
899 based on some basic mathematics operation on the hour, day, minute, second,
900 nanosecond and year of the current time and the monotonic count value.
902 @return The random seed initialized with current time.
913 UINT64 MonotonicCount
;
915 gRT
->GetTime (&Time
, NULL
);
916 Seed
= (Time
.Hour
<< 24 | Time
.Day
<< 16 | Time
.Minute
<< 8 | Time
.Second
);
917 Seed
^= Time
.Nanosecond
;
918 Seed
^= Time
.Year
<< 7;
920 gBS
->GetNextMonotonicCount (&MonotonicCount
);
921 Seed
+= (UINT32
) MonotonicCount
;
928 Extract a UINT32 from a byte stream.
930 ASSERT if Buf is NULL.
932 Copy a UINT32 from a byte stream, then converts it from Network
933 byte order to host byte order. Use this function to avoid alignment error.
935 @param[in] Buf The buffer to extract the UINT32.
937 @return The UINT32 extracted.
948 ASSERT (Buf
!= NULL
);
950 CopyMem (&Value
, Buf
, sizeof (UINT32
));
951 return NTOHL (Value
);
956 Put a UINT32 to the byte stream in network byte order.
958 ASSERT if Buf is NULL.
960 Converts a UINT32 from host byte order to network byte order. Then copy it to the
963 @param[in, out] Buf The buffer to put the UINT32.
964 @param[in] Data The data to be converted and put into the byte stream.
974 ASSERT (Buf
!= NULL
);
977 CopyMem (Buf
, &Data
, sizeof (UINT32
));
982 Remove the first node entry on the list, and return the removed node entry.
984 Removes the first node Entry from a doubly linked list. It is up to the caller of
985 this function to release the memory used by the first node if that is required. On
986 exit, the removed node is returned.
988 If Head is NULL, then ASSERT().
989 If Head was not initialized, then ASSERT().
990 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
991 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
994 @param[in, out] Head The list header.
996 @return The first node entry that is removed from the list, NULL if the list is empty.
1002 IN OUT LIST_ENTRY
*Head
1007 ASSERT (Head
!= NULL
);
1009 if (IsListEmpty (Head
)) {
1013 First
= Head
->ForwardLink
;
1014 Head
->ForwardLink
= First
->ForwardLink
;
1015 First
->ForwardLink
->BackLink
= Head
;
1018 First
->ForwardLink
= (LIST_ENTRY
*) NULL
;
1019 First
->BackLink
= (LIST_ENTRY
*) NULL
;
1027 Remove the last node entry on the list and and return the removed node entry.
1029 Removes the last node entry from a doubly linked list. It is up to the caller of
1030 this function to release the memory used by the first node if that is required. On
1031 exit, the removed node is returned.
1033 If Head is NULL, then ASSERT().
1034 If Head was not initialized, then ASSERT().
1035 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
1036 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
1039 @param[in, out] Head The list head.
1041 @return The last node entry that is removed from the list, NULL if the list is empty.
1047 IN OUT LIST_ENTRY
*Head
1052 ASSERT (Head
!= NULL
);
1054 if (IsListEmpty (Head
)) {
1058 Last
= Head
->BackLink
;
1059 Head
->BackLink
= Last
->BackLink
;
1060 Last
->BackLink
->ForwardLink
= Head
;
1063 Last
->ForwardLink
= (LIST_ENTRY
*) NULL
;
1064 Last
->BackLink
= (LIST_ENTRY
*) NULL
;
1072 Insert a new node entry after a designated node entry of a doubly linked list.
1074 ASSERT if PrevEntry or NewEntry is NULL.
1076 Inserts a new node entry donated by NewEntry after the node entry donated by PrevEntry
1077 of the doubly linked list.
1079 @param[in, out] PrevEntry The previous entry to insert after.
1080 @param[in, out] NewEntry The new entry to insert.
1085 NetListInsertAfter (
1086 IN OUT LIST_ENTRY
*PrevEntry
,
1087 IN OUT LIST_ENTRY
*NewEntry
1090 ASSERT (PrevEntry
!= NULL
&& NewEntry
!= NULL
);
1092 NewEntry
->BackLink
= PrevEntry
;
1093 NewEntry
->ForwardLink
= PrevEntry
->ForwardLink
;
1094 PrevEntry
->ForwardLink
->BackLink
= NewEntry
;
1095 PrevEntry
->ForwardLink
= NewEntry
;
1100 Insert a new node entry before a designated node entry of a doubly linked list.
1102 ASSERT if PostEntry or NewEntry is NULL.
1104 Inserts a new node entry donated by NewEntry after the node entry donated by PostEntry
1105 of the doubly linked list.
1107 @param[in, out] PostEntry The entry to insert before.
1108 @param[in, out] NewEntry The new entry to insert.
1113 NetListInsertBefore (
1114 IN OUT LIST_ENTRY
*PostEntry
,
1115 IN OUT LIST_ENTRY
*NewEntry
1118 ASSERT (PostEntry
!= NULL
&& NewEntry
!= NULL
);
1120 NewEntry
->ForwardLink
= PostEntry
;
1121 NewEntry
->BackLink
= PostEntry
->BackLink
;
1122 PostEntry
->BackLink
->ForwardLink
= NewEntry
;
1123 PostEntry
->BackLink
= NewEntry
;
1127 Safe destroy nodes in a linked list, and return the length of the list after all possible operations finished.
1129 Destroy network child instance list by list traversals is not safe due to graph dependencies between nodes.
1130 This function performs a safe traversal to destroy these nodes by checking to see if the node being destroyed
1131 has been removed from the list or not.
1132 If it has been removed, then restart the traversal from the head.
1133 If it hasn't been removed, then continue with the next node directly.
1134 This function will end the iterate and return the CallBack's last return value if error happens,
1135 or retrun EFI_SUCCESS if 2 complete passes are made with no changes in the number of children in the list.
1137 @param[in] List The head of the list.
1138 @param[in] CallBack Pointer to the callback function to destroy one node in the list.
1139 @param[in] Context Pointer to the callback function's context: corresponds to the
1140 parameter Context in NET_DESTROY_LINK_LIST_CALLBACK.
1141 @param[out] ListLength The length of the link list if the function returns successfully.
1143 @retval EFI_SUCCESS Two complete passes are made with no changes in the number of children.
1144 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
1145 @retval Others Return the CallBack's last return value.
1150 NetDestroyLinkList (
1151 IN LIST_ENTRY
*List
,
1152 IN NET_DESTROY_LINK_LIST_CALLBACK CallBack
,
1153 IN VOID
*Context
, OPTIONAL
1154 OUT UINTN
*ListLength OPTIONAL
1157 UINTN PreviousLength
;
1163 if (List
== NULL
|| CallBack
== NULL
) {
1164 return EFI_INVALID_PARAMETER
;
1169 PreviousLength
= Length
;
1170 Entry
= GetFirstNode (List
);
1171 while (!IsNull (List
, Entry
)) {
1172 Status
= CallBack (Entry
, Context
);
1173 if (EFI_ERROR (Status
)) {
1177 // Walk through the list to see whether the Entry has been removed or not.
1178 // If the Entry still exists, just try to destroy the next one.
1179 // If not, go back to the start point to iterate the list again.
1181 for (Ptr
= List
->ForwardLink
; Ptr
!= List
; Ptr
= Ptr
->ForwardLink
) {
1187 Entry
= GetNextNode (List
, Entry
);
1189 Entry
= GetFirstNode (List
);
1192 for (Length
= 0, Ptr
= List
->ForwardLink
; Ptr
!= List
; Length
++, Ptr
= Ptr
->ForwardLink
);
1193 } while (Length
!= PreviousLength
);
1195 if (ListLength
!= NULL
) {
1196 *ListLength
= Length
;
1202 This function checks the input Handle to see if it's one of these handles in ChildHandleBuffer.
1204 @param[in] Handle Handle to be checked.
1205 @param[in] NumberOfChildren Number of Handles in ChildHandleBuffer.
1206 @param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
1207 if NumberOfChildren is 0.
1209 @retval TRUE Found the input Handle in ChildHandleBuffer.
1210 @retval FALSE Can't find the input Handle in ChildHandleBuffer.
1215 NetIsInHandleBuffer (
1216 IN EFI_HANDLE Handle
,
1217 IN UINTN NumberOfChildren
,
1218 IN EFI_HANDLE
*ChildHandleBuffer OPTIONAL
1223 if (NumberOfChildren
== 0 || ChildHandleBuffer
== NULL
) {
1227 for (Index
= 0; Index
< NumberOfChildren
; Index
++) {
1228 if (Handle
== ChildHandleBuffer
[Index
]) {
1238 Initialize the netmap. Netmap is a reposity to keep the <Key, Value> pairs.
1240 Initialize the forward and backward links of two head nodes donated by Map->Used
1241 and Map->Recycled of two doubly linked lists.
1242 Initializes the count of the <Key, Value> pairs in the netmap to zero.
1244 If Map is NULL, then ASSERT().
1245 If the address of Map->Used is NULL, then ASSERT().
1246 If the address of Map->Recycled is NULl, then ASSERT().
1248 @param[in, out] Map The netmap to initialize.
1257 ASSERT (Map
!= NULL
);
1259 InitializeListHead (&Map
->Used
);
1260 InitializeListHead (&Map
->Recycled
);
1266 To clean up the netmap, that is, release allocated memories.
1268 Removes all nodes of the Used doubly linked list and free memory of all related netmap items.
1269 Removes all nodes of the Recycled doubly linked list and free memory of all related netmap items.
1270 The number of the <Key, Value> pairs in the netmap is set to be zero.
1272 If Map is NULL, then ASSERT().
1274 @param[in, out] Map The netmap to clean up.
1287 ASSERT (Map
!= NULL
);
1289 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, &Map
->Used
) {
1290 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1292 RemoveEntryList (&Item
->Link
);
1295 gBS
->FreePool (Item
);
1298 ASSERT ((Map
->Count
== 0) && IsListEmpty (&Map
->Used
));
1300 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, &Map
->Recycled
) {
1301 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1303 RemoveEntryList (&Item
->Link
);
1304 gBS
->FreePool (Item
);
1307 ASSERT (IsListEmpty (&Map
->Recycled
));
1312 Test whether the netmap is empty and return true if it is.
1314 If the number of the <Key, Value> pairs in the netmap is zero, return TRUE.
1316 If Map is NULL, then ASSERT().
1318 @param[in] Map The net map to test.
1320 @return TRUE if the netmap is empty, otherwise FALSE.
1329 ASSERT (Map
!= NULL
);
1330 return (BOOLEAN
) (Map
->Count
== 0);
1335 Return the number of the <Key, Value> pairs in the netmap.
1337 If Map is NULL, then ASSERT().
1339 @param[in] Map The netmap to get the entry number.
1341 @return The entry number in the netmap.
1350 ASSERT (Map
!= NULL
);
1356 Return one allocated item.
1358 If the Recycled doubly linked list of the netmap is empty, it will try to allocate
1359 a batch of items if there are enough resources and add corresponding nodes to the begining
1360 of the Recycled doubly linked list of the netmap. Otherwise, it will directly remove
1361 the fist node entry of the Recycled doubly linked list and return the corresponding item.
1363 If Map is NULL, then ASSERT().
1365 @param[in, out] Map The netmap to allocate item for.
1367 @return The allocated item. If NULL, the
1368 allocation failed due to resource limit.
1380 ASSERT (Map
!= NULL
);
1382 Head
= &Map
->Recycled
;
1384 if (IsListEmpty (Head
)) {
1385 for (Index
= 0; Index
< NET_MAP_INCREAMENT
; Index
++) {
1386 Item
= AllocatePool (sizeof (NET_MAP_ITEM
));
1396 InsertHeadList (Head
, &Item
->Link
);
1400 Item
= NET_LIST_HEAD (Head
, NET_MAP_ITEM
, Link
);
1401 NetListRemoveHead (Head
);
1408 Allocate an item to save the <Key, Value> pair to the head of the netmap.
1410 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1411 to the beginning of the Used doubly linked list. The number of the <Key, Value>
1412 pairs in the netmap increase by 1.
1414 If Map is NULL, then ASSERT().
1415 If Key is NULL, then ASSERT().
1417 @param[in, out] Map The netmap to insert into.
1418 @param[in] Key The user's key.
1419 @param[in] Value The user's value for the key.
1421 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1422 @retval EFI_SUCCESS The item is inserted to the head.
1428 IN OUT NET_MAP
*Map
,
1430 IN VOID
*Value OPTIONAL
1435 ASSERT (Map
!= NULL
&& Key
!= NULL
);
1437 Item
= NetMapAllocItem (Map
);
1440 return EFI_OUT_OF_RESOURCES
;
1444 Item
->Value
= Value
;
1445 InsertHeadList (&Map
->Used
, &Item
->Link
);
1453 Allocate an item to save the <Key, Value> pair to the tail of the netmap.
1455 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1456 to the tail of the Used doubly linked list. The number of the <Key, Value>
1457 pairs in the netmap increase by 1.
1459 If Map is NULL, then ASSERT().
1460 If Key is NULL, then ASSERT().
1462 @param[in, out] Map The netmap to insert into.
1463 @param[in] Key The user's key.
1464 @param[in] Value The user's value for the key.
1466 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1467 @retval EFI_SUCCESS The item is inserted to the tail.
1473 IN OUT NET_MAP
*Map
,
1475 IN VOID
*Value OPTIONAL
1480 ASSERT (Map
!= NULL
&& Key
!= NULL
);
1482 Item
= NetMapAllocItem (Map
);
1485 return EFI_OUT_OF_RESOURCES
;
1489 Item
->Value
= Value
;
1490 InsertTailList (&Map
->Used
, &Item
->Link
);
1499 Check whether the item is in the Map and return TRUE if it is.
1501 If Map is NULL, then ASSERT().
1502 If Item is NULL, then ASSERT().
1504 @param[in] Map The netmap to search within.
1505 @param[in] Item The item to search.
1507 @return TRUE if the item is in the netmap, otherwise FALSE.
1513 IN NET_MAP_ITEM
*Item
1516 LIST_ENTRY
*ListEntry
;
1518 ASSERT (Map
!= NULL
&& Item
!= NULL
);
1520 NET_LIST_FOR_EACH (ListEntry
, &Map
->Used
) {
1521 if (ListEntry
== &Item
->Link
) {
1531 Find the key in the netmap and returns the point to the item contains the Key.
1533 Iterate the Used doubly linked list of the netmap to get every item. Compare the key of every
1534 item with the key to search. It returns the point to the item contains the Key if found.
1536 If Map is NULL, then ASSERT().
1537 If Key is NULL, then ASSERT().
1539 @param[in] Map The netmap to search within.
1540 @param[in] Key The key to search.
1542 @return The point to the item contains the Key, or NULL if Key isn't in the map.
1555 ASSERT (Map
!= NULL
&& Key
!= NULL
);
1557 NET_LIST_FOR_EACH (Entry
, &Map
->Used
) {
1558 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1560 if (Item
->Key
== Key
) {
1570 Remove the node entry of the item from the netmap and return the key of the removed item.
1572 Remove the node entry of the item from the Used doubly linked list of the netmap.
1573 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1574 entry of the item to the Recycled doubly linked list of the netmap. If Value is not NULL,
1575 Value will point to the value of the item. It returns the key of the removed item.
1577 If Map is NULL, then ASSERT().
1578 If Item is NULL, then ASSERT().
1579 if item in not in the netmap, then ASSERT().
1581 @param[in, out] Map The netmap to remove the item from.
1582 @param[in, out] Item The item to remove.
1583 @param[out] Value The variable to receive the value if not NULL.
1585 @return The key of the removed item.
1591 IN OUT NET_MAP
*Map
,
1592 IN OUT NET_MAP_ITEM
*Item
,
1593 OUT VOID
**Value OPTIONAL
1596 ASSERT ((Map
!= NULL
) && (Item
!= NULL
));
1597 ASSERT (NetItemInMap (Map
, Item
));
1599 RemoveEntryList (&Item
->Link
);
1601 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1603 if (Value
!= NULL
) {
1604 *Value
= Item
->Value
;
1612 Remove the first node entry on the netmap and return the key of the removed item.
1614 Remove the first node entry from the Used doubly linked list of the netmap.
1615 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1616 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1617 parameter Value will point to the value of the item. It returns the key of the removed item.
1619 If Map is NULL, then ASSERT().
1620 If the Used doubly linked list is empty, then ASSERT().
1622 @param[in, out] Map The netmap to remove the head from.
1623 @param[out] Value The variable to receive the value if not NULL.
1625 @return The key of the item removed.
1631 IN OUT NET_MAP
*Map
,
1632 OUT VOID
**Value OPTIONAL
1638 // Often, it indicates a programming error to remove
1639 // the first entry in an empty list
1641 ASSERT (Map
&& !IsListEmpty (&Map
->Used
));
1643 Item
= NET_LIST_HEAD (&Map
->Used
, NET_MAP_ITEM
, Link
);
1644 RemoveEntryList (&Item
->Link
);
1646 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1648 if (Value
!= NULL
) {
1649 *Value
= Item
->Value
;
1657 Remove the last node entry on the netmap and return the key of the removed item.
1659 Remove the last node entry from the Used doubly linked list of the netmap.
1660 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1661 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1662 parameter Value will point to the value of the item. It returns the key of the removed item.
1664 If Map is NULL, then ASSERT().
1665 If the Used doubly linked list is empty, then ASSERT().
1667 @param[in, out] Map The netmap to remove the tail from.
1668 @param[out] Value The variable to receive the value if not NULL.
1670 @return The key of the item removed.
1676 IN OUT NET_MAP
*Map
,
1677 OUT VOID
**Value OPTIONAL
1683 // Often, it indicates a programming error to remove
1684 // the last entry in an empty list
1686 ASSERT (Map
&& !IsListEmpty (&Map
->Used
));
1688 Item
= NET_LIST_TAIL (&Map
->Used
, NET_MAP_ITEM
, Link
);
1689 RemoveEntryList (&Item
->Link
);
1691 InsertHeadList (&Map
->Recycled
, &Item
->Link
);
1693 if (Value
!= NULL
) {
1694 *Value
= Item
->Value
;
1702 Iterate through the netmap and call CallBack for each item.
1704 It will continue the traverse if CallBack returns EFI_SUCCESS, otherwise, break
1705 from the loop. It returns the CallBack's last return value. This function is
1706 delete safe for the current item.
1708 If Map is NULL, then ASSERT().
1709 If CallBack is NULL, then ASSERT().
1711 @param[in] Map The Map to iterate through.
1712 @param[in] CallBack The callback function to call for each item.
1713 @param[in] Arg The opaque parameter to the callback.
1715 @retval EFI_SUCCESS There is no item in the netmap or CallBack for each item
1717 @retval Others It returns the CallBack's last return value.
1724 IN NET_MAP_CALLBACK CallBack
,
1725 IN VOID
*Arg OPTIONAL
1735 ASSERT ((Map
!= NULL
) && (CallBack
!= NULL
));
1739 if (IsListEmpty (Head
)) {
1743 NET_LIST_FOR_EACH_SAFE (Entry
, Next
, Head
) {
1744 Item
= NET_LIST_USER_STRUCT (Entry
, NET_MAP_ITEM
, Link
);
1745 Result
= CallBack (Map
, Item
, Arg
);
1747 if (EFI_ERROR (Result
)) {
1757 This is the default unload handle for all the network drivers.
1759 Disconnect the driver specified by ImageHandle from all the devices in the handle database.
1760 Uninstall all the protocols installed in the driver entry point.
1762 @param[in] ImageHandle The drivers' driver image.
1764 @retval EFI_SUCCESS The image is unloaded.
1765 @retval Others Failed to unload the image.
1770 NetLibDefaultUnload (
1771 IN EFI_HANDLE ImageHandle
1775 EFI_HANDLE
*DeviceHandleBuffer
;
1776 UINTN DeviceHandleCount
;
1779 EFI_DRIVER_BINDING_PROTOCOL
*DriverBinding
;
1780 EFI_COMPONENT_NAME_PROTOCOL
*ComponentName
;
1781 EFI_COMPONENT_NAME2_PROTOCOL
*ComponentName2
;
1784 // Get the list of all the handles in the handle database.
1785 // If there is an error getting the list, then the unload
1788 Status
= gBS
->LocateHandleBuffer (
1796 if (EFI_ERROR (Status
)) {
1800 for (Index
= 0; Index
< DeviceHandleCount
; Index
++) {
1801 Status
= gBS
->HandleProtocol (
1802 DeviceHandleBuffer
[Index
],
1803 &gEfiDriverBindingProtocolGuid
,
1804 (VOID
**) &DriverBinding
1806 if (EFI_ERROR (Status
)) {
1810 if (DriverBinding
->ImageHandle
!= ImageHandle
) {
1815 // Disconnect the driver specified by ImageHandle from all
1816 // the devices in the handle database.
1818 for (Index2
= 0; Index2
< DeviceHandleCount
; Index2
++) {
1819 Status
= gBS
->DisconnectController (
1820 DeviceHandleBuffer
[Index2
],
1821 DriverBinding
->DriverBindingHandle
,
1827 // Uninstall all the protocols installed in the driver entry point
1829 gBS
->UninstallProtocolInterface (
1830 DriverBinding
->DriverBindingHandle
,
1831 &gEfiDriverBindingProtocolGuid
,
1835 Status
= gBS
->HandleProtocol (
1836 DeviceHandleBuffer
[Index
],
1837 &gEfiComponentNameProtocolGuid
,
1838 (VOID
**) &ComponentName
1840 if (!EFI_ERROR (Status
)) {
1841 gBS
->UninstallProtocolInterface (
1842 DriverBinding
->DriverBindingHandle
,
1843 &gEfiComponentNameProtocolGuid
,
1848 Status
= gBS
->HandleProtocol (
1849 DeviceHandleBuffer
[Index
],
1850 &gEfiComponentName2ProtocolGuid
,
1851 (VOID
**) &ComponentName2
1853 if (!EFI_ERROR (Status
)) {
1854 gBS
->UninstallProtocolInterface (
1855 DriverBinding
->DriverBindingHandle
,
1856 &gEfiComponentName2ProtocolGuid
,
1863 // Free the buffer containing the list of handles from the handle database
1865 if (DeviceHandleBuffer
!= NULL
) {
1866 gBS
->FreePool (DeviceHandleBuffer
);
1875 Create a child of the service that is identified by ServiceBindingGuid.
1877 Get the ServiceBinding Protocol first, then use it to create a child.
1879 If ServiceBindingGuid is NULL, then ASSERT().
1880 If ChildHandle is NULL, then ASSERT().
1882 @param[in] Controller The controller which has the service installed.
1883 @param[in] Image The image handle used to open service.
1884 @param[in] ServiceBindingGuid The service's Guid.
1885 @param[in, out] ChildHandle The handle to receive the create child.
1887 @retval EFI_SUCCESS The child is successfully created.
1888 @retval Others Failed to create the child.
1893 NetLibCreateServiceChild (
1894 IN EFI_HANDLE Controller
,
1895 IN EFI_HANDLE Image
,
1896 IN EFI_GUID
*ServiceBindingGuid
,
1897 IN OUT EFI_HANDLE
*ChildHandle
1901 EFI_SERVICE_BINDING_PROTOCOL
*Service
;
1904 ASSERT ((ServiceBindingGuid
!= NULL
) && (ChildHandle
!= NULL
));
1907 // Get the ServiceBinding Protocol
1909 Status
= gBS
->OpenProtocol (
1915 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1918 if (EFI_ERROR (Status
)) {
1925 Status
= Service
->CreateChild (Service
, ChildHandle
);
1931 Destroy a child of the service that is identified by ServiceBindingGuid.
1933 Get the ServiceBinding Protocol first, then use it to destroy a child.
1935 If ServiceBindingGuid is NULL, then ASSERT().
1937 @param[in] Controller The controller which has the service installed.
1938 @param[in] Image The image handle used to open service.
1939 @param[in] ServiceBindingGuid The service's Guid.
1940 @param[in] ChildHandle The child to destroy.
1942 @retval EFI_SUCCESS The child is successfully destroyed.
1943 @retval Others Failed to destroy the child.
1948 NetLibDestroyServiceChild (
1949 IN EFI_HANDLE Controller
,
1950 IN EFI_HANDLE Image
,
1951 IN EFI_GUID
*ServiceBindingGuid
,
1952 IN EFI_HANDLE ChildHandle
1956 EFI_SERVICE_BINDING_PROTOCOL
*Service
;
1958 ASSERT (ServiceBindingGuid
!= NULL
);
1961 // Get the ServiceBinding Protocol
1963 Status
= gBS
->OpenProtocol (
1969 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1972 if (EFI_ERROR (Status
)) {
1977 // destroy the child
1979 Status
= Service
->DestroyChild (Service
, ChildHandle
);
1984 Get handle with Simple Network Protocol installed on it.
1986 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
1987 If Simple Network Protocol is already installed on the ServiceHandle, the
1988 ServiceHandle will be returned. If SNP is not installed on the ServiceHandle,
1989 try to find its parent handle with SNP installed.
1991 @param[in] ServiceHandle The handle where network service binding protocols are
1993 @param[out] Snp The pointer to store the address of the SNP instance.
1994 This is an optional parameter that may be NULL.
1996 @return The SNP handle, or NULL if not found.
2001 NetLibGetSnpHandle (
2002 IN EFI_HANDLE ServiceHandle
,
2003 OUT EFI_SIMPLE_NETWORK_PROTOCOL
**Snp OPTIONAL
2007 EFI_SIMPLE_NETWORK_PROTOCOL
*SnpInstance
;
2008 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2009 EFI_HANDLE SnpHandle
;
2012 // Try to open SNP from ServiceHandle
2015 Status
= gBS
->HandleProtocol (ServiceHandle
, &gEfiSimpleNetworkProtocolGuid
, (VOID
**) &SnpInstance
);
2016 if (!EFI_ERROR (Status
)) {
2020 return ServiceHandle
;
2024 // Failed to open SNP, try to get SNP handle by LocateDevicePath()
2026 DevicePath
= DevicePathFromHandle (ServiceHandle
);
2027 if (DevicePath
== NULL
) {
2032 Status
= gBS
->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid
, &DevicePath
, &SnpHandle
);
2033 if (EFI_ERROR (Status
)) {
2035 // Failed to find SNP handle
2040 Status
= gBS
->HandleProtocol (SnpHandle
, &gEfiSimpleNetworkProtocolGuid
, (VOID
**) &SnpInstance
);
2041 if (!EFI_ERROR (Status
)) {
2052 Retrieve VLAN ID of a VLAN device handle.
2054 Search VLAN device path node in Device Path of specified ServiceHandle and
2055 return its VLAN ID. If no VLAN device path node found, then this ServiceHandle
2056 is not a VLAN device handle, and 0 will be returned.
2058 @param[in] ServiceHandle The handle where network service binding protocols are
2061 @return VLAN ID of the device handle, or 0 if not a VLAN device.
2067 IN EFI_HANDLE ServiceHandle
2070 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2071 EFI_DEVICE_PATH_PROTOCOL
*Node
;
2073 DevicePath
= DevicePathFromHandle (ServiceHandle
);
2074 if (DevicePath
== NULL
) {
2079 while (!IsDevicePathEnd (Node
)) {
2080 if (Node
->Type
== MESSAGING_DEVICE_PATH
&& Node
->SubType
== MSG_VLAN_DP
) {
2081 return ((VLAN_DEVICE_PATH
*) Node
)->VlanId
;
2083 Node
= NextDevicePathNode (Node
);
2090 Find VLAN device handle with specified VLAN ID.
2092 The VLAN child device handle is created by VLAN Config Protocol on ControllerHandle.
2093 This function will append VLAN device path node to the parent device path,
2094 and then use LocateDevicePath() to find the correct VLAN device handle.
2096 @param[in] ControllerHandle The handle where network service binding protocols are
2098 @param[in] VlanId The configured VLAN ID for the VLAN device.
2100 @return The VLAN device handle, or NULL if not found.
2105 NetLibGetVlanHandle (
2106 IN EFI_HANDLE ControllerHandle
,
2110 EFI_DEVICE_PATH_PROTOCOL
*ParentDevicePath
;
2111 EFI_DEVICE_PATH_PROTOCOL
*VlanDevicePath
;
2112 EFI_DEVICE_PATH_PROTOCOL
*DevicePath
;
2113 VLAN_DEVICE_PATH VlanNode
;
2116 ParentDevicePath
= DevicePathFromHandle (ControllerHandle
);
2117 if (ParentDevicePath
== NULL
) {
2122 // Construct VLAN device path
2124 CopyMem (&VlanNode
, &mNetVlanDevicePathTemplate
, sizeof (VLAN_DEVICE_PATH
));
2125 VlanNode
.VlanId
= VlanId
;
2126 VlanDevicePath
= AppendDevicePathNode (
2128 (EFI_DEVICE_PATH_PROTOCOL
*) &VlanNode
2130 if (VlanDevicePath
== NULL
) {
2135 // Find VLAN device handle
2138 DevicePath
= VlanDevicePath
;
2139 gBS
->LocateDevicePath (
2140 &gEfiDevicePathProtocolGuid
,
2144 if (!IsDevicePathEnd (DevicePath
)) {
2146 // Device path is not exactly match
2151 FreePool (VlanDevicePath
);
2156 Get MAC address associated with the network service handle.
2158 If MacAddress is NULL, then ASSERT().
2159 If AddressSize is NULL, then ASSERT().
2161 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
2162 If SNP is installed on the ServiceHandle or its parent handle, MAC address will
2163 be retrieved from SNP. If no SNP found, try to get SNP mode data use MNP.
2165 @param[in] ServiceHandle The handle where network service binding protocols are
2167 @param[out] MacAddress The pointer to store the returned MAC address.
2168 @param[out] AddressSize The length of returned MAC address.
2170 @retval EFI_SUCCESS MAC address is returned successfully.
2171 @retval Others Failed to get SNP mode data.
2176 NetLibGetMacAddress (
2177 IN EFI_HANDLE ServiceHandle
,
2178 OUT EFI_MAC_ADDRESS
*MacAddress
,
2179 OUT UINTN
*AddressSize
2183 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2184 EFI_SIMPLE_NETWORK_MODE
*SnpMode
;
2185 EFI_SIMPLE_NETWORK_MODE SnpModeData
;
2186 EFI_MANAGED_NETWORK_PROTOCOL
*Mnp
;
2187 EFI_SERVICE_BINDING_PROTOCOL
*MnpSb
;
2188 EFI_HANDLE
*SnpHandle
;
2189 EFI_HANDLE MnpChildHandle
;
2191 ASSERT (MacAddress
!= NULL
);
2192 ASSERT (AddressSize
!= NULL
);
2195 // Try to get SNP handle
2198 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2199 if (SnpHandle
!= NULL
) {
2201 // SNP found, use it directly
2203 SnpMode
= Snp
->Mode
;
2206 // Failed to get SNP handle, try to get MAC address from MNP
2208 MnpChildHandle
= NULL
;
2209 Status
= gBS
->HandleProtocol (
2211 &gEfiManagedNetworkServiceBindingProtocolGuid
,
2214 if (EFI_ERROR (Status
)) {
2219 // Create a MNP child
2221 Status
= MnpSb
->CreateChild (MnpSb
, &MnpChildHandle
);
2222 if (EFI_ERROR (Status
)) {
2227 // Open MNP protocol
2229 Status
= gBS
->HandleProtocol (
2231 &gEfiManagedNetworkProtocolGuid
,
2234 if (EFI_ERROR (Status
)) {
2235 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2240 // Try to get SNP mode from MNP
2242 Status
= Mnp
->GetModeData (Mnp
, NULL
, &SnpModeData
);
2243 if (EFI_ERROR (Status
) && (Status
!= EFI_NOT_STARTED
)) {
2244 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2247 SnpMode
= &SnpModeData
;
2250 // Destroy the MNP child
2252 MnpSb
->DestroyChild (MnpSb
, MnpChildHandle
);
2255 *AddressSize
= SnpMode
->HwAddressSize
;
2256 CopyMem (MacAddress
->Addr
, SnpMode
->CurrentAddress
.Addr
, SnpMode
->HwAddressSize
);
2262 Convert MAC address of the NIC associated with specified Service Binding Handle
2263 to a unicode string. Callers are responsible for freeing the string storage.
2265 If MacString is NULL, then ASSERT().
2267 Locate simple network protocol associated with the Service Binding Handle and
2268 get the mac address from SNP. Then convert the mac address into a unicode
2269 string. It takes 2 unicode characters to represent a 1 byte binary buffer.
2270 Plus one unicode character for the null-terminator.
2272 @param[in] ServiceHandle The handle where network service binding protocol is
2274 @param[in] ImageHandle The image handle used to act as the agent handle to
2275 get the simple network protocol. This parameter is
2276 optional and may be NULL.
2277 @param[out] MacString The pointer to store the address of the string
2278 representation of the mac address.
2280 @retval EFI_SUCCESS Convert the mac address a unicode string successfully.
2281 @retval EFI_OUT_OF_RESOURCES There are not enough memory resource.
2282 @retval Others Failed to open the simple network protocol.
2287 NetLibGetMacString (
2288 IN EFI_HANDLE ServiceHandle
,
2289 IN EFI_HANDLE ImageHandle
, OPTIONAL
2290 OUT CHAR16
**MacString
2294 EFI_MAC_ADDRESS MacAddress
;
2296 UINTN HwAddressSize
;
2302 ASSERT (MacString
!= NULL
);
2305 // Get MAC address of the network device
2307 Status
= NetLibGetMacAddress (ServiceHandle
, &MacAddress
, &HwAddressSize
);
2308 if (EFI_ERROR (Status
)) {
2313 // It takes 2 unicode characters to represent a 1 byte binary buffer.
2314 // If VLAN is configured, it will need extra 5 characters like "\0005".
2315 // Plus one unicode character for the null-terminator.
2317 BufferSize
= (2 * HwAddressSize
+ 5 + 1) * sizeof (CHAR16
);
2318 String
= AllocateZeroPool (BufferSize
);
2319 if (String
== NULL
) {
2320 return EFI_OUT_OF_RESOURCES
;
2322 *MacString
= String
;
2325 // Convert the MAC address into a unicode string.
2327 HwAddress
= &MacAddress
.Addr
[0];
2328 for (Index
= 0; Index
< HwAddressSize
; Index
++) {
2329 UnicodeValueToStringS (
2331 BufferSize
- ((UINTN
)String
- (UINTN
)*MacString
),
2332 PREFIX_ZERO
| RADIX_HEX
,
2336 String
+= StrnLenS (String
, (BufferSize
- ((UINTN
)String
- (UINTN
)*MacString
)) / sizeof (CHAR16
));
2340 // Append VLAN ID if any
2342 VlanId
= NetLibGetVlanId (ServiceHandle
);
2345 UnicodeValueToStringS (
2347 BufferSize
- ((UINTN
)String
- (UINTN
)*MacString
),
2348 PREFIX_ZERO
| RADIX_HEX
,
2352 String
+= StrnLenS (String
, (BufferSize
- ((UINTN
)String
- (UINTN
)*MacString
)) / sizeof (CHAR16
));
2356 // Null terminate the Unicode string
2364 Detect media status for specified network device.
2366 If MediaPresent is NULL, then ASSERT().
2368 The underlying UNDI driver may or may not support reporting media status from
2369 GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine
2370 will try to invoke Snp->GetStatus() to get the media status: if media already
2371 present, it return directly; if media not present, it will stop SNP and then
2372 restart SNP to get the latest media status, this give chance to get the correct
2373 media status for old UNDI driver which doesn't support reporting media status
2374 from GET_STATUS command.
2375 Note: there will be two limitations for current algorithm:
2376 1) for UNDI with this capability, in case of cable is not attached, there will
2377 be an redundant Stop/Start() process;
2378 2) for UNDI without this capability, in case that network cable is attached when
2379 Snp->Initialize() is invoked while network cable is unattached later,
2380 NetLibDetectMedia() will report MediaPresent as TRUE, causing upper layer
2381 apps to wait for timeout time.
2383 @param[in] ServiceHandle The handle where network service binding protocols are
2385 @param[out] MediaPresent The pointer to store the media status.
2387 @retval EFI_SUCCESS Media detection success.
2388 @retval EFI_INVALID_PARAMETER ServiceHandle is not valid network device handle.
2389 @retval EFI_UNSUPPORTED Network device does not support media detection.
2390 @retval EFI_DEVICE_ERROR SNP is in unknown state.
2396 IN EFI_HANDLE ServiceHandle
,
2397 OUT BOOLEAN
*MediaPresent
2401 EFI_HANDLE SnpHandle
;
2402 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2403 UINT32 InterruptStatus
;
2405 EFI_MAC_ADDRESS
*MCastFilter
;
2406 UINT32 MCastFilterCount
;
2407 UINT32 EnableFilterBits
;
2408 UINT32 DisableFilterBits
;
2409 BOOLEAN ResetMCastFilters
;
2411 ASSERT (MediaPresent
!= NULL
);
2417 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2418 if (SnpHandle
== NULL
) {
2419 return EFI_INVALID_PARAMETER
;
2423 // Check whether SNP support media detection
2425 if (!Snp
->Mode
->MediaPresentSupported
) {
2426 return EFI_UNSUPPORTED
;
2430 // Invoke Snp->GetStatus() to refresh MediaPresent field in SNP mode data
2432 Status
= Snp
->GetStatus (Snp
, &InterruptStatus
, NULL
);
2433 if (EFI_ERROR (Status
)) {
2437 if (Snp
->Mode
->MediaPresent
) {
2439 // Media is present, return directly
2441 *MediaPresent
= TRUE
;
2446 // Till now, GetStatus() report no media; while, in case UNDI not support
2447 // reporting media status from GetStatus(), this media status may be incorrect.
2448 // So, we will stop SNP and then restart it to get the correct media status.
2450 OldState
= Snp
->Mode
->State
;
2451 if (OldState
>= EfiSimpleNetworkMaxState
) {
2452 return EFI_DEVICE_ERROR
;
2457 if (OldState
== EfiSimpleNetworkInitialized
) {
2459 // SNP is already in use, need Shutdown/Stop and then Start/Initialize
2463 // Backup current SNP receive filter settings
2465 EnableFilterBits
= Snp
->Mode
->ReceiveFilterSetting
;
2466 DisableFilterBits
= Snp
->Mode
->ReceiveFilterMask
^ EnableFilterBits
;
2468 ResetMCastFilters
= TRUE
;
2469 MCastFilterCount
= Snp
->Mode
->MCastFilterCount
;
2470 if (MCastFilterCount
!= 0) {
2471 MCastFilter
= AllocateCopyPool (
2472 MCastFilterCount
* sizeof (EFI_MAC_ADDRESS
),
2473 Snp
->Mode
->MCastFilter
2475 ASSERT (MCastFilter
!= NULL
);
2476 if (MCastFilter
== NULL
) {
2477 Status
= EFI_OUT_OF_RESOURCES
;
2481 ResetMCastFilters
= FALSE
;
2485 // Shutdown/Stop the simple network
2487 Status
= Snp
->Shutdown (Snp
);
2488 if (!EFI_ERROR (Status
)) {
2489 Status
= Snp
->Stop (Snp
);
2491 if (EFI_ERROR (Status
)) {
2496 // Start/Initialize the simple network
2498 Status
= Snp
->Start (Snp
);
2499 if (!EFI_ERROR (Status
)) {
2500 Status
= Snp
->Initialize (Snp
, 0, 0);
2502 if (EFI_ERROR (Status
)) {
2507 // Here we get the correct media status
2509 *MediaPresent
= Snp
->Mode
->MediaPresent
;
2512 // Restore SNP receive filter settings
2514 Status
= Snp
->ReceiveFilters (
2523 if (MCastFilter
!= NULL
) {
2524 FreePool (MCastFilter
);
2531 // SNP is not in use, it's in state of EfiSimpleNetworkStopped or EfiSimpleNetworkStarted
2533 if (OldState
== EfiSimpleNetworkStopped
) {
2535 // SNP not start yet, start it
2537 Status
= Snp
->Start (Snp
);
2538 if (EFI_ERROR (Status
)) {
2544 // Initialize the simple network
2546 Status
= Snp
->Initialize (Snp
, 0, 0);
2547 if (EFI_ERROR (Status
)) {
2548 Status
= EFI_DEVICE_ERROR
;
2553 // Here we get the correct media status
2555 *MediaPresent
= Snp
->Mode
->MediaPresent
;
2558 // Shut down the simple network
2560 Snp
->Shutdown (Snp
);
2563 if (OldState
== EfiSimpleNetworkStopped
) {
2565 // Original SNP sate is Stopped, restore to original state
2570 if (MCastFilter
!= NULL
) {
2571 FreePool (MCastFilter
);
2579 Detect media state for a network device. This routine will wait for a period of time at
2580 a specified checking interval when a certain network is under connecting until connection
2581 process finishs or timeout. If Aip protocol is supported by low layer drivers, three kinds
2582 of media states can be detected: EFI_SUCCESS, EFI_NOT_READY and EFI_NO_MEDIA, represents
2583 connected state, connecting state and no media state respectively. When function detects
2584 the current state is EFI_NOT_READY, it will loop to wait for next time's check until state
2585 turns to be EFI_SUCCESS or EFI_NO_MEDIA. If Aip protocol is not supported, function will
2586 call NetLibDetectMedia() and return state directly.
2588 @param[in] ServiceHandle The handle where network service binding protocols are
2590 @param[in] Timeout The maximum number of 100ns units to wait when network
2591 is connecting. Zero value means detect once and return
2593 @param[out] MediaState The pointer to the detected media state.
2595 @retval EFI_SUCCESS Media detection success.
2596 @retval EFI_INVALID_PARAMETER ServiceHandle is not a valid network device handle or
2597 MediaState pointer is NULL.
2598 @retval EFI_DEVICE_ERROR A device error occurred.
2599 @retval EFI_TIMEOUT Network is connecting but timeout.
2604 NetLibDetectMediaWaitTimeout (
2605 IN EFI_HANDLE ServiceHandle
,
2607 OUT EFI_STATUS
*MediaState
2611 EFI_HANDLE SnpHandle
;
2612 EFI_SIMPLE_NETWORK_PROTOCOL
*Snp
;
2613 EFI_ADAPTER_INFORMATION_PROTOCOL
*Aip
;
2614 EFI_ADAPTER_INFO_MEDIA_STATE
*MediaInfo
;
2615 BOOLEAN MediaPresent
;
2617 EFI_STATUS TimerStatus
;
2619 UINT64 TimeRemained
;
2621 if (MediaState
== NULL
) {
2622 return EFI_INVALID_PARAMETER
;
2624 *MediaState
= EFI_SUCCESS
;
2631 SnpHandle
= NetLibGetSnpHandle (ServiceHandle
, &Snp
);
2632 if (SnpHandle
== NULL
) {
2633 return EFI_INVALID_PARAMETER
;
2636 Status
= gBS
->HandleProtocol (
2638 &gEfiAdapterInformationProtocolGuid
,
2641 if (EFI_ERROR (Status
)) {
2643 MediaPresent
= TRUE
;
2644 Status
= NetLibDetectMedia (ServiceHandle
, &MediaPresent
);
2645 if (!EFI_ERROR (Status
)) {
2647 *MediaState
= EFI_SUCCESS
;
2649 *MediaState
= EFI_NO_MEDIA
;
2654 // NetLibDetectMedia doesn't support EFI_NOT_READY status, return now!
2659 Status
= Aip
->GetInformation (
2661 &gEfiAdapterInfoMediaStateGuid
,
2662 (VOID
**) &MediaInfo
,
2665 if (!EFI_ERROR (Status
)) {
2667 *MediaState
= MediaInfo
->MediaState
;
2668 FreePool (MediaInfo
);
2669 if (*MediaState
!= EFI_NOT_READY
|| Timeout
< MEDIA_STATE_DETECT_TIME_INTERVAL
) {
2675 if (MediaInfo
!= NULL
) {
2676 FreePool (MediaInfo
);
2679 if (Status
== EFI_UNSUPPORTED
) {
2682 // If gEfiAdapterInfoMediaStateGuid is not supported, call NetLibDetectMedia to get media state!
2684 MediaPresent
= TRUE
;
2685 Status
= NetLibDetectMedia (ServiceHandle
, &MediaPresent
);
2686 if (!EFI_ERROR (Status
)) {
2688 *MediaState
= EFI_SUCCESS
;
2690 *MediaState
= EFI_NO_MEDIA
;
2700 // Loop to check media state
2704 TimeRemained
= Timeout
;
2705 Status
= gBS
->CreateEvent (EVT_TIMER
, TPL_CALLBACK
, NULL
, NULL
, &Timer
);
2706 if (EFI_ERROR (Status
)) {
2707 return EFI_DEVICE_ERROR
;
2711 Status
= gBS
->SetTimer (
2714 MEDIA_STATE_DETECT_TIME_INTERVAL
2716 if (EFI_ERROR (Status
)) {
2717 gBS
->CloseEvent(Timer
);
2718 return EFI_DEVICE_ERROR
;
2722 TimerStatus
= gBS
->CheckEvent (Timer
);
2723 if (!EFI_ERROR (TimerStatus
)) {
2725 TimeRemained
-= MEDIA_STATE_DETECT_TIME_INTERVAL
;
2726 Status
= Aip
->GetInformation (
2728 &gEfiAdapterInfoMediaStateGuid
,
2729 (VOID
**) &MediaInfo
,
2732 if (!EFI_ERROR (Status
)) {
2734 *MediaState
= MediaInfo
->MediaState
;
2735 FreePool (MediaInfo
);
2738 if (MediaInfo
!= NULL
) {
2739 FreePool (MediaInfo
);
2741 gBS
->CloseEvent(Timer
);
2745 } while (TimerStatus
== EFI_NOT_READY
);
2746 } while (*MediaState
== EFI_NOT_READY
&& TimeRemained
>= MEDIA_STATE_DETECT_TIME_INTERVAL
);
2748 gBS
->CloseEvent(Timer
);
2749 if (*MediaState
== EFI_NOT_READY
&& TimeRemained
< MEDIA_STATE_DETECT_TIME_INTERVAL
) {
2757 Check the default address used by the IPv4 driver is static or dynamic (acquired
2760 If the controller handle does not have the EFI_IP4_CONFIG2_PROTOCOL installed, the
2761 default address is static. If failed to get the policy from Ip4 Config2 Protocol,
2762 the default address is static. Otherwise, get the result from Ip4 Config2 Protocol.
2764 @param[in] Controller The controller handle which has the EFI_IP4_CONFIG2_PROTOCOL
2765 relative with the default address to judge.
2767 @retval TRUE If the default address is static.
2768 @retval FALSE If the default address is acquired from DHCP.
2772 NetLibDefaultAddressIsStatic (
2773 IN EFI_HANDLE Controller
2777 EFI_IP4_CONFIG2_PROTOCOL
*Ip4Config2
;
2779 EFI_IP4_CONFIG2_POLICY Policy
;
2784 DataSize
= sizeof (EFI_IP4_CONFIG2_POLICY
);
2789 // Get Ip4Config2 policy.
2791 Status
= gBS
->HandleProtocol (Controller
, &gEfiIp4Config2ProtocolGuid
, (VOID
**) &Ip4Config2
);
2792 if (EFI_ERROR (Status
)) {
2796 Status
= Ip4Config2
->GetData (Ip4Config2
, Ip4Config2DataTypePolicy
, &DataSize
, &Policy
);
2797 if (EFI_ERROR (Status
)) {
2801 IsStatic
= (BOOLEAN
) (Policy
== Ip4Config2PolicyStatic
);
2809 Create an IPv4 device path node.
2811 If Node is NULL, then ASSERT().
2813 The header type of IPv4 device path node is MESSAGING_DEVICE_PATH.
2814 The header subtype of IPv4 device path node is MSG_IPv4_DP.
2815 Get other info from parameters to make up the whole IPv4 device path node.
2817 @param[in, out] Node Pointer to the IPv4 device path node.
2818 @param[in] Controller The controller handle.
2819 @param[in] LocalIp The local IPv4 address.
2820 @param[in] LocalPort The local port.
2821 @param[in] RemoteIp The remote IPv4 address.
2822 @param[in] RemotePort The remote port.
2823 @param[in] Protocol The protocol type in the IP header.
2824 @param[in] UseDefaultAddress Whether this instance is using default address or not.
2829 NetLibCreateIPv4DPathNode (
2830 IN OUT IPv4_DEVICE_PATH
*Node
,
2831 IN EFI_HANDLE Controller
,
2832 IN IP4_ADDR LocalIp
,
2833 IN UINT16 LocalPort
,
2834 IN IP4_ADDR RemoteIp
,
2835 IN UINT16 RemotePort
,
2837 IN BOOLEAN UseDefaultAddress
2840 ASSERT (Node
!= NULL
);
2842 Node
->Header
.Type
= MESSAGING_DEVICE_PATH
;
2843 Node
->Header
.SubType
= MSG_IPv4_DP
;
2844 SetDevicePathNodeLength (&Node
->Header
, sizeof (IPv4_DEVICE_PATH
));
2846 CopyMem (&Node
->LocalIpAddress
, &LocalIp
, sizeof (EFI_IPv4_ADDRESS
));
2847 CopyMem (&Node
->RemoteIpAddress
, &RemoteIp
, sizeof (EFI_IPv4_ADDRESS
));
2849 Node
->LocalPort
= LocalPort
;
2850 Node
->RemotePort
= RemotePort
;
2852 Node
->Protocol
= Protocol
;
2854 if (!UseDefaultAddress
) {
2855 Node
->StaticIpAddress
= TRUE
;
2857 Node
->StaticIpAddress
= NetLibDefaultAddressIsStatic (Controller
);
2861 // Set the Gateway IP address to default value 0:0:0:0.
2862 // Set the Subnet mask to default value 255:255:255:0.
2864 ZeroMem (&Node
->GatewayIpAddress
, sizeof (EFI_IPv4_ADDRESS
));
2865 SetMem (&Node
->SubnetMask
, sizeof (EFI_IPv4_ADDRESS
), 0xff);
2866 Node
->SubnetMask
.Addr
[3] = 0;
2870 Create an IPv6 device path node.
2872 If Node is NULL, then ASSERT().
2873 If LocalIp is NULL, then ASSERT().
2874 If RemoteIp is NULL, then ASSERT().
2876 The header type of IPv6 device path node is MESSAGING_DEVICE_PATH.
2877 The header subtype of IPv6 device path node is MSG_IPv6_DP.
2878 Get other info from parameters to make up the whole IPv6 device path node.
2880 @param[in, out] Node Pointer to the IPv6 device path node.
2881 @param[in] Controller The controller handle.
2882 @param[in] LocalIp The local IPv6 address.
2883 @param[in] LocalPort The local port.
2884 @param[in] RemoteIp The remote IPv6 address.
2885 @param[in] RemotePort The remote port.
2886 @param[in] Protocol The protocol type in the IP header.
2891 NetLibCreateIPv6DPathNode (
2892 IN OUT IPv6_DEVICE_PATH
*Node
,
2893 IN EFI_HANDLE Controller
,
2894 IN EFI_IPv6_ADDRESS
*LocalIp
,
2895 IN UINT16 LocalPort
,
2896 IN EFI_IPv6_ADDRESS
*RemoteIp
,
2897 IN UINT16 RemotePort
,
2901 ASSERT (Node
!= NULL
&& LocalIp
!= NULL
&& RemoteIp
!= NULL
);
2903 Node
->Header
.Type
= MESSAGING_DEVICE_PATH
;
2904 Node
->Header
.SubType
= MSG_IPv6_DP
;
2905 SetDevicePathNodeLength (&Node
->Header
, sizeof (IPv6_DEVICE_PATH
));
2907 CopyMem (&Node
->LocalIpAddress
, LocalIp
, sizeof (EFI_IPv6_ADDRESS
));
2908 CopyMem (&Node
->RemoteIpAddress
, RemoteIp
, sizeof (EFI_IPv6_ADDRESS
));
2910 Node
->LocalPort
= LocalPort
;
2911 Node
->RemotePort
= RemotePort
;
2913 Node
->Protocol
= Protocol
;
2916 // Set default value to IPAddressOrigin, PrefixLength.
2917 // Set the Gateway IP address to unspecified address.
2919 Node
->IpAddressOrigin
= 0;
2920 Node
->PrefixLength
= IP6_PREFIX_LENGTH
;
2921 ZeroMem (&Node
->GatewayIpAddress
, sizeof (EFI_IPv6_ADDRESS
));
2925 Find the UNDI/SNP handle from controller and protocol GUID.
2927 If ProtocolGuid is NULL, then ASSERT().
2929 For example, IP will open a MNP child to transmit/receive
2930 packets, when MNP is stopped, IP should also be stopped. IP
2931 needs to find its own private data which is related the IP's
2932 service binding instance that is install on UNDI/SNP handle.
2933 Now, the controller is either a MNP or ARP child handle. But
2934 IP opens these handle BY_DRIVER, use that info, we can get the
2937 @param[in] Controller Then protocol handle to check.
2938 @param[in] ProtocolGuid The protocol that is related with the handle.
2940 @return The UNDI/SNP handle or NULL for errors.
2945 NetLibGetNicHandle (
2946 IN EFI_HANDLE Controller
,
2947 IN EFI_GUID
*ProtocolGuid
2950 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY
*OpenBuffer
;
2956 ASSERT (ProtocolGuid
!= NULL
);
2958 Status
= gBS
->OpenProtocolInformation (
2965 if (EFI_ERROR (Status
)) {
2971 for (Index
= 0; Index
< OpenCount
; Index
++) {
2972 if ((OpenBuffer
[Index
].Attributes
& EFI_OPEN_PROTOCOL_BY_DRIVER
) != 0) {
2973 Handle
= OpenBuffer
[Index
].ControllerHandle
;
2978 gBS
->FreePool (OpenBuffer
);
2983 Convert one Null-terminated ASCII string (decimal dotted) to EFI_IPv4_ADDRESS.
2985 @param[in] String The pointer to the Ascii string.
2986 @param[out] Ip4Address The pointer to the converted IPv4 address.
2988 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2989 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2994 NetLibAsciiStrToIp4 (
2995 IN CONST CHAR8
*String
,
2996 OUT EFI_IPv4_ADDRESS
*Ip4Address
2999 RETURN_STATUS Status
;
3002 Status
= AsciiStrToIpv4Address (String
, &EndPointer
, Ip4Address
, NULL
);
3003 if (RETURN_ERROR (Status
) || (*EndPointer
!= '\0')) {
3004 return EFI_INVALID_PARAMETER
;
3012 Convert one Null-terminated ASCII string to EFI_IPv6_ADDRESS. The format of the
3013 string is defined in RFC 4291 - Text Representation of Addresses.
3015 @param[in] String The pointer to the Ascii string.
3016 @param[out] Ip6Address The pointer to the converted IPv6 address.
3018 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3019 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3024 NetLibAsciiStrToIp6 (
3025 IN CONST CHAR8
*String
,
3026 OUT EFI_IPv6_ADDRESS
*Ip6Address
3029 RETURN_STATUS Status
;
3032 Status
= AsciiStrToIpv6Address (String
, &EndPointer
, Ip6Address
, NULL
);
3033 if (RETURN_ERROR (Status
) || (*EndPointer
!= '\0')) {
3034 return EFI_INVALID_PARAMETER
;
3042 Convert one Null-terminated Unicode string (decimal dotted) to EFI_IPv4_ADDRESS.
3044 @param[in] String The pointer to the Ascii string.
3045 @param[out] Ip4Address The pointer to the converted IPv4 address.
3047 @retval EFI_SUCCESS Convert to IPv4 address successfully.
3048 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
3054 IN CONST CHAR16
*String
,
3055 OUT EFI_IPv4_ADDRESS
*Ip4Address
3058 RETURN_STATUS Status
;
3061 Status
= StrToIpv4Address (String
, &EndPointer
, Ip4Address
, NULL
);
3062 if (RETURN_ERROR (Status
) || (*EndPointer
!= L
'\0')) {
3063 return EFI_INVALID_PARAMETER
;
3071 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS. The format of
3072 the string is defined in RFC 4291 - Text Representation of Addresses.
3074 @param[in] String The pointer to the Ascii string.
3075 @param[out] Ip6Address The pointer to the converted IPv6 address.
3077 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3078 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3084 IN CONST CHAR16
*String
,
3085 OUT EFI_IPv6_ADDRESS
*Ip6Address
3088 RETURN_STATUS Status
;
3091 Status
= StrToIpv6Address (String
, &EndPointer
, Ip6Address
, NULL
);
3092 if (RETURN_ERROR (Status
) || (*EndPointer
!= L
'\0')) {
3093 return EFI_INVALID_PARAMETER
;
3100 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS and prefix length.
3101 The format of the string is defined in RFC 4291 - Text Representation of Addresses
3102 Prefixes: ipv6-address/prefix-length.
3104 @param[in] String The pointer to the Ascii string.
3105 @param[out] Ip6Address The pointer to the converted IPv6 address.
3106 @param[out] PrefixLength The pointer to the converted prefix length.
3108 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3109 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3114 NetLibStrToIp6andPrefix (
3115 IN CONST CHAR16
*String
,
3116 OUT EFI_IPv6_ADDRESS
*Ip6Address
,
3117 OUT UINT8
*PrefixLength
3120 RETURN_STATUS Status
;
3123 Status
= StrToIpv6Address (String
, &EndPointer
, Ip6Address
, PrefixLength
);
3124 if (RETURN_ERROR (Status
) || (*EndPointer
!= L
'\0')) {
3125 return EFI_INVALID_PARAMETER
;
3133 Convert one EFI_IPv6_ADDRESS to Null-terminated Unicode string.
3134 The text representation of address is defined in RFC 4291.
3136 @param[in] Ip6Address The pointer to the IPv6 address.
3137 @param[out] String The buffer to return the converted string.
3138 @param[in] StringSize The length in bytes of the input String.
3140 @retval EFI_SUCCESS Convert to string successfully.
3141 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
3142 @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small for the result. BufferSize has been
3143 updated with the size needed to complete the request.
3148 IN EFI_IPv6_ADDRESS
*Ip6Address
,
3155 UINTN LongestZerosStart
;
3156 UINTN LongestZerosLength
;
3157 UINTN CurrentZerosStart
;
3158 UINTN CurrentZerosLength
;
3159 CHAR16 Buffer
[sizeof"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"];
3162 if (Ip6Address
== NULL
|| String
== NULL
|| StringSize
== 0) {
3163 return EFI_INVALID_PARAMETER
;
3167 // Convert the UINT8 array to an UINT16 array for easy handling.
3169 ZeroMem (Ip6Addr
, sizeof (Ip6Addr
));
3170 for (Index
= 0; Index
< 16; Index
++) {
3171 Ip6Addr
[Index
/ 2] |= (Ip6Address
->Addr
[Index
] << ((1 - (Index
% 2)) << 3));
3175 // Find the longest zeros and mark it.
3177 CurrentZerosStart
= DEFAULT_ZERO_START
;
3178 CurrentZerosLength
= 0;
3179 LongestZerosStart
= DEFAULT_ZERO_START
;
3180 LongestZerosLength
= 0;
3181 for (Index
= 0; Index
< 8; Index
++) {
3182 if (Ip6Addr
[Index
] == 0) {
3183 if (CurrentZerosStart
== DEFAULT_ZERO_START
) {
3184 CurrentZerosStart
= Index
;
3185 CurrentZerosLength
= 1;
3187 CurrentZerosLength
++;
3190 if (CurrentZerosStart
!= DEFAULT_ZERO_START
) {
3191 if (CurrentZerosLength
> 2 && (LongestZerosStart
== (DEFAULT_ZERO_START
) || CurrentZerosLength
> LongestZerosLength
)) {
3192 LongestZerosStart
= CurrentZerosStart
;
3193 LongestZerosLength
= CurrentZerosLength
;
3195 CurrentZerosStart
= DEFAULT_ZERO_START
;
3196 CurrentZerosLength
= 0;
3201 if (CurrentZerosStart
!= DEFAULT_ZERO_START
&& CurrentZerosLength
> 2) {
3202 if (LongestZerosStart
== DEFAULT_ZERO_START
|| LongestZerosLength
< CurrentZerosLength
) {
3203 LongestZerosStart
= CurrentZerosStart
;
3204 LongestZerosLength
= CurrentZerosLength
;
3209 for (Index
= 0; Index
< 8; Index
++) {
3210 if (LongestZerosStart
!= DEFAULT_ZERO_START
&& Index
>= LongestZerosStart
&& Index
< LongestZerosStart
+ LongestZerosLength
) {
3211 if (Index
== LongestZerosStart
) {
3219 Ptr
+= UnicodeSPrint(Ptr
, 10, L
"%x", Ip6Addr
[Index
]);
3222 if (LongestZerosStart
!= DEFAULT_ZERO_START
&& LongestZerosStart
+ LongestZerosLength
== 8) {
3227 if ((UINTN
)Ptr
- (UINTN
)Buffer
> StringSize
) {
3228 return EFI_BUFFER_TOO_SMALL
;
3231 StrCpyS (String
, StringSize
/ sizeof (CHAR16
), Buffer
);
3237 This function obtains the system guid from the smbios table.
3239 If SystemGuid is NULL, then ASSERT().
3241 @param[out] SystemGuid The pointer of the returned system guid.
3243 @retval EFI_SUCCESS Successfully obtained the system guid.
3244 @retval EFI_NOT_FOUND Did not find the SMBIOS table.
3249 NetLibGetSystemGuid (
3250 OUT EFI_GUID
*SystemGuid
3254 SMBIOS_TABLE_ENTRY_POINT
*SmbiosTable
;
3255 SMBIOS_TABLE_3_0_ENTRY_POINT
*Smbios30Table
;
3256 SMBIOS_STRUCTURE_POINTER Smbios
;
3257 SMBIOS_STRUCTURE_POINTER SmbiosEnd
;
3260 ASSERT (SystemGuid
!= NULL
);
3263 Status
= EfiGetSystemConfigurationTable (&gEfiSmbios3TableGuid
, (VOID
**) &Smbios30Table
);
3264 if (!(EFI_ERROR (Status
) || Smbios30Table
== NULL
)) {
3265 Smbios
.Hdr
= (SMBIOS_STRUCTURE
*) (UINTN
) Smbios30Table
->TableAddress
;
3266 SmbiosEnd
.Raw
= (UINT8
*) (UINTN
) (Smbios30Table
->TableAddress
+ Smbios30Table
->TableMaximumSize
);
3268 Status
= EfiGetSystemConfigurationTable (&gEfiSmbiosTableGuid
, (VOID
**) &SmbiosTable
);
3269 if (EFI_ERROR (Status
) || SmbiosTable
== NULL
) {
3270 return EFI_NOT_FOUND
;
3272 Smbios
.Hdr
= (SMBIOS_STRUCTURE
*) (UINTN
) SmbiosTable
->TableAddress
;
3273 SmbiosEnd
.Raw
= (UINT8
*) ((UINTN
) SmbiosTable
->TableAddress
+ SmbiosTable
->TableLength
);
3277 if (Smbios
.Hdr
->Type
== 1) {
3278 if (Smbios
.Hdr
->Length
< 0x19) {
3280 // Older version did not support UUID.
3282 return EFI_NOT_FOUND
;
3286 // SMBIOS tables are byte packed so we need to do a byte copy to
3287 // prevend alignment faults on Itanium-based platform.
3289 CopyMem (SystemGuid
, &Smbios
.Type1
->Uuid
, sizeof (EFI_GUID
));
3294 // Go to the next SMBIOS structure. Each SMBIOS structure may include 2 parts:
3295 // 1. Formatted section; 2. Unformatted string section. So, 2 steps are needed
3296 // to skip one SMBIOS structure.
3300 // Step 1: Skip over formatted section.
3302 String
= (CHAR8
*) (Smbios
.Raw
+ Smbios
.Hdr
->Length
);
3305 // Step 2: Skip over unformated string section.
3309 // Each string is terminated with a NULL(00h) BYTE and the sets of strings
3310 // is terminated with an additional NULL(00h) BYTE.
3312 for ( ; *String
!= 0; String
++) {
3315 if (*(UINT8
*)++String
== 0) {
3317 // Pointer to the next SMBIOS structure.
3319 Smbios
.Raw
= (UINT8
*)++String
;
3323 } while (Smbios
.Raw
< SmbiosEnd
.Raw
);
3324 return EFI_NOT_FOUND
;
3328 Create Dns QName according the queried domain name.
3330 If DomainName is NULL, then ASSERT().
3332 QName is a domain name represented as a sequence of labels,
3333 where each label consists of a length octet followed by that
3334 number of octets. The QName terminates with the zero
3335 length octet for the null label of the root. Caller should
3336 take responsibility to free the buffer in returned pointer.
3338 @param DomainName The pointer to the queried domain name string.
3340 @retval NULL Failed to fill QName.
3341 @return QName filled successfully.
3346 NetLibCreateDnsQName (
3347 IN CHAR16
*DomainName
3351 UINTN QueryNameSize
;
3357 ASSERT (DomainName
!= NULL
);
3365 // One byte for first label length, one byte for terminated length zero.
3367 QueryNameSize
= StrLen (DomainName
) + 2;
3369 if (QueryNameSize
> DNS_MAX_NAME_SIZE
) {
3373 QueryName
= AllocateZeroPool (QueryNameSize
);
3374 if (QueryName
== NULL
) {
3381 for (Index
= 0; DomainName
[Index
] != 0; Index
++) {
3382 *Tail
= (CHAR8
) DomainName
[Index
];
3384 *Header
= (CHAR8
) Len
;
3393 *Header
= (CHAR8
) Len
;