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