]> git.proxmox.com Git - mirror_edk2.git/blob - IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c
Fix BDS limitation of two "EFI DVD/CDROM" options appear after plug two CD-ROM.
[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 - 2008, Intel Corporation. <BR>
5 All rights reserved. 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
17 BOOLEAN mEnumBootDevice = FALSE;
18
19 ///
20 /// This GUID is used for an EFI Variable that stores the front device pathes
21 /// for a partial device path that starts with the HD node.
22 ///
23 EFI_GUID mHdBootVariablePrivateGuid = { 0xfab7e9e1, 0x39dd, 0x4f2b, { 0x84, 0x8, 0xe2, 0xe, 0x90, 0x6c, 0xb6, 0xde } };
24
25
26
27 /**
28 Boot the legacy system with the boot option
29
30 @param Option The legacy boot option which have BBS device path
31
32 @retval EFI_UNSUPPORTED There is no legacybios protocol, do not support
33 legacy boot.
34 @retval EFI_STATUS Return the status of LegacyBios->LegacyBoot ().
35
36 **/
37 EFI_STATUS
38 BdsLibDoLegacyBoot (
39 IN BDS_COMMON_OPTION *Option
40 )
41 {
42 EFI_STATUS Status;
43 EFI_LEGACY_BIOS_PROTOCOL *LegacyBios;
44
45 Status = gBS->LocateProtocol (&gEfiLegacyBiosProtocolGuid, NULL, (VOID **) &LegacyBios);
46 if (EFI_ERROR (Status)) {
47 //
48 // If no LegacyBios protocol we do not support legacy boot
49 //
50 return EFI_UNSUPPORTED;
51 }
52 //
53 // Notes: if we separate the int 19, then we don't need to refresh BBS
54 //
55 BdsRefreshBbsTableForBoot (Option);
56
57 //
58 // Write boot to OS performance data to a file
59 //
60 PERF_CODE (
61 WriteBootToOsPerformanceData ();
62 );
63
64 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Legacy Boot: %S\n", Option->Description));
65 return LegacyBios->LegacyBoot (
66 LegacyBios,
67 (BBS_BBS_DEVICE_PATH *) Option->DevicePath,
68 Option->LoadOptionsSize,
69 Option->LoadOptions
70 );
71 }
72
73 /**
74 Internal function to check if the input boot option is a valid EFI NV Boot####.
75
76 @param OptionToCheck Boot option to be checked.
77
78 @retval TRUE This boot option matches a valid EFI NV Boot####.
79 @retval FALSE If not.
80
81 **/
82
83 BOOLEAN
84 IsBootOptionValidNVVarialbe (
85 IN BDS_COMMON_OPTION *OptionToCheck
86 )
87 {
88 LIST_ENTRY TempList;
89 BDS_COMMON_OPTION *BootOption;
90 BOOLEAN Valid;
91 CHAR16 OptionName[20];
92
93 Valid = FALSE;
94
95 InitializeListHead (&TempList);
96 UnicodeSPrint (OptionName, sizeof (OptionName), L"Boot%04x", OptionToCheck->BootCurrent);
97
98 BootOption = BdsLibVariableToOption (&TempList, OptionName);
99 if (BootOption == NULL) {
100 return FALSE;
101 }
102
103 //
104 // If the Boot Option Number and Device Path matches, OptionToCheck matches a
105 // valid EFI NV Boot####.
106 //
107 if ((OptionToCheck->BootCurrent == BootOption->BootCurrent) &&
108 (CompareMem (OptionToCheck->DevicePath, BootOption->DevicePath, GetDevicePathSize (OptionToCheck->DevicePath)) == 0))
109 {
110 Valid = TRUE;
111 }
112
113 FreePool (BootOption);
114
115 return Valid;
116 }
117 /**
118 Process the boot option follow the UEFI specification and
119 special treat the legacy boot option with BBS_DEVICE_PATH.
120
121 @param Option The boot option need to be processed
122 @param DevicePath The device path which describe where to load the
123 boot image or the legacy BBS device path to boot
124 the legacy OS
125 @param ExitDataSize The size of exit data.
126 @param ExitData Data returned when Boot image failed.
127
128 @retval EFI_SUCCESS Boot from the input boot option successfully.
129 @retval EFI_NOT_FOUND If the Device Path is not found in the system
130
131 **/
132 EFI_STATUS
133 EFIAPI
134 BdsLibBootViaBootOption (
135 IN BDS_COMMON_OPTION *Option,
136 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
137 OUT UINTN *ExitDataSize,
138 OUT CHAR16 **ExitData OPTIONAL
139 )
140 {
141 EFI_STATUS Status;
142 EFI_HANDLE Handle;
143 EFI_HANDLE ImageHandle;
144 EFI_DEVICE_PATH_PROTOCOL *FilePath;
145 EFI_LOADED_IMAGE_PROTOCOL *ImageInfo;
146 EFI_DEVICE_PATH_PROTOCOL *WorkingDevicePath;
147 EFI_ACPI_S3_SAVE_PROTOCOL *AcpiS3Save;
148 LIST_ENTRY TempBootLists;
149 EFI_SECURITY_ARCH_PROTOCOL *SecurityProtocol;
150
151 //
152 // Record the performance data for End of BDS
153 //
154 PERF_END (0, "BDS", NULL, 0);
155
156 *ExitDataSize = 0;
157 *ExitData = NULL;
158
159 //
160 // Notes: put EFI64 ROM Shadow Solution
161 //
162 EFI64_SHADOW_ALL_LEGACY_ROM ();
163
164 //
165 // Notes: this code can be remove after the s3 script table
166 // hook on the event EVT_SIGNAL_READY_TO_BOOT or
167 // EVT_SIGNAL_LEGACY_BOOT
168 //
169 Status = gBS->LocateProtocol (&gEfiAcpiS3SaveProtocolGuid, NULL, (VOID **) &AcpiS3Save);
170 if (!EFI_ERROR (Status)) {
171 AcpiS3Save->S3Save (AcpiS3Save, NULL);
172 }
173 //
174 // If it's Device Path that starts with a hard drive path, append it with the front part to compose a
175 // full device path
176 //
177 WorkingDevicePath = NULL;
178 if ((DevicePathType (DevicePath) == MEDIA_DEVICE_PATH) &&
179 (DevicePathSubType (DevicePath) == MEDIA_HARDDRIVE_DP)) {
180 WorkingDevicePath = BdsExpandPartitionPartialDevicePathToFull (
181 (HARDDRIVE_DEVICE_PATH *)DevicePath
182 );
183 if (WorkingDevicePath != NULL) {
184 DevicePath = WorkingDevicePath;
185 }
186 }
187 //
188 // Signal the EVT_SIGNAL_READY_TO_BOOT event
189 //
190 EfiSignalEventReadyToBoot();
191
192
193 //
194 // Set Boot Current
195 //
196 if (IsBootOptionValidNVVarialbe (Option)) {
197 //
198 // For a temporary boot (i.e. a boot by selected a EFI Shell using "Boot From File"), Boot Current is actually not valid.
199 // In this case, "BootCurrent" is not created.
200 // Only create the BootCurrent variable when it points to a valid Boot#### variable.
201 //
202 gRT->SetVariable (
203 L"BootCurrent",
204 &gEfiGlobalVariableGuid,
205 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
206 sizeof (UINT16),
207 &Option->BootCurrent
208 );
209 }
210
211 ASSERT (Option->DevicePath != NULL);
212 if ((DevicePathType (Option->DevicePath) == BBS_DEVICE_PATH) &&
213 (DevicePathSubType (Option->DevicePath) == BBS_BBS_DP)
214 ) {
215 //
216 // Check to see if we should legacy BOOT. If yes then do the legacy boot
217 //
218 return BdsLibDoLegacyBoot (Option);
219 }
220
221 //
222 // If the boot option point to Internal FV shell, make sure it is valid
223 //
224 Status = BdsLibUpdateFvFileDevicePath (&DevicePath, &gEfiShellFileGuid);
225 if (!EFI_ERROR(Status)) {
226 if (Option->DevicePath != NULL) {
227 FreePool(Option->DevicePath);
228 }
229 Option->DevicePath = AllocateZeroPool (GetDevicePathSize (DevicePath));
230 ASSERT(Option->DevicePath != NULL);
231 CopyMem (Option->DevicePath, DevicePath, GetDevicePathSize (DevicePath));
232 //
233 // Update the shell boot option
234 //
235 InitializeListHead (&TempBootLists);
236 BdsLibRegisterNewOption (&TempBootLists, DevicePath, L"EFI Internal Shell", L"BootOrder");
237
238 //
239 // free the temporary device path created by BdsLibUpdateFvFileDevicePath()
240 //
241 FreePool (DevicePath);
242 DevicePath = Option->DevicePath;
243 }
244
245 //
246 // Measure GPT Table by SAP protocol.
247 //
248 Status = gBS->LocateProtocol (
249 &gEfiSecurityArchProtocolGuid,
250 NULL,
251 (VOID**) &SecurityProtocol
252 );
253 if (!EFI_ERROR (Status)) {
254 Status = SecurityProtocol->FileAuthenticationState (SecurityProtocol, 0, DevicePath);
255 }
256
257 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Booting %S\n", Option->Description));
258
259 Status = gBS->LoadImage (
260 TRUE,
261 mBdsImageHandle,
262 DevicePath,
263 NULL,
264 0,
265 &ImageHandle
266 );
267
268 //
269 // If we didn't find an image directly, we need to try as if it is a removable device boot opotion
270 // and load the image according to the default boot behavior for removable device.
271 //
272 if (EFI_ERROR (Status)) {
273 //
274 // check if there is a bootable removable media could be found in this device path ,
275 // and get the bootable media handle
276 //
277 Handle = BdsLibGetBootableHandle(DevicePath);
278 if (Handle == NULL) {
279 goto Done;
280 }
281 //
282 // Load the default boot file \EFI\BOOT\boot{machinename}.EFI from removable Media
283 // machinename is ia32, ia64, x64, ...
284 //
285 FilePath = FileDevicePath (Handle, EFI_REMOVABLE_MEDIA_FILE_NAME);
286 if (FilePath != NULL) {
287 Status = gBS->LoadImage (
288 TRUE,
289 mBdsImageHandle,
290 FilePath,
291 NULL,
292 0,
293 &ImageHandle
294 );
295 if (EFI_ERROR (Status)) {
296 //
297 // The DevicePath failed, and it's not a valid
298 // removable media device.
299 //
300 goto Done;
301 }
302 }
303 }
304
305 if (EFI_ERROR (Status)) {
306 //
307 // It there is any error from the Boot attempt exit now.
308 //
309 goto Done;
310 }
311 //
312 // Provide the image with it's load options
313 //
314 Status = gBS->HandleProtocol (ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &ImageInfo);
315 ASSERT_EFI_ERROR (Status);
316
317 if (Option->LoadOptionsSize != 0) {
318 ImageInfo->LoadOptionsSize = Option->LoadOptionsSize;
319 ImageInfo->LoadOptions = Option->LoadOptions;
320 }
321 //
322 // Before calling the image, enable the Watchdog Timer for
323 // the 5 Minute period
324 //
325 gBS->SetWatchdogTimer (5 * 60, 0x0000, 0x00, NULL);
326
327 Status = gBS->StartImage (ImageHandle, ExitDataSize, ExitData);
328 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Image Return Status = %r\n", Status));
329
330 //
331 // Clear the Watchdog Timer after the image returns
332 //
333 gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL);
334
335 Done:
336 //
337 // Clear Boot Current
338 //
339 gRT->SetVariable (
340 L"BootCurrent",
341 &gEfiGlobalVariableGuid,
342 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
343 0,
344 &Option->BootCurrent
345 );
346
347 return Status;
348 }
349
350
351 /**
352 Expand a device path that starts with a hard drive media device path node to be a
353 full device path that includes the full hardware path to the device. We need
354 to do this so it can be booted. As an optimization the front match (the part point
355 to the partition node. E.g. ACPI() /PCI()/ATA()/Partition() ) is saved in a variable
356 so a connect all is not required on every boot. All successful history device path
357 which point to partition node (the front part) will be saved.
358
359 @param HardDriveDevicePath EFI Device Path to boot, if it starts with a hard
360 drive media device path.
361 @return A Pointer to the full device path or NULL if a valid Hard Drive devic path
362 cannot be found.
363
364 **/
365 EFI_DEVICE_PATH_PROTOCOL *
366 EFIAPI
367 BdsExpandPartitionPartialDevicePathToFull (
368 IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath
369 )
370 {
371 EFI_STATUS Status;
372 UINTN BlockIoHandleCount;
373 EFI_HANDLE *BlockIoBuffer;
374 EFI_DEVICE_PATH_PROTOCOL *FullDevicePath;
375 EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath;
376 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
377 UINTN Index;
378 UINTN InstanceNum;
379 EFI_DEVICE_PATH_PROTOCOL *CachedDevicePath;
380 EFI_DEVICE_PATH_PROTOCOL *TempNewDevicePath;
381 UINTN CachedDevicePathSize;
382 BOOLEAN DeviceExist;
383 BOOLEAN NeedAdjust;
384 EFI_DEVICE_PATH_PROTOCOL *Instance;
385 UINTN Size;
386
387 FullDevicePath = NULL;
388 //
389 // Check if there is prestore 'HDDP' variable.
390 // If exist, search the front path which point to partition node in the variable instants.
391 // If fail to find or 'HDDP' not exist, reconnect all and search in all system
392 //
393 CachedDevicePath = BdsLibGetVariableAndSize (
394 L"HDDP",
395 &mHdBootVariablePrivateGuid,
396 &CachedDevicePathSize
397 );
398
399 if (CachedDevicePath != NULL) {
400 TempNewDevicePath = CachedDevicePath;
401 DeviceExist = FALSE;
402 NeedAdjust = FALSE;
403 do {
404 //
405 // Check every instance of the variable
406 // First, check whether the instance contain the partition node, which is needed for distinguishing multi
407 // partial partition boot option. Second, check whether the instance could be connected.
408 //
409 Instance = GetNextDevicePathInstance (&TempNewDevicePath, &Size);
410 if (MatchPartitionDevicePathNode (Instance, HardDriveDevicePath)) {
411 //
412 // Connect the device path instance, the device path point to hard drive media device path node
413 // e.g. ACPI() /PCI()/ATA()/Partition()
414 //
415 Status = BdsLibConnectDevicePath (Instance);
416 if (!EFI_ERROR (Status)) {
417 DeviceExist = TRUE;
418 break;
419 }
420 }
421 //
422 // Come here means the first instance is not matched
423 //
424 NeedAdjust = TRUE;
425 FreePool(Instance);
426 } while (TempNewDevicePath != NULL);
427
428 if (DeviceExist) {
429 //
430 // Find the matched device path.
431 // Append the file path information from the boot option and return the fully expanded device path.
432 //
433 DevicePath = NextDevicePathNode ((EFI_DEVICE_PATH_PROTOCOL *) HardDriveDevicePath);
434 FullDevicePath = AppendDevicePath (Instance, DevicePath);
435
436 //
437 // Adjust the 'HDDP' instances sequence if the matched one is not first one.
438 //
439 if (NeedAdjust) {
440 //
441 // First delete the matched instance.
442 //
443 TempNewDevicePath = CachedDevicePath;
444 CachedDevicePath = BdsLibDelPartMatchInstance (CachedDevicePath, Instance );
445 FreePool (TempNewDevicePath);
446
447 //
448 // Second, append the remaining path after the matched instance
449 //
450 TempNewDevicePath = CachedDevicePath;
451 CachedDevicePath = AppendDevicePathInstance (Instance, CachedDevicePath );
452 FreePool (TempNewDevicePath);
453 //
454 // Save the matching Device Path so we don't need to do a connect all next time
455 //
456 Status = gRT->SetVariable (
457 L"HDDP",
458 &mHdBootVariablePrivateGuid,
459 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
460 GetDevicePathSize (CachedDevicePath),
461 CachedDevicePath
462 );
463 }
464
465 FreePool (Instance);
466 FreePool (CachedDevicePath);
467 return FullDevicePath;
468 }
469 }
470
471 //
472 // If we get here we fail to find or 'HDDP' not exist, and now we need
473 // to search all devices in the system for a matched partition
474 //
475 BdsLibConnectAllDriversToAllControllers ();
476 Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiBlockIoProtocolGuid, NULL, &BlockIoHandleCount, &BlockIoBuffer);
477 if (EFI_ERROR (Status) || BlockIoHandleCount == 0 || BlockIoBuffer == NULL) {
478 //
479 // If there was an error or there are no device handles that support
480 // the BLOCK_IO Protocol, then return.
481 //
482 return NULL;
483 }
484 //
485 // Loop through all the device handles that support the BLOCK_IO Protocol
486 //
487 for (Index = 0; Index < BlockIoHandleCount; Index++) {
488
489 Status = gBS->HandleProtocol (BlockIoBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID *) &BlockIoDevicePath);
490 if (EFI_ERROR (Status) || BlockIoDevicePath == NULL) {
491 continue;
492 }
493
494 if (MatchPartitionDevicePathNode (BlockIoDevicePath, HardDriveDevicePath)) {
495 //
496 // Find the matched partition device path
497 //
498 DevicePath = NextDevicePathNode ((EFI_DEVICE_PATH_PROTOCOL *) HardDriveDevicePath);
499 FullDevicePath = AppendDevicePath (BlockIoDevicePath, DevicePath);
500
501 //
502 // Save the matched partition device path in 'HDDP' variable
503 //
504 if (CachedDevicePath != NULL) {
505 //
506 // Save the matched partition device path as first instance of 'HDDP' variable
507 //
508 if (BdsLibMatchDevicePaths (CachedDevicePath, BlockIoDevicePath)) {
509 TempNewDevicePath = CachedDevicePath;
510 CachedDevicePath = BdsLibDelPartMatchInstance (CachedDevicePath, BlockIoDevicePath);
511 FreePool(TempNewDevicePath);
512
513 TempNewDevicePath = CachedDevicePath;
514 CachedDevicePath = AppendDevicePathInstance (BlockIoDevicePath, CachedDevicePath);
515 FreePool(TempNewDevicePath);
516 } else {
517 TempNewDevicePath = CachedDevicePath;
518 CachedDevicePath = AppendDevicePathInstance (BlockIoDevicePath, CachedDevicePath);
519 FreePool(TempNewDevicePath);
520 }
521 //
522 // Here limit the device path instance number to 12, which is max number for a system support 3 IDE controller
523 // If the user try to boot many OS in different HDs or partitions, in theory, the 'HDDP' variable maybe become larger and larger.
524 //
525 InstanceNum = 0;
526 ASSERT (CachedDevicePath != NULL);
527 TempNewDevicePath = CachedDevicePath;
528 while (!IsDevicePathEnd (TempNewDevicePath)) {
529 TempNewDevicePath = NextDevicePathNode (TempNewDevicePath);
530 //
531 // Parse one instance
532 //
533 while (!IsDevicePathEndType (TempNewDevicePath)) {
534 TempNewDevicePath = NextDevicePathNode (TempNewDevicePath);
535 }
536 InstanceNum++;
537 //
538 // If the CachedDevicePath variable contain too much instance, only remain 12 instances.
539 //
540 if (InstanceNum >= 12) {
541 SetDevicePathEndNode (TempNewDevicePath);
542 break;
543 }
544 }
545 } else {
546 CachedDevicePath = DuplicateDevicePath (BlockIoDevicePath);
547 }
548
549 //
550 // Save the matching Device Path so we don't need to do a connect all next time
551 //
552 Status = gRT->SetVariable (
553 L"HDDP",
554 &mHdBootVariablePrivateGuid,
555 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
556 GetDevicePathSize (CachedDevicePath),
557 CachedDevicePath
558 );
559
560 break;
561 }
562 }
563
564 FreePool (CachedDevicePath);
565 if (BlockIoBuffer != NULL) {
566 FreePool (BlockIoBuffer);
567 }
568 return FullDevicePath;
569 }
570
571 /**
572 Check whether there is a instance in BlockIoDevicePath, which contain multi device path
573 instances, has the same partition node with HardDriveDevicePath device path
574
575 @param BlockIoDevicePath Multi device path instances which need to check
576 @param HardDriveDevicePath A device path which starts with a hard drive media
577 device path.
578
579 @retval TRUE There is a matched device path instance.
580 @retval FALSE There is no matched device path instance.
581
582 **/
583 BOOLEAN
584 EFIAPI
585 MatchPartitionDevicePathNode (
586 IN EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath,
587 IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath
588 )
589 {
590 HARDDRIVE_DEVICE_PATH *TmpHdPath;
591 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
592 BOOLEAN Match;
593 EFI_DEVICE_PATH_PROTOCOL *BlockIoHdDevicePathNode;
594
595 if ((BlockIoDevicePath == NULL) || (HardDriveDevicePath == NULL)) {
596 return FALSE;
597 }
598
599 //
600 // Make PreviousDevicePath == the device path node before the end node
601 //
602 DevicePath = BlockIoDevicePath;
603 BlockIoHdDevicePathNode = NULL;
604
605 //
606 // find the partition device path node
607 //
608 while (!IsDevicePathEnd (DevicePath)) {
609 if ((DevicePathType (DevicePath) == MEDIA_DEVICE_PATH) &&
610 (DevicePathSubType (DevicePath) == MEDIA_HARDDRIVE_DP)
611 ) {
612 BlockIoHdDevicePathNode = DevicePath;
613 break;
614 }
615
616 DevicePath = NextDevicePathNode (DevicePath);
617 }
618
619 if (BlockIoHdDevicePathNode == NULL) {
620 return FALSE;
621 }
622 //
623 // See if the harddrive device path in blockio matches the orig Hard Drive Node
624 //
625 TmpHdPath = (HARDDRIVE_DEVICE_PATH *) BlockIoHdDevicePathNode;
626 Match = FALSE;
627
628 //
629 // Check for the match
630 //
631 if ((TmpHdPath->MBRType == HardDriveDevicePath->MBRType) &&
632 (TmpHdPath->SignatureType == HardDriveDevicePath->SignatureType)) {
633 switch (TmpHdPath->SignatureType) {
634 case SIGNATURE_TYPE_GUID:
635 Match = CompareGuid ((EFI_GUID *)TmpHdPath->Signature, (EFI_GUID *)HardDriveDevicePath->Signature);
636 break;
637 case SIGNATURE_TYPE_MBR:
638 Match = (BOOLEAN)(*((UINT32 *)(&(TmpHdPath->Signature[0]))) == ReadUnaligned32((UINT32 *)(&(HardDriveDevicePath->Signature[0]))));
639 break;
640 default:
641 Match = FALSE;
642 break;
643 }
644 }
645
646 return Match;
647 }
648
649 /**
650 Delete the boot option associated with the handle passed in.
651
652 @param Handle The handle which present the device path to create
653 boot option
654
655 @retval EFI_SUCCESS Delete the boot option success
656 @retval EFI_NOT_FOUND If the Device Path is not found in the system
657 @retval EFI_OUT_OF_RESOURCES Lack of memory resource
658 @retval Other Error return value from SetVariable()
659
660 **/
661 EFI_STATUS
662 BdsLibDeleteOptionFromHandle (
663 IN EFI_HANDLE Handle
664 )
665 {
666 UINT16 *BootOrder;
667 UINT8 *BootOptionVar;
668 UINTN BootOrderSize;
669 UINTN BootOptionSize;
670 EFI_STATUS Status;
671 UINTN Index;
672 UINT16 BootOption[BOOT_OPTION_MAX_CHAR];
673 UINTN DevicePathSize;
674 UINTN OptionDevicePathSize;
675 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
676 EFI_DEVICE_PATH_PROTOCOL *OptionDevicePath;
677 UINT8 *TempPtr;
678
679 Status = EFI_SUCCESS;
680 BootOrder = NULL;
681 BootOrderSize = 0;
682
683 //
684 // Check "BootOrder" variable, if no, means there is no any boot order.
685 //
686 BootOrder = BdsLibGetVariableAndSize (
687 L"BootOrder",
688 &gEfiGlobalVariableGuid,
689 &BootOrderSize
690 );
691 if (BootOrder == NULL) {
692 return EFI_NOT_FOUND;
693 }
694
695 //
696 // Convert device handle to device path protocol instance
697 //
698 DevicePath = DevicePathFromHandle (Handle);
699 if (DevicePath == NULL) {
700 return EFI_NOT_FOUND;
701 }
702 DevicePathSize = GetDevicePathSize (DevicePath);
703
704 //
705 // Loop all boot order variable and find the matching device path
706 //
707 Index = 0;
708 while (Index < BootOrderSize / sizeof (UINT16)) {
709 UnicodeSPrint (BootOption, sizeof (BootOption), L"Boot%04x", BootOrder[Index]);
710 BootOptionVar = BdsLibGetVariableAndSize (
711 BootOption,
712 &gEfiGlobalVariableGuid,
713 &BootOptionSize
714 );
715
716 if (BootOptionVar == NULL) {
717 FreePool (BootOrder);
718 return EFI_OUT_OF_RESOURCES;
719 }
720
721 TempPtr = BootOptionVar;
722 TempPtr += sizeof (UINT32) + sizeof (UINT16);
723 TempPtr += StrSize ((CHAR16 *) TempPtr);
724 OptionDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) TempPtr;
725 OptionDevicePathSize = GetDevicePathSize (OptionDevicePath);
726
727 //
728 // Check whether the device path match
729 //
730 if ((OptionDevicePathSize == DevicePathSize) &&
731 (CompareMem (DevicePath, OptionDevicePath, DevicePathSize) == 0)) {
732 BdsDeleteBootOption (BootOrder[Index], BootOrder, &BootOrderSize);
733 FreePool (BootOptionVar);
734 break;
735 }
736
737 FreePool (BootOptionVar);
738 Index++;
739 }
740
741 //
742 // Adjust number of boot option for "BootOrder" variable.
743 //
744 Status = gRT->SetVariable (
745 L"BootOrder",
746 &gEfiGlobalVariableGuid,
747 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
748 BootOrderSize,
749 BootOrder
750 );
751
752 FreePool (BootOrder);
753
754 return Status;
755 }
756
757
758 /**
759 Delete all invalid EFI boot options.
760
761 @retval EFI_SUCCESS Delete all invalid boot option success
762 @retval EFI_NOT_FOUND Variable "BootOrder" is not found
763 @retval EFI_OUT_OF_RESOURCES Lack of memory resource
764 @retval Other Error return value from SetVariable()
765
766 **/
767 EFI_STATUS
768 BdsDeleteAllInvalidEfiBootOption (
769 VOID
770 )
771 {
772 UINT16 *BootOrder;
773 UINT8 *BootOptionVar;
774 UINTN BootOrderSize;
775 UINTN BootOptionSize;
776 EFI_STATUS Status;
777 UINTN Index;
778 UINTN Index2;
779 UINT16 BootOption[BOOT_OPTION_MAX_CHAR];
780 EFI_DEVICE_PATH_PROTOCOL *OptionDevicePath;
781 UINT8 *TempPtr;
782 CHAR16 *Description;
783
784 Status = EFI_SUCCESS;
785 BootOrder = NULL;
786 BootOrderSize = 0;
787
788 //
789 // Check "BootOrder" variable firstly, this variable hold the number of boot options
790 //
791 BootOrder = BdsLibGetVariableAndSize (
792 L"BootOrder",
793 &gEfiGlobalVariableGuid,
794 &BootOrderSize
795 );
796 if (NULL == BootOrder) {
797 return EFI_NOT_FOUND;
798 }
799
800 Index = 0;
801 while (Index < BootOrderSize / sizeof (UINT16)) {
802 UnicodeSPrint (BootOption, sizeof (BootOption), L"Boot%04x", BootOrder[Index]);
803 BootOptionVar = BdsLibGetVariableAndSize (
804 BootOption,
805 &gEfiGlobalVariableGuid,
806 &BootOptionSize
807 );
808 if (NULL == BootOptionVar) {
809 FreePool (BootOrder);
810 return EFI_OUT_OF_RESOURCES;
811 }
812
813 TempPtr = BootOptionVar;
814 TempPtr += sizeof (UINT32) + sizeof (UINT16);
815 Description = (CHAR16 *) TempPtr;
816 TempPtr += StrSize ((CHAR16 *) TempPtr);
817 OptionDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) TempPtr;
818
819 //
820 // Skip legacy boot option (BBS boot device)
821 //
822 if ((DevicePathType (OptionDevicePath) == BBS_DEVICE_PATH) &&
823 (DevicePathSubType (OptionDevicePath) == BBS_BBS_DP)) {
824 FreePool (BootOptionVar);
825 Index++;
826 continue;
827 }
828
829 if (!BdsLibIsValidEFIBootOptDevicePathExt (OptionDevicePath, FALSE, Description)) {
830 //
831 // Delete this invalid boot option "Boot####"
832 //
833 Status = gRT->SetVariable (
834 BootOption,
835 &gEfiGlobalVariableGuid,
836 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
837 0,
838 NULL
839 );
840 //
841 // Mark this boot option in boot order as deleted
842 //
843 BootOrder[Index] = 0xffff;
844 }
845
846 FreePool (BootOptionVar);
847 Index++;
848 }
849
850 //
851 // Adjust boot order array
852 //
853 Index2 = 0;
854 for (Index = 0; Index < BootOrderSize / sizeof (UINT16); Index++) {
855 if (BootOrder[Index] != 0xffff) {
856 BootOrder[Index2] = BootOrder[Index];
857 Index2 ++;
858 }
859 }
860 Status = gRT->SetVariable (
861 L"BootOrder",
862 &gEfiGlobalVariableGuid,
863 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
864 Index2 * sizeof (UINT16),
865 BootOrder
866 );
867
868 FreePool (BootOrder);
869
870 return Status;
871 }
872
873
874 /**
875 For EFI boot option, BDS separate them as six types:
876 1. Network - The boot option points to the SimpleNetworkProtocol device.
877 Bds will try to automatically create this type boot option when enumerate.
878 2. Shell - The boot option points to internal flash shell.
879 Bds will try to automatically create this type boot option when enumerate.
880 3. Removable BlockIo - The boot option only points to the removable media
881 device, like USB flash disk, DVD, Floppy etc.
882 These device should contain a *removable* blockIo
883 protocol in their device handle.
884 Bds will try to automatically create this type boot option
885 when enumerate.
886 4. Fixed BlockIo - The boot option only points to a Fixed blockIo device,
887 like HardDisk.
888 These device should contain a *fixed* blockIo
889 protocol in their device handle.
890 BDS will skip fixed blockIo devices, and NOT
891 automatically create boot option for them. But BDS
892 will help to delete those fixed blockIo boot option,
893 whose description rule conflict with other auto-created
894 boot options.
895 5. Non-BlockIo Simplefile - The boot option points to a device whose handle
896 has SimpleFileSystem Protocol, but has no blockio
897 protocol. These devices do not offer blockIo
898 protocol, but BDS still can get the
899 \EFI\BOOT\boot{machinename}.EFI by SimpleFileSystem
900 Protocol.
901 6. File - The boot option points to a file. These boot options are usually
902 created by user manually or OS loader. BDS will not delete or modify
903 these boot options.
904
905 This function will enumerate all possible boot device in the system, and
906 automatically create boot options for Network, Shell, Removable BlockIo,
907 and Non-BlockIo Simplefile devices.
908 It will only excute once of every boot.
909
910 @param BdsBootOptionList The header of the link list which indexed all
911 current boot options
912
913 @retval EFI_SUCCESS Finished all the boot device enumerate and create
914 the boot option base on that boot device
915
916 **/
917 EFI_STATUS
918 EFIAPI
919 BdsLibEnumerateAllBootOption (
920 IN OUT LIST_ENTRY *BdsBootOptionList
921 )
922 {
923 EFI_STATUS Status;
924 UINT16 FloppyNumber;
925 UINT16 CdromNumber;
926 UINT16 UsbNumber;
927 UINT16 MiscNumber;
928 UINT16 NonBlockNumber;
929 UINTN NumberBlockIoHandles;
930 EFI_HANDLE *BlockIoHandles;
931 EFI_BLOCK_IO_PROTOCOL *BlkIo;
932 UINTN Index;
933 UINTN NumberSimpleNetworkHandles;
934 EFI_HANDLE *SimpleNetworkHandles;
935 UINTN FvHandleCount;
936 EFI_HANDLE *FvHandleBuffer;
937 EFI_FV_FILETYPE Type;
938 UINTN Size;
939 EFI_FV_FILE_ATTRIBUTES Attributes;
940 UINT32 AuthenticationStatus;
941 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
942 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
943 UINTN DevicePathType;
944 CHAR16 Buffer[40];
945 EFI_HANDLE *FileSystemHandles;
946 UINTN NumberFileSystemHandles;
947 BOOLEAN NeedDelete;
948 EFI_IMAGE_DOS_HEADER DosHeader;
949 EFI_IMAGE_OPTIONAL_HEADER_UNION HdrData;
950 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
951
952 FloppyNumber = 0;
953 CdromNumber = 0;
954 UsbNumber = 0;
955 MiscNumber = 0;
956 ZeroMem (Buffer, sizeof (Buffer));
957
958 //
959 // If the boot device enumerate happened, just get the boot
960 // device from the boot order variable
961 //
962 if (mEnumBootDevice) {
963 BdsLibBuildOptionFromVar (BdsBootOptionList, L"BootOrder");
964 return EFI_SUCCESS;
965 }
966
967 //
968 // Notes: this dirty code is to get the legacy boot option from the
969 // BBS table and create to variable as the EFI boot option, it should
970 // be removed after the CSM can provide legacy boot option directly
971 //
972 REFRESH_LEGACY_BOOT_OPTIONS;
973
974 //
975 // Delete invalid boot option
976 //
977 BdsDeleteAllInvalidEfiBootOption ();
978
979 //
980 // Parse removable media
981 //
982 gBS->LocateHandleBuffer (
983 ByProtocol,
984 &gEfiBlockIoProtocolGuid,
985 NULL,
986 &NumberBlockIoHandles,
987 &BlockIoHandles
988 );
989
990 for (Index = 0; Index < NumberBlockIoHandles; Index++) {
991 Status = gBS->HandleProtocol (
992 BlockIoHandles[Index],
993 &gEfiBlockIoProtocolGuid,
994 (VOID **) &BlkIo
995 );
996 if (!EFI_ERROR (Status)) {
997 if (!BlkIo->Media->RemovableMedia) {
998 //
999 // skip the non-removable block devices
1000 //
1001 continue;
1002 }
1003 }
1004 DevicePath = DevicePathFromHandle (BlockIoHandles[Index]);
1005 DevicePathType = BdsGetBootTypeFromDevicePath (DevicePath);
1006
1007 switch (DevicePathType) {
1008 case BDS_EFI_ACPI_FLOPPY_BOOT:
1009 if (FloppyNumber == 0) {
1010 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_FLOPPY);
1011 } else {
1012 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_FLOPPY_NUM, FloppyNumber);
1013 }
1014 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1015 FloppyNumber++;
1016 break;
1017
1018 //
1019 // Assume a removable SATA device should be the DVD/CD device
1020 //
1021 case BDS_EFI_MESSAGE_ATAPI_BOOT:
1022 case BDS_EFI_MESSAGE_SATA_BOOT:
1023 if (CdromNumber == 0) {
1024 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_DVD);
1025 } else {
1026 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_DVD_NUM, CdromNumber);
1027 }
1028 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1029 CdromNumber++;
1030 break;
1031
1032 case BDS_EFI_MESSAGE_USB_DEVICE_BOOT:
1033 if (UsbNumber == 0) {
1034 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_USB);
1035 } else {
1036 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_USB_NUM, UsbNumber);
1037 }
1038 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1039 UsbNumber++;
1040 break;
1041
1042 case BDS_EFI_MESSAGE_SCSI_BOOT:
1043 if (UsbNumber == 0) {
1044 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_SCSI);
1045 } else {
1046 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_SCSI_NUM, UsbNumber);
1047 }
1048 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1049 UsbNumber++;
1050 break;
1051
1052 case BDS_EFI_MESSAGE_MISC_BOOT:
1053 if (MiscNumber == 0) {
1054 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_MISC);
1055 } else {
1056 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_MISC_NUM, MiscNumber);
1057 }
1058 BdsLibBuildOptionFromHandle (BlockIoHandles[Index], BdsBootOptionList, Buffer);
1059 MiscNumber++;
1060 break;
1061
1062 default:
1063 break;
1064 }
1065 }
1066
1067 if (NumberBlockIoHandles != 0) {
1068 FreePool (BlockIoHandles);
1069 }
1070
1071 //
1072 // If there is simple file protocol which does not consume block Io protocol, create a boot option for it here.
1073 //
1074 NonBlockNumber = 0;
1075 gBS->LocateHandleBuffer (
1076 ByProtocol,
1077 &gEfiSimpleFileSystemProtocolGuid,
1078 NULL,
1079 &NumberFileSystemHandles,
1080 &FileSystemHandles
1081 );
1082 for (Index = 0; Index < NumberFileSystemHandles; Index++) {
1083 Status = gBS->HandleProtocol (
1084 FileSystemHandles[Index],
1085 &gEfiBlockIoProtocolGuid,
1086 (VOID **) &BlkIo
1087 );
1088 if (!EFI_ERROR (Status)) {
1089 //
1090 // Skip if the file system handle supports a BlkIo protocol,
1091 //
1092 continue;
1093 }
1094
1095 //
1096 // Do the removable Media thing. \EFI\BOOT\boot{machinename}.EFI
1097 // machinename is ia32, ia64, x64, ...
1098 //
1099 Hdr.Union = &HdrData;
1100 NeedDelete = TRUE;
1101 Status = BdsLibGetImageHeader (
1102 FileSystemHandles[Index],
1103 EFI_REMOVABLE_MEDIA_FILE_NAME,
1104 &DosHeader,
1105 Hdr
1106 );
1107 if (!EFI_ERROR (Status) &&
1108 EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Hdr.Pe32->FileHeader.Machine) &&
1109 Hdr.Pe32->OptionalHeader.Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {
1110 NeedDelete = FALSE;
1111 }
1112
1113 if (NeedDelete) {
1114 //
1115 // No such file or the file is not a EFI application, delete this boot option
1116 //
1117 BdsLibDeleteOptionFromHandle (FileSystemHandles[Index]);
1118 } else {
1119 if (NonBlockNumber == 0) {
1120 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_NON_BLOCK);
1121 } else {
1122 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_NON_BLOCK_NUM, NonBlockNumber);
1123 }
1124 BdsLibBuildOptionFromHandle (FileSystemHandles[Index], BdsBootOptionList, Buffer);
1125 NonBlockNumber++;
1126 }
1127 }
1128
1129 if (NumberFileSystemHandles != 0) {
1130 FreePool (FileSystemHandles);
1131 }
1132
1133 //
1134 // Parse Network Boot Device
1135 //
1136 gBS->LocateHandleBuffer (
1137 ByProtocol,
1138 &gEfiSimpleNetworkProtocolGuid,
1139 NULL,
1140 &NumberSimpleNetworkHandles,
1141 &SimpleNetworkHandles
1142 );
1143 for (Index = 0; Index < NumberSimpleNetworkHandles; Index++) {
1144 if (Index == 0) {
1145 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_NETWORK);
1146 } else {
1147 UnicodeSPrint (Buffer, sizeof (Buffer), DESCRIPTION_NETWORK_NUM, Index);
1148 }
1149 BdsLibBuildOptionFromHandle (SimpleNetworkHandles[Index], BdsBootOptionList, Buffer);
1150 }
1151
1152 if (NumberSimpleNetworkHandles != 0) {
1153 FreePool (SimpleNetworkHandles);
1154 }
1155
1156 //
1157 // Check if we have on flash shell
1158 //
1159 gBS->LocateHandleBuffer (
1160 ByProtocol,
1161 &gEfiFirmwareVolume2ProtocolGuid,
1162 NULL,
1163 &FvHandleCount,
1164 &FvHandleBuffer
1165 );
1166 for (Index = 0; Index < FvHandleCount; Index++) {
1167 gBS->HandleProtocol (
1168 FvHandleBuffer[Index],
1169 &gEfiFirmwareVolume2ProtocolGuid,
1170 (VOID **) &Fv
1171 );
1172
1173 Status = Fv->ReadFile (
1174 Fv,
1175 &gEfiShellFileGuid,
1176 NULL,
1177 &Size,
1178 &Type,
1179 &Attributes,
1180 &AuthenticationStatus
1181 );
1182 if (EFI_ERROR (Status)) {
1183 //
1184 // Skip if no shell file in the FV
1185 //
1186 continue;
1187 }
1188 //
1189 // Build the shell boot option
1190 //
1191 BdsLibBuildOptionFromShell (FvHandleBuffer[Index], BdsBootOptionList);
1192 }
1193
1194 if (FvHandleCount != 0) {
1195 FreePool (FvHandleBuffer);
1196 }
1197 //
1198 // Make sure every boot only have one time
1199 // boot device enumerate
1200 //
1201 BdsLibBuildOptionFromVar (BdsBootOptionList, L"BootOrder");
1202 mEnumBootDevice = TRUE;
1203
1204 return EFI_SUCCESS;
1205 }
1206
1207 /**
1208 Build the boot option with the handle parsed in
1209
1210 @param Handle The handle which present the device path to create
1211 boot option
1212 @param BdsBootOptionList The header of the link list which indexed all
1213 current boot options
1214 @param String The description of the boot option.
1215
1216 **/
1217 VOID
1218 EFIAPI
1219 BdsLibBuildOptionFromHandle (
1220 IN EFI_HANDLE Handle,
1221 IN LIST_ENTRY *BdsBootOptionList,
1222 IN CHAR16 *String
1223 )
1224 {
1225 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1226
1227 DevicePath = DevicePathFromHandle (Handle);
1228
1229 //
1230 // Create and register new boot option
1231 //
1232 BdsLibRegisterNewOption (BdsBootOptionList, DevicePath, String, L"BootOrder");
1233 }
1234
1235
1236 /**
1237 Build the on flash shell boot option with the handle parsed in.
1238
1239 @param Handle The handle which present the device path to create
1240 on flash shell boot option
1241 @param BdsBootOptionList The header of the link list which indexed all
1242 current boot options
1243
1244 **/
1245 VOID
1246 EFIAPI
1247 BdsLibBuildOptionFromShell (
1248 IN EFI_HANDLE Handle,
1249 IN OUT LIST_ENTRY *BdsBootOptionList
1250 )
1251 {
1252 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1253 MEDIA_FW_VOL_FILEPATH_DEVICE_PATH ShellNode;
1254
1255 DevicePath = DevicePathFromHandle (Handle);
1256
1257 //
1258 // Build the shell device path
1259 //
1260 EfiInitializeFwVolDevicepathNode (&ShellNode, &gEfiShellFileGuid);
1261
1262 DevicePath = AppendDevicePathNode (DevicePath, (EFI_DEVICE_PATH_PROTOCOL *) &ShellNode);
1263
1264 //
1265 // Create and register the shell boot option
1266 //
1267 BdsLibRegisterNewOption (BdsBootOptionList, DevicePath, L"EFI Internal Shell", L"BootOrder");
1268
1269 }
1270
1271 /**
1272 Boot from the UEFI spec defined "BootNext" variable.
1273
1274 **/
1275 VOID
1276 EFIAPI
1277 BdsLibBootNext (
1278 VOID
1279 )
1280 {
1281 UINT16 *BootNext;
1282 UINTN BootNextSize;
1283 CHAR16 Buffer[20];
1284 BDS_COMMON_OPTION *BootOption;
1285 LIST_ENTRY TempList;
1286 UINTN ExitDataSize;
1287 CHAR16 *ExitData;
1288
1289 //
1290 // Init the boot option name buffer and temp link list
1291 //
1292 InitializeListHead (&TempList);
1293 ZeroMem (Buffer, sizeof (Buffer));
1294
1295 BootNext = BdsLibGetVariableAndSize (
1296 L"BootNext",
1297 &gEfiGlobalVariableGuid,
1298 &BootNextSize
1299 );
1300
1301 //
1302 // Clear the boot next variable first
1303 //
1304 if (BootNext != NULL) {
1305 gRT->SetVariable (
1306 L"BootNext",
1307 &gEfiGlobalVariableGuid,
1308 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1309 0,
1310 BootNext
1311 );
1312
1313 //
1314 // Start to build the boot option and try to boot
1315 //
1316 UnicodeSPrint (Buffer, sizeof (Buffer), L"Boot%04x", *BootNext);
1317 BootOption = BdsLibVariableToOption (&TempList, Buffer);
1318 ASSERT (BootOption != NULL);
1319 BdsLibConnectDevicePath (BootOption->DevicePath);
1320 BdsLibBootViaBootOption (BootOption, BootOption->DevicePath, &ExitDataSize, &ExitData);
1321 }
1322
1323 }
1324
1325 /**
1326 Return the bootable media handle.
1327 First, check the device is connected
1328 Second, check whether the device path point to a device which support SimpleFileSystemProtocol,
1329 Third, detect the the default boot file in the Media, and return the removable Media handle.
1330
1331 @param DevicePath Device Path to a bootable device
1332
1333 @retval NULL The media on the DevicePath is not bootable
1334
1335 **/
1336 EFI_HANDLE
1337 EFIAPI
1338 BdsLibGetBootableHandle (
1339 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
1340 )
1341 {
1342 EFI_STATUS Status;
1343 EFI_DEVICE_PATH_PROTOCOL *UpdatedDevicePath;
1344 EFI_DEVICE_PATH_PROTOCOL *DupDevicePath;
1345 EFI_HANDLE Handle;
1346 EFI_BLOCK_IO_PROTOCOL *BlockIo;
1347 VOID *Buffer;
1348 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
1349 UINTN Size;
1350 UINTN TempSize;
1351 EFI_HANDLE ReturnHandle;
1352 EFI_HANDLE *SimpleFileSystemHandles;
1353
1354 UINTN NumberSimpleFileSystemHandles;
1355 UINTN Index;
1356 EFI_IMAGE_DOS_HEADER DosHeader;
1357 EFI_IMAGE_OPTIONAL_HEADER_UNION HdrData;
1358 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
1359
1360 UpdatedDevicePath = DevicePath;
1361
1362 //
1363 // Check whether the device is connected
1364 //
1365 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &UpdatedDevicePath, &Handle);
1366 if (EFI_ERROR (Status)) {
1367 //
1368 // Skip the case that the boot option point to a simple file protocol which does not consume block Io protocol,
1369 //
1370 Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &UpdatedDevicePath, &Handle);
1371 if (EFI_ERROR (Status)) {
1372 //
1373 // Fail to find the proper BlockIo and simple file protocol, maybe because device not present, we need to connect it firstly
1374 //
1375 UpdatedDevicePath = DevicePath;
1376 Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &UpdatedDevicePath, &Handle);
1377 gBS->ConnectController (Handle, NULL, NULL, TRUE);
1378 }
1379 } else {
1380 //
1381 // Get BlockIo protocol and check removable attribute
1382 //
1383 Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo);
1384 //
1385 // Issue a dummy read to the device to check for media change.
1386 // When the removable media is changed, any Block IO read/write will
1387 // cause the BlockIo protocol be reinstalled and EFI_MEDIA_CHANGED is
1388 // returned. After the Block IO protocol is reinstalled, subsequent
1389 // Block IO read/write will success.
1390 //
1391 Buffer = AllocatePool (BlockIo->Media->BlockSize);
1392 if (Buffer != NULL) {
1393 BlockIo->ReadBlocks (
1394 BlockIo,
1395 BlockIo->Media->MediaId,
1396 0,
1397 BlockIo->Media->BlockSize,
1398 Buffer
1399 );
1400 FreePool(Buffer);
1401 }
1402 }
1403
1404 //
1405 // Detect the the default boot file from removable Media
1406 //
1407
1408 //
1409 // 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
1410 // Try to locate the USB node device path first, if fail then use its previous PCI node to search
1411 //
1412 DupDevicePath = DuplicateDevicePath (DevicePath);
1413 ASSERT (DupDevicePath != NULL);
1414
1415 UpdatedDevicePath = DupDevicePath;
1416 Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &UpdatedDevicePath, &Handle);
1417 //
1418 // 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
1419 // Acpi()/Pci()/Usb() --> Acpi()/Pci()
1420 //
1421 if ((DevicePathType (UpdatedDevicePath) == MESSAGING_DEVICE_PATH) &&
1422 (DevicePathSubType (UpdatedDevicePath) == MSG_USB_DP)) {
1423 //
1424 // Remove the usb node, let the device path only point to PCI node
1425 //
1426 SetDevicePathEndNode (UpdatedDevicePath);
1427 UpdatedDevicePath = DupDevicePath;
1428 } else {
1429 UpdatedDevicePath = DevicePath;
1430 }
1431
1432 //
1433 // Get the device path size of boot option
1434 //
1435 Size = GetDevicePathSize(UpdatedDevicePath) - sizeof (EFI_DEVICE_PATH_PROTOCOL); // minus the end node
1436 ReturnHandle = NULL;
1437 gBS->LocateHandleBuffer (
1438 ByProtocol,
1439 &gEfiSimpleFileSystemProtocolGuid,
1440 NULL,
1441 &NumberSimpleFileSystemHandles,
1442 &SimpleFileSystemHandles
1443 );
1444 for (Index = 0; Index < NumberSimpleFileSystemHandles; Index++) {
1445 //
1446 // Get the device path size of SimpleFileSystem handle
1447 //
1448 TempDevicePath = DevicePathFromHandle (SimpleFileSystemHandles[Index]);
1449 TempSize = GetDevicePathSize (TempDevicePath)- sizeof (EFI_DEVICE_PATH_PROTOCOL); // minus the end node
1450 //
1451 // Check whether the device path of boot option is part of the SimpleFileSystem handle's device path
1452 //
1453 if (Size <= TempSize && CompareMem (TempDevicePath, UpdatedDevicePath, Size)==0) {
1454 //
1455 // Load the default boot file \EFI\BOOT\boot{machinename}.EFI from removable Media
1456 // machinename is ia32, ia64, x64, ...
1457 //
1458 Hdr.Union = &HdrData;
1459 Status = BdsLibGetImageHeader (
1460 SimpleFileSystemHandles[Index],
1461 EFI_REMOVABLE_MEDIA_FILE_NAME,
1462 &DosHeader,
1463 Hdr
1464 );
1465 if (!EFI_ERROR (Status) &&
1466 EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Hdr.Pe32->FileHeader.Machine) &&
1467 Hdr.Pe32->OptionalHeader.Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {
1468 ReturnHandle = SimpleFileSystemHandles[Index];
1469 break;
1470 }
1471 }
1472 }
1473
1474 FreePool(DupDevicePath);
1475
1476 if (SimpleFileSystemHandles != NULL) {
1477 FreePool(SimpleFileSystemHandles);
1478 }
1479
1480 return ReturnHandle;
1481 }
1482
1483 /**
1484 Check to see if the network cable is plugged in. If the DevicePath is not
1485 connected it will be connected.
1486
1487 @param DevicePath Device Path to check
1488
1489 @retval TRUE DevicePath points to an Network that is connected
1490 @retval FALSE DevicePath does not point to a bootable network
1491
1492 **/
1493 BOOLEAN
1494 BdsLibNetworkBootWithMediaPresent (
1495 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
1496 )
1497 {
1498 EFI_STATUS Status;
1499 EFI_DEVICE_PATH_PROTOCOL *UpdatedDevicePath;
1500 EFI_HANDLE Handle;
1501 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
1502 BOOLEAN MediaPresent;
1503
1504 MediaPresent = FALSE;
1505
1506 UpdatedDevicePath = DevicePath;
1507 Status = gBS->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid, &UpdatedDevicePath, &Handle);
1508 if (EFI_ERROR (Status)) {
1509 //
1510 // Device not present so see if we need to connect it
1511 //
1512 Status = BdsLibConnectDevicePath (DevicePath);
1513 if (!EFI_ERROR (Status)) {
1514 //
1515 // This one should work after we did the connect
1516 //
1517 Status = gBS->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid, &UpdatedDevicePath, &Handle);
1518 }
1519 }
1520
1521 if (!EFI_ERROR (Status)) {
1522 Status = gBS->HandleProtocol (Handle, &gEfiSimpleNetworkProtocolGuid, (VOID **)&Snp);
1523 if (!EFI_ERROR (Status)) {
1524 if (Snp->Mode->MediaPresentSupported) {
1525 if (Snp->Mode->State == EfiSimpleNetworkInitialized) {
1526 //
1527 // In case some one else is using the SNP check to see if it's connected
1528 //
1529 MediaPresent = Snp->Mode->MediaPresent;
1530 } else {
1531 //
1532 // No one is using SNP so we need to Start and Initialize so
1533 // MediaPresent will be valid.
1534 //
1535 Status = Snp->Start (Snp);
1536 if (!EFI_ERROR (Status)) {
1537 Status = Snp->Initialize (Snp, 0, 0);
1538 if (!EFI_ERROR (Status)) {
1539 MediaPresent = Snp->Mode->MediaPresent;
1540 Snp->Shutdown (Snp);
1541 }
1542 Snp->Stop (Snp);
1543 }
1544 }
1545 } else {
1546 MediaPresent = TRUE;
1547 }
1548 }
1549 }
1550
1551 return MediaPresent;
1552 }
1553
1554 /**
1555 For a bootable Device path, return its boot type.
1556
1557 @param DevicePath The bootable device Path to check
1558
1559 @retval BDS_EFI_MEDIA_HD_BOOT If the device path contains any media device path node, it is media boot type
1560 For the floppy node, handle it as media node
1561 @retval BDS_EFI_MEDIA_CDROM_BOOT If the device path contains any media device path node, it is media boot type
1562 For the floppy node, handle it as media node
1563 @retval BDS_EFI_ACPI_FLOPPY_BOOT If the device path contains any media device path node, it is media boot type
1564 For the floppy node, handle it as media node
1565 @retval BDS_EFI_MESSAGE_ATAPI_BOOT If the device path not contains any media device path node, and
1566 its last device path node point to a message device path node, it is
1567
1568 @retval BDS_EFI_MESSAGE_SCSI_BOOT If the device path not contains any media device path node, and
1569 its last device path node point to a message device path node, it is
1570 @retval BDS_EFI_MESSAGE_USB_DEVICE_BOOT If the device path not contains any media device path node, and
1571 its last device path node point to a message device path node, it is
1572 @retval BDS_EFI_MESSAGE_MISC_BOOT If the device path not contains any media device path node, and
1573 its last device path node point to a message device path node, it is
1574 @retval BDS_LEGACY_BBS_BOOT Legacy boot type
1575 @retval BDS_EFI_UNSUPPORT An EFI Removable BlockIO device path not point to a media and message device,
1576
1577 **/
1578 UINT32
1579 EFIAPI
1580 BdsGetBootTypeFromDevicePath (
1581 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
1582 )
1583 {
1584 ACPI_HID_DEVICE_PATH *Acpi;
1585 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
1586 EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
1587
1588
1589 if (NULL == DevicePath) {
1590 return BDS_EFI_UNSUPPORT;
1591 }
1592
1593 TempDevicePath = DevicePath;
1594
1595 while (!IsDevicePathEndType (TempDevicePath)) {
1596 switch (DevicePathType (TempDevicePath)) {
1597 case BBS_DEVICE_PATH:
1598 return BDS_LEGACY_BBS_BOOT;
1599 case MEDIA_DEVICE_PATH:
1600 if (DevicePathSubType (TempDevicePath) == MEDIA_HARDDRIVE_DP) {
1601 return BDS_EFI_MEDIA_HD_BOOT;
1602 } else if (DevicePathSubType (TempDevicePath) == MEDIA_CDROM_DP) {
1603 return BDS_EFI_MEDIA_CDROM_BOOT;
1604 }
1605 break;
1606 case ACPI_DEVICE_PATH:
1607 Acpi = (ACPI_HID_DEVICE_PATH *) TempDevicePath;
1608 if (EISA_ID_TO_NUM (Acpi->HID) == 0x0604) {
1609 return BDS_EFI_ACPI_FLOPPY_BOOT;
1610 }
1611 break;
1612 case MESSAGING_DEVICE_PATH:
1613 //
1614 // Get the last device path node
1615 //
1616 LastDeviceNode = NextDevicePathNode (TempDevicePath);
1617 if (DevicePathSubType(LastDeviceNode) == MSG_DEVICE_LOGICAL_UNIT_DP) {
1618 //
1619 // if the next node type is Device Logical Unit, which specify the Logical Unit Number (LUN),
1620 // skit it
1621 //
1622 LastDeviceNode = NextDevicePathNode (LastDeviceNode);
1623 }
1624 //
1625 // if the device path not only point to driver device, it is not a messaging device path,
1626 //
1627 if (!IsDevicePathEndType (LastDeviceNode)) {
1628 break;
1629 }
1630
1631 if (DevicePathSubType(TempDevicePath) == MSG_ATAPI_DP) {
1632 return BDS_EFI_MESSAGE_ATAPI_BOOT;
1633 } else if (DevicePathSubType(TempDevicePath) == MSG_USB_DP) {
1634 return BDS_EFI_MESSAGE_USB_DEVICE_BOOT;
1635 } else if (DevicePathSubType(TempDevicePath) == MSG_SCSI_DP) {
1636 return BDS_EFI_MESSAGE_SCSI_BOOT;
1637 } else if (DevicePathSubType(TempDevicePath) == MSG_SATA_DP) {
1638 return BDS_EFI_MESSAGE_SATA_BOOT;
1639 }
1640 return BDS_EFI_MESSAGE_MISC_BOOT;
1641 default:
1642 break;
1643 }
1644 TempDevicePath = NextDevicePathNode (TempDevicePath);
1645 }
1646
1647 return BDS_EFI_UNSUPPORT;
1648 }
1649
1650
1651 /**
1652 Check whether the descriptionis is conflict with the description reserved for
1653 auto-created boot options.
1654
1655 @param Description The Description in a boot option
1656
1657 @retval TRUE The description is conflict with the description reserved for
1658 auto-created boot options.
1659 @retval FALSE The description is not conflict with the description reserved.
1660
1661 **/
1662 BOOLEAN
1663 EFIAPI
1664 CheckDescritptionConflict (
1665 IN CHAR16 *Description
1666 )
1667 {
1668 if (Description == NULL) {
1669 return FALSE;
1670 }
1671 if ((CompareMem (Description, DESCRIPTION_FLOPPY, StrLen (DESCRIPTION_FLOPPY) * sizeof (CHAR16)) == 0) ||
1672 (CompareMem (Description, DESCRIPTION_DVD, StrLen (DESCRIPTION_DVD) * sizeof (CHAR16)) == 0) ||
1673 (CompareMem (Description, DESCRIPTION_USB, StrLen (DESCRIPTION_USB) * sizeof (CHAR16)) == 0) ||
1674 (CompareMem (Description, DESCRIPTION_SCSI, StrLen (DESCRIPTION_SCSI) * sizeof (CHAR16)) == 0) ||
1675 (CompareMem (Description, DESCRIPTION_MISC, StrLen (DESCRIPTION_MISC) * sizeof (CHAR16)) == 0) ||
1676 (CompareMem (Description, DESCRIPTION_NETWORK, StrLen (DESCRIPTION_NETWORK) * sizeof (CHAR16)) == 0)||
1677 (CompareMem (Description, DESCRIPTION_NON_BLOCK, StrLen (DESCRIPTION_NON_BLOCK) * sizeof (CHAR16)) == 0)) {
1678 return TRUE;
1679 }
1680
1681 return FALSE;
1682 }
1683
1684
1685 /**
1686 Check whether the Device path in a boot option point to a valid bootable device,
1687 And if CheckMedia is true, check the device is ready to boot now.
1688
1689 @param DevPath the Device path in a boot option
1690 @param CheckMedia if true, check the device is ready to boot now.
1691
1692 @retval TRUE the Device path is valid
1693 @retval FALSE the Device path is invalid .
1694
1695 **/
1696 BOOLEAN
1697 EFIAPI
1698 BdsLibIsValidEFIBootOptDevicePath (
1699 IN EFI_DEVICE_PATH_PROTOCOL *DevPath,
1700 IN BOOLEAN CheckMedia
1701 )
1702 {
1703 return BdsLibIsValidEFIBootOptDevicePathExt (DevPath, CheckMedia, NULL);
1704 }
1705
1706 /**
1707 Check whether the Device path in a boot option point to a valid bootable device,
1708 And if CheckMedia is true, check the device is ready to boot now.
1709 If Description is not NULL and the device path point to a fixed BlockIo
1710 device, check the description whether conflict with other auto-created
1711 boot options.
1712
1713 @param DevPath the Device path in a boot option
1714 @param CheckMedia if true, check the device is ready to boot now.
1715 @param Description the description in a boot option
1716
1717 @retval TRUE the Device path is valid
1718 @retval FALSE the Device path is invalid .
1719
1720 **/
1721 BOOLEAN
1722 EFIAPI
1723 BdsLibIsValidEFIBootOptDevicePathExt (
1724 IN EFI_DEVICE_PATH_PROTOCOL *DevPath,
1725 IN BOOLEAN CheckMedia,
1726 IN CHAR16 *Description
1727 )
1728 {
1729 EFI_STATUS Status;
1730 EFI_HANDLE Handle;
1731 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
1732 EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
1733 EFI_BLOCK_IO_PROTOCOL *BlockIo;
1734
1735 TempDevicePath = DevPath;
1736 LastDeviceNode = DevPath;
1737
1738 //
1739 // Check if it's a valid boot option for network boot device
1740 // Only check if there is SimpleNetworkProtocol installed. If yes, that means
1741 // there is the network card there.
1742 //
1743 Status = gBS->LocateDevicePath (
1744 &gEfiSimpleNetworkProtocolGuid,
1745 &TempDevicePath,
1746 &Handle
1747 );
1748 if (EFI_ERROR (Status)) {
1749 //
1750 // Device not present so see if we need to connect it
1751 //
1752 TempDevicePath = DevPath;
1753 BdsLibConnectDevicePath (TempDevicePath);
1754 Status = gBS->LocateDevicePath (
1755 &gEfiSimpleNetworkProtocolGuid,
1756 &TempDevicePath,
1757 &Handle
1758 );
1759 }
1760
1761 if (!EFI_ERROR (Status)) {
1762 if (CheckMedia) {
1763 //
1764 // Test if it is ready to boot now
1765 //
1766 if (BdsLibNetworkBootWithMediaPresent(DevPath)) {
1767 return TRUE;
1768 }
1769 } else {
1770 return TRUE;
1771 }
1772 }
1773
1774 //
1775 // If the boot option point to a file, it is a valid EFI boot option,
1776 // and assume it is ready to boot now
1777 //
1778 while (!IsDevicePathEnd (TempDevicePath)) {
1779 LastDeviceNode = TempDevicePath;
1780 TempDevicePath = NextDevicePathNode (TempDevicePath);
1781 }
1782 if ((DevicePathType (LastDeviceNode) == MEDIA_DEVICE_PATH) &&
1783 (DevicePathSubType (LastDeviceNode) == MEDIA_FILEPATH_DP)) {
1784 return TRUE;
1785 }
1786
1787 //
1788 // Check if it's a valid boot option for internal Shell
1789 //
1790 if (EfiGetNameGuidFromFwVolDevicePathNode ((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LastDeviceNode) != NULL) {
1791 //
1792 // If the boot option point to Internal FV shell, make sure it is valid
1793 //
1794 TempDevicePath = DevPath;
1795 Status = BdsLibUpdateFvFileDevicePath (&TempDevicePath, &gEfiShellFileGuid);
1796 if (Status == EFI_ALREADY_STARTED) {
1797 return TRUE;
1798 } else {
1799 if (Status == EFI_SUCCESS) {
1800 FreePool (TempDevicePath);
1801 }
1802 return FALSE;
1803 }
1804 }
1805
1806 //
1807 // If the boot option point to a blockIO device:
1808 // if it is a removable blockIo device, it is valid.
1809 // if it is a fixed blockIo device, check its description confliction.
1810 //
1811 TempDevicePath = DevPath;
1812 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &TempDevicePath, &Handle);
1813 if (EFI_ERROR (Status)) {
1814 //
1815 // Device not present so see if we need to connect it
1816 //
1817 Status = BdsLibConnectDevicePath (DevPath);
1818 if (!EFI_ERROR (Status)) {
1819 //
1820 // Try again to get the Block Io protocol after we did the connect
1821 //
1822 TempDevicePath = DevPath;
1823 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &TempDevicePath, &Handle);
1824 }
1825 }
1826
1827 if (!EFI_ERROR (Status)) {
1828 Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo);
1829 if (!EFI_ERROR (Status)) {
1830 if (!BlockIo->Media->RemovableMedia) {
1831 //
1832 // For the Fixed block devices, check its description whether conflict
1833 // with other auto-created boot options. BDS permit a boot option point to
1834 // Fixed block device, but not permit it use the description reserved for
1835 // auto-created boot options.
1836 // The check is to cover the bug, that replace a removable BlockIo device
1837 // with a fixed BlockIo device at the same port, but the removable device's
1838 // boot option can not be automatically deleted.
1839 //
1840 if (CheckDescritptionConflict (Description)) {
1841 return FALSE;
1842 }
1843 }
1844 if (CheckMedia) {
1845 //
1846 // Test if it is ready to boot now
1847 //
1848 if (BdsLibGetBootableHandle (DevPath) != NULL) {
1849 return TRUE;
1850 }
1851 } else {
1852 return TRUE;
1853 }
1854 }
1855 } else {
1856 //
1857 // 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,
1858 //
1859 Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &TempDevicePath, &Handle);
1860 if (!EFI_ERROR (Status)) {
1861 if (CheckMedia) {
1862 //
1863 // Test if it is ready to boot now
1864 //
1865 if (BdsLibGetBootableHandle (DevPath) != NULL) {
1866 return TRUE;
1867 }
1868 } else {
1869 return TRUE;
1870 }
1871 }
1872 }
1873
1874 return FALSE;
1875 }
1876
1877
1878 /**
1879 According to a file guild, check a Fv file device path is valid. If it is invalid,
1880 try to return the valid device path.
1881 FV address maybe changes for memory layout adjust from time to time, use this function
1882 could promise the Fv file device path is right.
1883
1884 @param DevicePath on input, the Fv file device path need to check on
1885 output, the updated valid Fv file device path
1886 @param FileGuid the Fv file guild
1887
1888 @retval EFI_INVALID_PARAMETER the input DevicePath or FileGuid is invalid
1889 parameter
1890 @retval EFI_UNSUPPORTED the input DevicePath does not contain Fv file
1891 guild at all
1892 @retval EFI_ALREADY_STARTED the input DevicePath has pointed to Fv file, it is
1893 valid
1894 @retval EFI_SUCCESS has successfully updated the invalid DevicePath,
1895 and return the updated device path in DevicePath
1896
1897 **/
1898 EFI_STATUS
1899 EFIAPI
1900 BdsLibUpdateFvFileDevicePath (
1901 IN OUT EFI_DEVICE_PATH_PROTOCOL ** DevicePath,
1902 IN EFI_GUID *FileGuid
1903 )
1904 {
1905 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
1906 EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
1907 EFI_STATUS Status;
1908 EFI_GUID *GuidPoint;
1909 UINTN Index;
1910 UINTN FvHandleCount;
1911 EFI_HANDLE *FvHandleBuffer;
1912 EFI_FV_FILETYPE Type;
1913 UINTN Size;
1914 EFI_FV_FILE_ATTRIBUTES Attributes;
1915 UINT32 AuthenticationStatus;
1916 BOOLEAN FindFvFile;
1917 EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
1918 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
1919 MEDIA_FW_VOL_FILEPATH_DEVICE_PATH FvFileNode;
1920 EFI_HANDLE FoundFvHandle;
1921 EFI_DEVICE_PATH_PROTOCOL *NewDevicePath;
1922
1923 if ((DevicePath == NULL) || (*DevicePath == NULL)) {
1924 return EFI_INVALID_PARAMETER;
1925 }
1926 if (FileGuid == NULL) {
1927 return EFI_INVALID_PARAMETER;
1928 }
1929
1930 //
1931 // Check whether the device path point to the default the input Fv file
1932 //
1933 TempDevicePath = *DevicePath;
1934 LastDeviceNode = TempDevicePath;
1935 while (!IsDevicePathEnd (TempDevicePath)) {
1936 LastDeviceNode = TempDevicePath;
1937 TempDevicePath = NextDevicePathNode (TempDevicePath);
1938 }
1939 GuidPoint = EfiGetNameGuidFromFwVolDevicePathNode (
1940 (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LastDeviceNode
1941 );
1942 if (GuidPoint == NULL) {
1943 //
1944 // if this option does not points to a Fv file, just return EFI_UNSUPPORTED
1945 //
1946 return EFI_UNSUPPORTED;
1947 }
1948 if (!CompareGuid (GuidPoint, FileGuid)) {
1949 //
1950 // If the Fv file is not the input file guid, just return EFI_UNSUPPORTED
1951 //
1952 return EFI_UNSUPPORTED;
1953 }
1954
1955 //
1956 // Check whether the input Fv file device path is valid
1957 //
1958 TempDevicePath = *DevicePath;
1959 FoundFvHandle = NULL;
1960 Status = gBS->LocateDevicePath (
1961 &gEfiFirmwareVolume2ProtocolGuid,
1962 &TempDevicePath,
1963 &FoundFvHandle
1964 );
1965 if (!EFI_ERROR (Status)) {
1966 Status = gBS->HandleProtocol (
1967 FoundFvHandle,
1968 &gEfiFirmwareVolume2ProtocolGuid,
1969 (VOID **) &Fv
1970 );
1971 if (!EFI_ERROR (Status)) {
1972 //
1973 // Set FV ReadFile Buffer as NULL, only need to check whether input Fv file exist there
1974 //
1975 Status = Fv->ReadFile (
1976 Fv,
1977 FileGuid,
1978 NULL,
1979 &Size,
1980 &Type,
1981 &Attributes,
1982 &AuthenticationStatus
1983 );
1984 if (!EFI_ERROR (Status)) {
1985 return EFI_ALREADY_STARTED;
1986 }
1987 }
1988 }
1989
1990 //
1991 // Look for the input wanted FV file in current FV
1992 // First, try to look for in Bds own FV. Bds and input wanted FV file usually are in the same FV
1993 //
1994 FindFvFile = FALSE;
1995 FoundFvHandle = NULL;
1996 Status = gBS->HandleProtocol (
1997 mBdsImageHandle,
1998 &gEfiLoadedImageProtocolGuid,
1999 (VOID **) &LoadedImage
2000 );
2001 if (!EFI_ERROR (Status)) {
2002 Status = gBS->HandleProtocol (
2003 LoadedImage->DeviceHandle,
2004 &gEfiFirmwareVolume2ProtocolGuid,
2005 (VOID **) &Fv
2006 );
2007 if (!EFI_ERROR (Status)) {
2008 Status = Fv->ReadFile (
2009 Fv,
2010 FileGuid,
2011 NULL,
2012 &Size,
2013 &Type,
2014 &Attributes,
2015 &AuthenticationStatus
2016 );
2017 if (!EFI_ERROR (Status)) {
2018 FindFvFile = TRUE;
2019 FoundFvHandle = LoadedImage->DeviceHandle;
2020 }
2021 }
2022 }
2023 //
2024 // Second, if fail to find, try to enumerate all FV
2025 //
2026 if (!FindFvFile) {
2027 FvHandleBuffer = NULL;
2028 gBS->LocateHandleBuffer (
2029 ByProtocol,
2030 &gEfiFirmwareVolume2ProtocolGuid,
2031 NULL,
2032 &FvHandleCount,
2033 &FvHandleBuffer
2034 );
2035 for (Index = 0; Index < FvHandleCount; Index++) {
2036 gBS->HandleProtocol (
2037 FvHandleBuffer[Index],
2038 &gEfiFirmwareVolume2ProtocolGuid,
2039 (VOID **) &Fv
2040 );
2041
2042 Status = Fv->ReadFile (
2043 Fv,
2044 FileGuid,
2045 NULL,
2046 &Size,
2047 &Type,
2048 &Attributes,
2049 &AuthenticationStatus
2050 );
2051 if (EFI_ERROR (Status)) {
2052 //
2053 // Skip if input Fv file not in the FV
2054 //
2055 continue;
2056 }
2057 FindFvFile = TRUE;
2058 FoundFvHandle = FvHandleBuffer[Index];
2059 break;
2060 }
2061
2062 if (FvHandleBuffer != NULL) {
2063 FreePool (FvHandleBuffer);
2064 }
2065 }
2066
2067 if (FindFvFile) {
2068 //
2069 // Build the shell device path
2070 //
2071 NewDevicePath = DevicePathFromHandle (FoundFvHandle);
2072 EfiInitializeFwVolDevicepathNode (&FvFileNode, FileGuid);
2073 NewDevicePath = AppendDevicePathNode (NewDevicePath, (EFI_DEVICE_PATH_PROTOCOL *) &FvFileNode);
2074 *DevicePath = NewDevicePath;
2075 return EFI_SUCCESS;
2076 }
2077 return EFI_NOT_FOUND;
2078 }