]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Universal/BdsDxe/BdsEntry.c
49e403e18104b7da3e34272eebc48356d6947bd1
[mirror_edk2.git] / MdeModulePkg / Universal / BdsDxe / BdsEntry.c
1 /** @file
2 This module produce main entry for BDS phase - BdsEntry.
3 When this module was dispatched by DxeCore, gEfiBdsArchProtocolGuid will be installed
4 which contains interface of BdsEntry.
5 After DxeCore finish DXE phase, gEfiBdsArchProtocolGuid->BdsEntry will be invoked
6 to enter BDS phase.
7
8 Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.<BR>
9 (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
10 (C) Copyright 2015 Hewlett-Packard Development Company, L.P.<BR>
11 This program and the accompanying materials
12 are licensed and made available under the terms and conditions of the BSD License
13 which accompanies this distribution. The full text of the license may be found at
14 http://opensource.org/licenses/bsd-license.php
15
16 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
17 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
18
19 **/
20
21 #include "Bds.h"
22 #include "Language.h"
23 #include "HwErrRecSupport.h"
24
25 #define SET_BOOT_OPTION_SUPPORT_KEY_COUNT(a, c) { \
26 (a) = ((a) & ~EFI_BOOT_OPTION_SUPPORT_COUNT) | (((c) << LowBitSet32 (EFI_BOOT_OPTION_SUPPORT_COUNT)) & EFI_BOOT_OPTION_SUPPORT_COUNT); \
27 }
28
29 ///
30 /// BDS arch protocol instance initial value.
31 ///
32 EFI_BDS_ARCH_PROTOCOL gBds = {
33 BdsEntry
34 };
35
36 //
37 // gConnectConInEvent - Event which is signaled when ConIn connection is required
38 //
39 EFI_EVENT gConnectConInEvent = NULL;
40
41 ///
42 /// The read-only variables defined in UEFI Spec.
43 ///
44 CHAR16 *mReadOnlyVariables[] = {
45 EFI_PLATFORM_LANG_CODES_VARIABLE_NAME,
46 EFI_LANG_CODES_VARIABLE_NAME,
47 EFI_BOOT_OPTION_SUPPORT_VARIABLE_NAME,
48 EFI_HW_ERR_REC_SUPPORT_VARIABLE_NAME,
49 EFI_OS_INDICATIONS_SUPPORT_VARIABLE_NAME
50 };
51
52 CHAR16 *mBdsLoadOptionName[] = {
53 L"Driver",
54 L"SysPrep",
55 L"Boot",
56 L"PlatformRecovery"
57 };
58
59 /**
60 Event to Connect ConIn.
61
62 @param Event Event whose notification function is being invoked.
63 @param Context Pointer to the notification function's context,
64 which is implementation-dependent.
65
66 **/
67 VOID
68 EFIAPI
69 BdsDxeOnConnectConInCallBack (
70 IN EFI_EVENT Event,
71 IN VOID *Context
72 )
73 {
74 EFI_STATUS Status;
75
76 //
77 // When Osloader call ReadKeyStroke to signal this event
78 // no driver dependency is assumed existing. So use a non-dispatch version
79 //
80 Status = EfiBootManagerConnectConsoleVariable (ConIn);
81 if (EFI_ERROR (Status)) {
82 //
83 // Should not enter this case, if enter, the keyboard will not work.
84 // May need platfrom policy to connect keyboard.
85 //
86 DEBUG ((EFI_D_WARN, "[Bds] Connect ConIn failed - %r!!!\n", Status));
87 }
88 }
89 /**
90 Notify function for event group EFI_EVENT_GROUP_READY_TO_BOOT. This is used to
91 check whether there is remaining deferred load images.
92
93 @param[in] Event The Event that is being processed.
94 @param[in] Context The Event Context.
95
96 **/
97 VOID
98 EFIAPI
99 CheckDeferredLoadImageOnReadyToBoot (
100 IN EFI_EVENT Event,
101 IN VOID *Context
102 )
103 {
104 EFI_STATUS Status;
105 EFI_DEFERRED_IMAGE_LOAD_PROTOCOL *DeferredImage;
106 UINTN HandleCount;
107 EFI_HANDLE *Handles;
108 UINTN Index;
109 UINTN ImageIndex;
110 EFI_DEVICE_PATH_PROTOCOL *ImageDevicePath;
111 VOID *Image;
112 UINTN ImageSize;
113 BOOLEAN BootOption;
114 CHAR16 *DevicePathStr;
115
116 //
117 // Find all the deferred image load protocols.
118 //
119 HandleCount = 0;
120 Handles = NULL;
121 Status = gBS->LocateHandleBuffer (
122 ByProtocol,
123 &gEfiDeferredImageLoadProtocolGuid,
124 NULL,
125 &HandleCount,
126 &Handles
127 );
128 if (EFI_ERROR (Status)) {
129 return;
130 }
131
132 for (Index = 0; Index < HandleCount; Index++) {
133 Status = gBS->HandleProtocol (Handles[Index], &gEfiDeferredImageLoadProtocolGuid, (VOID **) &DeferredImage);
134 if (EFI_ERROR (Status)) {
135 continue;
136 }
137
138 for (ImageIndex = 0; ; ImageIndex++) {
139 //
140 // Load all the deferred images in this protocol instance.
141 //
142 Status = DeferredImage->GetImageInfo (
143 DeferredImage,
144 ImageIndex,
145 &ImageDevicePath,
146 (VOID **) &Image,
147 &ImageSize,
148 &BootOption
149 );
150 if (EFI_ERROR (Status)) {
151 break;
152 }
153 DevicePathStr = ConvertDevicePathToText (ImageDevicePath, FALSE, FALSE);
154 DEBUG ((DEBUG_LOAD, "[Bds] Image was deferred but not loaded: %s.\n", DevicePathStr));
155 if (DevicePathStr != NULL) {
156 FreePool (DevicePathStr);
157 }
158 }
159 }
160 if (Handles != NULL) {
161 FreePool (Handles);
162 }
163 }
164
165 /**
166
167 Install Boot Device Selection Protocol
168
169 @param ImageHandle The image handle.
170 @param SystemTable The system table.
171
172 @retval EFI_SUCEESS BDS has finished initializing.
173 Return the dispatcher and recall BDS.Entry
174 @retval Other Return status from AllocatePool() or gBS->InstallProtocolInterface
175
176 **/
177 EFI_STATUS
178 EFIAPI
179 BdsInitialize (
180 IN EFI_HANDLE ImageHandle,
181 IN EFI_SYSTEM_TABLE *SystemTable
182 )
183 {
184 EFI_STATUS Status;
185 EFI_HANDLE Handle;
186 //
187 // Install protocol interface
188 //
189 Handle = NULL;
190 Status = gBS->InstallMultipleProtocolInterfaces (
191 &Handle,
192 &gEfiBdsArchProtocolGuid, &gBds,
193 NULL
194 );
195 ASSERT_EFI_ERROR (Status);
196
197 DEBUG_CODE (
198 EFI_EVENT Event;
199 //
200 // Register notify function to check deferred images on ReadyToBoot Event.
201 //
202 Status = gBS->CreateEventEx (
203 EVT_NOTIFY_SIGNAL,
204 TPL_CALLBACK,
205 CheckDeferredLoadImageOnReadyToBoot,
206 NULL,
207 &gEfiEventReadyToBootGuid,
208 &Event
209 );
210 ASSERT_EFI_ERROR (Status);
211 );
212 return Status;
213 }
214
215 /**
216 Function waits for a given event to fire, or for an optional timeout to expire.
217
218 @param Event The event to wait for
219 @param Timeout An optional timeout value in 100 ns units.
220
221 @retval EFI_SUCCESS Event fired before Timeout expired.
222 @retval EFI_TIME_OUT Timout expired before Event fired..
223
224 **/
225 EFI_STATUS
226 BdsWaitForSingleEvent (
227 IN EFI_EVENT Event,
228 IN UINT64 Timeout OPTIONAL
229 )
230 {
231 UINTN Index;
232 EFI_STATUS Status;
233 EFI_EVENT TimerEvent;
234 EFI_EVENT WaitList[2];
235
236 if (Timeout != 0) {
237 //
238 // Create a timer event
239 //
240 Status = gBS->CreateEvent (EVT_TIMER, 0, NULL, NULL, &TimerEvent);
241 if (!EFI_ERROR (Status)) {
242 //
243 // Set the timer event
244 //
245 gBS->SetTimer (
246 TimerEvent,
247 TimerRelative,
248 Timeout
249 );
250
251 //
252 // Wait for the original event or the timer
253 //
254 WaitList[0] = Event;
255 WaitList[1] = TimerEvent;
256 Status = gBS->WaitForEvent (2, WaitList, &Index);
257 ASSERT_EFI_ERROR (Status);
258 gBS->CloseEvent (TimerEvent);
259
260 //
261 // If the timer expired, change the return to timed out
262 //
263 if (Index == 1) {
264 Status = EFI_TIMEOUT;
265 }
266 }
267 } else {
268 //
269 // No timeout... just wait on the event
270 //
271 Status = gBS->WaitForEvent (1, &Event, &Index);
272 ASSERT (!EFI_ERROR (Status));
273 ASSERT (Index == 0);
274 }
275
276 return Status;
277 }
278
279 /**
280 The function reads user inputs.
281
282 **/
283 VOID
284 BdsReadKeys (
285 VOID
286 )
287 {
288 EFI_STATUS Status;
289 EFI_INPUT_KEY Key;
290
291 if (PcdGetBool (PcdConInConnectOnDemand)) {
292 return;
293 }
294
295 while (gST->ConIn != NULL) {
296
297 Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
298
299 if (EFI_ERROR (Status)) {
300 //
301 // No more keys.
302 //
303 break;
304 }
305 }
306 }
307
308 /**
309 The function waits for the boot manager timeout expires or hotkey is pressed.
310
311 It calls PlatformBootManagerWaitCallback each second.
312
313 @param HotkeyTriggered Input hotkey event.
314 **/
315 VOID
316 BdsWait (
317 IN EFI_EVENT HotkeyTriggered
318 )
319 {
320 EFI_STATUS Status;
321 UINT16 TimeoutRemain;
322
323 DEBUG ((EFI_D_INFO, "[Bds]BdsWait ...Zzzzzzzzzzzz...\n"));
324
325 TimeoutRemain = PcdGet16 (PcdPlatformBootTimeOut);
326 while (TimeoutRemain != 0) {
327 DEBUG ((EFI_D_INFO, "[Bds]BdsWait(%d)..Zzzz...\n", (UINTN) TimeoutRemain));
328 PlatformBootManagerWaitCallback (TimeoutRemain);
329
330 BdsReadKeys (); // BUGBUG: Only reading can signal HotkeyTriggered
331 // Can be removed after all keyboard drivers invoke callback in timer callback.
332
333 if (HotkeyTriggered != NULL) {
334 Status = BdsWaitForSingleEvent (HotkeyTriggered, EFI_TIMER_PERIOD_SECONDS (1));
335 if (!EFI_ERROR (Status)) {
336 break;
337 }
338 } else {
339 gBS->Stall (1000000);
340 }
341
342 //
343 // 0xffff means waiting forever
344 // BDS with no hotkey provided and 0xffff as timeout will "hang" in the loop
345 //
346 if (TimeoutRemain != 0xffff) {
347 TimeoutRemain--;
348 }
349 }
350 DEBUG ((EFI_D_INFO, "[Bds]Exit the waiting!\n"));
351 }
352
353 /**
354 Attempt to boot each boot option in the BootOptions array.
355
356 @param BootOptions Input boot option array.
357 @param BootOptionCount Input boot option count.
358 @param BootManagerMenu Input boot manager menu.
359
360 @retval TRUE Successfully boot one of the boot options.
361 @retval FALSE Failed boot any of the boot options.
362 **/
363 BOOLEAN
364 BootBootOptions (
365 IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions,
366 IN UINTN BootOptionCount,
367 IN EFI_BOOT_MANAGER_LOAD_OPTION *BootManagerMenu OPTIONAL
368 )
369 {
370 UINTN Index;
371
372 //
373 // Report Status Code to indicate BDS starts attempting booting from the UEFI BootOrder list.
374 //
375 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_ATTEMPT_BOOT_ORDER_EVENT));
376
377 //
378 // Attempt boot each boot option
379 //
380 for (Index = 0; Index < BootOptionCount; Index++) {
381 //
382 // According to EFI Specification, if a load option is not marked
383 // as LOAD_OPTION_ACTIVE, the boot manager will not automatically
384 // load the option.
385 //
386 if ((BootOptions[Index].Attributes & LOAD_OPTION_ACTIVE) == 0) {
387 continue;
388 }
389
390 //
391 // Boot#### load options with LOAD_OPTION_CATEGORY_APP are executables which are not
392 // part of the normal boot processing. Boot options with reserved category values will be
393 // ignored by the boot manager.
394 //
395 if ((BootOptions[Index].Attributes & LOAD_OPTION_CATEGORY) != LOAD_OPTION_CATEGORY_BOOT) {
396 continue;
397 }
398
399 //
400 // All the driver options should have been processed since
401 // now boot will be performed.
402 //
403 EfiBootManagerBoot (&BootOptions[Index]);
404
405 //
406 // If the boot via Boot#### returns with a status of EFI_SUCCESS, platform firmware
407 // supports boot manager menu, and if firmware is configured to boot in an
408 // interactive mode, the boot manager will stop processing the BootOrder variable and
409 // present a boot manager menu to the user.
410 //
411 if ((BootManagerMenu != NULL) && (BootOptions[Index].Status == EFI_SUCCESS)) {
412 EfiBootManagerBoot (BootManagerMenu);
413 break;
414 }
415 }
416
417 return (BOOLEAN) (Index < BootOptionCount);
418 }
419
420 /**
421 The function will load and start every Driver####, SysPrep#### or PlatformRecovery####.
422
423 @param LoadOptions Load option array.
424 @param LoadOptionCount Load option count.
425 **/
426 VOID
427 ProcessLoadOptions (
428 IN EFI_BOOT_MANAGER_LOAD_OPTION *LoadOptions,
429 IN UINTN LoadOptionCount
430 )
431 {
432 EFI_STATUS Status;
433 UINTN Index;
434 BOOLEAN ReconnectAll;
435 EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType;
436
437 ReconnectAll = FALSE;
438 LoadOptionType = LoadOptionTypeMax;
439
440 //
441 // Process the driver option
442 //
443 for (Index = 0; Index < LoadOptionCount; Index++) {
444 //
445 // All the load options in the array should be of the same type.
446 //
447 if (Index == 0) {
448 LoadOptionType = LoadOptions[Index].OptionType;
449 }
450 ASSERT (LoadOptionType == LoadOptions[Index].OptionType);
451 ASSERT (LoadOptionType != LoadOptionTypeBoot);
452
453 Status = EfiBootManagerProcessLoadOption (&LoadOptions[Index]);
454
455 //
456 // Status indicates whether the load option is loaded and executed
457 // LoadOptions[Index].Status is what the load option returns
458 //
459 if (!EFI_ERROR (Status)) {
460 //
461 // Stop processing if any PlatformRecovery#### returns success.
462 //
463 if ((LoadOptions[Index].Status == EFI_SUCCESS) &&
464 (LoadOptionType == LoadOptionTypePlatformRecovery)) {
465 break;
466 }
467
468 //
469 // Only set ReconnectAll flag when the load option executes successfully.
470 //
471 if (!EFI_ERROR (LoadOptions[Index].Status) &&
472 (LoadOptions[Index].Attributes & LOAD_OPTION_FORCE_RECONNECT) != 0) {
473 ReconnectAll = TRUE;
474 }
475 }
476 }
477
478 //
479 // If a driver load option is marked as LOAD_OPTION_FORCE_RECONNECT,
480 // then all of the EFI drivers in the system will be disconnected and
481 // reconnected after the last driver load option is processed.
482 //
483 if (ReconnectAll && LoadOptionType == LoadOptionTypeDriver) {
484 EfiBootManagerDisconnectAll ();
485 EfiBootManagerConnectAll ();
486 }
487 }
488
489 /**
490
491 Validate input console variable data.
492
493 If found the device path is not a valid device path, remove the variable.
494
495 @param VariableName Input console variable name.
496
497 **/
498 VOID
499 BdsFormalizeConsoleVariable (
500 IN CHAR16 *VariableName
501 )
502 {
503 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
504 UINTN VariableSize;
505 EFI_STATUS Status;
506
507 GetEfiGlobalVariable2 (VariableName, (VOID **) &DevicePath, &VariableSize);
508 if ((DevicePath != NULL) && !IsDevicePathValid (DevicePath, VariableSize)) {
509 Status = gRT->SetVariable (
510 VariableName,
511 &gEfiGlobalVariableGuid,
512 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
513 0,
514 NULL
515 );
516 //
517 // Deleting variable with current variable implementation shouldn't fail.
518 //
519 ASSERT_EFI_ERROR (Status);
520 }
521
522 if (DevicePath != NULL) {
523 FreePool (DevicePath);
524 }
525 }
526
527 /**
528 Formalize OsIndication related variables.
529
530 For OsIndicationsSupported, Create a BS/RT/UINT64 variable to report caps
531 Delete OsIndications variable if it is not NV/BS/RT UINT64.
532
533 Item 3 is used to solve case when OS corrupts OsIndications. Here simply delete this NV variable.
534
535 Create a boot option for BootManagerMenu if it hasn't been created yet
536
537 **/
538 VOID
539 BdsFormalizeOSIndicationVariable (
540 VOID
541 )
542 {
543 EFI_STATUS Status;
544 UINT64 OsIndicationSupport;
545 UINT64 OsIndication;
546 UINTN DataSize;
547 UINT32 Attributes;
548 EFI_BOOT_MANAGER_LOAD_OPTION BootManagerMenu;
549
550 //
551 // OS indicater support variable
552 //
553 Status = EfiBootManagerGetBootManagerMenu (&BootManagerMenu);
554 if (Status != EFI_NOT_FOUND) {
555 OsIndicationSupport = EFI_OS_INDICATIONS_BOOT_TO_FW_UI | EFI_OS_INDICATIONS_START_PLATFORM_RECOVERY;
556 EfiBootManagerFreeLoadOption (&BootManagerMenu);
557 } else {
558 OsIndicationSupport = EFI_OS_INDICATIONS_START_PLATFORM_RECOVERY;
559 }
560
561 Status = gRT->SetVariable (
562 EFI_OS_INDICATIONS_SUPPORT_VARIABLE_NAME,
563 &gEfiGlobalVariableGuid,
564 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
565 sizeof(UINT64),
566 &OsIndicationSupport
567 );
568 //
569 // Platform needs to make sure setting volatile variable before calling 3rd party code shouldn't fail.
570 //
571 ASSERT_EFI_ERROR (Status);
572
573 //
574 // If OsIndications is invalid, remove it.
575 // Invalid case
576 // 1. Data size != UINT64
577 // 2. OsIndication value inconsistence
578 // 3. OsIndication attribute inconsistence
579 //
580 OsIndication = 0;
581 Attributes = 0;
582 DataSize = sizeof(UINT64);
583 Status = gRT->GetVariable (
584 EFI_OS_INDICATIONS_VARIABLE_NAME,
585 &gEfiGlobalVariableGuid,
586 &Attributes,
587 &DataSize,
588 &OsIndication
589 );
590 if (Status == EFI_NOT_FOUND) {
591 return;
592 }
593
594 if ((DataSize != sizeof (OsIndication)) ||
595 ((OsIndication & ~OsIndicationSupport) != 0) ||
596 (Attributes != (EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE))
597 ){
598
599 DEBUG ((EFI_D_ERROR, "[Bds] Unformalized OsIndications variable exists. Delete it\n"));
600 Status = gRT->SetVariable (
601 EFI_OS_INDICATIONS_VARIABLE_NAME,
602 &gEfiGlobalVariableGuid,
603 0,
604 0,
605 NULL
606 );
607 //
608 // Deleting variable with current variable implementation shouldn't fail.
609 //
610 ASSERT_EFI_ERROR(Status);
611 }
612 }
613
614 /**
615
616 Validate variables.
617
618 **/
619 VOID
620 BdsFormalizeEfiGlobalVariable (
621 VOID
622 )
623 {
624 //
625 // Validate Console variable.
626 //
627 BdsFormalizeConsoleVariable (EFI_CON_IN_VARIABLE_NAME);
628 BdsFormalizeConsoleVariable (EFI_CON_OUT_VARIABLE_NAME);
629 BdsFormalizeConsoleVariable (EFI_ERR_OUT_VARIABLE_NAME);
630
631 //
632 // Validate OSIndication related variable.
633 //
634 BdsFormalizeOSIndicationVariable ();
635 }
636
637 /**
638 Enter an infinite loop of calling the Boot Manager Menu.
639
640 This is a last resort alternative to BdsEntry() giving up for good. This
641 function never returns.
642
643 @param[in] BootManagerMenu The EFI_BOOT_MANAGER_LOAD_OPTION located and/or
644 created by the EfiBootManagerGetBootManagerMenu()
645 call in BdsEntry().
646 **/
647 VOID
648 BdsBootManagerMenuLoop (
649 IN EFI_BOOT_MANAGER_LOAD_OPTION *BootManagerMenu
650 )
651 {
652 EFI_INPUT_KEY Key;
653
654 //
655 // Normally BdsDxe does not print anything to the system console, but this is
656 // a last resort -- the end-user will likely not see any DEBUG messages
657 // logged in this situation.
658 //
659 // AsciiPrint() will NULL-check gST->ConOut internally. We check gST->ConIn
660 // here to see if it makes sense to request and wait for a keypress.
661 //
662 if (gST->ConIn != NULL) {
663 AsciiPrint (
664 "%a: No bootable option or device was found.\n"
665 "%a: Press any key to enter the Boot Manager Menu.\n",
666 gEfiCallerBaseName,
667 gEfiCallerBaseName
668 );
669 BdsWaitForSingleEvent (gST->ConIn->WaitForKey, 0);
670
671 //
672 // Drain any queued keys.
673 //
674 while (!EFI_ERROR (gST->ConIn->ReadKeyStroke (gST->ConIn, &Key))) {
675 //
676 // just throw away Key
677 //
678 }
679 }
680
681 for (;;) {
682 EfiBootManagerBoot (BootManagerMenu);
683 }
684 }
685
686 /**
687
688 Service routine for BdsInstance->Entry(). Devices are connected, the
689 consoles are initialized, and the boot options are tried.
690
691 @param This Protocol Instance structure.
692
693 **/
694 VOID
695 EFIAPI
696 BdsEntry (
697 IN EFI_BDS_ARCH_PROTOCOL *This
698 )
699 {
700 EFI_BOOT_MANAGER_LOAD_OPTION *LoadOptions;
701 UINTN LoadOptionCount;
702 CHAR16 *FirmwareVendor;
703 EFI_EVENT HotkeyTriggered;
704 UINT64 OsIndication;
705 UINTN DataSize;
706 EFI_STATUS Status;
707 UINT32 BootOptionSupport;
708 UINT16 BootTimeOut;
709 EDKII_VARIABLE_LOCK_PROTOCOL *VariableLock;
710 UINTN Index;
711 EFI_BOOT_MANAGER_LOAD_OPTION LoadOption;
712 UINT16 *BootNext;
713 CHAR16 BootNextVariableName[sizeof ("Boot####")];
714 EFI_BOOT_MANAGER_LOAD_OPTION BootManagerMenu;
715 BOOLEAN BootFwUi;
716 BOOLEAN PlatformRecovery;
717 BOOLEAN BootSuccess;
718 EFI_DEVICE_PATH_PROTOCOL *FilePath;
719 EFI_STATUS BootManagerMenuStatus;
720
721 HotkeyTriggered = NULL;
722 Status = EFI_SUCCESS;
723 BootSuccess = FALSE;
724
725 //
726 // Insert the performance probe
727 //
728 PERF_CROSSMODULE_END("DXE");
729 PERF_CROSSMODULE_BEGIN("BDS");
730 DEBUG ((EFI_D_INFO, "[Bds] Entry...\n"));
731
732 //
733 // Fill in FirmwareVendor and FirmwareRevision from PCDs
734 //
735 FirmwareVendor = (CHAR16 *) PcdGetPtr (PcdFirmwareVendor);
736 gST->FirmwareVendor = AllocateRuntimeCopyPool (StrSize (FirmwareVendor), FirmwareVendor);
737 ASSERT (gST->FirmwareVendor != NULL);
738 gST->FirmwareRevision = PcdGet32 (PcdFirmwareRevision);
739
740 //
741 // Fixup Tasble CRC after we updated Firmware Vendor and Revision
742 //
743 gST->Hdr.CRC32 = 0;
744 gBS->CalculateCrc32 ((VOID *) gST, sizeof (EFI_SYSTEM_TABLE), &gST->Hdr.CRC32);
745
746 //
747 // Validate Variable.
748 //
749 BdsFormalizeEfiGlobalVariable ();
750
751 //
752 // Mark the read-only variables if the Variable Lock protocol exists
753 //
754 Status = gBS->LocateProtocol (&gEdkiiVariableLockProtocolGuid, NULL, (VOID **) &VariableLock);
755 DEBUG ((EFI_D_INFO, "[BdsDxe] Locate Variable Lock protocol - %r\n", Status));
756 if (!EFI_ERROR (Status)) {
757 for (Index = 0; Index < ARRAY_SIZE (mReadOnlyVariables); Index++) {
758 Status = VariableLock->RequestToLock (VariableLock, mReadOnlyVariables[Index], &gEfiGlobalVariableGuid);
759 ASSERT_EFI_ERROR (Status);
760 }
761 }
762
763 InitializeHwErrRecSupport ();
764
765 //
766 // Initialize L"Timeout" EFI global variable.
767 //
768 BootTimeOut = PcdGet16 (PcdPlatformBootTimeOut);
769 if (BootTimeOut != 0xFFFF) {
770 //
771 // If time out value equal 0xFFFF, no need set to 0xFFFF to variable area because UEFI specification
772 // define same behavior between no value or 0xFFFF value for L"Timeout".
773 //
774 BdsDxeSetVariableAndReportStatusCodeOnError (
775 EFI_TIME_OUT_VARIABLE_NAME,
776 &gEfiGlobalVariableGuid,
777 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
778 sizeof (UINT16),
779 &BootTimeOut
780 );
781 }
782
783 //
784 // Initialize L"BootOptionSupport" EFI global variable.
785 // Lazy-ConIn implictly disables BDS hotkey.
786 //
787 BootOptionSupport = EFI_BOOT_OPTION_SUPPORT_APP | EFI_BOOT_OPTION_SUPPORT_SYSPREP;
788 if (!PcdGetBool (PcdConInConnectOnDemand)) {
789 BootOptionSupport |= EFI_BOOT_OPTION_SUPPORT_KEY;
790 SET_BOOT_OPTION_SUPPORT_KEY_COUNT (BootOptionSupport, 3);
791 }
792 Status = gRT->SetVariable (
793 EFI_BOOT_OPTION_SUPPORT_VARIABLE_NAME,
794 &gEfiGlobalVariableGuid,
795 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
796 sizeof (BootOptionSupport),
797 &BootOptionSupport
798 );
799 //
800 // Platform needs to make sure setting volatile variable before calling 3rd party code shouldn't fail.
801 //
802 ASSERT_EFI_ERROR (Status);
803
804 //
805 // Cache the "BootNext" NV variable before calling any PlatformBootManagerLib APIs
806 // This could avoid the "BootNext" set by PlatformBootManagerLib be consumed in this boot.
807 //
808 GetEfiGlobalVariable2 (EFI_BOOT_NEXT_VARIABLE_NAME, (VOID **) &BootNext, &DataSize);
809 if (DataSize != sizeof (UINT16)) {
810 if (BootNext != NULL) {
811 FreePool (BootNext);
812 }
813 BootNext = NULL;
814 }
815
816 //
817 // Initialize the platform language variables
818 //
819 InitializeLanguage (TRUE);
820
821 //
822 // System firmware must include a PlatformRecovery#### variable specifying
823 // a short-form File Path Media Device Path containing the platform default
824 // file path for removable media
825 //
826 FilePath = FileDevicePath (NULL, EFI_REMOVABLE_MEDIA_FILE_NAME);
827 Status = EfiBootManagerInitializeLoadOption (
828 &LoadOption,
829 LoadOptionNumberUnassigned,
830 LoadOptionTypePlatformRecovery,
831 LOAD_OPTION_ACTIVE,
832 L"Default PlatformRecovery",
833 FilePath,
834 NULL,
835 0
836 );
837 ASSERT_EFI_ERROR (Status);
838 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypePlatformRecovery);
839 if (EfiBootManagerFindLoadOption (&LoadOption, LoadOptions, LoadOptionCount) == -1) {
840 for (Index = 0; Index < LoadOptionCount; Index++) {
841 //
842 // The PlatformRecovery#### options are sorted by OptionNumber.
843 // Find the the smallest unused number as the new OptionNumber.
844 //
845 if (LoadOptions[Index].OptionNumber != Index) {
846 break;
847 }
848 }
849 LoadOption.OptionNumber = Index;
850 Status = EfiBootManagerLoadOptionToVariable (&LoadOption);
851 ASSERT_EFI_ERROR (Status);
852 }
853 EfiBootManagerFreeLoadOption (&LoadOption);
854 FreePool (FilePath);
855 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
856
857 //
858 // Report Status Code to indicate connecting drivers will happen
859 //
860 REPORT_STATUS_CODE (
861 EFI_PROGRESS_CODE,
862 (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_BEGIN_CONNECTING_DRIVERS)
863 );
864
865 //
866 // Initialize ConnectConIn event before calling platform code.
867 //
868 if (PcdGetBool (PcdConInConnectOnDemand)) {
869 Status = gBS->CreateEventEx (
870 EVT_NOTIFY_SIGNAL,
871 TPL_CALLBACK,
872 BdsDxeOnConnectConInCallBack,
873 NULL,
874 &gConnectConInEventGuid,
875 &gConnectConInEvent
876 );
877 if (EFI_ERROR (Status)) {
878 gConnectConInEvent = NULL;
879 }
880 }
881
882 //
883 // Do the platform init, can be customized by OEM/IBV
884 // Possible things that can be done in PlatformBootManagerBeforeConsole:
885 // > Update console variable: 1. include hot-plug devices; 2. Clear ConIn and add SOL for AMT
886 // > Register new Driver#### or Boot####
887 // > Register new Key####: e.g.: F12
888 // > Signal ReadyToLock event
889 // > Authentication action: 1. connect Auth devices; 2. Identify auto logon user.
890 //
891 PERF_INMODULE_BEGIN("PlatformBootManagerBeforeConsole");
892 PlatformBootManagerBeforeConsole ();
893 PERF_INMODULE_END("PlatformBootManagerBeforeConsole");
894
895 //
896 // Initialize hotkey service
897 //
898 EfiBootManagerStartHotkeyService (&HotkeyTriggered);
899
900 //
901 // Execute Driver Options
902 //
903 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypeDriver);
904 ProcessLoadOptions (LoadOptions, LoadOptionCount);
905 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
906
907 //
908 // Connect consoles
909 //
910 PERF_INMODULE_BEGIN("EfiBootManagerConnectAllDefaultConsoles");
911 if (PcdGetBool (PcdConInConnectOnDemand)) {
912 EfiBootManagerConnectConsoleVariable (ConOut);
913 EfiBootManagerConnectConsoleVariable (ErrOut);
914 //
915 // Do not connect ConIn devices when lazy ConIn feature is ON.
916 //
917 } else {
918 EfiBootManagerConnectAllDefaultConsoles ();
919 }
920 PERF_INMODULE_END("EfiBootManagerConnectAllDefaultConsoles");
921
922 //
923 // Do the platform specific action after the console is ready
924 // Possible things that can be done in PlatformBootManagerAfterConsole:
925 // > Console post action:
926 // > Dynamically switch output mode from 100x31 to 80x25 for certain senarino
927 // > Signal console ready platform customized event
928 // > Run diagnostics like memory testing
929 // > Connect certain devices
930 // > Dispatch aditional option roms
931 // > Special boot: e.g.: USB boot, enter UI
932 //
933 PERF_INMODULE_BEGIN("PlatformBootManagerAfterConsole");
934 PlatformBootManagerAfterConsole ();
935 PERF_INMODULE_END("PlatformBootManagerAfterConsole");
936 //
937 // Boot to Boot Manager Menu when EFI_OS_INDICATIONS_BOOT_TO_FW_UI is set. Skip HotkeyBoot
938 //
939 DataSize = sizeof (UINT64);
940 Status = gRT->GetVariable (
941 EFI_OS_INDICATIONS_VARIABLE_NAME,
942 &gEfiGlobalVariableGuid,
943 NULL,
944 &DataSize,
945 &OsIndication
946 );
947 if (EFI_ERROR (Status)) {
948 OsIndication = 0;
949 }
950
951 DEBUG_CODE (
952 EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType;
953 DEBUG ((EFI_D_INFO, "[Bds]OsIndication: %016x\n", OsIndication));
954 DEBUG ((EFI_D_INFO, "[Bds]=============Begin Load Options Dumping ...=============\n"));
955 for (LoadOptionType = 0; LoadOptionType < LoadOptionTypeMax; LoadOptionType++) {
956 DEBUG ((
957 EFI_D_INFO, " %s Options:\n",
958 mBdsLoadOptionName[LoadOptionType]
959 ));
960 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionType);
961 for (Index = 0; Index < LoadOptionCount; Index++) {
962 DEBUG ((
963 EFI_D_INFO, " %s%04x: %s \t\t 0x%04x\n",
964 mBdsLoadOptionName[LoadOptionType],
965 LoadOptions[Index].OptionNumber,
966 LoadOptions[Index].Description,
967 LoadOptions[Index].Attributes
968 ));
969 }
970 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
971 }
972 DEBUG ((EFI_D_INFO, "[Bds]=============End Load Options Dumping=============\n"));
973 );
974
975 //
976 // BootManagerMenu doesn't contain the correct information when return status is EFI_NOT_FOUND.
977 //
978 BootManagerMenuStatus = EfiBootManagerGetBootManagerMenu (&BootManagerMenu);
979
980 BootFwUi = (BOOLEAN) ((OsIndication & EFI_OS_INDICATIONS_BOOT_TO_FW_UI) != 0);
981 PlatformRecovery = (BOOLEAN) ((OsIndication & EFI_OS_INDICATIONS_START_PLATFORM_RECOVERY) != 0);
982 //
983 // Clear EFI_OS_INDICATIONS_BOOT_TO_FW_UI to acknowledge OS
984 //
985 if (BootFwUi || PlatformRecovery) {
986 OsIndication &= ~((UINT64) (EFI_OS_INDICATIONS_BOOT_TO_FW_UI | EFI_OS_INDICATIONS_START_PLATFORM_RECOVERY));
987 Status = gRT->SetVariable (
988 EFI_OS_INDICATIONS_VARIABLE_NAME,
989 &gEfiGlobalVariableGuid,
990 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
991 sizeof(UINT64),
992 &OsIndication
993 );
994 //
995 // Changing the content without increasing its size with current variable implementation shouldn't fail.
996 //
997 ASSERT_EFI_ERROR (Status);
998 }
999
1000 //
1001 // Launch Boot Manager Menu directly when EFI_OS_INDICATIONS_BOOT_TO_FW_UI is set. Skip HotkeyBoot
1002 //
1003 if (BootFwUi && (BootManagerMenuStatus != EFI_NOT_FOUND)) {
1004 //
1005 // Follow generic rule, Call BdsDxeOnConnectConInCallBack to connect ConIn before enter UI
1006 //
1007 if (PcdGetBool (PcdConInConnectOnDemand)) {
1008 BdsDxeOnConnectConInCallBack (NULL, NULL);
1009 }
1010
1011 //
1012 // Directly enter the setup page.
1013 //
1014 EfiBootManagerBoot (&BootManagerMenu);
1015 }
1016
1017 if (!PlatformRecovery) {
1018 //
1019 // Execute SysPrep####
1020 //
1021 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypeSysPrep);
1022 ProcessLoadOptions (LoadOptions, LoadOptionCount);
1023 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
1024
1025 //
1026 // Execute Key####
1027 //
1028 PERF_INMODULE_BEGIN ("BdsWait");
1029 BdsWait (HotkeyTriggered);
1030 PERF_INMODULE_END ("BdsWait");
1031 //
1032 // BdsReadKeys() can be removed after all keyboard drivers invoke callback in timer callback.
1033 //
1034 BdsReadKeys ();
1035
1036 EfiBootManagerHotkeyBoot ();
1037
1038 if (BootNext != NULL) {
1039 //
1040 // Delete "BootNext" NV variable before transferring control to it to prevent loops.
1041 //
1042 Status = gRT->SetVariable (
1043 EFI_BOOT_NEXT_VARIABLE_NAME,
1044 &gEfiGlobalVariableGuid,
1045 0,
1046 0,
1047 NULL
1048 );
1049 //
1050 // Deleting NV variable shouldn't fail unless it doesn't exist.
1051 //
1052 ASSERT (Status == EFI_SUCCESS || Status == EFI_NOT_FOUND);
1053
1054 //
1055 // Boot to "BootNext"
1056 //
1057 UnicodeSPrint (BootNextVariableName, sizeof (BootNextVariableName), L"Boot%04x", *BootNext);
1058 Status = EfiBootManagerVariableToLoadOption (BootNextVariableName, &LoadOption);
1059 if (!EFI_ERROR (Status)) {
1060 EfiBootManagerBoot (&LoadOption);
1061 EfiBootManagerFreeLoadOption (&LoadOption);
1062 if ((LoadOption.Status == EFI_SUCCESS) &&
1063 (BootManagerMenuStatus != EFI_NOT_FOUND) &&
1064 (LoadOption.OptionNumber != BootManagerMenu.OptionNumber)) {
1065 //
1066 // Boot to Boot Manager Menu upon EFI_SUCCESS
1067 // Exception: Do not boot again when the BootNext points to Boot Manager Menu.
1068 //
1069 EfiBootManagerBoot (&BootManagerMenu);
1070 }
1071 }
1072 }
1073
1074 do {
1075 //
1076 // Retry to boot if any of the boot succeeds
1077 //
1078 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypeBoot);
1079 BootSuccess = BootBootOptions (LoadOptions, LoadOptionCount, (BootManagerMenuStatus != EFI_NOT_FOUND) ? &BootManagerMenu : NULL);
1080 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
1081 } while (BootSuccess);
1082 }
1083
1084 if (!BootSuccess) {
1085 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypePlatformRecovery);
1086 ProcessLoadOptions (LoadOptions, LoadOptionCount);
1087 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
1088 }
1089
1090 //
1091 // If BootManagerMenu is available, fall back to it indefinitely.
1092 //
1093 if (BootManagerMenuStatus != EFI_NOT_FOUND) {
1094 BdsBootManagerMenuLoop (&BootManagerMenu);
1095 }
1096
1097 DEBUG ((EFI_D_ERROR, "[Bds] Unable to boot!\n"));
1098 CpuDeadLoop ();
1099 }
1100
1101 /**
1102 Set the variable and report the error through status code upon failure.
1103
1104 @param VariableName A Null-terminated string that is the name of the vendor's variable.
1105 Each VariableName is unique for each VendorGuid. VariableName must
1106 contain 1 or more characters. If VariableName is an empty string,
1107 then EFI_INVALID_PARAMETER is returned.
1108 @param VendorGuid A unique identifier for the vendor.
1109 @param Attributes Attributes bitmask to set for the variable.
1110 @param DataSize The size in bytes of the Data buffer. Unless the EFI_VARIABLE_APPEND_WRITE,
1111 or EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute is set, a size of zero
1112 causes the variable to be deleted. When the EFI_VARIABLE_APPEND_WRITE attribute is
1113 set, then a SetVariable() call with a DataSize of zero will not cause any change to
1114 the variable value (the timestamp associated with the variable may be updated however
1115 even if no new data value is provided,see the description of the
1116 EFI_VARIABLE_AUTHENTICATION_2 descriptor below. In this case the DataSize will not
1117 be zero since the EFI_VARIABLE_AUTHENTICATION_2 descriptor will be populated).
1118 @param Data The contents for the variable.
1119
1120 @retval EFI_SUCCESS The firmware has successfully stored the variable and its data as
1121 defined by the Attributes.
1122 @retval EFI_INVALID_PARAMETER An invalid combination of attribute bits, name, and GUID was supplied, or the
1123 DataSize exceeds the maximum allowed.
1124 @retval EFI_INVALID_PARAMETER VariableName is an empty string.
1125 @retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the variable and its data.
1126 @retval EFI_DEVICE_ERROR The variable could not be retrieved due to a hardware error.
1127 @retval EFI_WRITE_PROTECTED The variable in question is read-only.
1128 @retval EFI_WRITE_PROTECTED The variable in question cannot be deleted.
1129 @retval EFI_SECURITY_VIOLATION The variable could not be written due to EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACESS
1130 being set, but the AuthInfo does NOT pass the validation check carried out by the firmware.
1131
1132 @retval EFI_NOT_FOUND The variable trying to be updated or deleted was not found.
1133 **/
1134 EFI_STATUS
1135 BdsDxeSetVariableAndReportStatusCodeOnError (
1136 IN CHAR16 *VariableName,
1137 IN EFI_GUID *VendorGuid,
1138 IN UINT32 Attributes,
1139 IN UINTN DataSize,
1140 IN VOID *Data
1141 )
1142 {
1143 EFI_STATUS Status;
1144 EDKII_SET_VARIABLE_STATUS *SetVariableStatus;
1145 UINTN NameSize;
1146
1147 Status = gRT->SetVariable (
1148 VariableName,
1149 VendorGuid,
1150 Attributes,
1151 DataSize,
1152 Data
1153 );
1154 if (EFI_ERROR (Status)) {
1155 NameSize = StrSize (VariableName);
1156 SetVariableStatus = AllocatePool (sizeof (EDKII_SET_VARIABLE_STATUS) + NameSize + DataSize);
1157 if (SetVariableStatus != NULL) {
1158 CopyGuid (&SetVariableStatus->Guid, VendorGuid);
1159 SetVariableStatus->NameSize = NameSize;
1160 SetVariableStatus->DataSize = DataSize;
1161 SetVariableStatus->SetStatus = Status;
1162 SetVariableStatus->Attributes = Attributes;
1163 CopyMem (SetVariableStatus + 1, VariableName, NameSize);
1164 CopyMem (((UINT8 *) (SetVariableStatus + 1)) + NameSize, Data, DataSize);
1165
1166 REPORT_STATUS_CODE_EX (
1167 EFI_ERROR_CODE,
1168 PcdGet32 (PcdErrorCodeSetVariable),
1169 0,
1170 NULL,
1171 &gEdkiiStatusCodeDataTypeVariableGuid,
1172 SetVariableStatus,
1173 sizeof (EDKII_SET_VARIABLE_STATUS) + NameSize + DataSize
1174 );
1175
1176 FreePool (SetVariableStatus);
1177 }
1178 }
1179
1180 return Status;
1181 }