]> git.proxmox.com Git - mirror_edk2.git/blob - IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c
IntelFrameworkModulePkg/GenericBdsLib: update GenericBdsLib to report status code...
[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 - 2011, 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 /// This GUID is used for an EFI Variable that stores the front device pathes
23 /// for a partial device path that starts with the HD node.
24 ///
25 EFI_GUID mHdBootVariablePrivateGuid = { 0xfab7e9e1, 0x39dd, 0x4f2b, { 0x84, 0x8, 0xe2, 0xe, 0x90, 0x6c, 0xb6, 0xde } };
26
27 ///
28 /// This GUID is used for register UNI string.
29 ///
30 EFI_GUID mBdsLibStringPackGuid = { 0x3b4d9b23, 0x95ac, 0x44f6, { 0x9f, 0xcd, 0xe, 0x95, 0x94, 0x58, 0x6c, 0x72 } };
31
32 ///
33 /// This GUID is used for Set/Get platform language into/from variable at last time enumeration to ensure the enumeration will
34 /// only execute once.
35 ///
36 EFI_GUID mBdsLibLastLangGuid = { 0xe8c545b, 0xa2ee, 0x470d, { 0x8e, 0x26, 0xbd, 0xa1, 0xa1, 0x3c, 0xa, 0xa3 } };
37
38 /**
39 The constructor function register UNI strings into imageHandle.
40
41 It will ASSERT() if that operation fails and it will always return EFI_SUCCESS.
42
43 @param ImageHandle The firmware allocated handle for the EFI image.
44 @param SystemTable A pointer to the EFI System Table.
45
46 @retval EFI_SUCCESS The constructor successfully added string package.
47 @retval Other value The constructor can't add string package.
48
49 **/
50 EFI_STATUS
51 EFIAPI
52 GenericBdsLibConstructor (
53 IN EFI_HANDLE ImageHandle,
54 IN EFI_SYSTEM_TABLE *SystemTable
55 )
56 {
57
58 gBdsLibStringPackHandle = HiiAddPackages (
59 &mBdsLibStringPackGuid,
60 &ImageHandle,
61 GenericBdsLibStrings,
62 NULL
63 );
64
65 ASSERT (gBdsLibStringPackHandle != NULL);
66
67 return EFI_SUCCESS;
68 }
69
70
71
72 /**
73 Boot the legacy system with the boot option
74
75 @param Option The legacy boot option which have BBS device path
76
77 @retval EFI_UNSUPPORTED There is no legacybios protocol, do not support
78 legacy boot.
79 @retval EFI_STATUS Return the status of LegacyBios->LegacyBoot ().
80
81 **/
82 EFI_STATUS
83 BdsLibDoLegacyBoot (
84 IN BDS_COMMON_OPTION *Option
85 )
86 {
87 EFI_STATUS Status;
88 EFI_LEGACY_BIOS_PROTOCOL *LegacyBios;
89
90 Status = gBS->LocateProtocol (&gEfiLegacyBiosProtocolGuid, NULL, (VOID **) &LegacyBios);
91 if (EFI_ERROR (Status)) {
92 //
93 // If no LegacyBios protocol we do not support legacy boot
94 //
95 return EFI_UNSUPPORTED;
96 }
97 //
98 // Notes: if we separate the int 19, then we don't need to refresh BBS
99 //
100 BdsRefreshBbsTableForBoot (Option);
101
102 //
103 // Write boot to OS performance data for legacy boot.
104 //
105 PERF_CODE (
106 WriteBootToOsPerformanceData ();
107 );
108
109 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Legacy Boot: %S\n", Option->Description));
110 return LegacyBios->LegacyBoot (
111 LegacyBios,
112 (BBS_BBS_DEVICE_PATH *) Option->DevicePath,
113 Option->LoadOptionsSize,
114 Option->LoadOptions
115 );
116 }
117
118 /**
119 Internal function to check if the input boot option is a valid EFI NV Boot####.
120
121 @param OptionToCheck Boot option to be checked.
122
123 @retval TRUE This boot option matches a valid EFI NV Boot####.
124 @retval FALSE If not.
125
126 **/
127 BOOLEAN
128 IsBootOptionValidNVVarialbe (
129 IN BDS_COMMON_OPTION *OptionToCheck
130 )
131 {
132 LIST_ENTRY TempList;
133 BDS_COMMON_OPTION *BootOption;
134 BOOLEAN Valid;
135 CHAR16 OptionName[20];
136
137 Valid = FALSE;
138
139 InitializeListHead (&TempList);
140 UnicodeSPrint (OptionName, sizeof (OptionName), L"Boot%04x", OptionToCheck->BootCurrent);
141
142 BootOption = BdsLibVariableToOption (&TempList, OptionName);
143 if (BootOption == NULL) {
144 return FALSE;
145 }
146
147 //
148 // If the Boot Option Number and Device Path matches, OptionToCheck matches a
149 // valid EFI NV Boot####.
150 //
151 if ((OptionToCheck->BootCurrent == BootOption->BootCurrent) &&
152 (CompareMem (OptionToCheck->DevicePath, BootOption->DevicePath, GetDevicePathSize (OptionToCheck->DevicePath)) == 0))
153 {
154 Valid = TRUE;
155 }
156
157 FreePool (BootOption);
158
159 return Valid;
160 }
161
162 /**
163 Check whether a USB device match the specified USB Class device path. This
164 function follows "Load Option Processing" behavior in UEFI specification.
165
166 @param UsbIo USB I/O protocol associated with the USB device.
167 @param UsbClass The USB Class device path to match.
168
169 @retval TRUE The USB device match the USB Class device path.
170 @retval FALSE The USB device does not match the USB Class device path.
171
172 **/
173 BOOLEAN
174 BdsMatchUsbClass (
175 IN EFI_USB_IO_PROTOCOL *UsbIo,
176 IN USB_CLASS_DEVICE_PATH *UsbClass
177 )
178 {
179 EFI_STATUS Status;
180 EFI_USB_DEVICE_DESCRIPTOR DevDesc;
181 EFI_USB_INTERFACE_DESCRIPTOR IfDesc;
182 UINT8 DeviceClass;
183 UINT8 DeviceSubClass;
184 UINT8 DeviceProtocol;
185
186 if ((DevicePathType (UsbClass) != MESSAGING_DEVICE_PATH) ||
187 (DevicePathSubType (UsbClass) != MSG_USB_CLASS_DP)){
188 return FALSE;
189 }
190
191 //
192 // Check Vendor Id and Product Id.
193 //
194 Status = UsbIo->UsbGetDeviceDescriptor (UsbIo, &DevDesc);
195 if (EFI_ERROR (Status)) {
196 return FALSE;
197 }
198
199 if ((UsbClass->VendorId != 0xffff) &&
200 (UsbClass->VendorId != DevDesc.IdVendor)) {
201 return FALSE;
202 }
203
204 if ((UsbClass->ProductId != 0xffff) &&
205 (UsbClass->ProductId != DevDesc.IdProduct)) {
206 return FALSE;
207 }
208
209 DeviceClass = DevDesc.DeviceClass;
210 DeviceSubClass = DevDesc.DeviceSubClass;
211 DeviceProtocol = DevDesc.DeviceProtocol;
212 if (DeviceClass == 0) {
213 //
214 // If Class in Device Descriptor is set to 0, use the Class, SubClass and
215 // Protocol in Interface Descriptor instead.
216 //
217 Status = UsbIo->UsbGetInterfaceDescriptor (UsbIo, &IfDesc);
218 if (EFI_ERROR (Status)) {
219 return FALSE;
220 }
221
222 DeviceClass = IfDesc.InterfaceClass;
223 DeviceSubClass = IfDesc.InterfaceSubClass;
224 DeviceProtocol = IfDesc.InterfaceProtocol;
225 }
226
227 //
228 // Check Class, SubClass and Protocol.
229 //
230 if ((UsbClass->DeviceClass != 0xff) &&
231 (UsbClass->DeviceClass != DeviceClass)) {
232 return FALSE;
233 }
234
235 if ((UsbClass->DeviceSubClass != 0xff) &&
236 (UsbClass->DeviceSubClass != DeviceSubClass)) {
237 return FALSE;
238 }
239
240 if ((UsbClass->DeviceProtocol != 0xff) &&
241 (UsbClass->DeviceProtocol != DeviceProtocol)) {
242 return FALSE;
243 }
244
245 return TRUE;
246 }
247
248 /**
249 Check whether a USB device match the specified USB WWID device path. This
250 function follows "Load Option Processing" behavior in UEFI specification.
251
252 @param UsbIo USB I/O protocol associated with the USB device.
253 @param UsbWwid The USB WWID device path to match.
254
255 @retval TRUE The USB device match the USB WWID device path.
256 @retval FALSE The USB device does not match the USB WWID device path.
257
258 **/
259 BOOLEAN
260 BdsMatchUsbWwid (
261 IN EFI_USB_IO_PROTOCOL *UsbIo,
262 IN USB_WWID_DEVICE_PATH *UsbWwid
263 )
264 {
265 EFI_STATUS Status;
266 EFI_USB_DEVICE_DESCRIPTOR DevDesc;
267 EFI_USB_INTERFACE_DESCRIPTOR IfDesc;
268 UINT16 *LangIdTable;
269 UINT16 TableSize;
270 UINT16 Index;
271 CHAR16 *CompareStr;
272 UINTN CompareLen;
273 CHAR16 *SerialNumberStr;
274 UINTN Length;
275
276 if ((DevicePathType (UsbWwid) != MESSAGING_DEVICE_PATH) ||
277 (DevicePathSubType (UsbWwid) != MSG_USB_WWID_DP )){
278 return FALSE;
279 }
280
281 //
282 // Check Vendor Id and Product Id.
283 //
284 Status = UsbIo->UsbGetDeviceDescriptor (UsbIo, &DevDesc);
285 if (EFI_ERROR (Status)) {
286 return FALSE;
287 }
288 if ((DevDesc.IdVendor != UsbWwid->VendorId) ||
289 (DevDesc.IdProduct != UsbWwid->ProductId)) {
290 return FALSE;
291 }
292
293 //
294 // Check Interface Number.
295 //
296 Status = UsbIo->UsbGetInterfaceDescriptor (UsbIo, &IfDesc);
297 if (EFI_ERROR (Status)) {
298 return FALSE;
299 }
300 if (IfDesc.InterfaceNumber != UsbWwid->InterfaceNumber) {
301 return FALSE;
302 }
303
304 //
305 // Check Serial Number.
306 //
307 if (DevDesc.StrSerialNumber == 0) {
308 return FALSE;
309 }
310
311 //
312 // Get all supported languages.
313 //
314 TableSize = 0;
315 LangIdTable = NULL;
316 Status = UsbIo->UsbGetSupportedLanguages (UsbIo, &LangIdTable, &TableSize);
317 if (EFI_ERROR (Status) || (TableSize == 0) || (LangIdTable == NULL)) {
318 return FALSE;
319 }
320
321 //
322 // Serial number in USB WWID device path is the last 64-or-less UTF-16 characters.
323 //
324 CompareStr = (CHAR16 *) (UINTN) (UsbWwid + 1);
325 CompareLen = (DevicePathNodeLength (UsbWwid) - sizeof (USB_WWID_DEVICE_PATH)) / sizeof (CHAR16);
326 if (CompareStr[CompareLen - 1] == L'\0') {
327 CompareLen--;
328 }
329
330 //
331 // Compare serial number in each supported language.
332 //
333 for (Index = 0; Index < TableSize / sizeof (UINT16); Index++) {
334 SerialNumberStr = NULL;
335 Status = UsbIo->UsbGetStringDescriptor (
336 UsbIo,
337 LangIdTable[Index],
338 DevDesc.StrSerialNumber,
339 &SerialNumberStr
340 );
341 if (EFI_ERROR (Status) || (SerialNumberStr == NULL)) {
342 continue;
343 }
344
345 Length = StrLen (SerialNumberStr);
346 if ((Length >= CompareLen) &&
347 (CompareMem (SerialNumberStr + Length - CompareLen, CompareStr, CompareLen * sizeof (CHAR16)) == 0)) {
348 FreePool (SerialNumberStr);
349 return TRUE;
350 }
351
352 FreePool (SerialNumberStr);
353 }
354
355 return FALSE;
356 }
357
358 /**
359 Find a USB device path which match the specified short-form device path start
360 with USB Class or USB WWID device path and load the boot file then return the
361 image handle. If ParentDevicePath is NULL, this function will search in all USB
362 devices of the platform. If ParentDevicePath is not NULL,this function will only
363 search in its child devices.
364
365 @param ParentDevicePath The device path of the parent.
366 @param ShortFormDevicePath The USB Class or USB WWID device path to match.
367
368 @return The image Handle if find load file from specified short-form device path
369 or NULL if not found.
370
371 **/
372 EFI_HANDLE *
373 BdsFindUsbDevice (
374 IN EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath,
375 IN EFI_DEVICE_PATH_PROTOCOL *ShortFormDevicePath
376 )
377 {
378 EFI_STATUS Status;
379 UINTN UsbIoHandleCount;
380 EFI_HANDLE *UsbIoHandleBuffer;
381 EFI_DEVICE_PATH_PROTOCOL *UsbIoDevicePath;
382 EFI_USB_IO_PROTOCOL *UsbIo;
383 UINTN Index;
384 UINTN ParentSize;
385 UINTN Size;
386 EFI_HANDLE ImageHandle;
387 EFI_HANDLE Handle;
388 EFI_DEVICE_PATH_PROTOCOL *FullDevicePath;
389 EFI_DEVICE_PATH_PROTOCOL *NextDevicePath;
390
391 FullDevicePath = NULL;
392 ImageHandle = NULL;
393
394 //
395 // Get all UsbIo Handles.
396 //
397 UsbIoHandleCount = 0;
398 UsbIoHandleBuffer = NULL;
399 Status = gBS->LocateHandleBuffer (
400 ByProtocol,
401 &gEfiUsbIoProtocolGuid,
402 NULL,
403 &UsbIoHandleCount,
404 &UsbIoHandleBuffer
405 );
406 if (EFI_ERROR (Status) || (UsbIoHandleCount == 0) || (UsbIoHandleBuffer == NULL)) {
407 return NULL;
408 }
409
410 ParentSize = (ParentDevicePath == NULL) ? 0 : GetDevicePathSize (ParentDevicePath);
411 for (Index = 0; Index < UsbIoHandleCount; Index++) {
412 //
413 // Get the Usb IO interface.
414 //
415 Status = gBS->HandleProtocol(
416 UsbIoHandleBuffer[Index],
417 &gEfiUsbIoProtocolGuid,
418 (VOID **) &UsbIo
419 );
420 if (EFI_ERROR (Status)) {
421 continue;
422 }
423
424 UsbIoDevicePath = DevicePathFromHandle (UsbIoHandleBuffer[Index]);
425 if (UsbIoDevicePath == NULL) {
426 continue;
427 }
428
429 if (ParentDevicePath != NULL) {
430 //
431 // Compare starting part of UsbIoHandle's device path with ParentDevicePath.
432 //
433 Size = GetDevicePathSize (UsbIoDevicePath);
434 if ((Size < ParentSize) ||
435 (CompareMem (UsbIoDevicePath, ParentDevicePath, ParentSize - END_DEVICE_PATH_LENGTH) != 0)) {
436 continue;
437 }
438 }
439
440 if (BdsMatchUsbClass (UsbIo, (USB_CLASS_DEVICE_PATH *) ShortFormDevicePath) ||
441 BdsMatchUsbWwid (UsbIo, (USB_WWID_DEVICE_PATH *) ShortFormDevicePath)) {
442 //
443 // Try to find if there is the boot file in this DevicePath
444 //
445 NextDevicePath = NextDevicePathNode (ShortFormDevicePath);
446 if (!IsDevicePathEnd (NextDevicePath)) {
447 FullDevicePath = AppendDevicePath (UsbIoDevicePath, NextDevicePath);
448 //
449 // Connect the full device path, so that Simple File System protocol
450 // could be installed for this USB device.
451 //
452 BdsLibConnectDevicePath (FullDevicePath);
453 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderLoad));
454 Status = gBS->LoadImage (
455 TRUE,
456 gImageHandle,
457 FullDevicePath,
458 NULL,
459 0,
460 &ImageHandle
461 );
462 FreePool (FullDevicePath);
463 } else {
464 FullDevicePath = UsbIoDevicePath;
465 Status = EFI_NOT_FOUND;
466 }
467
468 //
469 // If we didn't find an image directly, we need to try as if it is a removable device boot option
470 // and load the image according to the default boot behavior for removable device.
471 //
472 if (EFI_ERROR (Status)) {
473 //
474 // check if there is a bootable removable media could be found in this device path ,
475 // and get the bootable media handle
476 //
477 Handle = BdsLibGetBootableHandle(UsbIoDevicePath);
478 if (Handle == NULL) {
479 continue;
480 }
481 //
482 // Load the default boot file \EFI\BOOT\boot{machinename}.EFI from removable Media
483 // machinename is ia32, ia64, x64, ...
484 //
485 FullDevicePath = FileDevicePath (Handle, EFI_REMOVABLE_MEDIA_FILE_NAME);
486 if (FullDevicePath != NULL) {
487 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderLoad));
488 Status = gBS->LoadImage (
489 TRUE,
490 gImageHandle,
491 FullDevicePath,
492 NULL,
493 0,
494 &ImageHandle
495 );
496 if (EFI_ERROR (Status)) {
497 //
498 // The DevicePath failed, and it's not a valid
499 // removable media device.
500 //
501 continue;
502 }
503 } else {
504 continue;
505 }
506 }
507 break;
508 }
509 }
510
511 FreePool (UsbIoHandleBuffer);
512 return ImageHandle;
513 }
514
515 /**
516 Expand USB Class or USB WWID device path node to be full device path of a USB
517 device in platform then load the boot file on this full device path and return the
518 image handle.
519
520 This function support following 4 cases:
521 1) Boot Option device path starts with a USB Class or USB WWID device path,
522 and there is no Media FilePath device path in the end.
523 In this case, it will follow Removable Media Boot Behavior.
524 2) Boot Option device path starts with a USB Class or USB WWID device path,
525 and ended with Media FilePath device path.
526 3) Boot Option device path starts with a full device path to a USB Host Controller,
527 contains a USB Class or USB WWID device path node, while not ended with Media
528 FilePath device path. In this case, it will follow Removable Media Boot Behavior.
529 4) Boot Option device path starts with a full device path to a USB Host Controller,
530 contains a USB Class or USB WWID device path node, and ended with Media
531 FilePath device path.
532
533 @param DevicePath The Boot Option device path.
534
535 @return The image handle of boot file, or NULL if there is no boot file found in
536 the specified USB Class or USB WWID device path.
537
538 **/
539 EFI_HANDLE *
540 BdsExpandUsbShortFormDevicePath (
541 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
542 )
543 {
544 EFI_HANDLE *ImageHandle;
545 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
546 EFI_DEVICE_PATH_PROTOCOL *ShortFormDevicePath;
547
548 //
549 // Search for USB Class or USB WWID device path node.
550 //
551 ShortFormDevicePath = NULL;
552 ImageHandle = NULL;
553 TempDevicePath = DevicePath;
554 while (!IsDevicePathEnd (TempDevicePath)) {
555 if ((DevicePathType (TempDevicePath) == MESSAGING_DEVICE_PATH) &&
556 ((DevicePathSubType (TempDevicePath) == MSG_USB_CLASS_DP) ||
557 (DevicePathSubType (TempDevicePath) == MSG_USB_WWID_DP))) {
558 ShortFormDevicePath = TempDevicePath;
559 break;
560 }
561 TempDevicePath = NextDevicePathNode (TempDevicePath);
562 }
563
564 if (ShortFormDevicePath == NULL) {
565 //
566 // No USB Class or USB WWID device path node found, do nothing.
567 //
568 return NULL;
569 }
570
571 if (ShortFormDevicePath == DevicePath) {
572 //
573 // Boot Option device path starts with USB Class or USB WWID device path.
574 //
575 ImageHandle = BdsFindUsbDevice (NULL, ShortFormDevicePath);
576 if (ImageHandle == NULL) {
577 //
578 // Failed to find a match in existing devices, connect the short form USB
579 // device path and try again.
580 //
581 BdsLibConnectUsbDevByShortFormDP (0xff, ShortFormDevicePath);
582 ImageHandle = BdsFindUsbDevice (NULL, ShortFormDevicePath);
583 }
584 } else {
585 //
586 // Boot Option device path contains USB Class or USB WWID device path node.
587 //
588
589 //
590 // Prepare the parent device path for search.
591 //
592 TempDevicePath = DuplicateDevicePath (DevicePath);
593 ASSERT (TempDevicePath != NULL);
594 SetDevicePathEndNode (((UINT8 *) TempDevicePath) + ((UINTN) ShortFormDevicePath - (UINTN) DevicePath));
595
596 //
597 // The USB Host Controller device path is already in Boot Option device path
598 // and USB Bus driver already support RemainingDevicePath starts with USB
599 // Class or USB WWID device path, so just search in existing USB devices and
600 // doesn't perform ConnectController here.
601 //
602 ImageHandle = BdsFindUsbDevice (TempDevicePath, ShortFormDevicePath);
603 FreePool (TempDevicePath);
604 }
605
606 return ImageHandle;
607 }
608
609 /**
610 Process the boot option follow the UEFI specification and
611 special treat the legacy boot option with BBS_DEVICE_PATH.
612
613 @param Option The boot option need to be processed
614 @param DevicePath The device path which describe where to load the
615 boot image or the legacy BBS device path to boot
616 the legacy OS
617 @param ExitDataSize The size of exit data.
618 @param ExitData Data returned when Boot image failed.
619
620 @retval EFI_SUCCESS Boot from the input boot option successfully.
621 @retval EFI_NOT_FOUND If the Device Path is not found in the system
622
623 **/
624 EFI_STATUS
625 EFIAPI
626 BdsLibBootViaBootOption (
627 IN BDS_COMMON_OPTION *Option,
628 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
629 OUT UINTN *ExitDataSize,
630 OUT CHAR16 **ExitData OPTIONAL
631 )
632 {
633 EFI_STATUS Status;
634 EFI_HANDLE Handle;
635 EFI_HANDLE ImageHandle;
636 EFI_DEVICE_PATH_PROTOCOL *FilePath;
637 EFI_LOADED_IMAGE_PROTOCOL *ImageInfo;
638 EFI_DEVICE_PATH_PROTOCOL *WorkingDevicePath;
639 EFI_ACPI_S3_SAVE_PROTOCOL *AcpiS3Save;
640 LIST_ENTRY TempBootLists;
641
642 //
643 // Record the performance data for End of BDS
644 //
645 PERF_END(NULL, "BDS", NULL, 0);
646
647 *ExitDataSize = 0;
648 *ExitData = NULL;
649
650 //
651 // Notes: this code can be remove after the s3 script table
652 // hook on the event EVT_SIGNAL_READY_TO_BOOT or
653 // EVT_SIGNAL_LEGACY_BOOT
654 //
655 Status = gBS->LocateProtocol (&gEfiAcpiS3SaveProtocolGuid, NULL, (VOID **) &AcpiS3Save);
656 if (!EFI_ERROR (Status)) {
657 AcpiS3Save->S3Save (AcpiS3Save, NULL);
658 }
659 //
660 // If it's Device Path that starts with a hard drive path, append it with the front part to compose a
661 // full device path
662 //
663 WorkingDevicePath = NULL;
664 if ((DevicePathType (DevicePath) == MEDIA_DEVICE_PATH) &&
665 (DevicePathSubType (DevicePath) == MEDIA_HARDDRIVE_DP)) {
666 WorkingDevicePath = BdsExpandPartitionPartialDevicePathToFull (
667 (HARDDRIVE_DEVICE_PATH *)DevicePath
668 );
669 if (WorkingDevicePath != NULL) {
670 DevicePath = WorkingDevicePath;
671 }
672 }
673
674 //
675 // Expand USB Class or USB WWID drive path node to full device path.
676 //
677 ImageHandle = BdsExpandUsbShortFormDevicePath (DevicePath);
678
679 //
680 // Signal the EVT_SIGNAL_READY_TO_BOOT event
681 //
682 EfiSignalEventReadyToBoot();
683
684 //
685 // Adjust the different type memory page number just before booting
686 // and save the updated info into the variable for next boot to use
687 //
688 BdsSetMemoryTypeInformationVariable ();
689
690
691 //
692 // Set Boot Current
693 //
694 if (IsBootOptionValidNVVarialbe (Option)) {
695 //
696 // For a temporary boot (i.e. a boot by selected a EFI Shell using "Boot From File"), Boot Current is actually not valid.
697 // In this case, "BootCurrent" is not created.
698 // Only create the BootCurrent variable when it points to a valid Boot#### variable.
699 //
700 gRT->SetVariable (
701 L"BootCurrent",
702 &gEfiGlobalVariableGuid,
703 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
704 sizeof (UINT16),
705 &Option->BootCurrent
706 );
707 }
708
709 //
710 // By expanding the USB Class or WWID device path, the ImageHandle has returnned.
711 // Here get the ImageHandle for the non USB class or WWID device path.
712 //
713 if (ImageHandle == NULL) {
714 ASSERT (Option->DevicePath != NULL);
715 if ((DevicePathType (Option->DevicePath) == BBS_DEVICE_PATH) &&
716 (DevicePathSubType (Option->DevicePath) == BBS_BBS_DP)
717 ) {
718 //
719 // Check to see if we should legacy BOOT. If yes then do the legacy boot
720 //
721 return BdsLibDoLegacyBoot (Option);
722 }
723
724 //
725 // If the boot option point to Internal FV shell, make sure it is valid
726 //
727 Status = BdsLibUpdateFvFileDevicePath (&DevicePath, PcdGetPtr(PcdShellFile));
728 if (!EFI_ERROR(Status)) {
729 if (Option->DevicePath != NULL) {
730 FreePool(Option->DevicePath);
731 }
732 Option->DevicePath = AllocateZeroPool (GetDevicePathSize (DevicePath));
733 ASSERT(Option->DevicePath != NULL);
734 CopyMem (Option->DevicePath, DevicePath, GetDevicePathSize (DevicePath));
735 //
736 // Update the shell boot option
737 //
738 InitializeListHead (&TempBootLists);
739 BdsLibRegisterNewOption (&TempBootLists, DevicePath, L"EFI Internal Shell", L"BootOrder");
740
741 //
742 // free the temporary device path created by BdsLibUpdateFvFileDevicePath()
743 //
744 FreePool (DevicePath);
745 DevicePath = Option->DevicePath;
746 }
747
748 DEBUG_CODE_BEGIN();
749
750 if (Option->Description == NULL) {
751 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Booting from unknown device path\n"));
752 } else {
753 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Booting %S\n", Option->Description));
754 }
755
756 DEBUG_CODE_END();
757
758 //
759 // Report status code for OS Loader LoadImage.
760 //
761 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderLoad));
762 Status = gBS->LoadImage (
763 TRUE,
764 gImageHandle,
765 DevicePath,
766 NULL,
767 0,
768 &ImageHandle
769 );
770
771 //
772 // If we didn't find an image directly, we need to try as if it is a removable device boot option
773 // and load the image according to the default boot behavior for removable device.
774 //
775 if (EFI_ERROR (Status)) {
776 //
777 // check if there is a bootable removable media could be found in this device path ,
778 // and get the bootable media handle
779 //
780 Handle = BdsLibGetBootableHandle(DevicePath);
781 if (Handle == NULL) {
782 goto Done;
783 }
784 //
785 // Load the default boot file \EFI\BOOT\boot{machinename}.EFI from removable Media
786 // machinename is ia32, ia64, x64, ...
787 //
788 FilePath = FileDevicePath (Handle, EFI_REMOVABLE_MEDIA_FILE_NAME);
789 if (FilePath != NULL) {
790 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderLoad));
791 Status = gBS->LoadImage (
792 TRUE,
793 gImageHandle,
794 FilePath,
795 NULL,
796 0,
797 &ImageHandle
798 );
799 if (EFI_ERROR (Status)) {
800 //
801 // The DevicePath failed, and it's not a valid
802 // removable media device.
803 //
804 goto Done;
805 }
806 }
807 }
808
809 if (EFI_ERROR (Status)) {
810 //
811 // It there is any error from the Boot attempt exit now.
812 //
813 goto Done;
814 }
815 }
816 //
817 // Provide the image with it's load options
818 //
819 if (ImageHandle == NULL) {
820 goto Done;
821 }
822 Status = gBS->HandleProtocol (ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &ImageInfo);
823 ASSERT_EFI_ERROR (Status);
824
825 if (Option->LoadOptionsSize != 0) {
826 ImageInfo->LoadOptionsSize = Option->LoadOptionsSize;
827 ImageInfo->LoadOptions = Option->LoadOptions;
828 }
829 //
830 // Before calling the image, enable the Watchdog Timer for
831 // the 5 Minute period
832 //
833 gBS->SetWatchdogTimer (5 * 60, 0x0000, 0x00, NULL);
834
835 //
836 // Write boot to OS performance data for UEFI boot
837 //
838 PERF_CODE (
839 WriteBootToOsPerformanceData ();
840 );
841
842 //
843 // Report status code for OS Loader StartImage.
844 //
845 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderStart));
846
847 Status = gBS->StartImage (ImageHandle, ExitDataSize, ExitData);
848 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Image Return Status = %r\n", Status));
849
850 //
851 // Clear the Watchdog Timer after the image returns
852 //
853 gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL);
854
855 Done:
856 //
857 // Clear Boot Current
858 //
859 gRT->SetVariable (
860 L"BootCurrent",
861 &gEfiGlobalVariableGuid,
862 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
863 0,
864 &Option->BootCurrent
865 );
866
867 return Status;
868 }
869
870
871 /**
872 Expand a device path that starts with a hard drive media device path node to be a
873 full device path that includes the full hardware path to the device. We need
874 to do this so it can be booted. As an optimization the front match (the part point
875 to the partition node. E.g. ACPI() /PCI()/ATA()/Partition() ) is saved in a variable
876 so a connect all is not required on every boot. All successful history device path
877 which point to partition node (the front part) will be saved.
878
879 @param HardDriveDevicePath EFI Device Path to boot, if it starts with a hard
880 drive media device path.
881 @return A Pointer to the full device path or NULL if a valid Hard Drive devic path
882 cannot be found.
883
884 **/
885 EFI_DEVICE_PATH_PROTOCOL *
886 EFIAPI
887 BdsExpandPartitionPartialDevicePathToFull (
888 IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath
889 )
890 {
891 EFI_STATUS Status;
892 UINTN BlockIoHandleCount;
893 EFI_HANDLE *BlockIoBuffer;
894 EFI_DEVICE_PATH_PROTOCOL *FullDevicePath;
895 EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath;
896 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
897 UINTN Index;
898 UINTN InstanceNum;
899 EFI_DEVICE_PATH_PROTOCOL *CachedDevicePath;
900 EFI_DEVICE_PATH_PROTOCOL *TempNewDevicePath;
901 UINTN CachedDevicePathSize;
902 BOOLEAN DeviceExist;
903 BOOLEAN NeedAdjust;
904 EFI_DEVICE_PATH_PROTOCOL *Instance;
905 UINTN Size;
906
907 FullDevicePath = NULL;
908 //
909 // Check if there is prestore 'HDDP' variable.
910 // If exist, search the front path which point to partition node in the variable instants.
911 // If fail to find or 'HDDP' not exist, reconnect all and search in all system
912 //
913 CachedDevicePath = BdsLibGetVariableAndSize (
914 L"HDDP",
915 &mHdBootVariablePrivateGuid,
916 &CachedDevicePathSize
917 );
918
919 if (CachedDevicePath != NULL) {
920 TempNewDevicePath = CachedDevicePath;
921 DeviceExist = FALSE;
922 NeedAdjust = FALSE;
923 do {
924 //
925 // Check every instance of the variable
926 // First, check whether the instance contain the partition node, which is needed for distinguishing multi
927 // partial partition boot option. Second, check whether the instance could be connected.
928 //
929 Instance = GetNextDevicePathInstance (&TempNewDevicePath, &Size);
930 if (MatchPartitionDevicePathNode (Instance, HardDriveDevicePath)) {
931 //
932 // Connect the device path instance, the device path point to hard drive media device path node
933 // e.g. ACPI() /PCI()/ATA()/Partition()
934 //
935 Status = BdsLibConnectDevicePath (Instance);
936 if (!EFI_ERROR (Status)) {
937 DeviceExist = TRUE;
938 break;
939 }
940 }
941 //
942 // Come here means the first instance is not matched
943 //
944 NeedAdjust = TRUE;
945 FreePool(Instance);
946 } while (TempNewDevicePath != NULL);
947
948 if (DeviceExist) {
949 //
950 // Find the matched device path.
951 // Append the file path information from the boot option and return the fully expanded device path.
952 //
953 DevicePath = NextDevicePathNode ((EFI_DEVICE_PATH_PROTOCOL *) HardDriveDevicePath);
954 FullDevicePath = AppendDevicePath (Instance, DevicePath);
955
956 //
957 // Adjust the 'HDDP' instances sequence if the matched one is not first one.
958 //
959 if (NeedAdjust) {
960 //
961 // First delete the matched instance.
962 //
963 TempNewDevicePath = CachedDevicePath;
964 CachedDevicePath = BdsLibDelPartMatchInstance (CachedDevicePath, Instance );
965 FreePool (TempNewDevicePath);
966
967 //
968 // Second, append the remaining path after the matched instance
969 //
970 TempNewDevicePath = CachedDevicePath;
971 CachedDevicePath = AppendDevicePathInstance (Instance, CachedDevicePath );
972 FreePool (TempNewDevicePath);
973 //
974 // Save the matching Device Path so we don't need to do a connect all next time
975 //
976 Status = gRT->SetVariable (
977 L"HDDP",
978 &mHdBootVariablePrivateGuid,
979 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
980 GetDevicePathSize (CachedDevicePath),
981 CachedDevicePath
982 );
983 }
984
985 FreePool (Instance);
986 FreePool (CachedDevicePath);
987 return FullDevicePath;
988 }
989 }
990
991 //
992 // If we get here we fail to find or 'HDDP' not exist, and now we need
993 // to search all devices in the system for a matched partition
994 //
995 BdsLibConnectAllDriversToAllControllers ();
996 Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiBlockIoProtocolGuid, NULL, &BlockIoHandleCount, &BlockIoBuffer);
997 if (EFI_ERROR (Status) || BlockIoHandleCount == 0 || BlockIoBuffer == NULL) {
998 //
999 // If there was an error or there are no device handles that support
1000 // the BLOCK_IO Protocol, then return.
1001 //
1002 return NULL;
1003 }
1004 //
1005 // Loop through all the device handles that support the BLOCK_IO Protocol
1006 //
1007 for (Index = 0; Index < BlockIoHandleCount; Index++) {
1008
1009 Status = gBS->HandleProtocol (BlockIoBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID *) &BlockIoDevicePath);
1010 if (EFI_ERROR (Status) || BlockIoDevicePath == NULL) {
1011 continue;
1012 }
1013
1014 if (MatchPartitionDevicePathNode (BlockIoDevicePath, HardDriveDevicePath)) {
1015 //
1016 // Find the matched partition device path
1017 //
1018 DevicePath = NextDevicePathNode ((EFI_DEVICE_PATH_PROTOCOL *) HardDriveDevicePath);
1019 FullDevicePath = AppendDevicePath (BlockIoDevicePath, DevicePath);
1020
1021 //
1022 // Save the matched partition device path in 'HDDP' variable
1023 //
1024 if (CachedDevicePath != NULL) {
1025 //
1026 // Save the matched partition device path as first instance of 'HDDP' variable
1027 //
1028 if (BdsLibMatchDevicePaths (CachedDevicePath, BlockIoDevicePath)) {
1029 TempNewDevicePath = CachedDevicePath;
1030 CachedDevicePath = BdsLibDelPartMatchInstance (CachedDevicePath, BlockIoDevicePath);
1031 FreePool(TempNewDevicePath);
1032
1033 TempNewDevicePath = CachedDevicePath;
1034 CachedDevicePath = AppendDevicePathInstance (BlockIoDevicePath, CachedDevicePath);
1035 if (TempNewDevicePath != NULL) {
1036 FreePool(TempNewDevicePath);
1037 }
1038 } else {
1039 TempNewDevicePath = CachedDevicePath;
1040 CachedDevicePath = AppendDevicePathInstance (BlockIoDevicePath, CachedDevicePath);
1041 FreePool(TempNewDevicePath);
1042 }
1043 //
1044 // Here limit the device path instance number to 12, which is max number for a system support 3 IDE controller
1045 // If the user try to boot many OS in different HDs or partitions, in theory, the 'HDDP' variable maybe become larger and larger.
1046 //
1047 InstanceNum = 0;
1048 ASSERT (CachedDevicePath != NULL);
1049 TempNewDevicePath = CachedDevicePath;
1050 while (!IsDevicePathEnd (TempNewDevicePath)) {
1051 TempNewDevicePath = NextDevicePathNode (TempNewDevicePath);
1052 //
1053 // Parse one instance
1054 //
1055 while (!IsDevicePathEndType (TempNewDevicePath)) {
1056 TempNewDevicePath = NextDevicePathNode (TempNewDevicePath);
1057 }
1058 InstanceNum++;
1059 //
1060 // If the CachedDevicePath variable contain too much instance, only remain 12 instances.
1061 //
1062 if (InstanceNum >= 12) {
1063 SetDevicePathEndNode (TempNewDevicePath);
1064 break;
1065 }
1066 }
1067 } else {
1068 CachedDevicePath = DuplicateDevicePath (BlockIoDevicePath);
1069 }
1070
1071 //
1072 // Save the matching Device Path so we don't need to do a connect all next time
1073 //
1074 Status = gRT->SetVariable (
1075 L"HDDP",
1076 &mHdBootVariablePrivateGuid,
1077 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1078 GetDevicePathSize (CachedDevicePath),
1079 CachedDevicePath
1080 );
1081
1082 break;
1083 }
1084 }
1085
1086 if (CachedDevicePath != NULL) {
1087 FreePool (CachedDevicePath);
1088 }
1089 if (BlockIoBuffer != NULL) {
1090 FreePool (BlockIoBuffer);
1091 }
1092 return FullDevicePath;
1093 }
1094
1095 /**
1096 Check whether there is a instance in BlockIoDevicePath, which contain multi device path
1097 instances, has the same partition node with HardDriveDevicePath device path
1098
1099 @param BlockIoDevicePath Multi device path instances which need to check
1100 @param HardDriveDevicePath A device path which starts with a hard drive media
1101 device path.
1102
1103 @retval TRUE There is a matched device path instance.
1104 @retval FALSE There is no matched device path instance.
1105
1106 **/
1107 BOOLEAN
1108 EFIAPI
1109 MatchPartitionDevicePathNode (
1110 IN EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath,
1111 IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath
1112 )
1113 {
1114 HARDDRIVE_DEVICE_PATH *TmpHdPath;
1115 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1116 BOOLEAN Match;
1117 EFI_DEVICE_PATH_PROTOCOL *BlockIoHdDevicePathNode;
1118
1119 if ((BlockIoDevicePath == NULL) || (HardDriveDevicePath == NULL)) {
1120 return FALSE;
1121 }
1122
1123 //
1124 // Make PreviousDevicePath == the device path node before the end node
1125 //
1126 DevicePath = BlockIoDevicePath;
1127 BlockIoHdDevicePathNode = NULL;
1128
1129 //
1130 // find the partition device path node
1131 //
1132 while (!IsDevicePathEnd (DevicePath)) {
1133 if ((DevicePathType (DevicePath) == MEDIA_DEVICE_PATH) &&
1134 (DevicePathSubType (DevicePath) == MEDIA_HARDDRIVE_DP)
1135 ) {
1136 BlockIoHdDevicePathNode = DevicePath;
1137 break;
1138 }
1139
1140 DevicePath = NextDevicePathNode (DevicePath);
1141 }
1142
1143 if (BlockIoHdDevicePathNode == NULL) {
1144 return FALSE;
1145 }
1146 //
1147 // See if the harddrive device path in blockio matches the orig Hard Drive Node
1148 //
1149 TmpHdPath = (HARDDRIVE_DEVICE_PATH *) BlockIoHdDevicePathNode;
1150 Match = FALSE;
1151
1152 //
1153 // Check for the match
1154 //
1155 if ((TmpHdPath->MBRType == HardDriveDevicePath->MBRType) &&
1156 (TmpHdPath->SignatureType == HardDriveDevicePath->SignatureType)) {
1157 switch (TmpHdPath->SignatureType) {
1158 case SIGNATURE_TYPE_GUID:
1159 Match = CompareGuid ((EFI_GUID *)TmpHdPath->Signature, (EFI_GUID *)HardDriveDevicePath->Signature);
1160 break;
1161 case SIGNATURE_TYPE_MBR:
1162 Match = (BOOLEAN)(*((UINT32 *)(&(TmpHdPath->Signature[0]))) == ReadUnaligned32((UINT32 *)(&(HardDriveDevicePath->Signature[0]))));
1163 break;
1164 default:
1165 Match = FALSE;
1166 break;
1167 }
1168 }
1169
1170 return Match;
1171 }
1172
1173 /**
1174 Delete the boot option associated with the handle passed in.
1175
1176 @param Handle The handle which present the device path to create
1177 boot option
1178
1179 @retval EFI_SUCCESS Delete the boot option success
1180 @retval EFI_NOT_FOUND If the Device Path is not found in the system
1181 @retval EFI_OUT_OF_RESOURCES Lack of memory resource
1182 @retval Other Error return value from SetVariable()
1183
1184 **/
1185 EFI_STATUS
1186 BdsLibDeleteOptionFromHandle (
1187 IN EFI_HANDLE Handle
1188 )
1189 {
1190 UINT16 *BootOrder;
1191 UINT8 *BootOptionVar;
1192 UINTN BootOrderSize;
1193 UINTN BootOptionSize;
1194 EFI_STATUS Status;
1195 UINTN Index;
1196 UINT16 BootOption[BOOT_OPTION_MAX_CHAR];
1197 UINTN DevicePathSize;
1198 UINTN OptionDevicePathSize;
1199 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1200 EFI_DEVICE_PATH_PROTOCOL *OptionDevicePath;
1201 UINT8 *TempPtr;
1202
1203 Status = EFI_SUCCESS;
1204 BootOrder = NULL;
1205 BootOrderSize = 0;
1206
1207 //
1208 // Check "BootOrder" variable, if no, means there is no any boot order.
1209 //
1210 BootOrder = BdsLibGetVariableAndSize (
1211 L"BootOrder",
1212 &gEfiGlobalVariableGuid,
1213 &BootOrderSize
1214 );
1215 if (BootOrder == NULL) {
1216 return EFI_NOT_FOUND;
1217 }
1218
1219 //
1220 // Convert device handle to device path protocol instance
1221 //
1222 DevicePath = DevicePathFromHandle (Handle);
1223 if (DevicePath == NULL) {
1224 return EFI_NOT_FOUND;
1225 }
1226 DevicePathSize = GetDevicePathSize (DevicePath);
1227
1228 //
1229 // Loop all boot order variable and find the matching device path
1230 //
1231 Index = 0;
1232 while (Index < BootOrderSize / sizeof (UINT16)) {
1233 UnicodeSPrint (BootOption, sizeof (BootOption), L"Boot%04x", BootOrder[Index]);
1234 BootOptionVar = BdsLibGetVariableAndSize (
1235 BootOption,
1236 &gEfiGlobalVariableGuid,
1237 &BootOptionSize
1238 );
1239
1240 if (BootOptionVar == NULL) {
1241 FreePool (BootOrder);
1242 return EFI_OUT_OF_RESOURCES;
1243 }
1244
1245 TempPtr = BootOptionVar;
1246 TempPtr += sizeof (UINT32) + sizeof (UINT16);
1247 TempPtr += StrSize ((CHAR16 *) TempPtr);
1248 OptionDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) TempPtr;
1249 OptionDevicePathSize = GetDevicePathSize (OptionDevicePath);
1250
1251 //
1252 // Check whether the device path match
1253 //
1254 if ((OptionDevicePathSize == DevicePathSize) &&
1255 (CompareMem (DevicePath, OptionDevicePath, DevicePathSize) == 0)) {
1256 BdsDeleteBootOption (BootOrder[Index], BootOrder, &BootOrderSize);
1257 FreePool (BootOptionVar);
1258 break;
1259 }
1260
1261 FreePool (BootOptionVar);
1262 Index++;
1263 }
1264
1265 //
1266 // Adjust number of boot option for "BootOrder" variable.
1267 //
1268 Status = gRT->SetVariable (
1269 L"BootOrder",
1270 &gEfiGlobalVariableGuid,
1271 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1272 BootOrderSize,
1273 BootOrder
1274 );
1275
1276 FreePool (BootOrder);
1277
1278 return Status;
1279 }
1280
1281
1282 /**
1283 Delete all invalid EFI boot options.
1284
1285 @retval EFI_SUCCESS Delete all invalid boot option success
1286 @retval EFI_NOT_FOUND Variable "BootOrder" is not found
1287 @retval EFI_OUT_OF_RESOURCES Lack of memory resource
1288 @retval Other Error return value from SetVariable()
1289
1290 **/
1291 EFI_STATUS
1292 BdsDeleteAllInvalidEfiBootOption (
1293 VOID
1294 )
1295 {
1296 UINT16 *BootOrder;
1297 UINT8 *BootOptionVar;
1298 UINTN BootOrderSize;
1299 UINTN BootOptionSize;
1300 EFI_STATUS Status;
1301 UINTN Index;
1302 UINTN Index2;
1303 UINT16 BootOption[BOOT_OPTION_MAX_CHAR];
1304 EFI_DEVICE_PATH_PROTOCOL *OptionDevicePath;
1305 UINT8 *TempPtr;
1306 CHAR16 *Description;
1307
1308 Status = EFI_SUCCESS;
1309 BootOrder = NULL;
1310 BootOrderSize = 0;
1311
1312 //
1313 // Check "BootOrder" variable firstly, this variable hold the number of boot options
1314 //
1315 BootOrder = BdsLibGetVariableAndSize (
1316 L"BootOrder",
1317 &gEfiGlobalVariableGuid,
1318 &BootOrderSize
1319 );
1320 if (NULL == BootOrder) {
1321 return EFI_NOT_FOUND;
1322 }
1323
1324 Index = 0;
1325 while (Index < BootOrderSize / sizeof (UINT16)) {
1326 UnicodeSPrint (BootOption, sizeof (BootOption), L"Boot%04x", BootOrder[Index]);
1327 BootOptionVar = BdsLibGetVariableAndSize (
1328 BootOption,
1329 &gEfiGlobalVariableGuid,
1330 &BootOptionSize
1331 );
1332 if (NULL == BootOptionVar) {
1333 FreePool (BootOrder);
1334 return EFI_OUT_OF_RESOURCES;
1335 }
1336
1337 TempPtr = BootOptionVar;
1338 TempPtr += sizeof (UINT32) + sizeof (UINT16);
1339 Description = (CHAR16 *) TempPtr;
1340 TempPtr += StrSize ((CHAR16 *) TempPtr);
1341 OptionDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) TempPtr;
1342
1343 //
1344 // Skip legacy boot option (BBS boot device)
1345 //
1346 if ((DevicePathType (OptionDevicePath) == BBS_DEVICE_PATH) &&
1347 (DevicePathSubType (OptionDevicePath) == BBS_BBS_DP)) {
1348 FreePool (BootOptionVar);
1349 Index++;
1350 continue;
1351 }
1352
1353 if (!BdsLibIsValidEFIBootOptDevicePathExt (OptionDevicePath, FALSE, Description)) {
1354 //
1355 // Delete this invalid boot option "Boot####"
1356 //
1357 Status = gRT->SetVariable (
1358 BootOption,
1359 &gEfiGlobalVariableGuid,
1360 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1361 0,
1362 NULL
1363 );
1364 //
1365 // Mark this boot option in boot order as deleted
1366 //
1367 BootOrder[Index] = 0xffff;
1368 }
1369
1370 FreePool (BootOptionVar);
1371 Index++;
1372 }
1373
1374 //
1375 // Adjust boot order array
1376 //
1377 Index2 = 0;
1378 for (Index = 0; Index < BootOrderSize / sizeof (UINT16); Index++) {
1379 if (BootOrder[Index] != 0xffff) {
1380 BootOrder[Index2] = BootOrder[Index];
1381 Index2 ++;
1382 }
1383 }
1384 Status = gRT->SetVariable (
1385 L"BootOrder",
1386 &gEfiGlobalVariableGuid,
1387 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1388 Index2 * sizeof (UINT16),
1389 BootOrder
1390 );
1391
1392 FreePool (BootOrder);
1393
1394 return Status;
1395 }
1396
1397
1398 /**
1399 For EFI boot option, BDS separate them as six types:
1400 1. Network - The boot option points to the SimpleNetworkProtocol device.
1401 Bds will try to automatically create this type boot option when enumerate.
1402 2. Shell - The boot option points to internal flash shell.
1403 Bds will try to automatically create this type boot option when enumerate.
1404 3. Removable BlockIo - The boot option only points to the removable media
1405 device, like USB flash disk, DVD, Floppy etc.
1406 These device should contain a *removable* blockIo
1407 protocol in their device handle.
1408 Bds will try to automatically create this type boot option
1409 when enumerate.
1410 4. Fixed BlockIo - The boot option only points to a Fixed blockIo device,
1411 like HardDisk.
1412 These device should contain a *fixed* blockIo
1413 protocol in their device handle.
1414 BDS will skip fixed blockIo devices, and NOT
1415 automatically create boot option for them. But BDS
1416 will help to delete those fixed blockIo boot option,
1417 whose description rule conflict with other auto-created
1418 boot options.
1419 5. Non-BlockIo Simplefile - The boot option points to a device whose handle
1420 has SimpleFileSystem Protocol, but has no blockio
1421 protocol. These devices do not offer blockIo
1422 protocol, but BDS still can get the
1423 \EFI\BOOT\boot{machinename}.EFI by SimpleFileSystem
1424 Protocol.
1425 6. File - The boot option points to a file. These boot options are usually
1426 created by user manually or OS loader. BDS will not delete or modify
1427 these boot options.
1428
1429 This function will enumerate all possible boot device in the system, and
1430 automatically create boot options for Network, Shell, Removable BlockIo,
1431 and Non-BlockIo Simplefile devices.
1432 It will only execute once of every boot.
1433
1434 @param BdsBootOptionList The header of the link list which indexed all
1435 current boot options
1436
1437 @retval EFI_SUCCESS Finished all the boot device enumerate and create
1438 the boot option base on that boot device
1439
1440 @retval EFI_OUT_OF_RESOURCES Failed to enumerate the boot device and create the boot option list
1441 **/
1442 EFI_STATUS
1443 EFIAPI
1444 BdsLibEnumerateAllBootOption (
1445 IN OUT LIST_ENTRY *BdsBootOptionList
1446 )
1447 {
1448 EFI_STATUS Status;
1449 UINT16 FloppyNumber;
1450 UINT16 HarddriveNumber;
1451 UINT16 CdromNumber;
1452 UINT16 UsbNumber;
1453 UINT16 MiscNumber;
1454 UINT16 ScsiNumber;
1455 UINT16 NonBlockNumber;
1456 UINTN NumberBlockIoHandles;
1457 EFI_HANDLE *BlockIoHandles;
1458 EFI_BLOCK_IO_PROTOCOL *BlkIo;
1459 BOOLEAN Removable[2];
1460 UINTN RemovableIndex;
1461 UINTN Index;
1462 UINTN NumOfLoadFileHandles;
1463 EFI_HANDLE *LoadFileHandles;
1464 UINTN FvHandleCount;
1465 EFI_HANDLE *FvHandleBuffer;
1466 EFI_FV_FILETYPE Type;
1467 UINTN Size;
1468 EFI_FV_FILE_ATTRIBUTES Attributes;
1469 UINT32 AuthenticationStatus;
1470 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
1471 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1472 UINTN DevicePathType;
1473 CHAR16 Buffer[40];
1474 EFI_HANDLE *FileSystemHandles;
1475 UINTN NumberFileSystemHandles;
1476 BOOLEAN NeedDelete;
1477 EFI_IMAGE_DOS_HEADER DosHeader;
1478 CHAR8 *PlatLang;
1479 CHAR8 *LastLang;
1480 EFI_IMAGE_OPTIONAL_HEADER_UNION HdrData;
1481 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
1482
1483 FloppyNumber = 0;
1484 HarddriveNumber = 0;
1485 CdromNumber = 0;
1486 UsbNumber = 0;
1487 MiscNumber = 0;
1488 ScsiNumber = 0;
1489 PlatLang = NULL;
1490 LastLang = NULL;
1491 ZeroMem (Buffer, sizeof (Buffer));
1492
1493 //
1494 // If the boot device enumerate happened, just get the boot
1495 // device from the boot order variable
1496 //
1497 if (mEnumBootDevice) {
1498 LastLang = GetVariable (L"LastEnumLang", &mBdsLibLastLangGuid);
1499 PlatLang = GetEfiGlobalVariable (L"PlatformLang");
1500 ASSERT (PlatLang != NULL);
1501 if ((LastLang != NULL) && (AsciiStrCmp (LastLang, PlatLang) == 0)) {
1502 Status = BdsLibBuildOptionFromVar (BdsBootOptionList, L"BootOrder");
1503 FreePool (LastLang);
1504 FreePool (PlatLang);
1505 return Status;
1506 } else {
1507 Status = gRT->SetVariable (
1508 L"LastEnumLang",
1509 &mBdsLibLastLangGuid,
1510 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1511 AsciiStrSize (PlatLang),
1512 PlatLang
1513 );
1514 ASSERT_EFI_ERROR (Status);
1515
1516 if (LastLang != NULL) {
1517 FreePool (LastLang);
1518 }
1519 FreePool (PlatLang);
1520 }
1521 }
1522
1523 //
1524 // Notes: this dirty code is to get the legacy boot option from the
1525 // BBS table and create to variable as the EFI boot option, it should
1526 // be removed after the CSM can provide legacy boot option directly
1527 //
1528 REFRESH_LEGACY_BOOT_OPTIONS;
1529
1530 //
1531 // Delete invalid boot option
1532 //
1533 BdsDeleteAllInvalidEfiBootOption ();
1534
1535 //
1536 // Parse removable media followed by fixed media.
1537 // The Removable[] array is used by the for-loop below to create removable media boot options
1538 // at first, and then to create fixed media boot options.
1539 //
1540 Removable[0] = FALSE;
1541 Removable[1] = TRUE;
1542
1543 gBS->LocateHandleBuffer (
1544 ByProtocol,
1545 &gEfiBlockIoProtocolGuid,
1546 NULL,
1547 &NumberBlockIoHandles,
1548 &BlockIoHandles
1549 );
1550
1551 for (RemovableIndex = 0; RemovableIndex < 2; RemovableIndex++) {
1552 for (Index = 0; Index < NumberBlockIoHandles; Index++) {
1553 Status = gBS->HandleProtocol (
1554 BlockIoHandles[Index],
1555 &gEfiBlockIoProtocolGuid,
1556 (VOID **) &BlkIo
1557 );
1558 //
1559 // skip the fixed block io then the removable block io
1560 //
1561 if (EFI_ERROR (Status) || (BlkIo->Media->RemovableMedia == Removable[RemovableIndex])) {
1562 continue;
1563 }
1564 DevicePath = DevicePathFromHandle (BlockIoHandles[Index]);
1565 DevicePathType = BdsGetBootTypeFromDevicePath (DevicePath);
1566
1567 switch (DevicePathType) {
1568 case BDS_EFI_ACPI_FLOPPY_BOOT:
1569 if (FloppyNumber != 0) {
1570 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_FLOPPY)), FloppyNumber);
1571 } else {
1572 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_FLOPPY)));
1573 }
1574 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1575 FloppyNumber++;
1576 break;
1577
1578 //
1579 // Assume a removable SATA device should be the DVD/CD device, a fixed SATA device should be the Hard Drive device.
1580 //
1581 case BDS_EFI_MESSAGE_ATAPI_BOOT:
1582 case BDS_EFI_MESSAGE_SATA_BOOT:
1583 if (BlkIo->Media->RemovableMedia) {
1584 if (CdromNumber != 0) {
1585 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_CD_DVD)), CdromNumber);
1586 } else {
1587 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_CD_DVD)));
1588 }
1589 CdromNumber++;
1590 } else {
1591 if (HarddriveNumber != 0) {
1592 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_HARDDRIVE)), HarddriveNumber);
1593 } else {
1594 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_HARDDRIVE)));
1595 }
1596 HarddriveNumber++;
1597 }
1598 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Buffer: %S\n", Buffer));
1599 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1600 break;
1601
1602 case BDS_EFI_MESSAGE_USB_DEVICE_BOOT:
1603 if (UsbNumber != 0) {
1604 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_USB)), UsbNumber);
1605 } else {
1606 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_USB)));
1607 }
1608 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1609 UsbNumber++;
1610 break;
1611
1612 case BDS_EFI_MESSAGE_SCSI_BOOT:
1613 if (ScsiNumber != 0) {
1614 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_SCSI)), ScsiNumber);
1615 } else {
1616 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_SCSI)));
1617 }
1618 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1619 ScsiNumber++;
1620 break;
1621
1622 case BDS_EFI_MESSAGE_MISC_BOOT:
1623 if (MiscNumber != 0) {
1624 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_MISC)), MiscNumber);
1625 } else {
1626 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_MISC)));
1627 }
1628 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1629 MiscNumber++;
1630 break;
1631
1632 default:
1633 break;
1634 }
1635 }
1636 }
1637
1638 if (NumberBlockIoHandles != 0) {
1639 FreePool (BlockIoHandles);
1640 }
1641
1642 //
1643 // If there is simple file protocol which does not consume block Io protocol, create a boot option for it here.
1644 //
1645 NonBlockNumber = 0;
1646 gBS->LocateHandleBuffer (
1647 ByProtocol,
1648 &gEfiSimpleFileSystemProtocolGuid,
1649 NULL,
1650 &NumberFileSystemHandles,
1651 &FileSystemHandles
1652 );
1653 for (Index = 0; Index < NumberFileSystemHandles; Index++) {
1654 Status = gBS->HandleProtocol (
1655 FileSystemHandles[Index],
1656 &gEfiBlockIoProtocolGuid,
1657 (VOID **) &BlkIo
1658 );
1659 if (!EFI_ERROR (Status)) {
1660 //
1661 // Skip if the file system handle supports a BlkIo protocol,
1662 //
1663 continue;
1664 }
1665
1666 //
1667 // Do the removable Media thing. \EFI\BOOT\boot{machinename}.EFI
1668 // machinename is ia32, ia64, x64, ...
1669 //
1670 Hdr.Union = &HdrData;
1671 NeedDelete = TRUE;
1672 Status = BdsLibGetImageHeader (
1673 FileSystemHandles[Index],
1674 EFI_REMOVABLE_MEDIA_FILE_NAME,
1675 &DosHeader,
1676 Hdr
1677 );
1678 if (!EFI_ERROR (Status) &&
1679 EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Hdr.Pe32->FileHeader.Machine) &&
1680 Hdr.Pe32->OptionalHeader.Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {
1681 NeedDelete = FALSE;
1682 }
1683
1684 if (NeedDelete) {
1685 //
1686 // No such file or the file is not a EFI application, delete this boot option
1687 //
1688 BdsLibDeleteOptionFromHandle (FileSystemHandles[Index]);
1689 } else {
1690 if (NonBlockNumber != 0) {
1691 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_NON_BLOCK)), NonBlockNumber);
1692 } else {
1693 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_NON_BLOCK)));
1694 }
1695 BdsLibBuildOptionFromHandle (FileSystemHandles[Index], BdsBootOptionList, Buffer);
1696 NonBlockNumber++;
1697 }
1698 }
1699
1700 if (NumberFileSystemHandles != 0) {
1701 FreePool (FileSystemHandles);
1702 }
1703
1704 //
1705 // Parse Network Boot Device
1706 //
1707 NumOfLoadFileHandles = 0;
1708 //
1709 // Search Load File protocol for PXE boot option.
1710 //
1711 gBS->LocateHandleBuffer (
1712 ByProtocol,
1713 &gEfiLoadFileProtocolGuid,
1714 NULL,
1715 &NumOfLoadFileHandles,
1716 &LoadFileHandles
1717 );
1718
1719 for (Index = 0; Index < NumOfLoadFileHandles; Index++) {
1720 if (Index != 0) {
1721 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_NETWORK)), Index);
1722 } else {
1723 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_NETWORK)));
1724 }
1725 BdsLibBuildOptionFromHandle (LoadFileHandles[Index], BdsBootOptionList, Buffer);
1726 }
1727
1728 if (NumOfLoadFileHandles != 0) {
1729 FreePool (LoadFileHandles);
1730 }
1731
1732 //
1733 // Check if we have on flash shell
1734 //
1735 gBS->LocateHandleBuffer (
1736 ByProtocol,
1737 &gEfiFirmwareVolume2ProtocolGuid,
1738 NULL,
1739 &FvHandleCount,
1740 &FvHandleBuffer
1741 );
1742 for (Index = 0; Index < FvHandleCount; Index++) {
1743 gBS->HandleProtocol (
1744 FvHandleBuffer[Index],
1745 &gEfiFirmwareVolume2ProtocolGuid,
1746 (VOID **) &Fv
1747 );
1748
1749 Status = Fv->ReadFile (
1750 Fv,
1751 PcdGetPtr(PcdShellFile),
1752 NULL,
1753 &Size,
1754 &Type,
1755 &Attributes,
1756 &AuthenticationStatus
1757 );
1758 if (EFI_ERROR (Status)) {
1759 //
1760 // Skip if no shell file in the FV
1761 //
1762 continue;
1763 }
1764 //
1765 // Build the shell boot option
1766 //
1767 BdsLibBuildOptionFromShell (FvHandleBuffer[Index], BdsBootOptionList);
1768 }
1769
1770 if (FvHandleCount != 0) {
1771 FreePool (FvHandleBuffer);
1772 }
1773 //
1774 // Make sure every boot only have one time
1775 // boot device enumerate
1776 //
1777 Status = BdsLibBuildOptionFromVar (BdsBootOptionList, L"BootOrder");
1778 mEnumBootDevice = TRUE;
1779
1780 return Status;
1781 }
1782
1783 /**
1784 Build the boot option with the handle parsed in
1785
1786 @param Handle The handle which present the device path to create
1787 boot option
1788 @param BdsBootOptionList The header of the link list which indexed all
1789 current boot options
1790 @param String The description of the boot option.
1791
1792 **/
1793 VOID
1794 EFIAPI
1795 BdsLibBuildOptionFromHandle (
1796 IN EFI_HANDLE Handle,
1797 IN LIST_ENTRY *BdsBootOptionList,
1798 IN CHAR16 *String
1799 )
1800 {
1801 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1802
1803 DevicePath = DevicePathFromHandle (Handle);
1804
1805 //
1806 // Create and register new boot option
1807 //
1808 BdsLibRegisterNewOption (BdsBootOptionList, DevicePath, String, L"BootOrder");
1809 }
1810
1811
1812 /**
1813 Build the on flash shell boot option with the handle parsed in.
1814
1815 @param Handle The handle which present the device path to create
1816 on flash shell boot option
1817 @param BdsBootOptionList The header of the link list which indexed all
1818 current boot options
1819
1820 **/
1821 VOID
1822 EFIAPI
1823 BdsLibBuildOptionFromShell (
1824 IN EFI_HANDLE Handle,
1825 IN OUT LIST_ENTRY *BdsBootOptionList
1826 )
1827 {
1828 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1829 MEDIA_FW_VOL_FILEPATH_DEVICE_PATH ShellNode;
1830
1831 DevicePath = DevicePathFromHandle (Handle);
1832
1833 //
1834 // Build the shell device path
1835 //
1836 EfiInitializeFwVolDevicepathNode (&ShellNode, PcdGetPtr(PcdShellFile));
1837
1838 DevicePath = AppendDevicePathNode (DevicePath, (EFI_DEVICE_PATH_PROTOCOL *) &ShellNode);
1839
1840 //
1841 // Create and register the shell boot option
1842 //
1843 BdsLibRegisterNewOption (BdsBootOptionList, DevicePath, L"EFI Internal Shell", L"BootOrder");
1844
1845 }
1846
1847 /**
1848 Boot from the UEFI spec defined "BootNext" variable.
1849
1850 **/
1851 VOID
1852 EFIAPI
1853 BdsLibBootNext (
1854 VOID
1855 )
1856 {
1857 UINT16 *BootNext;
1858 UINTN BootNextSize;
1859 CHAR16 Buffer[20];
1860 BDS_COMMON_OPTION *BootOption;
1861 LIST_ENTRY TempList;
1862 UINTN ExitDataSize;
1863 CHAR16 *ExitData;
1864
1865 //
1866 // Init the boot option name buffer and temp link list
1867 //
1868 InitializeListHead (&TempList);
1869 ZeroMem (Buffer, sizeof (Buffer));
1870
1871 BootNext = BdsLibGetVariableAndSize (
1872 L"BootNext",
1873 &gEfiGlobalVariableGuid,
1874 &BootNextSize
1875 );
1876
1877 //
1878 // Clear the boot next variable first
1879 //
1880 if (BootNext != NULL) {
1881 gRT->SetVariable (
1882 L"BootNext",
1883 &gEfiGlobalVariableGuid,
1884 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1885 0,
1886 BootNext
1887 );
1888
1889 //
1890 // Start to build the boot option and try to boot
1891 //
1892 UnicodeSPrint (Buffer, sizeof (Buffer), L"Boot%04x", *BootNext);
1893 BootOption = BdsLibVariableToOption (&TempList, Buffer);
1894 ASSERT (BootOption != NULL);
1895 BdsLibConnectDevicePath (BootOption->DevicePath);
1896 BdsLibBootViaBootOption (BootOption, BootOption->DevicePath, &ExitDataSize, &ExitData);
1897 }
1898
1899 }
1900
1901 /**
1902 Return the bootable media handle.
1903 First, check the device is connected
1904 Second, check whether the device path point to a device which support SimpleFileSystemProtocol,
1905 Third, detect the the default boot file in the Media, and return the removable Media handle.
1906
1907 @param DevicePath Device Path to a bootable device
1908
1909 @return The bootable media handle. If the media on the DevicePath is not bootable, NULL will return.
1910
1911 **/
1912 EFI_HANDLE
1913 EFIAPI
1914 BdsLibGetBootableHandle (
1915 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
1916 )
1917 {
1918 EFI_STATUS Status;
1919 EFI_TPL OldTpl;
1920 EFI_DEVICE_PATH_PROTOCOL *UpdatedDevicePath;
1921 EFI_DEVICE_PATH_PROTOCOL *DupDevicePath;
1922 EFI_HANDLE Handle;
1923 EFI_BLOCK_IO_PROTOCOL *BlockIo;
1924 VOID *Buffer;
1925 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
1926 UINTN Size;
1927 UINTN TempSize;
1928 EFI_HANDLE ReturnHandle;
1929 EFI_HANDLE *SimpleFileSystemHandles;
1930
1931 UINTN NumberSimpleFileSystemHandles;
1932 UINTN Index;
1933 EFI_IMAGE_DOS_HEADER DosHeader;
1934 EFI_IMAGE_OPTIONAL_HEADER_UNION HdrData;
1935 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
1936
1937 UpdatedDevicePath = DevicePath;
1938
1939 //
1940 // Enter to critical section to protect the acquired BlockIo instance
1941 // from getting released due to the USB mass storage hotplug event
1942 //
1943 OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
1944
1945 //
1946 // Check whether the device is connected
1947 //
1948 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &UpdatedDevicePath, &Handle);
1949 if (EFI_ERROR (Status)) {
1950 //
1951 // Skip the case that the boot option point to a simple file protocol which does not consume block Io protocol,
1952 //
1953 Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &UpdatedDevicePath, &Handle);
1954 if (EFI_ERROR (Status)) {
1955 //
1956 // Fail to find the proper BlockIo and simple file protocol, maybe because device not present, we need to connect it firstly
1957 //
1958 UpdatedDevicePath = DevicePath;
1959 Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &UpdatedDevicePath, &Handle);
1960 gBS->ConnectController (Handle, NULL, NULL, TRUE);
1961 }
1962 } else {
1963 //
1964 // For removable device boot option, its contained device path only point to the removable device handle,
1965 // should make sure all its children handles (its child partion or media handles) are created and connected.
1966 //
1967 gBS->ConnectController (Handle, NULL, NULL, TRUE);
1968 //
1969 // Get BlockIo protocol and check removable attribute
1970 //
1971 Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo);
1972 ASSERT_EFI_ERROR (Status);
1973
1974 //
1975 // Issue a dummy read to the device to check for media change.
1976 // When the removable media is changed, any Block IO read/write will
1977 // cause the BlockIo protocol be reinstalled and EFI_MEDIA_CHANGED is
1978 // returned. After the Block IO protocol is reinstalled, subsequent
1979 // Block IO read/write will success.
1980 //
1981 Buffer = AllocatePool (BlockIo->Media->BlockSize);
1982 if (Buffer != NULL) {
1983 BlockIo->ReadBlocks (
1984 BlockIo,
1985 BlockIo->Media->MediaId,
1986 0,
1987 BlockIo->Media->BlockSize,
1988 Buffer
1989 );
1990 FreePool(Buffer);
1991 }
1992 }
1993
1994 //
1995 // Detect the the default boot file from removable Media
1996 //
1997
1998 //
1999 // 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
2000 // Try to locate the USB node device path first, if fail then use its previous PCI node to search
2001 //
2002 DupDevicePath = DuplicateDevicePath (DevicePath);
2003 ASSERT (DupDevicePath != NULL);
2004
2005 UpdatedDevicePath = DupDevicePath;
2006 Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &UpdatedDevicePath, &Handle);
2007 //
2008 // 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
2009 // Acpi()/Pci()/Usb() --> Acpi()/Pci()
2010 //
2011 if ((DevicePathType (UpdatedDevicePath) == MESSAGING_DEVICE_PATH) &&
2012 (DevicePathSubType (UpdatedDevicePath) == MSG_USB_DP)) {
2013 //
2014 // Remove the usb node, let the device path only point to PCI node
2015 //
2016 SetDevicePathEndNode (UpdatedDevicePath);
2017 UpdatedDevicePath = DupDevicePath;
2018 } else {
2019 UpdatedDevicePath = DevicePath;
2020 }
2021
2022 //
2023 // Get the device path size of boot option
2024 //
2025 Size = GetDevicePathSize(UpdatedDevicePath) - sizeof (EFI_DEVICE_PATH_PROTOCOL); // minus the end node
2026 ReturnHandle = NULL;
2027 gBS->LocateHandleBuffer (
2028 ByProtocol,
2029 &gEfiSimpleFileSystemProtocolGuid,
2030 NULL,
2031 &NumberSimpleFileSystemHandles,
2032 &SimpleFileSystemHandles
2033 );
2034 for (Index = 0; Index < NumberSimpleFileSystemHandles; Index++) {
2035 //
2036 // Get the device path size of SimpleFileSystem handle
2037 //
2038 TempDevicePath = DevicePathFromHandle (SimpleFileSystemHandles[Index]);
2039 TempSize = GetDevicePathSize (TempDevicePath)- sizeof (EFI_DEVICE_PATH_PROTOCOL); // minus the end node
2040 //
2041 // Check whether the device path of boot option is part of the SimpleFileSystem handle's device path
2042 //
2043 if (Size <= TempSize && CompareMem (TempDevicePath, UpdatedDevicePath, Size)==0) {
2044 //
2045 // Load the default boot file \EFI\BOOT\boot{machinename}.EFI from removable Media
2046 // machinename is ia32, ia64, x64, ...
2047 //
2048 Hdr.Union = &HdrData;
2049 Status = BdsLibGetImageHeader (
2050 SimpleFileSystemHandles[Index],
2051 EFI_REMOVABLE_MEDIA_FILE_NAME,
2052 &DosHeader,
2053 Hdr
2054 );
2055 if (!EFI_ERROR (Status) &&
2056 EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Hdr.Pe32->FileHeader.Machine) &&
2057 Hdr.Pe32->OptionalHeader.Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {
2058 ReturnHandle = SimpleFileSystemHandles[Index];
2059 break;
2060 }
2061 }
2062 }
2063
2064 FreePool(DupDevicePath);
2065
2066 if (SimpleFileSystemHandles != NULL) {
2067 FreePool(SimpleFileSystemHandles);
2068 }
2069
2070 gBS->RestoreTPL (OldTpl);
2071
2072 return ReturnHandle;
2073 }
2074
2075 /**
2076 Check to see if the network cable is plugged in. If the DevicePath is not
2077 connected it will be connected.
2078
2079 @param DevicePath Device Path to check
2080
2081 @retval TRUE DevicePath points to an Network that is connected
2082 @retval FALSE DevicePath does not point to a bootable network
2083
2084 **/
2085 BOOLEAN
2086 BdsLibNetworkBootWithMediaPresent (
2087 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
2088 )
2089 {
2090 EFI_STATUS Status;
2091 EFI_DEVICE_PATH_PROTOCOL *UpdatedDevicePath;
2092 EFI_HANDLE Handle;
2093 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
2094 BOOLEAN MediaPresent;
2095 UINT32 InterruptStatus;
2096
2097 MediaPresent = FALSE;
2098
2099 UpdatedDevicePath = DevicePath;
2100 //
2101 // Locate Load File Protocol for PXE boot option first
2102 //
2103 Status = gBS->LocateDevicePath (&gEfiLoadFileProtocolGuid, &UpdatedDevicePath, &Handle);
2104 if (EFI_ERROR (Status)) {
2105 //
2106 // Device not present so see if we need to connect it
2107 //
2108 Status = BdsLibConnectDevicePath (DevicePath);
2109 if (!EFI_ERROR (Status)) {
2110 //
2111 // This one should work after we did the connect
2112 //
2113 Status = gBS->LocateDevicePath (&gEfiLoadFileProtocolGuid, &UpdatedDevicePath, &Handle);
2114 }
2115 }
2116
2117 if (!EFI_ERROR (Status)) {
2118 Status = gBS->HandleProtocol (Handle, &gEfiSimpleNetworkProtocolGuid, (VOID **)&Snp);
2119 if (EFI_ERROR (Status)) {
2120 //
2121 // Failed to open SNP from this handle, try to get SNP from parent handle
2122 //
2123 UpdatedDevicePath = DevicePathFromHandle (Handle);
2124 if (UpdatedDevicePath != NULL) {
2125 Status = gBS->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid, &UpdatedDevicePath, &Handle);
2126 if (!EFI_ERROR (Status)) {
2127 //
2128 // SNP handle found, get SNP from it
2129 //
2130 Status = gBS->HandleProtocol (Handle, &gEfiSimpleNetworkProtocolGuid, (VOID **) &Snp);
2131 }
2132 }
2133 }
2134
2135 if (!EFI_ERROR (Status)) {
2136 if (Snp->Mode->MediaPresentSupported) {
2137 if (Snp->Mode->State == EfiSimpleNetworkInitialized) {
2138 //
2139 // Invoke Snp->GetStatus() to refresh the media status
2140 //
2141 Snp->GetStatus (Snp, &InterruptStatus, NULL);
2142
2143 //
2144 // In case some one else is using the SNP check to see if it's connected
2145 //
2146 MediaPresent = Snp->Mode->MediaPresent;
2147 } else {
2148 //
2149 // No one is using SNP so we need to Start and Initialize so
2150 // MediaPresent will be valid.
2151 //
2152 Status = Snp->Start (Snp);
2153 if (!EFI_ERROR (Status)) {
2154 Status = Snp->Initialize (Snp, 0, 0);
2155 if (!EFI_ERROR (Status)) {
2156 MediaPresent = Snp->Mode->MediaPresent;
2157 Snp->Shutdown (Snp);
2158 }
2159 Snp->Stop (Snp);
2160 }
2161 }
2162 } else {
2163 MediaPresent = TRUE;
2164 }
2165 }
2166 }
2167
2168 return MediaPresent;
2169 }
2170
2171 /**
2172 For a bootable Device path, return its boot type.
2173
2174 @param DevicePath The bootable device Path to check
2175
2176 @retval BDS_EFI_MEDIA_HD_BOOT If given device path contains MEDIA_DEVICE_PATH type device path node
2177 which subtype is MEDIA_HARDDRIVE_DP
2178 @retval BDS_EFI_MEDIA_CDROM_BOOT If given device path contains MEDIA_DEVICE_PATH type device path node
2179 which subtype is MEDIA_CDROM_DP
2180 @retval BDS_EFI_ACPI_FLOPPY_BOOT If given device path contains ACPI_DEVICE_PATH type device path node
2181 which HID is floppy device.
2182 @retval BDS_EFI_MESSAGE_ATAPI_BOOT If given device path contains MESSAGING_DEVICE_PATH type device path node
2183 and its last device path node's subtype is MSG_ATAPI_DP.
2184 @retval BDS_EFI_MESSAGE_SCSI_BOOT If given device path contains MESSAGING_DEVICE_PATH type device path node
2185 and its last device path node's subtype is MSG_SCSI_DP.
2186 @retval BDS_EFI_MESSAGE_USB_DEVICE_BOOT If given device path contains MESSAGING_DEVICE_PATH type device path node
2187 and its last device path node's subtype is MSG_USB_DP.
2188 @retval BDS_EFI_MESSAGE_MISC_BOOT If the device path not contains any media device path node, and
2189 its last device path node point to a message device path node.
2190 @retval BDS_LEGACY_BBS_BOOT If given device path contains BBS_DEVICE_PATH type device path node.
2191 @retval BDS_EFI_UNSUPPORT An EFI Removable BlockIO device path not point to a media and message device,
2192
2193 **/
2194 UINT32
2195 EFIAPI
2196 BdsGetBootTypeFromDevicePath (
2197 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
2198 )
2199 {
2200 ACPI_HID_DEVICE_PATH *Acpi;
2201 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
2202 EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
2203 UINT32 BootType;
2204
2205 if (NULL == DevicePath) {
2206 return BDS_EFI_UNSUPPORT;
2207 }
2208
2209 TempDevicePath = DevicePath;
2210
2211 while (!IsDevicePathEndType (TempDevicePath)) {
2212 switch (DevicePathType (TempDevicePath)) {
2213 case BBS_DEVICE_PATH:
2214 return BDS_LEGACY_BBS_BOOT;
2215 case MEDIA_DEVICE_PATH:
2216 if (DevicePathSubType (TempDevicePath) == MEDIA_HARDDRIVE_DP) {
2217 return BDS_EFI_MEDIA_HD_BOOT;
2218 } else if (DevicePathSubType (TempDevicePath) == MEDIA_CDROM_DP) {
2219 return BDS_EFI_MEDIA_CDROM_BOOT;
2220 }
2221 break;
2222 case ACPI_DEVICE_PATH:
2223 Acpi = (ACPI_HID_DEVICE_PATH *) TempDevicePath;
2224 if (EISA_ID_TO_NUM (Acpi->HID) == 0x0604) {
2225 return BDS_EFI_ACPI_FLOPPY_BOOT;
2226 }
2227 break;
2228 case MESSAGING_DEVICE_PATH:
2229 //
2230 // Get the last device path node
2231 //
2232 LastDeviceNode = NextDevicePathNode (TempDevicePath);
2233 if (DevicePathSubType(LastDeviceNode) == MSG_DEVICE_LOGICAL_UNIT_DP) {
2234 //
2235 // if the next node type is Device Logical Unit, which specify the Logical Unit Number (LUN),
2236 // skip it
2237 //
2238 LastDeviceNode = NextDevicePathNode (LastDeviceNode);
2239 }
2240 //
2241 // if the device path not only point to driver device, it is not a messaging device path,
2242 //
2243 if (!IsDevicePathEndType (LastDeviceNode)) {
2244 break;
2245 }
2246
2247 switch (DevicePathSubType (TempDevicePath)) {
2248 case MSG_ATAPI_DP:
2249 BootType = BDS_EFI_MESSAGE_ATAPI_BOOT;
2250 break;
2251
2252 case MSG_USB_DP:
2253 BootType = BDS_EFI_MESSAGE_USB_DEVICE_BOOT;
2254 break;
2255
2256 case MSG_SCSI_DP:
2257 BootType = BDS_EFI_MESSAGE_SCSI_BOOT;
2258 break;
2259
2260 case MSG_SATA_DP:
2261 BootType = BDS_EFI_MESSAGE_SATA_BOOT;
2262 break;
2263
2264 case MSG_MAC_ADDR_DP:
2265 case MSG_VLAN_DP:
2266 case MSG_IPv4_DP:
2267 case MSG_IPv6_DP:
2268 BootType = BDS_EFI_MESSAGE_MAC_BOOT;
2269 break;
2270
2271 default:
2272 BootType = BDS_EFI_MESSAGE_MISC_BOOT;
2273 break;
2274 }
2275 return BootType;
2276
2277 default:
2278 break;
2279 }
2280 TempDevicePath = NextDevicePathNode (TempDevicePath);
2281 }
2282
2283 return BDS_EFI_UNSUPPORT;
2284 }
2285
2286 /**
2287 Check whether the Device path in a boot option point to a valid bootable device,
2288 And if CheckMedia is true, check the device is ready to boot now.
2289
2290 @param DevPath the Device path in a boot option
2291 @param CheckMedia if true, check the device is ready to boot now.
2292
2293 @retval TRUE the Device path is valid
2294 @retval FALSE the Device path is invalid .
2295
2296 **/
2297 BOOLEAN
2298 EFIAPI
2299 BdsLibIsValidEFIBootOptDevicePath (
2300 IN EFI_DEVICE_PATH_PROTOCOL *DevPath,
2301 IN BOOLEAN CheckMedia
2302 )
2303 {
2304 return BdsLibIsValidEFIBootOptDevicePathExt (DevPath, CheckMedia, NULL);
2305 }
2306
2307 /**
2308 Check whether the Device path in a boot option point to a valid bootable device,
2309 And if CheckMedia is true, check the device is ready to boot now.
2310 If Description is not NULL and the device path point to a fixed BlockIo
2311 device, check the description whether conflict with other auto-created
2312 boot options.
2313
2314 @param DevPath the Device path in a boot option
2315 @param CheckMedia if true, check the device is ready to boot now.
2316 @param Description the description in a boot option
2317
2318 @retval TRUE the Device path is valid
2319 @retval FALSE the Device path is invalid .
2320
2321 **/
2322 BOOLEAN
2323 EFIAPI
2324 BdsLibIsValidEFIBootOptDevicePathExt (
2325 IN EFI_DEVICE_PATH_PROTOCOL *DevPath,
2326 IN BOOLEAN CheckMedia,
2327 IN CHAR16 *Description
2328 )
2329 {
2330 EFI_STATUS Status;
2331 EFI_HANDLE Handle;
2332 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
2333 EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
2334 EFI_BLOCK_IO_PROTOCOL *BlockIo;
2335
2336 TempDevicePath = DevPath;
2337 LastDeviceNode = DevPath;
2338
2339 //
2340 // Check if it's a valid boot option for network boot device.
2341 // Check if there is EfiLoadFileProtocol installed.
2342 // If yes, that means there is a boot option for network.
2343 //
2344 Status = gBS->LocateDevicePath (
2345 &gEfiLoadFileProtocolGuid,
2346 &TempDevicePath,
2347 &Handle
2348 );
2349 if (EFI_ERROR (Status)) {
2350 //
2351 // Device not present so see if we need to connect it
2352 //
2353 TempDevicePath = DevPath;
2354 BdsLibConnectDevicePath (TempDevicePath);
2355 Status = gBS->LocateDevicePath (
2356 &gEfiLoadFileProtocolGuid,
2357 &TempDevicePath,
2358 &Handle
2359 );
2360 }
2361
2362 if (!EFI_ERROR (Status)) {
2363 if (!IsDevicePathEnd (TempDevicePath)) {
2364 //
2365 // LoadFile protocol is not installed on handle with exactly the same DevPath
2366 //
2367 return FALSE;
2368 }
2369
2370 if (CheckMedia) {
2371 //
2372 // Test if it is ready to boot now
2373 //
2374 if (BdsLibNetworkBootWithMediaPresent(DevPath)) {
2375 return TRUE;
2376 }
2377 } else {
2378 return TRUE;
2379 }
2380 }
2381
2382 //
2383 // If the boot option point to a file, it is a valid EFI boot option,
2384 // and assume it is ready to boot now
2385 //
2386 while (!IsDevicePathEnd (TempDevicePath)) {
2387 //
2388 // If there is USB Class or USB WWID device path node, treat it as valid EFI
2389 // Boot Option. BdsExpandUsbShortFormDevicePath () will be used to expand it
2390 // to full device path.
2391 //
2392 if ((DevicePathType (TempDevicePath) == MESSAGING_DEVICE_PATH) &&
2393 ((DevicePathSubType (TempDevicePath) == MSG_USB_CLASS_DP) ||
2394 (DevicePathSubType (TempDevicePath) == MSG_USB_WWID_DP))) {
2395 return TRUE;
2396 }
2397
2398 LastDeviceNode = TempDevicePath;
2399 TempDevicePath = NextDevicePathNode (TempDevicePath);
2400 }
2401 if ((DevicePathType (LastDeviceNode) == MEDIA_DEVICE_PATH) &&
2402 (DevicePathSubType (LastDeviceNode) == MEDIA_FILEPATH_DP)) {
2403 return TRUE;
2404 }
2405
2406 //
2407 // Check if it's a valid boot option for internal FV application
2408 //
2409 if (EfiGetNameGuidFromFwVolDevicePathNode ((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LastDeviceNode) != NULL) {
2410 //
2411 // If the boot option point to internal FV application, make sure it is valid
2412 //
2413 TempDevicePath = DevPath;
2414 Status = BdsLibUpdateFvFileDevicePath (
2415 &TempDevicePath,
2416 EfiGetNameGuidFromFwVolDevicePathNode ((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LastDeviceNode)
2417 );
2418 if (Status == EFI_ALREADY_STARTED) {
2419 return TRUE;
2420 } else {
2421 if (Status == EFI_SUCCESS) {
2422 FreePool (TempDevicePath);
2423 }
2424 return FALSE;
2425 }
2426 }
2427
2428 //
2429 // If the boot option point to a blockIO device:
2430 // if it is a removable blockIo device, it is valid.
2431 // if it is a fixed blockIo device, check its description confliction.
2432 //
2433 TempDevicePath = DevPath;
2434 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &TempDevicePath, &Handle);
2435 if (EFI_ERROR (Status)) {
2436 //
2437 // Device not present so see if we need to connect it
2438 //
2439 Status = BdsLibConnectDevicePath (DevPath);
2440 if (!EFI_ERROR (Status)) {
2441 //
2442 // Try again to get the Block Io protocol after we did the connect
2443 //
2444 TempDevicePath = DevPath;
2445 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &TempDevicePath, &Handle);
2446 }
2447 }
2448
2449 if (!EFI_ERROR (Status)) {
2450 Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo);
2451 if (!EFI_ERROR (Status)) {
2452 if (CheckMedia) {
2453 //
2454 // Test if it is ready to boot now
2455 //
2456 if (BdsLibGetBootableHandle (DevPath) != NULL) {
2457 return TRUE;
2458 }
2459 } else {
2460 return TRUE;
2461 }
2462 }
2463 } else {
2464 //
2465 // 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,
2466 //
2467 Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &TempDevicePath, &Handle);
2468 if (!EFI_ERROR (Status)) {
2469 if (CheckMedia) {
2470 //
2471 // Test if it is ready to boot now
2472 //
2473 if (BdsLibGetBootableHandle (DevPath) != NULL) {
2474 return TRUE;
2475 }
2476 } else {
2477 return TRUE;
2478 }
2479 }
2480 }
2481
2482 return FALSE;
2483 }
2484
2485
2486 /**
2487 According to a file guild, check a Fv file device path is valid. If it is invalid,
2488 try to return the valid device path.
2489 FV address maybe changes for memory layout adjust from time to time, use this function
2490 could promise the Fv file device path is right.
2491
2492 @param DevicePath on input, the Fv file device path need to check on
2493 output, the updated valid Fv file device path
2494 @param FileGuid the Fv file guild
2495
2496 @retval EFI_INVALID_PARAMETER the input DevicePath or FileGuid is invalid
2497 parameter
2498 @retval EFI_UNSUPPORTED the input DevicePath does not contain Fv file
2499 guild at all
2500 @retval EFI_ALREADY_STARTED the input DevicePath has pointed to Fv file, it is
2501 valid
2502 @retval EFI_SUCCESS has successfully updated the invalid DevicePath,
2503 and return the updated device path in DevicePath
2504
2505 **/
2506 EFI_STATUS
2507 EFIAPI
2508 BdsLibUpdateFvFileDevicePath (
2509 IN OUT EFI_DEVICE_PATH_PROTOCOL ** DevicePath,
2510 IN EFI_GUID *FileGuid
2511 )
2512 {
2513 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
2514 EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
2515 EFI_STATUS Status;
2516 EFI_GUID *GuidPoint;
2517 UINTN Index;
2518 UINTN FvHandleCount;
2519 EFI_HANDLE *FvHandleBuffer;
2520 EFI_FV_FILETYPE Type;
2521 UINTN Size;
2522 EFI_FV_FILE_ATTRIBUTES Attributes;
2523 UINT32 AuthenticationStatus;
2524 BOOLEAN FindFvFile;
2525 EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
2526 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
2527 MEDIA_FW_VOL_FILEPATH_DEVICE_PATH FvFileNode;
2528 EFI_HANDLE FoundFvHandle;
2529 EFI_DEVICE_PATH_PROTOCOL *NewDevicePath;
2530
2531 if ((DevicePath == NULL) || (*DevicePath == NULL)) {
2532 return EFI_INVALID_PARAMETER;
2533 }
2534 if (FileGuid == NULL) {
2535 return EFI_INVALID_PARAMETER;
2536 }
2537
2538 //
2539 // Check whether the device path point to the default the input Fv file
2540 //
2541 TempDevicePath = *DevicePath;
2542 LastDeviceNode = TempDevicePath;
2543 while (!IsDevicePathEnd (TempDevicePath)) {
2544 LastDeviceNode = TempDevicePath;
2545 TempDevicePath = NextDevicePathNode (TempDevicePath);
2546 }
2547 GuidPoint = EfiGetNameGuidFromFwVolDevicePathNode (
2548 (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LastDeviceNode
2549 );
2550 if (GuidPoint == NULL) {
2551 //
2552 // if this option does not points to a Fv file, just return EFI_UNSUPPORTED
2553 //
2554 return EFI_UNSUPPORTED;
2555 }
2556 if (!CompareGuid (GuidPoint, FileGuid)) {
2557 //
2558 // If the Fv file is not the input file guid, just return EFI_UNSUPPORTED
2559 //
2560 return EFI_UNSUPPORTED;
2561 }
2562
2563 //
2564 // Check whether the input Fv file device path is valid
2565 //
2566 TempDevicePath = *DevicePath;
2567 FoundFvHandle = NULL;
2568 Status = gBS->LocateDevicePath (
2569 &gEfiFirmwareVolume2ProtocolGuid,
2570 &TempDevicePath,
2571 &FoundFvHandle
2572 );
2573 if (!EFI_ERROR (Status)) {
2574 Status = gBS->HandleProtocol (
2575 FoundFvHandle,
2576 &gEfiFirmwareVolume2ProtocolGuid,
2577 (VOID **) &Fv
2578 );
2579 if (!EFI_ERROR (Status)) {
2580 //
2581 // Set FV ReadFile Buffer as NULL, only need to check whether input Fv file exist there
2582 //
2583 Status = Fv->ReadFile (
2584 Fv,
2585 FileGuid,
2586 NULL,
2587 &Size,
2588 &Type,
2589 &Attributes,
2590 &AuthenticationStatus
2591 );
2592 if (!EFI_ERROR (Status)) {
2593 return EFI_ALREADY_STARTED;
2594 }
2595 }
2596 }
2597
2598 //
2599 // Look for the input wanted FV file in current FV
2600 // First, try to look for in Bds own FV. Bds and input wanted FV file usually are in the same FV
2601 //
2602 FindFvFile = FALSE;
2603 FoundFvHandle = NULL;
2604 Status = gBS->HandleProtocol (
2605 gImageHandle,
2606 &gEfiLoadedImageProtocolGuid,
2607 (VOID **) &LoadedImage
2608 );
2609 if (!EFI_ERROR (Status)) {
2610 Status = gBS->HandleProtocol (
2611 LoadedImage->DeviceHandle,
2612 &gEfiFirmwareVolume2ProtocolGuid,
2613 (VOID **) &Fv
2614 );
2615 if (!EFI_ERROR (Status)) {
2616 Status = Fv->ReadFile (
2617 Fv,
2618 FileGuid,
2619 NULL,
2620 &Size,
2621 &Type,
2622 &Attributes,
2623 &AuthenticationStatus
2624 );
2625 if (!EFI_ERROR (Status)) {
2626 FindFvFile = TRUE;
2627 FoundFvHandle = LoadedImage->DeviceHandle;
2628 }
2629 }
2630 }
2631 //
2632 // Second, if fail to find, try to enumerate all FV
2633 //
2634 if (!FindFvFile) {
2635 FvHandleBuffer = NULL;
2636 gBS->LocateHandleBuffer (
2637 ByProtocol,
2638 &gEfiFirmwareVolume2ProtocolGuid,
2639 NULL,
2640 &FvHandleCount,
2641 &FvHandleBuffer
2642 );
2643 for (Index = 0; Index < FvHandleCount; Index++) {
2644 gBS->HandleProtocol (
2645 FvHandleBuffer[Index],
2646 &gEfiFirmwareVolume2ProtocolGuid,
2647 (VOID **) &Fv
2648 );
2649
2650 Status = Fv->ReadFile (
2651 Fv,
2652 FileGuid,
2653 NULL,
2654 &Size,
2655 &Type,
2656 &Attributes,
2657 &AuthenticationStatus
2658 );
2659 if (EFI_ERROR (Status)) {
2660 //
2661 // Skip if input Fv file not in the FV
2662 //
2663 continue;
2664 }
2665 FindFvFile = TRUE;
2666 FoundFvHandle = FvHandleBuffer[Index];
2667 break;
2668 }
2669
2670 if (FvHandleBuffer != NULL) {
2671 FreePool (FvHandleBuffer);
2672 }
2673 }
2674
2675 if (FindFvFile) {
2676 //
2677 // Build the shell device path
2678 //
2679 NewDevicePath = DevicePathFromHandle (FoundFvHandle);
2680 EfiInitializeFwVolDevicepathNode (&FvFileNode, FileGuid);
2681 NewDevicePath = AppendDevicePathNode (NewDevicePath, (EFI_DEVICE_PATH_PROTOCOL *) &FvFileNode);
2682 *DevicePath = NewDevicePath;
2683 return EFI_SUCCESS;
2684 }
2685 return EFI_NOT_FOUND;
2686 }