]> git.proxmox.com Git - mirror_edk2.git/blob - IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c
Add code to check boot option variable before use it
[mirror_edk2.git] / IntelFrameworkModulePkg / Library / GenericBdsLib / BdsBoot.c
1 /** @file
2 BDS Lib functions which relate with create or process the boot option.
3
4 Copyright (c) 2004 - 2012, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12
13 **/
14
15 #include "InternalBdsLib.h"
16 #include "String.h"
17
18 BOOLEAN mEnumBootDevice = FALSE;
19 EFI_HII_HANDLE gBdsLibStringPackHandle = NULL;
20
21 /**
22 The constructor function register UNI strings into imageHandle.
23
24 It will ASSERT() if that operation fails and it will always return EFI_SUCCESS.
25
26 @param ImageHandle The firmware allocated handle for the EFI image.
27 @param SystemTable A pointer to the EFI System Table.
28
29 @retval EFI_SUCCESS The constructor successfully added string package.
30 @retval Other value The constructor can't add string package.
31
32 **/
33 EFI_STATUS
34 EFIAPI
35 GenericBdsLibConstructor (
36 IN EFI_HANDLE ImageHandle,
37 IN EFI_SYSTEM_TABLE *SystemTable
38 )
39 {
40
41 gBdsLibStringPackHandle = HiiAddPackages (
42 &gBdsLibStringPackageGuid,
43 &ImageHandle,
44 GenericBdsLibStrings,
45 NULL
46 );
47
48 ASSERT (gBdsLibStringPackHandle != NULL);
49
50 return EFI_SUCCESS;
51 }
52
53
54
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_STATUS StatusLogo;
618 EFI_HANDLE Handle;
619 EFI_HANDLE ImageHandle;
620 EFI_DEVICE_PATH_PROTOCOL *FilePath;
621 EFI_LOADED_IMAGE_PROTOCOL *ImageInfo;
622 EFI_DEVICE_PATH_PROTOCOL *WorkingDevicePath;
623 EFI_ACPI_S3_SAVE_PROTOCOL *AcpiS3Save;
624 LIST_ENTRY TempBootLists;
625 EFI_BOOT_LOGO_PROTOCOL *BootLogo;
626
627 //
628 // Record the performance data for End of BDS
629 //
630 PERF_END(NULL, "BDS", NULL, 0);
631
632 *ExitDataSize = 0;
633 *ExitData = NULL;
634
635 //
636 // Notes: this code can be remove after the s3 script table
637 // hook on the event EVT_SIGNAL_READY_TO_BOOT or
638 // EVT_SIGNAL_LEGACY_BOOT
639 //
640 Status = gBS->LocateProtocol (&gEfiAcpiS3SaveProtocolGuid, NULL, (VOID **) &AcpiS3Save);
641 if (!EFI_ERROR (Status)) {
642 AcpiS3Save->S3Save (AcpiS3Save, NULL);
643 }
644 //
645 // If it's Device Path that starts with a hard drive path, append it with the front part to compose a
646 // full device path
647 //
648 WorkingDevicePath = NULL;
649 if ((DevicePathType (DevicePath) == MEDIA_DEVICE_PATH) &&
650 (DevicePathSubType (DevicePath) == MEDIA_HARDDRIVE_DP)) {
651 WorkingDevicePath = BdsExpandPartitionPartialDevicePathToFull (
652 (HARDDRIVE_DEVICE_PATH *)DevicePath
653 );
654 if (WorkingDevicePath != NULL) {
655 DevicePath = WorkingDevicePath;
656 }
657 }
658
659 //
660 // Set Boot Current
661 //
662 if (IsBootOptionValidNVVarialbe (Option)) {
663 //
664 // For a temporary boot (i.e. a boot by selected a EFI Shell using "Boot From File"), Boot Current is actually not valid.
665 // In this case, "BootCurrent" is not created.
666 // Only create the BootCurrent variable when it points to a valid Boot#### variable.
667 //
668 gRT->SetVariable (
669 L"BootCurrent",
670 &gEfiGlobalVariableGuid,
671 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
672 sizeof (UINT16),
673 &Option->BootCurrent
674 );
675 }
676
677 //
678 // Signal the EVT_SIGNAL_READY_TO_BOOT event
679 //
680 EfiSignalEventReadyToBoot();
681
682 //
683 // Expand USB Class or USB WWID device path node to be full device path of a USB
684 // device in platform then load the boot file on this full device path and get the
685 // image handle.
686 //
687 ImageHandle = BdsExpandUsbShortFormDevicePath (DevicePath);
688
689 //
690 // Adjust the different type memory page number just before booting
691 // and save the updated info into the variable for next boot to use
692 //
693 BdsSetMemoryTypeInformationVariable ();
694
695 //
696 // By expanding the USB Class or WWID device path, the ImageHandle has returnned.
697 // Here get the ImageHandle for the non USB class or WWID device path.
698 //
699 if (ImageHandle == NULL) {
700 ASSERT (Option->DevicePath != NULL);
701 if ((DevicePathType (Option->DevicePath) == BBS_DEVICE_PATH) &&
702 (DevicePathSubType (Option->DevicePath) == BBS_BBS_DP)
703 ) {
704 //
705 // Check to see if we should legacy BOOT. If yes then do the legacy boot
706 //
707 return BdsLibDoLegacyBoot (Option);
708 }
709
710 //
711 // If the boot option point to Internal FV shell, make sure it is valid
712 //
713 Status = BdsLibUpdateFvFileDevicePath (&DevicePath, PcdGetPtr(PcdShellFile));
714 if (!EFI_ERROR(Status)) {
715 if (Option->DevicePath != NULL) {
716 FreePool(Option->DevicePath);
717 }
718 Option->DevicePath = AllocateZeroPool (GetDevicePathSize (DevicePath));
719 ASSERT(Option->DevicePath != NULL);
720 CopyMem (Option->DevicePath, DevicePath, GetDevicePathSize (DevicePath));
721 //
722 // Update the shell boot option
723 //
724 InitializeListHead (&TempBootLists);
725 BdsLibRegisterNewOption (&TempBootLists, DevicePath, L"EFI Internal Shell", L"BootOrder");
726
727 //
728 // free the temporary device path created by BdsLibUpdateFvFileDevicePath()
729 //
730 FreePool (DevicePath);
731 DevicePath = Option->DevicePath;
732 }
733
734 DEBUG_CODE_BEGIN();
735
736 if (Option->Description == NULL) {
737 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Booting from unknown device path\n"));
738 } else {
739 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Booting %S\n", Option->Description));
740 }
741
742 DEBUG_CODE_END();
743
744 //
745 // Report status code for OS Loader LoadImage.
746 //
747 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderLoad));
748 Status = gBS->LoadImage (
749 TRUE,
750 gImageHandle,
751 DevicePath,
752 NULL,
753 0,
754 &ImageHandle
755 );
756
757 //
758 // If we didn't find an image directly, we need to try as if it is a removable device boot option
759 // and load the image according to the default boot behavior for removable device.
760 //
761 if (EFI_ERROR (Status)) {
762 //
763 // check if there is a bootable removable media could be found in this device path ,
764 // and get the bootable media handle
765 //
766 Handle = BdsLibGetBootableHandle(DevicePath);
767 if (Handle == NULL) {
768 goto Done;
769 }
770 //
771 // Load the default boot file \EFI\BOOT\boot{machinename}.EFI from removable Media
772 // machinename is ia32, ia64, x64, ...
773 //
774 FilePath = FileDevicePath (Handle, EFI_REMOVABLE_MEDIA_FILE_NAME);
775 if (FilePath != NULL) {
776 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderLoad));
777 Status = gBS->LoadImage (
778 TRUE,
779 gImageHandle,
780 FilePath,
781 NULL,
782 0,
783 &ImageHandle
784 );
785 if (EFI_ERROR (Status)) {
786 //
787 // The DevicePath failed, and it's not a valid
788 // removable media device.
789 //
790 goto Done;
791 }
792 }
793 }
794
795 if (EFI_ERROR (Status)) {
796 //
797 // It there is any error from the Boot attempt exit now.
798 //
799 goto Done;
800 }
801 }
802 //
803 // Provide the image with it's load options
804 //
805 if (ImageHandle == NULL) {
806 goto Done;
807 }
808 Status = gBS->HandleProtocol (ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &ImageInfo);
809 ASSERT_EFI_ERROR (Status);
810
811 if (Option->LoadOptionsSize != 0) {
812 ImageInfo->LoadOptionsSize = Option->LoadOptionsSize;
813 ImageInfo->LoadOptions = Option->LoadOptions;
814 }
815 //
816 // Before calling the image, enable the Watchdog Timer for
817 // the 5 Minute period
818 //
819 gBS->SetWatchdogTimer (5 * 60, 0x0000, 0x00, NULL);
820
821 //
822 // Write boot to OS performance data for UEFI boot
823 //
824 PERF_CODE (
825 WriteBootToOsPerformanceData ();
826 );
827
828 //
829 // Report status code for OS Loader StartImage.
830 //
831 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderStart));
832
833 Status = gBS->StartImage (ImageHandle, ExitDataSize, ExitData);
834 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Image Return Status = %r\n", Status));
835
836 //
837 // Clear the Watchdog Timer after the image returns
838 //
839 gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL);
840
841 Done:
842 //
843 // Set Logo status invalid after trying one boot option
844 //
845 BootLogo = NULL;
846 StatusLogo = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **) &BootLogo);
847 if (!EFI_ERROR (StatusLogo) && (BootLogo != NULL)) {
848 BootLogo->SetBootLogo (BootLogo, NULL, 0, 0, 0, 0);
849 }
850
851 //
852 // Clear Boot Current
853 //
854 gRT->SetVariable (
855 L"BootCurrent",
856 &gEfiGlobalVariableGuid,
857 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
858 0,
859 &Option->BootCurrent
860 );
861
862 return Status;
863 }
864
865
866 /**
867 Expand a device path that starts with a hard drive media device path node to be a
868 full device path that includes the full hardware path to the device. We need
869 to do this so it can be booted. As an optimization the front match (the part point
870 to the partition node. E.g. ACPI() /PCI()/ATA()/Partition() ) is saved in a variable
871 so a connect all is not required on every boot. All successful history device path
872 which point to partition node (the front part) will be saved.
873
874 @param HardDriveDevicePath EFI Device Path to boot, if it starts with a hard
875 drive media device path.
876 @return A Pointer to the full device path or NULL if a valid Hard Drive devic path
877 cannot be found.
878
879 **/
880 EFI_DEVICE_PATH_PROTOCOL *
881 EFIAPI
882 BdsExpandPartitionPartialDevicePathToFull (
883 IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath
884 )
885 {
886 EFI_STATUS Status;
887 UINTN BlockIoHandleCount;
888 EFI_HANDLE *BlockIoBuffer;
889 EFI_DEVICE_PATH_PROTOCOL *FullDevicePath;
890 EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath;
891 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
892 UINTN Index;
893 UINTN InstanceNum;
894 EFI_DEVICE_PATH_PROTOCOL *CachedDevicePath;
895 EFI_DEVICE_PATH_PROTOCOL *TempNewDevicePath;
896 UINTN CachedDevicePathSize;
897 BOOLEAN DeviceExist;
898 BOOLEAN NeedAdjust;
899 EFI_DEVICE_PATH_PROTOCOL *Instance;
900 UINTN Size;
901
902 FullDevicePath = NULL;
903 //
904 // Check if there is prestore HD_BOOT_DEVICE_PATH_VARIABLE_NAME variable.
905 // If exist, search the front path which point to partition node in the variable instants.
906 // If fail to find or HD_BOOT_DEVICE_PATH_VARIABLE_NAME not exist, reconnect all and search in all system
907 //
908 CachedDevicePath = BdsLibGetVariableAndSize (
909 HD_BOOT_DEVICE_PATH_VARIABLE_NAME,
910 &gHdBootDevicePathVariablGuid,
911 &CachedDevicePathSize
912 );
913
914 if (CachedDevicePath != NULL) {
915 TempNewDevicePath = CachedDevicePath;
916 DeviceExist = FALSE;
917 NeedAdjust = FALSE;
918 do {
919 //
920 // Check every instance of the variable
921 // First, check whether the instance contain the partition node, which is needed for distinguishing multi
922 // partial partition boot option. Second, check whether the instance could be connected.
923 //
924 Instance = GetNextDevicePathInstance (&TempNewDevicePath, &Size);
925 if (MatchPartitionDevicePathNode (Instance, HardDriveDevicePath)) {
926 //
927 // Connect the device path instance, the device path point to hard drive media device path node
928 // e.g. ACPI() /PCI()/ATA()/Partition()
929 //
930 Status = BdsLibConnectDevicePath (Instance);
931 if (!EFI_ERROR (Status)) {
932 DeviceExist = TRUE;
933 break;
934 }
935 }
936 //
937 // Come here means the first instance is not matched
938 //
939 NeedAdjust = TRUE;
940 FreePool(Instance);
941 } while (TempNewDevicePath != NULL);
942
943 if (DeviceExist) {
944 //
945 // Find the matched device path.
946 // Append the file path information from the boot option and return the fully expanded device path.
947 //
948 DevicePath = NextDevicePathNode ((EFI_DEVICE_PATH_PROTOCOL *) HardDriveDevicePath);
949 FullDevicePath = AppendDevicePath (Instance, DevicePath);
950
951 //
952 // Adjust the HD_BOOT_DEVICE_PATH_VARIABLE_NAME instances sequence if the matched one is not first one.
953 //
954 if (NeedAdjust) {
955 //
956 // First delete the matched instance.
957 //
958 TempNewDevicePath = CachedDevicePath;
959 CachedDevicePath = BdsLibDelPartMatchInstance (CachedDevicePath, Instance );
960 FreePool (TempNewDevicePath);
961
962 //
963 // Second, append the remaining path after the matched instance
964 //
965 TempNewDevicePath = CachedDevicePath;
966 CachedDevicePath = AppendDevicePathInstance (Instance, CachedDevicePath );
967 FreePool (TempNewDevicePath);
968 //
969 // Save the matching Device Path so we don't need to do a connect all next time
970 //
971 Status = gRT->SetVariable (
972 HD_BOOT_DEVICE_PATH_VARIABLE_NAME,
973 &gHdBootDevicePathVariablGuid,
974 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
975 GetDevicePathSize (CachedDevicePath),
976 CachedDevicePath
977 );
978 }
979
980 FreePool (Instance);
981 FreePool (CachedDevicePath);
982 return FullDevicePath;
983 }
984 }
985
986 //
987 // If we get here we fail to find or HD_BOOT_DEVICE_PATH_VARIABLE_NAME not exist, and now we need
988 // to search all devices in the system for a matched partition
989 //
990 BdsLibConnectAllDriversToAllControllers ();
991 Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiBlockIoProtocolGuid, NULL, &BlockIoHandleCount, &BlockIoBuffer);
992 if (EFI_ERROR (Status) || BlockIoHandleCount == 0 || BlockIoBuffer == NULL) {
993 //
994 // If there was an error or there are no device handles that support
995 // the BLOCK_IO Protocol, then return.
996 //
997 return NULL;
998 }
999 //
1000 // Loop through all the device handles that support the BLOCK_IO Protocol
1001 //
1002 for (Index = 0; Index < BlockIoHandleCount; Index++) {
1003
1004 Status = gBS->HandleProtocol (BlockIoBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID *) &BlockIoDevicePath);
1005 if (EFI_ERROR (Status) || BlockIoDevicePath == NULL) {
1006 continue;
1007 }
1008
1009 if (MatchPartitionDevicePathNode (BlockIoDevicePath, HardDriveDevicePath)) {
1010 //
1011 // Find the matched partition device path
1012 //
1013 DevicePath = NextDevicePathNode ((EFI_DEVICE_PATH_PROTOCOL *) HardDriveDevicePath);
1014 FullDevicePath = AppendDevicePath (BlockIoDevicePath, DevicePath);
1015
1016 //
1017 // Save the matched partition device path in HD_BOOT_DEVICE_PATH_VARIABLE_NAME variable
1018 //
1019 if (CachedDevicePath != NULL) {
1020 //
1021 // Save the matched partition device path as first instance of HD_BOOT_DEVICE_PATH_VARIABLE_NAME variable
1022 //
1023 if (BdsLibMatchDevicePaths (CachedDevicePath, BlockIoDevicePath)) {
1024 TempNewDevicePath = CachedDevicePath;
1025 CachedDevicePath = BdsLibDelPartMatchInstance (CachedDevicePath, BlockIoDevicePath);
1026 FreePool(TempNewDevicePath);
1027
1028 TempNewDevicePath = CachedDevicePath;
1029 CachedDevicePath = AppendDevicePathInstance (BlockIoDevicePath, CachedDevicePath);
1030 if (TempNewDevicePath != NULL) {
1031 FreePool(TempNewDevicePath);
1032 }
1033 } else {
1034 TempNewDevicePath = CachedDevicePath;
1035 CachedDevicePath = AppendDevicePathInstance (BlockIoDevicePath, CachedDevicePath);
1036 FreePool(TempNewDevicePath);
1037 }
1038 //
1039 // Here limit the device path instance number to 12, which is max number for a system support 3 IDE controller
1040 // If the user try to boot many OS in different HDs or partitions, in theory,
1041 // the HD_BOOT_DEVICE_PATH_VARIABLE_NAME variable maybe become larger and larger.
1042 //
1043 InstanceNum = 0;
1044 ASSERT (CachedDevicePath != NULL);
1045 TempNewDevicePath = CachedDevicePath;
1046 while (!IsDevicePathEnd (TempNewDevicePath)) {
1047 TempNewDevicePath = NextDevicePathNode (TempNewDevicePath);
1048 //
1049 // Parse one instance
1050 //
1051 while (!IsDevicePathEndType (TempNewDevicePath)) {
1052 TempNewDevicePath = NextDevicePathNode (TempNewDevicePath);
1053 }
1054 InstanceNum++;
1055 //
1056 // If the CachedDevicePath variable contain too much instance, only remain 12 instances.
1057 //
1058 if (InstanceNum >= 12) {
1059 SetDevicePathEndNode (TempNewDevicePath);
1060 break;
1061 }
1062 }
1063 } else {
1064 CachedDevicePath = DuplicateDevicePath (BlockIoDevicePath);
1065 }
1066
1067 //
1068 // Save the matching Device Path so we don't need to do a connect all next time
1069 //
1070 Status = gRT->SetVariable (
1071 HD_BOOT_DEVICE_PATH_VARIABLE_NAME,
1072 &gHdBootDevicePathVariablGuid,
1073 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1074 GetDevicePathSize (CachedDevicePath),
1075 CachedDevicePath
1076 );
1077
1078 break;
1079 }
1080 }
1081
1082 if (CachedDevicePath != NULL) {
1083 FreePool (CachedDevicePath);
1084 }
1085 if (BlockIoBuffer != NULL) {
1086 FreePool (BlockIoBuffer);
1087 }
1088 return FullDevicePath;
1089 }
1090
1091 /**
1092 Check whether there is a instance in BlockIoDevicePath, which contain multi device path
1093 instances, has the same partition node with HardDriveDevicePath device path
1094
1095 @param BlockIoDevicePath Multi device path instances which need to check
1096 @param HardDriveDevicePath A device path which starts with a hard drive media
1097 device path.
1098
1099 @retval TRUE There is a matched device path instance.
1100 @retval FALSE There is no matched device path instance.
1101
1102 **/
1103 BOOLEAN
1104 EFIAPI
1105 MatchPartitionDevicePathNode (
1106 IN EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath,
1107 IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath
1108 )
1109 {
1110 HARDDRIVE_DEVICE_PATH *TmpHdPath;
1111 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1112 BOOLEAN Match;
1113 EFI_DEVICE_PATH_PROTOCOL *BlockIoHdDevicePathNode;
1114
1115 if ((BlockIoDevicePath == NULL) || (HardDriveDevicePath == NULL)) {
1116 return FALSE;
1117 }
1118
1119 //
1120 // Make PreviousDevicePath == the device path node before the end node
1121 //
1122 DevicePath = BlockIoDevicePath;
1123 BlockIoHdDevicePathNode = NULL;
1124
1125 //
1126 // find the partition device path node
1127 //
1128 while (!IsDevicePathEnd (DevicePath)) {
1129 if ((DevicePathType (DevicePath) == MEDIA_DEVICE_PATH) &&
1130 (DevicePathSubType (DevicePath) == MEDIA_HARDDRIVE_DP)
1131 ) {
1132 BlockIoHdDevicePathNode = DevicePath;
1133 break;
1134 }
1135
1136 DevicePath = NextDevicePathNode (DevicePath);
1137 }
1138
1139 if (BlockIoHdDevicePathNode == NULL) {
1140 return FALSE;
1141 }
1142 //
1143 // See if the harddrive device path in blockio matches the orig Hard Drive Node
1144 //
1145 TmpHdPath = (HARDDRIVE_DEVICE_PATH *) BlockIoHdDevicePathNode;
1146 Match = FALSE;
1147
1148 //
1149 // Check for the match
1150 //
1151 if ((TmpHdPath->MBRType == HardDriveDevicePath->MBRType) &&
1152 (TmpHdPath->SignatureType == HardDriveDevicePath->SignatureType)) {
1153 switch (TmpHdPath->SignatureType) {
1154 case SIGNATURE_TYPE_GUID:
1155 Match = CompareGuid ((EFI_GUID *)TmpHdPath->Signature, (EFI_GUID *)HardDriveDevicePath->Signature);
1156 break;
1157 case SIGNATURE_TYPE_MBR:
1158 Match = (BOOLEAN)(*((UINT32 *)(&(TmpHdPath->Signature[0]))) == ReadUnaligned32((UINT32 *)(&(HardDriveDevicePath->Signature[0]))));
1159 break;
1160 default:
1161 Match = FALSE;
1162 break;
1163 }
1164 }
1165
1166 return Match;
1167 }
1168
1169 /**
1170 Delete the boot option associated with the handle passed in.
1171
1172 @param Handle The handle which present the device path to create
1173 boot option
1174
1175 @retval EFI_SUCCESS Delete the boot option success
1176 @retval EFI_NOT_FOUND If the Device Path is not found in the system
1177 @retval EFI_OUT_OF_RESOURCES Lack of memory resource
1178 @retval Other Error return value from SetVariable()
1179
1180 **/
1181 EFI_STATUS
1182 BdsLibDeleteOptionFromHandle (
1183 IN EFI_HANDLE Handle
1184 )
1185 {
1186 UINT16 *BootOrder;
1187 UINT8 *BootOptionVar;
1188 UINTN BootOrderSize;
1189 UINTN BootOptionSize;
1190 EFI_STATUS Status;
1191 UINTN Index;
1192 UINT16 BootOption[BOOT_OPTION_MAX_CHAR];
1193 UINTN DevicePathSize;
1194 UINTN OptionDevicePathSize;
1195 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1196 EFI_DEVICE_PATH_PROTOCOL *OptionDevicePath;
1197 UINT8 *TempPtr;
1198
1199 Status = EFI_SUCCESS;
1200 BootOrder = NULL;
1201 BootOrderSize = 0;
1202
1203 //
1204 // Check "BootOrder" variable, if no, means there is no any boot order.
1205 //
1206 BootOrder = BdsLibGetVariableAndSize (
1207 L"BootOrder",
1208 &gEfiGlobalVariableGuid,
1209 &BootOrderSize
1210 );
1211 if (BootOrder == NULL) {
1212 return EFI_NOT_FOUND;
1213 }
1214
1215 //
1216 // Convert device handle to device path protocol instance
1217 //
1218 DevicePath = DevicePathFromHandle (Handle);
1219 if (DevicePath == NULL) {
1220 return EFI_NOT_FOUND;
1221 }
1222 DevicePathSize = GetDevicePathSize (DevicePath);
1223
1224 //
1225 // Loop all boot order variable and find the matching device path
1226 //
1227 Index = 0;
1228 while (Index < BootOrderSize / sizeof (UINT16)) {
1229 UnicodeSPrint (BootOption, sizeof (BootOption), L"Boot%04x", BootOrder[Index]);
1230 BootOptionVar = BdsLibGetVariableAndSize (
1231 BootOption,
1232 &gEfiGlobalVariableGuid,
1233 &BootOptionSize
1234 );
1235
1236 if (BootOptionVar == NULL) {
1237 FreePool (BootOrder);
1238 return EFI_OUT_OF_RESOURCES;
1239 }
1240
1241 if (!ValidateOption(BootOptionVar, BootOptionSize)) {
1242 BdsDeleteBootOption (BootOrder[Index], BootOrder, &BootOrderSize);
1243 FreePool (BootOptionVar);
1244 Index++;
1245 continue;
1246 }
1247
1248 TempPtr = BootOptionVar;
1249 TempPtr += sizeof (UINT32) + sizeof (UINT16);
1250 TempPtr += StrSize ((CHAR16 *) TempPtr);
1251 OptionDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) TempPtr;
1252 OptionDevicePathSize = GetDevicePathSize (OptionDevicePath);
1253
1254 //
1255 // Check whether the device path match
1256 //
1257 if ((OptionDevicePathSize == DevicePathSize) &&
1258 (CompareMem (DevicePath, OptionDevicePath, DevicePathSize) == 0)) {
1259 BdsDeleteBootOption (BootOrder[Index], BootOrder, &BootOrderSize);
1260 FreePool (BootOptionVar);
1261 break;
1262 }
1263
1264 FreePool (BootOptionVar);
1265 Index++;
1266 }
1267
1268 //
1269 // Adjust number of boot option for "BootOrder" variable.
1270 //
1271 Status = gRT->SetVariable (
1272 L"BootOrder",
1273 &gEfiGlobalVariableGuid,
1274 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1275 BootOrderSize,
1276 BootOrder
1277 );
1278
1279 FreePool (BootOrder);
1280
1281 return Status;
1282 }
1283
1284
1285 /**
1286 Delete all invalid EFI boot options.
1287
1288 @retval EFI_SUCCESS Delete all invalid boot option success
1289 @retval EFI_NOT_FOUND Variable "BootOrder" is not found
1290 @retval EFI_OUT_OF_RESOURCES Lack of memory resource
1291 @retval Other Error return value from SetVariable()
1292
1293 **/
1294 EFI_STATUS
1295 BdsDeleteAllInvalidEfiBootOption (
1296 VOID
1297 )
1298 {
1299 UINT16 *BootOrder;
1300 UINT8 *BootOptionVar;
1301 UINTN BootOrderSize;
1302 UINTN BootOptionSize;
1303 EFI_STATUS Status;
1304 UINTN Index;
1305 UINTN Index2;
1306 UINT16 BootOption[BOOT_OPTION_MAX_CHAR];
1307 EFI_DEVICE_PATH_PROTOCOL *OptionDevicePath;
1308 UINT8 *TempPtr;
1309 CHAR16 *Description;
1310 BOOLEAN Corrupted;
1311
1312 Status = EFI_SUCCESS;
1313 BootOrder = NULL;
1314 Description = NULL;
1315 OptionDevicePath = NULL;
1316 BootOrderSize = 0;
1317 Corrupted = FALSE;
1318
1319 //
1320 // Check "BootOrder" variable firstly, this variable hold the number of boot options
1321 //
1322 BootOrder = BdsLibGetVariableAndSize (
1323 L"BootOrder",
1324 &gEfiGlobalVariableGuid,
1325 &BootOrderSize
1326 );
1327 if (NULL == BootOrder) {
1328 return EFI_NOT_FOUND;
1329 }
1330
1331 Index = 0;
1332 while (Index < BootOrderSize / sizeof (UINT16)) {
1333 UnicodeSPrint (BootOption, sizeof (BootOption), L"Boot%04x", BootOrder[Index]);
1334 BootOptionVar = BdsLibGetVariableAndSize (
1335 BootOption,
1336 &gEfiGlobalVariableGuid,
1337 &BootOptionSize
1338 );
1339 if (NULL == BootOptionVar) {
1340 FreePool (BootOrder);
1341 return EFI_OUT_OF_RESOURCES;
1342 }
1343
1344 if (!ValidateOption(BootOptionVar, BootOptionSize)) {
1345 Corrupted = TRUE;
1346 } else {
1347 TempPtr = BootOptionVar;
1348 TempPtr += sizeof (UINT32) + sizeof (UINT16);
1349 Description = (CHAR16 *) TempPtr;
1350 TempPtr += StrSize ((CHAR16 *) TempPtr);
1351 OptionDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) TempPtr;
1352
1353 //
1354 // Skip legacy boot option (BBS boot device)
1355 //
1356 if ((DevicePathType (OptionDevicePath) == BBS_DEVICE_PATH) &&
1357 (DevicePathSubType (OptionDevicePath) == BBS_BBS_DP)) {
1358 FreePool (BootOptionVar);
1359 Index++;
1360 continue;
1361 }
1362 }
1363
1364 if (Corrupted || !BdsLibIsValidEFIBootOptDevicePathExt (OptionDevicePath, FALSE, Description)) {
1365 //
1366 // Delete this invalid boot option "Boot####"
1367 //
1368 Status = gRT->SetVariable (
1369 BootOption,
1370 &gEfiGlobalVariableGuid,
1371 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1372 0,
1373 NULL
1374 );
1375 //
1376 // Mark this boot option in boot order as deleted
1377 //
1378 BootOrder[Index] = 0xffff;
1379 Corrupted = FALSE;
1380 }
1381
1382 FreePool (BootOptionVar);
1383 Index++;
1384 }
1385
1386 //
1387 // Adjust boot order array
1388 //
1389 Index2 = 0;
1390 for (Index = 0; Index < BootOrderSize / sizeof (UINT16); Index++) {
1391 if (BootOrder[Index] != 0xffff) {
1392 BootOrder[Index2] = BootOrder[Index];
1393 Index2 ++;
1394 }
1395 }
1396 Status = gRT->SetVariable (
1397 L"BootOrder",
1398 &gEfiGlobalVariableGuid,
1399 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1400 Index2 * sizeof (UINT16),
1401 BootOrder
1402 );
1403
1404 FreePool (BootOrder);
1405
1406 return Status;
1407 }
1408
1409
1410 /**
1411 For EFI boot option, BDS separate them as six types:
1412 1. Network - The boot option points to the SimpleNetworkProtocol device.
1413 Bds will try to automatically create this type boot option when enumerate.
1414 2. Shell - The boot option points to internal flash shell.
1415 Bds will try to automatically create this type boot option when enumerate.
1416 3. Removable BlockIo - The boot option only points to the removable media
1417 device, like USB flash disk, DVD, Floppy etc.
1418 These device should contain a *removable* blockIo
1419 protocol in their device handle.
1420 Bds will try to automatically create this type boot option
1421 when enumerate.
1422 4. Fixed BlockIo - The boot option only points to a Fixed blockIo device,
1423 like HardDisk.
1424 These device should contain a *fixed* blockIo
1425 protocol in their device handle.
1426 BDS will skip fixed blockIo devices, and NOT
1427 automatically create boot option for them. But BDS
1428 will help to delete those fixed blockIo boot option,
1429 whose description rule conflict with other auto-created
1430 boot options.
1431 5. Non-BlockIo Simplefile - The boot option points to a device whose handle
1432 has SimpleFileSystem Protocol, but has no blockio
1433 protocol. These devices do not offer blockIo
1434 protocol, but BDS still can get the
1435 \EFI\BOOT\boot{machinename}.EFI by SimpleFileSystem
1436 Protocol.
1437 6. File - The boot option points to a file. These boot options are usually
1438 created by user manually or OS loader. BDS will not delete or modify
1439 these boot options.
1440
1441 This function will enumerate all possible boot device in the system, and
1442 automatically create boot options for Network, Shell, Removable BlockIo,
1443 and Non-BlockIo Simplefile devices.
1444 It will only execute once of every boot.
1445
1446 @param BdsBootOptionList The header of the link list which indexed all
1447 current boot options
1448
1449 @retval EFI_SUCCESS Finished all the boot device enumerate and create
1450 the boot option base on that boot device
1451
1452 @retval EFI_OUT_OF_RESOURCES Failed to enumerate the boot device and create the boot option list
1453 **/
1454 EFI_STATUS
1455 EFIAPI
1456 BdsLibEnumerateAllBootOption (
1457 IN OUT LIST_ENTRY *BdsBootOptionList
1458 )
1459 {
1460 EFI_STATUS Status;
1461 UINT16 FloppyNumber;
1462 UINT16 HarddriveNumber;
1463 UINT16 CdromNumber;
1464 UINT16 UsbNumber;
1465 UINT16 MiscNumber;
1466 UINT16 ScsiNumber;
1467 UINT16 NonBlockNumber;
1468 UINTN NumberBlockIoHandles;
1469 EFI_HANDLE *BlockIoHandles;
1470 EFI_BLOCK_IO_PROTOCOL *BlkIo;
1471 BOOLEAN Removable[2];
1472 UINTN RemovableIndex;
1473 UINTN Index;
1474 UINTN NumOfLoadFileHandles;
1475 EFI_HANDLE *LoadFileHandles;
1476 UINTN FvHandleCount;
1477 EFI_HANDLE *FvHandleBuffer;
1478 EFI_FV_FILETYPE Type;
1479 UINTN Size;
1480 EFI_FV_FILE_ATTRIBUTES Attributes;
1481 UINT32 AuthenticationStatus;
1482 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
1483 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1484 UINTN DevicePathType;
1485 CHAR16 Buffer[40];
1486 EFI_HANDLE *FileSystemHandles;
1487 UINTN NumberFileSystemHandles;
1488 BOOLEAN NeedDelete;
1489 EFI_IMAGE_DOS_HEADER DosHeader;
1490 CHAR8 *PlatLang;
1491 CHAR8 *LastLang;
1492 EFI_IMAGE_OPTIONAL_HEADER_UNION HdrData;
1493 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
1494
1495 FloppyNumber = 0;
1496 HarddriveNumber = 0;
1497 CdromNumber = 0;
1498 UsbNumber = 0;
1499 MiscNumber = 0;
1500 ScsiNumber = 0;
1501 PlatLang = NULL;
1502 LastLang = NULL;
1503 ZeroMem (Buffer, sizeof (Buffer));
1504
1505 //
1506 // If the boot device enumerate happened, just get the boot
1507 // device from the boot order variable
1508 //
1509 if (mEnumBootDevice) {
1510 LastLang = GetVariable (LAST_ENUM_LANGUAGE_VARIABLE_NAME, &gLastEnumLangGuid);
1511 PlatLang = GetEfiGlobalVariable (L"PlatformLang");
1512 ASSERT (PlatLang != NULL);
1513 if ((LastLang != NULL) && (AsciiStrCmp (LastLang, PlatLang) == 0)) {
1514 Status = BdsLibBuildOptionFromVar (BdsBootOptionList, L"BootOrder");
1515 FreePool (LastLang);
1516 FreePool (PlatLang);
1517 return Status;
1518 } else {
1519 Status = gRT->SetVariable (
1520 LAST_ENUM_LANGUAGE_VARIABLE_NAME,
1521 &gLastEnumLangGuid,
1522 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1523 AsciiStrSize (PlatLang),
1524 PlatLang
1525 );
1526 ASSERT_EFI_ERROR (Status);
1527
1528 if (LastLang != NULL) {
1529 FreePool (LastLang);
1530 }
1531 FreePool (PlatLang);
1532 }
1533 }
1534
1535 //
1536 // Notes: this dirty code is to get the legacy boot option from the
1537 // BBS table and create to variable as the EFI boot option, it should
1538 // be removed after the CSM can provide legacy boot option directly
1539 //
1540 REFRESH_LEGACY_BOOT_OPTIONS;
1541
1542 //
1543 // Delete invalid boot option
1544 //
1545 BdsDeleteAllInvalidEfiBootOption ();
1546
1547 //
1548 // Parse removable media followed by fixed media.
1549 // The Removable[] array is used by the for-loop below to create removable media boot options
1550 // at first, and then to create fixed media boot options.
1551 //
1552 Removable[0] = FALSE;
1553 Removable[1] = TRUE;
1554
1555 gBS->LocateHandleBuffer (
1556 ByProtocol,
1557 &gEfiBlockIoProtocolGuid,
1558 NULL,
1559 &NumberBlockIoHandles,
1560 &BlockIoHandles
1561 );
1562
1563 for (RemovableIndex = 0; RemovableIndex < 2; RemovableIndex++) {
1564 for (Index = 0; Index < NumberBlockIoHandles; Index++) {
1565 Status = gBS->HandleProtocol (
1566 BlockIoHandles[Index],
1567 &gEfiBlockIoProtocolGuid,
1568 (VOID **) &BlkIo
1569 );
1570 //
1571 // skip the fixed block io then the removable block io
1572 //
1573 if (EFI_ERROR (Status) || (BlkIo->Media->RemovableMedia == Removable[RemovableIndex])) {
1574 continue;
1575 }
1576 DevicePath = DevicePathFromHandle (BlockIoHandles[Index]);
1577 DevicePathType = BdsGetBootTypeFromDevicePath (DevicePath);
1578
1579 switch (DevicePathType) {
1580 case BDS_EFI_ACPI_FLOPPY_BOOT:
1581 if (FloppyNumber != 0) {
1582 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_FLOPPY)), FloppyNumber);
1583 } else {
1584 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_FLOPPY)));
1585 }
1586 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1587 FloppyNumber++;
1588 break;
1589
1590 //
1591 // Assume a removable SATA device should be the DVD/CD device, a fixed SATA device should be the Hard Drive device.
1592 //
1593 case BDS_EFI_MESSAGE_ATAPI_BOOT:
1594 case BDS_EFI_MESSAGE_SATA_BOOT:
1595 if (BlkIo->Media->RemovableMedia) {
1596 if (CdromNumber != 0) {
1597 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_CD_DVD)), CdromNumber);
1598 } else {
1599 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_CD_DVD)));
1600 }
1601 CdromNumber++;
1602 } else {
1603 if (HarddriveNumber != 0) {
1604 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_HARDDRIVE)), HarddriveNumber);
1605 } else {
1606 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_HARDDRIVE)));
1607 }
1608 HarddriveNumber++;
1609 }
1610 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Buffer: %S\n", Buffer));
1611 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1612 break;
1613
1614 case BDS_EFI_MESSAGE_USB_DEVICE_BOOT:
1615 if (UsbNumber != 0) {
1616 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_USB)), UsbNumber);
1617 } else {
1618 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_USB)));
1619 }
1620 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1621 UsbNumber++;
1622 break;
1623
1624 case BDS_EFI_MESSAGE_SCSI_BOOT:
1625 if (ScsiNumber != 0) {
1626 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_SCSI)), ScsiNumber);
1627 } else {
1628 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_SCSI)));
1629 }
1630 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1631 ScsiNumber++;
1632 break;
1633
1634 case BDS_EFI_MESSAGE_MISC_BOOT:
1635 if (MiscNumber != 0) {
1636 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_MISC)), MiscNumber);
1637 } else {
1638 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_MISC)));
1639 }
1640 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1641 MiscNumber++;
1642 break;
1643
1644 default:
1645 break;
1646 }
1647 }
1648 }
1649
1650 if (NumberBlockIoHandles != 0) {
1651 FreePool (BlockIoHandles);
1652 }
1653
1654 //
1655 // If there is simple file protocol which does not consume block Io protocol, create a boot option for it here.
1656 //
1657 NonBlockNumber = 0;
1658 gBS->LocateHandleBuffer (
1659 ByProtocol,
1660 &gEfiSimpleFileSystemProtocolGuid,
1661 NULL,
1662 &NumberFileSystemHandles,
1663 &FileSystemHandles
1664 );
1665 for (Index = 0; Index < NumberFileSystemHandles; Index++) {
1666 Status = gBS->HandleProtocol (
1667 FileSystemHandles[Index],
1668 &gEfiBlockIoProtocolGuid,
1669 (VOID **) &BlkIo
1670 );
1671 if (!EFI_ERROR (Status)) {
1672 //
1673 // Skip if the file system handle supports a BlkIo protocol,
1674 //
1675 continue;
1676 }
1677
1678 //
1679 // Do the removable Media thing. \EFI\BOOT\boot{machinename}.EFI
1680 // machinename is ia32, ia64, x64, ...
1681 //
1682 Hdr.Union = &HdrData;
1683 NeedDelete = TRUE;
1684 Status = BdsLibGetImageHeader (
1685 FileSystemHandles[Index],
1686 EFI_REMOVABLE_MEDIA_FILE_NAME,
1687 &DosHeader,
1688 Hdr
1689 );
1690 if (!EFI_ERROR (Status) &&
1691 EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Hdr.Pe32->FileHeader.Machine) &&
1692 Hdr.Pe32->OptionalHeader.Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {
1693 NeedDelete = FALSE;
1694 }
1695
1696 if (NeedDelete) {
1697 //
1698 // No such file or the file is not a EFI application, delete this boot option
1699 //
1700 BdsLibDeleteOptionFromHandle (FileSystemHandles[Index]);
1701 } else {
1702 if (NonBlockNumber != 0) {
1703 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_NON_BLOCK)), NonBlockNumber);
1704 } else {
1705 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_NON_BLOCK)));
1706 }
1707 BdsLibBuildOptionFromHandle (FileSystemHandles[Index], BdsBootOptionList, Buffer);
1708 NonBlockNumber++;
1709 }
1710 }
1711
1712 if (NumberFileSystemHandles != 0) {
1713 FreePool (FileSystemHandles);
1714 }
1715
1716 //
1717 // Parse Network Boot Device
1718 //
1719 NumOfLoadFileHandles = 0;
1720 //
1721 // Search Load File protocol for PXE boot option.
1722 //
1723 gBS->LocateHandleBuffer (
1724 ByProtocol,
1725 &gEfiLoadFileProtocolGuid,
1726 NULL,
1727 &NumOfLoadFileHandles,
1728 &LoadFileHandles
1729 );
1730
1731 for (Index = 0; Index < NumOfLoadFileHandles; Index++) {
1732 if (Index != 0) {
1733 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s %d", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_NETWORK)), Index);
1734 } else {
1735 UnicodeSPrint (Buffer, sizeof (Buffer), L"%s", BdsLibGetStringById (STRING_TOKEN (STR_DESCRIPTION_NETWORK)));
1736 }
1737 BdsLibBuildOptionFromHandle (LoadFileHandles[Index], BdsBootOptionList, Buffer);
1738 }
1739
1740 if (NumOfLoadFileHandles != 0) {
1741 FreePool (LoadFileHandles);
1742 }
1743
1744 //
1745 // Check if we have on flash shell
1746 //
1747 gBS->LocateHandleBuffer (
1748 ByProtocol,
1749 &gEfiFirmwareVolume2ProtocolGuid,
1750 NULL,
1751 &FvHandleCount,
1752 &FvHandleBuffer
1753 );
1754 for (Index = 0; Index < FvHandleCount; Index++) {
1755 gBS->HandleProtocol (
1756 FvHandleBuffer[Index],
1757 &gEfiFirmwareVolume2ProtocolGuid,
1758 (VOID **) &Fv
1759 );
1760
1761 Status = Fv->ReadFile (
1762 Fv,
1763 PcdGetPtr(PcdShellFile),
1764 NULL,
1765 &Size,
1766 &Type,
1767 &Attributes,
1768 &AuthenticationStatus
1769 );
1770 if (EFI_ERROR (Status)) {
1771 //
1772 // Skip if no shell file in the FV
1773 //
1774 continue;
1775 }
1776 //
1777 // Build the shell boot option
1778 //
1779 BdsLibBuildOptionFromShell (FvHandleBuffer[Index], BdsBootOptionList);
1780 }
1781
1782 if (FvHandleCount != 0) {
1783 FreePool (FvHandleBuffer);
1784 }
1785 //
1786 // Make sure every boot only have one time
1787 // boot device enumerate
1788 //
1789 Status = BdsLibBuildOptionFromVar (BdsBootOptionList, L"BootOrder");
1790 mEnumBootDevice = TRUE;
1791
1792 return Status;
1793 }
1794
1795 /**
1796 Build the boot option with the handle parsed in
1797
1798 @param Handle The handle which present the device path to create
1799 boot option
1800 @param BdsBootOptionList The header of the link list which indexed all
1801 current boot options
1802 @param String The description of the boot option.
1803
1804 **/
1805 VOID
1806 EFIAPI
1807 BdsLibBuildOptionFromHandle (
1808 IN EFI_HANDLE Handle,
1809 IN LIST_ENTRY *BdsBootOptionList,
1810 IN CHAR16 *String
1811 )
1812 {
1813 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1814
1815 DevicePath = DevicePathFromHandle (Handle);
1816
1817 //
1818 // Create and register new boot option
1819 //
1820 BdsLibRegisterNewOption (BdsBootOptionList, DevicePath, String, L"BootOrder");
1821 }
1822
1823
1824 /**
1825 Build the on flash shell boot option with the handle parsed in.
1826
1827 @param Handle The handle which present the device path to create
1828 on flash shell boot option
1829 @param BdsBootOptionList The header of the link list which indexed all
1830 current boot options
1831
1832 **/
1833 VOID
1834 EFIAPI
1835 BdsLibBuildOptionFromShell (
1836 IN EFI_HANDLE Handle,
1837 IN OUT LIST_ENTRY *BdsBootOptionList
1838 )
1839 {
1840 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1841 MEDIA_FW_VOL_FILEPATH_DEVICE_PATH ShellNode;
1842
1843 DevicePath = DevicePathFromHandle (Handle);
1844
1845 //
1846 // Build the shell device path
1847 //
1848 EfiInitializeFwVolDevicepathNode (&ShellNode, PcdGetPtr(PcdShellFile));
1849
1850 DevicePath = AppendDevicePathNode (DevicePath, (EFI_DEVICE_PATH_PROTOCOL *) &ShellNode);
1851
1852 //
1853 // Create and register the shell boot option
1854 //
1855 BdsLibRegisterNewOption (BdsBootOptionList, DevicePath, L"EFI Internal Shell", L"BootOrder");
1856
1857 }
1858
1859 /**
1860 Boot from the UEFI spec defined "BootNext" variable.
1861
1862 **/
1863 VOID
1864 EFIAPI
1865 BdsLibBootNext (
1866 VOID
1867 )
1868 {
1869 UINT16 *BootNext;
1870 UINTN BootNextSize;
1871 CHAR16 Buffer[20];
1872 BDS_COMMON_OPTION *BootOption;
1873 LIST_ENTRY TempList;
1874 UINTN ExitDataSize;
1875 CHAR16 *ExitData;
1876
1877 //
1878 // Init the boot option name buffer and temp link list
1879 //
1880 InitializeListHead (&TempList);
1881 ZeroMem (Buffer, sizeof (Buffer));
1882
1883 BootNext = BdsLibGetVariableAndSize (
1884 L"BootNext",
1885 &gEfiGlobalVariableGuid,
1886 &BootNextSize
1887 );
1888
1889 //
1890 // Clear the boot next variable first
1891 //
1892 if (BootNext != NULL) {
1893 gRT->SetVariable (
1894 L"BootNext",
1895 &gEfiGlobalVariableGuid,
1896 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1897 0,
1898 BootNext
1899 );
1900
1901 //
1902 // Start to build the boot option and try to boot
1903 //
1904 UnicodeSPrint (Buffer, sizeof (Buffer), L"Boot%04x", *BootNext);
1905 BootOption = BdsLibVariableToOption (&TempList, Buffer);
1906 ASSERT (BootOption != NULL);
1907 BdsLibConnectDevicePath (BootOption->DevicePath);
1908 BdsLibBootViaBootOption (BootOption, BootOption->DevicePath, &ExitDataSize, &ExitData);
1909 }
1910
1911 }
1912
1913 /**
1914 Return the bootable media handle.
1915 First, check the device is connected
1916 Second, check whether the device path point to a device which support SimpleFileSystemProtocol,
1917 Third, detect the the default boot file in the Media, and return the removable Media handle.
1918
1919 @param DevicePath Device Path to a bootable device
1920
1921 @return The bootable media handle. If the media on the DevicePath is not bootable, NULL will return.
1922
1923 **/
1924 EFI_HANDLE
1925 EFIAPI
1926 BdsLibGetBootableHandle (
1927 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
1928 )
1929 {
1930 EFI_STATUS Status;
1931 EFI_TPL OldTpl;
1932 EFI_DEVICE_PATH_PROTOCOL *UpdatedDevicePath;
1933 EFI_DEVICE_PATH_PROTOCOL *DupDevicePath;
1934 EFI_HANDLE Handle;
1935 EFI_BLOCK_IO_PROTOCOL *BlockIo;
1936 VOID *Buffer;
1937 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
1938 UINTN Size;
1939 UINTN TempSize;
1940 EFI_HANDLE ReturnHandle;
1941 EFI_HANDLE *SimpleFileSystemHandles;
1942
1943 UINTN NumberSimpleFileSystemHandles;
1944 UINTN Index;
1945 EFI_IMAGE_DOS_HEADER DosHeader;
1946 EFI_IMAGE_OPTIONAL_HEADER_UNION HdrData;
1947 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
1948
1949 UpdatedDevicePath = DevicePath;
1950
1951 //
1952 // Enter to critical section to protect the acquired BlockIo instance
1953 // from getting released due to the USB mass storage hotplug event
1954 //
1955 OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
1956
1957 //
1958 // Check whether the device is connected
1959 //
1960 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &UpdatedDevicePath, &Handle);
1961 if (EFI_ERROR (Status)) {
1962 //
1963 // Skip the case that the boot option point to a simple file protocol which does not consume block Io protocol,
1964 //
1965 Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &UpdatedDevicePath, &Handle);
1966 if (EFI_ERROR (Status)) {
1967 //
1968 // Fail to find the proper BlockIo and simple file protocol, maybe because device not present, we need to connect it firstly
1969 //
1970 UpdatedDevicePath = DevicePath;
1971 Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &UpdatedDevicePath, &Handle);
1972 gBS->ConnectController (Handle, NULL, NULL, TRUE);
1973 }
1974 } else {
1975 //
1976 // For removable device boot option, its contained device path only point to the removable device handle,
1977 // should make sure all its children handles (its child partion or media handles) are created and connected.
1978 //
1979 gBS->ConnectController (Handle, NULL, NULL, TRUE);
1980 //
1981 // Get BlockIo protocol and check removable attribute
1982 //
1983 Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo);
1984 ASSERT_EFI_ERROR (Status);
1985
1986 //
1987 // Issue a dummy read to the device to check for media change.
1988 // When the removable media is changed, any Block IO read/write will
1989 // cause the BlockIo protocol be reinstalled and EFI_MEDIA_CHANGED is
1990 // returned. After the Block IO protocol is reinstalled, subsequent
1991 // Block IO read/write will success.
1992 //
1993 Buffer = AllocatePool (BlockIo->Media->BlockSize);
1994 if (Buffer != NULL) {
1995 BlockIo->ReadBlocks (
1996 BlockIo,
1997 BlockIo->Media->MediaId,
1998 0,
1999 BlockIo->Media->BlockSize,
2000 Buffer
2001 );
2002 FreePool(Buffer);
2003 }
2004 }
2005
2006 //
2007 // Detect the the default boot file from removable Media
2008 //
2009
2010 //
2011 // 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
2012 // Try to locate the USB node device path first, if fail then use its previous PCI node to search
2013 //
2014 DupDevicePath = DuplicateDevicePath (DevicePath);
2015 ASSERT (DupDevicePath != NULL);
2016
2017 UpdatedDevicePath = DupDevicePath;
2018 Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &UpdatedDevicePath, &Handle);
2019 //
2020 // 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
2021 // Acpi()/Pci()/Usb() --> Acpi()/Pci()
2022 //
2023 if ((DevicePathType (UpdatedDevicePath) == MESSAGING_DEVICE_PATH) &&
2024 (DevicePathSubType (UpdatedDevicePath) == MSG_USB_DP)) {
2025 //
2026 // Remove the usb node, let the device path only point to PCI node
2027 //
2028 SetDevicePathEndNode (UpdatedDevicePath);
2029 UpdatedDevicePath = DupDevicePath;
2030 } else {
2031 UpdatedDevicePath = DevicePath;
2032 }
2033
2034 //
2035 // Get the device path size of boot option
2036 //
2037 Size = GetDevicePathSize(UpdatedDevicePath) - sizeof (EFI_DEVICE_PATH_PROTOCOL); // minus the end node
2038 ReturnHandle = NULL;
2039 gBS->LocateHandleBuffer (
2040 ByProtocol,
2041 &gEfiSimpleFileSystemProtocolGuid,
2042 NULL,
2043 &NumberSimpleFileSystemHandles,
2044 &SimpleFileSystemHandles
2045 );
2046 for (Index = 0; Index < NumberSimpleFileSystemHandles; Index++) {
2047 //
2048 // Get the device path size of SimpleFileSystem handle
2049 //
2050 TempDevicePath = DevicePathFromHandle (SimpleFileSystemHandles[Index]);
2051 TempSize = GetDevicePathSize (TempDevicePath)- sizeof (EFI_DEVICE_PATH_PROTOCOL); // minus the end node
2052 //
2053 // Check whether the device path of boot option is part of the SimpleFileSystem handle's device path
2054 //
2055 if (Size <= TempSize && CompareMem (TempDevicePath, UpdatedDevicePath, Size)==0) {
2056 //
2057 // Load the default boot file \EFI\BOOT\boot{machinename}.EFI from removable Media
2058 // machinename is ia32, ia64, x64, ...
2059 //
2060 Hdr.Union = &HdrData;
2061 Status = BdsLibGetImageHeader (
2062 SimpleFileSystemHandles[Index],
2063 EFI_REMOVABLE_MEDIA_FILE_NAME,
2064 &DosHeader,
2065 Hdr
2066 );
2067 if (!EFI_ERROR (Status) &&
2068 EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Hdr.Pe32->FileHeader.Machine) &&
2069 Hdr.Pe32->OptionalHeader.Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {
2070 ReturnHandle = SimpleFileSystemHandles[Index];
2071 break;
2072 }
2073 }
2074 }
2075
2076 FreePool(DupDevicePath);
2077
2078 if (SimpleFileSystemHandles != NULL) {
2079 FreePool(SimpleFileSystemHandles);
2080 }
2081
2082 gBS->RestoreTPL (OldTpl);
2083
2084 return ReturnHandle;
2085 }
2086
2087 /**
2088 Check to see if the network cable is plugged in. If the DevicePath is not
2089 connected it will be connected.
2090
2091 @param DevicePath Device Path to check
2092
2093 @retval TRUE DevicePath points to an Network that is connected
2094 @retval FALSE DevicePath does not point to a bootable network
2095
2096 **/
2097 BOOLEAN
2098 BdsLibNetworkBootWithMediaPresent (
2099 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
2100 )
2101 {
2102 EFI_STATUS Status;
2103 EFI_DEVICE_PATH_PROTOCOL *UpdatedDevicePath;
2104 EFI_HANDLE Handle;
2105 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
2106 BOOLEAN MediaPresent;
2107 UINT32 InterruptStatus;
2108
2109 MediaPresent = FALSE;
2110
2111 UpdatedDevicePath = DevicePath;
2112 //
2113 // Locate Load File Protocol for PXE boot option first
2114 //
2115 Status = gBS->LocateDevicePath (&gEfiLoadFileProtocolGuid, &UpdatedDevicePath, &Handle);
2116 if (EFI_ERROR (Status)) {
2117 //
2118 // Device not present so see if we need to connect it
2119 //
2120 Status = BdsLibConnectDevicePath (DevicePath);
2121 if (!EFI_ERROR (Status)) {
2122 //
2123 // This one should work after we did the connect
2124 //
2125 Status = gBS->LocateDevicePath (&gEfiLoadFileProtocolGuid, &UpdatedDevicePath, &Handle);
2126 }
2127 }
2128
2129 if (!EFI_ERROR (Status)) {
2130 Status = gBS->HandleProtocol (Handle, &gEfiSimpleNetworkProtocolGuid, (VOID **)&Snp);
2131 if (EFI_ERROR (Status)) {
2132 //
2133 // Failed to open SNP from this handle, try to get SNP from parent handle
2134 //
2135 UpdatedDevicePath = DevicePathFromHandle (Handle);
2136 if (UpdatedDevicePath != NULL) {
2137 Status = gBS->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid, &UpdatedDevicePath, &Handle);
2138 if (!EFI_ERROR (Status)) {
2139 //
2140 // SNP handle found, get SNP from it
2141 //
2142 Status = gBS->HandleProtocol (Handle, &gEfiSimpleNetworkProtocolGuid, (VOID **) &Snp);
2143 }
2144 }
2145 }
2146
2147 if (!EFI_ERROR (Status)) {
2148 if (Snp->Mode->MediaPresentSupported) {
2149 if (Snp->Mode->State == EfiSimpleNetworkInitialized) {
2150 //
2151 // Invoke Snp->GetStatus() to refresh the media status
2152 //
2153 Snp->GetStatus (Snp, &InterruptStatus, NULL);
2154
2155 //
2156 // In case some one else is using the SNP check to see if it's connected
2157 //
2158 MediaPresent = Snp->Mode->MediaPresent;
2159 } else {
2160 //
2161 // No one is using SNP so we need to Start and Initialize so
2162 // MediaPresent will be valid.
2163 //
2164 Status = Snp->Start (Snp);
2165 if (!EFI_ERROR (Status)) {
2166 Status = Snp->Initialize (Snp, 0, 0);
2167 if (!EFI_ERROR (Status)) {
2168 MediaPresent = Snp->Mode->MediaPresent;
2169 Snp->Shutdown (Snp);
2170 }
2171 Snp->Stop (Snp);
2172 }
2173 }
2174 } else {
2175 MediaPresent = TRUE;
2176 }
2177 }
2178 }
2179
2180 return MediaPresent;
2181 }
2182
2183 /**
2184 For a bootable Device path, return its boot type.
2185
2186 @param DevicePath The bootable device Path to check
2187
2188 @retval BDS_EFI_MEDIA_HD_BOOT If given device path contains MEDIA_DEVICE_PATH type device path node
2189 which subtype is MEDIA_HARDDRIVE_DP
2190 @retval BDS_EFI_MEDIA_CDROM_BOOT If given device path contains MEDIA_DEVICE_PATH type device path node
2191 which subtype is MEDIA_CDROM_DP
2192 @retval BDS_EFI_ACPI_FLOPPY_BOOT If given device path contains ACPI_DEVICE_PATH type device path node
2193 which HID is floppy device.
2194 @retval BDS_EFI_MESSAGE_ATAPI_BOOT If given device path contains MESSAGING_DEVICE_PATH type device path node
2195 and its last device path node's subtype is MSG_ATAPI_DP.
2196 @retval BDS_EFI_MESSAGE_SCSI_BOOT If given device path contains MESSAGING_DEVICE_PATH type device path node
2197 and its last device path node's subtype is MSG_SCSI_DP.
2198 @retval BDS_EFI_MESSAGE_USB_DEVICE_BOOT If given device path contains MESSAGING_DEVICE_PATH type device path node
2199 and its last device path node's subtype is MSG_USB_DP.
2200 @retval BDS_EFI_MESSAGE_MISC_BOOT If the device path not contains any media device path node, and
2201 its last device path node point to a message device path node.
2202 @retval BDS_LEGACY_BBS_BOOT If given device path contains BBS_DEVICE_PATH type device path node.
2203 @retval BDS_EFI_UNSUPPORT An EFI Removable BlockIO device path not point to a media and message device,
2204
2205 **/
2206 UINT32
2207 EFIAPI
2208 BdsGetBootTypeFromDevicePath (
2209 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
2210 )
2211 {
2212 ACPI_HID_DEVICE_PATH *Acpi;
2213 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
2214 EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
2215 UINT32 BootType;
2216
2217 if (NULL == DevicePath) {
2218 return BDS_EFI_UNSUPPORT;
2219 }
2220
2221 TempDevicePath = DevicePath;
2222
2223 while (!IsDevicePathEndType (TempDevicePath)) {
2224 switch (DevicePathType (TempDevicePath)) {
2225 case BBS_DEVICE_PATH:
2226 return BDS_LEGACY_BBS_BOOT;
2227 case MEDIA_DEVICE_PATH:
2228 if (DevicePathSubType (TempDevicePath) == MEDIA_HARDDRIVE_DP) {
2229 return BDS_EFI_MEDIA_HD_BOOT;
2230 } else if (DevicePathSubType (TempDevicePath) == MEDIA_CDROM_DP) {
2231 return BDS_EFI_MEDIA_CDROM_BOOT;
2232 }
2233 break;
2234 case ACPI_DEVICE_PATH:
2235 Acpi = (ACPI_HID_DEVICE_PATH *) TempDevicePath;
2236 if (EISA_ID_TO_NUM (Acpi->HID) == 0x0604) {
2237 return BDS_EFI_ACPI_FLOPPY_BOOT;
2238 }
2239 break;
2240 case MESSAGING_DEVICE_PATH:
2241 //
2242 // Get the last device path node
2243 //
2244 LastDeviceNode = NextDevicePathNode (TempDevicePath);
2245 if (DevicePathSubType(LastDeviceNode) == MSG_DEVICE_LOGICAL_UNIT_DP) {
2246 //
2247 // if the next node type is Device Logical Unit, which specify the Logical Unit Number (LUN),
2248 // skip it
2249 //
2250 LastDeviceNode = NextDevicePathNode (LastDeviceNode);
2251 }
2252 //
2253 // if the device path not only point to driver device, it is not a messaging device path,
2254 //
2255 if (!IsDevicePathEndType (LastDeviceNode)) {
2256 break;
2257 }
2258
2259 switch (DevicePathSubType (TempDevicePath)) {
2260 case MSG_ATAPI_DP:
2261 BootType = BDS_EFI_MESSAGE_ATAPI_BOOT;
2262 break;
2263
2264 case MSG_USB_DP:
2265 BootType = BDS_EFI_MESSAGE_USB_DEVICE_BOOT;
2266 break;
2267
2268 case MSG_SCSI_DP:
2269 BootType = BDS_EFI_MESSAGE_SCSI_BOOT;
2270 break;
2271
2272 case MSG_SATA_DP:
2273 BootType = BDS_EFI_MESSAGE_SATA_BOOT;
2274 break;
2275
2276 case MSG_MAC_ADDR_DP:
2277 case MSG_VLAN_DP:
2278 case MSG_IPv4_DP:
2279 case MSG_IPv6_DP:
2280 BootType = BDS_EFI_MESSAGE_MAC_BOOT;
2281 break;
2282
2283 default:
2284 BootType = BDS_EFI_MESSAGE_MISC_BOOT;
2285 break;
2286 }
2287 return BootType;
2288
2289 default:
2290 break;
2291 }
2292 TempDevicePath = NextDevicePathNode (TempDevicePath);
2293 }
2294
2295 return BDS_EFI_UNSUPPORT;
2296 }
2297
2298 /**
2299 Check whether the Device path in a boot option point to a valid bootable device,
2300 And if CheckMedia is true, check the device is ready to boot now.
2301
2302 @param DevPath the Device path in a boot option
2303 @param CheckMedia if true, check the device is ready to boot now.
2304
2305 @retval TRUE the Device path is valid
2306 @retval FALSE the Device path is invalid .
2307
2308 **/
2309 BOOLEAN
2310 EFIAPI
2311 BdsLibIsValidEFIBootOptDevicePath (
2312 IN EFI_DEVICE_PATH_PROTOCOL *DevPath,
2313 IN BOOLEAN CheckMedia
2314 )
2315 {
2316 return BdsLibIsValidEFIBootOptDevicePathExt (DevPath, CheckMedia, NULL);
2317 }
2318
2319 /**
2320 Check whether the Device path in a boot option point to a valid bootable device,
2321 And if CheckMedia is true, check the device is ready to boot now.
2322 If Description is not NULL and the device path point to a fixed BlockIo
2323 device, check the description whether conflict with other auto-created
2324 boot options.
2325
2326 @param DevPath the Device path in a boot option
2327 @param CheckMedia if true, check the device is ready to boot now.
2328 @param Description the description in a boot option
2329
2330 @retval TRUE the Device path is valid
2331 @retval FALSE the Device path is invalid .
2332
2333 **/
2334 BOOLEAN
2335 EFIAPI
2336 BdsLibIsValidEFIBootOptDevicePathExt (
2337 IN EFI_DEVICE_PATH_PROTOCOL *DevPath,
2338 IN BOOLEAN CheckMedia,
2339 IN CHAR16 *Description
2340 )
2341 {
2342 EFI_STATUS Status;
2343 EFI_HANDLE Handle;
2344 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
2345 EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
2346 EFI_BLOCK_IO_PROTOCOL *BlockIo;
2347
2348 TempDevicePath = DevPath;
2349 LastDeviceNode = DevPath;
2350
2351 //
2352 // Check if it's a valid boot option for network boot device.
2353 // Check if there is EfiLoadFileProtocol installed.
2354 // If yes, that means there is a boot option for network.
2355 //
2356 Status = gBS->LocateDevicePath (
2357 &gEfiLoadFileProtocolGuid,
2358 &TempDevicePath,
2359 &Handle
2360 );
2361 if (EFI_ERROR (Status)) {
2362 //
2363 // Device not present so see if we need to connect it
2364 //
2365 TempDevicePath = DevPath;
2366 BdsLibConnectDevicePath (TempDevicePath);
2367 Status = gBS->LocateDevicePath (
2368 &gEfiLoadFileProtocolGuid,
2369 &TempDevicePath,
2370 &Handle
2371 );
2372 }
2373
2374 if (!EFI_ERROR (Status)) {
2375 if (!IsDevicePathEnd (TempDevicePath)) {
2376 //
2377 // LoadFile protocol is not installed on handle with exactly the same DevPath
2378 //
2379 return FALSE;
2380 }
2381
2382 if (CheckMedia) {
2383 //
2384 // Test if it is ready to boot now
2385 //
2386 if (BdsLibNetworkBootWithMediaPresent(DevPath)) {
2387 return TRUE;
2388 }
2389 } else {
2390 return TRUE;
2391 }
2392 }
2393
2394 //
2395 // If the boot option point to a file, it is a valid EFI boot option,
2396 // and assume it is ready to boot now
2397 //
2398 while (!IsDevicePathEnd (TempDevicePath)) {
2399 //
2400 // If there is USB Class or USB WWID device path node, treat it as valid EFI
2401 // Boot Option. BdsExpandUsbShortFormDevicePath () will be used to expand it
2402 // to full device path.
2403 //
2404 if ((DevicePathType (TempDevicePath) == MESSAGING_DEVICE_PATH) &&
2405 ((DevicePathSubType (TempDevicePath) == MSG_USB_CLASS_DP) ||
2406 (DevicePathSubType (TempDevicePath) == MSG_USB_WWID_DP))) {
2407 return TRUE;
2408 }
2409
2410 LastDeviceNode = TempDevicePath;
2411 TempDevicePath = NextDevicePathNode (TempDevicePath);
2412 }
2413 if ((DevicePathType (LastDeviceNode) == MEDIA_DEVICE_PATH) &&
2414 (DevicePathSubType (LastDeviceNode) == MEDIA_FILEPATH_DP)) {
2415 return TRUE;
2416 }
2417
2418 //
2419 // Check if it's a valid boot option for internal FV application
2420 //
2421 if (EfiGetNameGuidFromFwVolDevicePathNode ((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LastDeviceNode) != NULL) {
2422 //
2423 // If the boot option point to internal FV application, make sure it is valid
2424 //
2425 TempDevicePath = DevPath;
2426 Status = BdsLibUpdateFvFileDevicePath (
2427 &TempDevicePath,
2428 EfiGetNameGuidFromFwVolDevicePathNode ((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LastDeviceNode)
2429 );
2430 if (Status == EFI_ALREADY_STARTED) {
2431 return TRUE;
2432 } else {
2433 if (Status == EFI_SUCCESS) {
2434 FreePool (TempDevicePath);
2435 }
2436 return FALSE;
2437 }
2438 }
2439
2440 //
2441 // If the boot option point to a blockIO device:
2442 // if it is a removable blockIo device, it is valid.
2443 // if it is a fixed blockIo device, check its description confliction.
2444 //
2445 TempDevicePath = DevPath;
2446 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &TempDevicePath, &Handle);
2447 if (EFI_ERROR (Status)) {
2448 //
2449 // Device not present so see if we need to connect it
2450 //
2451 Status = BdsLibConnectDevicePath (DevPath);
2452 if (!EFI_ERROR (Status)) {
2453 //
2454 // Try again to get the Block Io protocol after we did the connect
2455 //
2456 TempDevicePath = DevPath;
2457 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &TempDevicePath, &Handle);
2458 }
2459 }
2460
2461 if (!EFI_ERROR (Status)) {
2462 Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo);
2463 if (!EFI_ERROR (Status)) {
2464 if (CheckMedia) {
2465 //
2466 // Test if it is ready to boot now
2467 //
2468 if (BdsLibGetBootableHandle (DevPath) != NULL) {
2469 return TRUE;
2470 }
2471 } else {
2472 return TRUE;
2473 }
2474 }
2475 } else {
2476 //
2477 // 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,
2478 //
2479 Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &TempDevicePath, &Handle);
2480 if (!EFI_ERROR (Status)) {
2481 if (CheckMedia) {
2482 //
2483 // Test if it is ready to boot now
2484 //
2485 if (BdsLibGetBootableHandle (DevPath) != NULL) {
2486 return TRUE;
2487 }
2488 } else {
2489 return TRUE;
2490 }
2491 }
2492 }
2493
2494 return FALSE;
2495 }
2496
2497
2498 /**
2499 According to a file guild, check a Fv file device path is valid. If it is invalid,
2500 try to return the valid device path.
2501 FV address maybe changes for memory layout adjust from time to time, use this function
2502 could promise the Fv file device path is right.
2503
2504 @param DevicePath on input, the Fv file device path need to check on
2505 output, the updated valid Fv file device path
2506 @param FileGuid the Fv file guild
2507
2508 @retval EFI_INVALID_PARAMETER the input DevicePath or FileGuid is invalid
2509 parameter
2510 @retval EFI_UNSUPPORTED the input DevicePath does not contain Fv file
2511 guild at all
2512 @retval EFI_ALREADY_STARTED the input DevicePath has pointed to Fv file, it is
2513 valid
2514 @retval EFI_SUCCESS has successfully updated the invalid DevicePath,
2515 and return the updated device path in DevicePath
2516
2517 **/
2518 EFI_STATUS
2519 EFIAPI
2520 BdsLibUpdateFvFileDevicePath (
2521 IN OUT EFI_DEVICE_PATH_PROTOCOL ** DevicePath,
2522 IN EFI_GUID *FileGuid
2523 )
2524 {
2525 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
2526 EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
2527 EFI_STATUS Status;
2528 EFI_GUID *GuidPoint;
2529 UINTN Index;
2530 UINTN FvHandleCount;
2531 EFI_HANDLE *FvHandleBuffer;
2532 EFI_FV_FILETYPE Type;
2533 UINTN Size;
2534 EFI_FV_FILE_ATTRIBUTES Attributes;
2535 UINT32 AuthenticationStatus;
2536 BOOLEAN FindFvFile;
2537 EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
2538 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
2539 MEDIA_FW_VOL_FILEPATH_DEVICE_PATH FvFileNode;
2540 EFI_HANDLE FoundFvHandle;
2541 EFI_DEVICE_PATH_PROTOCOL *NewDevicePath;
2542
2543 if ((DevicePath == NULL) || (*DevicePath == NULL)) {
2544 return EFI_INVALID_PARAMETER;
2545 }
2546 if (FileGuid == NULL) {
2547 return EFI_INVALID_PARAMETER;
2548 }
2549
2550 //
2551 // Check whether the device path point to the default the input Fv file
2552 //
2553 TempDevicePath = *DevicePath;
2554 LastDeviceNode = TempDevicePath;
2555 while (!IsDevicePathEnd (TempDevicePath)) {
2556 LastDeviceNode = TempDevicePath;
2557 TempDevicePath = NextDevicePathNode (TempDevicePath);
2558 }
2559 GuidPoint = EfiGetNameGuidFromFwVolDevicePathNode (
2560 (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LastDeviceNode
2561 );
2562 if (GuidPoint == NULL) {
2563 //
2564 // if this option does not points to a Fv file, just return EFI_UNSUPPORTED
2565 //
2566 return EFI_UNSUPPORTED;
2567 }
2568 if (!CompareGuid (GuidPoint, FileGuid)) {
2569 //
2570 // If the Fv file is not the input file guid, just return EFI_UNSUPPORTED
2571 //
2572 return EFI_UNSUPPORTED;
2573 }
2574
2575 //
2576 // Check whether the input Fv file device path is valid
2577 //
2578 TempDevicePath = *DevicePath;
2579 FoundFvHandle = NULL;
2580 Status = gBS->LocateDevicePath (
2581 &gEfiFirmwareVolume2ProtocolGuid,
2582 &TempDevicePath,
2583 &FoundFvHandle
2584 );
2585 if (!EFI_ERROR (Status)) {
2586 Status = gBS->HandleProtocol (
2587 FoundFvHandle,
2588 &gEfiFirmwareVolume2ProtocolGuid,
2589 (VOID **) &Fv
2590 );
2591 if (!EFI_ERROR (Status)) {
2592 //
2593 // Set FV ReadFile Buffer as NULL, only need to check whether input Fv file exist there
2594 //
2595 Status = Fv->ReadFile (
2596 Fv,
2597 FileGuid,
2598 NULL,
2599 &Size,
2600 &Type,
2601 &Attributes,
2602 &AuthenticationStatus
2603 );
2604 if (!EFI_ERROR (Status)) {
2605 return EFI_ALREADY_STARTED;
2606 }
2607 }
2608 }
2609
2610 //
2611 // Look for the input wanted FV file in current FV
2612 // First, try to look for in Bds own FV. Bds and input wanted FV file usually are in the same FV
2613 //
2614 FindFvFile = FALSE;
2615 FoundFvHandle = NULL;
2616 Status = gBS->HandleProtocol (
2617 gImageHandle,
2618 &gEfiLoadedImageProtocolGuid,
2619 (VOID **) &LoadedImage
2620 );
2621 if (!EFI_ERROR (Status)) {
2622 Status = gBS->HandleProtocol (
2623 LoadedImage->DeviceHandle,
2624 &gEfiFirmwareVolume2ProtocolGuid,
2625 (VOID **) &Fv
2626 );
2627 if (!EFI_ERROR (Status)) {
2628 Status = Fv->ReadFile (
2629 Fv,
2630 FileGuid,
2631 NULL,
2632 &Size,
2633 &Type,
2634 &Attributes,
2635 &AuthenticationStatus
2636 );
2637 if (!EFI_ERROR (Status)) {
2638 FindFvFile = TRUE;
2639 FoundFvHandle = LoadedImage->DeviceHandle;
2640 }
2641 }
2642 }
2643 //
2644 // Second, if fail to find, try to enumerate all FV
2645 //
2646 if (!FindFvFile) {
2647 FvHandleBuffer = NULL;
2648 gBS->LocateHandleBuffer (
2649 ByProtocol,
2650 &gEfiFirmwareVolume2ProtocolGuid,
2651 NULL,
2652 &FvHandleCount,
2653 &FvHandleBuffer
2654 );
2655 for (Index = 0; Index < FvHandleCount; Index++) {
2656 gBS->HandleProtocol (
2657 FvHandleBuffer[Index],
2658 &gEfiFirmwareVolume2ProtocolGuid,
2659 (VOID **) &Fv
2660 );
2661
2662 Status = Fv->ReadFile (
2663 Fv,
2664 FileGuid,
2665 NULL,
2666 &Size,
2667 &Type,
2668 &Attributes,
2669 &AuthenticationStatus
2670 );
2671 if (EFI_ERROR (Status)) {
2672 //
2673 // Skip if input Fv file not in the FV
2674 //
2675 continue;
2676 }
2677 FindFvFile = TRUE;
2678 FoundFvHandle = FvHandleBuffer[Index];
2679 break;
2680 }
2681
2682 if (FvHandleBuffer != NULL) {
2683 FreePool (FvHandleBuffer);
2684 }
2685 }
2686
2687 if (FindFvFile) {
2688 //
2689 // Build the shell device path
2690 //
2691 NewDevicePath = DevicePathFromHandle (FoundFvHandle);
2692 EfiInitializeFwVolDevicepathNode (&FvFileNode, FileGuid);
2693 NewDevicePath = AppendDevicePathNode (NewDevicePath, (EFI_DEVICE_PATH_PROTOCOL *) &FvFileNode);
2694 *DevicePath = NewDevicePath;
2695 return EFI_SUCCESS;
2696 }
2697 return EFI_NOT_FOUND;
2698 }