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