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