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