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