]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c
MdeModulePkg: Make the BmFindLoadOption function public
[mirror_edk2.git] / MdeModulePkg / Library / UefiBootManagerLib / BmBoot.c
1 /** @file
2 Library functions which relates with booting.
3
4 Copyright (c) 2011 - 2015, Intel Corporation. All rights reserved.<BR>
5 (C) Copyright 2015 Hewlett Packard Enterprise Development LP<BR>
6 This program and the accompanying materials
7 are licensed and made available under the terms and conditions of the BSD License
8 which accompanies this distribution. The full text of the license may be found at
9 http://opensource.org/licenses/bsd-license.php
10
11 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
12 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
13
14 **/
15
16 #include "InternalBm.h"
17
18 #define VENDOR_IDENTIFICATION_OFFSET 3
19 #define VENDOR_IDENTIFICATION_LENGTH 8
20 #define PRODUCT_IDENTIFICATION_OFFSET 11
21 #define PRODUCT_IDENTIFICATION_LENGTH 16
22
23 CONST UINT16 mBmUsbLangId = 0x0409; // English
24 CHAR16 mBmUefiPrefix[] = L"UEFI ";
25
26 EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION mBmRefreshLegacyBootOption = NULL;
27 EFI_BOOT_MANAGER_LEGACY_BOOT mBmLegacyBoot = NULL;
28
29 LIST_ENTRY mPlatformBootDescriptionHandlers = INITIALIZE_LIST_HEAD_VARIABLE (mPlatformBootDescriptionHandlers);
30
31 ///
32 /// This GUID is used for an EFI Variable that stores the front device pathes
33 /// for a partial device path that starts with the HD node.
34 ///
35 EFI_GUID mBmHardDriveBootVariableGuid = { 0xfab7e9e1, 0x39dd, 0x4f2b, { 0x84, 0x08, 0xe2, 0x0e, 0x90, 0x6c, 0xb6, 0xde } };
36 EFI_GUID mBmAutoCreateBootOptionGuid = { 0x8108ac4e, 0x9f11, 0x4d59, { 0x85, 0x0e, 0xe2, 0x1a, 0x52, 0x2c, 0x59, 0xb2 } };
37
38 /**
39 The function registers the legacy boot support capabilities.
40
41 @param RefreshLegacyBootOption The function pointer to create all the legacy boot options.
42 @param LegacyBoot The function pointer to boot the legacy boot option.
43 **/
44 VOID
45 EFIAPI
46 EfiBootManagerRegisterLegacyBootSupport (
47 EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION RefreshLegacyBootOption,
48 EFI_BOOT_MANAGER_LEGACY_BOOT LegacyBoot
49 )
50 {
51 mBmRefreshLegacyBootOption = RefreshLegacyBootOption;
52 mBmLegacyBoot = LegacyBoot;
53 }
54
55 /**
56 For a bootable Device path, return its boot type.
57
58 @param DevicePath The bootable device Path to check
59
60 @retval AcpiFloppyBoot If given device path contains ACPI_DEVICE_PATH type device path node
61 which HID is floppy device.
62 @retval MessageAtapiBoot If given device path contains MESSAGING_DEVICE_PATH type device path node
63 and its last device path node's subtype is MSG_ATAPI_DP.
64 @retval MessageSataBoot If given device path contains MESSAGING_DEVICE_PATH type device path node
65 and its last device path node's subtype is MSG_SATA_DP.
66 @retval MessageScsiBoot If given device path contains MESSAGING_DEVICE_PATH type device path node
67 and its last device path node's subtype is MSG_SCSI_DP.
68 @retval MessageUsbBoot If given device path contains MESSAGING_DEVICE_PATH type device path node
69 and its last device path node's subtype is MSG_USB_DP.
70 @retval MessageNetworkBoot If given device path contains MESSAGING_DEVICE_PATH type device path node
71 and its last device path node's subtype is MSG_MAC_ADDR_DP, MSG_VLAN_DP,
72 MSG_IPv4_DP or MSG_IPv6_DP.
73 @retval MessageHttpBoot If given device path contains MESSAGING_DEVICE_PATH type device path node
74 and its last device path node's subtype is MSG_URI_DP.
75 @retval UnsupportedBoot If tiven device path doesn't match the above condition, it's not supported.
76
77 **/
78 BM_BOOT_TYPE
79 BmDevicePathType (
80 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
81 )
82 {
83 EFI_DEVICE_PATH_PROTOCOL *Node;
84 EFI_DEVICE_PATH_PROTOCOL *NextNode;
85
86 ASSERT (DevicePath != NULL);
87
88 for (Node = DevicePath; !IsDevicePathEndType (Node); Node = NextDevicePathNode (Node)) {
89 switch (DevicePathType (Node)) {
90
91 case ACPI_DEVICE_PATH:
92 if (EISA_ID_TO_NUM (((ACPI_HID_DEVICE_PATH *) Node)->HID) == 0x0604) {
93 return BmAcpiFloppyBoot;
94 }
95 break;
96
97 case HARDWARE_DEVICE_PATH:
98 if (DevicePathSubType (Node) == HW_CONTROLLER_DP) {
99 return BmHardwareDeviceBoot;
100 }
101 break;
102
103 case MESSAGING_DEVICE_PATH:
104 //
105 // Skip LUN device node
106 //
107 NextNode = Node;
108 do {
109 NextNode = NextDevicePathNode (NextNode);
110 } while (
111 (DevicePathType (NextNode) == MESSAGING_DEVICE_PATH) &&
112 (DevicePathSubType(NextNode) == MSG_DEVICE_LOGICAL_UNIT_DP)
113 );
114
115 //
116 // If the device path not only point to driver device, it is not a messaging device path,
117 //
118 if (!IsDevicePathEndType (NextNode)) {
119 continue;
120 }
121
122 switch (DevicePathSubType (Node)) {
123 case MSG_ATAPI_DP:
124 return BmMessageAtapiBoot;
125 break;
126
127 case MSG_SATA_DP:
128 return BmMessageSataBoot;
129 break;
130
131 case MSG_USB_DP:
132 return BmMessageUsbBoot;
133 break;
134
135 case MSG_SCSI_DP:
136 return BmMessageScsiBoot;
137 break;
138
139 case MSG_MAC_ADDR_DP:
140 case MSG_VLAN_DP:
141 case MSG_IPv4_DP:
142 case MSG_IPv6_DP:
143 return BmMessageNetworkBoot;
144 break;
145
146 case MSG_URI_DP:
147 return BmMessageHttpBoot;
148 break;
149 }
150 }
151 }
152
153 return BmMiscBoot;
154 }
155
156 /**
157 Find the boot option in the NV storage and return the option number.
158
159 @param OptionToFind Boot option to be checked.
160
161 @return The option number of the found boot option.
162
163 **/
164 UINTN
165 BmFindBootOptionInVariable (
166 IN EFI_BOOT_MANAGER_LOAD_OPTION *OptionToFind
167 )
168 {
169 EFI_STATUS Status;
170 EFI_BOOT_MANAGER_LOAD_OPTION BootOption;
171 UINTN OptionNumber;
172 CHAR16 OptionName[BM_OPTION_NAME_LEN];
173 EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions;
174 UINTN BootOptionCount;
175 UINTN Index;
176
177 OptionNumber = LoadOptionNumberUnassigned;
178
179 //
180 // Try to match the variable exactly if the option number is assigned
181 //
182 if (OptionToFind->OptionNumber != LoadOptionNumberUnassigned) {
183 UnicodeSPrint (
184 OptionName, sizeof (OptionName), L"%s%04x",
185 mBmLoadOptionName[OptionToFind->OptionType], OptionToFind->OptionNumber
186 );
187 Status = EfiBootManagerVariableToLoadOption (OptionName, &BootOption);
188
189 if (!EFI_ERROR (Status)) {
190 ASSERT (OptionToFind->OptionNumber == BootOption.OptionNumber);
191 if ((OptionToFind->Attributes == BootOption.Attributes) &&
192 (StrCmp (OptionToFind->Description, BootOption.Description) == 0) &&
193 (CompareMem (OptionToFind->FilePath, BootOption.FilePath, GetDevicePathSize (OptionToFind->FilePath)) == 0) &&
194 (OptionToFind->OptionalDataSize == BootOption.OptionalDataSize) &&
195 (CompareMem (OptionToFind->OptionalData, BootOption.OptionalData, OptionToFind->OptionalDataSize) == 0)
196 ) {
197 OptionNumber = OptionToFind->OptionNumber;
198 }
199 EfiBootManagerFreeLoadOption (&BootOption);
200 }
201 }
202
203 //
204 // The option number assigned is either incorrect or unassigned.
205 //
206 if (OptionNumber == LoadOptionNumberUnassigned) {
207 BootOptions = EfiBootManagerGetLoadOptions (&BootOptionCount, LoadOptionTypeBoot);
208
209 Index = EfiBootManagerFindLoadOption (OptionToFind, BootOptions, BootOptionCount);
210 if (Index != -1) {
211 OptionNumber = BootOptions[Index].OptionNumber;
212 }
213
214 EfiBootManagerFreeLoadOptions (BootOptions, BootOptionCount);
215 }
216
217 return OptionNumber;
218 }
219
220 /**
221 Get the file buffer using a Memory Mapped Device Path.
222
223 FV address may change across reboot. This routine promises the FV file device path is right.
224
225 @param DevicePath The Memory Mapped Device Path to get the file buffer.
226 @param FullPath Receive the updated FV Device Path pointint to the file.
227 @param FileSize Receive the file buffer size.
228
229 @return The file buffer.
230 **/
231 VOID *
232 BmGetFileBufferByMemmapFv (
233 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
234 OUT EFI_DEVICE_PATH_PROTOCOL **FullPath,
235 OUT UINTN *FileSize
236 )
237 {
238 EFI_STATUS Status;
239 UINTN Index;
240 EFI_DEVICE_PATH_PROTOCOL *FvFileNode;
241 EFI_HANDLE FvHandle;
242 EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
243 UINT32 AuthenticationStatus;
244 UINTN FvHandleCount;
245 EFI_HANDLE *FvHandles;
246 EFI_DEVICE_PATH_PROTOCOL *NewDevicePath;
247 VOID *FileBuffer;
248
249 FvFileNode = DevicePath;
250 Status = gBS->LocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &FvFileNode, &FvHandle);
251 if (!EFI_ERROR (Status)) {
252 FileBuffer = GetFileBufferByFilePath (TRUE, DevicePath, FileSize, &AuthenticationStatus);
253 if (FileBuffer != NULL) {
254 *FullPath = DuplicateDevicePath (DevicePath);
255 }
256 return FileBuffer;
257 }
258
259 FvFileNode = NextDevicePathNode (DevicePath);
260
261 //
262 // Firstly find the FV file in current FV
263 //
264 gBS->HandleProtocol (
265 gImageHandle,
266 &gEfiLoadedImageProtocolGuid,
267 (VOID **) &LoadedImage
268 );
269 NewDevicePath = AppendDevicePathNode (DevicePathFromHandle (LoadedImage->DeviceHandle), FvFileNode);
270 FileBuffer = BmGetFileBufferByMemmapFv (NewDevicePath, FullPath, FileSize);
271 FreePool (NewDevicePath);
272
273 if (FileBuffer != NULL) {
274 return FileBuffer;
275 }
276
277 //
278 // Secondly find the FV file in all other FVs
279 //
280 gBS->LocateHandleBuffer (
281 ByProtocol,
282 &gEfiFirmwareVolume2ProtocolGuid,
283 NULL,
284 &FvHandleCount,
285 &FvHandles
286 );
287 for (Index = 0; (Index < FvHandleCount) && (FileBuffer == NULL); Index++) {
288 if (FvHandles[Index] == LoadedImage->DeviceHandle) {
289 //
290 // Skip current FV
291 //
292 continue;
293 }
294 NewDevicePath = AppendDevicePathNode (DevicePathFromHandle (FvHandles[Index]), FvFileNode);
295 FileBuffer = BmGetFileBufferByMemmapFv (NewDevicePath, FullPath, FileSize);
296 FreePool (NewDevicePath);
297 }
298
299 if (FvHandles != NULL) {
300 FreePool (FvHandles);
301 }
302 return FileBuffer;
303 }
304
305 /**
306 Check if it's a Memory Mapped FV Device Path.
307
308 The function doesn't garentee the device path points to existing FV file.
309
310 @param DevicePath Input device path.
311
312 @retval TRUE The device path is a Memory Mapped FV Device Path.
313 @retval FALSE The device path is NOT a Memory Mapped FV Device Path.
314 **/
315 BOOLEAN
316 BmIsMemmapFvFilePath (
317 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
318 )
319 {
320 EFI_DEVICE_PATH_PROTOCOL *FileNode;
321
322 if ((DevicePathType (DevicePath) == HARDWARE_DEVICE_PATH) && (DevicePathSubType (DevicePath) == HW_MEMMAP_DP)) {
323 FileNode = NextDevicePathNode (DevicePath);
324 if ((DevicePathType (FileNode) == MEDIA_DEVICE_PATH) && (DevicePathSubType (FileNode) == MEDIA_PIWG_FW_FILE_DP)) {
325 return IsDevicePathEnd (NextDevicePathNode (FileNode));
326 }
327 }
328
329 return FALSE;
330 }
331
332 /**
333 Check whether a USB device match the specified USB Class device path. This
334 function follows "Load Option Processing" behavior in UEFI specification.
335
336 @param UsbIo USB I/O protocol associated with the USB device.
337 @param UsbClass The USB Class device path to match.
338
339 @retval TRUE The USB device match the USB Class device path.
340 @retval FALSE The USB device does not match the USB Class device path.
341
342 **/
343 BOOLEAN
344 BmMatchUsbClass (
345 IN EFI_USB_IO_PROTOCOL *UsbIo,
346 IN USB_CLASS_DEVICE_PATH *UsbClass
347 )
348 {
349 EFI_STATUS Status;
350 EFI_USB_DEVICE_DESCRIPTOR DevDesc;
351 EFI_USB_INTERFACE_DESCRIPTOR IfDesc;
352 UINT8 DeviceClass;
353 UINT8 DeviceSubClass;
354 UINT8 DeviceProtocol;
355
356 if ((DevicePathType (UsbClass) != MESSAGING_DEVICE_PATH) ||
357 (DevicePathSubType (UsbClass) != MSG_USB_CLASS_DP)){
358 return FALSE;
359 }
360
361 //
362 // Check Vendor Id and Product Id.
363 //
364 Status = UsbIo->UsbGetDeviceDescriptor (UsbIo, &DevDesc);
365 if (EFI_ERROR (Status)) {
366 return FALSE;
367 }
368
369 if ((UsbClass->VendorId != 0xffff) &&
370 (UsbClass->VendorId != DevDesc.IdVendor)) {
371 return FALSE;
372 }
373
374 if ((UsbClass->ProductId != 0xffff) &&
375 (UsbClass->ProductId != DevDesc.IdProduct)) {
376 return FALSE;
377 }
378
379 DeviceClass = DevDesc.DeviceClass;
380 DeviceSubClass = DevDesc.DeviceSubClass;
381 DeviceProtocol = DevDesc.DeviceProtocol;
382 if (DeviceClass == 0) {
383 //
384 // If Class in Device Descriptor is set to 0, use the Class, SubClass and
385 // Protocol in Interface Descriptor instead.
386 //
387 Status = UsbIo->UsbGetInterfaceDescriptor (UsbIo, &IfDesc);
388 if (EFI_ERROR (Status)) {
389 return FALSE;
390 }
391
392 DeviceClass = IfDesc.InterfaceClass;
393 DeviceSubClass = IfDesc.InterfaceSubClass;
394 DeviceProtocol = IfDesc.InterfaceProtocol;
395 }
396
397 //
398 // Check Class, SubClass and Protocol.
399 //
400 if ((UsbClass->DeviceClass != 0xff) &&
401 (UsbClass->DeviceClass != DeviceClass)) {
402 return FALSE;
403 }
404
405 if ((UsbClass->DeviceSubClass != 0xff) &&
406 (UsbClass->DeviceSubClass != DeviceSubClass)) {
407 return FALSE;
408 }
409
410 if ((UsbClass->DeviceProtocol != 0xff) &&
411 (UsbClass->DeviceProtocol != DeviceProtocol)) {
412 return FALSE;
413 }
414
415 return TRUE;
416 }
417
418 /**
419 Eliminate the extra spaces in the Str to one space.
420
421 @param Str Input string info.
422 **/
423 VOID
424 BmEliminateExtraSpaces (
425 IN CHAR16 *Str
426 )
427 {
428 UINTN Index;
429 UINTN ActualIndex;
430
431 for (Index = 0, ActualIndex = 0; Str[Index] != L'\0'; Index++) {
432 if ((Str[Index] != L' ') || ((ActualIndex > 0) && (Str[ActualIndex - 1] != L' '))) {
433 Str[ActualIndex++] = Str[Index];
434 }
435 }
436 Str[ActualIndex] = L'\0';
437 }
438
439 /**
440 Try to get the controller's ATA/ATAPI description.
441
442 @param Handle Controller handle.
443
444 @return The description string.
445 **/
446 CHAR16 *
447 BmGetDescriptionFromDiskInfo (
448 IN EFI_HANDLE Handle
449 )
450 {
451 UINTN Index;
452 EFI_STATUS Status;
453 EFI_DISK_INFO_PROTOCOL *DiskInfo;
454 UINT32 BufferSize;
455 EFI_ATAPI_IDENTIFY_DATA IdentifyData;
456 EFI_SCSI_INQUIRY_DATA InquiryData;
457 CHAR16 *Description;
458 UINTN Length;
459 CONST UINTN ModelNameLength = 40;
460 CONST UINTN SerialNumberLength = 20;
461 CHAR8 *StrPtr;
462 UINT8 Temp;
463
464 Description = NULL;
465
466 Status = gBS->HandleProtocol (
467 Handle,
468 &gEfiDiskInfoProtocolGuid,
469 (VOID **) &DiskInfo
470 );
471 if (EFI_ERROR (Status)) {
472 return NULL;
473 }
474
475 if (CompareGuid (&DiskInfo->Interface, &gEfiDiskInfoAhciInterfaceGuid) ||
476 CompareGuid (&DiskInfo->Interface, &gEfiDiskInfoIdeInterfaceGuid)) {
477 BufferSize = sizeof (EFI_ATAPI_IDENTIFY_DATA);
478 Status = DiskInfo->Identify (
479 DiskInfo,
480 &IdentifyData,
481 &BufferSize
482 );
483 if (!EFI_ERROR (Status)) {
484 Description = AllocateZeroPool ((ModelNameLength + SerialNumberLength + 2) * sizeof (CHAR16));
485 ASSERT (Description != NULL);
486 for (Index = 0; Index + 1 < ModelNameLength; Index += 2) {
487 Description[Index] = (CHAR16) IdentifyData.ModelName[Index + 1];
488 Description[Index + 1] = (CHAR16) IdentifyData.ModelName[Index];
489 }
490
491 Length = Index;
492 Description[Length++] = L' ';
493
494 for (Index = 0; Index + 1 < SerialNumberLength; Index += 2) {
495 Description[Length + Index] = (CHAR16) IdentifyData.SerialNo[Index + 1];
496 Description[Length + Index + 1] = (CHAR16) IdentifyData.SerialNo[Index];
497 }
498 Length += Index;
499 Description[Length++] = L'\0';
500 ASSERT (Length == ModelNameLength + SerialNumberLength + 2);
501
502 BmEliminateExtraSpaces (Description);
503 }
504 } else if (CompareGuid (&DiskInfo->Interface, &gEfiDiskInfoScsiInterfaceGuid)) {
505 BufferSize = sizeof (EFI_SCSI_INQUIRY_DATA);
506 Status = DiskInfo->Inquiry (
507 DiskInfo,
508 &InquiryData,
509 &BufferSize
510 );
511 if (!EFI_ERROR (Status)) {
512 Description = AllocateZeroPool ((VENDOR_IDENTIFICATION_LENGTH + PRODUCT_IDENTIFICATION_LENGTH + 2) * sizeof (CHAR16));
513 ASSERT (Description != NULL);
514
515 //
516 // Per SCSI spec, EFI_SCSI_INQUIRY_DATA.Reserved_5_95[3 - 10] save the Verdor identification
517 // EFI_SCSI_INQUIRY_DATA.Reserved_5_95[11 - 26] save the product identification,
518 // Here combine the vendor identification and product identification to the description.
519 //
520 StrPtr = (CHAR8 *) (&InquiryData.Reserved_5_95[VENDOR_IDENTIFICATION_OFFSET]);
521 Temp = StrPtr[VENDOR_IDENTIFICATION_LENGTH];
522 StrPtr[VENDOR_IDENTIFICATION_LENGTH] = '\0';
523 AsciiStrToUnicodeStr (StrPtr, Description);
524 StrPtr[VENDOR_IDENTIFICATION_LENGTH] = Temp;
525
526 //
527 // Add one space at the middle of vendor information and product information.
528 //
529 Description[VENDOR_IDENTIFICATION_LENGTH] = L' ';
530
531 StrPtr = (CHAR8 *) (&InquiryData.Reserved_5_95[PRODUCT_IDENTIFICATION_OFFSET]);
532 StrPtr[PRODUCT_IDENTIFICATION_LENGTH] = '\0';
533 AsciiStrToUnicodeStr (StrPtr, Description + VENDOR_IDENTIFICATION_LENGTH + 1);
534
535 BmEliminateExtraSpaces (Description);
536 }
537 }
538
539 return Description;
540 }
541
542 /**
543 Try to get the controller's USB description.
544
545 @param Handle Controller handle.
546
547 @return The description string.
548 **/
549 CHAR16 *
550 BmGetUsbDescription (
551 IN EFI_HANDLE Handle
552 )
553 {
554 EFI_STATUS Status;
555 EFI_USB_IO_PROTOCOL *UsbIo;
556 CHAR16 NullChar;
557 CHAR16 *Manufacturer;
558 CHAR16 *Product;
559 CHAR16 *SerialNumber;
560 CHAR16 *Description;
561 EFI_USB_DEVICE_DESCRIPTOR DevDesc;
562 UINTN DescMaxSize;
563
564 Status = gBS->HandleProtocol (
565 Handle,
566 &gEfiUsbIoProtocolGuid,
567 (VOID **) &UsbIo
568 );
569 if (EFI_ERROR (Status)) {
570 return NULL;
571 }
572
573 NullChar = L'\0';
574
575 Status = UsbIo->UsbGetDeviceDescriptor (UsbIo, &DevDesc);
576 if (EFI_ERROR (Status)) {
577 return NULL;
578 }
579
580 Status = UsbIo->UsbGetStringDescriptor (
581 UsbIo,
582 mBmUsbLangId,
583 DevDesc.StrManufacturer,
584 &Manufacturer
585 );
586 if (EFI_ERROR (Status)) {
587 Manufacturer = &NullChar;
588 }
589
590 Status = UsbIo->UsbGetStringDescriptor (
591 UsbIo,
592 mBmUsbLangId,
593 DevDesc.StrProduct,
594 &Product
595 );
596 if (EFI_ERROR (Status)) {
597 Product = &NullChar;
598 }
599
600 Status = UsbIo->UsbGetStringDescriptor (
601 UsbIo,
602 mBmUsbLangId,
603 DevDesc.StrSerialNumber,
604 &SerialNumber
605 );
606 if (EFI_ERROR (Status)) {
607 SerialNumber = &NullChar;
608 }
609
610 if ((Manufacturer == &NullChar) &&
611 (Product == &NullChar) &&
612 (SerialNumber == &NullChar)
613 ) {
614 return NULL;
615 }
616
617 DescMaxSize = StrSize (Manufacturer) + StrSize (Product) + StrSize (SerialNumber);
618 Description = AllocateZeroPool (DescMaxSize);
619 ASSERT (Description != NULL);
620 StrCatS (Description, DescMaxSize/sizeof(CHAR16), Manufacturer);
621 StrCatS (Description, DescMaxSize/sizeof(CHAR16), L" ");
622
623 StrCatS (Description, DescMaxSize/sizeof(CHAR16), Product);
624 StrCatS (Description, DescMaxSize/sizeof(CHAR16), L" ");
625
626 StrCatS (Description, DescMaxSize/sizeof(CHAR16), SerialNumber);
627
628 if (Manufacturer != &NullChar) {
629 FreePool (Manufacturer);
630 }
631 if (Product != &NullChar) {
632 FreePool (Product);
633 }
634 if (SerialNumber != &NullChar) {
635 FreePool (SerialNumber);
636 }
637
638 BmEliminateExtraSpaces (Description);
639
640 return Description;
641 }
642
643 /**
644 Return the boot description for the controller based on the type.
645
646 @param Handle Controller handle.
647
648 @return The description string.
649 **/
650 CHAR16 *
651 BmGetMiscDescription (
652 IN EFI_HANDLE Handle
653 )
654 {
655 EFI_STATUS Status;
656 CHAR16 *Description;
657 EFI_BLOCK_IO_PROTOCOL *BlockIo;
658 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs;
659
660 switch (BmDevicePathType (DevicePathFromHandle (Handle))) {
661 case BmAcpiFloppyBoot:
662 Description = L"Floppy";
663 break;
664
665 case BmMessageAtapiBoot:
666 case BmMessageSataBoot:
667 Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **) &BlockIo);
668 ASSERT_EFI_ERROR (Status);
669 //
670 // Assume a removable SATA device should be the DVD/CD device
671 //
672 Description = BlockIo->Media->RemovableMedia ? L"DVD/CDROM" : L"Hard Drive";
673 break;
674
675 case BmMessageUsbBoot:
676 Description = L"USB Device";
677 break;
678
679 case BmMessageScsiBoot:
680 Description = L"SCSI Device";
681 break;
682
683 case BmHardwareDeviceBoot:
684 Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **) &BlockIo);
685 if (!EFI_ERROR (Status)) {
686 Description = BlockIo->Media->RemovableMedia ? L"Removable Disk" : L"Hard Drive";
687 } else {
688 Description = L"Misc Device";
689 }
690 break;
691
692 case BmMessageNetworkBoot:
693 Description = L"Network";
694 break;
695
696 case BmMessageHttpBoot:
697 Description = L"Http";
698 break;
699
700 default:
701 Status = gBS->HandleProtocol (Handle, &gEfiSimpleFileSystemProtocolGuid, (VOID **) &Fs);
702 if (!EFI_ERROR (Status)) {
703 Description = L"Non-Block Boot Device";
704 } else {
705 Description = L"Misc Device";
706 }
707 break;
708 }
709
710 return AllocateCopyPool (StrSize (Description), Description);
711 }
712
713 /**
714 Register the platform provided boot description handler.
715
716 @param Handler The platform provided boot description handler
717
718 @retval EFI_SUCCESS The handler was registered successfully.
719 @retval EFI_ALREADY_STARTED The handler was already registered.
720 @retval EFI_OUT_OF_RESOURCES There is not enough resource to perform the registration.
721 **/
722 EFI_STATUS
723 EFIAPI
724 EfiBootManagerRegisterBootDescriptionHandler (
725 IN EFI_BOOT_MANAGER_BOOT_DESCRIPTION_HANDLER Handler
726 )
727 {
728 LIST_ENTRY *Link;
729 BM_BOOT_DESCRIPTION_ENTRY *Entry;
730
731 for ( Link = GetFirstNode (&mPlatformBootDescriptionHandlers)
732 ; !IsNull (&mPlatformBootDescriptionHandlers, Link)
733 ; Link = GetNextNode (&mPlatformBootDescriptionHandlers, Link)
734 ) {
735 Entry = CR (Link, BM_BOOT_DESCRIPTION_ENTRY, Link, BM_BOOT_DESCRIPTION_ENTRY_SIGNATURE);
736 if (Entry->Handler == Handler) {
737 return EFI_ALREADY_STARTED;
738 }
739 }
740
741 Entry = AllocatePool (sizeof (BM_BOOT_DESCRIPTION_ENTRY));
742 if (Entry == NULL) {
743 return EFI_OUT_OF_RESOURCES;
744 }
745
746 Entry->Signature = BM_BOOT_DESCRIPTION_ENTRY_SIGNATURE;
747 Entry->Handler = Handler;
748 InsertTailList (&mPlatformBootDescriptionHandlers, &Entry->Link);
749 return EFI_SUCCESS;
750 }
751
752 BM_GET_BOOT_DESCRIPTION mBmBootDescriptionHandlers[] = {
753 BmGetUsbDescription,
754 BmGetDescriptionFromDiskInfo,
755 BmGetMiscDescription
756 };
757
758 /**
759 Return the boot description for the controller.
760
761 @param Handle Controller handle.
762
763 @return The description string.
764 **/
765 CHAR16 *
766 BmGetBootDescription (
767 IN EFI_HANDLE Handle
768 )
769 {
770 LIST_ENTRY *Link;
771 BM_BOOT_DESCRIPTION_ENTRY *Entry;
772 CHAR16 *Description;
773 CHAR16 *DefaultDescription;
774 CHAR16 *Temp;
775 UINTN Index;
776
777 //
778 // Firstly get the default boot description
779 //
780 DefaultDescription = NULL;
781 for (Index = 0; Index < sizeof (mBmBootDescriptionHandlers) / sizeof (mBmBootDescriptionHandlers[0]); Index++) {
782 DefaultDescription = mBmBootDescriptionHandlers[Index] (Handle);
783 if (DefaultDescription != NULL) {
784 //
785 // Avoid description confusion between UEFI & Legacy boot option by adding "UEFI " prefix
786 // ONLY for core provided boot description handler.
787 //
788 Temp = AllocatePool (StrSize (DefaultDescription) + sizeof (mBmUefiPrefix));
789 ASSERT (Temp != NULL);
790 StrCpyS ( Temp,
791 (StrSize (DefaultDescription) + sizeof (mBmUefiPrefix))/sizeof(CHAR16),
792 mBmUefiPrefix
793 );
794 StrCatS ( Temp,
795 (StrSize (DefaultDescription) + sizeof (mBmUefiPrefix))/sizeof(CHAR16),
796 DefaultDescription
797 );
798 FreePool (DefaultDescription);
799 DefaultDescription = Temp;
800 break;
801 }
802 }
803 ASSERT (DefaultDescription != NULL);
804
805 //
806 // Secondly query platform for the better boot description
807 //
808 for ( Link = GetFirstNode (&mPlatformBootDescriptionHandlers)
809 ; !IsNull (&mPlatformBootDescriptionHandlers, Link)
810 ; Link = GetNextNode (&mPlatformBootDescriptionHandlers, Link)
811 ) {
812 Entry = CR (Link, BM_BOOT_DESCRIPTION_ENTRY, Link, BM_BOOT_DESCRIPTION_ENTRY_SIGNATURE);
813 Description = Entry->Handler (Handle, DefaultDescription);
814 if (Description != NULL) {
815 FreePool (DefaultDescription);
816 return Description;
817 }
818 }
819
820 return DefaultDescription;
821 }
822
823 /**
824 Check whether a USB device match the specified USB WWID device path. This
825 function follows "Load Option Processing" behavior in UEFI specification.
826
827 @param UsbIo USB I/O protocol associated with the USB device.
828 @param UsbWwid The USB WWID device path to match.
829
830 @retval TRUE The USB device match the USB WWID device path.
831 @retval FALSE The USB device does not match the USB WWID device path.
832
833 **/
834 BOOLEAN
835 BmMatchUsbWwid (
836 IN EFI_USB_IO_PROTOCOL *UsbIo,
837 IN USB_WWID_DEVICE_PATH *UsbWwid
838 )
839 {
840 EFI_STATUS Status;
841 EFI_USB_DEVICE_DESCRIPTOR DevDesc;
842 EFI_USB_INTERFACE_DESCRIPTOR IfDesc;
843 UINT16 *LangIdTable;
844 UINT16 TableSize;
845 UINT16 Index;
846 CHAR16 *CompareStr;
847 UINTN CompareLen;
848 CHAR16 *SerialNumberStr;
849 UINTN Length;
850
851 if ((DevicePathType (UsbWwid) != MESSAGING_DEVICE_PATH) ||
852 (DevicePathSubType (UsbWwid) != MSG_USB_WWID_DP)) {
853 return FALSE;
854 }
855
856 //
857 // Check Vendor Id and Product Id.
858 //
859 Status = UsbIo->UsbGetDeviceDescriptor (UsbIo, &DevDesc);
860 if (EFI_ERROR (Status)) {
861 return FALSE;
862 }
863 if ((DevDesc.IdVendor != UsbWwid->VendorId) ||
864 (DevDesc.IdProduct != UsbWwid->ProductId)) {
865 return FALSE;
866 }
867
868 //
869 // Check Interface Number.
870 //
871 Status = UsbIo->UsbGetInterfaceDescriptor (UsbIo, &IfDesc);
872 if (EFI_ERROR (Status)) {
873 return FALSE;
874 }
875 if (IfDesc.InterfaceNumber != UsbWwid->InterfaceNumber) {
876 return FALSE;
877 }
878
879 //
880 // Check Serial Number.
881 //
882 if (DevDesc.StrSerialNumber == 0) {
883 return FALSE;
884 }
885
886 //
887 // Get all supported languages.
888 //
889 TableSize = 0;
890 LangIdTable = NULL;
891 Status = UsbIo->UsbGetSupportedLanguages (UsbIo, &LangIdTable, &TableSize);
892 if (EFI_ERROR (Status) || (TableSize == 0) || (LangIdTable == NULL)) {
893 return FALSE;
894 }
895
896 //
897 // Serial number in USB WWID device path is the last 64-or-less UTF-16 characters.
898 //
899 CompareStr = (CHAR16 *) (UINTN) (UsbWwid + 1);
900 CompareLen = (DevicePathNodeLength (UsbWwid) - sizeof (USB_WWID_DEVICE_PATH)) / sizeof (CHAR16);
901 if (CompareStr[CompareLen - 1] == L'\0') {
902 CompareLen--;
903 }
904
905 //
906 // Compare serial number in each supported language.
907 //
908 for (Index = 0; Index < TableSize / sizeof (UINT16); Index++) {
909 SerialNumberStr = NULL;
910 Status = UsbIo->UsbGetStringDescriptor (
911 UsbIo,
912 LangIdTable[Index],
913 DevDesc.StrSerialNumber,
914 &SerialNumberStr
915 );
916 if (EFI_ERROR (Status) || (SerialNumberStr == NULL)) {
917 continue;
918 }
919
920 Length = StrLen (SerialNumberStr);
921 if ((Length >= CompareLen) &&
922 (CompareMem (SerialNumberStr + Length - CompareLen, CompareStr, CompareLen * sizeof (CHAR16)) == 0)) {
923 FreePool (SerialNumberStr);
924 return TRUE;
925 }
926
927 FreePool (SerialNumberStr);
928 }
929
930 return FALSE;
931 }
932
933 /**
934 Find a USB device which match the specified short-form device path start with
935 USB Class or USB WWID device path. If ParentDevicePath is NULL, this function
936 will search in all USB devices of the platform. If ParentDevicePath is not NULL,
937 this function will only search in its child devices.
938
939 @param DevicePath The device path that contains USB Class or USB WWID device path.
940 @param ParentDevicePathSize The length of the device path before the USB Class or
941 USB WWID device path.
942 @param UsbIoHandleCount A pointer to the count of the returned USB IO handles.
943
944 @retval NULL The matched USB IO handles cannot be found.
945 @retval other The matched USB IO handles.
946
947 **/
948 EFI_HANDLE *
949 BmFindUsbDevice (
950 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
951 IN UINTN ParentDevicePathSize,
952 OUT UINTN *UsbIoHandleCount
953 )
954 {
955 EFI_STATUS Status;
956 EFI_HANDLE *UsbIoHandles;
957 EFI_DEVICE_PATH_PROTOCOL *UsbIoDevicePath;
958 EFI_USB_IO_PROTOCOL *UsbIo;
959 UINTN Index;
960 BOOLEAN Matched;
961
962 ASSERT (UsbIoHandleCount != NULL);
963
964 //
965 // Get all UsbIo Handles.
966 //
967 Status = gBS->LocateHandleBuffer (
968 ByProtocol,
969 &gEfiUsbIoProtocolGuid,
970 NULL,
971 UsbIoHandleCount,
972 &UsbIoHandles
973 );
974 if (EFI_ERROR (Status)) {
975 *UsbIoHandleCount = 0;
976 UsbIoHandles = NULL;
977 }
978
979 for (Index = 0; Index < *UsbIoHandleCount; ) {
980 //
981 // Get the Usb IO interface.
982 //
983 Status = gBS->HandleProtocol(
984 UsbIoHandles[Index],
985 &gEfiUsbIoProtocolGuid,
986 (VOID **) &UsbIo
987 );
988 UsbIoDevicePath = DevicePathFromHandle (UsbIoHandles[Index]);
989 Matched = FALSE;
990 if (!EFI_ERROR (Status) && (UsbIoDevicePath != NULL)) {
991
992 //
993 // Compare starting part of UsbIoHandle's device path with ParentDevicePath.
994 //
995 if (CompareMem (UsbIoDevicePath, DevicePath, ParentDevicePathSize) == 0) {
996 if (BmMatchUsbClass (UsbIo, (USB_CLASS_DEVICE_PATH *) ((UINTN) DevicePath + ParentDevicePathSize)) ||
997 BmMatchUsbWwid (UsbIo, (USB_WWID_DEVICE_PATH *) ((UINTN) DevicePath + ParentDevicePathSize))) {
998 Matched = TRUE;
999 }
1000 }
1001 }
1002
1003 if (!Matched) {
1004 (*UsbIoHandleCount) --;
1005 CopyMem (&UsbIoHandles[Index], &UsbIoHandles[Index + 1], (*UsbIoHandleCount - Index) * sizeof (EFI_HANDLE));
1006 } else {
1007 Index++;
1008 }
1009 }
1010
1011 return UsbIoHandles;
1012 }
1013
1014 /**
1015 Expand USB Class or USB WWID device path node to be full device path of a USB
1016 device in platform.
1017
1018 This function support following 4 cases:
1019 1) Boot Option device path starts with a USB Class or USB WWID device path,
1020 and there is no Media FilePath device path in the end.
1021 In this case, it will follow Removable Media Boot Behavior.
1022 2) Boot Option device path starts with a USB Class or USB WWID device path,
1023 and ended with Media FilePath device path.
1024 3) Boot Option device path starts with a full device path to a USB Host Controller,
1025 contains a USB Class or USB WWID device path node, while not ended with Media
1026 FilePath device path. In this case, it will follow Removable Media Boot Behavior.
1027 4) Boot Option device path starts with a full device path to a USB Host Controller,
1028 contains a USB Class or USB WWID device path node, and ended with Media
1029 FilePath device path.
1030
1031 @param FilePath The device path pointing to a load option.
1032 It could be a short-form device path.
1033 @param FullPath Return the full device path of the load option after
1034 short-form device path expanding.
1035 Caller is responsible to free it.
1036 @param FileSize Return the load option size.
1037 @param ShortformNode Pointer to the USB short-form device path node in the FilePath buffer.
1038
1039 @return The load option buffer. Caller is responsible to free the memory.
1040 **/
1041 VOID *
1042 BmExpandUsbDevicePath (
1043 IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
1044 OUT EFI_DEVICE_PATH_PROTOCOL **FullPath,
1045 OUT UINTN *FileSize,
1046 IN EFI_DEVICE_PATH_PROTOCOL *ShortformNode
1047 )
1048 {
1049 UINTN ParentDevicePathSize;
1050 EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath;
1051 EFI_DEVICE_PATH_PROTOCOL *FullDevicePath;
1052 EFI_HANDLE *Handles;
1053 UINTN HandleCount;
1054 UINTN Index;
1055 VOID *FileBuffer;
1056
1057 ParentDevicePathSize = (UINTN) ShortformNode - (UINTN) FilePath;
1058 RemainingDevicePath = NextDevicePathNode (ShortformNode);
1059 FileBuffer = NULL;
1060 Handles = BmFindUsbDevice (FilePath, ParentDevicePathSize, &HandleCount);
1061
1062 for (Index = 0; (Index < HandleCount) && (FileBuffer == NULL); Index++) {
1063 FullDevicePath = AppendDevicePath (DevicePathFromHandle (Handles[Index]), RemainingDevicePath);
1064 FileBuffer = BmGetLoadOptionBuffer (FullDevicePath, FullPath, FileSize);
1065 FreePool (FullDevicePath);
1066 }
1067
1068 if (Handles != NULL) {
1069 FreePool (Handles);
1070 }
1071
1072 return FileBuffer;
1073 }
1074
1075 /**
1076 Save the partition DevicePath to the CachedDevicePath as the first instance.
1077
1078 @param CachedDevicePath The device path cache.
1079 @param DevicePath The partition device path to be cached.
1080 **/
1081 VOID
1082 BmCachePartitionDevicePath (
1083 IN OUT EFI_DEVICE_PATH_PROTOCOL **CachedDevicePath,
1084 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
1085 )
1086 {
1087 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
1088 UINTN Count;
1089
1090 if (BmMatchDevicePaths (*CachedDevicePath, DevicePath)) {
1091 TempDevicePath = *CachedDevicePath;
1092 *CachedDevicePath = BmDelPartMatchInstance (*CachedDevicePath, DevicePath);
1093 FreePool (TempDevicePath);
1094 }
1095
1096 if (*CachedDevicePath == NULL) {
1097 *CachedDevicePath = DuplicateDevicePath (DevicePath);
1098 return;
1099 }
1100
1101 TempDevicePath = *CachedDevicePath;
1102 *CachedDevicePath = AppendDevicePathInstance (DevicePath, *CachedDevicePath);
1103 if (TempDevicePath != NULL) {
1104 FreePool (TempDevicePath);
1105 }
1106
1107 //
1108 // Here limit the device path instance number to 12, which is max number for a system support 3 IDE controller
1109 // If the user try to boot many OS in different HDs or partitions, in theory, the 'HDDP' variable maybe become larger and larger.
1110 //
1111 Count = 0;
1112 TempDevicePath = *CachedDevicePath;
1113 while (!IsDevicePathEnd (TempDevicePath)) {
1114 TempDevicePath = NextDevicePathNode (TempDevicePath);
1115 //
1116 // Parse one instance
1117 //
1118 while (!IsDevicePathEndType (TempDevicePath)) {
1119 TempDevicePath = NextDevicePathNode (TempDevicePath);
1120 }
1121 Count++;
1122 //
1123 // If the CachedDevicePath variable contain too much instance, only remain 12 instances.
1124 //
1125 if (Count == 12) {
1126 SetDevicePathEndNode (TempDevicePath);
1127 break;
1128 }
1129 }
1130 }
1131
1132 /**
1133 Expand a device path that starts with a hard drive media device path node to be a
1134 full device path that includes the full hardware path to the device. We need
1135 to do this so it can be booted. As an optimization the front match (the part point
1136 to the partition node. E.g. ACPI() /PCI()/ATA()/Partition() ) is saved in a variable
1137 so a connect all is not required on every boot. All successful history device path
1138 which point to partition node (the front part) will be saved.
1139
1140 @param FilePath The device path pointing to a load option.
1141 It could be a short-form device path.
1142 @param FullPath Return the full device path of the load option after
1143 short-form device path expanding.
1144 Caller is responsible to free it.
1145 @param FileSize Return the load option size.
1146
1147 @return The load option buffer. Caller is responsible to free the memory.
1148 **/
1149 VOID *
1150 BmExpandPartitionDevicePath (
1151 IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
1152 OUT EFI_DEVICE_PATH_PROTOCOL **FullPath,
1153 OUT UINTN *FileSize
1154 )
1155 {
1156 EFI_STATUS Status;
1157 UINTN BlockIoHandleCount;
1158 EFI_HANDLE *BlockIoBuffer;
1159 VOID *FileBuffer;
1160 EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath;
1161 UINTN Index;
1162 EFI_DEVICE_PATH_PROTOCOL *CachedDevicePath;
1163 EFI_DEVICE_PATH_PROTOCOL *TempNewDevicePath;
1164 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
1165 UINTN CachedDevicePathSize;
1166 BOOLEAN NeedAdjust;
1167 EFI_DEVICE_PATH_PROTOCOL *Instance;
1168 UINTN Size;
1169
1170 FileBuffer = NULL;
1171 //
1172 // Check if there is prestore 'HDDP' variable.
1173 // If exist, search the front path which point to partition node in the variable instants.
1174 // If fail to find or 'HDDP' not exist, reconnect all and search in all system
1175 //
1176 GetVariable2 (L"HDDP", &mBmHardDriveBootVariableGuid, (VOID **) &CachedDevicePath, &CachedDevicePathSize);
1177
1178 //
1179 // Delete the invalid 'HDDP' variable.
1180 //
1181 if ((CachedDevicePath != NULL) && !IsDevicePathValid (CachedDevicePath, CachedDevicePathSize)) {
1182 FreePool (CachedDevicePath);
1183 CachedDevicePath = NULL;
1184 Status = gRT->SetVariable (
1185 L"HDDP",
1186 &mBmHardDriveBootVariableGuid,
1187 0,
1188 0,
1189 NULL
1190 );
1191 ASSERT_EFI_ERROR (Status);
1192 }
1193
1194 if (CachedDevicePath != NULL) {
1195 TempNewDevicePath = CachedDevicePath;
1196 NeedAdjust = FALSE;
1197 do {
1198 //
1199 // Check every instance of the variable
1200 // First, check whether the instance contain the partition node, which is needed for distinguishing multi
1201 // partial partition boot option. Second, check whether the instance could be connected.
1202 //
1203 Instance = GetNextDevicePathInstance (&TempNewDevicePath, &Size);
1204 if (BmMatchPartitionDevicePathNode (Instance, (HARDDRIVE_DEVICE_PATH *) FilePath)) {
1205 //
1206 // Connect the device path instance, the device path point to hard drive media device path node
1207 // e.g. ACPI() /PCI()/ATA()/Partition()
1208 //
1209 Status = EfiBootManagerConnectDevicePath (Instance, NULL);
1210 if (!EFI_ERROR (Status)) {
1211 TempDevicePath = AppendDevicePath (Instance, NextDevicePathNode (FilePath));
1212 FileBuffer = BmGetLoadOptionBuffer (TempDevicePath, FullPath, FileSize);
1213 FreePool (TempDevicePath);
1214
1215 if (FileBuffer != NULL) {
1216 //
1217 // Adjust the 'HDDP' instances sequence if the matched one is not first one.
1218 //
1219 if (NeedAdjust) {
1220 BmCachePartitionDevicePath (&CachedDevicePath, Instance);
1221 //
1222 // Save the matching Device Path so we don't need to do a connect all next time
1223 // Failing to save only impacts performance next time expanding the short-form device path
1224 //
1225 Status = gRT->SetVariable (
1226 L"HDDP",
1227 &mBmHardDriveBootVariableGuid,
1228 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1229 GetDevicePathSize (CachedDevicePath),
1230 CachedDevicePath
1231 );
1232 }
1233
1234 FreePool (Instance);
1235 FreePool (CachedDevicePath);
1236 return FileBuffer;
1237 }
1238 }
1239 }
1240 //
1241 // Come here means the first instance is not matched
1242 //
1243 NeedAdjust = TRUE;
1244 FreePool(Instance);
1245 } while (TempNewDevicePath != NULL);
1246 }
1247
1248 //
1249 // If we get here we fail to find or 'HDDP' not exist, and now we need
1250 // to search all devices in the system for a matched partition
1251 //
1252 EfiBootManagerConnectAll ();
1253 Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiBlockIoProtocolGuid, NULL, &BlockIoHandleCount, &BlockIoBuffer);
1254 if (EFI_ERROR (Status)) {
1255 BlockIoHandleCount = 0;
1256 BlockIoBuffer = NULL;
1257 }
1258 //
1259 // Loop through all the device handles that support the BLOCK_IO Protocol
1260 //
1261 for (Index = 0; Index < BlockIoHandleCount; Index++) {
1262 BlockIoDevicePath = DevicePathFromHandle (BlockIoBuffer[Index]);
1263 if (BlockIoDevicePath == NULL) {
1264 continue;
1265 }
1266
1267 if (BmMatchPartitionDevicePathNode (BlockIoDevicePath, (HARDDRIVE_DEVICE_PATH *) FilePath)) {
1268 //
1269 // Find the matched partition device path
1270 //
1271 TempDevicePath = AppendDevicePath (BlockIoDevicePath, NextDevicePathNode (FilePath));
1272 FileBuffer = BmGetLoadOptionBuffer (TempDevicePath, FullPath, FileSize);
1273 FreePool (TempDevicePath);
1274
1275 if (FileBuffer != NULL) {
1276 BmCachePartitionDevicePath (&CachedDevicePath, BlockIoDevicePath);
1277
1278 //
1279 // Save the matching Device Path so we don't need to do a connect all next time
1280 // Failing to save only impacts performance next time expanding the short-form device path
1281 //
1282 Status = gRT->SetVariable (
1283 L"HDDP",
1284 &mBmHardDriveBootVariableGuid,
1285 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1286 GetDevicePathSize (CachedDevicePath),
1287 CachedDevicePath
1288 );
1289
1290 break;
1291 }
1292 }
1293 }
1294
1295 if (CachedDevicePath != NULL) {
1296 FreePool (CachedDevicePath);
1297 }
1298 if (BlockIoBuffer != NULL) {
1299 FreePool (BlockIoBuffer);
1300 }
1301 return FileBuffer;
1302 }
1303
1304 /**
1305 Expand the media device path which points to a BlockIo or SimpleFileSystem instance
1306 by appending EFI_REMOVABLE_MEDIA_FILE_NAME.
1307
1308 @param DevicePath The media device path pointing to a BlockIo or SimpleFileSystem instance.
1309 @param FullPath Return the full device path pointing to the load option.
1310 @param FileSize Return the size of the load option.
1311
1312 @return The load option buffer.
1313 **/
1314 VOID *
1315 BmExpandMediaDevicePath (
1316 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
1317 OUT EFI_DEVICE_PATH_PROTOCOL **FullPath,
1318 OUT UINTN *FileSize
1319 )
1320 {
1321 EFI_STATUS Status;
1322 EFI_HANDLE Handle;
1323 EFI_BLOCK_IO_PROTOCOL *BlockIo;
1324 VOID *Buffer;
1325 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
1326 UINTN Size;
1327 UINTN TempSize;
1328 EFI_HANDLE *SimpleFileSystemHandles;
1329 UINTN NumberSimpleFileSystemHandles;
1330 UINTN Index;
1331 VOID *FileBuffer;
1332 UINT32 AuthenticationStatus;
1333
1334 //
1335 // Check whether the device is connected
1336 //
1337 TempDevicePath = DevicePath;
1338 Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &TempDevicePath, &Handle);
1339 if (!EFI_ERROR (Status)) {
1340 ASSERT (IsDevicePathEnd (TempDevicePath));
1341
1342 TempDevicePath = FileDevicePath (Handle, EFI_REMOVABLE_MEDIA_FILE_NAME);
1343 FileBuffer = GetFileBufferByFilePath (TRUE, TempDevicePath, FileSize, &AuthenticationStatus);
1344 if (FileBuffer == NULL) {
1345 FreePool (TempDevicePath);
1346 TempDevicePath = NULL;
1347 }
1348 *FullPath = TempDevicePath;
1349 return FileBuffer;
1350 }
1351
1352 //
1353 // For device boot option only pointing to the removable device handle,
1354 // should make sure all its children handles (its child partion or media handles) are created and connected.
1355 //
1356 gBS->ConnectController (Handle, NULL, NULL, TRUE);
1357
1358 //
1359 // Issue a dummy read to the device to check for media change.
1360 // When the removable media is changed, any Block IO read/write will
1361 // cause the BlockIo protocol be reinstalled and EFI_MEDIA_CHANGED is
1362 // returned. After the Block IO protocol is reinstalled, subsequent
1363 // Block IO read/write will success.
1364 //
1365 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &TempDevicePath, &Handle);
1366 ASSERT_EFI_ERROR (Status);
1367 Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **) &BlockIo);
1368 ASSERT_EFI_ERROR (Status);
1369 Buffer = AllocatePool (BlockIo->Media->BlockSize);
1370 if (Buffer != NULL) {
1371 BlockIo->ReadBlocks (
1372 BlockIo,
1373 BlockIo->Media->MediaId,
1374 0,
1375 BlockIo->Media->BlockSize,
1376 Buffer
1377 );
1378 FreePool (Buffer);
1379 }
1380
1381 //
1382 // Detect the the default boot file from removable Media
1383 //
1384 FileBuffer = NULL;
1385 *FullPath = NULL;
1386 Size = GetDevicePathSize (DevicePath) - END_DEVICE_PATH_LENGTH;
1387 gBS->LocateHandleBuffer (
1388 ByProtocol,
1389 &gEfiSimpleFileSystemProtocolGuid,
1390 NULL,
1391 &NumberSimpleFileSystemHandles,
1392 &SimpleFileSystemHandles
1393 );
1394 for (Index = 0; Index < NumberSimpleFileSystemHandles; Index++) {
1395 //
1396 // Get the device path size of SimpleFileSystem handle
1397 //
1398 TempDevicePath = DevicePathFromHandle (SimpleFileSystemHandles[Index]);
1399 TempSize = GetDevicePathSize (TempDevicePath) - END_DEVICE_PATH_LENGTH;
1400 //
1401 // Check whether the device path of boot option is part of the SimpleFileSystem handle's device path
1402 //
1403 if ((Size <= TempSize) && (CompareMem (TempDevicePath, DevicePath, Size) == 0)) {
1404 TempDevicePath = FileDevicePath (SimpleFileSystemHandles[Index], EFI_REMOVABLE_MEDIA_FILE_NAME);
1405 FileBuffer = GetFileBufferByFilePath (TRUE, TempDevicePath, FileSize, &AuthenticationStatus);
1406 if (FileBuffer != NULL) {
1407 *FullPath = TempDevicePath;
1408 break;
1409 }
1410 FreePool (TempDevicePath);
1411 }
1412 }
1413
1414 if (SimpleFileSystemHandles != NULL) {
1415 FreePool (SimpleFileSystemHandles);
1416 }
1417
1418 return FileBuffer;
1419 }
1420
1421 /**
1422 Get the load option by its device path.
1423
1424 @param FilePath The device path pointing to a load option.
1425 It could be a short-form device path.
1426 @param FullPath Return the full device path of the load option after
1427 short-form device path expanding.
1428 Caller is responsible to free it.
1429 @param FileSize Return the load option size.
1430
1431 @return The load option buffer. Caller is responsible to free the memory.
1432 **/
1433 VOID *
1434 BmGetLoadOptionBuffer (
1435 IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
1436 OUT EFI_DEVICE_PATH_PROTOCOL **FullPath,
1437 OUT UINTN *FileSize
1438 )
1439 {
1440 EFI_HANDLE Handle;
1441 VOID *FileBuffer;
1442 UINT32 AuthenticationStatus;
1443 EFI_DEVICE_PATH_PROTOCOL *Node;
1444 EFI_STATUS Status;
1445
1446 ASSERT ((FilePath != NULL) && (FullPath != NULL) && (FileSize != NULL));
1447
1448 EfiBootManagerConnectDevicePath (FilePath, NULL);
1449
1450 *FullPath = NULL;
1451 *FileSize = 0;
1452 FileBuffer = NULL;
1453
1454 //
1455 // Boot from media device by adding a default file name \EFI\BOOT\BOOT{machine type short-name}.EFI
1456 //
1457 Node = FilePath;
1458 Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &Node, &Handle);
1459 if (EFI_ERROR (Status)) {
1460 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &Node, &Handle);
1461 }
1462
1463 if (!EFI_ERROR (Status) && IsDevicePathEnd (Node)) {
1464 return BmExpandMediaDevicePath (FilePath, FullPath, FileSize);
1465 }
1466
1467 //
1468 // Expand the short-form device path to full device path
1469 //
1470 if ((DevicePathType (FilePath) == MEDIA_DEVICE_PATH) &&
1471 (DevicePathSubType (FilePath) == MEDIA_HARDDRIVE_DP)) {
1472 //
1473 // Expand the Harddrive device path
1474 //
1475 return BmExpandPartitionDevicePath (FilePath, FullPath, FileSize);
1476 } else {
1477 for (Node = FilePath; !IsDevicePathEnd (Node); Node = NextDevicePathNode (Node)) {
1478 if ((DevicePathType (Node) == MESSAGING_DEVICE_PATH) &&
1479 ((DevicePathSubType (Node) == MSG_USB_CLASS_DP) || (DevicePathSubType (Node) == MSG_USB_WWID_DP))) {
1480 break;
1481 }
1482 }
1483
1484 if (!IsDevicePathEnd (Node)) {
1485 //
1486 // Expand the USB WWID/Class device path
1487 //
1488 FileBuffer = BmExpandUsbDevicePath (FilePath, FullPath, FileSize, Node);
1489 if ((FileBuffer == NULL) && (FilePath == Node)) {
1490 //
1491 // Boot Option device path starts with USB Class or USB WWID device path.
1492 // For Boot Option device path which doesn't begin with the USB Class or
1493 // USB WWID device path, it's not needed to connect again here.
1494 //
1495 BmConnectUsbShortFormDevicePath (FilePath);
1496 FileBuffer = BmExpandUsbDevicePath (FilePath, FullPath, FileSize, Node);
1497 }
1498 return FileBuffer;
1499 }
1500 }
1501
1502 //
1503 // Fix up the boot option path if it points to a FV in memory map style of device path
1504 //
1505 if (BmIsMemmapFvFilePath (FilePath)) {
1506 return BmGetFileBufferByMemmapFv (FilePath, FullPath, FileSize);
1507 }
1508
1509 //
1510 // Directly reads the load option when it doesn't reside in simple file system instance (LoadFile/LoadFile2),
1511 // or it directly points to a file in simple file system instance.
1512 //
1513 Node = FilePath;
1514 Status = gBS->LocateDevicePath (&gEfiLoadFileProtocolGuid, &Node, &Handle);
1515 FileBuffer = GetFileBufferByFilePath (TRUE, FilePath, FileSize, &AuthenticationStatus);
1516 if (FileBuffer != NULL) {
1517 if (EFI_ERROR (Status)) {
1518 *FullPath = DuplicateDevicePath (FilePath);
1519 } else {
1520 //
1521 // LoadFile () may cause the device path of the Handle be updated.
1522 //
1523 *FullPath = AppendDevicePath (DevicePathFromHandle (Handle), Node);
1524 }
1525 }
1526
1527 return FileBuffer;
1528 }
1529
1530 /**
1531 Attempt to boot the EFI boot option. This routine sets L"BootCurent" and
1532 also signals the EFI ready to boot event. If the device path for the option
1533 starts with a BBS device path a legacy boot is attempted via the registered
1534 gLegacyBoot function. Short form device paths are also supported via this
1535 rountine. A device path starting with MEDIA_HARDDRIVE_DP, MSG_USB_WWID_DP,
1536 MSG_USB_CLASS_DP gets expaned out to find the first device that matches.
1537 If the BootOption Device Path fails the removable media boot algorithm
1538 is attempted (\EFI\BOOTIA32.EFI, \EFI\BOOTX64.EFI,... only one file type
1539 is tried per processor type)
1540
1541 @param BootOption Boot Option to try and boot.
1542 On return, BootOption->Status contains the boot status.
1543 EFI_SUCCESS BootOption was booted
1544 EFI_UNSUPPORTED A BBS device path was found with no valid callback
1545 registered via EfiBootManagerInitialize().
1546 EFI_NOT_FOUND The BootOption was not found on the system
1547 !EFI_SUCCESS BootOption failed with this error status
1548
1549 **/
1550 VOID
1551 EFIAPI
1552 EfiBootManagerBoot (
1553 IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption
1554 )
1555 {
1556 EFI_STATUS Status;
1557 EFI_HANDLE ImageHandle;
1558 EFI_LOADED_IMAGE_PROTOCOL *ImageInfo;
1559 UINT16 Uint16;
1560 UINTN OptionNumber;
1561 UINTN OriginalOptionNumber;
1562 EFI_DEVICE_PATH_PROTOCOL *FilePath;
1563 EFI_DEVICE_PATH_PROTOCOL *Node;
1564 EFI_HANDLE FvHandle;
1565 VOID *FileBuffer;
1566 UINTN FileSize;
1567 EFI_BOOT_LOGO_PROTOCOL *BootLogo;
1568 EFI_EVENT LegacyBootEvent;
1569
1570 if (BootOption == NULL) {
1571 return;
1572 }
1573
1574 if (BootOption->FilePath == NULL || BootOption->OptionType != LoadOptionTypeBoot) {
1575 BootOption->Status = EFI_INVALID_PARAMETER;
1576 return;
1577 }
1578
1579 //
1580 // 1. Create Boot#### for a temporary boot if there is no match Boot#### (i.e. a boot by selected a EFI Shell using "Boot From File")
1581 //
1582 OptionNumber = BmFindBootOptionInVariable (BootOption);
1583 if (OptionNumber == LoadOptionNumberUnassigned) {
1584 Status = BmGetFreeOptionNumber (LoadOptionTypeBoot, &Uint16);
1585 if (!EFI_ERROR (Status)) {
1586 //
1587 // Save the BootOption->OptionNumber to restore later
1588 //
1589 OptionNumber = Uint16;
1590 OriginalOptionNumber = BootOption->OptionNumber;
1591 BootOption->OptionNumber = OptionNumber;
1592 Status = EfiBootManagerLoadOptionToVariable (BootOption);
1593 BootOption->OptionNumber = OriginalOptionNumber;
1594 }
1595
1596 if (EFI_ERROR (Status)) {
1597 DEBUG ((EFI_D_ERROR, "[Bds] Failed to create Boot#### for a temporary boot - %r!\n", Status));
1598 BootOption->Status = Status;
1599 return ;
1600 }
1601 }
1602
1603 //
1604 // 2. Set BootCurrent
1605 //
1606 Uint16 = (UINT16) OptionNumber;
1607 BmSetVariableAndReportStatusCodeOnError (
1608 L"BootCurrent",
1609 &gEfiGlobalVariableGuid,
1610 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
1611 sizeof (UINT16),
1612 &Uint16
1613 );
1614
1615 //
1616 // 3. Signal the EVT_SIGNAL_READY_TO_BOOT event when we are about to load and execute
1617 // the boot option.
1618 //
1619 Node = BootOption->FilePath;
1620 Status = gBS->LocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &Node, &FvHandle);
1621 if (!EFI_ERROR (Status) && CompareGuid (
1622 EfiGetNameGuidFromFwVolDevicePathNode ((CONST MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) Node),
1623 PcdGetPtr (PcdBootManagerMenuFile)
1624 )) {
1625 DEBUG ((EFI_D_INFO, "[Bds] Booting Boot Manager Menu.\n"));
1626 BmStopHotkeyService (NULL, NULL);
1627 } else {
1628 EfiSignalEventReadyToBoot();
1629 //
1630 // Report Status Code to indicate ReadyToBoot was signalled
1631 //
1632 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_READY_TO_BOOT_EVENT));
1633 //
1634 // 4. Repair system through DriverHealth protocol
1635 //
1636 BmRepairAllControllers ();
1637 }
1638
1639 PERF_START_EX (gImageHandle, "BdsAttempt", NULL, 0, (UINT32) OptionNumber);
1640
1641 //
1642 // 5. Load EFI boot option to ImageHandle
1643 //
1644 ImageHandle = NULL;
1645 if (DevicePathType (BootOption->FilePath) != BBS_DEVICE_PATH) {
1646 Status = EFI_NOT_FOUND;
1647 FileBuffer = BmGetLoadOptionBuffer (BootOption->FilePath, &FilePath, &FileSize);
1648 DEBUG_CODE (
1649 if (FileBuffer != NULL && CompareMem (BootOption->FilePath, FilePath, GetDevicePathSize (FilePath)) != 0) {
1650 DEBUG ((EFI_D_INFO, "[Bds] DevicePath expand: "));
1651 BmPrintDp (BootOption->FilePath);
1652 DEBUG ((EFI_D_INFO, " -> "));
1653 BmPrintDp (FilePath);
1654 DEBUG ((EFI_D_INFO, "\n"));
1655 }
1656 );
1657 if (BmIsLoadOptionPeHeaderValid (BootOption->OptionType, FileBuffer, FileSize)) {
1658 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderLoad));
1659 Status = gBS->LoadImage (
1660 TRUE,
1661 gImageHandle,
1662 FilePath,
1663 FileBuffer,
1664 FileSize,
1665 &ImageHandle
1666 );
1667 }
1668 if (FileBuffer != NULL) {
1669 FreePool (FileBuffer);
1670 }
1671 if (FilePath != NULL) {
1672 FreePool (FilePath);
1673 }
1674
1675 if (EFI_ERROR (Status)) {
1676 //
1677 // Report Status Code to indicate that the failure to load boot option
1678 //
1679 REPORT_STATUS_CODE (
1680 EFI_ERROR_CODE | EFI_ERROR_MINOR,
1681 (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_EC_BOOT_OPTION_LOAD_ERROR)
1682 );
1683 BootOption->Status = Status;
1684 return;
1685 }
1686 }
1687
1688 //
1689 // 6. Adjust the different type memory page number just before booting
1690 // and save the updated info into the variable for next boot to use
1691 //
1692 if ((BootOption->Attributes & LOAD_OPTION_CATEGORY) == LOAD_OPTION_CATEGORY_BOOT) {
1693 if (PcdGetBool (PcdResetOnMemoryTypeInformationChange)) {
1694 BmSetMemoryTypeInformationVariable ();
1695 }
1696 }
1697
1698 DEBUG_CODE_BEGIN();
1699 if (BootOption->Description == NULL) {
1700 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "[Bds]Booting from unknown device path\n"));
1701 } else {
1702 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "[Bds]Booting %s\n", BootOption->Description));
1703 }
1704 DEBUG_CODE_END();
1705
1706 //
1707 // Check to see if we should legacy BOOT. If yes then do the legacy boot
1708 // Write boot to OS performance data for Legacy boot
1709 //
1710 if ((DevicePathType (BootOption->FilePath) == BBS_DEVICE_PATH) && (DevicePathSubType (BootOption->FilePath) == BBS_BBS_DP)) {
1711 if (mBmLegacyBoot != NULL) {
1712 //
1713 // Write boot to OS performance data for legacy boot.
1714 //
1715 PERF_CODE (
1716 //
1717 // Create an event to be signalled when Legacy Boot occurs to write performance data.
1718 //
1719 Status = EfiCreateEventLegacyBootEx(
1720 TPL_NOTIFY,
1721 BmWriteBootToOsPerformanceData,
1722 NULL,
1723 &LegacyBootEvent
1724 );
1725 ASSERT_EFI_ERROR (Status);
1726 );
1727
1728 mBmLegacyBoot (BootOption);
1729 } else {
1730 BootOption->Status = EFI_UNSUPPORTED;
1731 }
1732
1733 PERF_END_EX (gImageHandle, "BdsAttempt", NULL, 0, (UINT32) OptionNumber);
1734 return;
1735 }
1736
1737 //
1738 // Provide the image with its load options
1739 //
1740 Status = gBS->HandleProtocol (ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &ImageInfo);
1741 ASSERT_EFI_ERROR (Status);
1742
1743 ImageInfo->LoadOptionsSize = BootOption->OptionalDataSize;
1744 ImageInfo->LoadOptions = BootOption->OptionalData;
1745
1746 //
1747 // Clean to NULL because the image is loaded directly from the firmwares boot manager.
1748 //
1749 ImageInfo->ParentHandle = NULL;
1750
1751 //
1752 // Before calling the image, enable the Watchdog Timer for 5 minutes period
1753 //
1754 gBS->SetWatchdogTimer (5 * 60, 0x0000, 0x00, NULL);
1755
1756 //
1757 // Write boot to OS performance data for UEFI boot
1758 //
1759 PERF_CODE (
1760 BmWriteBootToOsPerformanceData (NULL, NULL);
1761 );
1762
1763 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderStart));
1764
1765 Status = gBS->StartImage (ImageHandle, &BootOption->ExitDataSize, &BootOption->ExitData);
1766 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Image Return Status = %r\n", Status));
1767 BootOption->Status = Status;
1768 if (EFI_ERROR (Status)) {
1769 //
1770 // Report Status Code to indicate that boot failure
1771 //
1772 REPORT_STATUS_CODE (
1773 EFI_ERROR_CODE | EFI_ERROR_MINOR,
1774 (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_EC_BOOT_OPTION_FAILED)
1775 );
1776 }
1777 PERF_END_EX (gImageHandle, "BdsAttempt", NULL, 0, (UINT32) OptionNumber);
1778
1779 //
1780 // Clear the Watchdog Timer after the image returns
1781 //
1782 gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL);
1783
1784 //
1785 // Set Logo status invalid after trying one boot option
1786 //
1787 BootLogo = NULL;
1788 Status = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **) &BootLogo);
1789 if (!EFI_ERROR (Status) && (BootLogo != NULL)) {
1790 Status = BootLogo->SetBootLogo (BootLogo, NULL, 0, 0, 0, 0);
1791 ASSERT_EFI_ERROR (Status);
1792 }
1793
1794 //
1795 // Clear Boot Current
1796 //
1797 Status = gRT->SetVariable (
1798 L"BootCurrent",
1799 &gEfiGlobalVariableGuid,
1800 0,
1801 0,
1802 NULL
1803 );
1804 //
1805 // Deleting variable with current variable implementation shouldn't fail.
1806 // When BootXXXX (e.g.: BootManagerMenu) boots BootYYYY, exiting BootYYYY causes BootCurrent deleted,
1807 // exiting BootXXXX causes deleting BootCurrent returns EFI_NOT_FOUND.
1808 //
1809 ASSERT (Status == EFI_SUCCESS || Status == EFI_NOT_FOUND);
1810 }
1811
1812 /**
1813 Check whether there is a instance in BlockIoDevicePath, which contain multi device path
1814 instances, has the same partition node with HardDriveDevicePath device path
1815
1816 @param BlockIoDevicePath Multi device path instances which need to check
1817 @param HardDriveDevicePath A device path which starts with a hard drive media
1818 device path.
1819
1820 @retval TRUE There is a matched device path instance.
1821 @retval FALSE There is no matched device path instance.
1822
1823 **/
1824 BOOLEAN
1825 BmMatchPartitionDevicePathNode (
1826 IN EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath,
1827 IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath
1828 )
1829 {
1830 HARDDRIVE_DEVICE_PATH *Node;
1831
1832 if ((BlockIoDevicePath == NULL) || (HardDriveDevicePath == NULL)) {
1833 return FALSE;
1834 }
1835
1836 //
1837 // find the partition device path node
1838 //
1839 while (!IsDevicePathEnd (BlockIoDevicePath)) {
1840 if ((DevicePathType (BlockIoDevicePath) == MEDIA_DEVICE_PATH) &&
1841 (DevicePathSubType (BlockIoDevicePath) == MEDIA_HARDDRIVE_DP)
1842 ) {
1843 break;
1844 }
1845
1846 BlockIoDevicePath = NextDevicePathNode (BlockIoDevicePath);
1847 }
1848
1849 if (IsDevicePathEnd (BlockIoDevicePath)) {
1850 return FALSE;
1851 }
1852
1853 //
1854 // See if the harddrive device path in blockio matches the orig Hard Drive Node
1855 //
1856 Node = (HARDDRIVE_DEVICE_PATH *) BlockIoDevicePath;
1857
1858 //
1859 // Match Signature and PartitionNumber.
1860 // Unused bytes in Signature are initiaized with zeros.
1861 //
1862 return (BOOLEAN) (
1863 (Node->PartitionNumber == HardDriveDevicePath->PartitionNumber) &&
1864 (Node->MBRType == HardDriveDevicePath->MBRType) &&
1865 (Node->SignatureType == HardDriveDevicePath->SignatureType) &&
1866 (CompareMem (Node->Signature, HardDriveDevicePath->Signature, sizeof (Node->Signature)) == 0)
1867 );
1868 }
1869
1870 /**
1871 Enumerate all boot option descriptions and append " 2"/" 3"/... to make
1872 unique description.
1873
1874 @param BootOptions Array of boot options.
1875 @param BootOptionCount Count of boot options.
1876 **/
1877 VOID
1878 BmMakeBootOptionDescriptionUnique (
1879 EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions,
1880 UINTN BootOptionCount
1881 )
1882 {
1883 UINTN Base;
1884 UINTN Index;
1885 UINTN DescriptionSize;
1886 UINTN MaxSuffixSize;
1887 BOOLEAN *Visited;
1888 UINTN MatchCount;
1889
1890 if (BootOptionCount == 0) {
1891 return;
1892 }
1893
1894 //
1895 // Calculate the maximum buffer size for the number suffix.
1896 // The initial sizeof (CHAR16) is for the blank space before the number.
1897 //
1898 MaxSuffixSize = sizeof (CHAR16);
1899 for (Index = BootOptionCount; Index != 0; Index = Index / 10) {
1900 MaxSuffixSize += sizeof (CHAR16);
1901 }
1902
1903 Visited = AllocateZeroPool (sizeof (BOOLEAN) * BootOptionCount);
1904 ASSERT (Visited != NULL);
1905
1906 for (Base = 0; Base < BootOptionCount; Base++) {
1907 if (!Visited[Base]) {
1908 MatchCount = 1;
1909 Visited[Base] = TRUE;
1910 DescriptionSize = StrSize (BootOptions[Base].Description);
1911 for (Index = Base + 1; Index < BootOptionCount; Index++) {
1912 if (!Visited[Index] && StrCmp (BootOptions[Base].Description, BootOptions[Index].Description) == 0) {
1913 Visited[Index] = TRUE;
1914 MatchCount++;
1915 FreePool (BootOptions[Index].Description);
1916 BootOptions[Index].Description = AllocatePool (DescriptionSize + MaxSuffixSize);
1917 UnicodeSPrint (
1918 BootOptions[Index].Description, DescriptionSize + MaxSuffixSize,
1919 L"%s %d",
1920 BootOptions[Base].Description, MatchCount
1921 );
1922 }
1923 }
1924 }
1925 }
1926
1927 FreePool (Visited);
1928 }
1929
1930 /**
1931 Emuerate all possible bootable medias in the following order:
1932 1. Removable BlockIo - The boot option only points to the removable media
1933 device, like USB key, DVD, Floppy etc.
1934 2. Fixed BlockIo - The boot option only points to a Fixed blockIo device,
1935 like HardDisk.
1936 3. Non-BlockIo SimpleFileSystem - The boot option points to a device supporting
1937 SimpleFileSystem Protocol, but not supporting BlockIo
1938 protocol.
1939 4. LoadFile - The boot option points to the media supporting
1940 LoadFile protocol.
1941 Reference: UEFI Spec chapter 3.3 Boot Option Variables Default Boot Behavior
1942
1943 @param BootOptionCount Return the boot option count which has been found.
1944
1945 @retval Pointer to the boot option array.
1946 **/
1947 EFI_BOOT_MANAGER_LOAD_OPTION *
1948 BmEnumerateBootOptions (
1949 UINTN *BootOptionCount
1950 )
1951 {
1952 EFI_STATUS Status;
1953 EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions;
1954 UINTN HandleCount;
1955 EFI_HANDLE *Handles;
1956 EFI_BLOCK_IO_PROTOCOL *BlkIo;
1957 UINTN Removable;
1958 UINTN Index;
1959 CHAR16 *Description;
1960
1961 ASSERT (BootOptionCount != NULL);
1962
1963 *BootOptionCount = 0;
1964 BootOptions = NULL;
1965
1966 //
1967 // Parse removable block io followed by fixed block io
1968 //
1969 gBS->LocateHandleBuffer (
1970 ByProtocol,
1971 &gEfiBlockIoProtocolGuid,
1972 NULL,
1973 &HandleCount,
1974 &Handles
1975 );
1976
1977 for (Removable = 0; Removable < 2; Removable++) {
1978 for (Index = 0; Index < HandleCount; Index++) {
1979 Status = gBS->HandleProtocol (
1980 Handles[Index],
1981 &gEfiBlockIoProtocolGuid,
1982 (VOID **) &BlkIo
1983 );
1984 if (EFI_ERROR (Status)) {
1985 continue;
1986 }
1987
1988 //
1989 // Skip the logical partitions
1990 //
1991 if (BlkIo->Media->LogicalPartition) {
1992 continue;
1993 }
1994
1995 //
1996 // Skip the fixed block io then the removable block io
1997 //
1998 if (BlkIo->Media->RemovableMedia == ((Removable == 0) ? FALSE : TRUE)) {
1999 continue;
2000 }
2001
2002 Description = BmGetBootDescription (Handles[Index]);
2003 BootOptions = ReallocatePool (
2004 sizeof (EFI_BOOT_MANAGER_LOAD_OPTION) * (*BootOptionCount),
2005 sizeof (EFI_BOOT_MANAGER_LOAD_OPTION) * (*BootOptionCount + 1),
2006 BootOptions
2007 );
2008 ASSERT (BootOptions != NULL);
2009
2010 Status = EfiBootManagerInitializeLoadOption (
2011 &BootOptions[(*BootOptionCount)++],
2012 LoadOptionNumberUnassigned,
2013 LoadOptionTypeBoot,
2014 LOAD_OPTION_ACTIVE,
2015 Description,
2016 DevicePathFromHandle (Handles[Index]),
2017 NULL,
2018 0
2019 );
2020 ASSERT_EFI_ERROR (Status);
2021
2022 FreePool (Description);
2023 }
2024 }
2025
2026 if (HandleCount != 0) {
2027 FreePool (Handles);
2028 }
2029
2030 //
2031 // Parse simple file system not based on block io
2032 //
2033 gBS->LocateHandleBuffer (
2034 ByProtocol,
2035 &gEfiSimpleFileSystemProtocolGuid,
2036 NULL,
2037 &HandleCount,
2038 &Handles
2039 );
2040 for (Index = 0; Index < HandleCount; Index++) {
2041 Status = gBS->HandleProtocol (
2042 Handles[Index],
2043 &gEfiBlockIoProtocolGuid,
2044 (VOID **) &BlkIo
2045 );
2046 if (!EFI_ERROR (Status)) {
2047 //
2048 // Skip if the file system handle supports a BlkIo protocol, which we've handled in above
2049 //
2050 continue;
2051 }
2052 Description = BmGetBootDescription (Handles[Index]);
2053 BootOptions = ReallocatePool (
2054 sizeof (EFI_BOOT_MANAGER_LOAD_OPTION) * (*BootOptionCount),
2055 sizeof (EFI_BOOT_MANAGER_LOAD_OPTION) * (*BootOptionCount + 1),
2056 BootOptions
2057 );
2058 ASSERT (BootOptions != NULL);
2059
2060 Status = EfiBootManagerInitializeLoadOption (
2061 &BootOptions[(*BootOptionCount)++],
2062 LoadOptionNumberUnassigned,
2063 LoadOptionTypeBoot,
2064 LOAD_OPTION_ACTIVE,
2065 Description,
2066 DevicePathFromHandle (Handles[Index]),
2067 NULL,
2068 0
2069 );
2070 ASSERT_EFI_ERROR (Status);
2071 FreePool (Description);
2072 }
2073
2074 if (HandleCount != 0) {
2075 FreePool (Handles);
2076 }
2077
2078 //
2079 // Parse load file, assuming UEFI Network boot option
2080 //
2081 gBS->LocateHandleBuffer (
2082 ByProtocol,
2083 &gEfiLoadFileProtocolGuid,
2084 NULL,
2085 &HandleCount,
2086 &Handles
2087 );
2088 for (Index = 0; Index < HandleCount; Index++) {
2089
2090 Description = BmGetBootDescription (Handles[Index]);
2091 BootOptions = ReallocatePool (
2092 sizeof (EFI_BOOT_MANAGER_LOAD_OPTION) * (*BootOptionCount),
2093 sizeof (EFI_BOOT_MANAGER_LOAD_OPTION) * (*BootOptionCount + 1),
2094 BootOptions
2095 );
2096 ASSERT (BootOptions != NULL);
2097
2098 Status = EfiBootManagerInitializeLoadOption (
2099 &BootOptions[(*BootOptionCount)++],
2100 LoadOptionNumberUnassigned,
2101 LoadOptionTypeBoot,
2102 LOAD_OPTION_ACTIVE,
2103 Description,
2104 DevicePathFromHandle (Handles[Index]),
2105 NULL,
2106 0
2107 );
2108 ASSERT_EFI_ERROR (Status);
2109 FreePool (Description);
2110 }
2111
2112 if (HandleCount != 0) {
2113 FreePool (Handles);
2114 }
2115
2116 BmMakeBootOptionDescriptionUnique (BootOptions, *BootOptionCount);
2117 return BootOptions;
2118 }
2119
2120 /**
2121 The function enumerates all boot options, creates them and registers them in the BootOrder variable.
2122 **/
2123 VOID
2124 EFIAPI
2125 EfiBootManagerRefreshAllBootOption (
2126 VOID
2127 )
2128 {
2129 EFI_STATUS Status;
2130 EFI_BOOT_MANAGER_LOAD_OPTION *NvBootOptions;
2131 UINTN NvBootOptionCount;
2132 EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions;
2133 UINTN BootOptionCount;
2134 UINTN Index;
2135
2136 //
2137 // Optionally refresh the legacy boot option
2138 //
2139 if (mBmRefreshLegacyBootOption != NULL) {
2140 mBmRefreshLegacyBootOption ();
2141 }
2142
2143 BootOptions = BmEnumerateBootOptions (&BootOptionCount);
2144 NvBootOptions = EfiBootManagerGetLoadOptions (&NvBootOptionCount, LoadOptionTypeBoot);
2145
2146 //
2147 // Mark the boot option as added by BDS by setting OptionalData to a special GUID
2148 //
2149 for (Index = 0; Index < BootOptionCount; Index++) {
2150 BootOptions[Index].OptionalData = AllocateCopyPool (sizeof (EFI_GUID), &mBmAutoCreateBootOptionGuid);
2151 BootOptions[Index].OptionalDataSize = sizeof (EFI_GUID);
2152 }
2153
2154 //
2155 // Remove invalid EFI boot options from NV
2156 //
2157 for (Index = 0; Index < NvBootOptionCount; Index++) {
2158 if (((DevicePathType (NvBootOptions[Index].FilePath) != BBS_DEVICE_PATH) ||
2159 (DevicePathSubType (NvBootOptions[Index].FilePath) != BBS_BBS_DP)
2160 ) &&
2161 (NvBootOptions[Index].OptionalDataSize == sizeof (EFI_GUID)) &&
2162 CompareGuid ((EFI_GUID *) NvBootOptions[Index].OptionalData, &mBmAutoCreateBootOptionGuid)
2163 ) {
2164 //
2165 // Only check those added by BDS
2166 // so that the boot options added by end-user or OS installer won't be deleted
2167 //
2168 if (EfiBootManagerFindLoadOption (&NvBootOptions[Index], BootOptions, BootOptionCount) == (UINTN) -1) {
2169 Status = EfiBootManagerDeleteLoadOptionVariable (NvBootOptions[Index].OptionNumber, LoadOptionTypeBoot);
2170 //
2171 // Deleting variable with current variable implementation shouldn't fail.
2172 //
2173 ASSERT_EFI_ERROR (Status);
2174 }
2175 }
2176 }
2177
2178 //
2179 // Add new EFI boot options to NV
2180 //
2181 for (Index = 0; Index < BootOptionCount; Index++) {
2182 if (EfiBootManagerFindLoadOption (&BootOptions[Index], NvBootOptions, NvBootOptionCount) == (UINTN) -1) {
2183 EfiBootManagerAddLoadOptionVariable (&BootOptions[Index], (UINTN) -1);
2184 //
2185 // Try best to add the boot options so continue upon failure.
2186 //
2187 }
2188 }
2189
2190 EfiBootManagerFreeLoadOptions (BootOptions, BootOptionCount);
2191 EfiBootManagerFreeLoadOptions (NvBootOptions, NvBootOptionCount);
2192 }
2193
2194 /**
2195 This function is called to create the boot option for the Boot Manager Menu.
2196
2197 The Boot Manager Menu is shown after successfully booting a boot option.
2198 Assume the BootManagerMenuFile is in the same FV as the module links to this library.
2199
2200 @param BootOption Return the boot option of the Boot Manager Menu
2201
2202 @retval EFI_SUCCESS Successfully register the Boot Manager Menu.
2203 @retval Status Return status of gRT->SetVariable (). BootOption still points
2204 to the Boot Manager Menu even the Status is not EFI_SUCCESS.
2205 **/
2206 EFI_STATUS
2207 BmRegisterBootManagerMenu (
2208 OUT EFI_BOOT_MANAGER_LOAD_OPTION *BootOption
2209 )
2210 {
2211 EFI_STATUS Status;
2212 CHAR16 *Description;
2213 UINTN DescriptionLength;
2214 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2215 EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
2216 MEDIA_FW_VOL_FILEPATH_DEVICE_PATH FileNode;
2217
2218 Status = GetSectionFromFv (
2219 PcdGetPtr (PcdBootManagerMenuFile),
2220 EFI_SECTION_USER_INTERFACE,
2221 0,
2222 (VOID **) &Description,
2223 &DescriptionLength
2224 );
2225 if (EFI_ERROR (Status)) {
2226 Description = NULL;
2227 }
2228
2229 EfiInitializeFwVolDevicepathNode (&FileNode, PcdGetPtr (PcdBootManagerMenuFile));
2230 Status = gBS->HandleProtocol (
2231 gImageHandle,
2232 &gEfiLoadedImageProtocolGuid,
2233 (VOID **) &LoadedImage
2234 );
2235 ASSERT_EFI_ERROR (Status);
2236 DevicePath = AppendDevicePathNode (
2237 DevicePathFromHandle (LoadedImage->DeviceHandle),
2238 (EFI_DEVICE_PATH_PROTOCOL *) &FileNode
2239 );
2240 ASSERT (DevicePath != NULL);
2241
2242 Status = EfiBootManagerInitializeLoadOption (
2243 BootOption,
2244 LoadOptionNumberUnassigned,
2245 LoadOptionTypeBoot,
2246 LOAD_OPTION_CATEGORY_APP | LOAD_OPTION_ACTIVE | LOAD_OPTION_HIDDEN,
2247 (Description != NULL) ? Description : L"Boot Manager Menu",
2248 DevicePath,
2249 NULL,
2250 0
2251 );
2252 ASSERT_EFI_ERROR (Status);
2253 FreePool (DevicePath);
2254 if (Description != NULL) {
2255 FreePool (Description);
2256 }
2257
2258 DEBUG_CODE (
2259 EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions;
2260 UINTN BootOptionCount;
2261
2262 BootOptions = EfiBootManagerGetLoadOptions (&BootOptionCount, LoadOptionTypeBoot);
2263 ASSERT (EfiBootManagerFindLoadOption (BootOption, BootOptions, BootOptionCount) == -1);
2264 EfiBootManagerFreeLoadOptions (BootOptions, BootOptionCount);
2265 );
2266
2267 return EfiBootManagerAddLoadOptionVariable (BootOption, 0);
2268 }
2269
2270 /**
2271 Return the boot option corresponding to the Boot Manager Menu.
2272 It may automatically create one if the boot option hasn't been created yet.
2273
2274 @param BootOption Return the Boot Manager Menu.
2275
2276 @retval EFI_SUCCESS The Boot Manager Menu is successfully returned.
2277 @retval Status Return status of gRT->SetVariable (). BootOption still points
2278 to the Boot Manager Menu even the Status is not EFI_SUCCESS.
2279 **/
2280 EFI_STATUS
2281 EFIAPI
2282 EfiBootManagerGetBootManagerMenu (
2283 EFI_BOOT_MANAGER_LOAD_OPTION *BootOption
2284 )
2285 {
2286 EFI_STATUS Status;
2287 UINTN BootOptionCount;
2288 EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions;
2289 UINTN Index;
2290 EFI_DEVICE_PATH_PROTOCOL *Node;
2291 EFI_HANDLE FvHandle;
2292
2293 BootOptions = EfiBootManagerGetLoadOptions (&BootOptionCount, LoadOptionTypeBoot);
2294
2295 for (Index = 0; Index < BootOptionCount; Index++) {
2296 Node = BootOptions[Index].FilePath;
2297 Status = gBS->LocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &Node, &FvHandle);
2298 if (!EFI_ERROR (Status)) {
2299 if (CompareGuid (
2300 EfiGetNameGuidFromFwVolDevicePathNode ((CONST MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) Node),
2301 PcdGetPtr (PcdBootManagerMenuFile)
2302 )
2303 ) {
2304 Status = EfiBootManagerInitializeLoadOption (
2305 BootOption,
2306 BootOptions[Index].OptionNumber,
2307 BootOptions[Index].OptionType,
2308 BootOptions[Index].Attributes,
2309 BootOptions[Index].Description,
2310 BootOptions[Index].FilePath,
2311 BootOptions[Index].OptionalData,
2312 BootOptions[Index].OptionalDataSize
2313 );
2314 ASSERT_EFI_ERROR (Status);
2315 break;
2316 }
2317 }
2318 }
2319
2320 EfiBootManagerFreeLoadOptions (BootOptions, BootOptionCount);
2321
2322 //
2323 // Automatically create the Boot#### for Boot Manager Menu when not found.
2324 //
2325 if (Index == BootOptionCount) {
2326 return BmRegisterBootManagerMenu (BootOption);
2327 } else {
2328 return EFI_SUCCESS;
2329 }
2330 }
2331