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