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