]> git.proxmox.com Git - mirror_edk2.git/blob - IntelFrameworkModulePkg/Library/GenericBdsLib/BdsMisc.c
15a47e1917ea98893f35b887a43ad1967b43b890
[mirror_edk2.git] / IntelFrameworkModulePkg / Library / GenericBdsLib / BdsMisc.c
1 /** @file
2 Misc BDS library function
3
4 Copyright (c) 2004 - 2012, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12
13 **/
14
15 #include "InternalBdsLib.h"
16
17
18 #define MAX_STRING_LEN 200
19
20 BOOLEAN mFeaturerSwitch = TRUE;
21 BOOLEAN mResetRequired = FALSE;
22
23 extern UINT16 gPlatformBootTimeOutDefault;
24
25 /**
26 The function will go through the driver option link list, load and start
27 every driver the driver option device path point to.
28
29 @param BdsDriverLists The header of the current driver option link list
30
31 **/
32 VOID
33 EFIAPI
34 BdsLibLoadDrivers (
35 IN LIST_ENTRY *BdsDriverLists
36 )
37 {
38 EFI_STATUS Status;
39 LIST_ENTRY *Link;
40 BDS_COMMON_OPTION *Option;
41 EFI_HANDLE ImageHandle;
42 EFI_LOADED_IMAGE_PROTOCOL *ImageInfo;
43 UINTN ExitDataSize;
44 CHAR16 *ExitData;
45 BOOLEAN ReconnectAll;
46
47 ReconnectAll = FALSE;
48
49 //
50 // Process the driver option
51 //
52 for (Link = BdsDriverLists->ForwardLink; Link != BdsDriverLists; Link = Link->ForwardLink) {
53 Option = CR (Link, BDS_COMMON_OPTION, Link, BDS_LOAD_OPTION_SIGNATURE);
54
55 //
56 // If a load option is not marked as LOAD_OPTION_ACTIVE,
57 // the boot manager will not automatically load the option.
58 //
59 if (!IS_LOAD_OPTION_TYPE (Option->Attribute, LOAD_OPTION_ACTIVE)) {
60 continue;
61 }
62
63 //
64 // If a driver load option is marked as LOAD_OPTION_FORCE_RECONNECT,
65 // then all of the EFI drivers in the system will be disconnected and
66 // reconnected after the last driver load option is processed.
67 //
68 if (IS_LOAD_OPTION_TYPE (Option->Attribute, LOAD_OPTION_FORCE_RECONNECT)) {
69 ReconnectAll = TRUE;
70 }
71
72 //
73 // Make sure the driver path is connected.
74 //
75 BdsLibConnectDevicePath (Option->DevicePath);
76
77 //
78 // Load and start the image that Driver#### describes
79 //
80 Status = gBS->LoadImage (
81 FALSE,
82 gImageHandle,
83 Option->DevicePath,
84 NULL,
85 0,
86 &ImageHandle
87 );
88
89 if (!EFI_ERROR (Status)) {
90 gBS->HandleProtocol (ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &ImageInfo);
91
92 //
93 // Verify whether this image is a driver, if not,
94 // exit it and continue to parse next load option
95 //
96 if (ImageInfo->ImageCodeType != EfiBootServicesCode && ImageInfo->ImageCodeType != EfiRuntimeServicesCode) {
97 gBS->Exit (ImageHandle, EFI_INVALID_PARAMETER, 0, NULL);
98 continue;
99 }
100
101 if (Option->LoadOptionsSize != 0) {
102 ImageInfo->LoadOptionsSize = Option->LoadOptionsSize;
103 ImageInfo->LoadOptions = Option->LoadOptions;
104 }
105 //
106 // Before calling the image, enable the Watchdog Timer for
107 // the 5 Minute period
108 //
109 gBS->SetWatchdogTimer (5 * 60, 0x0000, 0x00, NULL);
110
111 Status = gBS->StartImage (ImageHandle, &ExitDataSize, &ExitData);
112 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Driver Return Status = %r\n", Status));
113
114 //
115 // Clear the Watchdog Timer after the image returns
116 //
117 gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL);
118 }
119 }
120
121 //
122 // Process the LOAD_OPTION_FORCE_RECONNECT driver option
123 //
124 if (ReconnectAll) {
125 BdsLibDisconnectAllEfi ();
126 BdsLibConnectAll ();
127 }
128
129 }
130
131 /**
132 Get the Option Number that does not used.
133 Try to locate the specific option variable one by one utile find a free number.
134
135 @param VariableName Indicate if the boot#### or driver#### option
136
137 @return The Minimal Free Option Number
138
139 **/
140 UINT16
141 BdsLibGetFreeOptionNumber (
142 IN CHAR16 *VariableName
143 )
144 {
145 UINTN Index;
146 CHAR16 StrTemp[10];
147 UINT16 *OptionBuffer;
148 UINTN OptionSize;
149
150 //
151 // Try to find the minimum free number from 0, 1, 2, 3....
152 //
153 Index = 0;
154 do {
155 if (*VariableName == 'B') {
156 UnicodeSPrint (StrTemp, sizeof (StrTemp), L"Boot%04x", Index);
157 } else {
158 UnicodeSPrint (StrTemp, sizeof (StrTemp), L"Driver%04x", Index);
159 }
160 //
161 // try if the option number is used
162 //
163 OptionBuffer = BdsLibGetVariableAndSize (
164 StrTemp,
165 &gEfiGlobalVariableGuid,
166 &OptionSize
167 );
168 if (OptionBuffer == NULL) {
169 break;
170 }
171 Index++;
172 } while (TRUE);
173
174 return ((UINT16) Index);
175 }
176
177
178 /**
179 This function will register the new boot#### or driver#### option base on
180 the VariableName. The new registered boot#### or driver#### will be linked
181 to BdsOptionList and also update to the VariableName. After the boot#### or
182 driver#### updated, the BootOrder or DriverOrder will also be updated.
183
184 @param BdsOptionList The header of the boot#### or driver#### link list
185 @param DevicePath The device path which the boot#### or driver####
186 option present
187 @param String The description of the boot#### or driver####
188 @param VariableName Indicate if the boot#### or driver#### option
189
190 @retval EFI_SUCCESS The boot#### or driver#### have been success
191 registered
192 @retval EFI_STATUS Return the status of gRT->SetVariable ().
193
194 **/
195 EFI_STATUS
196 EFIAPI
197 BdsLibRegisterNewOption (
198 IN LIST_ENTRY *BdsOptionList,
199 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
200 IN CHAR16 *String,
201 IN CHAR16 *VariableName
202 )
203 {
204 EFI_STATUS Status;
205 UINTN Index;
206 UINT16 RegisterOptionNumber;
207 UINT16 *TempOptionPtr;
208 UINTN TempOptionSize;
209 UINT16 *OptionOrderPtr;
210 VOID *OptionPtr;
211 UINTN OptionSize;
212 UINT8 *TempPtr;
213 EFI_DEVICE_PATH_PROTOCOL *OptionDevicePath;
214 CHAR16 *Description;
215 CHAR16 OptionName[10];
216 BOOLEAN UpdateDescription;
217 UINT16 BootOrderEntry;
218 UINTN OrderItemNum;
219
220
221 OptionPtr = NULL;
222 OptionSize = 0;
223 TempPtr = NULL;
224 OptionDevicePath = NULL;
225 Description = NULL;
226 OptionOrderPtr = NULL;
227 UpdateDescription = FALSE;
228 Status = EFI_SUCCESS;
229 ZeroMem (OptionName, sizeof (OptionName));
230
231 TempOptionSize = 0;
232 TempOptionPtr = BdsLibGetVariableAndSize (
233 VariableName,
234 &gEfiGlobalVariableGuid,
235 &TempOptionSize
236 );
237 //
238 // Compare with current option variable if the previous option is set in global variable.
239 //
240 for (Index = 0; Index < TempOptionSize / sizeof (UINT16); Index++) {
241 //
242 // TempOptionPtr must not be NULL if we have non-zero TempOptionSize.
243 //
244 ASSERT (TempOptionPtr != NULL);
245
246 if (*VariableName == 'B') {
247 UnicodeSPrint (OptionName, sizeof (OptionName), L"Boot%04x", TempOptionPtr[Index]);
248 } else {
249 UnicodeSPrint (OptionName, sizeof (OptionName), L"Driver%04x", TempOptionPtr[Index]);
250 }
251
252 OptionPtr = BdsLibGetVariableAndSize (
253 OptionName,
254 &gEfiGlobalVariableGuid,
255 &OptionSize
256 );
257 if (OptionPtr == NULL) {
258 continue;
259 }
260 TempPtr = OptionPtr;
261 TempPtr += sizeof (UINT32) + sizeof (UINT16);
262 Description = (CHAR16 *) TempPtr;
263 TempPtr += StrSize ((CHAR16 *) TempPtr);
264 OptionDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) TempPtr;
265
266 //
267 // Notes: the description may will change base on the GetStringToken
268 //
269 if (CompareMem (OptionDevicePath, DevicePath, GetDevicePathSize (OptionDevicePath)) == 0) {
270 if (CompareMem (Description, String, StrSize (Description)) == 0) {
271 //
272 // Got the option, so just return
273 //
274 FreePool (OptionPtr);
275 FreePool (TempOptionPtr);
276 return EFI_SUCCESS;
277 } else {
278 //
279 // Option description changed, need update.
280 //
281 UpdateDescription = TRUE;
282 FreePool (OptionPtr);
283 break;
284 }
285 }
286
287 FreePool (OptionPtr);
288 }
289
290 OptionSize = sizeof (UINT32) + sizeof (UINT16) + StrSize (String);
291 OptionSize += GetDevicePathSize (DevicePath);
292 OptionPtr = AllocateZeroPool (OptionSize);
293 ASSERT (OptionPtr != NULL);
294
295 TempPtr = OptionPtr;
296 *(UINT32 *) TempPtr = LOAD_OPTION_ACTIVE;
297 TempPtr += sizeof (UINT32);
298 *(UINT16 *) TempPtr = (UINT16) GetDevicePathSize (DevicePath);
299 TempPtr += sizeof (UINT16);
300 CopyMem (TempPtr, String, StrSize (String));
301 TempPtr += StrSize (String);
302 CopyMem (TempPtr, DevicePath, GetDevicePathSize (DevicePath));
303
304 if (UpdateDescription) {
305 //
306 // The number in option#### to be updated.
307 // In this case, we must have non-NULL TempOptionPtr.
308 //
309 ASSERT (TempOptionPtr != NULL);
310 RegisterOptionNumber = TempOptionPtr[Index];
311 } else {
312 //
313 // The new option#### number
314 //
315 RegisterOptionNumber = BdsLibGetFreeOptionNumber(VariableName);
316 }
317
318 if (*VariableName == 'B') {
319 UnicodeSPrint (OptionName, sizeof (OptionName), L"Boot%04x", RegisterOptionNumber);
320 } else {
321 UnicodeSPrint (OptionName, sizeof (OptionName), L"Driver%04x", RegisterOptionNumber);
322 }
323
324 Status = gRT->SetVariable (
325 OptionName,
326 &gEfiGlobalVariableGuid,
327 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
328 OptionSize,
329 OptionPtr
330 );
331 //
332 // Return if only need to update a changed description or fail to set option.
333 //
334 if (EFI_ERROR (Status) || UpdateDescription) {
335 FreePool (OptionPtr);
336 if (TempOptionPtr != NULL) {
337 FreePool (TempOptionPtr);
338 }
339 return Status;
340 }
341
342 FreePool (OptionPtr);
343
344 //
345 // Update the option order variable
346 //
347
348 //
349 // If no option order
350 //
351 if (TempOptionSize == 0) {
352 BootOrderEntry = 0;
353 Status = gRT->SetVariable (
354 VariableName,
355 &gEfiGlobalVariableGuid,
356 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
357 sizeof (UINT16),
358 &BootOrderEntry
359 );
360 if (TempOptionPtr != NULL) {
361 FreePool (TempOptionPtr);
362 }
363 return Status;
364 }
365
366 //
367 // TempOptionPtr must not be NULL if TempOptionSize is not zero.
368 //
369 ASSERT (TempOptionPtr != NULL);
370 //
371 // Append the new option number to the original option order
372 //
373 OrderItemNum = (TempOptionSize / sizeof (UINT16)) + 1 ;
374 OptionOrderPtr = AllocateZeroPool ( OrderItemNum * sizeof (UINT16));
375 ASSERT (OptionOrderPtr!= NULL);
376 CopyMem (OptionOrderPtr, TempOptionPtr, (OrderItemNum - 1) * sizeof (UINT16));
377
378 OptionOrderPtr[Index] = RegisterOptionNumber;
379
380 Status = gRT->SetVariable (
381 VariableName,
382 &gEfiGlobalVariableGuid,
383 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
384 OrderItemNum * sizeof (UINT16),
385 OptionOrderPtr
386 );
387 FreePool (TempOptionPtr);
388 FreePool (OptionOrderPtr);
389
390 return Status;
391 }
392
393 /**
394 Returns the size of a device path in bytes.
395
396 This function returns the size, in bytes, of the device path data structure
397 specified by DevicePath including the end of device path node. If DevicePath
398 is NULL, then 0 is returned. If the length of the device path is bigger than
399 MaxSize, also return 0 to indicate this is an invalidate device path.
400
401 @param DevicePath A pointer to a device path data structure.
402 @param MaxSize Max valid device path size. If big than this size,
403 return error.
404
405 @retval 0 An invalid device path.
406 @retval Others The size of a device path in bytes.
407
408 **/
409 UINTN
410 GetDevicePathSizeEx (
411 IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath,
412 IN UINTN MaxSize
413 )
414 {
415 UINTN Size;
416 UINTN NodeSize;
417
418 if (DevicePath == NULL) {
419 return 0;
420 }
421
422 //
423 // Search for the end of the device path structure
424 //
425 Size = 0;
426 while (!IsDevicePathEnd (DevicePath)) {
427 NodeSize = DevicePathNodeLength (DevicePath);
428 if (NodeSize == 0) {
429 return 0;
430 }
431 Size += NodeSize;
432 if (Size > MaxSize) {
433 return 0;
434 }
435 DevicePath = NextDevicePathNode (DevicePath);
436 }
437 Size += DevicePathNodeLength (DevicePath);
438 if (Size > MaxSize) {
439 return 0;
440 }
441
442 return Size;
443 }
444
445 /**
446 Returns the length of a Null-terminated Unicode string. If the length is
447 bigger than MaxStringLen, return length 0 to indicate that this is an
448 invalidate string.
449
450 This function returns the number of Unicode characters in the Null-terminated
451 Unicode string specified by String.
452
453 If String is NULL, then ASSERT().
454 If String is not aligned on a 16-bit boundary, then ASSERT().
455
456 @param String A pointer to a Null-terminated Unicode string.
457 @param MaxStringLen Max string len in this string.
458
459 @retval 0 An invalid string.
460 @retval Others The length of String.
461
462 **/
463 UINTN
464 StrSizeEx (
465 IN CONST CHAR16 *String,
466 IN UINTN MaxStringLen
467 )
468 {
469 UINTN Length;
470
471 ASSERT (String != NULL && MaxStringLen != 0);
472 ASSERT (((UINTN) String & BIT0) == 0);
473
474 for (Length = 0; *String != L'\0' && MaxStringLen != Length; String++, Length++);
475
476 if (*String != L'\0' && MaxStringLen == Length) {
477 return 0;
478 }
479
480 return (Length + 1) * sizeof (*String);
481 }
482
483 /**
484 Convert a single character to number.
485 It assumes the input Char is in the scope of L'0' ~ L'9' and L'A' ~ L'F'
486
487 @param Char The input char which need to change to a hex number.
488
489 **/
490 UINTN
491 CharToUint (
492 IN CHAR16 Char
493 )
494 {
495 if ((Char >= L'0') && (Char <= L'9')) {
496 return (UINTN) (Char - L'0');
497 }
498
499 if ((Char >= L'A') && (Char <= L'F')) {
500 return (UINTN) (Char - L'A' + 0xA);
501 }
502
503 ASSERT (FALSE);
504 return 0;
505 }
506
507 /**
508 Build the boot#### or driver#### option from the VariableName, the
509 build boot#### or driver#### will also be linked to BdsCommonOptionList.
510
511 @param BdsCommonOptionList The header of the boot#### or driver#### option
512 link list
513 @param VariableName EFI Variable name indicate if it is boot#### or
514 driver####
515
516 @retval BDS_COMMON_OPTION Get the option just been created
517 @retval NULL Failed to get the new option
518
519 **/
520 BDS_COMMON_OPTION *
521 EFIAPI
522 BdsLibVariableToOption (
523 IN OUT LIST_ENTRY *BdsCommonOptionList,
524 IN CHAR16 *VariableName
525 )
526 {
527 UINT32 Attribute;
528 UINT16 FilePathSize;
529 UINT8 *Variable;
530 UINT8 *TempPtr;
531 UINTN VariableSize;
532 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
533 EFI_DEVICE_PATH_PROTOCOL *TempPath;
534 BDS_COMMON_OPTION *Option;
535 VOID *LoadOptions;
536 UINT32 LoadOptionsSize;
537 CHAR16 *Description;
538 UINT8 NumOff;
539 UINTN TempSize;
540 //
541 // Read the variable. We will never free this data.
542 //
543 Variable = BdsLibGetVariableAndSize (
544 VariableName,
545 &gEfiGlobalVariableGuid,
546 &VariableSize
547 );
548 if (Variable == NULL) {
549 return NULL;
550 }
551 //
552 // Notes: careful defined the variable of Boot#### or
553 // Driver####, consider use some macro to abstract the code
554 //
555 //
556 // Get the option attribute
557 //
558 TempPtr = Variable;
559 Attribute = *(UINT32 *) Variable;
560 TempPtr += sizeof (UINT32);
561
562 //
563 // Get the option's device path size
564 //
565 FilePathSize = *(UINT16 *) TempPtr;
566 TempPtr += sizeof (UINT16);
567
568 //
569 // Get the option's description string
570 //
571 Description = (CHAR16 *) TempPtr;
572
573 //
574 // Get the option's description string size
575 //
576 TempSize = StrSizeEx ((CHAR16 *) TempPtr, VariableSize);
577 if (TempSize == 0) {
578 return NULL;
579 }
580 TempPtr += TempSize;
581
582 //
583 // Get the option's device path
584 //
585 DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) TempPtr;
586 TempPtr += FilePathSize;
587
588 //
589 // Validation device path.
590 //
591 TempPath = DevicePath;
592 while (FilePathSize > 0) {
593 TempSize = GetDevicePathSizeEx (TempPath, FilePathSize);
594 if (TempSize == 0) {
595 return NULL;
596 }
597 FilePathSize = (UINT16) (FilePathSize - TempSize);
598 TempPath += TempSize;
599 }
600
601 //
602 // Get load opion data.
603 //
604 LoadOptions = TempPtr;
605 if (VariableSize < (UINTN)(TempPtr - Variable)) {
606 return NULL;
607 }
608 LoadOptionsSize = (UINT32) (VariableSize - (UINTN) (TempPtr - Variable));
609
610 //
611 // The Console variables may have multiple device paths, so make
612 // an Entry for each one.
613 //
614 Option = AllocateZeroPool (sizeof (BDS_COMMON_OPTION));
615 if (Option == NULL) {
616 return NULL;
617 }
618
619 Option->Signature = BDS_LOAD_OPTION_SIGNATURE;
620 Option->DevicePath = AllocateZeroPool (GetDevicePathSize (DevicePath));
621 ASSERT(Option->DevicePath != NULL);
622 CopyMem (Option->DevicePath, DevicePath, GetDevicePathSize (DevicePath));
623
624 Option->Attribute = Attribute;
625 Option->Description = AllocateZeroPool (StrSize (Description));
626 ASSERT(Option->Description != NULL);
627 CopyMem (Option->Description, Description, StrSize (Description));
628
629 Option->LoadOptions = AllocateZeroPool (LoadOptionsSize);
630 ASSERT(Option->LoadOptions != NULL);
631 CopyMem (Option->LoadOptions, LoadOptions, LoadOptionsSize);
632 Option->LoadOptionsSize = LoadOptionsSize;
633
634 //
635 // Get the value from VariableName Unicode string
636 // since the ISO standard assumes ASCII equivalent abbreviations, we can be safe in converting this
637 // Unicode stream to ASCII without any loss in meaning.
638 //
639 if (*VariableName == 'B') {
640 NumOff = (UINT8) (sizeof (L"Boot") / sizeof (CHAR16) - 1);
641 Option->BootCurrent = (UINT16) (CharToUint (VariableName[NumOff+0]) * 0x1000)
642 + (UINT16) (CharToUint (VariableName[NumOff+1]) * 0x100)
643 + (UINT16) (CharToUint (VariableName[NumOff+2]) * 0x10)
644 + (UINT16) (CharToUint (VariableName[NumOff+3]) * 0x1);
645 }
646 //
647 // Insert active entry to BdsDeviceList
648 //
649 if ((Option->Attribute & LOAD_OPTION_ACTIVE) == LOAD_OPTION_ACTIVE) {
650 InsertTailList (BdsCommonOptionList, &Option->Link);
651 FreePool (Variable);
652 return Option;
653 }
654
655 FreePool (Variable);
656 FreePool (Option);
657 return NULL;
658
659 }
660
661 /**
662 Process BootOrder, or DriverOrder variables, by calling
663 BdsLibVariableToOption () for each UINT16 in the variables.
664
665 @param BdsCommonOptionList The header of the option list base on variable
666 VariableName
667 @param VariableName EFI Variable name indicate the BootOrder or
668 DriverOrder
669
670 @retval EFI_SUCCESS Success create the boot option or driver option
671 list
672 @retval EFI_OUT_OF_RESOURCES Failed to get the boot option or driver option list
673
674 **/
675 EFI_STATUS
676 EFIAPI
677 BdsLibBuildOptionFromVar (
678 IN LIST_ENTRY *BdsCommonOptionList,
679 IN CHAR16 *VariableName
680 )
681 {
682 UINT16 *OptionOrder;
683 UINTN OptionOrderSize;
684 UINTN Index;
685 BDS_COMMON_OPTION *Option;
686 CHAR16 OptionName[20];
687
688 //
689 // Zero Buffer in order to get all BOOT#### variables
690 //
691 ZeroMem (OptionName, sizeof (OptionName));
692
693 //
694 // Read the BootOrder, or DriverOrder variable.
695 //
696 OptionOrder = BdsLibGetVariableAndSize (
697 VariableName,
698 &gEfiGlobalVariableGuid,
699 &OptionOrderSize
700 );
701 if (OptionOrder == NULL) {
702 return EFI_OUT_OF_RESOURCES;
703 }
704
705 for (Index = 0; Index < OptionOrderSize / sizeof (UINT16); Index++) {
706 if (*VariableName == 'B') {
707 UnicodeSPrint (OptionName, sizeof (OptionName), L"Boot%04x", OptionOrder[Index]);
708 } else {
709 UnicodeSPrint (OptionName, sizeof (OptionName), L"Driver%04x", OptionOrder[Index]);
710 }
711
712 Option = BdsLibVariableToOption (BdsCommonOptionList, OptionName);
713 if (Option != NULL) {
714 Option->BootCurrent = OptionOrder[Index];
715 }
716 }
717
718 FreePool (OptionOrder);
719
720 return EFI_SUCCESS;
721 }
722
723 /**
724 Get boot mode by looking up configuration table and parsing HOB list
725
726 @param BootMode Boot mode from PEI handoff HOB.
727
728 @retval EFI_SUCCESS Successfully get boot mode
729
730 **/
731 EFI_STATUS
732 EFIAPI
733 BdsLibGetBootMode (
734 OUT EFI_BOOT_MODE *BootMode
735 )
736 {
737 *BootMode = GetBootModeHob ();
738
739 return EFI_SUCCESS;
740 }
741
742 /**
743 Read the EFI variable (VendorGuid/Name) and return a dynamically allocated
744 buffer, and the size of the buffer. If failure return NULL.
745
746 @param Name String part of EFI variable name
747 @param VendorGuid GUID part of EFI variable name
748 @param VariableSize Returns the size of the EFI variable that was read
749
750 @return Dynamically allocated memory that contains a copy of the EFI variable
751 Caller is responsible freeing the buffer.
752 @retval NULL Variable was not read
753
754 **/
755 VOID *
756 EFIAPI
757 BdsLibGetVariableAndSize (
758 IN CHAR16 *Name,
759 IN EFI_GUID *VendorGuid,
760 OUT UINTN *VariableSize
761 )
762 {
763 EFI_STATUS Status;
764 UINTN BufferSize;
765 VOID *Buffer;
766
767 Buffer = NULL;
768
769 //
770 // Pass in a zero size buffer to find the required buffer size.
771 //
772 BufferSize = 0;
773 Status = gRT->GetVariable (Name, VendorGuid, NULL, &BufferSize, Buffer);
774 if (Status == EFI_BUFFER_TOO_SMALL) {
775 //
776 // Allocate the buffer to return
777 //
778 Buffer = AllocateZeroPool (BufferSize);
779 if (Buffer == NULL) {
780 return NULL;
781 }
782 //
783 // Read variable into the allocated buffer.
784 //
785 Status = gRT->GetVariable (Name, VendorGuid, NULL, &BufferSize, Buffer);
786 if (EFI_ERROR (Status)) {
787 BufferSize = 0;
788 }
789 }
790
791 *VariableSize = BufferSize;
792 return Buffer;
793 }
794
795 /**
796 Delete the instance in Multi which matches partly with Single instance
797
798 @param Multi A pointer to a multi-instance device path data
799 structure.
800 @param Single A pointer to a single-instance device path data
801 structure.
802
803 @return This function will remove the device path instances in Multi which partly
804 match with the Single, and return the result device path. If there is no
805 remaining device path as a result, this function will return NULL.
806
807 **/
808 EFI_DEVICE_PATH_PROTOCOL *
809 EFIAPI
810 BdsLibDelPartMatchInstance (
811 IN EFI_DEVICE_PATH_PROTOCOL *Multi,
812 IN EFI_DEVICE_PATH_PROTOCOL *Single
813 )
814 {
815 EFI_DEVICE_PATH_PROTOCOL *Instance;
816 EFI_DEVICE_PATH_PROTOCOL *NewDevicePath;
817 EFI_DEVICE_PATH_PROTOCOL *TempNewDevicePath;
818 UINTN InstanceSize;
819 UINTN SingleDpSize;
820 UINTN Size;
821
822 NewDevicePath = NULL;
823 TempNewDevicePath = NULL;
824
825 if (Multi == NULL || Single == NULL) {
826 return Multi;
827 }
828
829 Instance = GetNextDevicePathInstance (&Multi, &InstanceSize);
830 SingleDpSize = GetDevicePathSize (Single) - END_DEVICE_PATH_LENGTH;
831 InstanceSize -= END_DEVICE_PATH_LENGTH;
832
833 while (Instance != NULL) {
834
835 Size = (SingleDpSize < InstanceSize) ? SingleDpSize : InstanceSize;
836
837 if ((CompareMem (Instance, Single, Size) != 0)) {
838 //
839 // Append the device path instance which does not match with Single
840 //
841 TempNewDevicePath = NewDevicePath;
842 NewDevicePath = AppendDevicePathInstance (NewDevicePath, Instance);
843 if (TempNewDevicePath != NULL) {
844 FreePool(TempNewDevicePath);
845 }
846 }
847 FreePool(Instance);
848 Instance = GetNextDevicePathInstance (&Multi, &InstanceSize);
849 InstanceSize -= END_DEVICE_PATH_LENGTH;
850 }
851
852 return NewDevicePath;
853 }
854
855 /**
856 Function compares a device path data structure to that of all the nodes of a
857 second device path instance.
858
859 @param Multi A pointer to a multi-instance device path data
860 structure.
861 @param Single A pointer to a single-instance device path data
862 structure.
863
864 @retval TRUE If the Single device path is contained within Multi device path.
865 @retval FALSE The Single device path is not match within Multi device path.
866
867 **/
868 BOOLEAN
869 EFIAPI
870 BdsLibMatchDevicePaths (
871 IN EFI_DEVICE_PATH_PROTOCOL *Multi,
872 IN EFI_DEVICE_PATH_PROTOCOL *Single
873 )
874 {
875 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
876 EFI_DEVICE_PATH_PROTOCOL *DevicePathInst;
877 UINTN Size;
878
879 if (Multi == NULL || Single == NULL) {
880 return FALSE;
881 }
882
883 DevicePath = Multi;
884 DevicePathInst = GetNextDevicePathInstance (&DevicePath, &Size);
885
886 //
887 // Search for the match of 'Single' in 'Multi'
888 //
889 while (DevicePathInst != NULL) {
890 //
891 // If the single device path is found in multiple device paths,
892 // return success
893 //
894 if (CompareMem (Single, DevicePathInst, Size) == 0) {
895 FreePool (DevicePathInst);
896 return TRUE;
897 }
898
899 FreePool (DevicePathInst);
900 DevicePathInst = GetNextDevicePathInstance (&DevicePath, &Size);
901 }
902
903 return FALSE;
904 }
905
906 /**
907 This function prints a series of strings.
908
909 @param ConOut Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL
910 @param ... A variable argument list containing series of
911 strings, the last string must be NULL.
912
913 @retval EFI_SUCCESS Success print out the string using ConOut.
914 @retval EFI_STATUS Return the status of the ConOut->OutputString ().
915
916 **/
917 EFI_STATUS
918 EFIAPI
919 BdsLibOutputStrings (
920 IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *ConOut,
921 ...
922 )
923 {
924 VA_LIST Args;
925 EFI_STATUS Status;
926 CHAR16 *String;
927
928 Status = EFI_SUCCESS;
929 VA_START (Args, ConOut);
930
931 while (!EFI_ERROR (Status)) {
932 //
933 // If String is NULL, then it's the end of the list
934 //
935 String = VA_ARG (Args, CHAR16 *);
936 if (String == NULL) {
937 break;
938 }
939
940 Status = ConOut->OutputString (ConOut, String);
941
942 if (EFI_ERROR (Status)) {
943 break;
944 }
945 }
946
947 VA_END(Args);
948 return Status;
949 }
950
951 //
952 // Following are BDS Lib functions which contain all the code about setup browser reset reminder feature.
953 // Setup Browser reset reminder feature is that an reset reminder will be given before user leaves the setup browser if
954 // user change any option setting which needs a reset to be effective, and the reset will be applied according to the user selection.
955 //
956
957
958 /**
959 Enable the setup browser reset reminder feature.
960 This routine is used in platform tip. If the platform policy need the feature, use the routine to enable it.
961
962 **/
963 VOID
964 EFIAPI
965 EnableResetReminderFeature (
966 VOID
967 )
968 {
969 mFeaturerSwitch = TRUE;
970 }
971
972
973 /**
974 Disable the setup browser reset reminder feature.
975 This routine is used in platform tip. If the platform policy do not want the feature, use the routine to disable it.
976
977 **/
978 VOID
979 EFIAPI
980 DisableResetReminderFeature (
981 VOID
982 )
983 {
984 mFeaturerSwitch = FALSE;
985 }
986
987
988 /**
989 Record the info that a reset is required.
990 A module boolean variable is used to record whether a reset is required.
991
992 **/
993 VOID
994 EFIAPI
995 EnableResetRequired (
996 VOID
997 )
998 {
999 mResetRequired = TRUE;
1000 }
1001
1002
1003 /**
1004 Record the info that no reset is required.
1005 A module boolean variable is used to record whether a reset is required.
1006
1007 **/
1008 VOID
1009 EFIAPI
1010 DisableResetRequired (
1011 VOID
1012 )
1013 {
1014 mResetRequired = FALSE;
1015 }
1016
1017
1018 /**
1019 Check whether platform policy enable the reset reminder feature. The default is enabled.
1020
1021 **/
1022 BOOLEAN
1023 EFIAPI
1024 IsResetReminderFeatureEnable (
1025 VOID
1026 )
1027 {
1028 return mFeaturerSwitch;
1029 }
1030
1031
1032 /**
1033 Check if user changed any option setting which needs a system reset to be effective.
1034
1035 **/
1036 BOOLEAN
1037 EFIAPI
1038 IsResetRequired (
1039 VOID
1040 )
1041 {
1042 return mResetRequired;
1043 }
1044
1045
1046 /**
1047 Check whether a reset is needed, and finish the reset reminder feature.
1048 If a reset is needed, Popup a menu to notice user, and finish the feature
1049 according to the user selection.
1050
1051 **/
1052 VOID
1053 EFIAPI
1054 SetupResetReminder (
1055 VOID
1056 )
1057 {
1058 EFI_INPUT_KEY Key;
1059 CHAR16 *StringBuffer1;
1060 CHAR16 *StringBuffer2;
1061
1062
1063 //
1064 //check any reset required change is applied? if yes, reset system
1065 //
1066 if (IsResetReminderFeatureEnable ()) {
1067 if (IsResetRequired ()) {
1068
1069 StringBuffer1 = AllocateZeroPool (MAX_STRING_LEN * sizeof (CHAR16));
1070 ASSERT (StringBuffer1 != NULL);
1071 StringBuffer2 = AllocateZeroPool (MAX_STRING_LEN * sizeof (CHAR16));
1072 ASSERT (StringBuffer2 != NULL);
1073 StrCpy (StringBuffer1, L"Configuration changed. Reset to apply it Now ? ");
1074 StrCpy (StringBuffer2, L"Enter (YES) / Esc (NO)");
1075 //
1076 // Popup a menu to notice user
1077 //
1078 do {
1079 CreatePopUp (EFI_LIGHTGRAY | EFI_BACKGROUND_BLUE, &Key, StringBuffer1, StringBuffer2, NULL);
1080 } while ((Key.ScanCode != SCAN_ESC) && (Key.UnicodeChar != CHAR_CARRIAGE_RETURN));
1081
1082 FreePool (StringBuffer1);
1083 FreePool (StringBuffer2);
1084 //
1085 // If the user hits the YES Response key, reset
1086 //
1087 if (Key.UnicodeChar == CHAR_CARRIAGE_RETURN) {
1088 gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL);
1089 }
1090 gST->ConOut->ClearScreen (gST->ConOut);
1091 }
1092 }
1093 }
1094
1095 /**
1096 Get the headers (dos, image, optional header) from an image
1097
1098 @param Device SimpleFileSystem device handle
1099 @param FileName File name for the image
1100 @param DosHeader Pointer to dos header
1101 @param Hdr The buffer in which to return the PE32, PE32+, or TE header.
1102
1103 @retval EFI_SUCCESS Successfully get the machine type.
1104 @retval EFI_NOT_FOUND The file is not found.
1105 @retval EFI_LOAD_ERROR File is not a valid image file.
1106
1107 **/
1108 EFI_STATUS
1109 EFIAPI
1110 BdsLibGetImageHeader (
1111 IN EFI_HANDLE Device,
1112 IN CHAR16 *FileName,
1113 OUT EFI_IMAGE_DOS_HEADER *DosHeader,
1114 OUT EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr
1115 )
1116 {
1117 EFI_STATUS Status;
1118 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Volume;
1119 EFI_FILE_HANDLE Root;
1120 EFI_FILE_HANDLE ThisFile;
1121 UINTN BufferSize;
1122 UINT64 FileSize;
1123 EFI_FILE_INFO *Info;
1124
1125 Root = NULL;
1126 ThisFile = NULL;
1127 //
1128 // Handle the file system interface to the device
1129 //
1130 Status = gBS->HandleProtocol (
1131 Device,
1132 &gEfiSimpleFileSystemProtocolGuid,
1133 (VOID *) &Volume
1134 );
1135 if (EFI_ERROR (Status)) {
1136 goto Done;
1137 }
1138
1139 Status = Volume->OpenVolume (
1140 Volume,
1141 &Root
1142 );
1143 if (EFI_ERROR (Status)) {
1144 Root = NULL;
1145 goto Done;
1146 }
1147 ASSERT (Root != NULL);
1148 Status = Root->Open (Root, &ThisFile, FileName, EFI_FILE_MODE_READ, 0);
1149 if (EFI_ERROR (Status)) {
1150 goto Done;
1151 }
1152 ASSERT (ThisFile != NULL);
1153
1154 //
1155 // Get file size
1156 //
1157 BufferSize = SIZE_OF_EFI_FILE_INFO + 200;
1158 do {
1159 Info = NULL;
1160 Status = gBS->AllocatePool (EfiBootServicesData, BufferSize, (VOID **) &Info);
1161 if (EFI_ERROR (Status)) {
1162 goto Done;
1163 }
1164 Status = ThisFile->GetInfo (
1165 ThisFile,
1166 &gEfiFileInfoGuid,
1167 &BufferSize,
1168 Info
1169 );
1170 if (!EFI_ERROR (Status)) {
1171 break;
1172 }
1173 if (Status != EFI_BUFFER_TOO_SMALL) {
1174 FreePool (Info);
1175 goto Done;
1176 }
1177 FreePool (Info);
1178 } while (TRUE);
1179
1180 FileSize = Info->FileSize;
1181 FreePool (Info);
1182
1183 //
1184 // Read dos header
1185 //
1186 BufferSize = sizeof (EFI_IMAGE_DOS_HEADER);
1187 Status = ThisFile->Read (ThisFile, &BufferSize, DosHeader);
1188 if (EFI_ERROR (Status) ||
1189 BufferSize < sizeof (EFI_IMAGE_DOS_HEADER) ||
1190 FileSize <= DosHeader->e_lfanew ||
1191 DosHeader->e_magic != EFI_IMAGE_DOS_SIGNATURE) {
1192 Status = EFI_LOAD_ERROR;
1193 goto Done;
1194 }
1195
1196 //
1197 // Move to PE signature
1198 //
1199 Status = ThisFile->SetPosition (ThisFile, DosHeader->e_lfanew);
1200 if (EFI_ERROR (Status)) {
1201 Status = EFI_LOAD_ERROR;
1202 goto Done;
1203 }
1204
1205 //
1206 // Read and check PE signature
1207 //
1208 BufferSize = sizeof (EFI_IMAGE_OPTIONAL_HEADER_UNION);
1209 Status = ThisFile->Read (ThisFile, &BufferSize, Hdr.Pe32);
1210 if (EFI_ERROR (Status) ||
1211 BufferSize < sizeof (EFI_IMAGE_OPTIONAL_HEADER_UNION) ||
1212 Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
1213 Status = EFI_LOAD_ERROR;
1214 goto Done;
1215 }
1216
1217 //
1218 // Check PE32 or PE32+ magic
1219 //
1220 if (Hdr.Pe32->OptionalHeader.Magic != EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC &&
1221 Hdr.Pe32->OptionalHeader.Magic != EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
1222 Status = EFI_LOAD_ERROR;
1223 goto Done;
1224 }
1225
1226 Done:
1227 if (ThisFile != NULL) {
1228 ThisFile->Close (ThisFile);
1229 }
1230 if (Root != NULL) {
1231 Root->Close (Root);
1232 }
1233 return Status;
1234 }
1235
1236 /**
1237 This routine adjusts the memory information for different memory type and
1238 saves them into the variables for next boot. It conditionally resets the
1239 system when the memory information changes. Platform can reserve memory
1240 large enough (125% of actual requirement) to avoid the reset in the first boot.
1241 **/
1242 VOID
1243 BdsSetMemoryTypeInformationVariable (
1244 VOID
1245 )
1246 {
1247 EFI_STATUS Status;
1248 EFI_MEMORY_TYPE_INFORMATION *PreviousMemoryTypeInformation;
1249 EFI_MEMORY_TYPE_INFORMATION *CurrentMemoryTypeInformation;
1250 UINTN VariableSize;
1251 UINTN Index;
1252 UINTN Index1;
1253 UINT32 Previous;
1254 UINT32 Current;
1255 UINT32 Next;
1256 EFI_HOB_GUID_TYPE *GuidHob;
1257 BOOLEAN MemoryTypeInformationModified;
1258 BOOLEAN MemoryTypeInformationVariableExists;
1259 EFI_BOOT_MODE BootMode;
1260
1261 MemoryTypeInformationModified = FALSE;
1262 MemoryTypeInformationVariableExists = FALSE;
1263
1264
1265 BootMode = GetBootModeHob ();
1266 //
1267 // In BOOT_IN_RECOVERY_MODE, Variable region is not reliable.
1268 //
1269 if (BootMode == BOOT_IN_RECOVERY_MODE) {
1270 return;
1271 }
1272
1273 //
1274 // Only check the the Memory Type Information variable in the boot mode
1275 // other than BOOT_WITH_DEFAULT_SETTINGS because the Memory Type
1276 // Information is not valid in this boot mode.
1277 //
1278 if (BootMode != BOOT_WITH_DEFAULT_SETTINGS) {
1279 VariableSize = 0;
1280 Status = gRT->GetVariable (
1281 EFI_MEMORY_TYPE_INFORMATION_VARIABLE_NAME,
1282 &gEfiMemoryTypeInformationGuid,
1283 NULL,
1284 &VariableSize,
1285 NULL
1286 );
1287 if (Status == EFI_BUFFER_TOO_SMALL) {
1288 MemoryTypeInformationVariableExists = TRUE;
1289 }
1290 }
1291
1292 //
1293 // Retrieve the current memory usage statistics. If they are not found, then
1294 // no adjustments can be made to the Memory Type Information variable.
1295 //
1296 Status = EfiGetSystemConfigurationTable (
1297 &gEfiMemoryTypeInformationGuid,
1298 (VOID **) &CurrentMemoryTypeInformation
1299 );
1300 if (EFI_ERROR (Status) || CurrentMemoryTypeInformation == NULL) {
1301 return;
1302 }
1303
1304 //
1305 // Get the Memory Type Information settings from Hob if they exist,
1306 // PEI is responsible for getting them from variable and build a Hob to save them.
1307 // If the previous Memory Type Information is not available, then set defaults
1308 //
1309 GuidHob = GetFirstGuidHob (&gEfiMemoryTypeInformationGuid);
1310 if (GuidHob == NULL) {
1311 //
1312 // If Platform has not built Memory Type Info into the Hob, just return.
1313 //
1314 return;
1315 }
1316 PreviousMemoryTypeInformation = GET_GUID_HOB_DATA (GuidHob);
1317 VariableSize = GET_GUID_HOB_DATA_SIZE (GuidHob);
1318
1319 //
1320 // Use a heuristic to adjust the Memory Type Information for the next boot
1321 //
1322 DEBUG ((EFI_D_INFO, "Memory Previous Current Next \n"));
1323 DEBUG ((EFI_D_INFO, " Type Pages Pages Pages \n"));
1324 DEBUG ((EFI_D_INFO, "====== ======== ======== ========\n"));
1325
1326 for (Index = 0; PreviousMemoryTypeInformation[Index].Type != EfiMaxMemoryType; Index++) {
1327
1328 for (Index1 = 0; CurrentMemoryTypeInformation[Index1].Type != EfiMaxMemoryType; Index1++) {
1329 if (PreviousMemoryTypeInformation[Index].Type == CurrentMemoryTypeInformation[Index1].Type) {
1330 break;
1331 }
1332 }
1333 if (CurrentMemoryTypeInformation[Index1].Type == EfiMaxMemoryType) {
1334 continue;
1335 }
1336
1337 //
1338 // Previous is the number of pages pre-allocated
1339 // Current is the number of pages actually needed
1340 //
1341 Previous = PreviousMemoryTypeInformation[Index].NumberOfPages;
1342 Current = CurrentMemoryTypeInformation[Index1].NumberOfPages;
1343 Next = Previous;
1344
1345 //
1346 // Write next varible to 125% * current and Inconsistent Memory Reserved across bootings may lead to S4 fail
1347 //
1348 if (Current < Previous) {
1349 if (BootMode == BOOT_WITH_DEFAULT_SETTINGS) {
1350 Next = Current + (Current >> 2);
1351 } else if (!MemoryTypeInformationVariableExists) {
1352 Next = MAX (Current + (Current >> 2), Previous);
1353 }
1354 } else if (Current > Previous) {
1355 Next = Current + (Current >> 2);
1356 }
1357 if (Next > 0 && Next < 4) {
1358 Next = 4;
1359 }
1360
1361 if (Next != Previous) {
1362 PreviousMemoryTypeInformation[Index].NumberOfPages = Next;
1363 MemoryTypeInformationModified = TRUE;
1364 }
1365
1366 DEBUG ((EFI_D_INFO, " %02x %08x %08x %08x\n", PreviousMemoryTypeInformation[Index].Type, Previous, Current, Next));
1367 }
1368
1369 //
1370 // If any changes were made to the Memory Type Information settings, then set the new variable value;
1371 // Or create the variable in first boot.
1372 //
1373 if (MemoryTypeInformationModified || !MemoryTypeInformationVariableExists) {
1374 Status = gRT->SetVariable (
1375 EFI_MEMORY_TYPE_INFORMATION_VARIABLE_NAME,
1376 &gEfiMemoryTypeInformationGuid,
1377 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
1378 VariableSize,
1379 PreviousMemoryTypeInformation
1380 );
1381
1382 //
1383 // If the Memory Type Information settings have been modified, then reset the platform
1384 // so the new Memory Type Information setting will be used to guarantee that an S4
1385 // entry/resume cycle will not fail.
1386 //
1387 if (MemoryTypeInformationModified && PcdGetBool (PcdResetOnMemoryTypeInformationChange)) {
1388 DEBUG ((EFI_D_INFO, "Memory Type Information settings change. Warm Reset!!!\n"));
1389 gRT->ResetSystem (EfiResetWarm, EFI_SUCCESS, 0, NULL);
1390 }
1391 }
1392 }
1393
1394 /**
1395 This routine is kept for backward compatibility.
1396 **/
1397 VOID
1398 EFIAPI
1399 BdsLibSaveMemoryTypeInformation (
1400 VOID
1401 )
1402 {
1403 }
1404
1405
1406 /**
1407 Identify a user and, if authenticated, returns the current user profile handle.
1408
1409 @param[out] User Point to user profile handle.
1410
1411 @retval EFI_SUCCESS User is successfully identified, or user identification
1412 is not supported.
1413 @retval EFI_ACCESS_DENIED User is not successfully identified
1414
1415 **/
1416 EFI_STATUS
1417 EFIAPI
1418 BdsLibUserIdentify (
1419 OUT EFI_USER_PROFILE_HANDLE *User
1420 )
1421 {
1422 EFI_STATUS Status;
1423 EFI_USER_MANAGER_PROTOCOL *Manager;
1424
1425 Status = gBS->LocateProtocol (
1426 &gEfiUserManagerProtocolGuid,
1427 NULL,
1428 (VOID **) &Manager
1429 );
1430 if (EFI_ERROR (Status)) {
1431 return EFI_SUCCESS;
1432 }
1433
1434 return Manager->Identify (Manager, User);
1435 }
1436