]> git.proxmox.com Git - mirror_edk2.git/blob - IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c
IntelFrameworkModulePkg: Clean up source files
[mirror_edk2.git] / IntelFrameworkModulePkg / Library / GenericBdsLib / BdsBoot.c
1 /** @file
2 BDS Lib functions which relate with create or process the boot option.
3
4 Copyright (c) 2004 - 2018, 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
15 #include "InternalBdsLib.h"
16 #include "String.h"
17
18 BOOLEAN mEnumBootDevice = FALSE;
19 EFI_HII_HANDLE gBdsLibStringPackHandle = NULL;
20
21 /**
22
23 End Perf entry of BDS
24
25 @param Event The triggered event.
26 @param Context Context for this event.
27
28 **/
29 VOID
30 EFIAPI
31 BmEndOfBdsPerfCode (
32 IN EFI_EVENT Event,
33 IN VOID *Context
34 )
35 {
36 //
37 // Record the performance data for End of BDS
38 //
39 PERF_END(NULL, "BDS", NULL, 0);
40
41 return ;
42 }
43
44 /**
45 The constructor function register UNI strings into imageHandle.
46
47 It will ASSERT() if that operation fails and it will always return EFI_SUCCESS.
48
49 @param ImageHandle The firmware allocated handle for the EFI image.
50 @param SystemTable A pointer to the EFI System Table.
51
52 @retval EFI_SUCCESS The constructor successfully added string package.
53 @retval Other value The constructor can't add string package.
54
55 **/
56 EFI_STATUS
57 EFIAPI
58 GenericBdsLibConstructor (
59 IN EFI_HANDLE ImageHandle,
60 IN EFI_SYSTEM_TABLE *SystemTable
61 )
62 {
63
64 gBdsLibStringPackHandle = HiiAddPackages (
65 &gBdsLibStringPackageGuid,
66 ImageHandle,
67 GenericBdsLibStrings,
68 NULL
69 );
70
71 ASSERT (gBdsLibStringPackHandle != NULL);
72
73 return EFI_SUCCESS;
74 }
75
76 /**
77 Deletete the Boot Option from EFI Variable. The Boot Order Arrray
78 is also updated.
79
80 @param OptionNumber The number of Boot option want to be deleted.
81 @param BootOrder The Boot Order array.
82 @param BootOrderSize The size of the Boot Order Array.
83
84 @retval EFI_SUCCESS The Boot Option Variable was found and removed
85 @retval EFI_UNSUPPORTED The Boot Option Variable store was inaccessible
86 @retval EFI_NOT_FOUND The Boot Option Variable was not found
87 **/
88 EFI_STATUS
89 EFIAPI
90 BdsDeleteBootOption (
91 IN UINTN OptionNumber,
92 IN OUT UINT16 *BootOrder,
93 IN OUT UINTN *BootOrderSize
94 )
95 {
96 CHAR16 BootOption[9];
97 UINTN Index;
98 EFI_STATUS Status;
99
100 UnicodeSPrint (BootOption, sizeof (BootOption), L"Boot%04x", OptionNumber);
101 Status = gRT->SetVariable (
102 BootOption,
103 &gEfiGlobalVariableGuid,
104 0,
105 0,
106 NULL
107 );
108 //
109 // Deleting variable with existing variable implementation shouldn't fail.
110 //
111 ASSERT_EFI_ERROR (Status);
112
113 //
114 // adjust boot order array
115 //
116 for (Index = 0; Index < *BootOrderSize / sizeof (UINT16); Index++) {
117 if (BootOrder[Index] == OptionNumber) {
118 CopyMem (&BootOrder[Index], &BootOrder[Index+1], *BootOrderSize - (Index+1) * sizeof (UINT16));
119 *BootOrderSize -= sizeof (UINT16);
120 break;
121 }
122 }
123
124 return Status;
125 }
126 /**
127
128 Translate the first n characters of an Ascii string to
129 Unicode characters. The count n is indicated by parameter
130 Size. If Size is greater than the length of string, then
131 the entire string is translated.
132
133
134 @param AStr Pointer to input Ascii string.
135 @param Size The number of characters to translate.
136 @param UStr Pointer to output Unicode string buffer.
137
138 **/
139 VOID
140 AsciiToUnicodeSize (
141 IN UINT8 *AStr,
142 IN UINTN Size,
143 OUT UINT16 *UStr
144 )
145 {
146 UINTN Idx;
147
148 Idx = 0;
149 while (AStr[Idx] != 0) {
150 UStr[Idx] = (CHAR16) AStr[Idx];
151 if (Idx == Size) {
152 break;
153 }
154
155 Idx++;
156 }
157 UStr[Idx] = 0;
158 }
159
160 /**
161 Build Legacy Device Name String according.
162
163 @param CurBBSEntry BBS Table.
164 @param Index Index.
165 @param BufSize The buffer size.
166 @param BootString The output string.
167
168 **/
169 VOID
170 BdsBuildLegacyDevNameString (
171 IN BBS_TABLE *CurBBSEntry,
172 IN UINTN Index,
173 IN UINTN BufSize,
174 OUT CHAR16 *BootString
175 )
176 {
177 CHAR16 *Fmt;
178 CHAR16 *Type;
179 UINT8 *StringDesc;
180 CHAR16 Temp[80];
181
182 switch (Index) {
183 //
184 // Primary Master
185 //
186 case 1:
187 Fmt = L"Primary Master %s";
188 break;
189
190 //
191 // Primary Slave
192 //
193 case 2:
194 Fmt = L"Primary Slave %s";
195 break;
196
197 //
198 // Secondary Master
199 //
200 case 3:
201 Fmt = L"Secondary Master %s";
202 break;
203
204 //
205 // Secondary Slave
206 //
207 case 4:
208 Fmt = L"Secondary Slave %s";
209 break;
210
211 default:
212 Fmt = L"%s";
213 break;
214 }
215
216 switch (CurBBSEntry->DeviceType) {
217 case BBS_FLOPPY:
218 Type = L"Floppy";
219 break;
220
221 case BBS_HARDDISK:
222 Type = L"Harddisk";
223 break;
224
225 case BBS_CDROM:
226 Type = L"CDROM";
227 break;
228
229 case BBS_PCMCIA:
230 Type = L"PCMCIAe";
231 break;
232
233 case BBS_USB:
234 Type = L"USB";
235 break;
236
237 case BBS_EMBED_NETWORK:
238 Type = L"Network";
239 break;
240
241 case BBS_BEV_DEVICE:
242 Type = L"BEVe";
243 break;
244
245 case BBS_UNKNOWN:
246 default:
247 Type = L"Unknown";
248 break;
249 }
250 //
251 // If current BBS entry has its description then use it.
252 //
253 StringDesc = (UINT8 *) (((UINTN) CurBBSEntry->DescStringSegment << 4) + CurBBSEntry->DescStringOffset);
254 if (NULL != StringDesc) {
255 //
256 // Only get fisrt 32 characters, this is suggested by BBS spec
257 //
258 AsciiToUnicodeSize (StringDesc, 32, Temp);
259 Fmt = L"%s";
260 Type = Temp;
261 }
262
263 //
264 // BbsTable 16 entries are for onboard IDE.
265 // Set description string for SATA harddisks, Harddisk 0 ~ Harddisk 11
266 //
267 if (Index >= 5 && Index <= 16 && (CurBBSEntry->DeviceType == BBS_HARDDISK || CurBBSEntry->DeviceType == BBS_CDROM)) {
268 Fmt = L"%s %d";
269 UnicodeSPrint (BootString, BufSize, Fmt, Type, Index - 5);
270 } else {
271 UnicodeSPrint (BootString, BufSize, Fmt, Type);
272 }
273 }
274
275 /**
276
277 Create a legacy boot option for the specified entry of
278 BBS table, save it as variable, and append it to the boot
279 order list.
280
281
282 @param CurrentBbsEntry Pointer to current BBS table.
283 @param CurrentBbsDevPath Pointer to the Device Path Protocol instance of BBS
284 @param Index Index of the specified entry in BBS table.
285 @param BootOrderList On input, the original boot order list.
286 On output, the new boot order list attached with the
287 created node.
288 @param BootOrderListSize On input, the original size of boot order list.
289 On output, the size of new boot order list.
290
291 @retval EFI_SUCCESS Boot Option successfully created.
292 @retval EFI_OUT_OF_RESOURCES Fail to allocate necessary memory.
293 @retval Other Error occurs while setting variable.
294
295 **/
296 EFI_STATUS
297 BdsCreateLegacyBootOption (
298 IN BBS_TABLE *CurrentBbsEntry,
299 IN EFI_DEVICE_PATH_PROTOCOL *CurrentBbsDevPath,
300 IN UINTN Index,
301 IN OUT UINT16 **BootOrderList,
302 IN OUT UINTN *BootOrderListSize
303 )
304 {
305 EFI_STATUS Status;
306 UINT16 CurrentBootOptionNo;
307 UINT16 BootString[10];
308 CHAR16 BootDesc[100];
309 CHAR8 HelpString[100];
310 UINT16 *NewBootOrderList;
311 UINTN BufferSize;
312 UINTN StringLen;
313 VOID *Buffer;
314 UINT8 *Ptr;
315 UINT16 CurrentBbsDevPathSize;
316 UINTN BootOrderIndex;
317 UINTN BootOrderLastIndex;
318 UINTN ArrayIndex;
319 BOOLEAN IndexNotFound;
320 BBS_BBS_DEVICE_PATH *NewBbsDevPathNode;
321
322 if ((*BootOrderList) == NULL) {
323 CurrentBootOptionNo = 0;
324 } else {
325 for (ArrayIndex = 0; ArrayIndex < (UINTN) (*BootOrderListSize / sizeof (UINT16)); ArrayIndex++) {
326 IndexNotFound = TRUE;
327 for (BootOrderIndex = 0; BootOrderIndex < (UINTN) (*BootOrderListSize / sizeof (UINT16)); BootOrderIndex++) {
328 if ((*BootOrderList)[BootOrderIndex] == ArrayIndex) {
329 IndexNotFound = FALSE;
330 break;
331 }
332 }
333
334 if (!IndexNotFound) {
335 continue;
336 } else {
337 break;
338 }
339 }
340
341 CurrentBootOptionNo = (UINT16) ArrayIndex;
342 }
343
344 UnicodeSPrint (
345 BootString,
346 sizeof (BootString),
347 L"Boot%04x",
348 CurrentBootOptionNo
349 );
350
351 BdsBuildLegacyDevNameString (CurrentBbsEntry, Index, sizeof (BootDesc), BootDesc);
352
353 //
354 // Create new BBS device path node with description string
355 //
356 UnicodeStrToAsciiStrS (BootDesc, HelpString, sizeof (HelpString));
357
358 StringLen = AsciiStrLen (HelpString);
359 NewBbsDevPathNode = AllocateZeroPool (sizeof (BBS_BBS_DEVICE_PATH) + StringLen);
360 if (NewBbsDevPathNode == NULL) {
361 return EFI_OUT_OF_RESOURCES;
362 }
363 CopyMem (NewBbsDevPathNode, CurrentBbsDevPath, sizeof (BBS_BBS_DEVICE_PATH));
364 CopyMem (NewBbsDevPathNode->String, HelpString, StringLen + 1);
365 SetDevicePathNodeLength (&(NewBbsDevPathNode->Header), sizeof (BBS_BBS_DEVICE_PATH) + StringLen);
366
367 //
368 // Create entire new CurrentBbsDevPath with end node
369 //
370 CurrentBbsDevPath = AppendDevicePathNode (
371 NULL,
372 (EFI_DEVICE_PATH_PROTOCOL *) NewBbsDevPathNode
373 );
374 if (CurrentBbsDevPath == NULL) {
375 FreePool (NewBbsDevPathNode);
376 return EFI_OUT_OF_RESOURCES;
377 }
378
379 CurrentBbsDevPathSize = (UINT16) (GetDevicePathSize (CurrentBbsDevPath));
380
381 BufferSize = sizeof (UINT32) +
382 sizeof (UINT16) +
383 StrSize (BootDesc) +
384 CurrentBbsDevPathSize +
385 sizeof (BBS_TABLE) +
386 sizeof (UINT16);
387
388 Buffer = AllocateZeroPool (BufferSize);
389 if (Buffer == NULL) {
390 FreePool (NewBbsDevPathNode);
391 FreePool (CurrentBbsDevPath);
392 return EFI_OUT_OF_RESOURCES;
393 }
394
395 Ptr = (UINT8 *) Buffer;
396
397 *((UINT32 *) Ptr) = LOAD_OPTION_ACTIVE;
398 Ptr += sizeof (UINT32);
399
400 *((UINT16 *) Ptr) = CurrentBbsDevPathSize;
401 Ptr += sizeof (UINT16);
402
403 CopyMem (
404 Ptr,
405 BootDesc,
406 StrSize (BootDesc)
407 );
408 Ptr += StrSize (BootDesc);
409
410 CopyMem (
411 Ptr,
412 CurrentBbsDevPath,
413 CurrentBbsDevPathSize
414 );
415 Ptr += CurrentBbsDevPathSize;
416
417 CopyMem (
418 Ptr,
419 CurrentBbsEntry,
420 sizeof (BBS_TABLE)
421 );
422
423 Ptr += sizeof (BBS_TABLE);
424 *((UINT16 *) Ptr) = (UINT16) Index;
425
426 Status = gRT->SetVariable (
427 BootString,
428 &gEfiGlobalVariableGuid,
429 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
430 BufferSize,
431 Buffer
432 );
433
434 FreePool (Buffer);
435
436 Buffer = NULL;
437
438 NewBootOrderList = AllocateZeroPool (*BootOrderListSize + sizeof (UINT16));
439 if (NULL == NewBootOrderList) {
440 FreePool (NewBbsDevPathNode);
441 FreePool (CurrentBbsDevPath);
442 return EFI_OUT_OF_RESOURCES;
443 }
444
445 if (*BootOrderList != NULL) {
446 CopyMem (NewBootOrderList, *BootOrderList, *BootOrderListSize);
447 FreePool (*BootOrderList);
448 }
449
450 BootOrderLastIndex = (UINTN) (*BootOrderListSize / sizeof (UINT16));
451 NewBootOrderList[BootOrderLastIndex] = CurrentBootOptionNo;
452 *BootOrderListSize += sizeof (UINT16);
453 *BootOrderList = NewBootOrderList;
454
455 FreePool (NewBbsDevPathNode);
456 FreePool (CurrentBbsDevPath);
457 return Status;
458 }
459
460 /**
461 Check if the boot option is a legacy one.
462
463 @param BootOptionVar The boot option data payload.
464 @param BbsEntry The BBS Table.
465 @param BbsIndex The table index.
466
467 @retval TRUE It is a legacy boot option.
468 @retval FALSE It is not a legacy boot option.
469
470 **/
471 BOOLEAN
472 BdsIsLegacyBootOption (
473 IN UINT8 *BootOptionVar,
474 OUT BBS_TABLE **BbsEntry,
475 OUT UINT16 *BbsIndex
476 )
477 {
478 UINT8 *Ptr;
479 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
480 BOOLEAN Ret;
481 UINT16 DevPathLen;
482
483 Ptr = BootOptionVar;
484 Ptr += sizeof (UINT32);
485 DevPathLen = *(UINT16 *) Ptr;
486 Ptr += sizeof (UINT16);
487 Ptr += StrSize ((UINT16 *) Ptr);
488 DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) Ptr;
489 if ((BBS_DEVICE_PATH == DevicePath->Type) && (BBS_BBS_DP == DevicePath->SubType)) {
490 Ptr += DevPathLen;
491 *BbsEntry = (BBS_TABLE *) Ptr;
492 Ptr += sizeof (BBS_TABLE);
493 *BbsIndex = *(UINT16 *) Ptr;
494 Ret = TRUE;
495 } else {
496 *BbsEntry = NULL;
497 Ret = FALSE;
498 }
499
500 return Ret;
501 }
502
503 /**
504 Delete all the invalid legacy boot options.
505
506 @retval EFI_SUCCESS All invalide legacy boot options are deleted.
507 @retval EFI_OUT_OF_RESOURCES Fail to allocate necessary memory.
508 @retval EFI_NOT_FOUND Fail to retrive variable of boot order.
509 **/
510 EFI_STATUS
511 EFIAPI
512 BdsDeleteAllInvalidLegacyBootOptions (
513 VOID
514 )
515 {
516 UINT16 *BootOrder;
517 UINT8 *BootOptionVar;
518 UINTN BootOrderSize;
519 UINTN BootOptionSize;
520 EFI_STATUS Status;
521 UINT16 HddCount;
522 UINT16 BbsCount;
523 HDD_INFO *LocalHddInfo;
524 BBS_TABLE *LocalBbsTable;
525 BBS_TABLE *BbsEntry;
526 UINT16 BbsIndex;
527 EFI_LEGACY_BIOS_PROTOCOL *LegacyBios;
528 UINTN Index;
529 UINT16 BootOption[10];
530 UINT16 BootDesc[100];
531 BOOLEAN DescStringMatch;
532
533 Status = EFI_SUCCESS;
534 BootOrder = NULL;
535 BootOrderSize = 0;
536 HddCount = 0;
537 BbsCount = 0;
538 LocalHddInfo = NULL;
539 LocalBbsTable = NULL;
540 BbsEntry = NULL;
541
542 Status = gBS->LocateProtocol (&gEfiLegacyBiosProtocolGuid, NULL, (VOID **) &LegacyBios);
543 if (EFI_ERROR (Status)) {
544 return Status;
545 }
546
547 BootOrder = BdsLibGetVariableAndSize (
548 L"BootOrder",
549 &gEfiGlobalVariableGuid,
550 &BootOrderSize
551 );
552 if (BootOrder == NULL) {
553 return EFI_NOT_FOUND;
554 }
555
556 LegacyBios->GetBbsInfo (
557 LegacyBios,
558 &HddCount,
559 &LocalHddInfo,
560 &BbsCount,
561 &LocalBbsTable
562 );
563
564 Index = 0;
565 while (Index < BootOrderSize / sizeof (UINT16)) {
566 UnicodeSPrint (BootOption, sizeof (BootOption), L"Boot%04x", BootOrder[Index]);
567 BootOptionVar = BdsLibGetVariableAndSize (
568 BootOption,
569 &gEfiGlobalVariableGuid,
570 &BootOptionSize
571 );
572 if (NULL == BootOptionVar) {
573 BootOptionSize = 0;
574 Status = gRT->GetVariable (
575 BootOption,
576 &gEfiGlobalVariableGuid,
577 NULL,
578 &BootOptionSize,
579 BootOptionVar
580 );
581 if (Status == EFI_NOT_FOUND) {
582 //
583 // Update BootOrder
584 //
585 BdsDeleteBootOption (
586 BootOrder[Index],
587 BootOrder,
588 &BootOrderSize
589 );
590 continue;
591 } else {
592 FreePool (BootOrder);
593 return EFI_OUT_OF_RESOURCES;
594 }
595 }
596
597 //
598 // Skip Non-Legacy boot option
599 //
600 if (!BdsIsLegacyBootOption (BootOptionVar, &BbsEntry, &BbsIndex)) {
601 if (BootOptionVar!= NULL) {
602 FreePool (BootOptionVar);
603 }
604 Index++;
605 continue;
606 }
607
608 if (BbsIndex < BbsCount) {
609 //
610 // Check if BBS Description String is changed
611 //
612 DescStringMatch = FALSE;
613 BdsBuildLegacyDevNameString (
614 &LocalBbsTable[BbsIndex],
615 BbsIndex,
616 sizeof (BootDesc),
617 BootDesc
618 );
619
620 if (StrCmp (BootDesc, (UINT16*)(BootOptionVar + sizeof (UINT32) + sizeof (UINT16))) == 0) {
621 DescStringMatch = TRUE;
622 }
623
624 if (!((LocalBbsTable[BbsIndex].BootPriority == BBS_IGNORE_ENTRY) ||
625 (LocalBbsTable[BbsIndex].BootPriority == BBS_DO_NOT_BOOT_FROM)) &&
626 (LocalBbsTable[BbsIndex].DeviceType == BbsEntry->DeviceType) &&
627 DescStringMatch) {
628 Index++;
629 continue;
630 }
631 }
632
633 if (BootOptionVar != NULL) {
634 FreePool (BootOptionVar);
635 }
636 //
637 // should delete
638 //
639 BdsDeleteBootOption (
640 BootOrder[Index],
641 BootOrder,
642 &BootOrderSize
643 );
644 }
645
646 //
647 // Adjust the number of boot options.
648 //
649 Status = gRT->SetVariable (
650 L"BootOrder",
651 &gEfiGlobalVariableGuid,
652 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
653 BootOrderSize,
654 BootOrder
655 );
656 //
657 // Shrinking variable with existing variable implementation shouldn't fail.
658 //
659 ASSERT_EFI_ERROR (Status);
660 FreePool (BootOrder);
661
662 return Status;
663 }
664
665 /**
666 Find all legacy boot option by device type.
667
668 @param BootOrder The boot order array.
669 @param BootOptionNum The number of boot option.
670 @param DevType Device type.
671 @param DevName Device name.
672 @param Attribute The boot option attribute.
673 @param BbsIndex The BBS table index.
674 @param OptionNumber The boot option index.
675
676 @retval TRUE The Legacy boot option is found.
677 @retval FALSE The legacy boot option is not found.
678
679 **/
680 BOOLEAN
681 BdsFindLegacyBootOptionByDevTypeAndName (
682 IN UINT16 *BootOrder,
683 IN UINTN BootOptionNum,
684 IN UINT16 DevType,
685 IN CHAR16 *DevName,
686 OUT UINT32 *Attribute,
687 OUT UINT16 *BbsIndex,
688 OUT UINT16 *OptionNumber
689 )
690 {
691 UINTN Index;
692 CHAR16 BootOption[9];
693 UINTN BootOptionSize;
694 UINT8 *BootOptionVar;
695 BBS_TABLE *BbsEntry;
696 BOOLEAN Found;
697
698 BbsEntry = NULL;
699 Found = FALSE;
700
701 if (NULL == BootOrder) {
702 return Found;
703 }
704
705 //
706 // Loop all boot option from variable
707 //
708 for (Index = 0; Index < BootOptionNum; Index++) {
709 UnicodeSPrint (BootOption, sizeof (BootOption), L"Boot%04x", (UINTN) BootOrder[Index]);
710 BootOptionVar = BdsLibGetVariableAndSize (
711 BootOption,
712 &gEfiGlobalVariableGuid,
713 &BootOptionSize
714 );
715 if (NULL == BootOptionVar) {
716 continue;
717 }
718
719 //
720 // Skip Non-legacy boot option
721 //
722 if (!BdsIsLegacyBootOption (BootOptionVar, &BbsEntry, BbsIndex)) {
723 FreePool (BootOptionVar);
724 continue;
725 }
726
727 if (
728 (BbsEntry->DeviceType != DevType) ||
729 (StrCmp (DevName, (CHAR16*)(BootOptionVar + sizeof (UINT32) + sizeof (UINT16))) != 0)
730 ) {
731 FreePool (BootOptionVar);
732 continue;
733 }
734
735 *Attribute = *(UINT32 *) BootOptionVar;
736 *OptionNumber = BootOrder[Index];
737 Found = TRUE;
738 FreePool (BootOptionVar);
739 break;
740 }
741
742 return Found;
743 }
744
745 /**
746 Create a legacy boot option.
747
748 @param BbsItem The BBS Table entry.
749 @param Index Index of the specified entry in BBS table.
750 @param BootOrderList The boot order list.
751 @param BootOrderListSize The size of boot order list.
752
753 @retval EFI_OUT_OF_RESOURCE No enough memory.
754 @retval EFI_SUCCESS The function complete successfully.
755 @return Other value if the legacy boot option is not created.
756
757 **/
758 EFI_STATUS
759 BdsCreateOneLegacyBootOption (
760 IN BBS_TABLE *BbsItem,
761 IN UINTN Index,
762 IN OUT UINT16 **BootOrderList,
763 IN OUT UINTN *BootOrderListSize
764 )
765 {
766 BBS_BBS_DEVICE_PATH BbsDevPathNode;
767 EFI_STATUS Status;
768 EFI_DEVICE_PATH_PROTOCOL *DevPath;
769
770 DevPath = NULL;
771
772 //
773 // Create device path node.
774 //
775 BbsDevPathNode.Header.Type = BBS_DEVICE_PATH;
776 BbsDevPathNode.Header.SubType = BBS_BBS_DP;
777 SetDevicePathNodeLength (&BbsDevPathNode.Header, sizeof (BBS_BBS_DEVICE_PATH));
778 BbsDevPathNode.DeviceType = BbsItem->DeviceType;
779 CopyMem (&BbsDevPathNode.StatusFlag, &BbsItem->StatusFlags, sizeof (UINT16));
780
781 DevPath = AppendDevicePathNode (
782 NULL,
783 (EFI_DEVICE_PATH_PROTOCOL *) &BbsDevPathNode
784 );
785 if (NULL == DevPath) {
786 return EFI_OUT_OF_RESOURCES;
787 }
788
789 Status = BdsCreateLegacyBootOption (
790 BbsItem,
791 DevPath,
792 Index,
793 BootOrderList,
794 BootOrderListSize
795 );
796 BbsItem->BootPriority = 0x00;
797
798 FreePool (DevPath);
799
800 return Status;
801 }
802
803 /**
804 Add the legacy boot options from BBS table if they do not exist.
805
806 @retval EFI_SUCCESS The boot options are added successfully
807 or they are already in boot options.
808 @retval EFI_NOT_FOUND No legacy boot options is found.
809 @retval EFI_OUT_OF_RESOURCE No enough memory.
810 @return Other value LegacyBoot options are not added.
811 **/
812 EFI_STATUS
813 EFIAPI
814 BdsAddNonExistingLegacyBootOptions (
815 VOID
816 )
817 {
818 UINT16 *BootOrder;
819 UINTN BootOrderSize;
820 EFI_STATUS Status;
821 CHAR16 Desc[100];
822 UINT16 HddCount;
823 UINT16 BbsCount;
824 HDD_INFO *LocalHddInfo;
825 BBS_TABLE *LocalBbsTable;
826 UINT16 BbsIndex;
827 EFI_LEGACY_BIOS_PROTOCOL *LegacyBios;
828 UINT16 Index;
829 UINT32 Attribute;
830 UINT16 OptionNumber;
831 BOOLEAN Exist;
832
833 HddCount = 0;
834 BbsCount = 0;
835 LocalHddInfo = NULL;
836 LocalBbsTable = NULL;
837
838 Status = gBS->LocateProtocol (&gEfiLegacyBiosProtocolGuid, NULL, (VOID **) &LegacyBios);
839 if (EFI_ERROR (Status)) {
840 return Status;
841 }
842
843 LegacyBios->GetBbsInfo (
844 LegacyBios,
845 &HddCount,
846 &LocalHddInfo,
847 &BbsCount,
848 &LocalBbsTable
849 );
850
851 BootOrder = BdsLibGetVariableAndSize (
852 L"BootOrder",
853 &gEfiGlobalVariableGuid,
854 &BootOrderSize
855 );
856 if (BootOrder == NULL) {
857 BootOrderSize = 0;
858 }
859
860 for (Index = 0; Index < BbsCount; Index++) {
861 if ((LocalBbsTable[Index].BootPriority == BBS_IGNORE_ENTRY) ||
862 (LocalBbsTable[Index].BootPriority == BBS_DO_NOT_BOOT_FROM)
863 ) {
864 continue;
865 }
866
867 BdsBuildLegacyDevNameString (&LocalBbsTable[Index], Index, sizeof (Desc), Desc);
868
869 Exist = BdsFindLegacyBootOptionByDevTypeAndName (
870 BootOrder,
871 BootOrderSize / sizeof (UINT16),
872 LocalBbsTable[Index].DeviceType,
873 Desc,
874 &Attribute,
875 &BbsIndex,
876 &OptionNumber
877 );
878 if (!Exist) {
879 //
880 // Not found such type of legacy device in boot options or we found but it's disabled
881 // so we have to create one and put it to the tail of boot order list
882 //
883 Status = BdsCreateOneLegacyBootOption (
884 &LocalBbsTable[Index],
885 Index,
886 &BootOrder,
887 &BootOrderSize
888 );
889 if (!EFI_ERROR (Status)) {
890 ASSERT (BootOrder != NULL);
891 BbsIndex = Index;
892 OptionNumber = BootOrder[BootOrderSize / sizeof (UINT16) - 1];
893 }
894 }
895
896 ASSERT (BbsIndex == Index);
897 }
898
899 Status = gRT->SetVariable (
900 L"BootOrder",
901 &gEfiGlobalVariableGuid,
902 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
903 BootOrderSize,
904 BootOrder
905 );
906 if (BootOrder != NULL) {
907 FreePool (BootOrder);
908 }
909
910 return Status;
911 }
912
913 /**
914 Fill the device order buffer.
915
916 @param BbsTable The BBS table.
917 @param BbsType The BBS Type.
918 @param BbsCount The BBS Count.
919 @param Buf device order buffer.
920
921 @return The device order buffer.
922
923 **/
924 UINT16 *
925 BdsFillDevOrderBuf (
926 IN BBS_TABLE *BbsTable,
927 IN BBS_TYPE BbsType,
928 IN UINTN BbsCount,
929 OUT UINT16 *Buf
930 )
931 {
932 UINTN Index;
933
934 for (Index = 0; Index < BbsCount; Index++) {
935 if (BbsTable[Index].BootPriority == BBS_IGNORE_ENTRY) {
936 continue;
937 }
938
939 if (BbsTable[Index].DeviceType != BbsType) {
940 continue;
941 }
942
943 *Buf = (UINT16) (Index & 0xFF);
944 Buf++;
945 }
946
947 return Buf;
948 }
949
950 /**
951 Create the device order buffer.
952
953 @param BbsTable The BBS table.
954 @param BbsCount The BBS Count.
955
956 @retval EFI_SUCCES The buffer is created and the EFI variable named
957 VAR_LEGACY_DEV_ORDER and gEfiLegacyDevOrderVariableGuid is
958 set correctly.
959 @retval EFI_OUT_OF_RESOURCES Memmory or storage is not enough.
960 @retval EFI_DEVICE_ERROR Fail to add the device order into EFI variable fail
961 because of hardware error.
962 **/
963 EFI_STATUS
964 BdsCreateDevOrder (
965 IN BBS_TABLE *BbsTable,
966 IN UINT16 BbsCount
967 )
968 {
969 UINTN Index;
970 UINTN FDCount;
971 UINTN HDCount;
972 UINTN CDCount;
973 UINTN NETCount;
974 UINTN BEVCount;
975 UINTN TotalSize;
976 UINTN HeaderSize;
977 LEGACY_DEV_ORDER_ENTRY *DevOrder;
978 LEGACY_DEV_ORDER_ENTRY *DevOrderPtr;
979 EFI_STATUS Status;
980
981 FDCount = 0;
982 HDCount = 0;
983 CDCount = 0;
984 NETCount = 0;
985 BEVCount = 0;
986 TotalSize = 0;
987 HeaderSize = sizeof (BBS_TYPE) + sizeof (UINT16);
988 DevOrder = NULL;
989 Status = EFI_SUCCESS;
990
991 //
992 // Count all boot devices
993 //
994 for (Index = 0; Index < BbsCount; Index++) {
995 if (BbsTable[Index].BootPriority == BBS_IGNORE_ENTRY) {
996 continue;
997 }
998
999 switch (BbsTable[Index].DeviceType) {
1000 case BBS_FLOPPY:
1001 FDCount++;
1002 break;
1003
1004 case BBS_HARDDISK:
1005 HDCount++;
1006 break;
1007
1008 case BBS_CDROM:
1009 CDCount++;
1010 break;
1011
1012 case BBS_EMBED_NETWORK:
1013 NETCount++;
1014 break;
1015
1016 case BBS_BEV_DEVICE:
1017 BEVCount++;
1018 break;
1019
1020 default:
1021 break;
1022 }
1023 }
1024
1025 TotalSize += (HeaderSize + sizeof (UINT16) * FDCount);
1026 TotalSize += (HeaderSize + sizeof (UINT16) * HDCount);
1027 TotalSize += (HeaderSize + sizeof (UINT16) * CDCount);
1028 TotalSize += (HeaderSize + sizeof (UINT16) * NETCount);
1029 TotalSize += (HeaderSize + sizeof (UINT16) * BEVCount);
1030
1031 //
1032 // Create buffer to hold all boot device order
1033 //
1034 DevOrder = AllocateZeroPool (TotalSize);
1035 if (NULL == DevOrder) {
1036 return EFI_OUT_OF_RESOURCES;
1037 }
1038 DevOrderPtr = DevOrder;
1039
1040 DevOrderPtr->BbsType = BBS_FLOPPY;
1041 DevOrderPtr->Length = (UINT16) (sizeof (DevOrderPtr->Length) + FDCount * sizeof (UINT16));
1042 DevOrderPtr = (LEGACY_DEV_ORDER_ENTRY *) BdsFillDevOrderBuf (BbsTable, BBS_FLOPPY, BbsCount, DevOrderPtr->Data);
1043
1044 DevOrderPtr->BbsType = BBS_HARDDISK;
1045 DevOrderPtr->Length = (UINT16) (sizeof (UINT16) + HDCount * sizeof (UINT16));
1046 DevOrderPtr = (LEGACY_DEV_ORDER_ENTRY *) BdsFillDevOrderBuf (BbsTable, BBS_HARDDISK, BbsCount, DevOrderPtr->Data);
1047
1048 DevOrderPtr->BbsType = BBS_CDROM;
1049 DevOrderPtr->Length = (UINT16) (sizeof (UINT16) + CDCount * sizeof (UINT16));
1050 DevOrderPtr = (LEGACY_DEV_ORDER_ENTRY *) BdsFillDevOrderBuf (BbsTable, BBS_CDROM, BbsCount, DevOrderPtr->Data);
1051
1052 DevOrderPtr->BbsType = BBS_EMBED_NETWORK;
1053 DevOrderPtr->Length = (UINT16) (sizeof (UINT16) + NETCount * sizeof (UINT16));
1054 DevOrderPtr = (LEGACY_DEV_ORDER_ENTRY *) BdsFillDevOrderBuf (BbsTable, BBS_EMBED_NETWORK, BbsCount, DevOrderPtr->Data);
1055
1056 DevOrderPtr->BbsType = BBS_BEV_DEVICE;
1057 DevOrderPtr->Length = (UINT16) (sizeof (UINT16) + BEVCount * sizeof (UINT16));
1058 DevOrderPtr = (LEGACY_DEV_ORDER_ENTRY *) BdsFillDevOrderBuf (BbsTable, BBS_BEV_DEVICE, BbsCount, DevOrderPtr->Data);
1059
1060 ASSERT (TotalSize == ((UINTN) DevOrderPtr - (UINTN) DevOrder));
1061
1062 //
1063 // Save device order for legacy boot device to variable.
1064 //
1065 Status = gRT->SetVariable (
1066 VAR_LEGACY_DEV_ORDER,
1067 &gEfiLegacyDevOrderVariableGuid,
1068 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1069 TotalSize,
1070 DevOrder
1071 );
1072 FreePool (DevOrder);
1073
1074 return Status;
1075 }
1076
1077 /**
1078 Add the legacy boot devices from BBS table into
1079 the legacy device boot order.
1080
1081 @retval EFI_SUCCESS The boot devices are added successfully.
1082 @retval EFI_NOT_FOUND The legacy boot devices are not found.
1083 @retval EFI_OUT_OF_RESOURCES Memmory or storage is not enough.
1084 @retval EFI_DEVICE_ERROR Fail to add the legacy device boot order into EFI variable
1085 because of hardware error.
1086 **/
1087 EFI_STATUS
1088 EFIAPI
1089 BdsUpdateLegacyDevOrder (
1090 VOID
1091 )
1092 {
1093 LEGACY_DEV_ORDER_ENTRY *DevOrder;
1094 LEGACY_DEV_ORDER_ENTRY *NewDevOrder;
1095 LEGACY_DEV_ORDER_ENTRY *Ptr;
1096 LEGACY_DEV_ORDER_ENTRY *NewPtr;
1097 UINTN DevOrderSize;
1098 EFI_LEGACY_BIOS_PROTOCOL *LegacyBios;
1099 EFI_STATUS Status;
1100 UINT16 HddCount;
1101 UINT16 BbsCount;
1102 HDD_INFO *LocalHddInfo;
1103 BBS_TABLE *LocalBbsTable;
1104 UINTN Index;
1105 UINTN Index2;
1106 UINTN *Idx;
1107 UINTN FDCount;
1108 UINTN HDCount;
1109 UINTN CDCount;
1110 UINTN NETCount;
1111 UINTN BEVCount;
1112 UINTN TotalSize;
1113 UINTN HeaderSize;
1114 UINT16 *NewFDPtr;
1115 UINT16 *NewHDPtr;
1116 UINT16 *NewCDPtr;
1117 UINT16 *NewNETPtr;
1118 UINT16 *NewBEVPtr;
1119 UINT16 *NewDevPtr;
1120 UINTN FDIndex;
1121 UINTN HDIndex;
1122 UINTN CDIndex;
1123 UINTN NETIndex;
1124 UINTN BEVIndex;
1125
1126 Idx = NULL;
1127 FDCount = 0;
1128 HDCount = 0;
1129 CDCount = 0;
1130 NETCount = 0;
1131 BEVCount = 0;
1132 TotalSize = 0;
1133 HeaderSize = sizeof (BBS_TYPE) + sizeof (UINT16);
1134 FDIndex = 0;
1135 HDIndex = 0;
1136 CDIndex = 0;
1137 NETIndex = 0;
1138 BEVIndex = 0;
1139 NewDevPtr = NULL;
1140
1141 Status = gBS->LocateProtocol (&gEfiLegacyBiosProtocolGuid, NULL, (VOID **) &LegacyBios);
1142 if (EFI_ERROR (Status)) {
1143 return Status;
1144 }
1145
1146 Status = LegacyBios->GetBbsInfo (
1147 LegacyBios,
1148 &HddCount,
1149 &LocalHddInfo,
1150 &BbsCount,
1151 &LocalBbsTable
1152 );
1153 if (EFI_ERROR (Status)) {
1154 return Status;
1155 }
1156
1157 DevOrder = BdsLibGetVariableAndSize (
1158 VAR_LEGACY_DEV_ORDER,
1159 &gEfiLegacyDevOrderVariableGuid,
1160 &DevOrderSize
1161 );
1162 if (NULL == DevOrder) {
1163 return BdsCreateDevOrder (LocalBbsTable, BbsCount);
1164 }
1165 //
1166 // First we figure out how many boot devices with same device type respectively
1167 //
1168 for (Index = 0; Index < BbsCount; Index++) {
1169 if ((LocalBbsTable[Index].BootPriority == BBS_IGNORE_ENTRY) ||
1170 (LocalBbsTable[Index].BootPriority == BBS_DO_NOT_BOOT_FROM)
1171 ) {
1172 continue;
1173 }
1174
1175 switch (LocalBbsTable[Index].DeviceType) {
1176 case BBS_FLOPPY:
1177 FDCount++;
1178 break;
1179
1180 case BBS_HARDDISK:
1181 HDCount++;
1182 break;
1183
1184 case BBS_CDROM:
1185 CDCount++;
1186 break;
1187
1188 case BBS_EMBED_NETWORK:
1189 NETCount++;
1190 break;
1191
1192 case BBS_BEV_DEVICE:
1193 BEVCount++;
1194 break;
1195
1196 default:
1197 break;
1198 }
1199 }
1200
1201 TotalSize += (HeaderSize + FDCount * sizeof (UINT16));
1202 TotalSize += (HeaderSize + HDCount * sizeof (UINT16));
1203 TotalSize += (HeaderSize + CDCount * sizeof (UINT16));
1204 TotalSize += (HeaderSize + NETCount * sizeof (UINT16));
1205 TotalSize += (HeaderSize + BEVCount * sizeof (UINT16));
1206
1207 NewDevOrder = AllocateZeroPool (TotalSize);
1208 if (NULL == NewDevOrder) {
1209 return EFI_OUT_OF_RESOURCES;
1210 }
1211
1212
1213
1214 //
1215 // copy FD
1216 //
1217 Ptr = DevOrder;
1218 NewPtr = NewDevOrder;
1219 NewPtr->BbsType = Ptr->BbsType;
1220 NewPtr->Length = (UINT16) (sizeof (UINT16) + FDCount * sizeof (UINT16));
1221 for (Index = 0; Index < Ptr->Length / sizeof (UINT16) - 1; Index++) {
1222 if (LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_IGNORE_ENTRY ||
1223 LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_DO_NOT_BOOT_FROM ||
1224 LocalBbsTable[Ptr->Data[Index] & 0xFF].DeviceType != BBS_FLOPPY
1225 ) {
1226 continue;
1227 }
1228
1229 NewPtr->Data[FDIndex] = Ptr->Data[Index];
1230 FDIndex++;
1231 }
1232 NewFDPtr = NewPtr->Data;
1233
1234 //
1235 // copy HD
1236 //
1237 Ptr = (LEGACY_DEV_ORDER_ENTRY *) (&Ptr->Data[Ptr->Length / sizeof (UINT16) - 1]);
1238 NewPtr = (LEGACY_DEV_ORDER_ENTRY *) (&NewPtr->Data[NewPtr->Length / sizeof (UINT16) -1]);
1239 NewPtr->BbsType = Ptr->BbsType;
1240 NewPtr->Length = (UINT16) (sizeof (UINT16) + HDCount * sizeof (UINT16));
1241 for (Index = 0; Index < Ptr->Length / sizeof (UINT16) - 1; Index++) {
1242 if (LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_IGNORE_ENTRY ||
1243 LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_DO_NOT_BOOT_FROM ||
1244 LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_LOWEST_PRIORITY ||
1245 LocalBbsTable[Ptr->Data[Index] & 0xFF].DeviceType != BBS_HARDDISK
1246 ) {
1247 continue;
1248 }
1249
1250 NewPtr->Data[HDIndex] = Ptr->Data[Index];
1251 HDIndex++;
1252 }
1253 NewHDPtr = NewPtr->Data;
1254
1255 //
1256 // copy CD
1257 //
1258 Ptr = (LEGACY_DEV_ORDER_ENTRY *) (&Ptr->Data[Ptr->Length / sizeof (UINT16) - 1]);
1259 NewPtr = (LEGACY_DEV_ORDER_ENTRY *) (&NewPtr->Data[NewPtr->Length / sizeof (UINT16) -1]);
1260 NewPtr->BbsType = Ptr->BbsType;
1261 NewPtr->Length = (UINT16) (sizeof (UINT16) + CDCount * sizeof (UINT16));
1262 for (Index = 0; Index < Ptr->Length / sizeof (UINT16) - 1; Index++) {
1263 if (LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_IGNORE_ENTRY ||
1264 LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_DO_NOT_BOOT_FROM ||
1265 LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_LOWEST_PRIORITY ||
1266 LocalBbsTable[Ptr->Data[Index] & 0xFF].DeviceType != BBS_CDROM
1267 ) {
1268 continue;
1269 }
1270
1271 NewPtr->Data[CDIndex] = Ptr->Data[Index];
1272 CDIndex++;
1273 }
1274 NewCDPtr = NewPtr->Data;
1275
1276 //
1277 // copy NET
1278 //
1279 Ptr = (LEGACY_DEV_ORDER_ENTRY *) (&Ptr->Data[Ptr->Length / sizeof (UINT16) - 1]);
1280 NewPtr = (LEGACY_DEV_ORDER_ENTRY *) (&NewPtr->Data[NewPtr->Length / sizeof (UINT16) -1]);
1281 NewPtr->BbsType = Ptr->BbsType;
1282 NewPtr->Length = (UINT16) (sizeof (UINT16) + NETCount * sizeof (UINT16));
1283 for (Index = 0; Index < Ptr->Length / sizeof (UINT16) - 1; Index++) {
1284 if (LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_IGNORE_ENTRY ||
1285 LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_DO_NOT_BOOT_FROM ||
1286 LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_LOWEST_PRIORITY ||
1287 LocalBbsTable[Ptr->Data[Index] & 0xFF].DeviceType != BBS_EMBED_NETWORK
1288 ) {
1289 continue;
1290 }
1291
1292 NewPtr->Data[NETIndex] = Ptr->Data[Index];
1293 NETIndex++;
1294 }
1295 NewNETPtr = NewPtr->Data;
1296
1297 //
1298 // copy BEV
1299 //
1300 Ptr = (LEGACY_DEV_ORDER_ENTRY *) (&Ptr->Data[Ptr->Length / sizeof (UINT16) - 1]);
1301 NewPtr = (LEGACY_DEV_ORDER_ENTRY *) (&NewPtr->Data[NewPtr->Length / sizeof (UINT16) -1]);
1302 NewPtr->BbsType = Ptr->BbsType;
1303 NewPtr->Length = (UINT16) (sizeof (UINT16) + BEVCount * sizeof (UINT16));
1304 for (Index = 0; Index < Ptr->Length / sizeof (UINT16) - 1; Index++) {
1305 if (LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_IGNORE_ENTRY ||
1306 LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_DO_NOT_BOOT_FROM ||
1307 LocalBbsTable[Ptr->Data[Index] & 0xFF].BootPriority == BBS_LOWEST_PRIORITY ||
1308 LocalBbsTable[Ptr->Data[Index] & 0xFF].DeviceType != BBS_BEV_DEVICE
1309 ) {
1310 continue;
1311 }
1312
1313 NewPtr->Data[BEVIndex] = Ptr->Data[Index];
1314 BEVIndex++;
1315 }
1316 NewBEVPtr = NewPtr->Data;
1317
1318 for (Index = 0; Index < BbsCount; Index++) {
1319 if ((LocalBbsTable[Index].BootPriority == BBS_IGNORE_ENTRY) ||
1320 (LocalBbsTable[Index].BootPriority == BBS_DO_NOT_BOOT_FROM)
1321 ) {
1322 continue;
1323 }
1324
1325 switch (LocalBbsTable[Index].DeviceType) {
1326 case BBS_FLOPPY:
1327 Idx = &FDIndex;
1328 NewDevPtr = NewFDPtr;
1329 break;
1330
1331 case BBS_HARDDISK:
1332 Idx = &HDIndex;
1333 NewDevPtr = NewHDPtr;
1334 break;
1335
1336 case BBS_CDROM:
1337 Idx = &CDIndex;
1338 NewDevPtr = NewCDPtr;
1339 break;
1340
1341 case BBS_EMBED_NETWORK:
1342 Idx = &NETIndex;
1343 NewDevPtr = NewNETPtr;
1344 break;
1345
1346 case BBS_BEV_DEVICE:
1347 Idx = &BEVIndex;
1348 NewDevPtr = NewBEVPtr;
1349 break;
1350
1351 default:
1352 Idx = NULL;
1353 break;
1354 }
1355 //
1356 // at this point we have copied those valid indexes to new buffer
1357 // and we should check if there is any new appeared boot device
1358 //
1359 if (Idx != NULL) {
1360 for (Index2 = 0; Index2 < *Idx; Index2++) {
1361 if ((NewDevPtr[Index2] & 0xFF) == (UINT16) Index) {
1362 break;
1363 }
1364 }
1365
1366 if (Index2 == *Idx) {
1367 //
1368 // Index2 == *Idx means we didn't find Index
1369 // so Index is a new appeared device's index in BBS table
1370 // insert it before disabled indexes.
1371 //
1372 for (Index2 = 0; Index2 < *Idx; Index2++) {
1373 if ((NewDevPtr[Index2] & 0xFF00) == 0xFF00) {
1374 break;
1375 }
1376 }
1377 CopyMem (&NewDevPtr[Index2 + 1], &NewDevPtr[Index2], (*Idx - Index2) * sizeof (UINT16));
1378 NewDevPtr[Index2] = (UINT16) (Index & 0xFF);
1379 (*Idx)++;
1380 }
1381 }
1382 }
1383
1384 FreePool (DevOrder);
1385
1386 Status = gRT->SetVariable (
1387 VAR_LEGACY_DEV_ORDER,
1388 &gEfiLegacyDevOrderVariableGuid,
1389 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1390 TotalSize,
1391 NewDevOrder
1392 );
1393 FreePool (NewDevOrder);
1394
1395 return Status;
1396 }
1397
1398 /**
1399 Set Boot Priority for specified device type.
1400
1401 @param DeviceType The device type.
1402 @param BbsIndex The BBS index to set the highest priority. Ignore when -1.
1403 @param LocalBbsTable The BBS table.
1404 @param Priority The prority table.
1405
1406 @retval EFI_SUCCESS The function completes successfully.
1407 @retval EFI_NOT_FOUND Failed to find device.
1408 @retval EFI_OUT_OF_RESOURCES Failed to get the efi variable of device order.
1409
1410 **/
1411 EFI_STATUS
1412 BdsSetBootPriority4SameTypeDev (
1413 IN UINT16 DeviceType,
1414 IN UINTN BbsIndex,
1415 IN OUT BBS_TABLE *LocalBbsTable,
1416 IN OUT UINT16 *Priority
1417 )
1418 {
1419 LEGACY_DEV_ORDER_ENTRY *DevOrder;
1420 LEGACY_DEV_ORDER_ENTRY *DevOrderPtr;
1421 UINTN DevOrderSize;
1422 UINTN Index;
1423
1424 DevOrder = BdsLibGetVariableAndSize (
1425 VAR_LEGACY_DEV_ORDER,
1426 &gEfiLegacyDevOrderVariableGuid,
1427 &DevOrderSize
1428 );
1429 if (NULL == DevOrder) {
1430 return EFI_OUT_OF_RESOURCES;
1431 }
1432
1433 DevOrderPtr = DevOrder;
1434 while ((UINT8 *) DevOrderPtr < (UINT8 *) DevOrder + DevOrderSize) {
1435 if (DevOrderPtr->BbsType == DeviceType) {
1436 break;
1437 }
1438
1439 DevOrderPtr = (LEGACY_DEV_ORDER_ENTRY *) ((UINTN) DevOrderPtr + sizeof (BBS_TYPE) + DevOrderPtr->Length);
1440 }
1441
1442 if ((UINT8 *) DevOrderPtr >= (UINT8 *) DevOrder + DevOrderSize) {
1443 FreePool (DevOrder);
1444 return EFI_NOT_FOUND;
1445 }
1446
1447 if (BbsIndex != (UINTN) -1) {
1448 LocalBbsTable[BbsIndex].BootPriority = *Priority;
1449 (*Priority)++;
1450 }
1451 //
1452 // If the high byte of the DevIndex is 0xFF, it indicates that this device has been disabled.
1453 //
1454 for (Index = 0; Index < DevOrderPtr->Length / sizeof (UINT16) - 1; Index++) {
1455 if ((DevOrderPtr->Data[Index] & 0xFF00) == 0xFF00) {
1456 //
1457 // LocalBbsTable[DevIndex[Index] & 0xFF].BootPriority = BBS_DISABLED_ENTRY;
1458 //
1459 } else if (DevOrderPtr->Data[Index] != BbsIndex) {
1460 LocalBbsTable[DevOrderPtr->Data[Index]].BootPriority = *Priority;
1461 (*Priority)++;
1462 }
1463 }
1464
1465 FreePool (DevOrder);
1466 return EFI_SUCCESS;
1467 }
1468
1469 /**
1470 Print the BBS Table.
1471
1472 @param LocalBbsTable The BBS table.
1473 @param BbsCount The count of entry in BBS table.
1474 **/
1475 VOID
1476 PrintBbsTable (
1477 IN BBS_TABLE *LocalBbsTable,
1478 IN UINT16 BbsCount
1479 )
1480 {
1481 UINT16 Idx;
1482
1483 DEBUG ((DEBUG_ERROR, "\n"));
1484 DEBUG ((DEBUG_ERROR, " NO Prio bb/dd/ff cl/sc Type Stat segm:offs\n"));
1485 DEBUG ((DEBUG_ERROR, "=============================================\n"));
1486 for (Idx = 0; Idx < BbsCount; Idx++) {
1487 if ((LocalBbsTable[Idx].BootPriority == BBS_IGNORE_ENTRY) ||
1488 (LocalBbsTable[Idx].BootPriority == BBS_DO_NOT_BOOT_FROM) ||
1489 (LocalBbsTable[Idx].BootPriority == BBS_LOWEST_PRIORITY)
1490 ) {
1491 continue;
1492 }
1493
1494 DEBUG (
1495 (DEBUG_ERROR,
1496 " %02x: %04x %02x/%02x/%02x %02x/%02x %04x %04x %04x:%04x\n",
1497 (UINTN) Idx,
1498 (UINTN) LocalBbsTable[Idx].BootPriority,
1499 (UINTN) LocalBbsTable[Idx].Bus,
1500 (UINTN) LocalBbsTable[Idx].Device,
1501 (UINTN) LocalBbsTable[Idx].Function,
1502 (UINTN) LocalBbsTable[Idx].Class,
1503 (UINTN) LocalBbsTable[Idx].SubClass,
1504 (UINTN) LocalBbsTable[Idx].DeviceType,
1505 (UINTN) * (UINT16 *) &LocalBbsTable[Idx].StatusFlags,
1506 (UINTN) LocalBbsTable[Idx].BootHandlerSegment,
1507 (UINTN) LocalBbsTable[Idx].BootHandlerOffset,
1508 (UINTN) ((LocalBbsTable[Idx].MfgStringSegment << 4) + LocalBbsTable[Idx].MfgStringOffset),
1509 (UINTN) ((LocalBbsTable[Idx].DescStringSegment << 4) + LocalBbsTable[Idx].DescStringOffset))
1510 );
1511 }
1512
1513 DEBUG ((DEBUG_ERROR, "\n"));
1514 }
1515
1516 /**
1517 Set the boot priority for BBS entries based on boot option entry and boot order.
1518
1519 @param Entry The boot option is to be checked for refresh BBS table.
1520
1521 @retval EFI_SUCCESS The boot priority for BBS entries is refreshed successfully.
1522 @retval EFI_NOT_FOUND BBS entries can't be found.
1523 @retval EFI_OUT_OF_RESOURCES Failed to get the legacy device boot order.
1524 **/
1525 EFI_STATUS
1526 EFIAPI
1527 BdsRefreshBbsTableForBoot (
1528 IN BDS_COMMON_OPTION *Entry
1529 )
1530 {
1531 EFI_STATUS Status;
1532 UINT16 BbsIndex;
1533 UINT16 HddCount;
1534 UINT16 BbsCount;
1535 HDD_INFO *LocalHddInfo;
1536 BBS_TABLE *LocalBbsTable;
1537 UINT16 DevType;
1538 EFI_LEGACY_BIOS_PROTOCOL *LegacyBios;
1539 UINTN Index;
1540 UINT16 Priority;
1541 UINT16 *BootOrder;
1542 UINTN BootOrderSize;
1543 UINT8 *BootOptionVar;
1544 UINTN BootOptionSize;
1545 CHAR16 BootOption[9];
1546 UINT8 *Ptr;
1547 UINT16 DevPathLen;
1548 EFI_DEVICE_PATH_PROTOCOL *DevPath;
1549 UINT16 *DeviceType;
1550 UINTN DeviceTypeCount;
1551 UINTN DeviceTypeIndex;
1552
1553 HddCount = 0;
1554 BbsCount = 0;
1555 LocalHddInfo = NULL;
1556 LocalBbsTable = NULL;
1557 DevType = BBS_UNKNOWN;
1558
1559 Status = gBS->LocateProtocol (&gEfiLegacyBiosProtocolGuid, NULL, (VOID **) &LegacyBios);
1560 if (EFI_ERROR (Status)) {
1561 return Status;
1562 }
1563
1564 LegacyBios->GetBbsInfo (
1565 LegacyBios,
1566 &HddCount,
1567 &LocalHddInfo,
1568 &BbsCount,
1569 &LocalBbsTable
1570 );
1571 //
1572 // First, set all the present devices' boot priority to BBS_UNPRIORITIZED_ENTRY
1573 // We will set them according to the settings setup by user
1574 //
1575 for (Index = 0; Index < BbsCount; Index++) {
1576 if (!((BBS_IGNORE_ENTRY == LocalBbsTable[Index].BootPriority) ||
1577 (BBS_DO_NOT_BOOT_FROM == LocalBbsTable[Index].BootPriority) ||
1578 (BBS_LOWEST_PRIORITY == LocalBbsTable[Index].BootPriority))) {
1579 LocalBbsTable[Index].BootPriority = BBS_UNPRIORITIZED_ENTRY;
1580 }
1581 }
1582 //
1583 // boot priority always starts at 0
1584 //
1585 Priority = 0;
1586 if (Entry->LoadOptionsSize == sizeof (BBS_TABLE) + sizeof (UINT16)) {
1587 //
1588 // If Entry stands for a legacy boot option, we prioritize the devices with the same type first.
1589 //
1590 DevType = ((BBS_TABLE *) Entry->LoadOptions)->DeviceType;
1591 BbsIndex = *(UINT16 *) ((BBS_TABLE *) Entry->LoadOptions + 1);
1592 Status = BdsSetBootPriority4SameTypeDev (
1593 DevType,
1594 BbsIndex,
1595 LocalBbsTable,
1596 &Priority
1597 );
1598 if (EFI_ERROR (Status)) {
1599 return Status;
1600 }
1601 }
1602 //
1603 // we have to set the boot priority for other BBS entries with different device types
1604 //
1605 BootOrder = BdsLibGetVariableAndSize (
1606 L"BootOrder",
1607 &gEfiGlobalVariableGuid,
1608 &BootOrderSize
1609 );
1610 DeviceType = AllocatePool (BootOrderSize + sizeof (UINT16));
1611 ASSERT (DeviceType != NULL);
1612
1613 DeviceType[0] = DevType;
1614 DeviceTypeCount = 1;
1615 for (Index = 0; ((BootOrder != NULL) && (Index < BootOrderSize / sizeof (UINT16))); Index++) {
1616 UnicodeSPrint (BootOption, sizeof (BootOption), L"Boot%04x", BootOrder[Index]);
1617 BootOptionVar = BdsLibGetVariableAndSize (
1618 BootOption,
1619 &gEfiGlobalVariableGuid,
1620 &BootOptionSize
1621 );
1622 if (NULL == BootOptionVar) {
1623 continue;
1624 }
1625
1626 Ptr = BootOptionVar;
1627
1628 Ptr += sizeof (UINT32);
1629 DevPathLen = *(UINT16 *) Ptr;
1630 Ptr += sizeof (UINT16);
1631 Ptr += StrSize ((UINT16 *) Ptr);
1632 DevPath = (EFI_DEVICE_PATH_PROTOCOL *) Ptr;
1633 if (BBS_DEVICE_PATH != DevPath->Type || BBS_BBS_DP != DevPath->SubType) {
1634 FreePool (BootOptionVar);
1635 continue;
1636 }
1637
1638 Ptr += DevPathLen;
1639 DevType = ((BBS_TABLE *) Ptr)->DeviceType;
1640 for (DeviceTypeIndex = 0; DeviceTypeIndex < DeviceTypeCount; DeviceTypeIndex++) {
1641 if (DeviceType[DeviceTypeIndex] == DevType) {
1642 break;
1643 }
1644 }
1645 if (DeviceTypeIndex < DeviceTypeCount) {
1646 //
1647 // We don't want to process twice for a device type
1648 //
1649 FreePool (BootOptionVar);
1650 continue;
1651 }
1652
1653 DeviceType[DeviceTypeCount] = DevType;
1654 DeviceTypeCount++;
1655
1656 Status = BdsSetBootPriority4SameTypeDev (
1657 DevType,
1658 (UINTN) -1,
1659 LocalBbsTable,
1660 &Priority
1661 );
1662 FreePool (BootOptionVar);
1663 if (EFI_ERROR (Status)) {
1664 break;
1665 }
1666 }
1667
1668 FreePool (DeviceType);
1669
1670 if (BootOrder != NULL) {
1671 FreePool (BootOrder);
1672 }
1673
1674 DEBUG_CODE_BEGIN();
1675 PrintBbsTable (LocalBbsTable, BbsCount);
1676 DEBUG_CODE_END();
1677
1678 return Status;
1679 }
1680
1681 /**
1682 Boot the legacy system with the boot option
1683
1684 @param Option The legacy boot option which have BBS device path
1685
1686 @retval EFI_UNSUPPORTED There is no legacybios protocol, do not support
1687 legacy boot.
1688 @retval EFI_STATUS Return the status of LegacyBios->LegacyBoot ().
1689
1690 **/
1691 EFI_STATUS
1692 BdsLibDoLegacyBoot (
1693 IN BDS_COMMON_OPTION *Option
1694 )
1695 {
1696 EFI_STATUS Status;
1697 EFI_LEGACY_BIOS_PROTOCOL *LegacyBios;
1698 EFI_EVENT LegacyBootEvent;
1699
1700 Status = gBS->LocateProtocol (&gEfiLegacyBiosProtocolGuid, NULL, (VOID **) &LegacyBios);
1701 if (EFI_ERROR (Status)) {
1702 //
1703 // If no LegacyBios protocol we do not support legacy boot
1704 //
1705 return EFI_UNSUPPORTED;
1706 }
1707 //
1708 // Notes: if we separate the int 19, then we don't need to refresh BBS
1709 //
1710 BdsRefreshBbsTableForBoot (Option);
1711
1712 //
1713 // Write boot to OS performance data for legacy boot.
1714 //
1715 PERF_CODE (
1716 //
1717 // Create an event to be signalled when Legacy Boot occurs to write performance data.
1718 //
1719 Status = EfiCreateEventLegacyBootEx(
1720 TPL_NOTIFY,
1721 BmEndOfBdsPerfCode,
1722 NULL,
1723 &LegacyBootEvent
1724 );
1725 ASSERT_EFI_ERROR (Status);
1726 );
1727
1728 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Legacy Boot: %S\n", Option->Description));
1729 return LegacyBios->LegacyBoot (
1730 LegacyBios,
1731 (BBS_BBS_DEVICE_PATH *) Option->DevicePath,
1732 Option->LoadOptionsSize,
1733 Option->LoadOptions
1734 );
1735 }
1736
1737 /**
1738 Internal function to check if the input boot option is a valid EFI NV Boot####.
1739
1740 @param OptionToCheck Boot option to be checked.
1741
1742 @retval TRUE This boot option matches a valid EFI NV Boot####.
1743 @retval FALSE If not.
1744
1745 **/
1746 BOOLEAN
1747 IsBootOptionValidNVVarialbe (
1748 IN BDS_COMMON_OPTION *OptionToCheck
1749 )
1750 {
1751 LIST_ENTRY TempList;
1752 BDS_COMMON_OPTION *BootOption;
1753 BOOLEAN Valid;
1754 CHAR16 OptionName[20];
1755
1756 Valid = FALSE;
1757
1758 InitializeListHead (&TempList);
1759 UnicodeSPrint (OptionName, sizeof (OptionName), L"Boot%04x", OptionToCheck->BootCurrent);
1760
1761 BootOption = BdsLibVariableToOption (&TempList, OptionName);
1762 if (BootOption == NULL) {
1763 return FALSE;
1764 }
1765
1766 //
1767 // If the Boot Option Number and Device Path matches, OptionToCheck matches a
1768 // valid EFI NV Boot####.
1769 //
1770 if ((OptionToCheck->BootCurrent == BootOption->BootCurrent) &&
1771 (CompareMem (OptionToCheck->DevicePath, BootOption->DevicePath, GetDevicePathSize (OptionToCheck->DevicePath)) == 0))
1772 {
1773 Valid = TRUE;
1774 }
1775
1776 FreePool (BootOption);
1777
1778 return Valid;
1779 }
1780
1781 /**
1782 Check whether a USB device match the specified USB Class device path. This
1783 function follows "Load Option Processing" behavior in UEFI specification.
1784
1785 @param UsbIo USB I/O protocol associated with the USB device.
1786 @param UsbClass The USB Class device path to match.
1787
1788 @retval TRUE The USB device match the USB Class device path.
1789 @retval FALSE The USB device does not match the USB Class device path.
1790
1791 **/
1792 BOOLEAN
1793 BdsMatchUsbClass (
1794 IN EFI_USB_IO_PROTOCOL *UsbIo,
1795 IN USB_CLASS_DEVICE_PATH *UsbClass
1796 )
1797 {
1798 EFI_STATUS Status;
1799 EFI_USB_DEVICE_DESCRIPTOR DevDesc;
1800 EFI_USB_INTERFACE_DESCRIPTOR IfDesc;
1801 UINT8 DeviceClass;
1802 UINT8 DeviceSubClass;
1803 UINT8 DeviceProtocol;
1804
1805 if ((DevicePathType (UsbClass) != MESSAGING_DEVICE_PATH) ||
1806 (DevicePathSubType (UsbClass) != MSG_USB_CLASS_DP)){
1807 return FALSE;
1808 }
1809
1810 //
1811 // Check Vendor Id and Product Id.
1812 //
1813 Status = UsbIo->UsbGetDeviceDescriptor (UsbIo, &DevDesc);
1814 if (EFI_ERROR (Status)) {
1815 return FALSE;
1816 }
1817
1818 if ((UsbClass->VendorId != 0xffff) &&
1819 (UsbClass->VendorId != DevDesc.IdVendor)) {
1820 return FALSE;
1821 }
1822
1823 if ((UsbClass->ProductId != 0xffff) &&
1824 (UsbClass->ProductId != DevDesc.IdProduct)) {
1825 return FALSE;
1826 }
1827
1828 DeviceClass = DevDesc.DeviceClass;
1829 DeviceSubClass = DevDesc.DeviceSubClass;
1830 DeviceProtocol = DevDesc.DeviceProtocol;
1831 if (DeviceClass == 0) {
1832 //
1833 // If Class in Device Descriptor is set to 0, use the Class, SubClass and
1834 // Protocol in Interface Descriptor instead.
1835 //
1836 Status = UsbIo->UsbGetInterfaceDescriptor (UsbIo, &IfDesc);
1837 if (EFI_ERROR (Status)) {
1838 return FALSE;
1839 }
1840
1841 DeviceClass = IfDesc.InterfaceClass;
1842 DeviceSubClass = IfDesc.InterfaceSubClass;
1843 DeviceProtocol = IfDesc.InterfaceProtocol;
1844 }
1845
1846 //
1847 // Check Class, SubClass and Protocol.
1848 //
1849 if ((UsbClass->DeviceClass != 0xff) &&
1850 (UsbClass->DeviceClass != DeviceClass)) {
1851 return FALSE;
1852 }
1853
1854 if ((UsbClass->DeviceSubClass != 0xff) &&
1855 (UsbClass->DeviceSubClass != DeviceSubClass)) {
1856 return FALSE;
1857 }
1858
1859 if ((UsbClass->DeviceProtocol != 0xff) &&
1860 (UsbClass->DeviceProtocol != DeviceProtocol)) {
1861 return FALSE;
1862 }
1863
1864 return TRUE;
1865 }
1866
1867 /**
1868 Check whether a USB device match the specified USB WWID device path. This
1869 function follows "Load Option Processing" behavior in UEFI specification.
1870
1871 @param UsbIo USB I/O protocol associated with the USB device.
1872 @param UsbWwid The USB WWID device path to match.
1873
1874 @retval TRUE The USB device match the USB WWID device path.
1875 @retval FALSE The USB device does not match the USB WWID device path.
1876
1877 **/
1878 BOOLEAN
1879 BdsMatchUsbWwid (
1880 IN EFI_USB_IO_PROTOCOL *UsbIo,
1881 IN USB_WWID_DEVICE_PATH *UsbWwid
1882 )
1883 {
1884 EFI_STATUS Status;
1885 EFI_USB_DEVICE_DESCRIPTOR DevDesc;
1886 EFI_USB_INTERFACE_DESCRIPTOR IfDesc;
1887 UINT16 *LangIdTable;
1888 UINT16 TableSize;
1889 UINT16 Index;
1890 CHAR16 *CompareStr;
1891 UINTN CompareLen;
1892 CHAR16 *SerialNumberStr;
1893 UINTN Length;
1894
1895 if ((DevicePathType (UsbWwid) != MESSAGING_DEVICE_PATH) ||
1896 (DevicePathSubType (UsbWwid) != MSG_USB_WWID_DP )){
1897 return FALSE;
1898 }
1899
1900 //
1901 // Check Vendor Id and Product Id.
1902 //
1903 Status = UsbIo->UsbGetDeviceDescriptor (UsbIo, &DevDesc);
1904 if (EFI_ERROR (Status)) {
1905 return FALSE;
1906 }
1907 if ((DevDesc.IdVendor != UsbWwid->VendorId) ||
1908 (DevDesc.IdProduct != UsbWwid->ProductId)) {
1909 return FALSE;
1910 }
1911
1912 //
1913 // Check Interface Number.
1914 //
1915 Status = UsbIo->UsbGetInterfaceDescriptor (UsbIo, &IfDesc);
1916 if (EFI_ERROR (Status)) {
1917 return FALSE;
1918 }
1919 if (IfDesc.InterfaceNumber != UsbWwid->InterfaceNumber) {
1920 return FALSE;
1921 }
1922
1923 //
1924 // Check Serial Number.
1925 //
1926 if (DevDesc.StrSerialNumber == 0) {
1927 return FALSE;
1928 }
1929
1930 //
1931 // Get all supported languages.
1932 //
1933 TableSize = 0;
1934 LangIdTable = NULL;
1935 Status = UsbIo->UsbGetSupportedLanguages (UsbIo, &LangIdTable, &TableSize);
1936 if (EFI_ERROR (Status) || (TableSize == 0) || (LangIdTable == NULL)) {
1937 return FALSE;
1938 }
1939
1940 //
1941 // Serial number in USB WWID device path is the last 64-or-less UTF-16 characters.
1942 //
1943 CompareStr = (CHAR16 *) (UINTN) (UsbWwid + 1);
1944 CompareLen = (DevicePathNodeLength (UsbWwid) - sizeof (USB_WWID_DEVICE_PATH)) / sizeof (CHAR16);
1945 if (CompareStr[CompareLen - 1] == L'\0') {
1946 CompareLen--;
1947 }
1948
1949 //
1950 // Compare serial number in each supported language.
1951 //
1952 for (Index = 0; Index < TableSize / sizeof (UINT16); Index++) {
1953 SerialNumberStr = NULL;
1954 Status = UsbIo->UsbGetStringDescriptor (
1955 UsbIo,
1956 LangIdTable[Index],
1957 DevDesc.StrSerialNumber,
1958 &SerialNumberStr
1959 );
1960 if (EFI_ERROR (Status) || (SerialNumberStr == NULL)) {
1961 continue;
1962 }
1963
1964 Length = StrLen (SerialNumberStr);
1965 if ((Length >= CompareLen) &&
1966 (CompareMem (SerialNumberStr + Length - CompareLen, CompareStr, CompareLen * sizeof (CHAR16)) == 0)) {
1967 FreePool (SerialNumberStr);
1968 return TRUE;
1969 }
1970
1971 FreePool (SerialNumberStr);
1972 }
1973
1974 return FALSE;
1975 }
1976
1977 /**
1978 Find a USB device path which match the specified short-form device path start
1979 with USB Class or USB WWID device path and load the boot file then return the
1980 image handle. If ParentDevicePath is NULL, this function will search in all USB
1981 devices of the platform. If ParentDevicePath is not NULL,this function will only
1982 search in its child devices.
1983
1984 @param ParentDevicePath The device path of the parent.
1985 @param ShortFormDevicePath The USB Class or USB WWID device path to match.
1986
1987 @return The image Handle if find load file from specified short-form device path
1988 or NULL if not found.
1989
1990 **/
1991 EFI_HANDLE *
1992 BdsFindUsbDevice (
1993 IN EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath,
1994 IN EFI_DEVICE_PATH_PROTOCOL *ShortFormDevicePath
1995 )
1996 {
1997 EFI_STATUS Status;
1998 UINTN UsbIoHandleCount;
1999 EFI_HANDLE *UsbIoHandleBuffer;
2000 EFI_DEVICE_PATH_PROTOCOL *UsbIoDevicePath;
2001 EFI_USB_IO_PROTOCOL *UsbIo;
2002 UINTN Index;
2003 UINTN ParentSize;
2004 UINTN Size;
2005 EFI_HANDLE ImageHandle;
2006 EFI_HANDLE Handle;
2007 EFI_DEVICE_PATH_PROTOCOL *FullDevicePath;
2008 EFI_DEVICE_PATH_PROTOCOL *NextDevicePath;
2009
2010 FullDevicePath = NULL;
2011 ImageHandle = NULL;
2012
2013 //
2014 // Get all UsbIo Handles.
2015 //
2016 UsbIoHandleCount = 0;
2017 UsbIoHandleBuffer = NULL;
2018 Status = gBS->LocateHandleBuffer (
2019 ByProtocol,
2020 &gEfiUsbIoProtocolGuid,
2021 NULL,
2022 &UsbIoHandleCount,
2023 &UsbIoHandleBuffer
2024 );
2025 if (EFI_ERROR (Status) || (UsbIoHandleCount == 0) || (UsbIoHandleBuffer == NULL)) {
2026 return NULL;
2027 }
2028
2029 ParentSize = (ParentDevicePath == NULL) ? 0 : GetDevicePathSize (ParentDevicePath);
2030 for (Index = 0; Index < UsbIoHandleCount; Index++) {
2031 //
2032 // Get the Usb IO interface.
2033 //
2034 Status = gBS->HandleProtocol(
2035 UsbIoHandleBuffer[Index],
2036 &gEfiUsbIoProtocolGuid,
2037 (VOID **) &UsbIo
2038 );
2039 if (EFI_ERROR (Status)) {
2040 continue;
2041 }
2042
2043 UsbIoDevicePath = DevicePathFromHandle (UsbIoHandleBuffer[Index]);
2044 if (UsbIoDevicePath == NULL) {
2045 continue;
2046 }
2047
2048 if (ParentDevicePath != NULL) {
2049 //
2050 // Compare starting part of UsbIoHandle's device path with ParentDevicePath.
2051 //
2052 Size = GetDevicePathSize (UsbIoDevicePath);
2053 if ((Size < ParentSize) ||
2054 (CompareMem (UsbIoDevicePath, ParentDevicePath, ParentSize - END_DEVICE_PATH_LENGTH) != 0)) {
2055 continue;
2056 }
2057 }
2058
2059 if (BdsMatchUsbClass (UsbIo, (USB_CLASS_DEVICE_PATH *) ShortFormDevicePath) ||
2060 BdsMatchUsbWwid (UsbIo, (USB_WWID_DEVICE_PATH *) ShortFormDevicePath)) {
2061 //
2062 // Try to find if there is the boot file in this DevicePath
2063 //
2064 NextDevicePath = NextDevicePathNode (ShortFormDevicePath);
2065 if (!IsDevicePathEnd (NextDevicePath)) {
2066 FullDevicePath = AppendDevicePath (UsbIoDevicePath, NextDevicePath);
2067 //
2068 // Connect the full device path, so that Simple File System protocol
2069 // could be installed for this USB device.
2070 //
2071 BdsLibConnectDevicePath (FullDevicePath);
2072 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderLoad));
2073 Status = gBS->LoadImage (
2074 TRUE,
2075 gImageHandle,
2076 FullDevicePath,
2077 NULL,
2078 0,
2079 &ImageHandle
2080 );
2081 FreePool (FullDevicePath);
2082 } else {
2083 FullDevicePath = UsbIoDevicePath;
2084 Status = EFI_NOT_FOUND;
2085 }
2086
2087 //
2088 // If we didn't find an image directly, we need to try as if it is a removable device boot option
2089 // and load the image according to the default boot behavior for removable device.
2090 //
2091 if (EFI_ERROR (Status)) {
2092 //
2093 // check if there is a bootable removable media could be found in this device path ,
2094 // and get the bootable media handle
2095 //
2096 Handle = BdsLibGetBootableHandle(UsbIoDevicePath);
2097 if (Handle == NULL) {
2098 continue;
2099 }
2100 //
2101 // Load the default boot file \EFI\BOOT\boot{machinename}.EFI from removable Media
2102 // machinename is ia32, ia64, x64, ...
2103 //
2104 FullDevicePath = FileDevicePath (Handle, EFI_REMOVABLE_MEDIA_FILE_NAME);
2105 if (FullDevicePath != NULL) {
2106 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderLoad));
2107 Status = gBS->LoadImage (
2108 TRUE,
2109 gImageHandle,
2110 FullDevicePath,
2111 NULL,
2112 0,
2113 &ImageHandle
2114 );
2115 if (EFI_ERROR (Status)) {
2116 //
2117 // The DevicePath failed, and it's not a valid
2118 // removable media device.
2119 //
2120 continue;
2121 }
2122 } else {
2123 continue;
2124 }
2125 }
2126 break;
2127 }
2128 }
2129
2130 FreePool (UsbIoHandleBuffer);
2131 return ImageHandle;
2132 }
2133
2134 /**
2135 Expand USB Class or USB WWID device path node to be full device path of a USB
2136 device in platform then load the boot file on this full device path and return the
2137 image handle.
2138
2139 This function support following 4 cases:
2140 1) Boot Option device path starts with a USB Class or USB WWID device path,
2141 and there is no Media FilePath device path in the end.
2142 In this case, it will follow Removable Media Boot Behavior.
2143 2) Boot Option device path starts with a USB Class or USB WWID device path,
2144 and ended with Media FilePath device path.
2145 3) Boot Option device path starts with a full device path to a USB Host Controller,
2146 contains a USB Class or USB WWID device path node, while not ended with Media
2147 FilePath device path. In this case, it will follow Removable Media Boot Behavior.
2148 4) Boot Option device path starts with a full device path to a USB Host Controller,
2149 contains a USB Class or USB WWID device path node, and ended with Media
2150 FilePath device path.
2151
2152 @param DevicePath The Boot Option device path.
2153
2154 @return The image handle of boot file, or NULL if there is no boot file found in
2155 the specified USB Class or USB WWID device path.
2156
2157 **/
2158 EFI_HANDLE *
2159 BdsExpandUsbShortFormDevicePath (
2160 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
2161 )
2162 {
2163 EFI_HANDLE *ImageHandle;
2164 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
2165 EFI_DEVICE_PATH_PROTOCOL *ShortFormDevicePath;
2166
2167 //
2168 // Search for USB Class or USB WWID device path node.
2169 //
2170 ShortFormDevicePath = NULL;
2171 ImageHandle = NULL;
2172 TempDevicePath = DevicePath;
2173 while (!IsDevicePathEnd (TempDevicePath)) {
2174 if ((DevicePathType (TempDevicePath) == MESSAGING_DEVICE_PATH) &&
2175 ((DevicePathSubType (TempDevicePath) == MSG_USB_CLASS_DP) ||
2176 (DevicePathSubType (TempDevicePath) == MSG_USB_WWID_DP))) {
2177 ShortFormDevicePath = TempDevicePath;
2178 break;
2179 }
2180 TempDevicePath = NextDevicePathNode (TempDevicePath);
2181 }
2182
2183 if (ShortFormDevicePath == NULL) {
2184 //
2185 // No USB Class or USB WWID device path node found, do nothing.
2186 //
2187 return NULL;
2188 }
2189
2190 if (ShortFormDevicePath == DevicePath) {
2191 //
2192 // Boot Option device path starts with USB Class or USB WWID device path.
2193 //
2194 ImageHandle = BdsFindUsbDevice (NULL, ShortFormDevicePath);
2195 if (ImageHandle == NULL) {
2196 //
2197 // Failed to find a match in existing devices, connect the short form USB
2198 // device path and try again.
2199 //
2200 BdsLibConnectUsbDevByShortFormDP (0xff, ShortFormDevicePath);
2201 ImageHandle = BdsFindUsbDevice (NULL, ShortFormDevicePath);
2202 }
2203 } else {
2204 //
2205 // Boot Option device path contains USB Class or USB WWID device path node.
2206 //
2207
2208 //
2209 // Prepare the parent device path for search.
2210 //
2211 TempDevicePath = DuplicateDevicePath (DevicePath);
2212 ASSERT (TempDevicePath != NULL);
2213 SetDevicePathEndNode (((UINT8 *) TempDevicePath) + ((UINTN) ShortFormDevicePath - (UINTN) DevicePath));
2214
2215 //
2216 // The USB Host Controller device path is already in Boot Option device path
2217 // and USB Bus driver already support RemainingDevicePath starts with USB
2218 // Class or USB WWID device path, so just search in existing USB devices and
2219 // doesn't perform ConnectController here.
2220 //
2221 ImageHandle = BdsFindUsbDevice (TempDevicePath, ShortFormDevicePath);
2222 FreePool (TempDevicePath);
2223 }
2224
2225 return ImageHandle;
2226 }
2227
2228 /**
2229 Process the boot option follow the UEFI specification and
2230 special treat the legacy boot option with BBS_DEVICE_PATH.
2231
2232 @param Option The boot option need to be processed
2233 @param DevicePath The device path which describe where to load the
2234 boot image or the legacy BBS device path to boot
2235 the legacy OS
2236 @param ExitDataSize The size of exit data.
2237 @param ExitData Data returned when Boot image failed.
2238
2239 @retval EFI_SUCCESS Boot from the input boot option successfully.
2240 @retval EFI_NOT_FOUND If the Device Path is not found in the system
2241
2242 **/
2243 EFI_STATUS
2244 EFIAPI
2245 BdsLibBootViaBootOption (
2246 IN BDS_COMMON_OPTION *Option,
2247 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
2248 OUT UINTN *ExitDataSize,
2249 OUT CHAR16 **ExitData OPTIONAL
2250 )
2251 {
2252 EFI_STATUS Status;
2253 EFI_STATUS StatusLogo;
2254 EFI_HANDLE Handle;
2255 EFI_HANDLE ImageHandle;
2256 EFI_DEVICE_PATH_PROTOCOL *FilePath;
2257 EFI_LOADED_IMAGE_PROTOCOL *ImageInfo;
2258 EFI_DEVICE_PATH_PROTOCOL *WorkingDevicePath;
2259 LIST_ENTRY TempBootLists;
2260 EFI_BOOT_LOGO_PROTOCOL *BootLogo;
2261
2262 Status = EFI_SUCCESS;
2263 *ExitDataSize = 0;
2264 *ExitData = NULL;
2265
2266 //
2267 // If it's Device Path that starts with a hard drive path, append it with the front part to compose a
2268 // full device path
2269 //
2270 WorkingDevicePath = NULL;
2271 if ((DevicePathType (DevicePath) == MEDIA_DEVICE_PATH) &&
2272 (DevicePathSubType (DevicePath) == MEDIA_HARDDRIVE_DP)) {
2273 WorkingDevicePath = BdsExpandPartitionPartialDevicePathToFull (
2274 (HARDDRIVE_DEVICE_PATH *)DevicePath
2275 );
2276 if (WorkingDevicePath != NULL) {
2277 DevicePath = WorkingDevicePath;
2278 }
2279 }
2280
2281 //
2282 // Set Boot Current
2283 //
2284 if (IsBootOptionValidNVVarialbe (Option)) {
2285 //
2286 // For a temporary boot (i.e. a boot by selected a EFI Shell using "Boot From File"), Boot Current is actually not valid.
2287 // In this case, "BootCurrent" is not created.
2288 // Only create the BootCurrent variable when it points to a valid Boot#### variable.
2289 //
2290 SetVariableAndReportStatusCodeOnError (
2291 L"BootCurrent",
2292 &gEfiGlobalVariableGuid,
2293 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
2294 sizeof (UINT16),
2295 &Option->BootCurrent
2296 );
2297 }
2298
2299 //
2300 // Signal the EVT_SIGNAL_READY_TO_BOOT event
2301 //
2302 EfiSignalEventReadyToBoot();
2303
2304 //
2305 // Report Status Code to indicate ReadyToBoot event was signalled
2306 //
2307 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_READY_TO_BOOT_EVENT));
2308
2309 //
2310 // Expand USB Class or USB WWID device path node to be full device path of a USB
2311 // device in platform then load the boot file on this full device path and get the
2312 // image handle.
2313 //
2314 ImageHandle = BdsExpandUsbShortFormDevicePath (DevicePath);
2315
2316 //
2317 // Adjust the different type memory page number just before booting
2318 // and save the updated info into the variable for next boot to use
2319 //
2320 BdsSetMemoryTypeInformationVariable ();
2321
2322 //
2323 // By expanding the USB Class or WWID device path, the ImageHandle has returnned.
2324 // Here get the ImageHandle for the non USB class or WWID device path.
2325 //
2326 if (ImageHandle == NULL) {
2327 ASSERT (Option->DevicePath != NULL);
2328 if ((DevicePathType (Option->DevicePath) == BBS_DEVICE_PATH) &&
2329 (DevicePathSubType (Option->DevicePath) == BBS_BBS_DP)
2330 ) {
2331 //
2332 // Check to see if we should legacy BOOT. If yes then do the legacy boot
2333 //
2334 return BdsLibDoLegacyBoot (Option);
2335 }
2336
2337 //
2338 // If the boot option point to Internal FV shell, make sure it is valid
2339 //
2340 Status = BdsLibUpdateFvFileDevicePath (&DevicePath, PcdGetPtr(PcdShellFile));
2341 if (!EFI_ERROR(Status)) {
2342 if (Option->DevicePath != NULL) {
2343 FreePool(Option->DevicePath);
2344 }
2345 Option->DevicePath = AllocateZeroPool (GetDevicePathSize (DevicePath));
2346 ASSERT(Option->DevicePath != NULL);
2347 CopyMem (Option->DevicePath, DevicePath, GetDevicePathSize (DevicePath));
2348 //
2349 // Update the shell boot option
2350 //
2351 InitializeListHead (&TempBootLists);
2352 BdsLibRegisterNewOption (&TempBootLists, DevicePath, L"EFI Internal Shell", L"BootOrder");
2353
2354 //
2355 // free the temporary device path created by BdsLibUpdateFvFileDevicePath()
2356 //
2357 FreePool (DevicePath);
2358 DevicePath = Option->DevicePath;
2359 }
2360
2361 DEBUG_CODE_BEGIN();
2362
2363 if (Option->Description == NULL) {
2364 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Booting from unknown device path\n"));
2365 } else {
2366 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Booting %S\n", Option->Description));
2367 }
2368
2369 DEBUG_CODE_END();
2370
2371 //
2372 // Report status code for OS Loader LoadImage.
2373 //
2374 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderLoad));
2375 Status = gBS->LoadImage (
2376 TRUE,
2377 gImageHandle,
2378 DevicePath,
2379 NULL,
2380 0,
2381 &ImageHandle
2382 );
2383
2384 //
2385 // If we didn't find an image directly, we need to try as if it is a removable device boot option
2386 // and load the image according to the default boot behavior for removable device.
2387 //
2388 if (EFI_ERROR (Status)) {
2389 //
2390 // check if there is a bootable removable media could be found in this device path ,
2391 // and get the bootable media handle
2392 //
2393 Handle = BdsLibGetBootableHandle(DevicePath);
2394 if (Handle != NULL) {
2395 //
2396 // Load the default boot file \EFI\BOOT\boot{machinename}.EFI from removable Media
2397 // machinename is ia32, ia64, x64, ...
2398 //
2399 FilePath = FileDevicePath (Handle, EFI_REMOVABLE_MEDIA_FILE_NAME);
2400 if (FilePath != NULL) {
2401 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderLoad));
2402 Status = gBS->LoadImage (
2403 TRUE,
2404 gImageHandle,
2405 FilePath,
2406 NULL,
2407 0,
2408 &ImageHandle
2409 );
2410 }
2411 }
2412 }
2413 }
2414 //
2415 // Provide the image with it's load options
2416 //
2417 if ((ImageHandle == NULL) || (EFI_ERROR(Status))) {
2418 //
2419 // Report Status Code to indicate that the failure to load boot option
2420 //
2421 REPORT_STATUS_CODE (
2422 EFI_ERROR_CODE | EFI_ERROR_MINOR,
2423 (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_EC_BOOT_OPTION_LOAD_ERROR)
2424 );
2425 goto Done;
2426 }
2427
2428 Status = gBS->HandleProtocol (ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &ImageInfo);
2429 ASSERT_EFI_ERROR (Status);
2430
2431 if (Option->LoadOptionsSize != 0) {
2432 ImageInfo->LoadOptionsSize = Option->LoadOptionsSize;
2433 ImageInfo->LoadOptions = Option->LoadOptions;
2434 }
2435
2436 //
2437 // Clean to NULL because the image is loaded directly from the firmwares boot manager.
2438 //
2439 ImageInfo->ParentHandle = NULL;
2440
2441 //
2442 // Before calling the image, enable the Watchdog Timer for
2443 // the 5 Minute period
2444 //
2445 gBS->SetWatchdogTimer (5 * 60, 0x0000, 0x00, NULL);
2446
2447 //
2448 // Write boot to OS performance data for UEFI boot
2449 //
2450 PERF_CODE (
2451 BmEndOfBdsPerfCode (NULL, NULL);
2452 );
2453
2454 //
2455 // Report status code for OS Loader StartImage.
2456 //
2457 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderStart));
2458
2459 Status = gBS->StartImage (ImageHandle, ExitDataSize, ExitData);
2460 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Image Return Status = %r\n", Status));
2461 if (EFI_ERROR (Status)) {
2462 //
2463 // Report Status Code to indicate that boot failure
2464 //
2465 REPORT_STATUS_CODE (
2466 EFI_ERROR_CODE | EFI_ERROR_MINOR,
2467 (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_EC_BOOT_OPTION_FAILED)
2468 );
2469 }
2470
2471 //
2472 // Clear the Watchdog Timer after the image returns
2473 //
2474 gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL);
2475
2476 Done:
2477 //
2478 // Set Logo status invalid after trying one boot option
2479 //
2480 BootLogo = NULL;
2481 StatusLogo = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **) &BootLogo);
2482 if (!EFI_ERROR (StatusLogo) && (BootLogo != NULL)) {
2483 BootLogo->SetBootLogo (BootLogo, NULL, 0, 0, 0, 0);
2484 }
2485
2486 //
2487 // Clear Boot Current
2488 // Deleting variable with current implementation shouldn't fail.
2489 //
2490 gRT->SetVariable (
2491 L"BootCurrent",
2492 &gEfiGlobalVariableGuid,
2493 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
2494 0,
2495 NULL
2496 );
2497
2498 return Status;
2499 }
2500
2501
2502 /**
2503 Expand a device path that starts with a hard drive media device path node to be a
2504 full device path that includes the full hardware path to the device. We need
2505 to do this so it can be booted. As an optimization the front match (the part point
2506 to the partition node. E.g. ACPI() /PCI()/ATA()/Partition() ) is saved in a variable
2507 so a connect all is not required on every boot. All successful history device path
2508 which point to partition node (the front part) will be saved.
2509
2510 @param HardDriveDevicePath EFI Device Path to boot, if it starts with a hard
2511 drive media device path.
2512 @return A Pointer to the full device path or NULL if a valid Hard Drive devic path
2513 cannot be found.
2514
2515 **/
2516 EFI_DEVICE_PATH_PROTOCOL *
2517 EFIAPI
2518 BdsExpandPartitionPartialDevicePathToFull (
2519 IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath
2520 )
2521 {
2522 EFI_STATUS Status;
2523 UINTN BlockIoHandleCount;
2524 EFI_HANDLE *BlockIoBuffer;
2525 EFI_DEVICE_PATH_PROTOCOL *FullDevicePath;
2526 EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath;
2527 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2528 UINTN Index;
2529 UINTN InstanceNum;
2530 EFI_DEVICE_PATH_PROTOCOL *CachedDevicePath;
2531 EFI_DEVICE_PATH_PROTOCOL *TempNewDevicePath;
2532 UINTN CachedDevicePathSize;
2533 BOOLEAN DeviceExist;
2534 BOOLEAN NeedAdjust;
2535 EFI_DEVICE_PATH_PROTOCOL *Instance;
2536 UINTN Size;
2537
2538 FullDevicePath = NULL;
2539 //
2540 // Check if there is prestore HD_BOOT_DEVICE_PATH_VARIABLE_NAME variable.
2541 // If exist, search the front path which point to partition node in the variable instants.
2542 // If fail to find or HD_BOOT_DEVICE_PATH_VARIABLE_NAME not exist, reconnect all and search in all system
2543 //
2544 GetVariable2 (
2545 HD_BOOT_DEVICE_PATH_VARIABLE_NAME,
2546 &gHdBootDevicePathVariablGuid,
2547 (VOID **) &CachedDevicePath,
2548 &CachedDevicePathSize
2549 );
2550
2551 //
2552 // Delete the invalid HD_BOOT_DEVICE_PATH_VARIABLE_NAME variable.
2553 //
2554 if ((CachedDevicePath != NULL) && !IsDevicePathValid (CachedDevicePath, CachedDevicePathSize)) {
2555 FreePool (CachedDevicePath);
2556 CachedDevicePath = NULL;
2557 Status = gRT->SetVariable (
2558 HD_BOOT_DEVICE_PATH_VARIABLE_NAME,
2559 &gHdBootDevicePathVariablGuid,
2560 0,
2561 0,
2562 NULL
2563 );
2564 ASSERT_EFI_ERROR (Status);
2565 }
2566
2567 if (CachedDevicePath != NULL) {
2568 TempNewDevicePath = CachedDevicePath;
2569 DeviceExist = FALSE;
2570 NeedAdjust = FALSE;
2571 do {
2572 //
2573 // Check every instance of the variable
2574 // First, check whether the instance contain the partition node, which is needed for distinguishing multi
2575 // partial partition boot option. Second, check whether the instance could be connected.
2576 //
2577 Instance = GetNextDevicePathInstance (&TempNewDevicePath, &Size);
2578 if (MatchPartitionDevicePathNode (Instance, HardDriveDevicePath)) {
2579 //
2580 // Connect the device path instance, the device path point to hard drive media device path node
2581 // e.g. ACPI() /PCI()/ATA()/Partition()
2582 //
2583 Status = BdsLibConnectDevicePath (Instance);
2584 if (!EFI_ERROR (Status)) {
2585 DeviceExist = TRUE;
2586 break;
2587 }
2588 }
2589 //
2590 // Come here means the first instance is not matched
2591 //
2592 NeedAdjust = TRUE;
2593 FreePool(Instance);
2594 } while (TempNewDevicePath != NULL);
2595
2596 if (DeviceExist) {
2597 //
2598 // Find the matched device path.
2599 // Append the file path information from the boot option and return the fully expanded device path.
2600 //
2601 DevicePath = NextDevicePathNode ((EFI_DEVICE_PATH_PROTOCOL *) HardDriveDevicePath);
2602 FullDevicePath = AppendDevicePath (Instance, DevicePath);
2603
2604 //
2605 // Adjust the HD_BOOT_DEVICE_PATH_VARIABLE_NAME instances sequence if the matched one is not first one.
2606 //
2607 if (NeedAdjust) {
2608 //
2609 // First delete the matched instance.
2610 //
2611 TempNewDevicePath = CachedDevicePath;
2612 CachedDevicePath = BdsLibDelPartMatchInstance (CachedDevicePath, Instance );
2613 FreePool (TempNewDevicePath);
2614
2615 //
2616 // Second, append the remaining path after the matched instance
2617 //
2618 TempNewDevicePath = CachedDevicePath;
2619 CachedDevicePath = AppendDevicePathInstance (Instance, CachedDevicePath );
2620 FreePool (TempNewDevicePath);
2621 //
2622 // Save the matching Device Path so we don't need to do a connect all next time
2623 // Failure to set the variable only impacts the performance when next time expanding the short-form device path.
2624 //
2625 Status = gRT->SetVariable (
2626 HD_BOOT_DEVICE_PATH_VARIABLE_NAME,
2627 &gHdBootDevicePathVariablGuid,
2628 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
2629 GetDevicePathSize (CachedDevicePath),
2630 CachedDevicePath
2631 );
2632 }
2633
2634 FreePool (Instance);
2635 FreePool (CachedDevicePath);
2636 return FullDevicePath;
2637 }
2638 }
2639
2640 //
2641 // If we get here we fail to find or HD_BOOT_DEVICE_PATH_VARIABLE_NAME not exist, and now we need
2642 // to search all devices in the system for a matched partition
2643 //
2644 BdsLibConnectAllDriversToAllControllers ();
2645 Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiBlockIoProtocolGuid, NULL, &BlockIoHandleCount, &BlockIoBuffer);
2646 if (EFI_ERROR (Status) || BlockIoHandleCount == 0 || BlockIoBuffer == NULL) {
2647 //
2648 // If there was an error or there are no device handles that support
2649 // the BLOCK_IO Protocol, then return.
2650 //
2651 return NULL;
2652 }
2653 //
2654 // Loop through all the device handles that support the BLOCK_IO Protocol
2655 //
2656 for (Index = 0; Index < BlockIoHandleCount; Index++) {
2657
2658 Status = gBS->HandleProtocol (BlockIoBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID *) &BlockIoDevicePath);
2659 if (EFI_ERROR (Status) || BlockIoDevicePath == NULL) {
2660 continue;
2661 }
2662
2663 if (MatchPartitionDevicePathNode (BlockIoDevicePath, HardDriveDevicePath)) {
2664 //
2665 // Find the matched partition device path
2666 //
2667 DevicePath = NextDevicePathNode ((EFI_DEVICE_PATH_PROTOCOL *) HardDriveDevicePath);
2668 FullDevicePath = AppendDevicePath (BlockIoDevicePath, DevicePath);
2669
2670 //
2671 // Save the matched partition device path in HD_BOOT_DEVICE_PATH_VARIABLE_NAME variable
2672 //
2673 if (CachedDevicePath != NULL) {
2674 //
2675 // Save the matched partition device path as first instance of HD_BOOT_DEVICE_PATH_VARIABLE_NAME variable
2676 //
2677 if (BdsLibMatchDevicePaths (CachedDevicePath, BlockIoDevicePath)) {
2678 TempNewDevicePath = CachedDevicePath;
2679 CachedDevicePath = BdsLibDelPartMatchInstance (CachedDevicePath, BlockIoDevicePath);
2680 FreePool(TempNewDevicePath);
2681 }
2682
2683 if (CachedDevicePath != NULL) {
2684 TempNewDevicePath = CachedDevicePath;
2685 CachedDevicePath = AppendDevicePathInstance (BlockIoDevicePath, CachedDevicePath);
2686 FreePool(TempNewDevicePath);
2687 } else {
2688 CachedDevicePath = DuplicateDevicePath (BlockIoDevicePath);
2689 }
2690
2691 //
2692 // Here limit the device path instance number to 12, which is max number for a system support 3 IDE controller
2693 // If the user try to boot many OS in different HDs or partitions, in theory,
2694 // the HD_BOOT_DEVICE_PATH_VARIABLE_NAME variable maybe become larger and larger.
2695 //
2696 InstanceNum = 0;
2697 ASSERT (CachedDevicePath != NULL);
2698 TempNewDevicePath = CachedDevicePath;
2699 while (!IsDevicePathEnd (TempNewDevicePath)) {
2700 TempNewDevicePath = NextDevicePathNode (TempNewDevicePath);
2701 //
2702 // Parse one instance
2703 //
2704 while (!IsDevicePathEndType (TempNewDevicePath)) {
2705 TempNewDevicePath = NextDevicePathNode (TempNewDevicePath);
2706 }
2707 InstanceNum++;
2708 //
2709 // If the CachedDevicePath variable contain too much instance, only remain 12 instances.
2710 //
2711 if (InstanceNum >= 12) {
2712 SetDevicePathEndNode (TempNewDevicePath);
2713 break;
2714 }
2715 }
2716 } else {
2717 CachedDevicePath = DuplicateDevicePath (BlockIoDevicePath);
2718 }
2719
2720 //
2721 // Save the matching Device Path so we don't need to do a connect all next time
2722 // Failure to set the variable only impacts the performance when next time expanding the short-form device path.
2723 //
2724 Status = gRT->SetVariable (
2725 HD_BOOT_DEVICE_PATH_VARIABLE_NAME,
2726 &gHdBootDevicePathVariablGuid,
2727 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
2728 GetDevicePathSize (CachedDevicePath),
2729 CachedDevicePath
2730 );
2731
2732 break;
2733 }
2734 }
2735
2736 if (CachedDevicePath != NULL) {
2737 FreePool (CachedDevicePath);
2738 }
2739 if (BlockIoBuffer != NULL) {
2740 FreePool (BlockIoBuffer);
2741 }
2742 return FullDevicePath;
2743 }
2744
2745 /**
2746 Check whether there is a instance in BlockIoDevicePath, which contain multi device path
2747 instances, has the same partition node with HardDriveDevicePath device path
2748
2749 @param BlockIoDevicePath Multi device path instances which need to check
2750 @param HardDriveDevicePath A device path which starts with a hard drive media
2751 device path.
2752
2753 @retval TRUE There is a matched device path instance.
2754 @retval FALSE There is no matched device path instance.
2755
2756 **/
2757 BOOLEAN
2758 EFIAPI
2759 MatchPartitionDevicePathNode (
2760 IN EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath,
2761 IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath
2762 )
2763 {
2764 HARDDRIVE_DEVICE_PATH *TmpHdPath;
2765 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2766 BOOLEAN Match;
2767 EFI_DEVICE_PATH_PROTOCOL *BlockIoHdDevicePathNode;
2768
2769 if ((BlockIoDevicePath == NULL) || (HardDriveDevicePath == NULL)) {
2770 return FALSE;
2771 }
2772
2773 //
2774 // Make PreviousDevicePath == the device path node before the end node
2775 //
2776 DevicePath = BlockIoDevicePath;
2777 BlockIoHdDevicePathNode = NULL;
2778
2779 //
2780 // find the partition device path node
2781 //
2782 while (!IsDevicePathEnd (DevicePath)) {
2783 if ((DevicePathType (DevicePath) == MEDIA_DEVICE_PATH) &&
2784 (DevicePathSubType (DevicePath) == MEDIA_HARDDRIVE_DP)
2785 ) {
2786 BlockIoHdDevicePathNode = DevicePath;
2787 break;
2788 }
2789
2790 DevicePath = NextDevicePathNode (DevicePath);
2791 }
2792
2793 if (BlockIoHdDevicePathNode == NULL) {
2794 return FALSE;
2795 }
2796 //
2797 // See if the harddrive device path in blockio matches the orig Hard Drive Node
2798 //
2799 TmpHdPath = (HARDDRIVE_DEVICE_PATH *) BlockIoHdDevicePathNode;
2800 Match = FALSE;
2801
2802 //
2803 // Check for the match
2804 //
2805 if ((TmpHdPath->MBRType == HardDriveDevicePath->MBRType) &&
2806 (TmpHdPath->SignatureType == HardDriveDevicePath->SignatureType)) {
2807 switch (TmpHdPath->SignatureType) {
2808 case SIGNATURE_TYPE_GUID:
2809 Match = CompareGuid ((EFI_GUID *)TmpHdPath->Signature, (EFI_GUID *)HardDriveDevicePath->Signature);
2810 break;
2811 case SIGNATURE_TYPE_MBR:
2812 Match = (BOOLEAN)(*((UINT32 *)(&(TmpHdPath->Signature[0]))) == ReadUnaligned32((UINT32 *)(&(HardDriveDevicePath->Signature[0]))));
2813 break;
2814 default:
2815 Match = FALSE;
2816 break;
2817 }
2818 }
2819
2820 return Match;
2821 }
2822
2823 /**
2824 Delete the boot option associated with the handle passed in.
2825
2826 @param Handle The handle which present the device path to create
2827 boot option
2828
2829 @retval EFI_SUCCESS Delete the boot option success
2830 @retval EFI_NOT_FOUND If the Device Path is not found in the system
2831 @retval EFI_OUT_OF_RESOURCES Lack of memory resource
2832 @retval Other Error return value from SetVariable()
2833
2834 **/
2835 EFI_STATUS
2836 BdsLibDeleteOptionFromHandle (
2837 IN EFI_HANDLE Handle
2838 )
2839 {
2840 UINT16 *BootOrder;
2841 UINT8 *BootOptionVar;
2842 UINTN BootOrderSize;
2843 UINTN BootOptionSize;
2844 EFI_STATUS Status;
2845 UINTN Index;
2846 UINT16 BootOption[BOOT_OPTION_MAX_CHAR];
2847 UINTN DevicePathSize;
2848 UINTN OptionDevicePathSize;
2849 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2850 EFI_DEVICE_PATH_PROTOCOL *OptionDevicePath;
2851 UINT8 *TempPtr;
2852
2853 Status = EFI_SUCCESS;
2854 BootOrder = NULL;
2855 BootOrderSize = 0;
2856
2857 //
2858 // Check "BootOrder" variable, if no, means there is no any boot order.
2859 //
2860 BootOrder = BdsLibGetVariableAndSize (
2861 L"BootOrder",
2862 &gEfiGlobalVariableGuid,
2863 &BootOrderSize
2864 );
2865 if (BootOrder == NULL) {
2866 return EFI_NOT_FOUND;
2867 }
2868
2869 //
2870 // Convert device handle to device path protocol instance
2871 //
2872 DevicePath = DevicePathFromHandle (Handle);
2873 if (DevicePath == NULL) {
2874 return EFI_NOT_FOUND;
2875 }
2876 DevicePathSize = GetDevicePathSize (DevicePath);
2877
2878 //
2879 // Loop all boot order variable and find the matching device path
2880 //
2881 Index = 0;
2882 while (Index < BootOrderSize / sizeof (UINT16)) {
2883 UnicodeSPrint (BootOption, sizeof (BootOption), L"Boot%04x", BootOrder[Index]);
2884 BootOptionVar = BdsLibGetVariableAndSize (
2885 BootOption,
2886 &gEfiGlobalVariableGuid,
2887 &BootOptionSize
2888 );
2889
2890 if (BootOptionVar == NULL) {
2891 FreePool (BootOrder);
2892 return EFI_OUT_OF_RESOURCES;
2893 }
2894
2895 if (!ValidateOption(BootOptionVar, BootOptionSize)) {
2896 BdsDeleteBootOption (BootOrder[Index], BootOrder, &BootOrderSize);
2897 FreePool (BootOptionVar);
2898 Index++;
2899 continue;
2900 }
2901
2902 TempPtr = BootOptionVar;
2903 TempPtr += sizeof (UINT32) + sizeof (UINT16);
2904 TempPtr += StrSize ((CHAR16 *) TempPtr);
2905 OptionDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) TempPtr;
2906 OptionDevicePathSize = GetDevicePathSize (OptionDevicePath);
2907
2908 //
2909 // Check whether the device path match
2910 //
2911 if ((OptionDevicePathSize == DevicePathSize) &&
2912 (CompareMem (DevicePath, OptionDevicePath, DevicePathSize) == 0)) {
2913 BdsDeleteBootOption (BootOrder[Index], BootOrder, &BootOrderSize);
2914 FreePool (BootOptionVar);
2915 break;
2916 }
2917
2918 FreePool (BootOptionVar);
2919 Index++;
2920 }
2921
2922 //
2923 // Adjust number of boot option for "BootOrder" variable.
2924 //
2925 Status = gRT->SetVariable (
2926 L"BootOrder",
2927 &gEfiGlobalVariableGuid,
2928 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
2929 BootOrderSize,
2930 BootOrder
2931 );
2932 //
2933 // Shrinking variable with existing variable implementation shouldn't fail.
2934 //
2935 ASSERT_EFI_ERROR (Status);
2936
2937 FreePool (BootOrder);
2938
2939 return Status;
2940 }
2941
2942
2943 /**
2944 Delete all invalid EFI boot options.
2945
2946 @retval EFI_SUCCESS Delete all invalid boot option success
2947 @retval EFI_NOT_FOUND Variable "BootOrder" is not found
2948 @retval EFI_OUT_OF_RESOURCES Lack of memory resource
2949 @retval Other Error return value from SetVariable()
2950
2951 **/
2952 EFI_STATUS
2953 BdsDeleteAllInvalidEfiBootOption (
2954 VOID
2955 )
2956 {
2957 UINT16 *BootOrder;
2958 UINT8 *BootOptionVar;
2959 UINTN BootOrderSize;
2960 UINTN BootOptionSize;
2961 EFI_STATUS Status;
2962 UINTN Index;
2963 UINTN Index2;
2964 UINT16 BootOption[BOOT_OPTION_MAX_CHAR];
2965 EFI_DEVICE_PATH_PROTOCOL *OptionDevicePath;
2966 UINT8 *TempPtr;
2967 CHAR16 *Description;
2968 BOOLEAN Corrupted;
2969
2970 Status = EFI_SUCCESS;
2971 BootOrder = NULL;
2972 Description = NULL;
2973 OptionDevicePath = NULL;
2974 BootOrderSize = 0;
2975 Corrupted = FALSE;
2976
2977 //
2978 // Check "BootOrder" variable firstly, this variable hold the number of boot options
2979 //
2980 BootOrder = BdsLibGetVariableAndSize (
2981 L"BootOrder",
2982 &gEfiGlobalVariableGuid,
2983 &BootOrderSize
2984 );
2985 if (NULL == BootOrder) {
2986 return EFI_NOT_FOUND;
2987 }
2988
2989 Index = 0;
2990 while (Index < BootOrderSize / sizeof (UINT16)) {
2991 UnicodeSPrint (BootOption, sizeof (BootOption), L"Boot%04x", BootOrder[Index]);
2992 BootOptionVar = BdsLibGetVariableAndSize (
2993 BootOption,
2994 &gEfiGlobalVariableGuid,
2995 &BootOptionSize
2996 );
2997 if (NULL == BootOptionVar) {
2998 FreePool (BootOrder);
2999 return EFI_OUT_OF_RESOURCES;
3000 }
3001
3002 if (!ValidateOption(BootOptionVar, BootOptionSize)) {
3003 Corrupted = TRUE;
3004 } else {
3005 TempPtr = BootOptionVar;
3006 TempPtr += sizeof (UINT32) + sizeof (UINT16);
3007 Description = (CHAR16 *) TempPtr;
3008 TempPtr += StrSize ((CHAR16 *) TempPtr);
3009 OptionDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) TempPtr;
3010
3011 //
3012 // Skip legacy boot option (BBS boot device)
3013 //
3014 if ((DevicePathType (OptionDevicePath) == BBS_DEVICE_PATH) &&
3015 (DevicePathSubType (OptionDevicePath) == BBS_BBS_DP)) {
3016 FreePool (BootOptionVar);
3017 Index++;
3018 continue;
3019 }
3020 }
3021
3022 if (Corrupted || !BdsLibIsValidEFIBootOptDevicePathExt (OptionDevicePath, FALSE, Description)) {
3023 //
3024 // Delete this invalid boot option "Boot####"
3025 //
3026 Status = gRT->SetVariable (
3027 BootOption,
3028 &gEfiGlobalVariableGuid,
3029 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
3030 0,
3031 NULL
3032 );
3033 //
3034 // Deleting variable with current variable implementation shouldn't fail.
3035 //
3036 ASSERT_EFI_ERROR (Status);
3037 //
3038 // Mark this boot option in boot order as deleted
3039 //
3040 BootOrder[Index] = 0xffff;
3041 Corrupted = FALSE;
3042 }
3043
3044 FreePool (BootOptionVar);
3045 Index++;
3046 }
3047
3048 //
3049 // Adjust boot order array
3050 //
3051 Index2 = 0;
3052 for (Index = 0; Index < BootOrderSize / sizeof (UINT16); Index++) {
3053 if (BootOrder[Index] != 0xffff) {
3054 BootOrder[Index2] = BootOrder[Index];
3055 Index2 ++;
3056 }
3057 }
3058 Status = gRT->SetVariable (
3059 L"BootOrder",
3060 &gEfiGlobalVariableGuid,
3061 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
3062 Index2 * sizeof (UINT16),
3063 BootOrder
3064 );
3065 //
3066 // Shrinking variable with current variable implementation shouldn't fail.
3067 //
3068 ASSERT_EFI_ERROR (Status);
3069
3070 FreePool (BootOrder);
3071
3072 return Status;
3073 }
3074
3075
3076 /**
3077 For EFI boot option, BDS separate them as six types:
3078 1. Network - The boot option points to the SimpleNetworkProtocol device.
3079 Bds will try to automatically create this type boot option when enumerate.
3080 2. Shell - The boot option points to internal flash shell.
3081 Bds will try to automatically create this type boot option when enumerate.
3082 3. Removable BlockIo - The boot option only points to the removable media
3083 device, like USB flash disk, DVD, Floppy etc.
3084 These device should contain a *removable* blockIo
3085 protocol in their device handle.
3086 Bds will try to automatically create this type boot option
3087 when enumerate.
3088 4. Fixed BlockIo - The boot option only points to a Fixed blockIo device,
3089 like HardDisk.
3090 These device should contain a *fixed* blockIo
3091 protocol in their device handle.
3092 BDS will skip fixed blockIo devices, and NOT
3093 automatically create boot option for them. But BDS
3094 will help to delete those fixed blockIo boot option,
3095 whose description rule conflict with other auto-created
3096 boot options.
3097 5. Non-BlockIo Simplefile - The boot option points to a device whose handle
3098 has SimpleFileSystem Protocol, but has no blockio
3099 protocol. These devices do not offer blockIo
3100 protocol, but BDS still can get the
3101 \EFI\BOOT\boot{machinename}.EFI by SimpleFileSystem
3102 Protocol.
3103 6. File - The boot option points to a file. These boot options are usually
3104 created by user manually or OS loader. BDS will not delete or modify
3105 these boot options.
3106
3107 This function will enumerate all possible boot device in the system, and
3108 automatically create boot options for Network, Shell, Removable BlockIo,
3109 and Non-BlockIo Simplefile devices.
3110 It will only execute once of every boot.
3111
3112 @param BdsBootOptionList The header of the link list which indexed all
3113 current boot options
3114
3115 @retval EFI_SUCCESS Finished all the boot device enumerate and create
3116 the boot option base on that boot device
3117
3118 @retval EFI_OUT_OF_RESOURCES Failed to enumerate the boot device and create the boot option list
3119 **/
3120 EFI_STATUS
3121 EFIAPI
3122 BdsLibEnumerateAllBootOption (
3123 IN OUT LIST_ENTRY *BdsBootOptionList
3124 )
3125 {
3126 EFI_STATUS Status;
3127 UINT16 FloppyNumber;
3128 UINT16 HarddriveNumber;
3129 UINT16 CdromNumber;
3130 UINT16 UsbNumber;
3131 UINT16 MiscNumber;
3132 UINT16 ScsiNumber;
3133 UINT16 NonBlockNumber;
3134 UINTN NumberBlockIoHandles;
3135 EFI_HANDLE *BlockIoHandles;
3136 EFI_BLOCK_IO_PROTOCOL *BlkIo;
3137 BOOLEAN Removable[2];
3138 UINTN RemovableIndex;
3139 UINTN Index;
3140 UINTN NumOfLoadFileHandles;
3141 EFI_HANDLE *LoadFileHandles;
3142 UINTN FvHandleCount;
3143 EFI_HANDLE *FvHandleBuffer;
3144 EFI_FV_FILETYPE Type;
3145 UINTN Size;
3146 EFI_FV_FILE_ATTRIBUTES Attributes;
3147 UINT32 AuthenticationStatus;
3148 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
3149 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
3150 UINTN DevicePathType;
3151 CHAR16 Buffer[40];
3152 EFI_HANDLE *FileSystemHandles;
3153 UINTN NumberFileSystemHandles;
3154 BOOLEAN NeedDelete;
3155 EFI_IMAGE_DOS_HEADER DosHeader;
3156 CHAR8 *PlatLang;
3157 CHAR8 *LastLang;
3158 EFI_IMAGE_OPTIONAL_HEADER_UNION HdrData;
3159 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
3160
3161 FloppyNumber = 0;
3162 HarddriveNumber = 0;
3163 CdromNumber = 0;
3164 UsbNumber = 0;
3165 MiscNumber = 0;
3166 ScsiNumber = 0;
3167 PlatLang = NULL;
3168 LastLang = NULL;
3169 ZeroMem (Buffer, sizeof (Buffer));
3170
3171 //
3172 // If the boot device enumerate happened, just get the boot
3173 // device from the boot order variable
3174 //
3175 if (mEnumBootDevice) {
3176 GetVariable2 (LAST_ENUM_LANGUAGE_VARIABLE_NAME, &gLastEnumLangGuid, (VOID**)&LastLang, NULL);
3177 GetEfiGlobalVariable2 (L"PlatformLang", (VOID**)&PlatLang, NULL);
3178 ASSERT (PlatLang != NULL);
3179 if ((LastLang != NULL) && (AsciiStrCmp (LastLang, PlatLang) == 0)) {
3180 Status = BdsLibBuildOptionFromVar (BdsBootOptionList, L"BootOrder");
3181 FreePool (LastLang);
3182 FreePool (PlatLang);
3183 return Status;
3184 } else {
3185 Status = gRT->SetVariable (
3186 LAST_ENUM_LANGUAGE_VARIABLE_NAME,
3187 &gLastEnumLangGuid,
3188 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
3189 AsciiStrSize (PlatLang),
3190 PlatLang
3191 );
3192 //
3193 // Failure to set the variable only impacts the performance next time enumerating the boot options.
3194 //
3195
3196 if (LastLang != NULL) {
3197 FreePool (LastLang);
3198 }
3199 FreePool (PlatLang);
3200 }
3201 }
3202
3203 //
3204 // Notes: this dirty code is to get the legacy boot option from the
3205 // BBS table and create to variable as the EFI boot option, it should
3206 // be removed after the CSM can provide legacy boot option directly
3207 //
3208 REFRESH_LEGACY_BOOT_OPTIONS;
3209
3210 //
3211 // Delete invalid boot option
3212 //
3213 BdsDeleteAllInvalidEfiBootOption ();
3214
3215 //
3216 // Parse removable media followed by fixed media.
3217 // The Removable[] array is used by the for-loop below to create removable media boot options
3218 // at first, and then to create fixed media boot options.
3219 //
3220 Removable[0] = FALSE;
3221 Removable[1] = TRUE;
3222
3223 gBS->LocateHandleBuffer (
3224 ByProtocol,
3225 &gEfiBlockIoProtocolGuid,
3226 NULL,
3227 &NumberBlockIoHandles,
3228 &BlockIoHandles
3229 );
3230
3231 for (RemovableIndex = 0; RemovableIndex < 2; RemovableIndex++) {
3232 for (Index = 0; Index < NumberBlockIoHandles; Index++) {
3233 Status = gBS->HandleProtocol (
3234 BlockIoHandles[Index],
3235 &gEfiBlockIoProtocolGuid,
3236 (VOID **) &BlkIo
3237 );
3238 //
3239 // skip the logical partition
3240 //
3241 if (EFI_ERROR (Status) || BlkIo->Media->LogicalPartition) {
3242 continue;
3243 }
3244
3245 //
3246 // firstly fixed block io then the removable block io
3247 //
3248 if (BlkIo->Media->RemovableMedia == Removable[RemovableIndex]) {
3249 continue;
3250 }
3251 DevicePath = DevicePathFromHandle (BlockIoHandles[Index]);
3252 DevicePathType = BdsGetBootTypeFromDevicePath (DevicePath);
3253
3254 switch (DevicePathType) {
3255 case BDS_EFI_ACPI_FLOPPY_BOOT:
3256 if (FloppyNumber != 0) {
3257 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_FLOPPY)), FloppyNumber);
3258 } else {
3259 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_FLOPPY)));
3260 }
3261 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
3262 FloppyNumber++;
3263 break;
3264
3265 //
3266 // Assume a removable SATA device should be the DVD/CD device, a fixed SATA device should be the Hard Drive device.
3267 //
3268 case BDS_EFI_MESSAGE_ATAPI_BOOT:
3269 case BDS_EFI_MESSAGE_SATA_BOOT:
3270 if (BlkIo->Media->RemovableMedia) {
3271 if (CdromNumber != 0) {
3272 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_CD_DVD)), CdromNumber);
3273 } else {
3274 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_CD_DVD)));
3275 }
3276 CdromNumber++;
3277 } else {
3278 if (HarddriveNumber != 0) {
3279 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_HARDDRIVE)), HarddriveNumber);
3280 } else {
3281 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_HARDDRIVE)));
3282 }
3283 HarddriveNumber++;
3284 }
3285 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Buffer: %S\n", Buffer));
3286 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
3287 break;
3288
3289 case BDS_EFI_MESSAGE_USB_DEVICE_BOOT:
3290 if (UsbNumber != 0) {
3291 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_USB)), UsbNumber);
3292 } else {
3293 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_USB)));
3294 }
3295 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
3296 UsbNumber++;
3297 break;
3298
3299 case BDS_EFI_MESSAGE_SCSI_BOOT:
3300 if (ScsiNumber != 0) {
3301 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_SCSI)), ScsiNumber);
3302 } else {
3303 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_SCSI)));
3304 }
3305 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
3306 ScsiNumber++;
3307 break;
3308
3309 case BDS_EFI_MESSAGE_MISC_BOOT:
3310 default:
3311 if (MiscNumber != 0) {
3312 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_MISC)), MiscNumber);
3313 } else {
3314 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_MISC)));
3315 }
3316 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
3317 MiscNumber++;
3318 break;
3319 }
3320 }
3321 }
3322
3323 if (NumberBlockIoHandles != 0) {
3324 FreePool (BlockIoHandles);
3325 }
3326
3327 //
3328 // If there is simple file protocol which does not consume block Io protocol, create a boot option for it here.
3329 //
3330 NonBlockNumber = 0;
3331 gBS->LocateHandleBuffer (
3332 ByProtocol,
3333 &gEfiSimpleFileSystemProtocolGuid,
3334 NULL,
3335 &NumberFileSystemHandles,
3336 &FileSystemHandles
3337 );
3338 for (Index = 0; Index < NumberFileSystemHandles; Index++) {
3339 Status = gBS->HandleProtocol (
3340 FileSystemHandles[Index],
3341 &gEfiBlockIoProtocolGuid,
3342 (VOID **) &BlkIo
3343 );
3344 if (!EFI_ERROR (Status)) {
3345 //
3346 // Skip if the file system handle supports a BlkIo protocol,
3347 //
3348 continue;
3349 }
3350
3351 //
3352 // Do the removable Media thing. \EFI\BOOT\boot{machinename}.EFI
3353 // machinename is ia32, ia64, x64, ...
3354 //
3355 Hdr.Union = &HdrData;
3356 NeedDelete = TRUE;
3357 Status = BdsLibGetImageHeader (
3358 FileSystemHandles[Index],
3359 EFI_REMOVABLE_MEDIA_FILE_NAME,
3360 &DosHeader,
3361 Hdr
3362 );
3363 if (!EFI_ERROR (Status) &&
3364 EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Hdr.Pe32->FileHeader.Machine) &&
3365 Hdr.Pe32->OptionalHeader.Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {
3366 NeedDelete = FALSE;
3367 }
3368
3369 if (NeedDelete) {
3370 //
3371 // No such file or the file is not a EFI application, delete this boot option
3372 //
3373 BdsLibDeleteOptionFromHandle (FileSystemHandles[Index]);
3374 } else {
3375 if (NonBlockNumber != 0) {
3376 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_NON_BLOCK)), NonBlockNumber);
3377 } else {
3378 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_NON_BLOCK)));
3379 }
3380 BdsLibBuildOptionFromHandle (FileSystemHandles[Index], BdsBootOptionList, Buffer);
3381 NonBlockNumber++;
3382 }
3383 }
3384
3385 if (NumberFileSystemHandles != 0) {
3386 FreePool (FileSystemHandles);
3387 }
3388
3389 //
3390 // Parse Network Boot Device
3391 //
3392 NumOfLoadFileHandles = 0;
3393 //
3394 // Search Load File protocol for PXE boot option.
3395 //
3396 gBS->LocateHandleBuffer (
3397 ByProtocol,
3398 &gEfiLoadFileProtocolGuid,
3399 NULL,
3400 &NumOfLoadFileHandles,
3401 &LoadFileHandles
3402 );
3403
3404 for (Index = 0; Index < NumOfLoadFileHandles; Index++) {
3405 if (Index != 0) {
3406 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_NETWORK)), Index);
3407 } else {
3408 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_NETWORK)));
3409 }
3410 BdsLibBuildOptionFromHandle (LoadFileHandles[Index], BdsBootOptionList, Buffer);
3411 }
3412
3413 if (NumOfLoadFileHandles != 0) {
3414 FreePool (LoadFileHandles);
3415 }
3416
3417 //
3418 // Check if we have on flash shell
3419 //
3420 gBS->LocateHandleBuffer (
3421 ByProtocol,
3422 &gEfiFirmwareVolume2ProtocolGuid,
3423 NULL,
3424 &FvHandleCount,
3425 &FvHandleBuffer
3426 );
3427 for (Index = 0; Index < FvHandleCount; Index++) {
3428 gBS->HandleProtocol (
3429 FvHandleBuffer[Index],
3430 &gEfiFirmwareVolume2ProtocolGuid,
3431 (VOID **) &Fv
3432 );
3433
3434 Status = Fv->ReadFile (
3435 Fv,
3436 PcdGetPtr(PcdShellFile),
3437 NULL,
3438 &Size,
3439 &Type,
3440 &Attributes,
3441 &AuthenticationStatus
3442 );
3443 if (EFI_ERROR (Status)) {
3444 //
3445 // Skip if no shell file in the FV
3446 //
3447 continue;
3448 }
3449 //
3450 // Build the shell boot option
3451 //
3452 BdsLibBuildOptionFromShell (FvHandleBuffer[Index], BdsBootOptionList);
3453 }
3454
3455 if (FvHandleCount != 0) {
3456 FreePool (FvHandleBuffer);
3457 }
3458 //
3459 // Make sure every boot only have one time
3460 // boot device enumerate
3461 //
3462 Status = BdsLibBuildOptionFromVar (BdsBootOptionList, L"BootOrder");
3463 mEnumBootDevice = TRUE;
3464
3465 return Status;
3466 }
3467
3468 /**
3469 Build the boot option with the handle parsed in
3470
3471 @param Handle The handle which present the device path to create
3472 boot option
3473 @param BdsBootOptionList The header of the link list which indexed all
3474 current boot options
3475 @param String The description of the boot option.
3476
3477 **/
3478 VOID
3479 EFIAPI
3480 BdsLibBuildOptionFromHandle (
3481 IN EFI_HANDLE Handle,
3482 IN LIST_ENTRY *BdsBootOptionList,
3483 IN CHAR16 *String
3484 )
3485 {
3486 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
3487
3488 DevicePath = DevicePathFromHandle (Handle);
3489
3490 //
3491 // Create and register new boot option
3492 //
3493 BdsLibRegisterNewOption (BdsBootOptionList, DevicePath, String, L"BootOrder");
3494 }
3495
3496
3497 /**
3498 Build the on flash shell boot option with the handle parsed in.
3499
3500 @param Handle The handle which present the device path to create
3501 on flash shell boot option
3502 @param BdsBootOptionList The header of the link list which indexed all
3503 current boot options
3504
3505 **/
3506 VOID
3507 EFIAPI
3508 BdsLibBuildOptionFromShell (
3509 IN EFI_HANDLE Handle,
3510 IN OUT LIST_ENTRY *BdsBootOptionList
3511 )
3512 {
3513 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
3514 MEDIA_FW_VOL_FILEPATH_DEVICE_PATH ShellNode;
3515
3516 DevicePath = DevicePathFromHandle (Handle);
3517
3518 //
3519 // Build the shell device path
3520 //
3521 EfiInitializeFwVolDevicepathNode (&ShellNode, PcdGetPtr(PcdShellFile));
3522
3523 DevicePath = AppendDevicePathNode (DevicePath, (EFI_DEVICE_PATH_PROTOCOL *) &ShellNode);
3524
3525 //
3526 // Create and register the shell boot option
3527 //
3528 BdsLibRegisterNewOption (BdsBootOptionList, DevicePath, L"EFI Internal Shell", L"BootOrder");
3529
3530 }
3531
3532 /**
3533 Boot from the UEFI spec defined "BootNext" variable.
3534
3535 **/
3536 VOID
3537 EFIAPI
3538 BdsLibBootNext (
3539 VOID
3540 )
3541 {
3542 EFI_STATUS Status;
3543 UINT16 *BootNext;
3544 UINTN BootNextSize;
3545 CHAR16 Buffer[20];
3546 BDS_COMMON_OPTION *BootOption;
3547 LIST_ENTRY TempList;
3548 UINTN ExitDataSize;
3549 CHAR16 *ExitData;
3550
3551 //
3552 // Init the boot option name buffer and temp link list
3553 //
3554 InitializeListHead (&TempList);
3555 ZeroMem (Buffer, sizeof (Buffer));
3556
3557 BootNext = BdsLibGetVariableAndSize (
3558 L"BootNext",
3559 &gEfiGlobalVariableGuid,
3560 &BootNextSize
3561 );
3562
3563 //
3564 // Clear the boot next variable first
3565 //
3566 if (BootNext != NULL) {
3567 Status = gRT->SetVariable (
3568 L"BootNext",
3569 &gEfiGlobalVariableGuid,
3570 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
3571 0,
3572 NULL
3573 );
3574 //
3575 // Deleting variable with current variable implementation shouldn't fail.
3576 //
3577 ASSERT_EFI_ERROR (Status);
3578
3579 //
3580 // Start to build the boot option and try to boot
3581 //
3582 UnicodeSPrint (Buffer, sizeof (Buffer), L"Boot%04x", *BootNext);
3583 BootOption = BdsLibVariableToOption (&TempList, Buffer);
3584 ASSERT (BootOption != NULL);
3585 BdsLibConnectDevicePath (BootOption->DevicePath);
3586 BdsLibBootViaBootOption (BootOption, BootOption->DevicePath, &ExitDataSize, &ExitData);
3587 FreePool(BootOption);
3588 FreePool(BootNext);
3589 }
3590
3591 }
3592
3593 /**
3594 Return the bootable media handle.
3595 First, check the device is connected
3596 Second, check whether the device path point to a device which support SimpleFileSystemProtocol,
3597 Third, detect the the default boot file in the Media, and return the removable Media handle.
3598
3599 @param DevicePath Device Path to a bootable device
3600
3601 @return The bootable media handle. If the media on the DevicePath is not bootable, NULL will return.
3602
3603 **/
3604 EFI_HANDLE
3605 EFIAPI
3606 BdsLibGetBootableHandle (
3607 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
3608 )
3609 {
3610 EFI_STATUS Status;
3611 EFI_TPL OldTpl;
3612 EFI_DEVICE_PATH_PROTOCOL *UpdatedDevicePath;
3613 EFI_DEVICE_PATH_PROTOCOL *DupDevicePath;
3614 EFI_HANDLE Handle;
3615 EFI_BLOCK_IO_PROTOCOL *BlockIo;
3616 VOID *Buffer;
3617 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
3618 UINTN Size;
3619 UINTN TempSize;
3620 EFI_HANDLE ReturnHandle;
3621 EFI_HANDLE *SimpleFileSystemHandles;
3622
3623 UINTN NumberSimpleFileSystemHandles;
3624 UINTN Index;
3625 EFI_IMAGE_DOS_HEADER DosHeader;
3626 EFI_IMAGE_OPTIONAL_HEADER_UNION HdrData;
3627 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
3628
3629 UpdatedDevicePath = DevicePath;
3630
3631 //
3632 // Enter to critical section to protect the acquired BlockIo instance
3633 // from getting released due to the USB mass storage hotplug event
3634 //
3635 OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
3636
3637 //
3638 // Check whether the device is connected
3639 //
3640 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &UpdatedDevicePath, &Handle);
3641 if (EFI_ERROR (Status)) {
3642 //
3643 // Skip the case that the boot option point to a simple file protocol which does not consume block Io protocol,
3644 //
3645 Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &UpdatedDevicePath, &Handle);
3646 if (EFI_ERROR (Status)) {
3647 //
3648 // Fail to find the proper BlockIo and simple file protocol, maybe because device not present, we need to connect it firstly
3649 //
3650 UpdatedDevicePath = DevicePath;
3651 Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &UpdatedDevicePath, &Handle);
3652 gBS->ConnectController (Handle, NULL, NULL, TRUE);
3653 }
3654 } else {
3655 //
3656 // For removable device boot option, its contained device path only point to the removable device handle,
3657 // should make sure all its children handles (its child partion or media handles) are created and connected.
3658 //
3659 gBS->ConnectController (Handle, NULL, NULL, TRUE);
3660 //
3661 // Get BlockIo protocol and check removable attribute
3662 //
3663 Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo);
3664 ASSERT_EFI_ERROR (Status);
3665
3666 //
3667 // Issue a dummy read to the device to check for media change.
3668 // When the removable media is changed, any Block IO read/write will
3669 // cause the BlockIo protocol be reinstalled and EFI_MEDIA_CHANGED is
3670 // returned. After the Block IO protocol is reinstalled, subsequent
3671 // Block IO read/write will success.
3672 //
3673 Buffer = AllocatePool (BlockIo->Media->BlockSize);
3674 if (Buffer != NULL) {
3675 BlockIo->ReadBlocks (
3676 BlockIo,
3677 BlockIo->Media->MediaId,
3678 0,
3679 BlockIo->Media->BlockSize,
3680 Buffer
3681 );
3682 FreePool(Buffer);
3683 }
3684 }
3685
3686 //
3687 // Detect the the default boot file from removable Media
3688 //
3689
3690 //
3691 // If fail to get bootable handle specified by a USB boot option, the BDS should try to find other bootable device in the same USB bus
3692 // Try to locate the USB node device path first, if fail then use its previous PCI node to search
3693 //
3694 DupDevicePath = DuplicateDevicePath (DevicePath);
3695 ASSERT (DupDevicePath != NULL);
3696
3697 UpdatedDevicePath = DupDevicePath;
3698 Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &UpdatedDevicePath, &Handle);
3699 //
3700 // if the resulting device path point to a usb node, and the usb node is a dummy node, should only let device path only point to the previous Pci node
3701 // Acpi()/Pci()/Usb() --> Acpi()/Pci()
3702 //
3703 if ((DevicePathType (UpdatedDevicePath) == MESSAGING_DEVICE_PATH) &&
3704 (DevicePathSubType (UpdatedDevicePath) == MSG_USB_DP)) {
3705 //
3706 // Remove the usb node, let the device path only point to PCI node
3707 //
3708 SetDevicePathEndNode (UpdatedDevicePath);
3709 UpdatedDevicePath = DupDevicePath;
3710 } else {
3711 UpdatedDevicePath = DevicePath;
3712 }
3713
3714 //
3715 // Get the device path size of boot option
3716 //
3717 Size = GetDevicePathSize(UpdatedDevicePath) - sizeof (EFI_DEVICE_PATH_PROTOCOL); // minus the end node
3718 ReturnHandle = NULL;
3719 gBS->LocateHandleBuffer (
3720 ByProtocol,
3721 &gEfiSimpleFileSystemProtocolGuid,
3722 NULL,
3723 &NumberSimpleFileSystemHandles,
3724 &SimpleFileSystemHandles
3725 );
3726 for (Index = 0; Index < NumberSimpleFileSystemHandles; Index++) {
3727 //
3728 // Get the device path size of SimpleFileSystem handle
3729 //
3730 TempDevicePath = DevicePathFromHandle (SimpleFileSystemHandles[Index]);
3731 TempSize = GetDevicePathSize (TempDevicePath)- sizeof (EFI_DEVICE_PATH_PROTOCOL); // minus the end node
3732 //
3733 // Check whether the device path of boot option is part of the SimpleFileSystem handle's device path
3734 //
3735 if (Size <= TempSize && CompareMem (TempDevicePath, UpdatedDevicePath, Size)==0) {
3736 //
3737 // Load the default boot file \EFI\BOOT\boot{machinename}.EFI from removable Media
3738 // machinename is ia32, ia64, x64, ...
3739 //
3740 Hdr.Union = &HdrData;
3741 Status = BdsLibGetImageHeader (
3742 SimpleFileSystemHandles[Index],
3743 EFI_REMOVABLE_MEDIA_FILE_NAME,
3744 &DosHeader,
3745 Hdr
3746 );
3747 if (!EFI_ERROR (Status) &&
3748 EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Hdr.Pe32->FileHeader.Machine) &&
3749 Hdr.Pe32->OptionalHeader.Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {
3750 ReturnHandle = SimpleFileSystemHandles[Index];
3751 break;
3752 }
3753 }
3754 }
3755
3756 FreePool(DupDevicePath);
3757
3758 if (SimpleFileSystemHandles != NULL) {
3759 FreePool(SimpleFileSystemHandles);
3760 }
3761
3762 gBS->RestoreTPL (OldTpl);
3763
3764 return ReturnHandle;
3765 }
3766
3767 /**
3768 Check to see if the network cable is plugged in. If the DevicePath is not
3769 connected it will be connected.
3770
3771 @param DevicePath Device Path to check
3772
3773 @retval TRUE DevicePath points to an Network that is connected
3774 @retval FALSE DevicePath does not point to a bootable network
3775
3776 **/
3777 BOOLEAN
3778 BdsLibNetworkBootWithMediaPresent (
3779 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
3780 )
3781 {
3782 EFI_STATUS Status;
3783 EFI_DEVICE_PATH_PROTOCOL *UpdatedDevicePath;
3784 EFI_HANDLE Handle;
3785 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
3786 BOOLEAN MediaPresent;
3787 UINT32 InterruptStatus;
3788
3789 MediaPresent = FALSE;
3790
3791 UpdatedDevicePath = DevicePath;
3792 //
3793 // Locate Load File Protocol for PXE boot option first
3794 //
3795 Status = gBS->LocateDevicePath (&gEfiLoadFileProtocolGuid, &UpdatedDevicePath, &Handle);
3796 if (EFI_ERROR (Status)) {
3797 //
3798 // Device not present so see if we need to connect it
3799 //
3800 Status = BdsLibConnectDevicePath (DevicePath);
3801 if (!EFI_ERROR (Status)) {
3802 //
3803 // This one should work after we did the connect
3804 //
3805 Status = gBS->LocateDevicePath (&gEfiLoadFileProtocolGuid, &UpdatedDevicePath, &Handle);
3806 }
3807 }
3808
3809 if (!EFI_ERROR (Status)) {
3810 Status = gBS->HandleProtocol (Handle, &gEfiSimpleNetworkProtocolGuid, (VOID **)&Snp);
3811 if (EFI_ERROR (Status)) {
3812 //
3813 // Failed to open SNP from this handle, try to get SNP from parent handle
3814 //
3815 UpdatedDevicePath = DevicePathFromHandle (Handle);
3816 if (UpdatedDevicePath != NULL) {
3817 Status = gBS->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid, &UpdatedDevicePath, &Handle);
3818 if (!EFI_ERROR (Status)) {
3819 //
3820 // SNP handle found, get SNP from it
3821 //
3822 Status = gBS->HandleProtocol (Handle, &gEfiSimpleNetworkProtocolGuid, (VOID **) &Snp);
3823 }
3824 }
3825 }
3826
3827 if (!EFI_ERROR (Status)) {
3828 if (Snp->Mode->MediaPresentSupported) {
3829 if (Snp->Mode->State == EfiSimpleNetworkInitialized) {
3830 //
3831 // Invoke Snp->GetStatus() to refresh the media status
3832 //
3833 Snp->GetStatus (Snp, &InterruptStatus, NULL);
3834
3835 //
3836 // In case some one else is using the SNP check to see if it's connected
3837 //
3838 MediaPresent = Snp->Mode->MediaPresent;
3839 } else {
3840 //
3841 // No one is using SNP so we need to Start and Initialize so
3842 // MediaPresent will be valid.
3843 //
3844 Status = Snp->Start (Snp);
3845 if (!EFI_ERROR (Status)) {
3846 Status = Snp->Initialize (Snp, 0, 0);
3847 if (!EFI_ERROR (Status)) {
3848 MediaPresent = Snp->Mode->MediaPresent;
3849 Snp->Shutdown (Snp);
3850 }
3851 Snp->Stop (Snp);
3852 }
3853 }
3854 } else {
3855 MediaPresent = TRUE;
3856 }
3857 }
3858 }
3859
3860 return MediaPresent;
3861 }
3862
3863 /**
3864 For a bootable Device path, return its boot type.
3865
3866 @param DevicePath The bootable device Path to check
3867
3868 @retval BDS_EFI_MEDIA_HD_BOOT If given device path contains MEDIA_DEVICE_PATH type device path node
3869 which subtype is MEDIA_HARDDRIVE_DP
3870 @retval BDS_EFI_MEDIA_CDROM_BOOT If given device path contains MEDIA_DEVICE_PATH type device path node
3871 which subtype is MEDIA_CDROM_DP
3872 @retval BDS_EFI_ACPI_FLOPPY_BOOT If given device path contains ACPI_DEVICE_PATH type device path node
3873 which HID is floppy device.
3874 @retval BDS_EFI_MESSAGE_ATAPI_BOOT If given device path contains MESSAGING_DEVICE_PATH type device path node
3875 and its last device path node's subtype is MSG_ATAPI_DP.
3876 @retval BDS_EFI_MESSAGE_SCSI_BOOT If given device path contains MESSAGING_DEVICE_PATH type device path node
3877 and its last device path node's subtype is MSG_SCSI_DP.
3878 @retval BDS_EFI_MESSAGE_USB_DEVICE_BOOT If given device path contains MESSAGING_DEVICE_PATH type device path node
3879 and its last device path node's subtype is MSG_USB_DP.
3880 @retval BDS_EFI_MESSAGE_MISC_BOOT If the device path not contains any media device path node, and
3881 its last device path node point to a message device path node.
3882 @retval BDS_LEGACY_BBS_BOOT If given device path contains BBS_DEVICE_PATH type device path node.
3883 @retval BDS_EFI_UNSUPPORT An EFI Removable BlockIO device path not point to a media and message device,
3884
3885 **/
3886 UINT32
3887 EFIAPI
3888 BdsGetBootTypeFromDevicePath (
3889 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
3890 )
3891 {
3892 ACPI_HID_DEVICE_PATH *Acpi;
3893 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
3894 EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
3895 UINT32 BootType;
3896
3897 if (NULL == DevicePath) {
3898 return BDS_EFI_UNSUPPORT;
3899 }
3900
3901 TempDevicePath = DevicePath;
3902
3903 while (!IsDevicePathEndType (TempDevicePath)) {
3904 switch (DevicePathType (TempDevicePath)) {
3905 case BBS_DEVICE_PATH:
3906 return BDS_LEGACY_BBS_BOOT;
3907 case MEDIA_DEVICE_PATH:
3908 if (DevicePathSubType (TempDevicePath) == MEDIA_HARDDRIVE_DP) {
3909 return BDS_EFI_MEDIA_HD_BOOT;
3910 } else if (DevicePathSubType (TempDevicePath) == MEDIA_CDROM_DP) {
3911 return BDS_EFI_MEDIA_CDROM_BOOT;
3912 }
3913 break;
3914 case ACPI_DEVICE_PATH:
3915 Acpi = (ACPI_HID_DEVICE_PATH *) TempDevicePath;
3916 if (EISA_ID_TO_NUM (Acpi->HID) == 0x0604) {
3917 return BDS_EFI_ACPI_FLOPPY_BOOT;
3918 }
3919 break;
3920 case MESSAGING_DEVICE_PATH:
3921 //
3922 // Get the last device path node
3923 //
3924 LastDeviceNode = NextDevicePathNode (TempDevicePath);
3925 if (DevicePathSubType(LastDeviceNode) == MSG_DEVICE_LOGICAL_UNIT_DP) {
3926 //
3927 // if the next node type is Device Logical Unit, which specify the Logical Unit Number (LUN),
3928 // skip it
3929 //
3930 LastDeviceNode = NextDevicePathNode (LastDeviceNode);
3931 }
3932 //
3933 // if the device path not only point to driver device, it is not a messaging device path,
3934 //
3935 if (!IsDevicePathEndType (LastDeviceNode)) {
3936 break;
3937 }
3938
3939 switch (DevicePathSubType (TempDevicePath)) {
3940 case MSG_ATAPI_DP:
3941 BootType = BDS_EFI_MESSAGE_ATAPI_BOOT;
3942 break;
3943
3944 case MSG_USB_DP:
3945 BootType = BDS_EFI_MESSAGE_USB_DEVICE_BOOT;
3946 break;
3947
3948 case MSG_SCSI_DP:
3949 BootType = BDS_EFI_MESSAGE_SCSI_BOOT;
3950 break;
3951
3952 case MSG_SATA_DP:
3953 BootType = BDS_EFI_MESSAGE_SATA_BOOT;
3954 break;
3955
3956 case MSG_MAC_ADDR_DP:
3957 case MSG_VLAN_DP:
3958 case MSG_IPv4_DP:
3959 case MSG_IPv6_DP:
3960 BootType = BDS_EFI_MESSAGE_MAC_BOOT;
3961 break;
3962
3963 default:
3964 BootType = BDS_EFI_MESSAGE_MISC_BOOT;
3965 break;
3966 }
3967 return BootType;
3968
3969 default:
3970 break;
3971 }
3972 TempDevicePath = NextDevicePathNode (TempDevicePath);
3973 }
3974
3975 return BDS_EFI_UNSUPPORT;
3976 }
3977
3978 /**
3979 Check whether the Device path in a boot option point to a valid bootable device,
3980 And if CheckMedia is true, check the device is ready to boot now.
3981
3982 @param DevPath the Device path in a boot option
3983 @param CheckMedia if true, check the device is ready to boot now.
3984
3985 @retval TRUE the Device path is valid
3986 @retval FALSE the Device path is invalid .
3987
3988 **/
3989 BOOLEAN
3990 EFIAPI
3991 BdsLibIsValidEFIBootOptDevicePath (
3992 IN EFI_DEVICE_PATH_PROTOCOL *DevPath,
3993 IN BOOLEAN CheckMedia
3994 )
3995 {
3996 return BdsLibIsValidEFIBootOptDevicePathExt (DevPath, CheckMedia, NULL);
3997 }
3998
3999 /**
4000 Check whether the Device path in a boot option point to a valid bootable device,
4001 And if CheckMedia is true, check the device is ready to boot now.
4002 If Description is not NULL and the device path point to a fixed BlockIo
4003 device, check the description whether conflict with other auto-created
4004 boot options.
4005
4006 @param DevPath the Device path in a boot option
4007 @param CheckMedia if true, check the device is ready to boot now.
4008 @param Description the description in a boot option
4009
4010 @retval TRUE the Device path is valid
4011 @retval FALSE the Device path is invalid .
4012
4013 **/
4014 BOOLEAN
4015 EFIAPI
4016 BdsLibIsValidEFIBootOptDevicePathExt (
4017 IN EFI_DEVICE_PATH_PROTOCOL *DevPath,
4018 IN BOOLEAN CheckMedia,
4019 IN CHAR16 *Description
4020 )
4021 {
4022 EFI_STATUS Status;
4023 EFI_HANDLE Handle;
4024 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
4025 EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
4026 EFI_BLOCK_IO_PROTOCOL *BlockIo;
4027
4028 TempDevicePath = DevPath;
4029 LastDeviceNode = DevPath;
4030
4031 //
4032 // Check if it's a valid boot option for network boot device.
4033 // Check if there is EfiLoadFileProtocol installed.
4034 // If yes, that means there is a boot option for network.
4035 //
4036 Status = gBS->LocateDevicePath (
4037 &gEfiLoadFileProtocolGuid,
4038 &TempDevicePath,
4039 &Handle
4040 );
4041 if (EFI_ERROR (Status)) {
4042 //
4043 // Device not present so see if we need to connect it
4044 //
4045 TempDevicePath = DevPath;
4046 BdsLibConnectDevicePath (TempDevicePath);
4047 Status = gBS->LocateDevicePath (
4048 &gEfiLoadFileProtocolGuid,
4049 &TempDevicePath,
4050 &Handle
4051 );
4052 }
4053
4054 if (!EFI_ERROR (Status)) {
4055 if (!IsDevicePathEnd (TempDevicePath)) {
4056 //
4057 // LoadFile protocol is not installed on handle with exactly the same DevPath
4058 //
4059 return FALSE;
4060 }
4061
4062 if (CheckMedia) {
4063 //
4064 // Test if it is ready to boot now
4065 //
4066 if (BdsLibNetworkBootWithMediaPresent(DevPath)) {
4067 return TRUE;
4068 }
4069 } else {
4070 return TRUE;
4071 }
4072 }
4073
4074 //
4075 // If the boot option point to a file, it is a valid EFI boot option,
4076 // and assume it is ready to boot now
4077 //
4078 while (!IsDevicePathEnd (TempDevicePath)) {
4079 //
4080 // If there is USB Class or USB WWID device path node, treat it as valid EFI
4081 // Boot Option. BdsExpandUsbShortFormDevicePath () will be used to expand it
4082 // to full device path.
4083 //
4084 if ((DevicePathType (TempDevicePath) == MESSAGING_DEVICE_PATH) &&
4085 ((DevicePathSubType (TempDevicePath) == MSG_USB_CLASS_DP) ||
4086 (DevicePathSubType (TempDevicePath) == MSG_USB_WWID_DP))) {
4087 return TRUE;
4088 }
4089
4090 LastDeviceNode = TempDevicePath;
4091 TempDevicePath = NextDevicePathNode (TempDevicePath);
4092 }
4093 if ((DevicePathType (LastDeviceNode) == MEDIA_DEVICE_PATH) &&
4094 (DevicePathSubType (LastDeviceNode) == MEDIA_FILEPATH_DP)) {
4095 return TRUE;
4096 }
4097
4098 //
4099 // Check if it's a valid boot option for internal FV application
4100 //
4101 if (EfiGetNameGuidFromFwVolDevicePathNode ((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LastDeviceNode) != NULL) {
4102 //
4103 // If the boot option point to internal FV application, make sure it is valid
4104 //
4105 TempDevicePath = DevPath;
4106 Status = BdsLibUpdateFvFileDevicePath (
4107 &TempDevicePath,
4108 EfiGetNameGuidFromFwVolDevicePathNode ((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LastDeviceNode)
4109 );
4110 if (Status == EFI_ALREADY_STARTED) {
4111 return TRUE;
4112 } else {
4113 if (Status == EFI_SUCCESS) {
4114 FreePool (TempDevicePath);
4115 }
4116 return FALSE;
4117 }
4118 }
4119
4120 //
4121 // If the boot option point to a blockIO device:
4122 // if it is a removable blockIo device, it is valid.
4123 // if it is a fixed blockIo device, check its description confliction.
4124 //
4125 TempDevicePath = DevPath;
4126 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &TempDevicePath, &Handle);
4127 if (EFI_ERROR (Status)) {
4128 //
4129 // Device not present so see if we need to connect it
4130 //
4131 Status = BdsLibConnectDevicePath (DevPath);
4132 if (!EFI_ERROR (Status)) {
4133 //
4134 // Try again to get the Block Io protocol after we did the connect
4135 //
4136 TempDevicePath = DevPath;
4137 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &TempDevicePath, &Handle);
4138 }
4139 }
4140
4141 if (!EFI_ERROR (Status)) {
4142 Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo);
4143 if (!EFI_ERROR (Status)) {
4144 if (CheckMedia) {
4145 //
4146 // Test if it is ready to boot now
4147 //
4148 if (BdsLibGetBootableHandle (DevPath) != NULL) {
4149 return TRUE;
4150 }
4151 } else {
4152 return TRUE;
4153 }
4154 }
4155 } else {
4156 //
4157 // if the boot option point to a simple file protocol which does not consume block Io protocol, it is also a valid EFI boot option,
4158 //
4159 Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &TempDevicePath, &Handle);
4160 if (!EFI_ERROR (Status)) {
4161 if (CheckMedia) {
4162 //
4163 // Test if it is ready to boot now
4164 //
4165 if (BdsLibGetBootableHandle (DevPath) != NULL) {
4166 return TRUE;
4167 }
4168 } else {
4169 return TRUE;
4170 }
4171 }
4172 }
4173
4174 return FALSE;
4175 }
4176
4177
4178 /**
4179 According to a file guild, check a Fv file device path is valid. If it is invalid,
4180 try to return the valid device path.
4181 FV address maybe changes for memory layout adjust from time to time, use this function
4182 could promise the Fv file device path is right.
4183
4184 @param DevicePath on input, the Fv file device path need to check on
4185 output, the updated valid Fv file device path
4186 @param FileGuid the Fv file guild
4187
4188 @retval EFI_INVALID_PARAMETER the input DevicePath or FileGuid is invalid
4189 parameter
4190 @retval EFI_UNSUPPORTED the input DevicePath does not contain Fv file
4191 guild at all
4192 @retval EFI_ALREADY_STARTED the input DevicePath has pointed to Fv file, it is
4193 valid
4194 @retval EFI_SUCCESS has successfully updated the invalid DevicePath,
4195 and return the updated device path in DevicePath
4196
4197 **/
4198 EFI_STATUS
4199 EFIAPI
4200 BdsLibUpdateFvFileDevicePath (
4201 IN OUT EFI_DEVICE_PATH_PROTOCOL ** DevicePath,
4202 IN EFI_GUID *FileGuid
4203 )
4204 {
4205 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
4206 EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
4207 EFI_STATUS Status;
4208 EFI_GUID *GuidPoint;
4209 UINTN Index;
4210 UINTN FvHandleCount;
4211 EFI_HANDLE *FvHandleBuffer;
4212 EFI_FV_FILETYPE Type;
4213 UINTN Size;
4214 EFI_FV_FILE_ATTRIBUTES Attributes;
4215 UINT32 AuthenticationStatus;
4216 BOOLEAN FindFvFile;
4217 EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
4218 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
4219 MEDIA_FW_VOL_FILEPATH_DEVICE_PATH FvFileNode;
4220 EFI_HANDLE FoundFvHandle;
4221 EFI_DEVICE_PATH_PROTOCOL *NewDevicePath;
4222
4223 if ((DevicePath == NULL) || (*DevicePath == NULL)) {
4224 return EFI_INVALID_PARAMETER;
4225 }
4226 if (FileGuid == NULL) {
4227 return EFI_INVALID_PARAMETER;
4228 }
4229
4230 //
4231 // Check whether the device path point to the default the input Fv file
4232 //
4233 TempDevicePath = *DevicePath;
4234 LastDeviceNode = TempDevicePath;
4235 while (!IsDevicePathEnd (TempDevicePath)) {
4236 LastDeviceNode = TempDevicePath;
4237 TempDevicePath = NextDevicePathNode (TempDevicePath);
4238 }
4239 GuidPoint = EfiGetNameGuidFromFwVolDevicePathNode (
4240 (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LastDeviceNode
4241 );
4242 if (GuidPoint == NULL) {
4243 //
4244 // if this option does not points to a Fv file, just return EFI_UNSUPPORTED
4245 //
4246 return EFI_UNSUPPORTED;
4247 }
4248 if (!CompareGuid (GuidPoint, FileGuid)) {
4249 //
4250 // If the Fv file is not the input file guid, just return EFI_UNSUPPORTED
4251 //
4252 return EFI_UNSUPPORTED;
4253 }
4254
4255 //
4256 // Check whether the input Fv file device path is valid
4257 //
4258 TempDevicePath = *DevicePath;
4259 FoundFvHandle = NULL;
4260 Status = gBS->LocateDevicePath (
4261 &gEfiFirmwareVolume2ProtocolGuid,
4262 &TempDevicePath,
4263 &FoundFvHandle
4264 );
4265 if (!EFI_ERROR (Status)) {
4266 Status = gBS->HandleProtocol (
4267 FoundFvHandle,
4268 &gEfiFirmwareVolume2ProtocolGuid,
4269 (VOID **) &Fv
4270 );
4271 if (!EFI_ERROR (Status)) {
4272 //
4273 // Set FV ReadFile Buffer as NULL, only need to check whether input Fv file exist there
4274 //
4275 Status = Fv->ReadFile (
4276 Fv,
4277 FileGuid,
4278 NULL,
4279 &Size,
4280 &Type,
4281 &Attributes,
4282 &AuthenticationStatus
4283 );
4284 if (!EFI_ERROR (Status)) {
4285 return EFI_ALREADY_STARTED;
4286 }
4287 }
4288 }
4289
4290 //
4291 // Look for the input wanted FV file in current FV
4292 // First, try to look for in Bds own FV. Bds and input wanted FV file usually are in the same FV
4293 //
4294 FindFvFile = FALSE;
4295 FoundFvHandle = NULL;
4296 Status = gBS->HandleProtocol (
4297 gImageHandle,
4298 &gEfiLoadedImageProtocolGuid,
4299 (VOID **) &LoadedImage
4300 );
4301 if (!EFI_ERROR (Status)) {
4302 Status = gBS->HandleProtocol (
4303 LoadedImage->DeviceHandle,
4304 &gEfiFirmwareVolume2ProtocolGuid,
4305 (VOID **) &Fv
4306 );
4307 if (!EFI_ERROR (Status)) {
4308 Status = Fv->ReadFile (
4309 Fv,
4310 FileGuid,
4311 NULL,
4312 &Size,
4313 &Type,
4314 &Attributes,
4315 &AuthenticationStatus
4316 );
4317 if (!EFI_ERROR (Status)) {
4318 FindFvFile = TRUE;
4319 FoundFvHandle = LoadedImage->DeviceHandle;
4320 }
4321 }
4322 }
4323 //
4324 // Second, if fail to find, try to enumerate all FV
4325 //
4326 if (!FindFvFile) {
4327 FvHandleBuffer = NULL;
4328 gBS->LocateHandleBuffer (
4329 ByProtocol,
4330 &gEfiFirmwareVolume2ProtocolGuid,
4331 NULL,
4332 &FvHandleCount,
4333 &FvHandleBuffer
4334 );
4335 for (Index = 0; Index < FvHandleCount; Index++) {
4336 gBS->HandleProtocol (
4337 FvHandleBuffer[Index],
4338 &gEfiFirmwareVolume2ProtocolGuid,
4339 (VOID **) &Fv
4340 );
4341
4342 Status = Fv->ReadFile (
4343 Fv,
4344 FileGuid,
4345 NULL,
4346 &Size,
4347 &Type,
4348 &Attributes,
4349 &AuthenticationStatus
4350 );
4351 if (EFI_ERROR (Status)) {
4352 //
4353 // Skip if input Fv file not in the FV
4354 //
4355 continue;
4356 }
4357 FindFvFile = TRUE;
4358 FoundFvHandle = FvHandleBuffer[Index];
4359 break;
4360 }
4361
4362 if (FvHandleBuffer != NULL) {
4363 FreePool (FvHandleBuffer);
4364 }
4365 }
4366
4367 if (FindFvFile) {
4368 //
4369 // Build the shell device path
4370 //
4371 NewDevicePath = DevicePathFromHandle (FoundFvHandle);
4372 EfiInitializeFwVolDevicepathNode (&FvFileNode, FileGuid);
4373 NewDevicePath = AppendDevicePathNode (NewDevicePath, (EFI_DEVICE_PATH_PROTOCOL *) &FvFileNode);
4374 ASSERT (NewDevicePath != NULL);
4375 *DevicePath = NewDevicePath;
4376 return EFI_SUCCESS;
4377 }
4378 return EFI_NOT_FOUND;
4379 }