]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/DxeNetLib/DxeNetLib.c
MdeModulePkg: Remove NetLib and Ip4Config Protocol dependency.
[mirror_edk2.git] / MdeModulePkg / Library / DxeNetLib / DxeNetLib.c
1 /** @file
2 Network library.
3
4 Copyright (c) 2005 - 2015, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12 **/
13
14 #include <Uefi.h>
15
16 #include <IndustryStandard/SmBios.h>
17
18 #include <Protocol/DriverBinding.h>
19 #include <Protocol/ServiceBinding.h>
20 #include <Protocol/SimpleNetwork.h>
21 #include <Protocol/ManagedNetwork.h>
22 #include <Protocol/Ip4Config2.h>
23 #include <Protocol/ComponentName.h>
24 #include <Protocol/ComponentName2.h>
25
26 #include <Guid/SmBios.h>
27
28 #include <Library/NetLib.h>
29 #include <Library/BaseLib.h>
30 #include <Library/DebugLib.h>
31 #include <Library/BaseMemoryLib.h>
32 #include <Library/UefiBootServicesTableLib.h>
33 #include <Library/UefiRuntimeServicesTableLib.h>
34 #include <Library/MemoryAllocationLib.h>
35 #include <Library/DevicePathLib.h>
36 #include <Library/PrintLib.h>
37 #include <Library/UefiLib.h>
38
39 #define NIC_ITEM_CONFIG_SIZE sizeof (NIC_IP4_CONFIG_INFO) + sizeof (EFI_IP4_ROUTE_TABLE) * MAX_IP4_CONFIG_IN_VARIABLE
40 #define DEFAULT_ZERO_START ((UINTN) ~0)
41
42 //
43 // All the supported IP4 maskes in host byte order.
44 //
45 GLOBAL_REMOVE_IF_UNREFERENCED IP4_ADDR gIp4AllMasks[IP4_MASK_NUM] = {
46 0x00000000,
47 0x80000000,
48 0xC0000000,
49 0xE0000000,
50 0xF0000000,
51 0xF8000000,
52 0xFC000000,
53 0xFE000000,
54
55 0xFF000000,
56 0xFF800000,
57 0xFFC00000,
58 0xFFE00000,
59 0xFFF00000,
60 0xFFF80000,
61 0xFFFC0000,
62 0xFFFE0000,
63
64 0xFFFF0000,
65 0xFFFF8000,
66 0xFFFFC000,
67 0xFFFFE000,
68 0xFFFFF000,
69 0xFFFFF800,
70 0xFFFFFC00,
71 0xFFFFFE00,
72
73 0xFFFFFF00,
74 0xFFFFFF80,
75 0xFFFFFFC0,
76 0xFFFFFFE0,
77 0xFFFFFFF0,
78 0xFFFFFFF8,
79 0xFFFFFFFC,
80 0xFFFFFFFE,
81 0xFFFFFFFF,
82 };
83
84 GLOBAL_REMOVE_IF_UNREFERENCED EFI_IPv4_ADDRESS mZeroIp4Addr = {{0, 0, 0, 0}};
85
86 //
87 // Any error level digitally larger than mNetDebugLevelMax
88 // will be silently discarded.
89 //
90 GLOBAL_REMOVE_IF_UNREFERENCED UINTN mNetDebugLevelMax = NETDEBUG_LEVEL_ERROR;
91 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogPacketSeq = 0xDEADBEEF;
92
93 //
94 // You can change mSyslogDstMac mSyslogDstIp and mSyslogSrcIp
95 // here to direct the syslog packets to the syslog deamon. The
96 // default is broadcast to both the ethernet and IP.
97 //
98 GLOBAL_REMOVE_IF_UNREFERENCED UINT8 mSyslogDstMac[NET_ETHER_ADDR_LEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
99 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogDstIp = 0xffffffff;
100 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogSrcIp = 0;
101
102 GLOBAL_REMOVE_IF_UNREFERENCED CHAR8 *mMonthName[] = {
103 "Jan",
104 "Feb",
105 "Mar",
106 "Apr",
107 "May",
108 "Jun",
109 "Jul",
110 "Aug",
111 "Sep",
112 "Oct",
113 "Nov",
114 "Dec"
115 };
116
117 //
118 // VLAN device path node template
119 //
120 GLOBAL_REMOVE_IF_UNREFERENCED VLAN_DEVICE_PATH mNetVlanDevicePathTemplate = {
121 {
122 MESSAGING_DEVICE_PATH,
123 MSG_VLAN_DP,
124 {
125 (UINT8) (sizeof (VLAN_DEVICE_PATH)),
126 (UINT8) ((sizeof (VLAN_DEVICE_PATH)) >> 8)
127 }
128 },
129 0
130 };
131
132 /**
133 Locate the handles that support SNP, then open one of them
134 to send the syslog packets. The caller isn't required to close
135 the SNP after use because the SNP is opened by HandleProtocol.
136
137 @return The point to SNP if one is properly openned. Otherwise NULL
138
139 **/
140 EFI_SIMPLE_NETWORK_PROTOCOL *
141 SyslogLocateSnp (
142 VOID
143 )
144 {
145 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
146 EFI_STATUS Status;
147 EFI_HANDLE *Handles;
148 UINTN HandleCount;
149 UINTN Index;
150
151 //
152 // Locate the handles which has SNP installed.
153 //
154 Handles = NULL;
155 Status = gBS->LocateHandleBuffer (
156 ByProtocol,
157 &gEfiSimpleNetworkProtocolGuid,
158 NULL,
159 &HandleCount,
160 &Handles
161 );
162
163 if (EFI_ERROR (Status) || (HandleCount == 0)) {
164 return NULL;
165 }
166
167 //
168 // Try to open one of the ethernet SNP protocol to send packet
169 //
170 Snp = NULL;
171
172 for (Index = 0; Index < HandleCount; Index++) {
173 Status = gBS->HandleProtocol (
174 Handles[Index],
175 &gEfiSimpleNetworkProtocolGuid,
176 (VOID **) &Snp
177 );
178
179 if ((Status == EFI_SUCCESS) && (Snp != NULL) &&
180 (Snp->Mode->IfType == NET_IFTYPE_ETHERNET) &&
181 (Snp->Mode->MaxPacketSize >= NET_SYSLOG_PACKET_LEN)) {
182
183 break;
184 }
185
186 Snp = NULL;
187 }
188
189 FreePool (Handles);
190 return Snp;
191 }
192
193 /**
194 Transmit a syslog packet synchronously through SNP. The Packet
195 already has the ethernet header prepended. This function should
196 fill in the source MAC because it will try to locate a SNP each
197 time it is called to avoid the problem if SNP is unloaded.
198 This code snip is copied from MNP.
199
200 @param[in] Packet The Syslog packet
201 @param[in] Length The length of the packet
202
203 @retval EFI_DEVICE_ERROR Failed to locate a usable SNP protocol
204 @retval EFI_TIMEOUT Timeout happened to send the packet.
205 @retval EFI_SUCCESS Packet is sent.
206
207 **/
208 EFI_STATUS
209 SyslogSendPacket (
210 IN CHAR8 *Packet,
211 IN UINT32 Length
212 )
213 {
214 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
215 ETHER_HEAD *Ether;
216 EFI_STATUS Status;
217 EFI_EVENT TimeoutEvent;
218 UINT8 *TxBuf;
219
220 Snp = SyslogLocateSnp ();
221
222 if (Snp == NULL) {
223 return EFI_DEVICE_ERROR;
224 }
225
226 Ether = (ETHER_HEAD *) Packet;
227 CopyMem (Ether->SrcMac, Snp->Mode->CurrentAddress.Addr, NET_ETHER_ADDR_LEN);
228
229 //
230 // Start the timeout event.
231 //
232 Status = gBS->CreateEvent (
233 EVT_TIMER,
234 TPL_NOTIFY,
235 NULL,
236 NULL,
237 &TimeoutEvent
238 );
239
240 if (EFI_ERROR (Status)) {
241 return Status;
242 }
243
244 Status = gBS->SetTimer (TimeoutEvent, TimerRelative, NET_SYSLOG_TX_TIMEOUT);
245
246 if (EFI_ERROR (Status)) {
247 goto ON_EXIT;
248 }
249
250 for (;;) {
251 //
252 // Transmit the packet through SNP.
253 //
254 Status = Snp->Transmit (Snp, 0, Length, Packet, NULL, NULL, NULL);
255
256 if ((Status != EFI_SUCCESS) && (Status != EFI_NOT_READY)) {
257 Status = EFI_DEVICE_ERROR;
258 break;
259 }
260
261 //
262 // If Status is EFI_SUCCESS, the packet is put in the transmit queue.
263 // if Status is EFI_NOT_READY, the transmit engine of the network
264 // interface is busy. Both need to sync SNP.
265 //
266 TxBuf = NULL;
267
268 do {
269 //
270 // Get the recycled transmit buffer status.
271 //
272 Snp->GetStatus (Snp, NULL, (VOID **) &TxBuf);
273
274 if (!EFI_ERROR (gBS->CheckEvent (TimeoutEvent))) {
275 Status = EFI_TIMEOUT;
276 break;
277 }
278
279 } while (TxBuf == NULL);
280
281 if ((Status == EFI_SUCCESS) || (Status == EFI_TIMEOUT)) {
282 break;
283 }
284
285 //
286 // Status is EFI_NOT_READY. Restart the timer event and
287 // call Snp->Transmit again.
288 //
289 gBS->SetTimer (TimeoutEvent, TimerRelative, NET_SYSLOG_TX_TIMEOUT);
290 }
291
292 gBS->SetTimer (TimeoutEvent, TimerCancel, 0);
293
294 ON_EXIT:
295 gBS->CloseEvent (TimeoutEvent);
296 return Status;
297 }
298
299 /**
300 Build a syslog packet, including the Ethernet/Ip/Udp headers
301 and user's message.
302
303 @param[in] Level Syslog servity level
304 @param[in] Module The module that generates the log
305 @param[in] File The file that contains the current log
306 @param[in] Line The line of code in the File that contains the current log
307 @param[in] Message The log message
308 @param[in] BufLen The lenght of the Buf
309 @param[out] Buf The buffer to put the packet data
310
311 @return The length of the syslog packet built.
312
313 **/
314 UINT32
315 SyslogBuildPacket (
316 IN UINT32 Level,
317 IN UINT8 *Module,
318 IN UINT8 *File,
319 IN UINT32 Line,
320 IN UINT8 *Message,
321 IN UINT32 BufLen,
322 OUT CHAR8 *Buf
323 )
324 {
325 ETHER_HEAD *Ether;
326 IP4_HEAD *Ip4;
327 EFI_UDP_HEADER *Udp4;
328 EFI_TIME Time;
329 UINT32 Pri;
330 UINT32 Len;
331
332 //
333 // Fill in the Ethernet header. Leave alone the source MAC.
334 // SyslogSendPacket will fill in the address for us.
335 //
336 Ether = (ETHER_HEAD *) Buf;
337 CopyMem (Ether->DstMac, mSyslogDstMac, NET_ETHER_ADDR_LEN);
338 ZeroMem (Ether->SrcMac, NET_ETHER_ADDR_LEN);
339
340 Ether->EtherType = HTONS (0x0800); // IPv4 protocol
341
342 Buf += sizeof (ETHER_HEAD);
343 BufLen -= sizeof (ETHER_HEAD);
344
345 //
346 // Fill in the IP header
347 //
348 Ip4 = (IP4_HEAD *) Buf;
349 Ip4->HeadLen = 5;
350 Ip4->Ver = 4;
351 Ip4->Tos = 0;
352 Ip4->TotalLen = 0;
353 Ip4->Id = (UINT16) mSyslogPacketSeq;
354 Ip4->Fragment = 0;
355 Ip4->Ttl = 16;
356 Ip4->Protocol = 0x11;
357 Ip4->Checksum = 0;
358 Ip4->Src = mSyslogSrcIp;
359 Ip4->Dst = mSyslogDstIp;
360
361 Buf += sizeof (IP4_HEAD);
362 BufLen -= sizeof (IP4_HEAD);
363
364 //
365 // Fill in the UDP header, Udp checksum is optional. Leave it zero.
366 //
367 Udp4 = (EFI_UDP_HEADER *) Buf;
368 Udp4->SrcPort = HTONS (514);
369 Udp4->DstPort = HTONS (514);
370 Udp4->Length = 0;
371 Udp4->Checksum = 0;
372
373 Buf += sizeof (EFI_UDP_HEADER);
374 BufLen -= sizeof (EFI_UDP_HEADER);
375
376 //
377 // Build the syslog message body with <PRI> Timestamp machine module Message
378 //
379 Pri = ((NET_SYSLOG_FACILITY & 31) << 3) | (Level & 7);
380 gRT->GetTime (&Time, NULL);
381 ASSERT ((Time.Month <= 12) && (Time.Month >= 1));
382
383 //
384 // Use %a to format the ASCII strings, %s to format UNICODE strings
385 //
386 Len = 0;
387 Len += (UINT32) AsciiSPrint (
388 Buf,
389 BufLen,
390 "<%d> %a %d %d:%d:%d ",
391 Pri,
392 mMonthName [Time.Month-1],
393 Time.Day,
394 Time.Hour,
395 Time.Minute,
396 Time.Second
397 );
398 Len--;
399
400 Len += (UINT32) AsciiSPrint (
401 Buf + Len,
402 BufLen - Len,
403 "Tiano %a: %a (Line: %d File: %a)",
404 Module,
405 Message,
406 Line,
407 File
408 );
409 Len--;
410
411 //
412 // OK, patch the IP length/checksum and UDP length fields.
413 //
414 Len += sizeof (EFI_UDP_HEADER);
415 Udp4->Length = HTONS ((UINT16) Len);
416
417 Len += sizeof (IP4_HEAD);
418 Ip4->TotalLen = HTONS ((UINT16) Len);
419 Ip4->Checksum = (UINT16) (~NetblockChecksum ((UINT8 *) Ip4, sizeof (IP4_HEAD)));
420
421 return Len + sizeof (ETHER_HEAD);
422 }
423
424 /**
425 Allocate a buffer, then format the message to it. This is a
426 help function for the NET_DEBUG_XXX macros. The PrintArg of
427 these macros treats the variable length print parameters as a
428 single parameter, and pass it to the NetDebugASPrint. For
429 example, NET_DEBUG_TRACE ("Tcp", ("State transit to %a\n", Name))
430 if extracted to:
431
432 NetDebugOutput (
433 NETDEBUG_LEVEL_TRACE,
434 "Tcp",
435 __FILE__,
436 __LINE__,
437 NetDebugASPrint ("State transit to %a\n", Name)
438 )
439
440 @param Format The ASCII format string.
441 @param ... The variable length parameter whose format is determined
442 by the Format string.
443
444 @return The buffer containing the formatted message,
445 or NULL if failed to allocate memory.
446
447 **/
448 CHAR8 *
449 EFIAPI
450 NetDebugASPrint (
451 IN CHAR8 *Format,
452 ...
453 )
454 {
455 VA_LIST Marker;
456 CHAR8 *Buf;
457
458 Buf = (CHAR8 *) AllocatePool (NET_DEBUG_MSG_LEN);
459
460 if (Buf == NULL) {
461 return NULL;
462 }
463
464 VA_START (Marker, Format);
465 AsciiVSPrint (Buf, NET_DEBUG_MSG_LEN, Format, Marker);
466 VA_END (Marker);
467
468 return Buf;
469 }
470
471 /**
472 Builds an UDP4 syslog packet and send it using SNP.
473
474 This function will locate a instance of SNP then send the message through it.
475 Because it isn't open the SNP BY_DRIVER, apply caution when using it.
476
477 @param Level The servity level of the message.
478 @param Module The Moudle that generates the log.
479 @param File The file that contains the log.
480 @param Line The exact line that contains the log.
481 @param Message The user message to log.
482
483 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
484 @retval EFI_OUT_OF_RESOURCES Failed to allocate memory for the packet
485 @retval EFI_SUCCESS The log is discard because that it is more verbose
486 than the mNetDebugLevelMax. Or, it has been sent out.
487 **/
488 EFI_STATUS
489 EFIAPI
490 NetDebugOutput (
491 IN UINT32 Level,
492 IN UINT8 *Module,
493 IN UINT8 *File,
494 IN UINT32 Line,
495 IN UINT8 *Message
496 )
497 {
498 CHAR8 *Packet;
499 UINT32 Len;
500 EFI_STATUS Status;
501
502 //
503 // Check whether the message should be sent out
504 //
505 if (Message == NULL) {
506 return EFI_INVALID_PARAMETER;
507 }
508
509 if (Level > mNetDebugLevelMax) {
510 Status = EFI_SUCCESS;
511 goto ON_EXIT;
512 }
513
514 //
515 // Allocate a maxium of 1024 bytes, the caller should ensure
516 // that the message plus the ethernet/ip/udp header is shorter
517 // than this
518 //
519 Packet = (CHAR8 *) AllocatePool (NET_SYSLOG_PACKET_LEN);
520
521 if (Packet == NULL) {
522 Status = EFI_OUT_OF_RESOURCES;
523 goto ON_EXIT;
524 }
525
526 //
527 // Build the message: Ethernet header + IP header + Udp Header + user data
528 //
529 Len = SyslogBuildPacket (
530 Level,
531 Module,
532 File,
533 Line,
534 Message,
535 NET_SYSLOG_PACKET_LEN,
536 Packet
537 );
538
539 mSyslogPacketSeq++;
540 Status = SyslogSendPacket (Packet, Len);
541 FreePool (Packet);
542
543 ON_EXIT:
544 FreePool (Message);
545 return Status;
546 }
547 /**
548 Return the length of the mask.
549
550 Return the length of the mask, the correct value is from 0 to 32.
551 If the mask is invalid, return the invalid length 33, which is IP4_MASK_NUM.
552 NetMask is in the host byte order.
553
554 @param[in] NetMask The netmask to get the length from.
555
556 @return The length of the netmask, IP4_MASK_NUM if the mask is invalid.
557
558 **/
559 INTN
560 EFIAPI
561 NetGetMaskLength (
562 IN IP4_ADDR NetMask
563 )
564 {
565 INTN Index;
566
567 for (Index = 0; Index < IP4_MASK_NUM; Index++) {
568 if (NetMask == gIp4AllMasks[Index]) {
569 break;
570 }
571 }
572
573 return Index;
574 }
575
576
577
578 /**
579 Return the class of the IP address, such as class A, B, C.
580 Addr is in host byte order.
581
582 The address of class A starts with 0.
583 If the address belong to class A, return IP4_ADDR_CLASSA.
584 The address of class B starts with 10.
585 If the address belong to class B, return IP4_ADDR_CLASSB.
586 The address of class C starts with 110.
587 If the address belong to class C, return IP4_ADDR_CLASSC.
588 The address of class D starts with 1110.
589 If the address belong to class D, return IP4_ADDR_CLASSD.
590 The address of class E starts with 1111.
591 If the address belong to class E, return IP4_ADDR_CLASSE.
592
593
594 @param[in] Addr The address to get the class from.
595
596 @return IP address class, such as IP4_ADDR_CLASSA.
597
598 **/
599 INTN
600 EFIAPI
601 NetGetIpClass (
602 IN IP4_ADDR Addr
603 )
604 {
605 UINT8 ByteOne;
606
607 ByteOne = (UINT8) (Addr >> 24);
608
609 if ((ByteOne & 0x80) == 0) {
610 return IP4_ADDR_CLASSA;
611
612 } else if ((ByteOne & 0xC0) == 0x80) {
613 return IP4_ADDR_CLASSB;
614
615 } else if ((ByteOne & 0xE0) == 0xC0) {
616 return IP4_ADDR_CLASSC;
617
618 } else if ((ByteOne & 0xF0) == 0xE0) {
619 return IP4_ADDR_CLASSD;
620
621 } else {
622 return IP4_ADDR_CLASSE;
623
624 }
625 }
626
627
628 /**
629 Check whether the IP is a valid unicast address according to
630 the netmask. If NetMask is zero, use the IP address's class to get the default mask.
631
632 If Ip is 0, IP is not a valid unicast address.
633 Class D address is used for multicasting and class E address is reserved for future. If Ip
634 belongs to class D or class E, IP is not a valid unicast address.
635 If all bits of the host address of IP are 0 or 1, IP is also not a valid unicast address.
636
637 @param[in] Ip The IP to check against.
638 @param[in] NetMask The mask of the IP.
639
640 @return TRUE if IP is a valid unicast address on the network, otherwise FALSE.
641
642 **/
643 BOOLEAN
644 EFIAPI
645 NetIp4IsUnicast (
646 IN IP4_ADDR Ip,
647 IN IP4_ADDR NetMask
648 )
649 {
650 INTN Class;
651
652 Class = NetGetIpClass (Ip);
653
654 if ((Ip == 0) || (Class >= IP4_ADDR_CLASSD)) {
655 return FALSE;
656 }
657
658 if (NetMask == 0) {
659 NetMask = gIp4AllMasks[Class << 3];
660 }
661
662 if (((Ip &~NetMask) == ~NetMask) || ((Ip &~NetMask) == 0)) {
663 return FALSE;
664 }
665
666 return TRUE;
667 }
668
669 /**
670 Check whether the incoming IPv6 address is a valid unicast address.
671
672 If the address is a multicast address has binary 0xFF at the start, it is not
673 a valid unicast address. If the address is unspecified ::, it is not a valid
674 unicast address to be assigned to any node. If the address is loopback address
675 ::1, it is also not a valid unicast address to be assigned to any physical
676 interface.
677
678 @param[in] Ip6 The IPv6 address to check against.
679
680 @return TRUE if Ip6 is a valid unicast address on the network, otherwise FALSE.
681
682 **/
683 BOOLEAN
684 EFIAPI
685 NetIp6IsValidUnicast (
686 IN EFI_IPv6_ADDRESS *Ip6
687 )
688 {
689 UINT8 Byte;
690 UINT8 Index;
691
692 if (Ip6->Addr[0] == 0xFF) {
693 return FALSE;
694 }
695
696 for (Index = 0; Index < 15; Index++) {
697 if (Ip6->Addr[Index] != 0) {
698 return TRUE;
699 }
700 }
701
702 Byte = Ip6->Addr[Index];
703
704 if (Byte == 0x0 || Byte == 0x1) {
705 return FALSE;
706 }
707
708 return TRUE;
709 }
710
711 /**
712 Check whether the incoming Ipv6 address is the unspecified address or not.
713
714 @param[in] Ip6 - Ip6 address, in network order.
715
716 @retval TRUE - Yes, unspecified
717 @retval FALSE - No
718
719 **/
720 BOOLEAN
721 EFIAPI
722 NetIp6IsUnspecifiedAddr (
723 IN EFI_IPv6_ADDRESS *Ip6
724 )
725 {
726 UINT8 Index;
727
728 for (Index = 0; Index < 16; Index++) {
729 if (Ip6->Addr[Index] != 0) {
730 return FALSE;
731 }
732 }
733
734 return TRUE;
735 }
736
737 /**
738 Check whether the incoming Ipv6 address is a link-local address.
739
740 @param[in] Ip6 - Ip6 address, in network order.
741
742 @retval TRUE - Yes, link-local address
743 @retval FALSE - No
744
745 **/
746 BOOLEAN
747 EFIAPI
748 NetIp6IsLinkLocalAddr (
749 IN EFI_IPv6_ADDRESS *Ip6
750 )
751 {
752 UINT8 Index;
753
754 ASSERT (Ip6 != NULL);
755
756 if (Ip6->Addr[0] != 0xFE) {
757 return FALSE;
758 }
759
760 if (Ip6->Addr[1] != 0x80) {
761 return FALSE;
762 }
763
764 for (Index = 2; Index < 8; Index++) {
765 if (Ip6->Addr[Index] != 0) {
766 return FALSE;
767 }
768 }
769
770 return TRUE;
771 }
772
773 /**
774 Check whether the Ipv6 address1 and address2 are on the connected network.
775
776 @param[in] Ip1 - Ip6 address1, in network order.
777 @param[in] Ip2 - Ip6 address2, in network order.
778 @param[in] PrefixLength - The prefix length of the checking net.
779
780 @retval TRUE - Yes, connected.
781 @retval FALSE - No.
782
783 **/
784 BOOLEAN
785 EFIAPI
786 NetIp6IsNetEqual (
787 EFI_IPv6_ADDRESS *Ip1,
788 EFI_IPv6_ADDRESS *Ip2,
789 UINT8 PrefixLength
790 )
791 {
792 UINT8 Byte;
793 UINT8 Bit;
794 UINT8 Mask;
795
796 ASSERT ((Ip1 != NULL) && (Ip2 != NULL) && (PrefixLength < IP6_PREFIX_NUM));
797
798 if (PrefixLength == 0) {
799 return TRUE;
800 }
801
802 Byte = (UINT8) (PrefixLength / 8);
803 Bit = (UINT8) (PrefixLength % 8);
804
805 if (CompareMem (Ip1, Ip2, Byte) != 0) {
806 return FALSE;
807 }
808
809 if (Bit > 0) {
810 Mask = (UINT8) (0xFF << (8 - Bit));
811
812 ASSERT (Byte < 16);
813 if ((Ip1->Addr[Byte] & Mask) != (Ip2->Addr[Byte] & Mask)) {
814 return FALSE;
815 }
816 }
817
818 return TRUE;
819 }
820
821
822 /**
823 Switches the endianess of an IPv6 address
824
825 This function swaps the bytes in a 128-bit IPv6 address to switch the value
826 from little endian to big endian or vice versa. The byte swapped value is
827 returned.
828
829 @param Ip6 Points to an IPv6 address
830
831 @return The byte swapped IPv6 address.
832
833 **/
834 EFI_IPv6_ADDRESS *
835 EFIAPI
836 Ip6Swap128 (
837 EFI_IPv6_ADDRESS *Ip6
838 )
839 {
840 UINT64 High;
841 UINT64 Low;
842
843 CopyMem (&High, Ip6, sizeof (UINT64));
844 CopyMem (&Low, &Ip6->Addr[8], sizeof (UINT64));
845
846 High = SwapBytes64 (High);
847 Low = SwapBytes64 (Low);
848
849 CopyMem (Ip6, &Low, sizeof (UINT64));
850 CopyMem (&Ip6->Addr[8], &High, sizeof (UINT64));
851
852 return Ip6;
853 }
854
855 /**
856 Initialize a random seed using current time.
857
858 Get current time first. Then initialize a random seed based on some basic
859 mathematics operation on the hour, day, minute, second, nanosecond and year
860 of the current time.
861
862 @return The random seed initialized with current time.
863
864 **/
865 UINT32
866 EFIAPI
867 NetRandomInitSeed (
868 VOID
869 )
870 {
871 EFI_TIME Time;
872 UINT32 Seed;
873
874 gRT->GetTime (&Time, NULL);
875 Seed = (~Time.Hour << 24 | Time.Day << 16 | Time.Minute << 8 | Time.Second);
876 Seed ^= Time.Nanosecond;
877 Seed ^= Time.Year << 7;
878
879 return Seed;
880 }
881
882
883 /**
884 Extract a UINT32 from a byte stream.
885
886 Copy a UINT32 from a byte stream, then converts it from Network
887 byte order to host byte order. Use this function to avoid alignment error.
888
889 @param[in] Buf The buffer to extract the UINT32.
890
891 @return The UINT32 extracted.
892
893 **/
894 UINT32
895 EFIAPI
896 NetGetUint32 (
897 IN UINT8 *Buf
898 )
899 {
900 UINT32 Value;
901
902 CopyMem (&Value, Buf, sizeof (UINT32));
903 return NTOHL (Value);
904 }
905
906
907 /**
908 Put a UINT32 to the byte stream in network byte order.
909
910 Converts a UINT32 from host byte order to network byte order. Then copy it to the
911 byte stream.
912
913 @param[in, out] Buf The buffer to put the UINT32.
914 @param[in] Data The data to be converted and put into the byte stream.
915
916 **/
917 VOID
918 EFIAPI
919 NetPutUint32 (
920 IN OUT UINT8 *Buf,
921 IN UINT32 Data
922 )
923 {
924 Data = HTONL (Data);
925 CopyMem (Buf, &Data, sizeof (UINT32));
926 }
927
928
929 /**
930 Remove the first node entry on the list, and return the removed node entry.
931
932 Removes the first node Entry from a doubly linked list. It is up to the caller of
933 this function to release the memory used by the first node if that is required. On
934 exit, the removed node is returned.
935
936 If Head is NULL, then ASSERT().
937 If Head was not initialized, then ASSERT().
938 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
939 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
940 then ASSERT().
941
942 @param[in, out] Head The list header.
943
944 @return The first node entry that is removed from the list, NULL if the list is empty.
945
946 **/
947 LIST_ENTRY *
948 EFIAPI
949 NetListRemoveHead (
950 IN OUT LIST_ENTRY *Head
951 )
952 {
953 LIST_ENTRY *First;
954
955 ASSERT (Head != NULL);
956
957 if (IsListEmpty (Head)) {
958 return NULL;
959 }
960
961 First = Head->ForwardLink;
962 Head->ForwardLink = First->ForwardLink;
963 First->ForwardLink->BackLink = Head;
964
965 DEBUG_CODE (
966 First->ForwardLink = (LIST_ENTRY *) NULL;
967 First->BackLink = (LIST_ENTRY *) NULL;
968 );
969
970 return First;
971 }
972
973
974 /**
975 Remove the last node entry on the list and and return the removed node entry.
976
977 Removes the last node entry from a doubly linked list. It is up to the caller of
978 this function to release the memory used by the first node if that is required. On
979 exit, the removed node is returned.
980
981 If Head is NULL, then ASSERT().
982 If Head was not initialized, then ASSERT().
983 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
984 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
985 then ASSERT().
986
987 @param[in, out] Head The list head.
988
989 @return The last node entry that is removed from the list, NULL if the list is empty.
990
991 **/
992 LIST_ENTRY *
993 EFIAPI
994 NetListRemoveTail (
995 IN OUT LIST_ENTRY *Head
996 )
997 {
998 LIST_ENTRY *Last;
999
1000 ASSERT (Head != NULL);
1001
1002 if (IsListEmpty (Head)) {
1003 return NULL;
1004 }
1005
1006 Last = Head->BackLink;
1007 Head->BackLink = Last->BackLink;
1008 Last->BackLink->ForwardLink = Head;
1009
1010 DEBUG_CODE (
1011 Last->ForwardLink = (LIST_ENTRY *) NULL;
1012 Last->BackLink = (LIST_ENTRY *) NULL;
1013 );
1014
1015 return Last;
1016 }
1017
1018
1019 /**
1020 Insert a new node entry after a designated node entry of a doubly linked list.
1021
1022 Inserts a new node entry donated by NewEntry after the node entry donated by PrevEntry
1023 of the doubly linked list.
1024
1025 @param[in, out] PrevEntry The previous entry to insert after.
1026 @param[in, out] NewEntry The new entry to insert.
1027
1028 **/
1029 VOID
1030 EFIAPI
1031 NetListInsertAfter (
1032 IN OUT LIST_ENTRY *PrevEntry,
1033 IN OUT LIST_ENTRY *NewEntry
1034 )
1035 {
1036 NewEntry->BackLink = PrevEntry;
1037 NewEntry->ForwardLink = PrevEntry->ForwardLink;
1038 PrevEntry->ForwardLink->BackLink = NewEntry;
1039 PrevEntry->ForwardLink = NewEntry;
1040 }
1041
1042
1043 /**
1044 Insert a new node entry before a designated node entry of a doubly linked list.
1045
1046 Inserts a new node entry donated by NewEntry after the node entry donated by PostEntry
1047 of the doubly linked list.
1048
1049 @param[in, out] PostEntry The entry to insert before.
1050 @param[in, out] NewEntry The new entry to insert.
1051
1052 **/
1053 VOID
1054 EFIAPI
1055 NetListInsertBefore (
1056 IN OUT LIST_ENTRY *PostEntry,
1057 IN OUT LIST_ENTRY *NewEntry
1058 )
1059 {
1060 NewEntry->ForwardLink = PostEntry;
1061 NewEntry->BackLink = PostEntry->BackLink;
1062 PostEntry->BackLink->ForwardLink = NewEntry;
1063 PostEntry->BackLink = NewEntry;
1064 }
1065
1066 /**
1067 Safe destroy nodes in a linked list, and return the length of the list after all possible operations finished.
1068
1069 Destroy network child instance list by list traversals is not safe due to graph dependencies between nodes.
1070 This function performs a safe traversal to destroy these nodes by checking to see if the node being destroyed
1071 has been removed from the list or not.
1072 If it has been removed, then restart the traversal from the head.
1073 If it hasn't been removed, then continue with the next node directly.
1074 This function will end the iterate and return the CallBack's last return value if error happens,
1075 or retrun EFI_SUCCESS if 2 complete passes are made with no changes in the number of children in the list.
1076
1077 @param[in] List The head of the list.
1078 @param[in] CallBack Pointer to the callback function to destroy one node in the list.
1079 @param[in] Context Pointer to the callback function's context: corresponds to the
1080 parameter Context in NET_DESTROY_LINK_LIST_CALLBACK.
1081 @param[out] ListLength The length of the link list if the function returns successfully.
1082
1083 @retval EFI_SUCCESS Two complete passes are made with no changes in the number of children.
1084 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
1085 @retval Others Return the CallBack's last return value.
1086
1087 **/
1088 EFI_STATUS
1089 EFIAPI
1090 NetDestroyLinkList (
1091 IN LIST_ENTRY *List,
1092 IN NET_DESTROY_LINK_LIST_CALLBACK CallBack,
1093 IN VOID *Context, OPTIONAL
1094 OUT UINTN *ListLength OPTIONAL
1095 )
1096 {
1097 UINTN PreviousLength;
1098 LIST_ENTRY *Entry;
1099 LIST_ENTRY *Ptr;
1100 UINTN Length;
1101 EFI_STATUS Status;
1102
1103 if (List == NULL || CallBack == NULL) {
1104 return EFI_INVALID_PARAMETER;
1105 }
1106
1107 Length = 0;
1108 do {
1109 PreviousLength = Length;
1110 Entry = GetFirstNode (List);
1111 while (!IsNull (List, Entry)) {
1112 Status = CallBack (Entry, Context);
1113 if (EFI_ERROR (Status)) {
1114 return Status;
1115 }
1116 //
1117 // Walk through the list to see whether the Entry has been removed or not.
1118 // If the Entry still exists, just try to destroy the next one.
1119 // If not, go back to the start point to iterate the list again.
1120 //
1121 for (Ptr = List->ForwardLink; Ptr != List; Ptr = Ptr->ForwardLink) {
1122 if (Ptr == Entry) {
1123 break;
1124 }
1125 }
1126 if (Ptr == Entry) {
1127 Entry = GetNextNode (List, Entry);
1128 } else {
1129 Entry = GetFirstNode (List);
1130 }
1131 }
1132 for (Length = 0, Ptr = List->ForwardLink; Ptr != List; Length++, Ptr = Ptr->ForwardLink);
1133 } while (Length != PreviousLength);
1134
1135 if (ListLength != NULL) {
1136 *ListLength = Length;
1137 }
1138 return EFI_SUCCESS;
1139 }
1140
1141 /**
1142 This function checks the input Handle to see if it's one of these handles in ChildHandleBuffer.
1143
1144 @param[in] Handle Handle to be checked.
1145 @param[in] NumberOfChildren Number of Handles in ChildHandleBuffer.
1146 @param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
1147 if NumberOfChildren is 0.
1148
1149 @retval TURE Found the input Handle in ChildHandleBuffer.
1150 @retval FALSE Can't find the input Handle in ChildHandleBuffer.
1151
1152 **/
1153 BOOLEAN
1154 EFIAPI
1155 NetIsInHandleBuffer (
1156 IN EFI_HANDLE Handle,
1157 IN UINTN NumberOfChildren,
1158 IN EFI_HANDLE *ChildHandleBuffer OPTIONAL
1159 )
1160 {
1161 UINTN Index;
1162
1163 if (NumberOfChildren == 0 || ChildHandleBuffer == NULL) {
1164 return FALSE;
1165 }
1166
1167 for (Index = 0; Index < NumberOfChildren; Index++) {
1168 if (Handle == ChildHandleBuffer[Index]) {
1169 return TRUE;
1170 }
1171 }
1172
1173 return FALSE;
1174 }
1175
1176
1177 /**
1178 Initialize the netmap. Netmap is a reposity to keep the <Key, Value> pairs.
1179
1180 Initialize the forward and backward links of two head nodes donated by Map->Used
1181 and Map->Recycled of two doubly linked lists.
1182 Initializes the count of the <Key, Value> pairs in the netmap to zero.
1183
1184 If Map is NULL, then ASSERT().
1185 If the address of Map->Used is NULL, then ASSERT().
1186 If the address of Map->Recycled is NULl, then ASSERT().
1187
1188 @param[in, out] Map The netmap to initialize.
1189
1190 **/
1191 VOID
1192 EFIAPI
1193 NetMapInit (
1194 IN OUT NET_MAP *Map
1195 )
1196 {
1197 ASSERT (Map != NULL);
1198
1199 InitializeListHead (&Map->Used);
1200 InitializeListHead (&Map->Recycled);
1201 Map->Count = 0;
1202 }
1203
1204
1205 /**
1206 To clean up the netmap, that is, release allocated memories.
1207
1208 Removes all nodes of the Used doubly linked list and free memory of all related netmap items.
1209 Removes all nodes of the Recycled doubly linked list and free memory of all related netmap items.
1210 The number of the <Key, Value> pairs in the netmap is set to be zero.
1211
1212 If Map is NULL, then ASSERT().
1213
1214 @param[in, out] Map The netmap to clean up.
1215
1216 **/
1217 VOID
1218 EFIAPI
1219 NetMapClean (
1220 IN OUT NET_MAP *Map
1221 )
1222 {
1223 NET_MAP_ITEM *Item;
1224 LIST_ENTRY *Entry;
1225 LIST_ENTRY *Next;
1226
1227 ASSERT (Map != NULL);
1228
1229 NET_LIST_FOR_EACH_SAFE (Entry, Next, &Map->Used) {
1230 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1231
1232 RemoveEntryList (&Item->Link);
1233 Map->Count--;
1234
1235 gBS->FreePool (Item);
1236 }
1237
1238 ASSERT ((Map->Count == 0) && IsListEmpty (&Map->Used));
1239
1240 NET_LIST_FOR_EACH_SAFE (Entry, Next, &Map->Recycled) {
1241 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1242
1243 RemoveEntryList (&Item->Link);
1244 gBS->FreePool (Item);
1245 }
1246
1247 ASSERT (IsListEmpty (&Map->Recycled));
1248 }
1249
1250
1251 /**
1252 Test whether the netmap is empty and return true if it is.
1253
1254 If the number of the <Key, Value> pairs in the netmap is zero, return TRUE.
1255
1256 If Map is NULL, then ASSERT().
1257
1258
1259 @param[in] Map The net map to test.
1260
1261 @return TRUE if the netmap is empty, otherwise FALSE.
1262
1263 **/
1264 BOOLEAN
1265 EFIAPI
1266 NetMapIsEmpty (
1267 IN NET_MAP *Map
1268 )
1269 {
1270 ASSERT (Map != NULL);
1271 return (BOOLEAN) (Map->Count == 0);
1272 }
1273
1274
1275 /**
1276 Return the number of the <Key, Value> pairs in the netmap.
1277
1278 @param[in] Map The netmap to get the entry number.
1279
1280 @return The entry number in the netmap.
1281
1282 **/
1283 UINTN
1284 EFIAPI
1285 NetMapGetCount (
1286 IN NET_MAP *Map
1287 )
1288 {
1289 return Map->Count;
1290 }
1291
1292
1293 /**
1294 Return one allocated item.
1295
1296 If the Recycled doubly linked list of the netmap is empty, it will try to allocate
1297 a batch of items if there are enough resources and add corresponding nodes to the begining
1298 of the Recycled doubly linked list of the netmap. Otherwise, it will directly remove
1299 the fist node entry of the Recycled doubly linked list and return the corresponding item.
1300
1301 If Map is NULL, then ASSERT().
1302
1303 @param[in, out] Map The netmap to allocate item for.
1304
1305 @return The allocated item. If NULL, the
1306 allocation failed due to resource limit.
1307
1308 **/
1309 NET_MAP_ITEM *
1310 NetMapAllocItem (
1311 IN OUT NET_MAP *Map
1312 )
1313 {
1314 NET_MAP_ITEM *Item;
1315 LIST_ENTRY *Head;
1316 UINTN Index;
1317
1318 ASSERT (Map != NULL);
1319
1320 Head = &Map->Recycled;
1321
1322 if (IsListEmpty (Head)) {
1323 for (Index = 0; Index < NET_MAP_INCREAMENT; Index++) {
1324 Item = AllocatePool (sizeof (NET_MAP_ITEM));
1325
1326 if (Item == NULL) {
1327 if (Index == 0) {
1328 return NULL;
1329 }
1330
1331 break;
1332 }
1333
1334 InsertHeadList (Head, &Item->Link);
1335 }
1336 }
1337
1338 Item = NET_LIST_HEAD (Head, NET_MAP_ITEM, Link);
1339 NetListRemoveHead (Head);
1340
1341 return Item;
1342 }
1343
1344
1345 /**
1346 Allocate an item to save the <Key, Value> pair to the head of the netmap.
1347
1348 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1349 to the beginning of the Used doubly linked list. The number of the <Key, Value>
1350 pairs in the netmap increase by 1.
1351
1352 If Map is NULL, then ASSERT().
1353
1354 @param[in, out] Map The netmap to insert into.
1355 @param[in] Key The user's key.
1356 @param[in] Value The user's value for the key.
1357
1358 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1359 @retval EFI_SUCCESS The item is inserted to the head.
1360
1361 **/
1362 EFI_STATUS
1363 EFIAPI
1364 NetMapInsertHead (
1365 IN OUT NET_MAP *Map,
1366 IN VOID *Key,
1367 IN VOID *Value OPTIONAL
1368 )
1369 {
1370 NET_MAP_ITEM *Item;
1371
1372 ASSERT (Map != NULL);
1373
1374 Item = NetMapAllocItem (Map);
1375
1376 if (Item == NULL) {
1377 return EFI_OUT_OF_RESOURCES;
1378 }
1379
1380 Item->Key = Key;
1381 Item->Value = Value;
1382 InsertHeadList (&Map->Used, &Item->Link);
1383
1384 Map->Count++;
1385 return EFI_SUCCESS;
1386 }
1387
1388
1389 /**
1390 Allocate an item to save the <Key, Value> pair to the tail of the netmap.
1391
1392 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1393 to the tail of the Used doubly linked list. The number of the <Key, Value>
1394 pairs in the netmap increase by 1.
1395
1396 If Map is NULL, then ASSERT().
1397
1398 @param[in, out] Map The netmap to insert into.
1399 @param[in] Key The user's key.
1400 @param[in] Value The user's value for the key.
1401
1402 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1403 @retval EFI_SUCCESS The item is inserted to the tail.
1404
1405 **/
1406 EFI_STATUS
1407 EFIAPI
1408 NetMapInsertTail (
1409 IN OUT NET_MAP *Map,
1410 IN VOID *Key,
1411 IN VOID *Value OPTIONAL
1412 )
1413 {
1414 NET_MAP_ITEM *Item;
1415
1416 ASSERT (Map != NULL);
1417
1418 Item = NetMapAllocItem (Map);
1419
1420 if (Item == NULL) {
1421 return EFI_OUT_OF_RESOURCES;
1422 }
1423
1424 Item->Key = Key;
1425 Item->Value = Value;
1426 InsertTailList (&Map->Used, &Item->Link);
1427
1428 Map->Count++;
1429
1430 return EFI_SUCCESS;
1431 }
1432
1433
1434 /**
1435 Check whether the item is in the Map and return TRUE if it is.
1436
1437 @param[in] Map The netmap to search within.
1438 @param[in] Item The item to search.
1439
1440 @return TRUE if the item is in the netmap, otherwise FALSE.
1441
1442 **/
1443 BOOLEAN
1444 NetItemInMap (
1445 IN NET_MAP *Map,
1446 IN NET_MAP_ITEM *Item
1447 )
1448 {
1449 LIST_ENTRY *ListEntry;
1450
1451 NET_LIST_FOR_EACH (ListEntry, &Map->Used) {
1452 if (ListEntry == &Item->Link) {
1453 return TRUE;
1454 }
1455 }
1456
1457 return FALSE;
1458 }
1459
1460
1461 /**
1462 Find the key in the netmap and returns the point to the item contains the Key.
1463
1464 Iterate the Used doubly linked list of the netmap to get every item. Compare the key of every
1465 item with the key to search. It returns the point to the item contains the Key if found.
1466
1467 If Map is NULL, then ASSERT().
1468
1469 @param[in] Map The netmap to search within.
1470 @param[in] Key The key to search.
1471
1472 @return The point to the item contains the Key, or NULL if Key isn't in the map.
1473
1474 **/
1475 NET_MAP_ITEM *
1476 EFIAPI
1477 NetMapFindKey (
1478 IN NET_MAP *Map,
1479 IN VOID *Key
1480 )
1481 {
1482 LIST_ENTRY *Entry;
1483 NET_MAP_ITEM *Item;
1484
1485 ASSERT (Map != NULL);
1486
1487 NET_LIST_FOR_EACH (Entry, &Map->Used) {
1488 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1489
1490 if (Item->Key == Key) {
1491 return Item;
1492 }
1493 }
1494
1495 return NULL;
1496 }
1497
1498
1499 /**
1500 Remove the node entry of the item from the netmap and return the key of the removed item.
1501
1502 Remove the node entry of the item from the Used doubly linked list of the netmap.
1503 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1504 entry of the item to the Recycled doubly linked list of the netmap. If Value is not NULL,
1505 Value will point to the value of the item. It returns the key of the removed item.
1506
1507 If Map is NULL, then ASSERT().
1508 If Item is NULL, then ASSERT().
1509 if item in not in the netmap, then ASSERT().
1510
1511 @param[in, out] Map The netmap to remove the item from.
1512 @param[in, out] Item The item to remove.
1513 @param[out] Value The variable to receive the value if not NULL.
1514
1515 @return The key of the removed item.
1516
1517 **/
1518 VOID *
1519 EFIAPI
1520 NetMapRemoveItem (
1521 IN OUT NET_MAP *Map,
1522 IN OUT NET_MAP_ITEM *Item,
1523 OUT VOID **Value OPTIONAL
1524 )
1525 {
1526 ASSERT ((Map != NULL) && (Item != NULL));
1527 ASSERT (NetItemInMap (Map, Item));
1528
1529 RemoveEntryList (&Item->Link);
1530 Map->Count--;
1531 InsertHeadList (&Map->Recycled, &Item->Link);
1532
1533 if (Value != NULL) {
1534 *Value = Item->Value;
1535 }
1536
1537 return Item->Key;
1538 }
1539
1540
1541 /**
1542 Remove the first node entry on the netmap and return the key of the removed item.
1543
1544 Remove the first node entry from the Used doubly linked list of the netmap.
1545 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1546 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1547 parameter Value will point to the value of the item. It returns the key of the removed item.
1548
1549 If Map is NULL, then ASSERT().
1550 If the Used doubly linked list is empty, then ASSERT().
1551
1552 @param[in, out] Map The netmap to remove the head from.
1553 @param[out] Value The variable to receive the value if not NULL.
1554
1555 @return The key of the item removed.
1556
1557 **/
1558 VOID *
1559 EFIAPI
1560 NetMapRemoveHead (
1561 IN OUT NET_MAP *Map,
1562 OUT VOID **Value OPTIONAL
1563 )
1564 {
1565 NET_MAP_ITEM *Item;
1566
1567 //
1568 // Often, it indicates a programming error to remove
1569 // the first entry in an empty list
1570 //
1571 ASSERT (Map && !IsListEmpty (&Map->Used));
1572
1573 Item = NET_LIST_HEAD (&Map->Used, NET_MAP_ITEM, Link);
1574 RemoveEntryList (&Item->Link);
1575 Map->Count--;
1576 InsertHeadList (&Map->Recycled, &Item->Link);
1577
1578 if (Value != NULL) {
1579 *Value = Item->Value;
1580 }
1581
1582 return Item->Key;
1583 }
1584
1585
1586 /**
1587 Remove the last node entry on the netmap and return the key of the removed item.
1588
1589 Remove the last node entry from the Used doubly linked list of the netmap.
1590 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1591 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1592 parameter Value will point to the value of the item. It returns the key of the removed item.
1593
1594 If Map is NULL, then ASSERT().
1595 If the Used doubly linked list is empty, then ASSERT().
1596
1597 @param[in, out] Map The netmap to remove the tail from.
1598 @param[out] Value The variable to receive the value if not NULL.
1599
1600 @return The key of the item removed.
1601
1602 **/
1603 VOID *
1604 EFIAPI
1605 NetMapRemoveTail (
1606 IN OUT NET_MAP *Map,
1607 OUT VOID **Value OPTIONAL
1608 )
1609 {
1610 NET_MAP_ITEM *Item;
1611
1612 //
1613 // Often, it indicates a programming error to remove
1614 // the last entry in an empty list
1615 //
1616 ASSERT (Map && !IsListEmpty (&Map->Used));
1617
1618 Item = NET_LIST_TAIL (&Map->Used, NET_MAP_ITEM, Link);
1619 RemoveEntryList (&Item->Link);
1620 Map->Count--;
1621 InsertHeadList (&Map->Recycled, &Item->Link);
1622
1623 if (Value != NULL) {
1624 *Value = Item->Value;
1625 }
1626
1627 return Item->Key;
1628 }
1629
1630
1631 /**
1632 Iterate through the netmap and call CallBack for each item.
1633
1634 It will contiue the traverse if CallBack returns EFI_SUCCESS, otherwise, break
1635 from the loop. It returns the CallBack's last return value. This function is
1636 delete safe for the current item.
1637
1638 If Map is NULL, then ASSERT().
1639 If CallBack is NULL, then ASSERT().
1640
1641 @param[in] Map The Map to iterate through.
1642 @param[in] CallBack The callback function to call for each item.
1643 @param[in] Arg The opaque parameter to the callback.
1644
1645 @retval EFI_SUCCESS There is no item in the netmap or CallBack for each item
1646 return EFI_SUCCESS.
1647 @retval Others It returns the CallBack's last return value.
1648
1649 **/
1650 EFI_STATUS
1651 EFIAPI
1652 NetMapIterate (
1653 IN NET_MAP *Map,
1654 IN NET_MAP_CALLBACK CallBack,
1655 IN VOID *Arg OPTIONAL
1656 )
1657 {
1658
1659 LIST_ENTRY *Entry;
1660 LIST_ENTRY *Next;
1661 LIST_ENTRY *Head;
1662 NET_MAP_ITEM *Item;
1663 EFI_STATUS Result;
1664
1665 ASSERT ((Map != NULL) && (CallBack != NULL));
1666
1667 Head = &Map->Used;
1668
1669 if (IsListEmpty (Head)) {
1670 return EFI_SUCCESS;
1671 }
1672
1673 NET_LIST_FOR_EACH_SAFE (Entry, Next, Head) {
1674 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1675 Result = CallBack (Map, Item, Arg);
1676
1677 if (EFI_ERROR (Result)) {
1678 return Result;
1679 }
1680 }
1681
1682 return EFI_SUCCESS;
1683 }
1684
1685
1686 /**
1687 This is the default unload handle for all the network drivers.
1688
1689 Disconnect the driver specified by ImageHandle from all the devices in the handle database.
1690 Uninstall all the protocols installed in the driver entry point.
1691
1692 @param[in] ImageHandle The drivers' driver image.
1693
1694 @retval EFI_SUCCESS The image is unloaded.
1695 @retval Others Failed to unload the image.
1696
1697 **/
1698 EFI_STATUS
1699 EFIAPI
1700 NetLibDefaultUnload (
1701 IN EFI_HANDLE ImageHandle
1702 )
1703 {
1704 EFI_STATUS Status;
1705 EFI_HANDLE *DeviceHandleBuffer;
1706 UINTN DeviceHandleCount;
1707 UINTN Index;
1708 UINTN Index2;
1709 EFI_DRIVER_BINDING_PROTOCOL *DriverBinding;
1710 EFI_COMPONENT_NAME_PROTOCOL *ComponentName;
1711 EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2;
1712
1713 //
1714 // Get the list of all the handles in the handle database.
1715 // If there is an error getting the list, then the unload
1716 // operation fails.
1717 //
1718 Status = gBS->LocateHandleBuffer (
1719 AllHandles,
1720 NULL,
1721 NULL,
1722 &DeviceHandleCount,
1723 &DeviceHandleBuffer
1724 );
1725
1726 if (EFI_ERROR (Status)) {
1727 return Status;
1728 }
1729
1730 for (Index = 0; Index < DeviceHandleCount; Index++) {
1731 Status = gBS->HandleProtocol (
1732 DeviceHandleBuffer[Index],
1733 &gEfiDriverBindingProtocolGuid,
1734 (VOID **) &DriverBinding
1735 );
1736 if (EFI_ERROR (Status)) {
1737 continue;
1738 }
1739
1740 if (DriverBinding->ImageHandle != ImageHandle) {
1741 continue;
1742 }
1743
1744 //
1745 // Disconnect the driver specified by ImageHandle from all
1746 // the devices in the handle database.
1747 //
1748 for (Index2 = 0; Index2 < DeviceHandleCount; Index2++) {
1749 Status = gBS->DisconnectController (
1750 DeviceHandleBuffer[Index2],
1751 DriverBinding->DriverBindingHandle,
1752 NULL
1753 );
1754 }
1755
1756 //
1757 // Uninstall all the protocols installed in the driver entry point
1758 //
1759 gBS->UninstallProtocolInterface (
1760 DriverBinding->DriverBindingHandle,
1761 &gEfiDriverBindingProtocolGuid,
1762 DriverBinding
1763 );
1764
1765 Status = gBS->HandleProtocol (
1766 DeviceHandleBuffer[Index],
1767 &gEfiComponentNameProtocolGuid,
1768 (VOID **) &ComponentName
1769 );
1770 if (!EFI_ERROR (Status)) {
1771 gBS->UninstallProtocolInterface (
1772 DriverBinding->DriverBindingHandle,
1773 &gEfiComponentNameProtocolGuid,
1774 ComponentName
1775 );
1776 }
1777
1778 Status = gBS->HandleProtocol (
1779 DeviceHandleBuffer[Index],
1780 &gEfiComponentName2ProtocolGuid,
1781 (VOID **) &ComponentName2
1782 );
1783 if (!EFI_ERROR (Status)) {
1784 gBS->UninstallProtocolInterface (
1785 DriverBinding->DriverBindingHandle,
1786 &gEfiComponentName2ProtocolGuid,
1787 ComponentName2
1788 );
1789 }
1790 }
1791
1792 //
1793 // Free the buffer containing the list of handles from the handle database
1794 //
1795 if (DeviceHandleBuffer != NULL) {
1796 gBS->FreePool (DeviceHandleBuffer);
1797 }
1798
1799 return EFI_SUCCESS;
1800 }
1801
1802
1803
1804 /**
1805 Create a child of the service that is identified by ServiceBindingGuid.
1806
1807 Get the ServiceBinding Protocol first, then use it to create a child.
1808
1809 If ServiceBindingGuid is NULL, then ASSERT().
1810 If ChildHandle is NULL, then ASSERT().
1811
1812 @param[in] Controller The controller which has the service installed.
1813 @param[in] Image The image handle used to open service.
1814 @param[in] ServiceBindingGuid The service's Guid.
1815 @param[in, out] ChildHandle The handle to receive the create child.
1816
1817 @retval EFI_SUCCESS The child is successfully created.
1818 @retval Others Failed to create the child.
1819
1820 **/
1821 EFI_STATUS
1822 EFIAPI
1823 NetLibCreateServiceChild (
1824 IN EFI_HANDLE Controller,
1825 IN EFI_HANDLE Image,
1826 IN EFI_GUID *ServiceBindingGuid,
1827 IN OUT EFI_HANDLE *ChildHandle
1828 )
1829 {
1830 EFI_STATUS Status;
1831 EFI_SERVICE_BINDING_PROTOCOL *Service;
1832
1833
1834 ASSERT ((ServiceBindingGuid != NULL) && (ChildHandle != NULL));
1835
1836 //
1837 // Get the ServiceBinding Protocol
1838 //
1839 Status = gBS->OpenProtocol (
1840 Controller,
1841 ServiceBindingGuid,
1842 (VOID **) &Service,
1843 Image,
1844 Controller,
1845 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1846 );
1847
1848 if (EFI_ERROR (Status)) {
1849 return Status;
1850 }
1851
1852 //
1853 // Create a child
1854 //
1855 Status = Service->CreateChild (Service, ChildHandle);
1856 return Status;
1857 }
1858
1859
1860 /**
1861 Destroy a child of the service that is identified by ServiceBindingGuid.
1862
1863 Get the ServiceBinding Protocol first, then use it to destroy a child.
1864
1865 If ServiceBindingGuid is NULL, then ASSERT().
1866
1867 @param[in] Controller The controller which has the service installed.
1868 @param[in] Image The image handle used to open service.
1869 @param[in] ServiceBindingGuid The service's Guid.
1870 @param[in] ChildHandle The child to destroy.
1871
1872 @retval EFI_SUCCESS The child is successfully destroyed.
1873 @retval Others Failed to destroy the child.
1874
1875 **/
1876 EFI_STATUS
1877 EFIAPI
1878 NetLibDestroyServiceChild (
1879 IN EFI_HANDLE Controller,
1880 IN EFI_HANDLE Image,
1881 IN EFI_GUID *ServiceBindingGuid,
1882 IN EFI_HANDLE ChildHandle
1883 )
1884 {
1885 EFI_STATUS Status;
1886 EFI_SERVICE_BINDING_PROTOCOL *Service;
1887
1888 ASSERT (ServiceBindingGuid != NULL);
1889
1890 //
1891 // Get the ServiceBinding Protocol
1892 //
1893 Status = gBS->OpenProtocol (
1894 Controller,
1895 ServiceBindingGuid,
1896 (VOID **) &Service,
1897 Image,
1898 Controller,
1899 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1900 );
1901
1902 if (EFI_ERROR (Status)) {
1903 return Status;
1904 }
1905
1906 //
1907 // destroy the child
1908 //
1909 Status = Service->DestroyChild (Service, ChildHandle);
1910 return Status;
1911 }
1912
1913 /**
1914 Get handle with Simple Network Protocol installed on it.
1915
1916 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
1917 If Simple Network Protocol is already installed on the ServiceHandle, the
1918 ServiceHandle will be returned. If SNP is not installed on the ServiceHandle,
1919 try to find its parent handle with SNP installed.
1920
1921 @param[in] ServiceHandle The handle where network service binding protocols are
1922 installed on.
1923 @param[out] Snp The pointer to store the address of the SNP instance.
1924 This is an optional parameter that may be NULL.
1925
1926 @return The SNP handle, or NULL if not found.
1927
1928 **/
1929 EFI_HANDLE
1930 EFIAPI
1931 NetLibGetSnpHandle (
1932 IN EFI_HANDLE ServiceHandle,
1933 OUT EFI_SIMPLE_NETWORK_PROTOCOL **Snp OPTIONAL
1934 )
1935 {
1936 EFI_STATUS Status;
1937 EFI_SIMPLE_NETWORK_PROTOCOL *SnpInstance;
1938 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1939 EFI_HANDLE SnpHandle;
1940
1941 //
1942 // Try to open SNP from ServiceHandle
1943 //
1944 SnpInstance = NULL;
1945 Status = gBS->HandleProtocol (ServiceHandle, &gEfiSimpleNetworkProtocolGuid, (VOID **) &SnpInstance);
1946 if (!EFI_ERROR (Status)) {
1947 if (Snp != NULL) {
1948 *Snp = SnpInstance;
1949 }
1950 return ServiceHandle;
1951 }
1952
1953 //
1954 // Failed to open SNP, try to get SNP handle by LocateDevicePath()
1955 //
1956 DevicePath = DevicePathFromHandle (ServiceHandle);
1957 if (DevicePath == NULL) {
1958 return NULL;
1959 }
1960
1961 SnpHandle = NULL;
1962 Status = gBS->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid, &DevicePath, &SnpHandle);
1963 if (EFI_ERROR (Status)) {
1964 //
1965 // Failed to find SNP handle
1966 //
1967 return NULL;
1968 }
1969
1970 Status = gBS->HandleProtocol (SnpHandle, &gEfiSimpleNetworkProtocolGuid, (VOID **) &SnpInstance);
1971 if (!EFI_ERROR (Status)) {
1972 if (Snp != NULL) {
1973 *Snp = SnpInstance;
1974 }
1975 return SnpHandle;
1976 }
1977
1978 return NULL;
1979 }
1980
1981 /**
1982 Retrieve VLAN ID of a VLAN device handle.
1983
1984 Search VLAN device path node in Device Path of specified ServiceHandle and
1985 return its VLAN ID. If no VLAN device path node found, then this ServiceHandle
1986 is not a VLAN device handle, and 0 will be returned.
1987
1988 @param[in] ServiceHandle The handle where network service binding protocols are
1989 installed on.
1990
1991 @return VLAN ID of the device handle, or 0 if not a VLAN device.
1992
1993 **/
1994 UINT16
1995 EFIAPI
1996 NetLibGetVlanId (
1997 IN EFI_HANDLE ServiceHandle
1998 )
1999 {
2000 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2001 EFI_DEVICE_PATH_PROTOCOL *Node;
2002
2003 DevicePath = DevicePathFromHandle (ServiceHandle);
2004 if (DevicePath == NULL) {
2005 return 0;
2006 }
2007
2008 Node = DevicePath;
2009 while (!IsDevicePathEnd (Node)) {
2010 if (Node->Type == MESSAGING_DEVICE_PATH && Node->SubType == MSG_VLAN_DP) {
2011 return ((VLAN_DEVICE_PATH *) Node)->VlanId;
2012 }
2013 Node = NextDevicePathNode (Node);
2014 }
2015
2016 return 0;
2017 }
2018
2019 /**
2020 Find VLAN device handle with specified VLAN ID.
2021
2022 The VLAN child device handle is created by VLAN Config Protocol on ControllerHandle.
2023 This function will append VLAN device path node to the parent device path,
2024 and then use LocateDevicePath() to find the correct VLAN device handle.
2025
2026 @param[in] ControllerHandle The handle where network service binding protocols are
2027 installed on.
2028 @param[in] VlanId The configured VLAN ID for the VLAN device.
2029
2030 @return The VLAN device handle, or NULL if not found.
2031
2032 **/
2033 EFI_HANDLE
2034 EFIAPI
2035 NetLibGetVlanHandle (
2036 IN EFI_HANDLE ControllerHandle,
2037 IN UINT16 VlanId
2038 )
2039 {
2040 EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath;
2041 EFI_DEVICE_PATH_PROTOCOL *VlanDevicePath;
2042 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2043 VLAN_DEVICE_PATH VlanNode;
2044 EFI_HANDLE Handle;
2045
2046 ParentDevicePath = DevicePathFromHandle (ControllerHandle);
2047 if (ParentDevicePath == NULL) {
2048 return NULL;
2049 }
2050
2051 //
2052 // Construct VLAN device path
2053 //
2054 CopyMem (&VlanNode, &mNetVlanDevicePathTemplate, sizeof (VLAN_DEVICE_PATH));
2055 VlanNode.VlanId = VlanId;
2056 VlanDevicePath = AppendDevicePathNode (
2057 ParentDevicePath,
2058 (EFI_DEVICE_PATH_PROTOCOL *) &VlanNode
2059 );
2060 if (VlanDevicePath == NULL) {
2061 return NULL;
2062 }
2063
2064 //
2065 // Find VLAN device handle
2066 //
2067 Handle = NULL;
2068 DevicePath = VlanDevicePath;
2069 gBS->LocateDevicePath (
2070 &gEfiDevicePathProtocolGuid,
2071 &DevicePath,
2072 &Handle
2073 );
2074 if (!IsDevicePathEnd (DevicePath)) {
2075 //
2076 // Device path is not exactly match
2077 //
2078 Handle = NULL;
2079 }
2080
2081 FreePool (VlanDevicePath);
2082 return Handle;
2083 }
2084
2085 /**
2086 Get MAC address associated with the network service handle.
2087
2088 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
2089 If SNP is installed on the ServiceHandle or its parent handle, MAC address will
2090 be retrieved from SNP. If no SNP found, try to get SNP mode data use MNP.
2091
2092 @param[in] ServiceHandle The handle where network service binding protocols are
2093 installed on.
2094 @param[out] MacAddress The pointer to store the returned MAC address.
2095 @param[out] AddressSize The length of returned MAC address.
2096
2097 @retval EFI_SUCCESS MAC address is returned successfully.
2098 @retval Others Failed to get SNP mode data.
2099
2100 **/
2101 EFI_STATUS
2102 EFIAPI
2103 NetLibGetMacAddress (
2104 IN EFI_HANDLE ServiceHandle,
2105 OUT EFI_MAC_ADDRESS *MacAddress,
2106 OUT UINTN *AddressSize
2107 )
2108 {
2109 EFI_STATUS Status;
2110 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
2111 EFI_SIMPLE_NETWORK_MODE *SnpMode;
2112 EFI_SIMPLE_NETWORK_MODE SnpModeData;
2113 EFI_MANAGED_NETWORK_PROTOCOL *Mnp;
2114 EFI_SERVICE_BINDING_PROTOCOL *MnpSb;
2115 EFI_HANDLE *SnpHandle;
2116 EFI_HANDLE MnpChildHandle;
2117
2118 ASSERT (MacAddress != NULL);
2119 ASSERT (AddressSize != NULL);
2120
2121 //
2122 // Try to get SNP handle
2123 //
2124 Snp = NULL;
2125 SnpHandle = NetLibGetSnpHandle (ServiceHandle, &Snp);
2126 if (SnpHandle != NULL) {
2127 //
2128 // SNP found, use it directly
2129 //
2130 SnpMode = Snp->Mode;
2131 } else {
2132 //
2133 // Failed to get SNP handle, try to get MAC address from MNP
2134 //
2135 MnpChildHandle = NULL;
2136 Status = gBS->HandleProtocol (
2137 ServiceHandle,
2138 &gEfiManagedNetworkServiceBindingProtocolGuid,
2139 (VOID **) &MnpSb
2140 );
2141 if (EFI_ERROR (Status)) {
2142 return Status;
2143 }
2144
2145 //
2146 // Create a MNP child
2147 //
2148 Status = MnpSb->CreateChild (MnpSb, &MnpChildHandle);
2149 if (EFI_ERROR (Status)) {
2150 return Status;
2151 }
2152
2153 //
2154 // Open MNP protocol
2155 //
2156 Status = gBS->HandleProtocol (
2157 MnpChildHandle,
2158 &gEfiManagedNetworkProtocolGuid,
2159 (VOID **) &Mnp
2160 );
2161 if (EFI_ERROR (Status)) {
2162 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2163 return Status;
2164 }
2165
2166 //
2167 // Try to get SNP mode from MNP
2168 //
2169 Status = Mnp->GetModeData (Mnp, NULL, &SnpModeData);
2170 if (EFI_ERROR (Status) && (Status != EFI_NOT_STARTED)) {
2171 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2172 return Status;
2173 }
2174 SnpMode = &SnpModeData;
2175
2176 //
2177 // Destroy the MNP child
2178 //
2179 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2180 }
2181
2182 *AddressSize = SnpMode->HwAddressSize;
2183 CopyMem (MacAddress->Addr, SnpMode->CurrentAddress.Addr, SnpMode->HwAddressSize);
2184
2185 return EFI_SUCCESS;
2186 }
2187
2188 /**
2189 Convert MAC address of the NIC associated with specified Service Binding Handle
2190 to a unicode string. Callers are responsible for freeing the string storage.
2191
2192 Locate simple network protocol associated with the Service Binding Handle and
2193 get the mac address from SNP. Then convert the mac address into a unicode
2194 string. It takes 2 unicode characters to represent a 1 byte binary buffer.
2195 Plus one unicode character for the null-terminator.
2196
2197 @param[in] ServiceHandle The handle where network service binding protocol is
2198 installed on.
2199 @param[in] ImageHandle The image handle used to act as the agent handle to
2200 get the simple network protocol. This parameter is
2201 optional and may be NULL.
2202 @param[out] MacString The pointer to store the address of the string
2203 representation of the mac address.
2204
2205 @retval EFI_SUCCESS Convert the mac address a unicode string successfully.
2206 @retval EFI_OUT_OF_RESOURCES There are not enough memory resource.
2207 @retval Others Failed to open the simple network protocol.
2208
2209 **/
2210 EFI_STATUS
2211 EFIAPI
2212 NetLibGetMacString (
2213 IN EFI_HANDLE ServiceHandle,
2214 IN EFI_HANDLE ImageHandle, OPTIONAL
2215 OUT CHAR16 **MacString
2216 )
2217 {
2218 EFI_STATUS Status;
2219 EFI_MAC_ADDRESS MacAddress;
2220 UINT8 *HwAddress;
2221 UINTN HwAddressSize;
2222 UINT16 VlanId;
2223 CHAR16 *String;
2224 UINTN Index;
2225
2226 ASSERT (MacString != NULL);
2227
2228 //
2229 // Get MAC address of the network device
2230 //
2231 Status = NetLibGetMacAddress (ServiceHandle, &MacAddress, &HwAddressSize);
2232 if (EFI_ERROR (Status)) {
2233 return Status;
2234 }
2235
2236 //
2237 // It takes 2 unicode characters to represent a 1 byte binary buffer.
2238 // If VLAN is configured, it will need extra 5 characters like "\0005".
2239 // Plus one unicode character for the null-terminator.
2240 //
2241 String = AllocateZeroPool ((2 * HwAddressSize + 5 + 1) * sizeof (CHAR16));
2242 if (String == NULL) {
2243 return EFI_OUT_OF_RESOURCES;
2244 }
2245 *MacString = String;
2246
2247 //
2248 // Convert the MAC address into a unicode string.
2249 //
2250 HwAddress = &MacAddress.Addr[0];
2251 for (Index = 0; Index < HwAddressSize; Index++) {
2252 String += UnicodeValueToString (String, PREFIX_ZERO | RADIX_HEX, *(HwAddress++), 2);
2253 }
2254
2255 //
2256 // Append VLAN ID if any
2257 //
2258 VlanId = NetLibGetVlanId (ServiceHandle);
2259 if (VlanId != 0) {
2260 *String++ = L'\\';
2261 String += UnicodeValueToString (String, PREFIX_ZERO | RADIX_HEX, VlanId, 4);
2262 }
2263
2264 //
2265 // Null terminate the Unicode string
2266 //
2267 *String = L'\0';
2268
2269 return EFI_SUCCESS;
2270 }
2271
2272 /**
2273 Detect media status for specified network device.
2274
2275 The underlying UNDI driver may or may not support reporting media status from
2276 GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine
2277 will try to invoke Snp->GetStatus() to get the media status: if media already
2278 present, it return directly; if media not present, it will stop SNP and then
2279 restart SNP to get the latest media status, this give chance to get the correct
2280 media status for old UNDI driver which doesn't support reporting media status
2281 from GET_STATUS command.
2282 Note: there will be two limitations for current algorithm:
2283 1) for UNDI with this capability, in case of cable is not attached, there will
2284 be an redundant Stop/Start() process;
2285 2) for UNDI without this capability, in case that network cable is attached when
2286 Snp->Initialize() is invoked while network cable is unattached later,
2287 NetLibDetectMedia() will report MediaPresent as TRUE, causing upper layer
2288 apps to wait for timeout time.
2289
2290 @param[in] ServiceHandle The handle where network service binding protocols are
2291 installed on.
2292 @param[out] MediaPresent The pointer to store the media status.
2293
2294 @retval EFI_SUCCESS Media detection success.
2295 @retval EFI_INVALID_PARAMETER ServiceHandle is not valid network device handle.
2296 @retval EFI_UNSUPPORTED Network device does not support media detection.
2297 @retval EFI_DEVICE_ERROR SNP is in unknown state.
2298
2299 **/
2300 EFI_STATUS
2301 EFIAPI
2302 NetLibDetectMedia (
2303 IN EFI_HANDLE ServiceHandle,
2304 OUT BOOLEAN *MediaPresent
2305 )
2306 {
2307 EFI_STATUS Status;
2308 EFI_HANDLE SnpHandle;
2309 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
2310 UINT32 InterruptStatus;
2311 UINT32 OldState;
2312 EFI_MAC_ADDRESS *MCastFilter;
2313 UINT32 MCastFilterCount;
2314 UINT32 EnableFilterBits;
2315 UINT32 DisableFilterBits;
2316 BOOLEAN ResetMCastFilters;
2317
2318 ASSERT (MediaPresent != NULL);
2319
2320 //
2321 // Get SNP handle
2322 //
2323 Snp = NULL;
2324 SnpHandle = NetLibGetSnpHandle (ServiceHandle, &Snp);
2325 if (SnpHandle == NULL) {
2326 return EFI_INVALID_PARAMETER;
2327 }
2328
2329 //
2330 // Check whether SNP support media detection
2331 //
2332 if (!Snp->Mode->MediaPresentSupported) {
2333 return EFI_UNSUPPORTED;
2334 }
2335
2336 //
2337 // Invoke Snp->GetStatus() to refresh MediaPresent field in SNP mode data
2338 //
2339 Status = Snp->GetStatus (Snp, &InterruptStatus, NULL);
2340 if (EFI_ERROR (Status)) {
2341 return Status;
2342 }
2343
2344 if (Snp->Mode->MediaPresent) {
2345 //
2346 // Media is present, return directly
2347 //
2348 *MediaPresent = TRUE;
2349 return EFI_SUCCESS;
2350 }
2351
2352 //
2353 // Till now, GetStatus() report no media; while, in case UNDI not support
2354 // reporting media status from GetStatus(), this media status may be incorrect.
2355 // So, we will stop SNP and then restart it to get the correct media status.
2356 //
2357 OldState = Snp->Mode->State;
2358 if (OldState >= EfiSimpleNetworkMaxState) {
2359 return EFI_DEVICE_ERROR;
2360 }
2361
2362 MCastFilter = NULL;
2363
2364 if (OldState == EfiSimpleNetworkInitialized) {
2365 //
2366 // SNP is already in use, need Shutdown/Stop and then Start/Initialize
2367 //
2368
2369 //
2370 // Backup current SNP receive filter settings
2371 //
2372 EnableFilterBits = Snp->Mode->ReceiveFilterSetting;
2373 DisableFilterBits = Snp->Mode->ReceiveFilterMask ^ EnableFilterBits;
2374
2375 ResetMCastFilters = TRUE;
2376 MCastFilterCount = Snp->Mode->MCastFilterCount;
2377 if (MCastFilterCount != 0) {
2378 MCastFilter = AllocateCopyPool (
2379 MCastFilterCount * sizeof (EFI_MAC_ADDRESS),
2380 Snp->Mode->MCastFilter
2381 );
2382 ASSERT (MCastFilter != NULL);
2383
2384 ResetMCastFilters = FALSE;
2385 }
2386
2387 //
2388 // Shutdown/Stop the simple network
2389 //
2390 Status = Snp->Shutdown (Snp);
2391 if (!EFI_ERROR (Status)) {
2392 Status = Snp->Stop (Snp);
2393 }
2394 if (EFI_ERROR (Status)) {
2395 goto Exit;
2396 }
2397
2398 //
2399 // Start/Initialize the simple network
2400 //
2401 Status = Snp->Start (Snp);
2402 if (!EFI_ERROR (Status)) {
2403 Status = Snp->Initialize (Snp, 0, 0);
2404 }
2405 if (EFI_ERROR (Status)) {
2406 goto Exit;
2407 }
2408
2409 //
2410 // Here we get the correct media status
2411 //
2412 *MediaPresent = Snp->Mode->MediaPresent;
2413
2414 //
2415 // Restore SNP receive filter settings
2416 //
2417 Status = Snp->ReceiveFilters (
2418 Snp,
2419 EnableFilterBits,
2420 DisableFilterBits,
2421 ResetMCastFilters,
2422 MCastFilterCount,
2423 MCastFilter
2424 );
2425
2426 if (MCastFilter != NULL) {
2427 FreePool (MCastFilter);
2428 }
2429
2430 return Status;
2431 }
2432
2433 //
2434 // SNP is not in use, it's in state of EfiSimpleNetworkStopped or EfiSimpleNetworkStarted
2435 //
2436 if (OldState == EfiSimpleNetworkStopped) {
2437 //
2438 // SNP not start yet, start it
2439 //
2440 Status = Snp->Start (Snp);
2441 if (EFI_ERROR (Status)) {
2442 goto Exit;
2443 }
2444 }
2445
2446 //
2447 // Initialize the simple network
2448 //
2449 Status = Snp->Initialize (Snp, 0, 0);
2450 if (EFI_ERROR (Status)) {
2451 Status = EFI_DEVICE_ERROR;
2452 goto Exit;
2453 }
2454
2455 //
2456 // Here we get the correct media status
2457 //
2458 *MediaPresent = Snp->Mode->MediaPresent;
2459
2460 //
2461 // Shut down the simple network
2462 //
2463 Snp->Shutdown (Snp);
2464
2465 Exit:
2466 if (OldState == EfiSimpleNetworkStopped) {
2467 //
2468 // Original SNP sate is Stopped, restore to original state
2469 //
2470 Snp->Stop (Snp);
2471 }
2472
2473 if (MCastFilter != NULL) {
2474 FreePool (MCastFilter);
2475 }
2476
2477 return Status;
2478 }
2479
2480 /**
2481 Check the default address used by the IPv4 driver is static or dynamic (acquired
2482 from DHCP).
2483
2484 If the controller handle does not have the EFI_IP4_CONFIG2_PROTOCOL installed, the
2485 default address is static. If failed to get the policy from Ip4 Config2 Protocol,
2486 the default address is static. Otherwise, get the result from Ip4 Config2 Protocol.
2487
2488 @param[in] Controller The controller handle which has the EFI_IP4_CONFIG2_PROTOCOL
2489 relative with the default address to judge.
2490
2491 @retval TRUE If the default address is static.
2492 @retval FALSE If the default address is acquired from DHCP.
2493
2494 **/
2495 BOOLEAN
2496 NetLibDefaultAddressIsStatic (
2497 IN EFI_HANDLE Controller
2498 )
2499 {
2500 EFI_STATUS Status;
2501 EFI_IP4_CONFIG2_PROTOCOL *Ip4Config2;
2502 UINTN DataSize;
2503 EFI_IP4_CONFIG2_POLICY Policy;
2504 BOOLEAN IsStatic;
2505
2506 Ip4Config2 = NULL;
2507
2508 DataSize = sizeof (EFI_IP4_CONFIG2_POLICY);
2509
2510 IsStatic = TRUE;
2511
2512 //
2513 // Get Ip4Config2 policy.
2514 //
2515 Status = gBS->HandleProtocol (Controller, &gEfiIp4Config2ProtocolGuid, (VOID **) &Ip4Config2);
2516 if (EFI_ERROR (Status)) {
2517 goto ON_EXIT;
2518 }
2519
2520 Status = Ip4Config2->GetData (Ip4Config2, Ip4Config2DataTypePolicy, &DataSize, &Policy);
2521 if (EFI_ERROR (Status)) {
2522 goto ON_EXIT;
2523 }
2524
2525 IsStatic = (BOOLEAN) (Policy == Ip4Config2PolicyStatic);
2526
2527 ON_EXIT:
2528
2529 return IsStatic;
2530 }
2531
2532 /**
2533 Create an IPv4 device path node.
2534
2535 The header type of IPv4 device path node is MESSAGING_DEVICE_PATH.
2536 The header subtype of IPv4 device path node is MSG_IPv4_DP.
2537 Get other info from parameters to make up the whole IPv4 device path node.
2538
2539 @param[in, out] Node Pointer to the IPv4 device path node.
2540 @param[in] Controller The controller handle.
2541 @param[in] LocalIp The local IPv4 address.
2542 @param[in] LocalPort The local port.
2543 @param[in] RemoteIp The remote IPv4 address.
2544 @param[in] RemotePort The remote port.
2545 @param[in] Protocol The protocol type in the IP header.
2546 @param[in] UseDefaultAddress Whether this instance is using default address or not.
2547
2548 **/
2549 VOID
2550 EFIAPI
2551 NetLibCreateIPv4DPathNode (
2552 IN OUT IPv4_DEVICE_PATH *Node,
2553 IN EFI_HANDLE Controller,
2554 IN IP4_ADDR LocalIp,
2555 IN UINT16 LocalPort,
2556 IN IP4_ADDR RemoteIp,
2557 IN UINT16 RemotePort,
2558 IN UINT16 Protocol,
2559 IN BOOLEAN UseDefaultAddress
2560 )
2561 {
2562 Node->Header.Type = MESSAGING_DEVICE_PATH;
2563 Node->Header.SubType = MSG_IPv4_DP;
2564 SetDevicePathNodeLength (&Node->Header, sizeof (IPv4_DEVICE_PATH));
2565
2566 CopyMem (&Node->LocalIpAddress, &LocalIp, sizeof (EFI_IPv4_ADDRESS));
2567 CopyMem (&Node->RemoteIpAddress, &RemoteIp, sizeof (EFI_IPv4_ADDRESS));
2568
2569 Node->LocalPort = LocalPort;
2570 Node->RemotePort = RemotePort;
2571
2572 Node->Protocol = Protocol;
2573
2574 if (!UseDefaultAddress) {
2575 Node->StaticIpAddress = TRUE;
2576 } else {
2577 Node->StaticIpAddress = NetLibDefaultAddressIsStatic (Controller);
2578 }
2579
2580 //
2581 // Set the Gateway IP address to default value 0:0:0:0.
2582 // Set the Subnet mask to default value 255:255:255:0.
2583 //
2584 ZeroMem (&Node->GatewayIpAddress, sizeof (EFI_IPv4_ADDRESS));
2585 SetMem (&Node->SubnetMask, sizeof (EFI_IPv4_ADDRESS), 0xff);
2586 Node->SubnetMask.Addr[3] = 0;
2587 }
2588
2589 /**
2590 Create an IPv6 device path node.
2591
2592 The header type of IPv6 device path node is MESSAGING_DEVICE_PATH.
2593 The header subtype of IPv6 device path node is MSG_IPv6_DP.
2594 Get other info from parameters to make up the whole IPv6 device path node.
2595
2596 @param[in, out] Node Pointer to the IPv6 device path node.
2597 @param[in] Controller The controller handle.
2598 @param[in] LocalIp The local IPv6 address.
2599 @param[in] LocalPort The local port.
2600 @param[in] RemoteIp The remote IPv6 address.
2601 @param[in] RemotePort The remote port.
2602 @param[in] Protocol The protocol type in the IP header.
2603
2604 **/
2605 VOID
2606 EFIAPI
2607 NetLibCreateIPv6DPathNode (
2608 IN OUT IPv6_DEVICE_PATH *Node,
2609 IN EFI_HANDLE Controller,
2610 IN EFI_IPv6_ADDRESS *LocalIp,
2611 IN UINT16 LocalPort,
2612 IN EFI_IPv6_ADDRESS *RemoteIp,
2613 IN UINT16 RemotePort,
2614 IN UINT16 Protocol
2615 )
2616 {
2617 Node->Header.Type = MESSAGING_DEVICE_PATH;
2618 Node->Header.SubType = MSG_IPv6_DP;
2619 SetDevicePathNodeLength (&Node->Header, sizeof (IPv6_DEVICE_PATH));
2620
2621 CopyMem (&Node->LocalIpAddress, LocalIp, sizeof (EFI_IPv6_ADDRESS));
2622 CopyMem (&Node->RemoteIpAddress, RemoteIp, sizeof (EFI_IPv6_ADDRESS));
2623
2624 Node->LocalPort = LocalPort;
2625 Node->RemotePort = RemotePort;
2626
2627 Node->Protocol = Protocol;
2628
2629 //
2630 // Set default value to IPAddressOrigin, PrefixLength.
2631 // Set the Gateway IP address to unspecified address.
2632 //
2633 Node->IpAddressOrigin = 0;
2634 Node->PrefixLength = IP6_PREFIX_LENGTH;
2635 ZeroMem (&Node->GatewayIpAddress, sizeof (EFI_IPv6_ADDRESS));
2636 }
2637
2638 /**
2639 Find the UNDI/SNP handle from controller and protocol GUID.
2640
2641 For example, IP will open a MNP child to transmit/receive
2642 packets, when MNP is stopped, IP should also be stopped. IP
2643 needs to find its own private data which is related the IP's
2644 service binding instance that is install on UNDI/SNP handle.
2645 Now, the controller is either a MNP or ARP child handle. But
2646 IP opens these handle BY_DRIVER, use that info, we can get the
2647 UNDI/SNP handle.
2648
2649 @param[in] Controller Then protocol handle to check.
2650 @param[in] ProtocolGuid The protocol that is related with the handle.
2651
2652 @return The UNDI/SNP handle or NULL for errors.
2653
2654 **/
2655 EFI_HANDLE
2656 EFIAPI
2657 NetLibGetNicHandle (
2658 IN EFI_HANDLE Controller,
2659 IN EFI_GUID *ProtocolGuid
2660 )
2661 {
2662 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenBuffer;
2663 EFI_HANDLE Handle;
2664 EFI_STATUS Status;
2665 UINTN OpenCount;
2666 UINTN Index;
2667
2668 Status = gBS->OpenProtocolInformation (
2669 Controller,
2670 ProtocolGuid,
2671 &OpenBuffer,
2672 &OpenCount
2673 );
2674
2675 if (EFI_ERROR (Status)) {
2676 return NULL;
2677 }
2678
2679 Handle = NULL;
2680
2681 for (Index = 0; Index < OpenCount; Index++) {
2682 if ((OpenBuffer[Index].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) {
2683 Handle = OpenBuffer[Index].ControllerHandle;
2684 break;
2685 }
2686 }
2687
2688 gBS->FreePool (OpenBuffer);
2689 return Handle;
2690 }
2691
2692 /**
2693 Convert one Null-terminated ASCII string (decimal dotted) to EFI_IPv4_ADDRESS.
2694
2695 @param[in] String The pointer to the Ascii string.
2696 @param[out] Ip4Address The pointer to the converted IPv4 address.
2697
2698 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2699 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2700
2701 **/
2702 EFI_STATUS
2703 EFIAPI
2704 NetLibAsciiStrToIp4 (
2705 IN CONST CHAR8 *String,
2706 OUT EFI_IPv4_ADDRESS *Ip4Address
2707 )
2708 {
2709 UINT8 Index;
2710 CHAR8 *Ip4Str;
2711 CHAR8 *TempStr;
2712 UINTN NodeVal;
2713
2714 if ((String == NULL) || (Ip4Address == NULL)) {
2715 return EFI_INVALID_PARAMETER;
2716 }
2717
2718 Ip4Str = (CHAR8 *) String;
2719
2720 for (Index = 0; Index < 4; Index++) {
2721 TempStr = Ip4Str;
2722
2723 while ((*Ip4Str != '\0') && (*Ip4Str != '.')) {
2724 Ip4Str++;
2725 }
2726
2727 //
2728 // The IPv4 address is X.X.X.X
2729 //
2730 if (*Ip4Str == '.') {
2731 if (Index == 3) {
2732 return EFI_INVALID_PARAMETER;
2733 }
2734 } else {
2735 if (Index != 3) {
2736 return EFI_INVALID_PARAMETER;
2737 }
2738 }
2739
2740 //
2741 // Convert the string to IPv4 address. AsciiStrDecimalToUintn stops at the
2742 // first character that is not a valid decimal character, '.' or '\0' here.
2743 //
2744 NodeVal = AsciiStrDecimalToUintn (TempStr);
2745 if (NodeVal > 0xFF) {
2746 return EFI_INVALID_PARAMETER;
2747 }
2748
2749 Ip4Address->Addr[Index] = (UINT8) NodeVal;
2750
2751 Ip4Str++;
2752 }
2753
2754 return EFI_SUCCESS;
2755 }
2756
2757
2758 /**
2759 Convert one Null-terminated ASCII string to EFI_IPv6_ADDRESS. The format of the
2760 string is defined in RFC 4291 - Text Pepresentation of Addresses.
2761
2762 @param[in] String The pointer to the Ascii string.
2763 @param[out] Ip6Address The pointer to the converted IPv6 address.
2764
2765 @retval EFI_SUCCESS Convert to IPv6 address successfully.
2766 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
2767
2768 **/
2769 EFI_STATUS
2770 EFIAPI
2771 NetLibAsciiStrToIp6 (
2772 IN CONST CHAR8 *String,
2773 OUT EFI_IPv6_ADDRESS *Ip6Address
2774 )
2775 {
2776 UINT8 Index;
2777 CHAR8 *Ip6Str;
2778 CHAR8 *TempStr;
2779 CHAR8 *TempStr2;
2780 UINT8 NodeCnt;
2781 UINT8 TailNodeCnt;
2782 UINT8 AllowedCnt;
2783 UINTN NodeVal;
2784 BOOLEAN Short;
2785 BOOLEAN Update;
2786 BOOLEAN LeadZero;
2787 UINT8 LeadZeroCnt;
2788 UINT8 Cnt;
2789
2790 if ((String == NULL) || (Ip6Address == NULL)) {
2791 return EFI_INVALID_PARAMETER;
2792 }
2793
2794 Ip6Str = (CHAR8 *) String;
2795 AllowedCnt = 6;
2796 LeadZeroCnt = 0;
2797
2798 //
2799 // An IPv6 address leading with : looks strange.
2800 //
2801 if (*Ip6Str == ':') {
2802 if (*(Ip6Str + 1) != ':') {
2803 return EFI_INVALID_PARAMETER;
2804 } else {
2805 AllowedCnt = 7;
2806 }
2807 }
2808
2809 ZeroMem (Ip6Address, sizeof (EFI_IPv6_ADDRESS));
2810
2811 NodeCnt = 0;
2812 TailNodeCnt = 0;
2813 Short = FALSE;
2814 Update = FALSE;
2815 LeadZero = FALSE;
2816
2817 for (Index = 0; Index < 15; Index = (UINT8) (Index + 2)) {
2818 TempStr = Ip6Str;
2819
2820 while ((*Ip6Str != '\0') && (*Ip6Str != ':')) {
2821 Ip6Str++;
2822 }
2823
2824 if ((*Ip6Str == '\0') && (Index != 14)) {
2825 return EFI_INVALID_PARAMETER;
2826 }
2827
2828 if (*Ip6Str == ':') {
2829 if (*(Ip6Str + 1) == ':') {
2830 if ((NodeCnt > 6) ||
2831 ((*(Ip6Str + 2) != '\0') && (AsciiStrHexToUintn (Ip6Str + 2) == 0))) {
2832 //
2833 // ::0 looks strange. report error to user.
2834 //
2835 return EFI_INVALID_PARAMETER;
2836 }
2837 if ((NodeCnt == 6) && (*(Ip6Str + 2) != '\0') &&
2838 (AsciiStrHexToUintn (Ip6Str + 2) != 0)) {
2839 return EFI_INVALID_PARAMETER;
2840 }
2841
2842 //
2843 // Skip the abbreviation part of IPv6 address.
2844 //
2845 TempStr2 = Ip6Str + 2;
2846 while ((*TempStr2 != '\0')) {
2847 if (*TempStr2 == ':') {
2848 if (*(TempStr2 + 1) == ':') {
2849 //
2850 // :: can only appear once in IPv6 address.
2851 //
2852 return EFI_INVALID_PARAMETER;
2853 }
2854
2855 TailNodeCnt++;
2856 if (TailNodeCnt >= (AllowedCnt - NodeCnt)) {
2857 //
2858 // :: indicates one or more groups of 16 bits of zeros.
2859 //
2860 return EFI_INVALID_PARAMETER;
2861 }
2862 }
2863
2864 TempStr2++;
2865 }
2866
2867 Short = TRUE;
2868 Update = TRUE;
2869
2870 Ip6Str = Ip6Str + 2;
2871 } else {
2872 if (*(Ip6Str + 1) == '\0') {
2873 return EFI_INVALID_PARAMETER;
2874 }
2875 Ip6Str++;
2876 NodeCnt++;
2877 if ((Short && (NodeCnt > 6)) || (!Short && (NodeCnt > 7))) {
2878 //
2879 // There are more than 8 groups of 16 bits of zeros.
2880 //
2881 return EFI_INVALID_PARAMETER;
2882 }
2883 }
2884 }
2885
2886 //
2887 // Convert the string to IPv6 address. AsciiStrHexToUintn stops at the first
2888 // character that is not a valid hexadecimal character, ':' or '\0' here.
2889 //
2890 NodeVal = AsciiStrHexToUintn (TempStr);
2891 if ((NodeVal > 0xFFFF) || (Index > 14)) {
2892 return EFI_INVALID_PARAMETER;
2893 }
2894 if (NodeVal != 0) {
2895 if ((*TempStr == '0') &&
2896 ((*(TempStr + 2) == ':') || (*(TempStr + 3) == ':') ||
2897 (*(TempStr + 2) == '\0') || (*(TempStr + 3) == '\0'))) {
2898 return EFI_INVALID_PARAMETER;
2899 }
2900 if ((*TempStr == '0') && (*(TempStr + 4) != '\0') &&
2901 (*(TempStr + 4) != ':')) {
2902 return EFI_INVALID_PARAMETER;
2903 }
2904 } else {
2905 if (((*TempStr == '0') && (*(TempStr + 1) == '0') &&
2906 ((*(TempStr + 2) == ':') || (*(TempStr + 2) == '\0'))) ||
2907 ((*TempStr == '0') && (*(TempStr + 1) == '0') && (*(TempStr + 2) == '0') &&
2908 ((*(TempStr + 3) == ':') || (*(TempStr + 3) == '\0')))) {
2909 return EFI_INVALID_PARAMETER;
2910 }
2911 }
2912
2913 Cnt = 0;
2914 while ((TempStr[Cnt] != ':') && (TempStr[Cnt] != '\0')) {
2915 Cnt++;
2916 }
2917 if (LeadZeroCnt == 0) {
2918 if ((Cnt == 4) && (*TempStr == '0')) {
2919 LeadZero = TRUE;
2920 LeadZeroCnt++;
2921 }
2922 if ((Cnt != 0) && (Cnt < 4)) {
2923 LeadZero = FALSE;
2924 LeadZeroCnt++;
2925 }
2926 } else {
2927 if ((Cnt == 4) && (*TempStr == '0') && !LeadZero) {
2928 return EFI_INVALID_PARAMETER;
2929 }
2930 if ((Cnt != 0) && (Cnt < 4) && LeadZero) {
2931 return EFI_INVALID_PARAMETER;
2932 }
2933 }
2934
2935 Ip6Address->Addr[Index] = (UINT8) (NodeVal >> 8);
2936 Ip6Address->Addr[Index + 1] = (UINT8) (NodeVal & 0xFF);
2937
2938 //
2939 // Skip the groups of zeros by ::
2940 //
2941 if (Short && Update) {
2942 Index = (UINT8) (16 - (TailNodeCnt + 2) * 2);
2943 Update = FALSE;
2944 }
2945 }
2946
2947 if ((!Short && Index != 16) || (*Ip6Str != '\0')) {
2948 return EFI_INVALID_PARAMETER;
2949 }
2950
2951 return EFI_SUCCESS;
2952 }
2953
2954
2955 /**
2956 Convert one Null-terminated Unicode string (decimal dotted) to EFI_IPv4_ADDRESS.
2957
2958 @param[in] String The pointer to the Ascii string.
2959 @param[out] Ip4Address The pointer to the converted IPv4 address.
2960
2961 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2962 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2963 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
2964
2965 **/
2966 EFI_STATUS
2967 EFIAPI
2968 NetLibStrToIp4 (
2969 IN CONST CHAR16 *String,
2970 OUT EFI_IPv4_ADDRESS *Ip4Address
2971 )
2972 {
2973 CHAR8 *Ip4Str;
2974 EFI_STATUS Status;
2975
2976 if ((String == NULL) || (Ip4Address == NULL)) {
2977 return EFI_INVALID_PARAMETER;
2978 }
2979
2980 Ip4Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8));
2981 if (Ip4Str == NULL) {
2982 return EFI_OUT_OF_RESOURCES;
2983 }
2984
2985 UnicodeStrToAsciiStr (String, Ip4Str);
2986
2987 Status = NetLibAsciiStrToIp4 (Ip4Str, Ip4Address);
2988
2989 FreePool (Ip4Str);
2990
2991 return Status;
2992 }
2993
2994
2995 /**
2996 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS. The format of
2997 the string is defined in RFC 4291 - Text Pepresentation of Addresses.
2998
2999 @param[in] String The pointer to the Ascii string.
3000 @param[out] Ip6Address The pointer to the converted IPv6 address.
3001
3002 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3003 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3004 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3005
3006 **/
3007 EFI_STATUS
3008 EFIAPI
3009 NetLibStrToIp6 (
3010 IN CONST CHAR16 *String,
3011 OUT EFI_IPv6_ADDRESS *Ip6Address
3012 )
3013 {
3014 CHAR8 *Ip6Str;
3015 EFI_STATUS Status;
3016
3017 if ((String == NULL) || (Ip6Address == NULL)) {
3018 return EFI_INVALID_PARAMETER;
3019 }
3020
3021 Ip6Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8));
3022 if (Ip6Str == NULL) {
3023 return EFI_OUT_OF_RESOURCES;
3024 }
3025
3026 UnicodeStrToAsciiStr (String, Ip6Str);
3027
3028 Status = NetLibAsciiStrToIp6 (Ip6Str, Ip6Address);
3029
3030 FreePool (Ip6Str);
3031
3032 return Status;
3033 }
3034
3035 /**
3036 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS and prefix length.
3037 The format of the string is defined in RFC 4291 - Text Pepresentation of Addresses
3038 Prefixes: ipv6-address/prefix-length.
3039
3040 @param[in] String The pointer to the Ascii string.
3041 @param[out] Ip6Address The pointer to the converted IPv6 address.
3042 @param[out] PrefixLength The pointer to the converted prefix length.
3043
3044 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3045 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3046 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3047
3048 **/
3049 EFI_STATUS
3050 EFIAPI
3051 NetLibStrToIp6andPrefix (
3052 IN CONST CHAR16 *String,
3053 OUT EFI_IPv6_ADDRESS *Ip6Address,
3054 OUT UINT8 *PrefixLength
3055 )
3056 {
3057 CHAR8 *Ip6Str;
3058 CHAR8 *PrefixStr;
3059 CHAR8 *TempStr;
3060 EFI_STATUS Status;
3061 UINT8 Length;
3062
3063 if ((String == NULL) || (Ip6Address == NULL) || (PrefixLength == NULL)) {
3064 return EFI_INVALID_PARAMETER;
3065 }
3066
3067 Ip6Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8));
3068 if (Ip6Str == NULL) {
3069 return EFI_OUT_OF_RESOURCES;
3070 }
3071
3072 UnicodeStrToAsciiStr (String, Ip6Str);
3073
3074 //
3075 // Get the sub string describing prefix length.
3076 //
3077 TempStr = Ip6Str;
3078 while (*TempStr != '\0' && (*TempStr != '/')) {
3079 TempStr++;
3080 }
3081
3082 if (*TempStr == '/') {
3083 PrefixStr = TempStr + 1;
3084 } else {
3085 PrefixStr = NULL;
3086 }
3087
3088 //
3089 // Get the sub string describing IPv6 address and convert it.
3090 //
3091 *TempStr = '\0';
3092
3093 Status = NetLibAsciiStrToIp6 (Ip6Str, Ip6Address);
3094 if (EFI_ERROR (Status)) {
3095 goto Exit;
3096 }
3097
3098 //
3099 // If input string doesn't indicate the prefix length, return 0xff.
3100 //
3101 Length = 0xFF;
3102
3103 //
3104 // Convert the string to prefix length
3105 //
3106 if (PrefixStr != NULL) {
3107
3108 Status = EFI_INVALID_PARAMETER;
3109 Length = 0;
3110 while (*PrefixStr != '\0') {
3111 if (NET_IS_DIGIT (*PrefixStr)) {
3112 Length = (UINT8) (Length * 10 + (*PrefixStr - '0'));
3113 if (Length >= IP6_PREFIX_NUM) {
3114 goto Exit;
3115 }
3116 } else {
3117 goto Exit;
3118 }
3119
3120 PrefixStr++;
3121 }
3122 }
3123
3124 *PrefixLength = Length;
3125 Status = EFI_SUCCESS;
3126
3127 Exit:
3128
3129 FreePool (Ip6Str);
3130 return Status;
3131 }
3132
3133 /**
3134
3135 Convert one EFI_IPv6_ADDRESS to Null-terminated Unicode string.
3136 The text representation of address is defined in RFC 4291.
3137
3138 @param[in] Ip6Address The pointer to the IPv6 address.
3139 @param[out] String The buffer to return the converted string.
3140 @param[in] StringSize The length in bytes of the input String.
3141
3142 @retval EFI_SUCCESS Convert to string successfully.
3143 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
3144 @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small for the result. BufferSize has been
3145 updated with the size needed to complete the request.
3146 **/
3147 EFI_STATUS
3148 EFIAPI
3149 NetLibIp6ToStr (
3150 IN EFI_IPv6_ADDRESS *Ip6Address,
3151 OUT CHAR16 *String,
3152 IN UINTN StringSize
3153 )
3154 {
3155 UINT16 Ip6Addr[8];
3156 UINTN Index;
3157 UINTN LongestZerosStart;
3158 UINTN LongestZerosLength;
3159 UINTN CurrentZerosStart;
3160 UINTN CurrentZerosLength;
3161 CHAR16 Buffer[sizeof"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"];
3162 CHAR16 *Ptr;
3163
3164 if (Ip6Address == NULL || String == NULL || StringSize == 0) {
3165 return EFI_INVALID_PARAMETER;
3166 }
3167
3168 //
3169 // Convert the UINT8 array to an UINT16 array for easy handling.
3170 //
3171 ZeroMem (Ip6Addr, sizeof (Ip6Addr));
3172 for (Index = 0; Index < 16; Index++) {
3173 Ip6Addr[Index / 2] |= (Ip6Address->Addr[Index] << ((1 - (Index % 2)) << 3));
3174 }
3175
3176 //
3177 // Find the longest zeros and mark it.
3178 //
3179 CurrentZerosStart = DEFAULT_ZERO_START;
3180 CurrentZerosLength = 0;
3181 LongestZerosStart = DEFAULT_ZERO_START;
3182 LongestZerosLength = 0;
3183 for (Index = 0; Index < 8; Index++) {
3184 if (Ip6Addr[Index] == 0) {
3185 if (CurrentZerosStart == DEFAULT_ZERO_START) {
3186 CurrentZerosStart = Index;
3187 CurrentZerosLength = 1;
3188 } else {
3189 CurrentZerosLength++;
3190 }
3191 } else {
3192 if (CurrentZerosStart != DEFAULT_ZERO_START) {
3193 if (CurrentZerosLength > 2 && (LongestZerosStart == (DEFAULT_ZERO_START) || CurrentZerosLength > LongestZerosLength)) {
3194 LongestZerosStart = CurrentZerosStart;
3195 LongestZerosLength = CurrentZerosLength;
3196 }
3197 CurrentZerosStart = DEFAULT_ZERO_START;
3198 CurrentZerosLength = 0;
3199 }
3200 }
3201 }
3202
3203 if (CurrentZerosStart != DEFAULT_ZERO_START && CurrentZerosLength > 2) {
3204 if (LongestZerosStart == DEFAULT_ZERO_START || LongestZerosLength < CurrentZerosLength) {
3205 LongestZerosStart = CurrentZerosStart;
3206 LongestZerosLength = CurrentZerosLength;
3207 }
3208 }
3209
3210 Ptr = Buffer;
3211 for (Index = 0; Index < 8; Index++) {
3212 if (LongestZerosStart != DEFAULT_ZERO_START && Index >= LongestZerosStart && Index < LongestZerosStart + LongestZerosLength) {
3213 if (Index == LongestZerosStart) {
3214 *Ptr++ = L':';
3215 }
3216 continue;
3217 }
3218 if (Index != 0) {
3219 *Ptr++ = L':';
3220 }
3221 Ptr += UnicodeSPrint(Ptr, 10, L"%x", Ip6Addr[Index]);
3222 }
3223
3224 if (LongestZerosStart != DEFAULT_ZERO_START && LongestZerosStart + LongestZerosLength == 8) {
3225 *Ptr++ = L':';
3226 }
3227 *Ptr = L'\0';
3228
3229 if ((UINTN)Ptr - (UINTN)Buffer > StringSize) {
3230 return EFI_BUFFER_TOO_SMALL;
3231 }
3232
3233 StrCpy (String, Buffer);
3234
3235 return EFI_SUCCESS;
3236 }
3237
3238 /**
3239 This function obtains the system guid from the smbios table.
3240
3241 @param[out] SystemGuid The pointer of the returned system guid.
3242
3243 @retval EFI_SUCCESS Successfully obtained the system guid.
3244 @retval EFI_NOT_FOUND Did not find the SMBIOS table.
3245
3246 **/
3247 EFI_STATUS
3248 EFIAPI
3249 NetLibGetSystemGuid (
3250 OUT EFI_GUID *SystemGuid
3251 )
3252 {
3253 EFI_STATUS Status;
3254 SMBIOS_TABLE_ENTRY_POINT *SmbiosTable;
3255 SMBIOS_STRUCTURE_POINTER Smbios;
3256 SMBIOS_STRUCTURE_POINTER SmbiosEnd;
3257 CHAR8 *String;
3258
3259 SmbiosTable = NULL;
3260 Status = EfiGetSystemConfigurationTable (&gEfiSmbiosTableGuid, (VOID **) &SmbiosTable);
3261
3262 if (EFI_ERROR (Status) || SmbiosTable == NULL) {
3263 return EFI_NOT_FOUND;
3264 }
3265
3266 Smbios.Hdr = (SMBIOS_STRUCTURE *) (UINTN) SmbiosTable->TableAddress;
3267 SmbiosEnd.Raw = (UINT8 *) (UINTN) (SmbiosTable->TableAddress + SmbiosTable->TableLength);
3268
3269 do {
3270 if (Smbios.Hdr->Type == 1) {
3271 if (Smbios.Hdr->Length < 0x19) {
3272 //
3273 // Older version did not support UUID.
3274 //
3275 return EFI_NOT_FOUND;
3276 }
3277
3278 //
3279 // SMBIOS tables are byte packed so we need to do a byte copy to
3280 // prevend alignment faults on Itanium-based platform.
3281 //
3282 CopyMem (SystemGuid, &Smbios.Type1->Uuid, sizeof (EFI_GUID));
3283 return EFI_SUCCESS;
3284 }
3285
3286 //
3287 // Go to the next SMBIOS structure. Each SMBIOS structure may include 2 parts:
3288 // 1. Formatted section; 2. Unformatted string section. So, 2 steps are needed
3289 // to skip one SMBIOS structure.
3290 //
3291
3292 //
3293 // Step 1: Skip over formatted section.
3294 //
3295 String = (CHAR8 *) (Smbios.Raw + Smbios.Hdr->Length);
3296
3297 //
3298 // Step 2: Skip over unformated string section.
3299 //
3300 do {
3301 //
3302 // Each string is terminated with a NULL(00h) BYTE and the sets of strings
3303 // is terminated with an additional NULL(00h) BYTE.
3304 //
3305 for ( ; *String != 0; String++) {
3306 }
3307
3308 if (*(UINT8*)++String == 0) {
3309 //
3310 // Pointer to the next SMBIOS structure.
3311 //
3312 Smbios.Raw = (UINT8 *)++String;
3313 break;
3314 }
3315 } while (TRUE);
3316 } while (Smbios.Raw < SmbiosEnd.Raw);
3317 return EFI_NOT_FOUND;
3318 }