2 The common variable operation routines shared by DXE_RUNTIME variable
3 module and DXE_SMM variable module.
5 Caution: This module requires additional review when modified.
6 This driver will have external input - variable data. They may be input in SMM mode.
7 This external input must be validated carefully to avoid security issue like
8 buffer overflow, integer overflow.
10 VariableServiceGetNextVariableName () and VariableServiceQueryVariableInfo() are external API.
11 They need check input parameter.
13 VariableServiceGetVariable() and VariableServiceSetVariable() are external API
14 to receive datasize and data buffer. The size should be checked carefully.
16 VariableServiceSetVariable() should also check authenticate data to avoid buffer overflow,
17 integer overflow. It should also check attribute to avoid authentication bypass.
19 Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>
20 This program and the accompanying materials
21 are licensed and made available under the terms and conditions of the BSD License
22 which accompanies this distribution. The full text of the license may be found at
23 http://opensource.org/licenses/bsd-license.php
25 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
26 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
31 #include "AuthService.h"
33 VARIABLE_MODULE_GLOBAL
*mVariableModuleGlobal
;
36 /// Define a memory cache that improves the search performance for a variable.
38 VARIABLE_STORE_HEADER
*mNvVariableCache
= NULL
;
41 /// The memory entry used for variable statistics data.
43 VARIABLE_INFO_ENTRY
*gVariableInfo
= NULL
;
46 /// The list to store the variables which cannot be set after the EFI_END_OF_DXE_EVENT_GROUP_GUID
47 /// or EVT_GROUP_READY_TO_BOOT event.
49 LIST_ENTRY mLockedVariableList
= INITIALIZE_LIST_HEAD_VARIABLE (mLockedVariableList
);
52 /// The flag to indicate whether the platform has left the DXE phase of execution.
54 BOOLEAN mEndOfDxe
= FALSE
;
57 /// The flag to indicate whether the variable storage locking is enabled.
59 BOOLEAN mEnableLocking
= TRUE
;
62 // It will record the current boot error flag before EndOfDxe.
64 VAR_ERROR_FLAG mCurrentBootVarErrFlag
= VAR_ERROR_FLAG_NO_ERROR
;
68 SecureBoot Hook for auth variable update.
70 @param[in] VariableName Name of Variable to be found.
71 @param[in] VendorGuid Variable vendor GUID.
76 IN CHAR16
*VariableName
,
77 IN EFI_GUID
*VendorGuid
81 Routine used to track statistical information about variable usage.
82 The data is stored in the EFI system table so it can be accessed later.
83 VariableInfo.efi can dump out the table. Only Boot Services variable
84 accesses are tracked by this code. The PcdVariableCollectStatistics
85 build flag controls if this feature is enabled.
87 A read that hits in the cache will have Read and Cache true for
88 the transaction. Data is allocated by this routine, but never
91 @param[in] VariableName Name of the Variable to track.
92 @param[in] VendorGuid Guid of the Variable to track.
93 @param[in] Volatile TRUE if volatile FALSE if non-volatile.
94 @param[in] Read TRUE if GetVariable() was called.
95 @param[in] Write TRUE if SetVariable() was called.
96 @param[in] Delete TRUE if deleted via SetVariable().
97 @param[in] Cache TRUE for a cache hit.
102 IN CHAR16
*VariableName
,
103 IN EFI_GUID
*VendorGuid
,
111 VARIABLE_INFO_ENTRY
*Entry
;
113 if (FeaturePcdGet (PcdVariableCollectStatistics
)) {
116 // Don't collect statistics at runtime.
120 if (gVariableInfo
== NULL
) {
122 // On the first call allocate a entry and place a pointer to it in
123 // the EFI System Table.
125 gVariableInfo
= AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY
));
126 ASSERT (gVariableInfo
!= NULL
);
128 CopyGuid (&gVariableInfo
->VendorGuid
, VendorGuid
);
129 gVariableInfo
->Name
= AllocatePool (StrSize (VariableName
));
130 ASSERT (gVariableInfo
->Name
!= NULL
);
131 StrCpy (gVariableInfo
->Name
, VariableName
);
132 gVariableInfo
->Volatile
= Volatile
;
136 for (Entry
= gVariableInfo
; Entry
!= NULL
; Entry
= Entry
->Next
) {
137 if (CompareGuid (VendorGuid
, &Entry
->VendorGuid
)) {
138 if (StrCmp (VariableName
, Entry
->Name
) == 0) {
146 Entry
->DeleteCount
++;
156 if (Entry
->Next
== NULL
) {
158 // If the entry is not in the table add it.
159 // Next iteration of the loop will fill in the data.
161 Entry
->Next
= AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY
));
162 ASSERT (Entry
->Next
!= NULL
);
164 CopyGuid (&Entry
->Next
->VendorGuid
, VendorGuid
);
165 Entry
->Next
->Name
= AllocatePool (StrSize (VariableName
));
166 ASSERT (Entry
->Next
->Name
!= NULL
);
167 StrCpy (Entry
->Next
->Name
, VariableName
);
168 Entry
->Next
->Volatile
= Volatile
;
178 This code checks if variable header is valid or not.
180 @param Variable Pointer to the Variable Header.
181 @param VariableStoreEnd Pointer to the Variable Store End.
183 @retval TRUE Variable header is valid.
184 @retval FALSE Variable header is not valid.
188 IsValidVariableHeader (
189 IN VARIABLE_HEADER
*Variable
,
190 IN VARIABLE_HEADER
*VariableStoreEnd
193 if ((Variable
== NULL
) || (Variable
>= VariableStoreEnd
) || (Variable
->StartId
!= VARIABLE_DATA
)) {
195 // Variable is NULL or has reached the end of variable store,
196 // or the StartId is not correct.
207 This function writes data to the FWH at the correct LBA even if the LBAs
210 @param Global Pointer to VARAIBLE_GLOBAL structure.
211 @param Volatile Point out the Variable is Volatile or Non-Volatile.
212 @param SetByIndex TRUE if target pointer is given as index.
213 FALSE if target pointer is absolute.
214 @param Fvb Pointer to the writable FVB protocol.
215 @param DataPtrIndex Pointer to the Data from the end of VARIABLE_STORE_HEADER
217 @param DataSize Size of data to be written.
218 @param Buffer Pointer to the buffer from which data is written.
220 @retval EFI_INVALID_PARAMETER Parameters not valid.
221 @retval EFI_SUCCESS Variable store successfully updated.
225 UpdateVariableStore (
226 IN VARIABLE_GLOBAL
*Global
,
228 IN BOOLEAN SetByIndex
,
229 IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL
*Fvb
,
230 IN UINTN DataPtrIndex
,
235 EFI_FV_BLOCK_MAP_ENTRY
*PtrBlockMapEntry
;
243 EFI_FIRMWARE_VOLUME_HEADER
*FwVolHeader
;
244 VARIABLE_STORE_HEADER
*VolatileBase
;
245 EFI_PHYSICAL_ADDRESS FvVolHdr
;
246 EFI_PHYSICAL_ADDRESS DataPtr
;
250 DataPtr
= DataPtrIndex
;
253 // Check if the Data is Volatile.
257 return EFI_INVALID_PARAMETER
;
259 Status
= Fvb
->GetPhysicalAddress(Fvb
, &FvVolHdr
);
260 ASSERT_EFI_ERROR (Status
);
262 FwVolHeader
= (EFI_FIRMWARE_VOLUME_HEADER
*) ((UINTN
) FvVolHdr
);
264 // Data Pointer should point to the actual Address where data is to be
268 DataPtr
+= mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
;
271 if ((DataPtr
+ DataSize
) >= ((EFI_PHYSICAL_ADDRESS
) (UINTN
) ((UINT8
*) FwVolHeader
+ FwVolHeader
->FvLength
))) {
272 return EFI_INVALID_PARAMETER
;
276 // Data Pointer should point to the actual Address where data is to be
279 VolatileBase
= (VARIABLE_STORE_HEADER
*) ((UINTN
) mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
);
281 DataPtr
+= mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
;
284 if ((DataPtr
+ DataSize
) >= ((UINTN
) ((UINT8
*) VolatileBase
+ VolatileBase
->Size
))) {
285 return EFI_INVALID_PARAMETER
;
289 // If Volatile Variable just do a simple mem copy.
291 CopyMem ((UINT8
*)(UINTN
)DataPtr
, Buffer
, DataSize
);
296 // If we are here we are dealing with Non-Volatile Variables.
298 LinearOffset
= (UINTN
) FwVolHeader
;
299 CurrWritePtr
= (UINTN
) DataPtr
;
300 CurrWriteSize
= DataSize
;
304 if (CurrWritePtr
< LinearOffset
) {
305 return EFI_INVALID_PARAMETER
;
308 for (PtrBlockMapEntry
= FwVolHeader
->BlockMap
; PtrBlockMapEntry
->NumBlocks
!= 0; PtrBlockMapEntry
++) {
309 for (BlockIndex2
= 0; BlockIndex2
< PtrBlockMapEntry
->NumBlocks
; BlockIndex2
++) {
311 // Check to see if the Variable Writes are spanning through multiple
314 if ((CurrWritePtr
>= LinearOffset
) && (CurrWritePtr
< LinearOffset
+ PtrBlockMapEntry
->Length
)) {
315 if ((CurrWritePtr
+ CurrWriteSize
) <= (LinearOffset
+ PtrBlockMapEntry
->Length
)) {
316 Status
= Fvb
->Write (
319 (UINTN
) (CurrWritePtr
- LinearOffset
),
325 Size
= (UINT32
) (LinearOffset
+ PtrBlockMapEntry
->Length
- CurrWritePtr
);
326 Status
= Fvb
->Write (
329 (UINTN
) (CurrWritePtr
- LinearOffset
),
333 if (EFI_ERROR (Status
)) {
337 CurrWritePtr
= LinearOffset
+ PtrBlockMapEntry
->Length
;
338 CurrBuffer
= CurrBuffer
+ Size
;
339 CurrWriteSize
= CurrWriteSize
- Size
;
343 LinearOffset
+= PtrBlockMapEntry
->Length
;
354 This code gets the current status of Variable Store.
356 @param VarStoreHeader Pointer to the Variable Store Header.
358 @retval EfiRaw Variable store status is raw.
359 @retval EfiValid Variable store status is valid.
360 @retval EfiInvalid Variable store status is invalid.
363 VARIABLE_STORE_STATUS
364 GetVariableStoreStatus (
365 IN VARIABLE_STORE_HEADER
*VarStoreHeader
368 if (CompareGuid (&VarStoreHeader
->Signature
, &gEfiAuthenticatedVariableGuid
) &&
369 VarStoreHeader
->Format
== VARIABLE_STORE_FORMATTED
&&
370 VarStoreHeader
->State
== VARIABLE_STORE_HEALTHY
374 } else if (((UINT32
*)(&VarStoreHeader
->Signature
))[0] == 0xffffffff &&
375 ((UINT32
*)(&VarStoreHeader
->Signature
))[1] == 0xffffffff &&
376 ((UINT32
*)(&VarStoreHeader
->Signature
))[2] == 0xffffffff &&
377 ((UINT32
*)(&VarStoreHeader
->Signature
))[3] == 0xffffffff &&
378 VarStoreHeader
->Size
== 0xffffffff &&
379 VarStoreHeader
->Format
== 0xff &&
380 VarStoreHeader
->State
== 0xff
392 This code gets the size of name of variable.
394 @param Variable Pointer to the Variable Header.
396 @return UINTN Size of variable in bytes.
401 IN VARIABLE_HEADER
*Variable
404 if (Variable
->State
== (UINT8
) (-1) ||
405 Variable
->DataSize
== (UINT32
) (-1) ||
406 Variable
->NameSize
== (UINT32
) (-1) ||
407 Variable
->Attributes
== (UINT32
) (-1)) {
410 return (UINTN
) Variable
->NameSize
;
415 This code gets the size of variable data.
417 @param Variable Pointer to the Variable Header.
419 @return Size of variable in bytes.
424 IN VARIABLE_HEADER
*Variable
427 if (Variable
->State
== (UINT8
) (-1) ||
428 Variable
->DataSize
== (UINT32
) (-1) ||
429 Variable
->NameSize
== (UINT32
) (-1) ||
430 Variable
->Attributes
== (UINT32
) (-1)) {
433 return (UINTN
) Variable
->DataSize
;
438 This code gets the pointer to the variable name.
440 @param Variable Pointer to the Variable Header.
442 @return Pointer to Variable Name which is Unicode encoding.
447 IN VARIABLE_HEADER
*Variable
451 return (CHAR16
*) (Variable
+ 1);
456 This code gets the pointer to the variable data.
458 @param Variable Pointer to the Variable Header.
460 @return Pointer to Variable Data.
465 IN VARIABLE_HEADER
*Variable
471 // Be careful about pad size for alignment.
473 Value
= (UINTN
) GetVariableNamePtr (Variable
);
474 Value
+= NameSizeOfVariable (Variable
);
475 Value
+= GET_PAD_SIZE (NameSizeOfVariable (Variable
));
477 return (UINT8
*) Value
;
483 This code gets the pointer to the next variable header.
485 @param Variable Pointer to the Variable Header.
487 @return Pointer to next variable header.
492 IN VARIABLE_HEADER
*Variable
497 Value
= (UINTN
) GetVariableDataPtr (Variable
);
498 Value
+= DataSizeOfVariable (Variable
);
499 Value
+= GET_PAD_SIZE (DataSizeOfVariable (Variable
));
502 // Be careful about pad size for alignment.
504 return (VARIABLE_HEADER
*) HEADER_ALIGN (Value
);
509 Gets the pointer to the first variable header in given variable store area.
511 @param VarStoreHeader Pointer to the Variable Store Header.
513 @return Pointer to the first variable header.
518 IN VARIABLE_STORE_HEADER
*VarStoreHeader
522 // The end of variable store.
524 return (VARIABLE_HEADER
*) HEADER_ALIGN (VarStoreHeader
+ 1);
529 Gets the pointer to the end of the variable storage area.
531 This function gets pointer to the end of the variable storage
532 area, according to the input variable store header.
534 @param VarStoreHeader Pointer to the Variable Store Header.
536 @return Pointer to the end of the variable storage area.
541 IN VARIABLE_STORE_HEADER
*VarStoreHeader
545 // The end of variable store
547 return (VARIABLE_HEADER
*) HEADER_ALIGN ((UINTN
) VarStoreHeader
+ VarStoreHeader
->Size
);
551 Record variable error flag.
553 @param[in] Flag Variable error flag to record.
554 @param[in] VariableName Name of variable.
555 @param[in] VendorGuid Guid of variable.
556 @param[in] Attributes Attributes of the variable.
557 @param[in] VariableSize Size of the variable.
562 IN VAR_ERROR_FLAG Flag
,
563 IN CHAR16
*VariableName
,
564 IN EFI_GUID
*VendorGuid
,
565 IN UINT32 Attributes
,
566 IN UINTN VariableSize
570 VARIABLE_POINTER_TRACK Variable
;
571 VAR_ERROR_FLAG
*VarErrFlag
;
572 VAR_ERROR_FLAG TempFlag
;
575 DEBUG ((EFI_D_ERROR
, "RecordVarErrorFlag (0x%02x) %s:%g - 0x%08x - 0x%x\n", Flag
, VariableName
, VendorGuid
, Attributes
, VariableSize
));
576 if (Flag
== VAR_ERROR_FLAG_SYSTEM_ERROR
) {
578 DEBUG ((EFI_D_ERROR
, "CommonRuntimeVariableSpace = 0x%x - CommonVariableTotalSize = 0x%x\n", mVariableModuleGlobal
->CommonRuntimeVariableSpace
, mVariableModuleGlobal
->CommonVariableTotalSize
));
580 DEBUG ((EFI_D_ERROR
, "CommonVariableSpace = 0x%x - CommonVariableTotalSize = 0x%x\n", mVariableModuleGlobal
->CommonVariableSpace
, mVariableModuleGlobal
->CommonVariableTotalSize
));
583 DEBUG ((EFI_D_ERROR
, "CommonMaxUserVariableSpace = 0x%x - CommonUserVariableTotalSize = 0x%x\n", mVariableModuleGlobal
->CommonMaxUserVariableSpace
, mVariableModuleGlobal
->CommonUserVariableTotalSize
));
589 // Before EndOfDxe, just record the current boot variable error flag to local variable,
590 // and leave the variable error flag in NV flash as the last boot variable error flag.
591 // After EndOfDxe in InitializeVarErrorFlag (), the variable error flag in NV flash
592 // will be initialized to this local current boot variable error flag.
594 mCurrentBootVarErrFlag
&= Flag
;
599 // Record error flag (it should have be initialized).
601 Status
= FindVariable (
603 &gEdkiiVarErrorFlagGuid
,
605 &mVariableModuleGlobal
->VariableGlobal
,
608 if (!EFI_ERROR (Status
)) {
609 VarErrFlag
= (VAR_ERROR_FLAG
*) GetVariableDataPtr (Variable
.CurrPtr
);
610 TempFlag
= *VarErrFlag
;
612 if (TempFlag
== *VarErrFlag
) {
615 Status
= UpdateVariableStore (
616 &mVariableModuleGlobal
->VariableGlobal
,
619 mVariableModuleGlobal
->FvbInstance
,
620 (UINTN
) VarErrFlag
- (UINTN
) mNvVariableCache
+ (UINTN
) mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
,
624 if (!EFI_ERROR (Status
)) {
626 // Update the data in NV cache.
634 Initialize variable error flag.
636 Before EndOfDxe, the variable indicates the last boot variable error flag,
637 then it means the last boot variable error flag must be got before EndOfDxe.
638 After EndOfDxe, the variable indicates the current boot variable error flag,
639 then it means the current boot variable error flag must be got after EndOfDxe.
643 InitializeVarErrorFlag (
648 VARIABLE_POINTER_TRACK Variable
;
650 VAR_ERROR_FLAG VarErrFlag
;
656 Flag
= mCurrentBootVarErrFlag
;
657 DEBUG ((EFI_D_INFO
, "Initialize variable error flag (%02x)\n", Flag
));
659 Status
= FindVariable (
661 &gEdkiiVarErrorFlagGuid
,
663 &mVariableModuleGlobal
->VariableGlobal
,
666 if (!EFI_ERROR (Status
)) {
667 VarErrFlag
= *((VAR_ERROR_FLAG
*) GetVariableDataPtr (Variable
.CurrPtr
));
668 if (VarErrFlag
== Flag
) {
675 &gEdkiiVarErrorFlagGuid
,
678 VARIABLE_ATTRIBUTE_NV_BS_RT
,
689 @param[in] Variable Pointer to variable header.
691 @retval TRUE User variable.
692 @retval FALSE System variable.
697 IN VARIABLE_HEADER
*Variable
700 VAR_CHECK_VARIABLE_PROPERTY Property
;
703 // Only after End Of Dxe, the variables belong to system variable are fixed.
704 // If PcdMaxUserNvStorageVariableSize is 0, it means user variable share the same NV storage with system variable,
705 // then no need to check if the variable is user variable or not specially.
707 if (mEndOfDxe
&& (mVariableModuleGlobal
->CommonMaxUserVariableSpace
!= mVariableModuleGlobal
->CommonVariableSpace
)) {
708 if (InternalVarCheckVariablePropertyGet (GetVariableNamePtr (Variable
), &Variable
->VendorGuid
, &Property
) == EFI_NOT_FOUND
) {
716 Calculate common user variable total size.
720 CalculateCommonUserVariableTotalSize (
724 VARIABLE_HEADER
*Variable
;
725 VARIABLE_HEADER
*NextVariable
;
727 VAR_CHECK_VARIABLE_PROPERTY Property
;
730 // Only after End Of Dxe, the variables belong to system variable are fixed.
731 // If PcdMaxUserNvStorageVariableSize is 0, it means user variable share the same NV storage with system variable,
732 // then no need to calculate the common user variable total size specially.
734 if (mEndOfDxe
&& (mVariableModuleGlobal
->CommonMaxUserVariableSpace
!= mVariableModuleGlobal
->CommonVariableSpace
)) {
735 Variable
= GetStartPointer (mNvVariableCache
);
736 while (IsValidVariableHeader (Variable
, GetEndPointer (mNvVariableCache
))) {
737 NextVariable
= GetNextVariablePtr (Variable
);
738 VariableSize
= (UINTN
) NextVariable
- (UINTN
) Variable
;
739 if ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) != EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
740 if (InternalVarCheckVariablePropertyGet (GetVariableNamePtr (Variable
), &Variable
->VendorGuid
, &Property
) == EFI_NOT_FOUND
) {
742 // No property, it is user variable.
744 mVariableModuleGlobal
->CommonUserVariableTotalSize
+= VariableSize
;
748 Variable
= NextVariable
;
754 Initialize variable quota.
758 InitializeVariableQuota (
762 STATIC BOOLEAN Initialized
;
764 if (!mEndOfDxe
|| Initialized
) {
769 InitializeVarErrorFlag ();
770 CalculateCommonUserVariableTotalSize ();
775 Check the PubKeyIndex is a valid key or not.
777 This function will iterate the NV storage to see if this PubKeyIndex is still referenced
778 by any valid count-based auth variabe.
780 @param[in] PubKeyIndex Index of the public key in public key store.
782 @retval TRUE The PubKeyIndex is still in use.
783 @retval FALSE The PubKeyIndex is not referenced by any count-based auth variabe.
788 IN UINT32 PubKeyIndex
791 VARIABLE_HEADER
*Variable
;
792 VARIABLE_HEADER
*VariableStoreEnd
;
794 if (PubKeyIndex
> mPubKeyNumber
) {
798 Variable
= GetStartPointer ((VARIABLE_STORE_HEADER
*) (UINTN
) mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
);
799 VariableStoreEnd
= GetEndPointer ((VARIABLE_STORE_HEADER
*) (UINTN
) mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
);
801 while (IsValidVariableHeader (Variable
, VariableStoreEnd
)) {
802 if ((Variable
->State
== VAR_ADDED
|| Variable
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)) &&
803 Variable
->PubKeyIndex
== PubKeyIndex
) {
806 Variable
= GetNextVariablePtr (Variable
);
814 Get the number of valid public key in PubKeyStore.
816 @param[in] PubKeyNumber Number of the public key in public key store.
818 @return Number of valid public key in PubKeyStore.
822 GetValidPubKeyNumber (
823 IN UINT32 PubKeyNumber
831 for (PubKeyIndex
= 1; PubKeyIndex
<= PubKeyNumber
; PubKeyIndex
++) {
832 if (IsValidPubKeyIndex (PubKeyIndex
)) {
842 Filter the useless key in public key store.
844 This function will find out all valid public keys in public key database, save them in new allocated
845 buffer NewPubKeyStore, and give the new PubKeyIndex. The caller is responsible for freeing buffer
846 NewPubKeyIndex and NewPubKeyStore with FreePool().
848 @param[in] PubKeyStore Point to the public key database.
849 @param[in] PubKeyNumber Number of the public key in PubKeyStore.
850 @param[out] NewPubKeyIndex Point to an array of new PubKeyIndex corresponds to NewPubKeyStore.
851 @param[out] NewPubKeyStore Saved all valid public keys in PubKeyStore.
852 @param[out] NewPubKeySize Buffer size of the NewPubKeyStore.
854 @retval EFI_SUCCESS Trim operation is complete successfully.
855 @retval EFI_OUT_OF_RESOURCES No enough memory resources, or no useless key in PubKeyStore.
860 IN UINT8
*PubKeyStore
,
861 IN UINT32 PubKeyNumber
,
862 OUT UINT32
**NewPubKeyIndex
,
863 OUT UINT8
**NewPubKeyStore
,
864 OUT UINT32
*NewPubKeySize
869 UINT32 NewPubKeyNumber
;
871 NewPubKeyNumber
= GetValidPubKeyNumber (PubKeyNumber
);
872 if (NewPubKeyNumber
== PubKeyNumber
) {
873 return EFI_OUT_OF_RESOURCES
;
876 if (NewPubKeyNumber
!= 0) {
877 *NewPubKeySize
= NewPubKeyNumber
* EFI_CERT_TYPE_RSA2048_SIZE
;
879 *NewPubKeySize
= sizeof (UINT8
);
882 *NewPubKeyStore
= AllocatePool (*NewPubKeySize
);
883 if (*NewPubKeyStore
== NULL
) {
884 return EFI_OUT_OF_RESOURCES
;
887 *NewPubKeyIndex
= AllocateZeroPool ((PubKeyNumber
+ 1) * sizeof (UINT32
));
888 if (*NewPubKeyIndex
== NULL
) {
889 FreePool (*NewPubKeyStore
);
890 *NewPubKeyStore
= NULL
;
891 return EFI_OUT_OF_RESOURCES
;
895 for (PubKeyIndex
= 1; PubKeyIndex
<= PubKeyNumber
; PubKeyIndex
++) {
896 if (IsValidPubKeyIndex (PubKeyIndex
)) {
898 *NewPubKeyStore
+ CopiedKey
* EFI_CERT_TYPE_RSA2048_SIZE
,
899 PubKeyStore
+ (PubKeyIndex
- 1) * EFI_CERT_TYPE_RSA2048_SIZE
,
900 EFI_CERT_TYPE_RSA2048_SIZE
902 (*NewPubKeyIndex
)[PubKeyIndex
] = ++CopiedKey
;
910 Variable store garbage collection and reclaim operation.
912 If ReclaimPubKeyStore is FALSE, reclaim variable space by deleting the obsoleted varaibles.
913 If ReclaimPubKeyStore is TRUE, reclaim invalid key in public key database and update the PubKeyIndex
914 for all the count-based authenticate variable in NV storage.
916 @param[in] VariableBase Base address of variable store.
917 @param[out] LastVariableOffset Offset of last variable.
918 @param[in] IsVolatile The variable store is volatile or not;
919 if it is non-volatile, need FTW.
920 @param[in, out] UpdatingPtrTrack Pointer to updating variable pointer track structure.
921 @param[in] NewVariable Pointer to new variable.
922 @param[in] NewVariableSize New variable size.
923 @param[in] ReclaimPubKeyStore Reclaim for public key database or not.
925 @return EFI_SUCCESS Reclaim operation has finished successfully.
926 @return EFI_OUT_OF_RESOURCES No enough memory resources or variable space.
927 @return EFI_DEVICE_ERROR The public key database doesn't exist.
928 @return Others Unexpect error happened during reclaim operation.
933 IN EFI_PHYSICAL_ADDRESS VariableBase
,
934 OUT UINTN
*LastVariableOffset
,
935 IN BOOLEAN IsVolatile
,
936 IN OUT VARIABLE_POINTER_TRACK
*UpdatingPtrTrack
,
937 IN VARIABLE_HEADER
*NewVariable
,
938 IN UINTN NewVariableSize
,
939 IN BOOLEAN ReclaimPubKeyStore
942 VARIABLE_HEADER
*Variable
;
943 VARIABLE_HEADER
*AddedVariable
;
944 VARIABLE_HEADER
*NextVariable
;
945 VARIABLE_HEADER
*NextAddedVariable
;
946 VARIABLE_STORE_HEADER
*VariableStoreHeader
;
948 UINTN MaximumBufferSize
;
956 UINTN CommonVariableTotalSize
;
957 UINTN CommonUserVariableTotalSize
;
958 UINTN HwErrVariableTotalSize
;
959 UINT32
*NewPubKeyIndex
;
960 UINT8
*NewPubKeyStore
;
961 UINT32 NewPubKeySize
;
962 VARIABLE_HEADER
*PubKeyHeader
;
963 VARIABLE_HEADER
*UpdatingVariable
;
964 VARIABLE_HEADER
*UpdatingInDeletedTransition
;
966 UpdatingVariable
= NULL
;
967 UpdatingInDeletedTransition
= NULL
;
968 if (UpdatingPtrTrack
!= NULL
) {
969 UpdatingVariable
= UpdatingPtrTrack
->CurrPtr
;
970 UpdatingInDeletedTransition
= UpdatingPtrTrack
->InDeletedTransitionPtr
;
973 VariableStoreHeader
= (VARIABLE_STORE_HEADER
*) ((UINTN
) VariableBase
);
975 CommonVariableTotalSize
= 0;
976 CommonUserVariableTotalSize
= 0;
977 HwErrVariableTotalSize
= 0;
978 NewPubKeyIndex
= NULL
;
979 NewPubKeyStore
= NULL
;
985 // Start Pointers for the variable.
987 Variable
= GetStartPointer (VariableStoreHeader
);
988 MaximumBufferSize
= sizeof (VARIABLE_STORE_HEADER
);
990 while (IsValidVariableHeader (Variable
, GetEndPointer (VariableStoreHeader
))) {
991 NextVariable
= GetNextVariablePtr (Variable
);
992 if ((Variable
->State
== VAR_ADDED
|| Variable
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)) &&
993 Variable
!= UpdatingVariable
&&
994 Variable
!= UpdatingInDeletedTransition
996 VariableSize
= (UINTN
) NextVariable
- (UINTN
) Variable
;
997 MaximumBufferSize
+= VariableSize
;
1000 Variable
= NextVariable
;
1003 if (NewVariable
!= NULL
) {
1005 // Add the new variable size.
1007 MaximumBufferSize
+= NewVariableSize
;
1011 // Reserve the 1 Bytes with Oxff to identify the
1012 // end of the variable buffer.
1014 MaximumBufferSize
+= 1;
1015 ValidBuffer
= AllocatePool (MaximumBufferSize
);
1016 if (ValidBuffer
== NULL
) {
1017 return EFI_OUT_OF_RESOURCES
;
1021 // For NV variable reclaim, don't allocate pool here and just use mNvVariableCache
1022 // as the buffer to reduce SMRAM consumption for SMM variable driver.
1024 MaximumBufferSize
= mNvVariableCache
->Size
;
1025 ValidBuffer
= (UINT8
*) mNvVariableCache
;
1028 SetMem (ValidBuffer
, MaximumBufferSize
, 0xff);
1031 // Copy variable store header.
1033 CopyMem (ValidBuffer
, VariableStoreHeader
, sizeof (VARIABLE_STORE_HEADER
));
1034 CurrPtr
= (UINT8
*) GetStartPointer ((VARIABLE_STORE_HEADER
*) ValidBuffer
);
1036 if (ReclaimPubKeyStore
) {
1037 ASSERT (IsVolatile
== FALSE
);
1039 // Trim the PubKeyStore and get new PubKeyIndex.
1041 Status
= PubKeyStoreFilter (
1048 if (EFI_ERROR (Status
)) {
1051 ASSERT ((NewPubKeyIndex
!= NULL
) && (NewPubKeyStore
!= NULL
));
1054 // Refresh the PubKeyIndex for all valid variables (ADDED and IN_DELETED_TRANSITION).
1056 Variable
= GetStartPointer (VariableStoreHeader
);
1057 while (IsValidVariableHeader (Variable
, GetEndPointer (VariableStoreHeader
))) {
1058 NextVariable
= GetNextVariablePtr (Variable
);
1059 if (Variable
->State
== VAR_ADDED
|| Variable
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)) {
1060 if ((StrCmp (GetVariableNamePtr (Variable
), AUTHVAR_KEYDB_NAME
) == 0) &&
1061 (CompareGuid (&Variable
->VendorGuid
, &gEfiAuthenticatedVariableGuid
))) {
1063 // Skip the public key database, it will be reinstalled later.
1065 PubKeyHeader
= Variable
;
1066 Variable
= NextVariable
;
1070 VariableSize
= (UINTN
) NextVariable
- (UINTN
) Variable
;
1071 CopyMem (CurrPtr
, (UINT8
*) Variable
, VariableSize
);
1072 ((VARIABLE_HEADER
*) CurrPtr
)->PubKeyIndex
= NewPubKeyIndex
[Variable
->PubKeyIndex
];
1073 CurrPtr
+= VariableSize
;
1074 if ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
1075 HwErrVariableTotalSize
+= VariableSize
;
1076 } else if ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) != EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
1077 CommonVariableTotalSize
+= VariableSize
;
1078 if (IsUserVariable (Variable
)) {
1079 CommonUserVariableTotalSize
+= VariableSize
;
1083 Variable
= NextVariable
;
1087 // Reinstall the new public key database.
1089 ASSERT (PubKeyHeader
!= NULL
);
1090 if (PubKeyHeader
== NULL
) {
1091 Status
= EFI_DEVICE_ERROR
;
1094 CopyMem (CurrPtr
, (UINT8
*) PubKeyHeader
, sizeof (VARIABLE_HEADER
));
1095 Variable
= (VARIABLE_HEADER
*) CurrPtr
;
1096 Variable
->DataSize
= NewPubKeySize
;
1097 StrCpy (GetVariableNamePtr (Variable
), GetVariableNamePtr (PubKeyHeader
));
1098 CopyMem (GetVariableDataPtr (Variable
), NewPubKeyStore
, NewPubKeySize
);
1099 CurrPtr
= (UINT8
*) GetNextVariablePtr (Variable
);
1100 CommonVariableTotalSize
+= (UINTN
) CurrPtr
- (UINTN
) Variable
;
1101 if (IsUserVariable (Variable
)) {
1102 CommonUserVariableTotalSize
+= (UINTN
) CurrPtr
- (UINTN
) Variable
;
1106 // Reinstall all ADDED variables as long as they are not identical to Updating Variable.
1108 Variable
= GetStartPointer (VariableStoreHeader
);
1109 while (IsValidVariableHeader (Variable
, GetEndPointer (VariableStoreHeader
))) {
1110 NextVariable
= GetNextVariablePtr (Variable
);
1111 if (Variable
!= UpdatingVariable
&& Variable
->State
== VAR_ADDED
) {
1112 VariableSize
= (UINTN
) NextVariable
- (UINTN
) Variable
;
1113 CopyMem (CurrPtr
, (UINT8
*) Variable
, VariableSize
);
1114 CurrPtr
+= VariableSize
;
1115 if ((!IsVolatile
) && ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) {
1116 HwErrVariableTotalSize
+= VariableSize
;
1117 } else if ((!IsVolatile
) && ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) != EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) {
1118 CommonVariableTotalSize
+= VariableSize
;
1119 if (IsUserVariable (Variable
)) {
1120 CommonUserVariableTotalSize
+= VariableSize
;
1124 Variable
= NextVariable
;
1128 // Reinstall all in delete transition variables.
1130 Variable
= GetStartPointer (VariableStoreHeader
);
1131 while (IsValidVariableHeader (Variable
, GetEndPointer (VariableStoreHeader
))) {
1132 NextVariable
= GetNextVariablePtr (Variable
);
1133 if (Variable
!= UpdatingVariable
&& Variable
!= UpdatingInDeletedTransition
&& Variable
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)) {
1136 // Buffer has cached all ADDED variable.
1137 // Per IN_DELETED variable, we have to guarantee that
1138 // no ADDED one in previous buffer.
1142 AddedVariable
= GetStartPointer ((VARIABLE_STORE_HEADER
*) ValidBuffer
);
1143 while (IsValidVariableHeader (AddedVariable
, GetEndPointer ((VARIABLE_STORE_HEADER
*) ValidBuffer
))) {
1144 NextAddedVariable
= GetNextVariablePtr (AddedVariable
);
1145 NameSize
= NameSizeOfVariable (AddedVariable
);
1146 if (CompareGuid (&AddedVariable
->VendorGuid
, &Variable
->VendorGuid
) &&
1147 NameSize
== NameSizeOfVariable (Variable
)
1149 Point0
= (VOID
*) GetVariableNamePtr (AddedVariable
);
1150 Point1
= (VOID
*) GetVariableNamePtr (Variable
);
1151 if (CompareMem (Point0
, Point1
, NameSize
) == 0) {
1156 AddedVariable
= NextAddedVariable
;
1160 // Promote VAR_IN_DELETED_TRANSITION to VAR_ADDED.
1162 VariableSize
= (UINTN
) NextVariable
- (UINTN
) Variable
;
1163 CopyMem (CurrPtr
, (UINT8
*) Variable
, VariableSize
);
1164 ((VARIABLE_HEADER
*) CurrPtr
)->State
= VAR_ADDED
;
1165 CurrPtr
+= VariableSize
;
1166 if ((!IsVolatile
) && ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) {
1167 HwErrVariableTotalSize
+= VariableSize
;
1168 } else if ((!IsVolatile
) && ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) != EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) {
1169 CommonVariableTotalSize
+= VariableSize
;
1170 if (IsUserVariable (Variable
)) {
1171 CommonUserVariableTotalSize
+= VariableSize
;
1177 Variable
= NextVariable
;
1181 // Install the new variable if it is not NULL.
1183 if (NewVariable
!= NULL
) {
1184 if ((UINTN
) (CurrPtr
- ValidBuffer
) + NewVariableSize
> VariableStoreHeader
->Size
) {
1186 // No enough space to store the new variable.
1188 Status
= EFI_OUT_OF_RESOURCES
;
1192 if ((NewVariable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
1193 HwErrVariableTotalSize
+= NewVariableSize
;
1194 } else if ((NewVariable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) != EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
1195 CommonVariableTotalSize
+= NewVariableSize
;
1196 if (IsUserVariable (NewVariable
)) {
1197 CommonUserVariableTotalSize
+= NewVariableSize
;
1200 if ((HwErrVariableTotalSize
> PcdGet32 (PcdHwErrStorageSize
)) ||
1201 (CommonVariableTotalSize
> mVariableModuleGlobal
->CommonVariableSpace
) ||
1202 (CommonUserVariableTotalSize
> mVariableModuleGlobal
->CommonMaxUserVariableSpace
)) {
1204 // No enough space to store the new variable by NV or NV+HR attribute.
1206 Status
= EFI_OUT_OF_RESOURCES
;
1211 CopyMem (CurrPtr
, (UINT8
*) NewVariable
, NewVariableSize
);
1212 ((VARIABLE_HEADER
*) CurrPtr
)->State
= VAR_ADDED
;
1213 if (UpdatingVariable
!= NULL
) {
1214 UpdatingPtrTrack
->CurrPtr
= (VARIABLE_HEADER
*)((UINTN
)UpdatingPtrTrack
->StartPtr
+ ((UINTN
)CurrPtr
- (UINTN
)GetStartPointer ((VARIABLE_STORE_HEADER
*) ValidBuffer
)));
1215 UpdatingPtrTrack
->InDeletedTransitionPtr
= NULL
;
1217 CurrPtr
+= NewVariableSize
;
1223 // If volatile variable store, just copy valid buffer.
1225 SetMem ((UINT8
*) (UINTN
) VariableBase
, VariableStoreHeader
->Size
, 0xff);
1226 CopyMem ((UINT8
*) (UINTN
) VariableBase
, ValidBuffer
, (UINTN
) (CurrPtr
- ValidBuffer
));
1227 *LastVariableOffset
= (UINTN
) (CurrPtr
- ValidBuffer
);
1228 Status
= EFI_SUCCESS
;
1231 // If non-volatile variable store, perform FTW here.
1233 Status
= FtwVariableSpace (
1235 (VARIABLE_STORE_HEADER
*) ValidBuffer
1237 if (!EFI_ERROR (Status
)) {
1238 *LastVariableOffset
= (UINTN
) (CurrPtr
- ValidBuffer
);
1239 mVariableModuleGlobal
->HwErrVariableTotalSize
= HwErrVariableTotalSize
;
1240 mVariableModuleGlobal
->CommonVariableTotalSize
= CommonVariableTotalSize
;
1241 mVariableModuleGlobal
->CommonUserVariableTotalSize
= CommonUserVariableTotalSize
;
1243 Variable
= GetStartPointer ((VARIABLE_STORE_HEADER
*)(UINTN
)VariableBase
);
1244 while (IsValidVariableHeader (Variable
, GetEndPointer ((VARIABLE_STORE_HEADER
*)(UINTN
)VariableBase
))) {
1245 NextVariable
= GetNextVariablePtr (Variable
);
1246 VariableSize
= (UINTN
) NextVariable
- (UINTN
) Variable
;
1247 if ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
1248 mVariableModuleGlobal
->HwErrVariableTotalSize
+= VariableSize
;
1249 } else if ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) != EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
1250 mVariableModuleGlobal
->CommonVariableTotalSize
+= VariableSize
;
1251 if (IsUserVariable (Variable
)) {
1252 mVariableModuleGlobal
->CommonUserVariableTotalSize
+= VariableSize
;
1256 Variable
= NextVariable
;
1258 *LastVariableOffset
= (UINTN
) Variable
- (UINTN
) VariableBase
;
1264 FreePool (ValidBuffer
);
1267 // For NV variable reclaim, we use mNvVariableCache as the buffer, so copy the data back.
1269 CopyMem (mNvVariableCache
, (UINT8
*)(UINTN
)VariableBase
, VariableStoreHeader
->Size
);
1271 if (NewPubKeyStore
!= NULL
) {
1272 FreePool (NewPubKeyStore
);
1275 if (NewPubKeyIndex
!= NULL
) {
1276 FreePool (NewPubKeyIndex
);
1284 Find the variable in the specified variable store.
1286 @param[in] VariableName Name of the variable to be found
1287 @param[in] VendorGuid Vendor GUID to be found.
1288 @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
1289 check at runtime when searching variable.
1290 @param[in, out] PtrTrack Variable Track Pointer structure that contains Variable Information.
1292 @retval EFI_SUCCESS Variable found successfully
1293 @retval EFI_NOT_FOUND Variable not found
1297 IN CHAR16
*VariableName
,
1298 IN EFI_GUID
*VendorGuid
,
1299 IN BOOLEAN IgnoreRtCheck
,
1300 IN OUT VARIABLE_POINTER_TRACK
*PtrTrack
1303 VARIABLE_HEADER
*InDeletedVariable
;
1306 PtrTrack
->InDeletedTransitionPtr
= NULL
;
1309 // Find the variable by walk through HOB, volatile and non-volatile variable store.
1311 InDeletedVariable
= NULL
;
1313 for ( PtrTrack
->CurrPtr
= PtrTrack
->StartPtr
1314 ; IsValidVariableHeader (PtrTrack
->CurrPtr
, PtrTrack
->EndPtr
)
1315 ; PtrTrack
->CurrPtr
= GetNextVariablePtr (PtrTrack
->CurrPtr
)
1317 if (PtrTrack
->CurrPtr
->State
== VAR_ADDED
||
1318 PtrTrack
->CurrPtr
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)
1320 if (IgnoreRtCheck
|| !AtRuntime () || ((PtrTrack
->CurrPtr
->Attributes
& EFI_VARIABLE_RUNTIME_ACCESS
) != 0)) {
1321 if (VariableName
[0] == 0) {
1322 if (PtrTrack
->CurrPtr
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)) {
1323 InDeletedVariable
= PtrTrack
->CurrPtr
;
1325 PtrTrack
->InDeletedTransitionPtr
= InDeletedVariable
;
1329 if (CompareGuid (VendorGuid
, &PtrTrack
->CurrPtr
->VendorGuid
)) {
1330 Point
= (VOID
*) GetVariableNamePtr (PtrTrack
->CurrPtr
);
1332 ASSERT (NameSizeOfVariable (PtrTrack
->CurrPtr
) != 0);
1333 if (CompareMem (VariableName
, Point
, NameSizeOfVariable (PtrTrack
->CurrPtr
)) == 0) {
1334 if (PtrTrack
->CurrPtr
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)) {
1335 InDeletedVariable
= PtrTrack
->CurrPtr
;
1337 PtrTrack
->InDeletedTransitionPtr
= InDeletedVariable
;
1347 PtrTrack
->CurrPtr
= InDeletedVariable
;
1348 return (PtrTrack
->CurrPtr
== NULL
) ? EFI_NOT_FOUND
: EFI_SUCCESS
;
1353 Finds variable in storage blocks of volatile and non-volatile storage areas.
1355 This code finds variable in storage blocks of volatile and non-volatile storage areas.
1356 If VariableName is an empty string, then we just return the first
1357 qualified variable without comparing VariableName and VendorGuid.
1358 If IgnoreRtCheck is TRUE, then we ignore the EFI_VARIABLE_RUNTIME_ACCESS attribute check
1359 at runtime when searching existing variable, only VariableName and VendorGuid are compared.
1360 Otherwise, variables without EFI_VARIABLE_RUNTIME_ACCESS are not visible at runtime.
1362 @param[in] VariableName Name of the variable to be found.
1363 @param[in] VendorGuid Vendor GUID to be found.
1364 @param[out] PtrTrack VARIABLE_POINTER_TRACK structure for output,
1365 including the range searched and the target position.
1366 @param[in] Global Pointer to VARIABLE_GLOBAL structure, including
1367 base of volatile variable storage area, base of
1368 NV variable storage area, and a lock.
1369 @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
1370 check at runtime when searching variable.
1372 @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while
1374 @retval EFI_SUCCESS Variable successfully found.
1375 @retval EFI_NOT_FOUND Variable not found
1380 IN CHAR16
*VariableName
,
1381 IN EFI_GUID
*VendorGuid
,
1382 OUT VARIABLE_POINTER_TRACK
*PtrTrack
,
1383 IN VARIABLE_GLOBAL
*Global
,
1384 IN BOOLEAN IgnoreRtCheck
1388 VARIABLE_STORE_HEADER
*VariableStoreHeader
[VariableStoreTypeMax
];
1389 VARIABLE_STORE_TYPE Type
;
1391 if (VariableName
[0] != 0 && VendorGuid
== NULL
) {
1392 return EFI_INVALID_PARAMETER
;
1396 // 0: Volatile, 1: HOB, 2: Non-Volatile.
1397 // The index and attributes mapping must be kept in this order as RuntimeServiceGetNextVariableName
1398 // make use of this mapping to implement search algorithm.
1400 VariableStoreHeader
[VariableStoreTypeVolatile
] = (VARIABLE_STORE_HEADER
*) (UINTN
) Global
->VolatileVariableBase
;
1401 VariableStoreHeader
[VariableStoreTypeHob
] = (VARIABLE_STORE_HEADER
*) (UINTN
) Global
->HobVariableBase
;
1402 VariableStoreHeader
[VariableStoreTypeNv
] = mNvVariableCache
;
1405 // Find the variable by walk through HOB, volatile and non-volatile variable store.
1407 for (Type
= (VARIABLE_STORE_TYPE
) 0; Type
< VariableStoreTypeMax
; Type
++) {
1408 if (VariableStoreHeader
[Type
] == NULL
) {
1412 PtrTrack
->StartPtr
= GetStartPointer (VariableStoreHeader
[Type
]);
1413 PtrTrack
->EndPtr
= GetEndPointer (VariableStoreHeader
[Type
]);
1414 PtrTrack
->Volatile
= (BOOLEAN
) (Type
== VariableStoreTypeVolatile
);
1416 Status
= FindVariableEx (VariableName
, VendorGuid
, IgnoreRtCheck
, PtrTrack
);
1417 if (!EFI_ERROR (Status
)) {
1421 return EFI_NOT_FOUND
;
1425 Get index from supported language codes according to language string.
1427 This code is used to get corresponding index in supported language codes. It can handle
1428 RFC4646 and ISO639 language tags.
1429 In ISO639 language tags, take 3-characters as a delimitation to find matched string and calculate the index.
1430 In RFC4646 language tags, take semicolon as a delimitation to find matched string and calculate the index.
1433 SupportedLang = "engfraengfra"
1435 Iso639Language = TRUE
1436 The return value is "0".
1438 SupportedLang = "en;fr;en-US;fr-FR"
1440 Iso639Language = FALSE
1441 The return value is "3".
1443 @param SupportedLang Platform supported language codes.
1444 @param Lang Configured language.
1445 @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
1447 @retval The index of language in the language codes.
1451 GetIndexFromSupportedLangCodes(
1452 IN CHAR8
*SupportedLang
,
1454 IN BOOLEAN Iso639Language
1458 UINTN CompareLength
;
1459 UINTN LanguageLength
;
1461 if (Iso639Language
) {
1462 CompareLength
= ISO_639_2_ENTRY_SIZE
;
1463 for (Index
= 0; Index
< AsciiStrLen (SupportedLang
); Index
+= CompareLength
) {
1464 if (AsciiStrnCmp (Lang
, SupportedLang
+ Index
, CompareLength
) == 0) {
1466 // Successfully find the index of Lang string in SupportedLang string.
1468 Index
= Index
/ CompareLength
;
1476 // Compare RFC4646 language code
1479 for (LanguageLength
= 0; Lang
[LanguageLength
] != '\0'; LanguageLength
++);
1481 for (Index
= 0; *SupportedLang
!= '\0'; Index
++, SupportedLang
+= CompareLength
) {
1483 // Skip ';' characters in SupportedLang
1485 for (; *SupportedLang
!= '\0' && *SupportedLang
== ';'; SupportedLang
++);
1487 // Determine the length of the next language code in SupportedLang
1489 for (CompareLength
= 0; SupportedLang
[CompareLength
] != '\0' && SupportedLang
[CompareLength
] != ';'; CompareLength
++);
1491 if ((CompareLength
== LanguageLength
) &&
1492 (AsciiStrnCmp (Lang
, SupportedLang
, CompareLength
) == 0)) {
1494 // Successfully find the index of Lang string in SupportedLang string.
1505 Get language string from supported language codes according to index.
1507 This code is used to get corresponding language strings in supported language codes. It can handle
1508 RFC4646 and ISO639 language tags.
1509 In ISO639 language tags, take 3-characters as a delimitation. Find language string according to the index.
1510 In RFC4646 language tags, take semicolon as a delimitation. Find language string according to the index.
1513 SupportedLang = "engfraengfra"
1515 Iso639Language = TRUE
1516 The return value is "fra".
1518 SupportedLang = "en;fr;en-US;fr-FR"
1520 Iso639Language = FALSE
1521 The return value is "fr".
1523 @param SupportedLang Platform supported language codes.
1524 @param Index The index in supported language codes.
1525 @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
1527 @retval The language string in the language codes.
1531 GetLangFromSupportedLangCodes (
1532 IN CHAR8
*SupportedLang
,
1534 IN BOOLEAN Iso639Language
1538 UINTN CompareLength
;
1542 Supported
= SupportedLang
;
1543 if (Iso639Language
) {
1545 // According to the index of Lang string in SupportedLang string to get the language.
1546 // This code will be invoked in RUNTIME, therefore there is not a memory allocate/free operation.
1547 // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.
1549 CompareLength
= ISO_639_2_ENTRY_SIZE
;
1550 mVariableModuleGlobal
->Lang
[CompareLength
] = '\0';
1551 return CopyMem (mVariableModuleGlobal
->Lang
, SupportedLang
+ Index
* CompareLength
, CompareLength
);
1556 // Take semicolon as delimitation, sequentially traverse supported language codes.
1558 for (CompareLength
= 0; *Supported
!= ';' && *Supported
!= '\0'; CompareLength
++) {
1561 if ((*Supported
== '\0') && (SubIndex
!= Index
)) {
1563 // Have completed the traverse, but not find corrsponding string.
1564 // This case is not allowed to happen.
1569 if (SubIndex
== Index
) {
1571 // According to the index of Lang string in SupportedLang string to get the language.
1572 // As this code will be invoked in RUNTIME, therefore there is not memory allocate/free operation.
1573 // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.
1575 mVariableModuleGlobal
->PlatformLang
[CompareLength
] = '\0';
1576 return CopyMem (mVariableModuleGlobal
->PlatformLang
, Supported
- CompareLength
, CompareLength
);
1581 // Skip ';' characters in Supported
1583 for (; *Supported
!= '\0' && *Supported
== ';'; Supported
++);
1589 Returns a pointer to an allocated buffer that contains the best matching language
1590 from a set of supported languages.
1592 This function supports both ISO 639-2 and RFC 4646 language codes, but language
1593 code types may not be mixed in a single call to this function. This function
1594 supports a variable argument list that allows the caller to pass in a prioritized
1595 list of language codes to test against all the language codes in SupportedLanguages.
1597 If SupportedLanguages is NULL, then ASSERT().
1599 @param[in] SupportedLanguages A pointer to a Null-terminated ASCII string that
1600 contains a set of language codes in the format
1601 specified by Iso639Language.
1602 @param[in] Iso639Language If TRUE, then all language codes are assumed to be
1603 in ISO 639-2 format. If FALSE, then all language
1604 codes are assumed to be in RFC 4646 language format
1605 @param[in] ... A variable argument list that contains pointers to
1606 Null-terminated ASCII strings that contain one or more
1607 language codes in the format specified by Iso639Language.
1608 The first language code from each of these language
1609 code lists is used to determine if it is an exact or
1610 close match to any of the language codes in
1611 SupportedLanguages. Close matches only apply to RFC 4646
1612 language codes, and the matching algorithm from RFC 4647
1613 is used to determine if a close match is present. If
1614 an exact or close match is found, then the matching
1615 language code from SupportedLanguages is returned. If
1616 no matches are found, then the next variable argument
1617 parameter is evaluated. The variable argument list
1618 is terminated by a NULL.
1620 @retval NULL The best matching language could not be found in SupportedLanguages.
1621 @retval NULL There are not enough resources available to return the best matching
1623 @retval Other A pointer to a Null-terminated ASCII string that is the best matching
1624 language in SupportedLanguages.
1629 VariableGetBestLanguage (
1630 IN CONST CHAR8
*SupportedLanguages
,
1631 IN BOOLEAN Iso639Language
,
1637 UINTN CompareLength
;
1638 UINTN LanguageLength
;
1639 CONST CHAR8
*Supported
;
1642 if (SupportedLanguages
== NULL
) {
1646 VA_START (Args
, Iso639Language
);
1647 while ((Language
= VA_ARG (Args
, CHAR8
*)) != NULL
) {
1649 // Default to ISO 639-2 mode
1652 LanguageLength
= MIN (3, AsciiStrLen (Language
));
1655 // If in RFC 4646 mode, then determine the length of the first RFC 4646 language code in Language
1657 if (!Iso639Language
) {
1658 for (LanguageLength
= 0; Language
[LanguageLength
] != 0 && Language
[LanguageLength
] != ';'; LanguageLength
++);
1662 // Trim back the length of Language used until it is empty
1664 while (LanguageLength
> 0) {
1666 // Loop through all language codes in SupportedLanguages
1668 for (Supported
= SupportedLanguages
; *Supported
!= '\0'; Supported
+= CompareLength
) {
1670 // In RFC 4646 mode, then Loop through all language codes in SupportedLanguages
1672 if (!Iso639Language
) {
1674 // Skip ';' characters in Supported
1676 for (; *Supported
!= '\0' && *Supported
== ';'; Supported
++);
1678 // Determine the length of the next language code in Supported
1680 for (CompareLength
= 0; Supported
[CompareLength
] != 0 && Supported
[CompareLength
] != ';'; CompareLength
++);
1682 // If Language is longer than the Supported, then skip to the next language
1684 if (LanguageLength
> CompareLength
) {
1689 // See if the first LanguageLength characters in Supported match Language
1691 if (AsciiStrnCmp (Supported
, Language
, LanguageLength
) == 0) {
1694 Buffer
= Iso639Language
? mVariableModuleGlobal
->Lang
: mVariableModuleGlobal
->PlatformLang
;
1695 Buffer
[CompareLength
] = '\0';
1696 return CopyMem (Buffer
, Supported
, CompareLength
);
1700 if (Iso639Language
) {
1702 // If ISO 639 mode, then each language can only be tested once
1707 // If RFC 4646 mode, then trim Language from the right to the next '-' character
1709 for (LanguageLength
--; LanguageLength
> 0 && Language
[LanguageLength
] != '-'; LanguageLength
--);
1716 // No matches were found
1722 This function is to check if the remaining variable space is enough to set
1723 all Variables from argument list successfully. The purpose of the check
1724 is to keep the consistency of the Variables to be in variable storage.
1726 Note: Variables are assumed to be in same storage.
1727 The set sequence of Variables will be same with the sequence of VariableEntry from argument list,
1728 so follow the argument sequence to check the Variables.
1730 @param[in] Attributes Variable attributes for Variable entries.
1731 @param ... The variable argument list with type VARIABLE_ENTRY_CONSISTENCY *.
1732 A NULL terminates the list. The VariableSize of
1733 VARIABLE_ENTRY_CONSISTENCY is the variable data size as input.
1734 It will be changed to variable total size as output.
1736 @retval TRUE Have enough variable space to set the Variables successfully.
1737 @retval FALSE No enough variable space to set the Variables successfully.
1742 CheckRemainingSpaceForConsistency (
1743 IN UINT32 Attributes
,
1749 VARIABLE_ENTRY_CONSISTENCY
*VariableEntry
;
1750 UINT64 MaximumVariableStorageSize
;
1751 UINT64 RemainingVariableStorageSize
;
1752 UINT64 MaximumVariableSize
;
1753 UINTN TotalNeededSize
;
1754 UINTN OriginalVarSize
;
1755 VARIABLE_STORE_HEADER
*VariableStoreHeader
;
1756 VARIABLE_POINTER_TRACK VariablePtrTrack
;
1757 VARIABLE_HEADER
*NextVariable
;
1762 // Non-Volatile related.
1764 VariableStoreHeader
= mNvVariableCache
;
1766 Status
= VariableServiceQueryVariableInfoInternal (
1768 &MaximumVariableStorageSize
,
1769 &RemainingVariableStorageSize
,
1770 &MaximumVariableSize
1772 ASSERT_EFI_ERROR (Status
);
1774 TotalNeededSize
= 0;
1775 VA_START (Args
, Attributes
);
1776 VariableEntry
= VA_ARG (Args
, VARIABLE_ENTRY_CONSISTENCY
*);
1777 while (VariableEntry
!= NULL
) {
1779 // Calculate variable total size.
1781 VarNameSize
= StrSize (VariableEntry
->Name
);
1782 VarNameSize
+= GET_PAD_SIZE (VarNameSize
);
1783 VarDataSize
= VariableEntry
->VariableSize
;
1784 VarDataSize
+= GET_PAD_SIZE (VarDataSize
);
1785 VariableEntry
->VariableSize
= HEADER_ALIGN (sizeof (VARIABLE_HEADER
) + VarNameSize
+ VarDataSize
);
1787 TotalNeededSize
+= VariableEntry
->VariableSize
;
1788 VariableEntry
= VA_ARG (Args
, VARIABLE_ENTRY_CONSISTENCY
*);
1792 if (RemainingVariableStorageSize
>= TotalNeededSize
) {
1794 // Already have enough space.
1797 } else if (AtRuntime ()) {
1799 // At runtime, no reclaim.
1800 // The original variable space of Variables can't be reused.
1805 VA_START (Args
, Attributes
);
1806 VariableEntry
= VA_ARG (Args
, VARIABLE_ENTRY_CONSISTENCY
*);
1807 while (VariableEntry
!= NULL
) {
1809 // Check if Variable[Index] has been present and get its size.
1811 OriginalVarSize
= 0;
1812 VariablePtrTrack
.StartPtr
= GetStartPointer (VariableStoreHeader
);
1813 VariablePtrTrack
.EndPtr
= GetEndPointer (VariableStoreHeader
);
1814 Status
= FindVariableEx (
1815 VariableEntry
->Name
,
1816 VariableEntry
->Guid
,
1820 if (!EFI_ERROR (Status
)) {
1822 // Get size of Variable[Index].
1824 NextVariable
= GetNextVariablePtr (VariablePtrTrack
.CurrPtr
);
1825 OriginalVarSize
= (UINTN
) NextVariable
- (UINTN
) VariablePtrTrack
.CurrPtr
;
1827 // Add the original size of Variable[Index] to remaining variable storage size.
1829 RemainingVariableStorageSize
+= OriginalVarSize
;
1831 if (VariableEntry
->VariableSize
> RemainingVariableStorageSize
) {
1833 // No enough space for Variable[Index].
1839 // Sub the (new) size of Variable[Index] from remaining variable storage size.
1841 RemainingVariableStorageSize
-= VariableEntry
->VariableSize
;
1842 VariableEntry
= VA_ARG (Args
, VARIABLE_ENTRY_CONSISTENCY
*);
1850 Hook the operations in PlatformLangCodes, LangCodes, PlatformLang and Lang.
1852 When setting Lang/LangCodes, simultaneously update PlatformLang/PlatformLangCodes.
1854 According to UEFI spec, PlatformLangCodes/LangCodes are only set once in firmware initialization,
1855 and are read-only. Therefore, in variable driver, only store the original value for other use.
1857 @param[in] VariableName Name of variable.
1859 @param[in] Data Variable data.
1861 @param[in] DataSize Size of data. 0 means delete.
1863 @retval EFI_SUCCESS The update operation is successful or ignored.
1864 @retval EFI_WRITE_PROTECTED Update PlatformLangCodes/LangCodes at runtime.
1865 @retval EFI_OUT_OF_RESOURCES No enough variable space to do the update operation.
1866 @retval Others Other errors happened during the update operation.
1870 AutoUpdateLangVariable (
1871 IN CHAR16
*VariableName
,
1877 CHAR8
*BestPlatformLang
;
1881 VARIABLE_POINTER_TRACK Variable
;
1882 BOOLEAN SetLanguageCodes
;
1883 VARIABLE_ENTRY_CONSISTENCY VariableEntry
[2];
1886 // Don't do updates for delete operation
1888 if (DataSize
== 0) {
1892 SetLanguageCodes
= FALSE
;
1894 if (StrCmp (VariableName
, EFI_PLATFORM_LANG_CODES_VARIABLE_NAME
) == 0) {
1896 // PlatformLangCodes is a volatile variable, so it can not be updated at runtime.
1899 return EFI_WRITE_PROTECTED
;
1902 SetLanguageCodes
= TRUE
;
1905 // According to UEFI spec, PlatformLangCodes is only set once in firmware initialization, and is read-only
1906 // Therefore, in variable driver, only store the original value for other use.
1908 if (mVariableModuleGlobal
->PlatformLangCodes
!= NULL
) {
1909 FreePool (mVariableModuleGlobal
->PlatformLangCodes
);
1911 mVariableModuleGlobal
->PlatformLangCodes
= AllocateRuntimeCopyPool (DataSize
, Data
);
1912 ASSERT (mVariableModuleGlobal
->PlatformLangCodes
!= NULL
);
1915 // PlatformLang holds a single language from PlatformLangCodes,
1916 // so the size of PlatformLangCodes is enough for the PlatformLang.
1918 if (mVariableModuleGlobal
->PlatformLang
!= NULL
) {
1919 FreePool (mVariableModuleGlobal
->PlatformLang
);
1921 mVariableModuleGlobal
->PlatformLang
= AllocateRuntimePool (DataSize
);
1922 ASSERT (mVariableModuleGlobal
->PlatformLang
!= NULL
);
1924 } else if (StrCmp (VariableName
, EFI_LANG_CODES_VARIABLE_NAME
) == 0) {
1926 // LangCodes is a volatile variable, so it can not be updated at runtime.
1929 return EFI_WRITE_PROTECTED
;
1932 SetLanguageCodes
= TRUE
;
1935 // According to UEFI spec, LangCodes is only set once in firmware initialization, and is read-only
1936 // Therefore, in variable driver, only store the original value for other use.
1938 if (mVariableModuleGlobal
->LangCodes
!= NULL
) {
1939 FreePool (mVariableModuleGlobal
->LangCodes
);
1941 mVariableModuleGlobal
->LangCodes
= AllocateRuntimeCopyPool (DataSize
, Data
);
1942 ASSERT (mVariableModuleGlobal
->LangCodes
!= NULL
);
1945 if (SetLanguageCodes
1946 && (mVariableModuleGlobal
->PlatformLangCodes
!= NULL
)
1947 && (mVariableModuleGlobal
->LangCodes
!= NULL
)) {
1949 // Update Lang if PlatformLang is already set
1950 // Update PlatformLang if Lang is already set
1952 Status
= FindVariable (EFI_PLATFORM_LANG_VARIABLE_NAME
, &gEfiGlobalVariableGuid
, &Variable
, &mVariableModuleGlobal
->VariableGlobal
, FALSE
);
1953 if (!EFI_ERROR (Status
)) {
1957 VariableName
= EFI_PLATFORM_LANG_VARIABLE_NAME
;
1958 Data
= GetVariableDataPtr (Variable
.CurrPtr
);
1959 DataSize
= Variable
.CurrPtr
->DataSize
;
1961 Status
= FindVariable (EFI_LANG_VARIABLE_NAME
, &gEfiGlobalVariableGuid
, &Variable
, &mVariableModuleGlobal
->VariableGlobal
, FALSE
);
1962 if (!EFI_ERROR (Status
)) {
1964 // Update PlatformLang
1966 VariableName
= EFI_LANG_VARIABLE_NAME
;
1967 Data
= GetVariableDataPtr (Variable
.CurrPtr
);
1968 DataSize
= Variable
.CurrPtr
->DataSize
;
1971 // Neither PlatformLang nor Lang is set, directly return
1978 Status
= EFI_SUCCESS
;
1981 // According to UEFI spec, "Lang" and "PlatformLang" is NV|BS|RT attributions.
1983 Attributes
= EFI_VARIABLE_NON_VOLATILE
| EFI_VARIABLE_BOOTSERVICE_ACCESS
| EFI_VARIABLE_RUNTIME_ACCESS
;
1985 if (StrCmp (VariableName
, EFI_PLATFORM_LANG_VARIABLE_NAME
) == 0) {
1987 // Update Lang when PlatformLangCodes/LangCodes were set.
1989 if ((mVariableModuleGlobal
->PlatformLangCodes
!= NULL
) && (mVariableModuleGlobal
->LangCodes
!= NULL
)) {
1991 // When setting PlatformLang, firstly get most matched language string from supported language codes.
1993 BestPlatformLang
= VariableGetBestLanguage (mVariableModuleGlobal
->PlatformLangCodes
, FALSE
, Data
, NULL
);
1994 if (BestPlatformLang
!= NULL
) {
1996 // Get the corresponding index in language codes.
1998 Index
= GetIndexFromSupportedLangCodes (mVariableModuleGlobal
->PlatformLangCodes
, BestPlatformLang
, FALSE
);
2001 // Get the corresponding ISO639 language tag according to RFC4646 language tag.
2003 BestLang
= GetLangFromSupportedLangCodes (mVariableModuleGlobal
->LangCodes
, Index
, TRUE
);
2006 // Check the variable space for both Lang and PlatformLang variable.
2008 VariableEntry
[0].VariableSize
= ISO_639_2_ENTRY_SIZE
+ 1;
2009 VariableEntry
[0].Guid
= &gEfiGlobalVariableGuid
;
2010 VariableEntry
[0].Name
= EFI_LANG_VARIABLE_NAME
;
2012 VariableEntry
[1].VariableSize
= AsciiStrSize (BestPlatformLang
);
2013 VariableEntry
[1].Guid
= &gEfiGlobalVariableGuid
;
2014 VariableEntry
[1].Name
= EFI_PLATFORM_LANG_VARIABLE_NAME
;
2015 if (!CheckRemainingSpaceForConsistency (VARIABLE_ATTRIBUTE_NV_BS_RT
, &VariableEntry
[0], &VariableEntry
[1], NULL
)) {
2017 // No enough variable space to set both Lang and PlatformLang successfully.
2019 Status
= EFI_OUT_OF_RESOURCES
;
2022 // Successfully convert PlatformLang to Lang, and set the BestLang value into Lang variable simultaneously.
2024 FindVariable (EFI_LANG_VARIABLE_NAME
, &gEfiGlobalVariableGuid
, &Variable
, &mVariableModuleGlobal
->VariableGlobal
, FALSE
);
2026 Status
= UpdateVariable (EFI_LANG_VARIABLE_NAME
, &gEfiGlobalVariableGuid
, BestLang
,
2027 ISO_639_2_ENTRY_SIZE
+ 1, Attributes
, 0, 0, &Variable
, NULL
);
2030 DEBUG ((EFI_D_INFO
, "Variable Driver Auto Update PlatformLang, PlatformLang:%a, Lang:%a Status: %r\n", BestPlatformLang
, BestLang
, Status
));
2034 } else if (StrCmp (VariableName
, EFI_LANG_VARIABLE_NAME
) == 0) {
2036 // Update PlatformLang when PlatformLangCodes/LangCodes were set.
2038 if ((mVariableModuleGlobal
->PlatformLangCodes
!= NULL
) && (mVariableModuleGlobal
->LangCodes
!= NULL
)) {
2040 // When setting Lang, firstly get most matched language string from supported language codes.
2042 BestLang
= VariableGetBestLanguage (mVariableModuleGlobal
->LangCodes
, TRUE
, Data
, NULL
);
2043 if (BestLang
!= NULL
) {
2045 // Get the corresponding index in language codes.
2047 Index
= GetIndexFromSupportedLangCodes (mVariableModuleGlobal
->LangCodes
, BestLang
, TRUE
);
2050 // Get the corresponding RFC4646 language tag according to ISO639 language tag.
2052 BestPlatformLang
= GetLangFromSupportedLangCodes (mVariableModuleGlobal
->PlatformLangCodes
, Index
, FALSE
);
2055 // Check the variable space for both PlatformLang and Lang variable.
2057 VariableEntry
[0].VariableSize
= AsciiStrSize (BestPlatformLang
);
2058 VariableEntry
[0].Guid
= &gEfiGlobalVariableGuid
;
2059 VariableEntry
[0].Name
= EFI_PLATFORM_LANG_VARIABLE_NAME
;
2061 VariableEntry
[1].VariableSize
= ISO_639_2_ENTRY_SIZE
+ 1;
2062 VariableEntry
[1].Guid
= &gEfiGlobalVariableGuid
;
2063 VariableEntry
[1].Name
= EFI_LANG_VARIABLE_NAME
;
2064 if (!CheckRemainingSpaceForConsistency (VARIABLE_ATTRIBUTE_NV_BS_RT
, &VariableEntry
[0], &VariableEntry
[1], NULL
)) {
2066 // No enough variable space to set both PlatformLang and Lang successfully.
2068 Status
= EFI_OUT_OF_RESOURCES
;
2071 // Successfully convert Lang to PlatformLang, and set the BestPlatformLang value into PlatformLang variable simultaneously.
2073 FindVariable (EFI_PLATFORM_LANG_VARIABLE_NAME
, &gEfiGlobalVariableGuid
, &Variable
, &mVariableModuleGlobal
->VariableGlobal
, FALSE
);
2075 Status
= UpdateVariable (EFI_PLATFORM_LANG_VARIABLE_NAME
, &gEfiGlobalVariableGuid
, BestPlatformLang
,
2076 AsciiStrSize (BestPlatformLang
), Attributes
, 0, 0, &Variable
, NULL
);
2079 DEBUG ((EFI_D_INFO
, "Variable Driver Auto Update Lang, Lang:%a, PlatformLang:%a Status: %r\n", BestLang
, BestPlatformLang
, Status
));
2084 if (SetLanguageCodes
) {
2086 // Continue to set PlatformLangCodes or LangCodes.
2095 Update the variable region with Variable information. If EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is set,
2096 index of associated public key is needed.
2098 @param[in] VariableName Name of variable.
2099 @param[in] VendorGuid Guid of variable.
2100 @param[in] Data Variable data.
2101 @param[in] DataSize Size of data. 0 means delete.
2102 @param[in] Attributes Attributes of the variable.
2103 @param[in] KeyIndex Index of associated public key.
2104 @param[in] MonotonicCount Value of associated monotonic count.
2105 @param[in, out] CacheVariable The variable information which is used to keep track of variable usage.
2106 @param[in] TimeStamp Value of associated TimeStamp.
2108 @retval EFI_SUCCESS The update operation is success.
2109 @retval EFI_OUT_OF_RESOURCES Variable region is full, can not write other data into this region.
2114 IN CHAR16
*VariableName
,
2115 IN EFI_GUID
*VendorGuid
,
2118 IN UINT32 Attributes OPTIONAL
,
2119 IN UINT32 KeyIndex OPTIONAL
,
2120 IN UINT64 MonotonicCount OPTIONAL
,
2121 IN OUT VARIABLE_POINTER_TRACK
*CacheVariable
,
2122 IN EFI_TIME
*TimeStamp OPTIONAL
2126 VARIABLE_HEADER
*NextVariable
;
2129 UINTN VarNameOffset
;
2130 UINTN VarDataOffset
;
2134 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL
*Fvb
;
2136 VARIABLE_POINTER_TRACK
*Variable
;
2137 VARIABLE_POINTER_TRACK NvVariable
;
2138 VARIABLE_STORE_HEADER
*VariableStoreHeader
;
2140 UINT8
*BufferForMerge
;
2141 UINTN MergedBufSize
;
2144 BOOLEAN IsCommonVariable
;
2145 BOOLEAN IsCommonUserVariable
;
2147 if (mVariableModuleGlobal
->FvbInstance
== NULL
) {
2149 // The FVB protocol is not installed, so the EFI_VARIABLE_WRITE_ARCH_PROTOCOL is not installed.
2151 if ((Attributes
& EFI_VARIABLE_NON_VOLATILE
) != 0) {
2153 // Trying to update NV variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
2155 return EFI_NOT_AVAILABLE_YET
;
2156 } else if ((Attributes
& EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
) != 0) {
2158 // Trying to update volatile authenticated variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
2159 // The authenticated variable perhaps is not initialized, just return here.
2161 return EFI_NOT_AVAILABLE_YET
;
2165 if ((CacheVariable
->CurrPtr
== NULL
) || CacheVariable
->Volatile
) {
2166 Variable
= CacheVariable
;
2169 // Update/Delete existing NV variable.
2170 // CacheVariable points to the variable in the memory copy of Flash area
2171 // Now let Variable points to the same variable in Flash area.
2173 VariableStoreHeader
= (VARIABLE_STORE_HEADER
*) ((UINTN
) mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
);
2174 Variable
= &NvVariable
;
2175 Variable
->StartPtr
= GetStartPointer (VariableStoreHeader
);
2176 Variable
->EndPtr
= GetEndPointer (VariableStoreHeader
);
2177 Variable
->CurrPtr
= (VARIABLE_HEADER
*)((UINTN
)Variable
->StartPtr
+ ((UINTN
)CacheVariable
->CurrPtr
- (UINTN
)CacheVariable
->StartPtr
));
2178 if (CacheVariable
->InDeletedTransitionPtr
!= NULL
) {
2179 Variable
->InDeletedTransitionPtr
= (VARIABLE_HEADER
*)((UINTN
)Variable
->StartPtr
+ ((UINTN
)CacheVariable
->InDeletedTransitionPtr
- (UINTN
)CacheVariable
->StartPtr
));
2181 Variable
->InDeletedTransitionPtr
= NULL
;
2183 Variable
->Volatile
= FALSE
;
2186 Fvb
= mVariableModuleGlobal
->FvbInstance
;
2189 // Tricky part: Use scratch data area at the end of volatile variable store
2190 // as a temporary storage.
2192 NextVariable
= GetEndPointer ((VARIABLE_STORE_HEADER
*) ((UINTN
) mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
));
2193 ScratchSize
= MAX (PcdGet32 (PcdMaxVariableSize
), PcdGet32 (PcdMaxHardwareErrorVariableSize
));
2194 SetMem (NextVariable
, ScratchSize
, 0xff);
2197 if (Variable
->CurrPtr
!= NULL
) {
2199 // Update/Delete existing variable.
2203 // If AtRuntime and the variable is Volatile and Runtime Access,
2204 // the volatile is ReadOnly, and SetVariable should be aborted and
2205 // return EFI_WRITE_PROTECTED.
2207 if (Variable
->Volatile
) {
2208 Status
= EFI_WRITE_PROTECTED
;
2212 // Only variable that have NV attributes can be updated/deleted in Runtime.
2214 if ((Variable
->CurrPtr
->Attributes
& EFI_VARIABLE_NON_VOLATILE
) == 0) {
2215 Status
= EFI_INVALID_PARAMETER
;
2220 // Only variable that have RT attributes can be updated/deleted in Runtime.
2222 if ((Variable
->CurrPtr
->Attributes
& EFI_VARIABLE_RUNTIME_ACCESS
) == 0) {
2223 Status
= EFI_INVALID_PARAMETER
;
2229 // Setting a data variable with no access, or zero DataSize attributes
2230 // causes it to be deleted.
2231 // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will
2232 // not delete the variable.
2234 if ((((Attributes
& EFI_VARIABLE_APPEND_WRITE
) == 0) && (DataSize
== 0))|| ((Attributes
& (EFI_VARIABLE_RUNTIME_ACCESS
| EFI_VARIABLE_BOOTSERVICE_ACCESS
)) == 0)) {
2235 if (Variable
->InDeletedTransitionPtr
!= NULL
) {
2237 // Both ADDED and IN_DELETED_TRANSITION variable are present,
2238 // set IN_DELETED_TRANSITION one to DELETED state first.
2240 State
= Variable
->InDeletedTransitionPtr
->State
;
2241 State
&= VAR_DELETED
;
2242 Status
= UpdateVariableStore (
2243 &mVariableModuleGlobal
->VariableGlobal
,
2247 (UINTN
) &Variable
->InDeletedTransitionPtr
->State
,
2251 if (!EFI_ERROR (Status
)) {
2252 if (!Variable
->Volatile
) {
2253 ASSERT (CacheVariable
->InDeletedTransitionPtr
!= NULL
);
2254 CacheVariable
->InDeletedTransitionPtr
->State
= State
;
2261 State
= Variable
->CurrPtr
->State
;
2262 State
&= VAR_DELETED
;
2264 Status
= UpdateVariableStore (
2265 &mVariableModuleGlobal
->VariableGlobal
,
2269 (UINTN
) &Variable
->CurrPtr
->State
,
2273 if (!EFI_ERROR (Status
)) {
2274 UpdateVariableInfo (VariableName
, VendorGuid
, Variable
->Volatile
, FALSE
, FALSE
, TRUE
, FALSE
);
2275 if (!Variable
->Volatile
) {
2276 CacheVariable
->CurrPtr
->State
= State
;
2277 FlushHobVariableToFlash (VariableName
, VendorGuid
);
2283 // If the variable is marked valid, and the same data has been passed in,
2284 // then return to the caller immediately.
2286 if (DataSizeOfVariable (Variable
->CurrPtr
) == DataSize
&&
2287 (CompareMem (Data
, GetVariableDataPtr (Variable
->CurrPtr
), DataSize
) == 0) &&
2288 ((Attributes
& EFI_VARIABLE_APPEND_WRITE
) == 0) &&
2289 (TimeStamp
== NULL
)) {
2291 // Variable content unchanged and no need to update timestamp, just return.
2293 UpdateVariableInfo (VariableName
, VendorGuid
, Variable
->Volatile
, FALSE
, TRUE
, FALSE
, FALSE
);
2294 Status
= EFI_SUCCESS
;
2296 } else if ((Variable
->CurrPtr
->State
== VAR_ADDED
) ||
2297 (Variable
->CurrPtr
->State
== (VAR_ADDED
& VAR_IN_DELETED_TRANSITION
))) {
2300 // EFI_VARIABLE_APPEND_WRITE attribute only effects for existing variable
2302 if ((Attributes
& EFI_VARIABLE_APPEND_WRITE
) != 0) {
2304 // NOTE: From 0 to DataOffset of NextVariable is reserved for Variable Header and Name.
2305 // From DataOffset of NextVariable is to save the existing variable data.
2307 DataOffset
= sizeof (VARIABLE_HEADER
) + Variable
->CurrPtr
->NameSize
+ GET_PAD_SIZE (Variable
->CurrPtr
->NameSize
);
2308 BufferForMerge
= (UINT8
*) ((UINTN
) NextVariable
+ DataOffset
);
2309 CopyMem (BufferForMerge
, (UINT8
*) ((UINTN
) Variable
->CurrPtr
+ DataOffset
), Variable
->CurrPtr
->DataSize
);
2312 // Set Max Common Variable Data Size as default MaxDataSize
2314 MaxDataSize
= PcdGet32 (PcdMaxVariableSize
) - DataOffset
;
2316 if ((CompareGuid (VendorGuid
, &gEfiImageSecurityDatabaseGuid
) &&
2317 ((StrCmp (VariableName
, EFI_IMAGE_SECURITY_DATABASE
) == 0) || (StrCmp (VariableName
, EFI_IMAGE_SECURITY_DATABASE1
) == 0) ||
2318 (StrCmp (VariableName
, EFI_IMAGE_SECURITY_DATABASE2
) == 0))) ||
2319 (CompareGuid (VendorGuid
, &gEfiGlobalVariableGuid
) && (StrCmp (VariableName
, EFI_KEY_EXCHANGE_KEY_NAME
) == 0))) {
2321 // For variables with formatted as EFI_SIGNATURE_LIST, the driver shall not perform an append of
2322 // EFI_SIGNATURE_DATA values that are already part of the existing variable value.
2324 Status
= AppendSignatureList (
2326 Variable
->CurrPtr
->DataSize
,
2327 MaxDataSize
- Variable
->CurrPtr
->DataSize
,
2332 if (Status
== EFI_BUFFER_TOO_SMALL
) {
2334 // Signature List is too long, Failed to Append.
2336 Status
= EFI_INVALID_PARAMETER
;
2340 if (MergedBufSize
== Variable
->CurrPtr
->DataSize
) {
2341 if ((TimeStamp
== NULL
) || CompareTimeStamp (TimeStamp
, &Variable
->CurrPtr
->TimeStamp
)) {
2343 // New EFI_SIGNATURE_DATA is not found and timestamp is not later
2344 // than current timestamp, return EFI_SUCCESS directly.
2346 UpdateVariableInfo (VariableName
, VendorGuid
, Variable
->Volatile
, FALSE
, TRUE
, FALSE
, FALSE
);
2347 Status
= EFI_SUCCESS
;
2353 // For other Variables, append the new data to the end of existing data.
2354 // Max Harware error record variable data size is different from common variable
2356 if ((Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
2357 MaxDataSize
= PcdGet32 (PcdMaxHardwareErrorVariableSize
) - DataOffset
;
2360 if (Variable
->CurrPtr
->DataSize
+ DataSize
> MaxDataSize
) {
2362 // Existing data size + new data size exceed maximum variable size limitation.
2364 Status
= EFI_INVALID_PARAMETER
;
2367 CopyMem ((UINT8
*) ((UINTN
) BufferForMerge
+ Variable
->CurrPtr
->DataSize
), Data
, DataSize
);
2368 MergedBufSize
= Variable
->CurrPtr
->DataSize
+ DataSize
;
2372 // BufferForMerge(from DataOffset of NextVariable) has included the merged existing and new data.
2374 Data
= BufferForMerge
;
2375 DataSize
= MergedBufSize
;
2380 // Mark the old variable as in delete transition.
2382 State
= Variable
->CurrPtr
->State
;
2383 State
&= VAR_IN_DELETED_TRANSITION
;
2385 Status
= UpdateVariableStore (
2386 &mVariableModuleGlobal
->VariableGlobal
,
2390 (UINTN
) &Variable
->CurrPtr
->State
,
2394 if (EFI_ERROR (Status
)) {
2397 if (!Variable
->Volatile
) {
2398 CacheVariable
->CurrPtr
->State
= State
;
2403 // Not found existing variable. Create a new variable.
2406 if ((DataSize
== 0) && ((Attributes
& EFI_VARIABLE_APPEND_WRITE
) != 0)) {
2407 Status
= EFI_SUCCESS
;
2412 // Make sure we are trying to create a new variable.
2413 // Setting a data variable with zero DataSize or no access attributes means to delete it.
2415 if (DataSize
== 0 || (Attributes
& (EFI_VARIABLE_RUNTIME_ACCESS
| EFI_VARIABLE_BOOTSERVICE_ACCESS
)) == 0) {
2416 Status
= EFI_NOT_FOUND
;
2421 // Only variable have NV|RT attribute can be created in Runtime.
2424 (((Attributes
& EFI_VARIABLE_RUNTIME_ACCESS
) == 0) || ((Attributes
& EFI_VARIABLE_NON_VOLATILE
) == 0))) {
2425 Status
= EFI_INVALID_PARAMETER
;
2431 // Function part - create a new variable and copy the data.
2432 // Both update a variable and create a variable will come here.
2434 NextVariable
->StartId
= VARIABLE_DATA
;
2436 // NextVariable->State = VAR_ADDED;
2438 NextVariable
->Reserved
= 0;
2439 NextVariable
->PubKeyIndex
= KeyIndex
;
2440 NextVariable
->MonotonicCount
= MonotonicCount
;
2441 ZeroMem (&NextVariable
->TimeStamp
, sizeof (EFI_TIME
));
2443 if (((Attributes
& EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
) != 0) &&
2444 (TimeStamp
!= NULL
)) {
2445 if ((Attributes
& EFI_VARIABLE_APPEND_WRITE
) == 0) {
2446 CopyMem (&NextVariable
->TimeStamp
, TimeStamp
, sizeof (EFI_TIME
));
2449 // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only
2450 // when the new TimeStamp value is later than the current timestamp associated
2451 // with the variable, we need associate the new timestamp with the updated value.
2453 if (Variable
->CurrPtr
!= NULL
) {
2454 if (CompareTimeStamp (&Variable
->CurrPtr
->TimeStamp
, TimeStamp
)) {
2455 CopyMem (&NextVariable
->TimeStamp
, TimeStamp
, sizeof (EFI_TIME
));
2462 // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned
2463 // Attributes bitmask parameter of a GetVariable() call.
2465 NextVariable
->Attributes
= Attributes
& (~EFI_VARIABLE_APPEND_WRITE
);
2467 VarNameOffset
= sizeof (VARIABLE_HEADER
);
2468 VarNameSize
= StrSize (VariableName
);
2470 (UINT8
*) ((UINTN
) NextVariable
+ VarNameOffset
),
2474 VarDataOffset
= VarNameOffset
+ VarNameSize
+ GET_PAD_SIZE (VarNameSize
);
2477 // If DataReady is TRUE, it means the variable data has been saved into
2478 // NextVariable during EFI_VARIABLE_APPEND_WRITE operation preparation.
2482 (UINT8
*) ((UINTN
) NextVariable
+ VarDataOffset
),
2488 CopyMem (&NextVariable
->VendorGuid
, VendorGuid
, sizeof (EFI_GUID
));
2490 // There will be pad bytes after Data, the NextVariable->NameSize and
2491 // NextVariable->DataSize should not include pad size so that variable
2492 // service can get actual size in GetVariable.
2494 NextVariable
->NameSize
= (UINT32
)VarNameSize
;
2495 NextVariable
->DataSize
= (UINT32
)DataSize
;
2498 // The actual size of the variable that stores in storage should
2499 // include pad size.
2501 VarSize
= VarDataOffset
+ DataSize
+ GET_PAD_SIZE (DataSize
);
2502 if ((Attributes
& EFI_VARIABLE_NON_VOLATILE
) != 0) {
2504 // Create a nonvolatile variable.
2508 IsCommonVariable
= FALSE
;
2509 IsCommonUserVariable
= FALSE
;
2510 if ((Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == 0) {
2511 IsCommonVariable
= TRUE
;
2512 IsCommonUserVariable
= IsUserVariable (NextVariable
);
2514 if ((((Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) != 0)
2515 && ((VarSize
+ mVariableModuleGlobal
->HwErrVariableTotalSize
) > PcdGet32 (PcdHwErrStorageSize
)))
2516 || (IsCommonVariable
&& ((VarSize
+ mVariableModuleGlobal
->CommonVariableTotalSize
) > mVariableModuleGlobal
->CommonVariableSpace
))
2517 || (IsCommonVariable
&& AtRuntime () && ((VarSize
+ mVariableModuleGlobal
->CommonVariableTotalSize
) > mVariableModuleGlobal
->CommonRuntimeVariableSpace
))
2518 || (IsCommonUserVariable
&& ((VarSize
+ mVariableModuleGlobal
->CommonUserVariableTotalSize
) > mVariableModuleGlobal
->CommonMaxUserVariableSpace
))) {
2520 if (IsCommonUserVariable
&& ((VarSize
+ mVariableModuleGlobal
->CommonUserVariableTotalSize
) > mVariableModuleGlobal
->CommonMaxUserVariableSpace
)) {
2521 RecordVarErrorFlag (VAR_ERROR_FLAG_USER_ERROR
, VariableName
, VendorGuid
, Attributes
, VarSize
);
2523 if (IsCommonVariable
&& ((VarSize
+ mVariableModuleGlobal
->CommonVariableTotalSize
) > mVariableModuleGlobal
->CommonRuntimeVariableSpace
)) {
2524 RecordVarErrorFlag (VAR_ERROR_FLAG_SYSTEM_ERROR
, VariableName
, VendorGuid
, Attributes
, VarSize
);
2526 Status
= EFI_OUT_OF_RESOURCES
;
2530 // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.
2533 mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
,
2534 &mVariableModuleGlobal
->NonVolatileLastVariableOffset
,
2538 HEADER_ALIGN (VarSize
),
2541 if (!EFI_ERROR (Status
)) {
2543 // The new variable has been integrated successfully during reclaiming.
2545 if (Variable
->CurrPtr
!= NULL
) {
2546 CacheVariable
->CurrPtr
= (VARIABLE_HEADER
*)((UINTN
) CacheVariable
->StartPtr
+ ((UINTN
) Variable
->CurrPtr
- (UINTN
) Variable
->StartPtr
));
2547 CacheVariable
->InDeletedTransitionPtr
= NULL
;
2549 UpdateVariableInfo (VariableName
, VendorGuid
, FALSE
, FALSE
, TRUE
, FALSE
, FALSE
);
2550 FlushHobVariableToFlash (VariableName
, VendorGuid
);
2552 if (IsCommonUserVariable
&& ((VarSize
+ mVariableModuleGlobal
->CommonUserVariableTotalSize
) > mVariableModuleGlobal
->CommonMaxUserVariableSpace
)) {
2553 RecordVarErrorFlag (VAR_ERROR_FLAG_USER_ERROR
, VariableName
, VendorGuid
, Attributes
, VarSize
);
2555 if (IsCommonVariable
&& ((VarSize
+ mVariableModuleGlobal
->CommonVariableTotalSize
) > mVariableModuleGlobal
->CommonVariableSpace
)) {
2556 RecordVarErrorFlag (VAR_ERROR_FLAG_SYSTEM_ERROR
, VariableName
, VendorGuid
, Attributes
, VarSize
);
2563 // 1. Write variable header
2564 // 2. Set variable state to header valid
2565 // 3. Write variable data
2566 // 4. Set variable state to valid
2571 CacheOffset
= mVariableModuleGlobal
->NonVolatileLastVariableOffset
;
2572 Status
= UpdateVariableStore (
2573 &mVariableModuleGlobal
->VariableGlobal
,
2577 mVariableModuleGlobal
->NonVolatileLastVariableOffset
,
2578 sizeof (VARIABLE_HEADER
),
2579 (UINT8
*) NextVariable
2582 if (EFI_ERROR (Status
)) {
2589 NextVariable
->State
= VAR_HEADER_VALID_ONLY
;
2590 Status
= UpdateVariableStore (
2591 &mVariableModuleGlobal
->VariableGlobal
,
2595 mVariableModuleGlobal
->NonVolatileLastVariableOffset
+ OFFSET_OF (VARIABLE_HEADER
, State
),
2597 &NextVariable
->State
2600 if (EFI_ERROR (Status
)) {
2606 Status
= UpdateVariableStore (
2607 &mVariableModuleGlobal
->VariableGlobal
,
2611 mVariableModuleGlobal
->NonVolatileLastVariableOffset
+ sizeof (VARIABLE_HEADER
),
2612 (UINT32
) VarSize
- sizeof (VARIABLE_HEADER
),
2613 (UINT8
*) NextVariable
+ sizeof (VARIABLE_HEADER
)
2616 if (EFI_ERROR (Status
)) {
2622 NextVariable
->State
= VAR_ADDED
;
2623 Status
= UpdateVariableStore (
2624 &mVariableModuleGlobal
->VariableGlobal
,
2628 mVariableModuleGlobal
->NonVolatileLastVariableOffset
+ OFFSET_OF (VARIABLE_HEADER
, State
),
2630 &NextVariable
->State
2633 if (EFI_ERROR (Status
)) {
2637 mVariableModuleGlobal
->NonVolatileLastVariableOffset
+= HEADER_ALIGN (VarSize
);
2639 if ((Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) != 0) {
2640 mVariableModuleGlobal
->HwErrVariableTotalSize
+= HEADER_ALIGN (VarSize
);
2642 mVariableModuleGlobal
->CommonVariableTotalSize
+= HEADER_ALIGN (VarSize
);
2643 if (IsCommonUserVariable
) {
2644 mVariableModuleGlobal
->CommonUserVariableTotalSize
+= HEADER_ALIGN (VarSize
);
2648 // update the memory copy of Flash region.
2650 CopyMem ((UINT8
*)mNvVariableCache
+ CacheOffset
, (UINT8
*)NextVariable
, VarSize
);
2653 // Create a volatile variable.
2657 if ((UINT32
) (VarSize
+ mVariableModuleGlobal
->VolatileLastVariableOffset
) >
2658 ((VARIABLE_STORE_HEADER
*) ((UINTN
) (mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
)))->Size
) {
2660 // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.
2663 mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
,
2664 &mVariableModuleGlobal
->VolatileLastVariableOffset
,
2668 HEADER_ALIGN (VarSize
),
2671 if (!EFI_ERROR (Status
)) {
2673 // The new variable has been integrated successfully during reclaiming.
2675 if (Variable
->CurrPtr
!= NULL
) {
2676 CacheVariable
->CurrPtr
= (VARIABLE_HEADER
*)((UINTN
) CacheVariable
->StartPtr
+ ((UINTN
) Variable
->CurrPtr
- (UINTN
) Variable
->StartPtr
));
2677 CacheVariable
->InDeletedTransitionPtr
= NULL
;
2679 UpdateVariableInfo (VariableName
, VendorGuid
, TRUE
, FALSE
, TRUE
, FALSE
, FALSE
);
2684 NextVariable
->State
= VAR_ADDED
;
2685 Status
= UpdateVariableStore (
2686 &mVariableModuleGlobal
->VariableGlobal
,
2690 mVariableModuleGlobal
->VolatileLastVariableOffset
,
2692 (UINT8
*) NextVariable
2695 if (EFI_ERROR (Status
)) {
2699 mVariableModuleGlobal
->VolatileLastVariableOffset
+= HEADER_ALIGN (VarSize
);
2703 // Mark the old variable as deleted.
2705 if (!EFI_ERROR (Status
) && Variable
->CurrPtr
!= NULL
) {
2706 if (Variable
->InDeletedTransitionPtr
!= NULL
) {
2708 // Both ADDED and IN_DELETED_TRANSITION old variable are present,
2709 // set IN_DELETED_TRANSITION one to DELETED state first.
2711 State
= Variable
->InDeletedTransitionPtr
->State
;
2712 State
&= VAR_DELETED
;
2713 Status
= UpdateVariableStore (
2714 &mVariableModuleGlobal
->VariableGlobal
,
2718 (UINTN
) &Variable
->InDeletedTransitionPtr
->State
,
2722 if (!EFI_ERROR (Status
)) {
2723 if (!Variable
->Volatile
) {
2724 ASSERT (CacheVariable
->InDeletedTransitionPtr
!= NULL
);
2725 CacheVariable
->InDeletedTransitionPtr
->State
= State
;
2732 State
= Variable
->CurrPtr
->State
;
2733 State
&= VAR_DELETED
;
2735 Status
= UpdateVariableStore (
2736 &mVariableModuleGlobal
->VariableGlobal
,
2740 (UINTN
) &Variable
->CurrPtr
->State
,
2744 if (!EFI_ERROR (Status
) && !Variable
->Volatile
) {
2745 CacheVariable
->CurrPtr
->State
= State
;
2749 if (!EFI_ERROR (Status
)) {
2750 UpdateVariableInfo (VariableName
, VendorGuid
, Volatile
, FALSE
, TRUE
, FALSE
, FALSE
);
2752 FlushHobVariableToFlash (VariableName
, VendorGuid
);
2761 Check if a Unicode character is a hexadecimal character.
2763 This function checks if a Unicode character is a
2764 hexadecimal character. The valid hexadecimal character is
2765 L'0' to L'9', L'a' to L'f', or L'A' to L'F'.
2768 @param Char The character to check against.
2770 @retval TRUE If the Char is a hexadecmial character.
2771 @retval FALSE If the Char is not a hexadecmial character.
2776 IsHexaDecimalDigitCharacter (
2780 return (BOOLEAN
) ((Char
>= L
'0' && Char
<= L
'9') || (Char
>= L
'A' && Char
<= L
'F') || (Char
>= L
'a' && Char
<= L
'f'));
2785 This code checks if variable is hardware error record variable or not.
2787 According to UEFI spec, hardware error record variable should use the EFI_HARDWARE_ERROR_VARIABLE VendorGuid
2788 and have the L"HwErrRec####" name convention, #### is a printed hex value and no 0x or h is included in the hex value.
2790 @param VariableName Pointer to variable name.
2791 @param VendorGuid Variable Vendor Guid.
2793 @retval TRUE Variable is hardware error record variable.
2794 @retval FALSE Variable is not hardware error record variable.
2799 IsHwErrRecVariable (
2800 IN CHAR16
*VariableName
,
2801 IN EFI_GUID
*VendorGuid
2804 if (!CompareGuid (VendorGuid
, &gEfiHardwareErrorVariableGuid
) ||
2805 (StrLen (VariableName
) != StrLen (L
"HwErrRec####")) ||
2806 (StrnCmp(VariableName
, L
"HwErrRec", StrLen (L
"HwErrRec")) != 0) ||
2807 !IsHexaDecimalDigitCharacter (VariableName
[0x8]) ||
2808 !IsHexaDecimalDigitCharacter (VariableName
[0x9]) ||
2809 !IsHexaDecimalDigitCharacter (VariableName
[0xA]) ||
2810 !IsHexaDecimalDigitCharacter (VariableName
[0xB])) {
2818 Mark a variable that will become read-only after leaving the DXE phase of execution.
2820 @param[in] This The VARIABLE_LOCK_PROTOCOL instance.
2821 @param[in] VariableName A pointer to the variable name that will be made read-only subsequently.
2822 @param[in] VendorGuid A pointer to the vendor GUID that will be made read-only subsequently.
2824 @retval EFI_SUCCESS The variable specified by the VariableName and the VendorGuid was marked
2825 as pending to be read-only.
2826 @retval EFI_INVALID_PARAMETER VariableName or VendorGuid is NULL.
2827 Or VariableName is an empty string.
2828 @retval EFI_ACCESS_DENIED EFI_END_OF_DXE_EVENT_GROUP_GUID or EFI_EVENT_GROUP_READY_TO_BOOT has
2829 already been signaled.
2830 @retval EFI_OUT_OF_RESOURCES There is not enough resource to hold the lock request.
2834 VariableLockRequestToLock (
2835 IN CONST EDKII_VARIABLE_LOCK_PROTOCOL
*This
,
2836 IN CHAR16
*VariableName
,
2837 IN EFI_GUID
*VendorGuid
2840 VARIABLE_ENTRY
*Entry
;
2843 if (VariableName
== NULL
|| VariableName
[0] == 0 || VendorGuid
== NULL
) {
2844 return EFI_INVALID_PARAMETER
;
2848 return EFI_ACCESS_DENIED
;
2851 Entry
= AllocateRuntimeZeroPool (sizeof (*Entry
) + StrSize (VariableName
));
2852 if (Entry
== NULL
) {
2853 return EFI_OUT_OF_RESOURCES
;
2856 DEBUG ((EFI_D_INFO
, "[Variable] Lock: %g:%s\n", VendorGuid
, VariableName
));
2858 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
2860 Name
= (CHAR16
*) ((UINTN
) Entry
+ sizeof (*Entry
));
2861 StrnCpy (Name
, VariableName
, StrLen (VariableName
));
2862 CopyGuid (&Entry
->Guid
, VendorGuid
);
2863 InsertTailList (&mLockedVariableList
, &Entry
->Link
);
2865 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
2872 This code finds variable in storage blocks (Volatile or Non-Volatile).
2874 Caution: This function may receive untrusted input.
2875 This function may be invoked in SMM mode, and datasize is external input.
2876 This function will do basic validation, before parse the data.
2878 @param VariableName Name of Variable to be found.
2879 @param VendorGuid Variable vendor GUID.
2880 @param Attributes Attribute value of the variable found.
2881 @param DataSize Size of Data found. If size is less than the
2882 data, this value contains the required size.
2883 @param Data Data pointer.
2885 @return EFI_INVALID_PARAMETER Invalid parameter.
2886 @return EFI_SUCCESS Find the specified variable.
2887 @return EFI_NOT_FOUND Not found.
2888 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2893 VariableServiceGetVariable (
2894 IN CHAR16
*VariableName
,
2895 IN EFI_GUID
*VendorGuid
,
2896 OUT UINT32
*Attributes OPTIONAL
,
2897 IN OUT UINTN
*DataSize
,
2902 VARIABLE_POINTER_TRACK Variable
;
2905 if (VariableName
== NULL
|| VendorGuid
== NULL
|| DataSize
== NULL
) {
2906 return EFI_INVALID_PARAMETER
;
2909 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
2911 Status
= FindVariable (VariableName
, VendorGuid
, &Variable
, &mVariableModuleGlobal
->VariableGlobal
, FALSE
);
2912 if (Variable
.CurrPtr
== NULL
|| EFI_ERROR (Status
)) {
2919 VarDataSize
= DataSizeOfVariable (Variable
.CurrPtr
);
2920 ASSERT (VarDataSize
!= 0);
2922 if (*DataSize
>= VarDataSize
) {
2924 Status
= EFI_INVALID_PARAMETER
;
2928 CopyMem (Data
, GetVariableDataPtr (Variable
.CurrPtr
), VarDataSize
);
2929 if (Attributes
!= NULL
) {
2930 *Attributes
= Variable
.CurrPtr
->Attributes
;
2933 *DataSize
= VarDataSize
;
2934 UpdateVariableInfo (VariableName
, VendorGuid
, Variable
.Volatile
, TRUE
, FALSE
, FALSE
, FALSE
);
2936 Status
= EFI_SUCCESS
;
2939 *DataSize
= VarDataSize
;
2940 Status
= EFI_BUFFER_TOO_SMALL
;
2945 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
2953 This code Finds the Next available variable.
2955 Caution: This function may receive untrusted input.
2956 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2958 @param VariableNameSize Size of the variable name.
2959 @param VariableName Pointer to variable name.
2960 @param VendorGuid Variable Vendor Guid.
2962 @return EFI_INVALID_PARAMETER Invalid parameter.
2963 @return EFI_SUCCESS Find the specified variable.
2964 @return EFI_NOT_FOUND Not found.
2965 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2970 VariableServiceGetNextVariableName (
2971 IN OUT UINTN
*VariableNameSize
,
2972 IN OUT CHAR16
*VariableName
,
2973 IN OUT EFI_GUID
*VendorGuid
2976 VARIABLE_STORE_TYPE Type
;
2977 VARIABLE_POINTER_TRACK Variable
;
2978 VARIABLE_POINTER_TRACK VariableInHob
;
2979 VARIABLE_POINTER_TRACK VariablePtrTrack
;
2982 VARIABLE_STORE_HEADER
*VariableStoreHeader
[VariableStoreTypeMax
];
2984 if (VariableNameSize
== NULL
|| VariableName
== NULL
|| VendorGuid
== NULL
) {
2985 return EFI_INVALID_PARAMETER
;
2988 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
2990 Status
= FindVariable (VariableName
, VendorGuid
, &Variable
, &mVariableModuleGlobal
->VariableGlobal
, FALSE
);
2991 if (Variable
.CurrPtr
== NULL
|| EFI_ERROR (Status
)) {
2995 if (VariableName
[0] != 0) {
2997 // If variable name is not NULL, get next variable.
2999 Variable
.CurrPtr
= GetNextVariablePtr (Variable
.CurrPtr
);
3003 // 0: Volatile, 1: HOB, 2: Non-Volatile.
3004 // The index and attributes mapping must be kept in this order as FindVariable
3005 // makes use of this mapping to implement search algorithm.
3007 VariableStoreHeader
[VariableStoreTypeVolatile
] = (VARIABLE_STORE_HEADER
*) (UINTN
) mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
;
3008 VariableStoreHeader
[VariableStoreTypeHob
] = (VARIABLE_STORE_HEADER
*) (UINTN
) mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
;
3009 VariableStoreHeader
[VariableStoreTypeNv
] = mNvVariableCache
;
3013 // Switch from Volatile to HOB, to Non-Volatile.
3015 while (!IsValidVariableHeader (Variable
.CurrPtr
, Variable
.EndPtr
)) {
3017 // Find current storage index
3019 for (Type
= (VARIABLE_STORE_TYPE
) 0; Type
< VariableStoreTypeMax
; Type
++) {
3020 if ((VariableStoreHeader
[Type
] != NULL
) && (Variable
.StartPtr
== GetStartPointer (VariableStoreHeader
[Type
]))) {
3024 ASSERT (Type
< VariableStoreTypeMax
);
3026 // Switch to next storage
3028 for (Type
++; Type
< VariableStoreTypeMax
; Type
++) {
3029 if (VariableStoreHeader
[Type
] != NULL
) {
3034 // Capture the case that
3035 // 1. current storage is the last one, or
3036 // 2. no further storage
3038 if (Type
== VariableStoreTypeMax
) {
3039 Status
= EFI_NOT_FOUND
;
3042 Variable
.StartPtr
= GetStartPointer (VariableStoreHeader
[Type
]);
3043 Variable
.EndPtr
= GetEndPointer (VariableStoreHeader
[Type
]);
3044 Variable
.CurrPtr
= Variable
.StartPtr
;
3048 // Variable is found
3050 if (Variable
.CurrPtr
->State
== VAR_ADDED
|| Variable
.CurrPtr
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)) {
3051 if (!AtRuntime () || ((Variable
.CurrPtr
->Attributes
& EFI_VARIABLE_RUNTIME_ACCESS
) != 0)) {
3052 if (Variable
.CurrPtr
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)) {
3054 // If it is a IN_DELETED_TRANSITION variable,
3055 // and there is also a same ADDED one at the same time,
3058 VariablePtrTrack
.StartPtr
= Variable
.StartPtr
;
3059 VariablePtrTrack
.EndPtr
= Variable
.EndPtr
;
3060 Status
= FindVariableEx (
3061 GetVariableNamePtr (Variable
.CurrPtr
),
3062 &Variable
.CurrPtr
->VendorGuid
,
3066 if (!EFI_ERROR (Status
) && VariablePtrTrack
.CurrPtr
->State
== VAR_ADDED
) {
3067 Variable
.CurrPtr
= GetNextVariablePtr (Variable
.CurrPtr
);
3073 // Don't return NV variable when HOB overrides it
3075 if ((VariableStoreHeader
[VariableStoreTypeHob
] != NULL
) && (VariableStoreHeader
[VariableStoreTypeNv
] != NULL
) &&
3076 (Variable
.StartPtr
== GetStartPointer (VariableStoreHeader
[VariableStoreTypeNv
]))
3078 VariableInHob
.StartPtr
= GetStartPointer (VariableStoreHeader
[VariableStoreTypeHob
]);
3079 VariableInHob
.EndPtr
= GetEndPointer (VariableStoreHeader
[VariableStoreTypeHob
]);
3080 Status
= FindVariableEx (
3081 GetVariableNamePtr (Variable
.CurrPtr
),
3082 &Variable
.CurrPtr
->VendorGuid
,
3086 if (!EFI_ERROR (Status
)) {
3087 Variable
.CurrPtr
= GetNextVariablePtr (Variable
.CurrPtr
);
3092 VarNameSize
= NameSizeOfVariable (Variable
.CurrPtr
);
3093 ASSERT (VarNameSize
!= 0);
3095 if (VarNameSize
<= *VariableNameSize
) {
3096 CopyMem (VariableName
, GetVariableNamePtr (Variable
.CurrPtr
), VarNameSize
);
3097 CopyMem (VendorGuid
, &Variable
.CurrPtr
->VendorGuid
, sizeof (EFI_GUID
));
3098 Status
= EFI_SUCCESS
;
3100 Status
= EFI_BUFFER_TOO_SMALL
;
3103 *VariableNameSize
= VarNameSize
;
3108 Variable
.CurrPtr
= GetNextVariablePtr (Variable
.CurrPtr
);
3112 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
3118 This code sets variable in storage blocks (Volatile or Non-Volatile).
3120 Caution: This function may receive untrusted input.
3121 This function may be invoked in SMM mode, and datasize and data are external input.
3122 This function will do basic validation, before parse the data.
3123 This function will parse the authentication carefully to avoid security issues, like
3124 buffer overflow, integer overflow.
3125 This function will check attribute carefully to avoid authentication bypass.
3127 @param VariableName Name of Variable to be found.
3128 @param VendorGuid Variable vendor GUID.
3129 @param Attributes Attribute value of the variable found
3130 @param DataSize Size of Data found. If size is less than the
3131 data, this value contains the required size.
3132 @param Data Data pointer.
3134 @return EFI_INVALID_PARAMETER Invalid parameter.
3135 @return EFI_SUCCESS Set successfully.
3136 @return EFI_OUT_OF_RESOURCES Resource not enough to set variable.
3137 @return EFI_NOT_FOUND Not found.
3138 @return EFI_WRITE_PROTECTED Variable is read-only.
3143 VariableServiceSetVariable (
3144 IN CHAR16
*VariableName
,
3145 IN EFI_GUID
*VendorGuid
,
3146 IN UINT32 Attributes
,
3151 VARIABLE_POINTER_TRACK Variable
;
3153 VARIABLE_HEADER
*NextVariable
;
3154 EFI_PHYSICAL_ADDRESS Point
;
3157 VARIABLE_ENTRY
*Entry
;
3161 // Check input parameters.
3163 if (VariableName
== NULL
|| VariableName
[0] == 0 || VendorGuid
== NULL
) {
3164 return EFI_INVALID_PARAMETER
;
3167 if (DataSize
!= 0 && Data
== NULL
) {
3168 return EFI_INVALID_PARAMETER
;
3172 // Check for reserverd bit in variable attribute.
3174 if ((Attributes
& (~EFI_VARIABLE_ATTRIBUTES_MASK
)) != 0) {
3175 return EFI_INVALID_PARAMETER
;
3179 // Make sure if runtime bit is set, boot service bit is set also.
3181 if ((Attributes
& (EFI_VARIABLE_RUNTIME_ACCESS
| EFI_VARIABLE_BOOTSERVICE_ACCESS
)) == EFI_VARIABLE_RUNTIME_ACCESS
) {
3182 return EFI_INVALID_PARAMETER
;
3186 // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute
3187 // cannot be set both.
3189 if (((Attributes
& EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
)
3190 && ((Attributes
& EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
)) {
3191 return EFI_INVALID_PARAMETER
;
3194 if ((Attributes
& EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
) {
3195 if (DataSize
< AUTHINFO_SIZE
) {
3197 // Try to write Authenticated Variable without AuthInfo.
3199 return EFI_SECURITY_VIOLATION
;
3201 PayloadSize
= DataSize
- AUTHINFO_SIZE
;
3202 } else if ((Attributes
& EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
) {
3204 // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor.
3206 if (DataSize
< OFFSET_OF_AUTHINFO2_CERT_DATA
||
3207 ((EFI_VARIABLE_AUTHENTICATION_2
*) Data
)->AuthInfo
.Hdr
.dwLength
> DataSize
- (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2
, AuthInfo
)) ||
3208 ((EFI_VARIABLE_AUTHENTICATION_2
*) Data
)->AuthInfo
.Hdr
.dwLength
< OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID
, CertData
)) {
3209 return EFI_SECURITY_VIOLATION
;
3211 PayloadSize
= DataSize
- AUTHINFO2_SIZE (Data
);
3213 PayloadSize
= DataSize
;
3216 if ((UINTN
)(~0) - PayloadSize
< StrSize(VariableName
)){
3218 // Prevent whole variable size overflow
3220 return EFI_INVALID_PARAMETER
;
3224 // The size of the VariableName, including the Unicode Null in bytes plus
3225 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)
3226 // bytes for HwErrRec, and PcdGet32 (PcdMaxVariableSize) bytes for the others.
3228 if ((Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
3229 if (StrSize (VariableName
) + PayloadSize
> PcdGet32 (PcdMaxHardwareErrorVariableSize
) - sizeof (VARIABLE_HEADER
)) {
3230 return EFI_INVALID_PARAMETER
;
3232 if (!IsHwErrRecVariable(VariableName
, VendorGuid
)) {
3233 return EFI_INVALID_PARAMETER
;
3237 // The size of the VariableName, including the Unicode Null in bytes plus
3238 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxVariableSize) bytes.
3240 if (StrSize (VariableName
) + PayloadSize
> PcdGet32 (PcdMaxVariableSize
) - sizeof (VARIABLE_HEADER
)) {
3241 return EFI_INVALID_PARAMETER
;
3245 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
3248 // Consider reentrant in MCA/INIT/NMI. It needs be reupdated.
3250 if (1 < InterlockedIncrement (&mVariableModuleGlobal
->VariableGlobal
.ReentrantState
)) {
3251 Point
= mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
;
3253 // Parse non-volatile variable data and get last variable offset.
3255 NextVariable
= GetStartPointer ((VARIABLE_STORE_HEADER
*) (UINTN
) Point
);
3256 while (IsValidVariableHeader (NextVariable
, GetEndPointer ((VARIABLE_STORE_HEADER
*) (UINTN
) Point
))) {
3257 NextVariable
= GetNextVariablePtr (NextVariable
);
3259 mVariableModuleGlobal
->NonVolatileLastVariableOffset
= (UINTN
) NextVariable
- (UINTN
) Point
;
3262 if (mEndOfDxe
&& mEnableLocking
) {
3264 // Treat the variables listed in the forbidden variable list as read-only after leaving DXE phase.
3266 for ( Link
= GetFirstNode (&mLockedVariableList
)
3267 ; !IsNull (&mLockedVariableList
, Link
)
3268 ; Link
= GetNextNode (&mLockedVariableList
, Link
)
3270 Entry
= BASE_CR (Link
, VARIABLE_ENTRY
, Link
);
3271 Name
= (CHAR16
*) ((UINTN
) Entry
+ sizeof (*Entry
));
3272 if (CompareGuid (&Entry
->Guid
, VendorGuid
) && (StrCmp (Name
, VariableName
) == 0)) {
3273 Status
= EFI_WRITE_PROTECTED
;
3274 DEBUG ((EFI_D_INFO
, "[Variable]: Changing readonly variable after leaving DXE phase - %g:%s\n", VendorGuid
, VariableName
));
3280 Status
= InternalVarCheckSetVariableCheck (VariableName
, VendorGuid
, Attributes
, PayloadSize
, (VOID
*) ((UINTN
) Data
+ DataSize
- PayloadSize
));
3281 if (EFI_ERROR (Status
)) {
3286 // Check whether the input variable is already existed.
3288 Status
= FindVariable (VariableName
, VendorGuid
, &Variable
, &mVariableModuleGlobal
->VariableGlobal
, TRUE
);
3289 if (!EFI_ERROR (Status
)) {
3290 if (((Variable
.CurrPtr
->Attributes
& EFI_VARIABLE_RUNTIME_ACCESS
) == 0) && AtRuntime ()) {
3291 Status
= EFI_WRITE_PROTECTED
;
3294 if (Attributes
!= 0 && (Attributes
& (~EFI_VARIABLE_APPEND_WRITE
)) != Variable
.CurrPtr
->Attributes
) {
3296 // If a preexisting variable is rewritten with different attributes, SetVariable() shall not
3297 // modify the variable and shall return EFI_INVALID_PARAMETER. Two exceptions to this rule:
3298 // 1. No access attributes specified
3299 // 2. The only attribute differing is EFI_VARIABLE_APPEND_WRITE
3301 Status
= EFI_INVALID_PARAMETER
;
3302 DEBUG ((EFI_D_INFO
, "[Variable]: Rewritten a preexisting variable(0x%08x) with different attributes(0x%08x) - %g:%s\n", Variable
.CurrPtr
->Attributes
, Attributes
, VendorGuid
, VariableName
));
3307 if (!FeaturePcdGet (PcdUefiVariableDefaultLangDeprecate
)) {
3309 // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.
3311 Status
= AutoUpdateLangVariable (VariableName
, Data
, DataSize
);
3312 if (EFI_ERROR (Status
)) {
3314 // The auto update operation failed, directly return to avoid inconsistency between PlatformLang and Lang.
3321 // Process PK, KEK, Sigdb seperately.
3323 if (CompareGuid (VendorGuid
, &gEfiGlobalVariableGuid
) && (StrCmp (VariableName
, EFI_PLATFORM_KEY_NAME
) == 0)){
3324 Status
= ProcessVarWithPk (VariableName
, VendorGuid
, Data
, DataSize
, &Variable
, Attributes
, TRUE
);
3325 } else if (CompareGuid (VendorGuid
, &gEfiGlobalVariableGuid
) && (StrCmp (VariableName
, EFI_KEY_EXCHANGE_KEY_NAME
) == 0)) {
3326 Status
= ProcessVarWithPk (VariableName
, VendorGuid
, Data
, DataSize
, &Variable
, Attributes
, FALSE
);
3327 } else if (CompareGuid (VendorGuid
, &gEfiImageSecurityDatabaseGuid
) &&
3328 ((StrCmp (VariableName
, EFI_IMAGE_SECURITY_DATABASE
) == 0) ||
3329 (StrCmp (VariableName
, EFI_IMAGE_SECURITY_DATABASE1
) == 0) ||
3330 (StrCmp (VariableName
, EFI_IMAGE_SECURITY_DATABASE2
) == 0)
3333 Status
= ProcessVarWithPk (VariableName
, VendorGuid
, Data
, DataSize
, &Variable
, Attributes
, FALSE
);
3334 if (EFI_ERROR (Status
)) {
3335 Status
= ProcessVarWithKek (VariableName
, VendorGuid
, Data
, DataSize
, &Variable
, Attributes
);
3338 Status
= ProcessVariable (VariableName
, VendorGuid
, Data
, DataSize
, &Variable
, Attributes
);
3342 InterlockedDecrement (&mVariableModuleGlobal
->VariableGlobal
.ReentrantState
);
3343 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
3345 if (!AtRuntime ()) {
3346 if (!EFI_ERROR (Status
)) {
3359 This code returns information about the EFI variables.
3361 Caution: This function may receive untrusted input.
3362 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
3364 @param Attributes Attributes bitmask to specify the type of variables
3365 on which to return information.
3366 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
3367 for the EFI variables associated with the attributes specified.
3368 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
3369 for EFI variables associated with the attributes specified.
3370 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
3371 associated with the attributes specified.
3373 @return EFI_SUCCESS Query successfully.
3378 VariableServiceQueryVariableInfoInternal (
3379 IN UINT32 Attributes
,
3380 OUT UINT64
*MaximumVariableStorageSize
,
3381 OUT UINT64
*RemainingVariableStorageSize
,
3382 OUT UINT64
*MaximumVariableSize
3385 VARIABLE_HEADER
*Variable
;
3386 VARIABLE_HEADER
*NextVariable
;
3387 UINT64 VariableSize
;
3388 VARIABLE_STORE_HEADER
*VariableStoreHeader
;
3389 UINT64 CommonVariableTotalSize
;
3390 UINT64 HwErrVariableTotalSize
;
3392 VARIABLE_POINTER_TRACK VariablePtrTrack
;
3394 CommonVariableTotalSize
= 0;
3395 HwErrVariableTotalSize
= 0;
3397 if((Attributes
& EFI_VARIABLE_NON_VOLATILE
) == 0) {
3399 // Query is Volatile related.
3401 VariableStoreHeader
= (VARIABLE_STORE_HEADER
*) ((UINTN
) mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
);
3404 // Query is Non-Volatile related.
3406 VariableStoreHeader
= mNvVariableCache
;
3410 // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize
3411 // with the storage size (excluding the storage header size).
3413 *MaximumVariableStorageSize
= VariableStoreHeader
->Size
- sizeof (VARIABLE_STORE_HEADER
);
3416 // Harware error record variable needs larger size.
3418 if ((Attributes
& (EFI_VARIABLE_NON_VOLATILE
| EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) == (EFI_VARIABLE_NON_VOLATILE
| EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) {
3419 *MaximumVariableStorageSize
= PcdGet32 (PcdHwErrStorageSize
);
3420 *MaximumVariableSize
= PcdGet32 (PcdMaxHardwareErrorVariableSize
) - sizeof (VARIABLE_HEADER
);
3422 if ((Attributes
& EFI_VARIABLE_NON_VOLATILE
) != 0) {
3424 *MaximumVariableStorageSize
= mVariableModuleGlobal
->CommonRuntimeVariableSpace
;
3426 *MaximumVariableStorageSize
= mVariableModuleGlobal
->CommonVariableSpace
;
3431 // Let *MaximumVariableSize be PcdGet32 (PcdMaxVariableSize) with the exception of the variable header size.
3433 *MaximumVariableSize
= PcdGet32 (PcdMaxVariableSize
) - sizeof (VARIABLE_HEADER
);
3437 // Point to the starting address of the variables.
3439 Variable
= GetStartPointer (VariableStoreHeader
);
3442 // Now walk through the related variable store.
3444 while (IsValidVariableHeader (Variable
, GetEndPointer (VariableStoreHeader
))) {
3445 NextVariable
= GetNextVariablePtr (Variable
);
3446 VariableSize
= (UINT64
) (UINTN
) NextVariable
- (UINT64
) (UINTN
) Variable
;
3450 // We don't take the state of the variables in mind
3451 // when calculating RemainingVariableStorageSize,
3452 // since the space occupied by variables not marked with
3453 // VAR_ADDED is not allowed to be reclaimed in Runtime.
3455 if ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
3456 HwErrVariableTotalSize
+= VariableSize
;
3458 CommonVariableTotalSize
+= VariableSize
;
3462 // Only care about Variables with State VAR_ADDED, because
3463 // the space not marked as VAR_ADDED is reclaimable now.
3465 if (Variable
->State
== VAR_ADDED
) {
3466 if ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
3467 HwErrVariableTotalSize
+= VariableSize
;
3469 CommonVariableTotalSize
+= VariableSize
;
3471 } else if (Variable
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)) {
3473 // If it is a IN_DELETED_TRANSITION variable,
3474 // and there is not also a same ADDED one at the same time,
3475 // this IN_DELETED_TRANSITION variable is valid.
3477 VariablePtrTrack
.StartPtr
= GetStartPointer (VariableStoreHeader
);
3478 VariablePtrTrack
.EndPtr
= GetEndPointer (VariableStoreHeader
);
3479 Status
= FindVariableEx (
3480 GetVariableNamePtr (Variable
),
3481 &Variable
->VendorGuid
,
3485 if (!EFI_ERROR (Status
) && VariablePtrTrack
.CurrPtr
->State
!= VAR_ADDED
) {
3486 if ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
3487 HwErrVariableTotalSize
+= VariableSize
;
3489 CommonVariableTotalSize
+= VariableSize
;
3496 // Go to the next one.
3498 Variable
= NextVariable
;
3501 if ((Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
){
3502 *RemainingVariableStorageSize
= *MaximumVariableStorageSize
- HwErrVariableTotalSize
;
3504 if (*MaximumVariableStorageSize
< CommonVariableTotalSize
) {
3505 *RemainingVariableStorageSize
= 0;
3507 *RemainingVariableStorageSize
= *MaximumVariableStorageSize
- CommonVariableTotalSize
;
3511 if (*RemainingVariableStorageSize
< sizeof (VARIABLE_HEADER
)) {
3512 *MaximumVariableSize
= 0;
3513 } else if ((*RemainingVariableStorageSize
- sizeof (VARIABLE_HEADER
)) < *MaximumVariableSize
) {
3514 *MaximumVariableSize
= *RemainingVariableStorageSize
- sizeof (VARIABLE_HEADER
);
3522 This code returns information about the EFI variables.
3524 Caution: This function may receive untrusted input.
3525 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
3527 @param Attributes Attributes bitmask to specify the type of variables
3528 on which to return information.
3529 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
3530 for the EFI variables associated with the attributes specified.
3531 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
3532 for EFI variables associated with the attributes specified.
3533 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
3534 associated with the attributes specified.
3536 @return EFI_INVALID_PARAMETER An invalid combination of attribute bits was supplied.
3537 @return EFI_SUCCESS Query successfully.
3538 @return EFI_UNSUPPORTED The attribute is not supported on this platform.
3543 VariableServiceQueryVariableInfo (
3544 IN UINT32 Attributes
,
3545 OUT UINT64
*MaximumVariableStorageSize
,
3546 OUT UINT64
*RemainingVariableStorageSize
,
3547 OUT UINT64
*MaximumVariableSize
3552 if(MaximumVariableStorageSize
== NULL
|| RemainingVariableStorageSize
== NULL
|| MaximumVariableSize
== NULL
|| Attributes
== 0) {
3553 return EFI_INVALID_PARAMETER
;
3556 if ((Attributes
& VARIABLE_ATTRIBUTE_NV_BS_RT_AT_HR_AW
) == 0) {
3558 // Make sure the Attributes combination is supported by the platform.
3560 return EFI_UNSUPPORTED
;
3561 } else if ((Attributes
& (EFI_VARIABLE_RUNTIME_ACCESS
| EFI_VARIABLE_BOOTSERVICE_ACCESS
)) == EFI_VARIABLE_RUNTIME_ACCESS
) {
3563 // Make sure if runtime bit is set, boot service bit is set also.
3565 return EFI_INVALID_PARAMETER
;
3566 } else if (AtRuntime () && ((Attributes
& EFI_VARIABLE_RUNTIME_ACCESS
) == 0)) {
3568 // Make sure RT Attribute is set if we are in Runtime phase.
3570 return EFI_INVALID_PARAMETER
;
3571 } else if ((Attributes
& (EFI_VARIABLE_NON_VOLATILE
| EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
3573 // Make sure Hw Attribute is set with NV.
3575 return EFI_INVALID_PARAMETER
;
3578 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
3580 Status
= VariableServiceQueryVariableInfoInternal (
3582 MaximumVariableStorageSize
,
3583 RemainingVariableStorageSize
,
3587 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
3592 This function reclaims variable storage if free size is below the threshold.
3594 Caution: This function may be invoked at SMM mode.
3595 Care must be taken to make sure not security issue.
3604 UINTN RemainingCommonRuntimeVariableSpace
;
3605 UINTN RemainingHwErrVariableSpace
;
3606 STATIC BOOLEAN Reclaimed
;
3609 // This function will be called only once at EndOfDxe or ReadyToBoot event.
3616 Status
= EFI_SUCCESS
;
3618 if (mVariableModuleGlobal
->CommonRuntimeVariableSpace
< mVariableModuleGlobal
->CommonVariableTotalSize
) {
3619 RemainingCommonRuntimeVariableSpace
= 0;
3621 RemainingCommonRuntimeVariableSpace
= mVariableModuleGlobal
->CommonRuntimeVariableSpace
- mVariableModuleGlobal
->CommonVariableTotalSize
;
3624 RemainingHwErrVariableSpace
= PcdGet32 (PcdHwErrStorageSize
) - mVariableModuleGlobal
->HwErrVariableTotalSize
;
3626 // Check if the free area is below a threshold.
3628 if ((RemainingCommonRuntimeVariableSpace
< PcdGet32 (PcdMaxVariableSize
))
3629 || ((PcdGet32 (PcdHwErrStorageSize
) != 0) &&
3630 (RemainingHwErrVariableSpace
< PcdGet32 (PcdMaxHardwareErrorVariableSize
)))){
3632 mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
,
3633 &mVariableModuleGlobal
->NonVolatileLastVariableOffset
,
3640 ASSERT_EFI_ERROR (Status
);
3645 Init non-volatile variable store.
3647 @retval EFI_SUCCESS Function successfully executed.
3648 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
3649 @retval EFI_VOLUME_CORRUPTED Variable Store or Firmware Volume for Variable Store is corrupted.
3653 InitNonVolatileVariableStore (
3657 EFI_FIRMWARE_VOLUME_HEADER
*FvHeader
;
3658 VARIABLE_HEADER
*Variable
;
3659 VARIABLE_HEADER
*NextVariable
;
3660 EFI_PHYSICAL_ADDRESS VariableStoreBase
;
3661 UINT64 VariableStoreLength
;
3663 EFI_HOB_GUID_TYPE
*GuidHob
;
3664 EFI_PHYSICAL_ADDRESS NvStorageBase
;
3665 UINT8
*NvStorageData
;
3666 UINT32 NvStorageSize
;
3667 FAULT_TOLERANT_WRITE_LAST_WRITE_DATA
*FtwLastWriteData
;
3668 UINT32 BackUpOffset
;
3670 UINT32 HwErrStorageSize
;
3671 UINT32 MaxUserNvVariableSpaceSize
;
3672 UINT32 BoottimeReservedNvVariableSpaceSize
;
3674 mVariableModuleGlobal
->FvbInstance
= NULL
;
3677 // Allocate runtime memory used for a memory copy of the FLASH region.
3678 // Keep the memory and the FLASH in sync as updates occur.
3680 NvStorageSize
= PcdGet32 (PcdFlashNvStorageVariableSize
);
3681 NvStorageData
= AllocateRuntimeZeroPool (NvStorageSize
);
3682 if (NvStorageData
== NULL
) {
3683 return EFI_OUT_OF_RESOURCES
;
3686 NvStorageBase
= (EFI_PHYSICAL_ADDRESS
) PcdGet64 (PcdFlashNvStorageVariableBase64
);
3687 if (NvStorageBase
== 0) {
3688 NvStorageBase
= (EFI_PHYSICAL_ADDRESS
) PcdGet32 (PcdFlashNvStorageVariableBase
);
3691 // Copy NV storage data to the memory buffer.
3693 CopyMem (NvStorageData
, (UINT8
*) (UINTN
) NvStorageBase
, NvStorageSize
);
3696 // Check the FTW last write data hob.
3698 GuidHob
= GetFirstGuidHob (&gEdkiiFaultTolerantWriteGuid
);
3699 if (GuidHob
!= NULL
) {
3700 FtwLastWriteData
= (FAULT_TOLERANT_WRITE_LAST_WRITE_DATA
*) GET_GUID_HOB_DATA (GuidHob
);
3701 if (FtwLastWriteData
->TargetAddress
== NvStorageBase
) {
3702 DEBUG ((EFI_D_INFO
, "Variable: NV storage is backed up in spare block: 0x%x\n", (UINTN
) FtwLastWriteData
->SpareAddress
));
3704 // Copy the backed up NV storage data to the memory buffer from spare block.
3706 CopyMem (NvStorageData
, (UINT8
*) (UINTN
) (FtwLastWriteData
->SpareAddress
), NvStorageSize
);
3707 } else if ((FtwLastWriteData
->TargetAddress
> NvStorageBase
) &&
3708 (FtwLastWriteData
->TargetAddress
< (NvStorageBase
+ NvStorageSize
))) {
3710 // Flash NV storage from the Offset is backed up in spare block.
3712 BackUpOffset
= (UINT32
) (FtwLastWriteData
->TargetAddress
- NvStorageBase
);
3713 BackUpSize
= NvStorageSize
- BackUpOffset
;
3714 DEBUG ((EFI_D_INFO
, "Variable: High partial NV storage from offset: %x is backed up in spare block: 0x%x\n", BackUpOffset
, (UINTN
) FtwLastWriteData
->SpareAddress
));
3716 // Copy the partial backed up NV storage data to the memory buffer from spare block.
3718 CopyMem (NvStorageData
+ BackUpOffset
, (UINT8
*) (UINTN
) FtwLastWriteData
->SpareAddress
, BackUpSize
);
3722 FvHeader
= (EFI_FIRMWARE_VOLUME_HEADER
*) NvStorageData
;
3725 // Check if the Firmware Volume is not corrupted
3727 if ((FvHeader
->Signature
!= EFI_FVH_SIGNATURE
) || (!CompareGuid (&gEfiSystemNvDataFvGuid
, &FvHeader
->FileSystemGuid
))) {
3728 FreePool (NvStorageData
);
3729 DEBUG ((EFI_D_ERROR
, "Firmware Volume for Variable Store is corrupted\n"));
3730 return EFI_VOLUME_CORRUPTED
;
3733 VariableStoreBase
= (EFI_PHYSICAL_ADDRESS
) ((UINTN
) FvHeader
+ FvHeader
->HeaderLength
);
3734 VariableStoreLength
= (UINT64
) (NvStorageSize
- FvHeader
->HeaderLength
);
3736 mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
= VariableStoreBase
;
3737 mNvVariableCache
= (VARIABLE_STORE_HEADER
*) (UINTN
) VariableStoreBase
;
3738 if (GetVariableStoreStatus (mNvVariableCache
) != EfiValid
) {
3739 FreePool (NvStorageData
);
3740 DEBUG((EFI_D_ERROR
, "Variable Store header is corrupted\n"));
3741 return EFI_VOLUME_CORRUPTED
;
3743 ASSERT(mNvVariableCache
->Size
== VariableStoreLength
);
3746 ASSERT (sizeof (VARIABLE_STORE_HEADER
) <= VariableStoreLength
);
3748 HwErrStorageSize
= PcdGet32 (PcdHwErrStorageSize
);
3749 MaxUserNvVariableSpaceSize
= PcdGet32 (PcdMaxUserNvVariableSpaceSize
);
3750 BoottimeReservedNvVariableSpaceSize
= PcdGet32 (PcdBoottimeReservedNvVariableSpaceSize
);
3753 // Note that in EdkII variable driver implementation, Hardware Error Record type variable
3754 // is stored with common variable in the same NV region. So the platform integrator should
3755 // ensure that the value of PcdHwErrStorageSize is less than the value of
3756 // VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).
3758 ASSERT (HwErrStorageSize
< (VariableStoreLength
- sizeof (VARIABLE_STORE_HEADER
)));
3760 // Ensure that the value of PcdMaxUserNvVariableSpaceSize is less than the value of
3761 // VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).
3763 ASSERT (MaxUserNvVariableSpaceSize
< (VariableStoreLength
- sizeof (VARIABLE_STORE_HEADER
) - HwErrStorageSize
));
3765 // Ensure that the value of PcdBoottimeReservedNvVariableSpaceSize is less than the value of
3766 // VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).
3768 ASSERT (BoottimeReservedNvVariableSpaceSize
< (VariableStoreLength
- sizeof (VARIABLE_STORE_HEADER
) - HwErrStorageSize
));
3770 mVariableModuleGlobal
->CommonVariableSpace
= ((UINTN
) VariableStoreLength
- sizeof (VARIABLE_STORE_HEADER
) - HwErrStorageSize
);
3771 mVariableModuleGlobal
->CommonMaxUserVariableSpace
= ((MaxUserNvVariableSpaceSize
!= 0) ? MaxUserNvVariableSpaceSize
: mVariableModuleGlobal
->CommonVariableSpace
);
3772 mVariableModuleGlobal
->CommonRuntimeVariableSpace
= mVariableModuleGlobal
->CommonVariableSpace
- BoottimeReservedNvVariableSpaceSize
;
3774 DEBUG ((EFI_D_INFO
, "Variable driver common space: 0x%x 0x%x 0x%x\n", mVariableModuleGlobal
->CommonVariableSpace
, mVariableModuleGlobal
->CommonMaxUserVariableSpace
, mVariableModuleGlobal
->CommonRuntimeVariableSpace
));
3777 // The max variable or hardware error variable size should be < variable store size.
3779 ASSERT(MAX (PcdGet32 (PcdMaxVariableSize
), PcdGet32 (PcdMaxHardwareErrorVariableSize
)) < VariableStoreLength
);
3782 // Parse non-volatile variable data and get last variable offset.
3784 Variable
= GetStartPointer ((VARIABLE_STORE_HEADER
*)(UINTN
)VariableStoreBase
);
3785 while (IsValidVariableHeader (Variable
, GetEndPointer ((VARIABLE_STORE_HEADER
*)(UINTN
)VariableStoreBase
))) {
3786 NextVariable
= GetNextVariablePtr (Variable
);
3787 VariableSize
= (UINTN
) NextVariable
- (UINTN
) Variable
;
3788 if ((Variable
->Attributes
& (EFI_VARIABLE_NON_VOLATILE
| EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) == (EFI_VARIABLE_NON_VOLATILE
| EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) {
3789 mVariableModuleGlobal
->HwErrVariableTotalSize
+= VariableSize
;
3791 mVariableModuleGlobal
->CommonVariableTotalSize
+= VariableSize
;
3794 Variable
= NextVariable
;
3796 mVariableModuleGlobal
->NonVolatileLastVariableOffset
= (UINTN
) Variable
- (UINTN
) VariableStoreBase
;
3802 Flush the HOB variable to flash.
3804 @param[in] VariableName Name of variable has been updated or deleted.
3805 @param[in] VendorGuid Guid of variable has been updated or deleted.
3809 FlushHobVariableToFlash (
3810 IN CHAR16
*VariableName
,
3811 IN EFI_GUID
*VendorGuid
3815 VARIABLE_STORE_HEADER
*VariableStoreHeader
;
3816 VARIABLE_HEADER
*Variable
;
3823 // Flush the HOB variable to flash.
3825 if (mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
!= 0) {
3826 VariableStoreHeader
= (VARIABLE_STORE_HEADER
*) (UINTN
) mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
;
3828 // Set HobVariableBase to 0, it can avoid SetVariable to call back.
3830 mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
= 0;
3831 for ( Variable
= GetStartPointer (VariableStoreHeader
)
3832 ; IsValidVariableHeader (Variable
, GetEndPointer (VariableStoreHeader
))
3833 ; Variable
= GetNextVariablePtr (Variable
)
3835 if (Variable
->State
!= VAR_ADDED
) {
3837 // The HOB variable has been set to DELETED state in local.
3841 ASSERT ((Variable
->Attributes
& EFI_VARIABLE_NON_VOLATILE
) != 0);
3842 if (VendorGuid
== NULL
|| VariableName
== NULL
||
3843 !CompareGuid (VendorGuid
, &Variable
->VendorGuid
) ||
3844 StrCmp (VariableName
, GetVariableNamePtr (Variable
)) != 0) {
3845 VariableData
= GetVariableDataPtr (Variable
);
3846 Status
= VariableServiceSetVariable (
3847 GetVariableNamePtr (Variable
),
3848 &Variable
->VendorGuid
,
3849 Variable
->Attributes
,
3853 DEBUG ((EFI_D_INFO
, "Variable driver flush the HOB variable to flash: %g %s %r\n", &Variable
->VendorGuid
, GetVariableNamePtr (Variable
), Status
));
3856 // The updated or deleted variable is matched with the HOB variable.
3857 // Don't break here because we will try to set other HOB variables
3858 // since this variable could be set successfully.
3860 Status
= EFI_SUCCESS
;
3862 if (!EFI_ERROR (Status
)) {
3864 // If set variable successful, or the updated or deleted variable is matched with the HOB variable,
3865 // set the HOB variable to DELETED state in local.
3867 DEBUG ((EFI_D_INFO
, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", &Variable
->VendorGuid
, GetVariableNamePtr (Variable
)));
3868 Variable
->State
&= VAR_DELETED
;
3875 // We still have HOB variable(s) not flushed in flash.
3877 mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
= (EFI_PHYSICAL_ADDRESS
) (UINTN
) VariableStoreHeader
;
3880 // All HOB variables have been flushed in flash.
3882 DEBUG ((EFI_D_INFO
, "Variable driver: all HOB variables have been flushed in flash.\n"));
3883 if (!AtRuntime ()) {
3884 FreePool ((VOID
*) VariableStoreHeader
);
3892 Initializes variable write service after FTW was ready.
3894 @retval EFI_SUCCESS Function successfully executed.
3895 @retval Others Fail to initialize the variable service.
3899 VariableWriteServiceInitialize (
3904 VARIABLE_STORE_HEADER
*VariableStoreHeader
;
3907 EFI_PHYSICAL_ADDRESS VariableStoreBase
;
3908 EFI_PHYSICAL_ADDRESS NvStorageBase
;
3910 NvStorageBase
= (EFI_PHYSICAL_ADDRESS
) PcdGet64 (PcdFlashNvStorageVariableBase64
);
3911 if (NvStorageBase
== 0) {
3912 NvStorageBase
= (EFI_PHYSICAL_ADDRESS
) PcdGet32 (PcdFlashNvStorageVariableBase
);
3914 VariableStoreBase
= NvStorageBase
+ (((EFI_FIRMWARE_VOLUME_HEADER
*)(UINTN
)(NvStorageBase
))->HeaderLength
);
3917 // Let NonVolatileVariableBase point to flash variable store base directly after FTW ready.
3919 mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
= VariableStoreBase
;
3920 VariableStoreHeader
= (VARIABLE_STORE_HEADER
*)(UINTN
)VariableStoreBase
;
3923 // Check if the free area is really free.
3925 for (Index
= mVariableModuleGlobal
->NonVolatileLastVariableOffset
; Index
< VariableStoreHeader
->Size
; Index
++) {
3926 Data
= ((UINT8
*) mNvVariableCache
)[Index
];
3929 // There must be something wrong in variable store, do reclaim operation.
3932 mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
,
3933 &mVariableModuleGlobal
->NonVolatileLastVariableOffset
,
3940 if (EFI_ERROR (Status
)) {
3947 FlushHobVariableToFlash (NULL
, NULL
);
3950 // Authenticated variable initialize.
3952 Status
= AutenticatedVariableServiceInitialize ();
3959 Initializes variable store area for non-volatile and volatile variable.
3961 @retval EFI_SUCCESS Function successfully executed.
3962 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
3966 VariableCommonInitialize (
3971 VARIABLE_STORE_HEADER
*VolatileVariableStore
;
3972 VARIABLE_STORE_HEADER
*VariableStoreHeader
;
3973 UINT64 VariableStoreLength
;
3975 EFI_HOB_GUID_TYPE
*GuidHob
;
3978 // Allocate runtime memory for variable driver global structure.
3980 mVariableModuleGlobal
= AllocateRuntimeZeroPool (sizeof (VARIABLE_MODULE_GLOBAL
));
3981 if (mVariableModuleGlobal
== NULL
) {
3982 return EFI_OUT_OF_RESOURCES
;
3985 InitializeLock (&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
, TPL_NOTIFY
);
3988 // Get HOB variable store.
3990 GuidHob
= GetFirstGuidHob (&gEfiAuthenticatedVariableGuid
);
3991 if (GuidHob
!= NULL
) {
3992 VariableStoreHeader
= GET_GUID_HOB_DATA (GuidHob
);
3993 VariableStoreLength
= (UINT64
) (GuidHob
->Header
.HobLength
- sizeof (EFI_HOB_GUID_TYPE
));
3994 if (GetVariableStoreStatus (VariableStoreHeader
) == EfiValid
) {
3995 mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
= (EFI_PHYSICAL_ADDRESS
) (UINTN
) AllocateRuntimeCopyPool ((UINTN
) VariableStoreLength
, (VOID
*) VariableStoreHeader
);
3996 if (mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
== 0) {
3997 FreePool (mVariableModuleGlobal
);
3998 return EFI_OUT_OF_RESOURCES
;
4001 DEBUG ((EFI_D_ERROR
, "HOB Variable Store header is corrupted!\n"));
4006 // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.
4008 ScratchSize
= MAX (PcdGet32 (PcdMaxVariableSize
), PcdGet32 (PcdMaxHardwareErrorVariableSize
));
4009 VolatileVariableStore
= AllocateRuntimePool (PcdGet32 (PcdVariableStoreSize
) + ScratchSize
);
4010 if (VolatileVariableStore
== NULL
) {
4011 if (mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
!= 0) {
4012 FreePool ((VOID
*) (UINTN
) mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
);
4014 FreePool (mVariableModuleGlobal
);
4015 return EFI_OUT_OF_RESOURCES
;
4018 SetMem (VolatileVariableStore
, PcdGet32 (PcdVariableStoreSize
) + ScratchSize
, 0xff);
4021 // Initialize Variable Specific Data.
4023 mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
= (EFI_PHYSICAL_ADDRESS
) (UINTN
) VolatileVariableStore
;
4024 mVariableModuleGlobal
->VolatileLastVariableOffset
= (UINTN
) GetStartPointer (VolatileVariableStore
) - (UINTN
) VolatileVariableStore
;
4026 CopyGuid (&VolatileVariableStore
->Signature
, &gEfiAuthenticatedVariableGuid
);
4027 VolatileVariableStore
->Size
= PcdGet32 (PcdVariableStoreSize
);
4028 VolatileVariableStore
->Format
= VARIABLE_STORE_FORMATTED
;
4029 VolatileVariableStore
->State
= VARIABLE_STORE_HEALTHY
;
4030 VolatileVariableStore
->Reserved
= 0;
4031 VolatileVariableStore
->Reserved1
= 0;
4034 // Init non-volatile variable store.
4036 Status
= InitNonVolatileVariableStore ();
4037 if (EFI_ERROR (Status
)) {
4038 if (mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
!= 0) {
4039 FreePool ((VOID
*) (UINTN
) mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
);
4041 FreePool (mVariableModuleGlobal
);
4042 FreePool (VolatileVariableStore
);
4050 Get the proper fvb handle and/or fvb protocol by the given Flash address.
4052 @param[in] Address The Flash address.
4053 @param[out] FvbHandle In output, if it is not NULL, it points to the proper FVB handle.
4054 @param[out] FvbProtocol In output, if it is not NULL, it points to the proper FVB protocol.
4058 GetFvbInfoByAddress (
4059 IN EFI_PHYSICAL_ADDRESS Address
,
4060 OUT EFI_HANDLE
*FvbHandle OPTIONAL
,
4061 OUT EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL
**FvbProtocol OPTIONAL
4065 EFI_HANDLE
*HandleBuffer
;
4068 EFI_PHYSICAL_ADDRESS FvbBaseAddress
;
4069 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL
*Fvb
;
4070 EFI_FVB_ATTRIBUTES_2 Attributes
;
4072 UINTN NumberOfBlocks
;
4074 HandleBuffer
= NULL
;
4076 // Get all FVB handles.
4078 Status
= GetFvbCountAndBuffer (&HandleCount
, &HandleBuffer
);
4079 if (EFI_ERROR (Status
)) {
4080 return EFI_NOT_FOUND
;
4084 // Get the FVB to access variable store.
4087 for (Index
= 0; Index
< HandleCount
; Index
+= 1, Status
= EFI_NOT_FOUND
, Fvb
= NULL
) {
4088 Status
= GetFvbByHandle (HandleBuffer
[Index
], &Fvb
);
4089 if (EFI_ERROR (Status
)) {
4090 Status
= EFI_NOT_FOUND
;
4095 // Ensure this FVB protocol supported Write operation.
4097 Status
= Fvb
->GetAttributes (Fvb
, &Attributes
);
4098 if (EFI_ERROR (Status
) || ((Attributes
& EFI_FVB2_WRITE_STATUS
) == 0)) {
4103 // Compare the address and select the right one.
4105 Status
= Fvb
->GetPhysicalAddress (Fvb
, &FvbBaseAddress
);
4106 if (EFI_ERROR (Status
)) {
4111 // Assume one FVB has one type of BlockSize.
4113 Status
= Fvb
->GetBlockSize (Fvb
, 0, &BlockSize
, &NumberOfBlocks
);
4114 if (EFI_ERROR (Status
)) {
4118 if ((Address
>= FvbBaseAddress
) && (Address
< (FvbBaseAddress
+ BlockSize
* NumberOfBlocks
))) {
4119 if (FvbHandle
!= NULL
) {
4120 *FvbHandle
= HandleBuffer
[Index
];
4122 if (FvbProtocol
!= NULL
) {
4125 Status
= EFI_SUCCESS
;
4129 FreePool (HandleBuffer
);
4132 Status
= EFI_NOT_FOUND
;