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