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
& VARIABLE_ATTRIBUTE_AT_AW
) != 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
= mVariableModuleGlobal
->ScratchBufferSize
;
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/Auth Variable Data Size as default MaxDataSize
2314 if ((Attributes
& VARIABLE_ATTRIBUTE_AT_AW
) != 0) {
2315 MaxDataSize
= mVariableModuleGlobal
->MaxAuthVariableSize
- DataOffset
;
2317 MaxDataSize
= mVariableModuleGlobal
->MaxVariableSize
- DataOffset
;
2320 if ((CompareGuid (VendorGuid
, &gEfiImageSecurityDatabaseGuid
) &&
2321 ((StrCmp (VariableName
, EFI_IMAGE_SECURITY_DATABASE
) == 0) || (StrCmp (VariableName
, EFI_IMAGE_SECURITY_DATABASE1
) == 0) ||
2322 (StrCmp (VariableName
, EFI_IMAGE_SECURITY_DATABASE2
) == 0))) ||
2323 (CompareGuid (VendorGuid
, &gEfiGlobalVariableGuid
) && (StrCmp (VariableName
, EFI_KEY_EXCHANGE_KEY_NAME
) == 0))) {
2325 // For variables with formatted as EFI_SIGNATURE_LIST, the driver shall not perform an append of
2326 // EFI_SIGNATURE_DATA values that are already part of the existing variable value.
2328 Status
= AppendSignatureList (
2330 Variable
->CurrPtr
->DataSize
,
2331 MaxDataSize
- Variable
->CurrPtr
->DataSize
,
2336 if (Status
== EFI_BUFFER_TOO_SMALL
) {
2338 // Signature List is too long, Failed to Append.
2340 Status
= EFI_INVALID_PARAMETER
;
2344 if (MergedBufSize
== Variable
->CurrPtr
->DataSize
) {
2345 if ((TimeStamp
== NULL
) || CompareTimeStamp (TimeStamp
, &Variable
->CurrPtr
->TimeStamp
)) {
2347 // New EFI_SIGNATURE_DATA is not found and timestamp is not later
2348 // than current timestamp, return EFI_SUCCESS directly.
2350 UpdateVariableInfo (VariableName
, VendorGuid
, Variable
->Volatile
, FALSE
, TRUE
, FALSE
, FALSE
);
2351 Status
= EFI_SUCCESS
;
2357 // For other Variables, append the new data to the end of existing data.
2358 // Max Harware error record variable data size is different from common/auth variable
2360 if ((Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
2361 MaxDataSize
= PcdGet32 (PcdMaxHardwareErrorVariableSize
) - DataOffset
;
2364 if (Variable
->CurrPtr
->DataSize
+ DataSize
> MaxDataSize
) {
2366 // Existing data size + new data size exceed maximum variable size limitation.
2368 Status
= EFI_INVALID_PARAMETER
;
2371 CopyMem ((UINT8
*) ((UINTN
) BufferForMerge
+ Variable
->CurrPtr
->DataSize
), Data
, DataSize
);
2372 MergedBufSize
= Variable
->CurrPtr
->DataSize
+ DataSize
;
2376 // BufferForMerge(from DataOffset of NextVariable) has included the merged existing and new data.
2378 Data
= BufferForMerge
;
2379 DataSize
= MergedBufSize
;
2384 // Mark the old variable as in delete transition.
2386 State
= Variable
->CurrPtr
->State
;
2387 State
&= VAR_IN_DELETED_TRANSITION
;
2389 Status
= UpdateVariableStore (
2390 &mVariableModuleGlobal
->VariableGlobal
,
2394 (UINTN
) &Variable
->CurrPtr
->State
,
2398 if (EFI_ERROR (Status
)) {
2401 if (!Variable
->Volatile
) {
2402 CacheVariable
->CurrPtr
->State
= State
;
2407 // Not found existing variable. Create a new variable.
2410 if ((DataSize
== 0) && ((Attributes
& EFI_VARIABLE_APPEND_WRITE
) != 0)) {
2411 Status
= EFI_SUCCESS
;
2416 // Make sure we are trying to create a new variable.
2417 // Setting a data variable with zero DataSize or no access attributes means to delete it.
2419 if (DataSize
== 0 || (Attributes
& (EFI_VARIABLE_RUNTIME_ACCESS
| EFI_VARIABLE_BOOTSERVICE_ACCESS
)) == 0) {
2420 Status
= EFI_NOT_FOUND
;
2425 // Only variable have NV|RT attribute can be created in Runtime.
2428 (((Attributes
& EFI_VARIABLE_RUNTIME_ACCESS
) == 0) || ((Attributes
& EFI_VARIABLE_NON_VOLATILE
) == 0))) {
2429 Status
= EFI_INVALID_PARAMETER
;
2435 // Function part - create a new variable and copy the data.
2436 // Both update a variable and create a variable will come here.
2438 NextVariable
->StartId
= VARIABLE_DATA
;
2440 // NextVariable->State = VAR_ADDED;
2442 NextVariable
->Reserved
= 0;
2443 NextVariable
->PubKeyIndex
= KeyIndex
;
2444 NextVariable
->MonotonicCount
= MonotonicCount
;
2445 ZeroMem (&NextVariable
->TimeStamp
, sizeof (EFI_TIME
));
2447 if (((Attributes
& EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
) != 0) &&
2448 (TimeStamp
!= NULL
)) {
2449 if ((Attributes
& EFI_VARIABLE_APPEND_WRITE
) == 0) {
2450 CopyMem (&NextVariable
->TimeStamp
, TimeStamp
, sizeof (EFI_TIME
));
2453 // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only
2454 // when the new TimeStamp value is later than the current timestamp associated
2455 // with the variable, we need associate the new timestamp with the updated value.
2457 if (Variable
->CurrPtr
!= NULL
) {
2458 if (CompareTimeStamp (&Variable
->CurrPtr
->TimeStamp
, TimeStamp
)) {
2459 CopyMem (&NextVariable
->TimeStamp
, TimeStamp
, sizeof (EFI_TIME
));
2466 // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned
2467 // Attributes bitmask parameter of a GetVariable() call.
2469 NextVariable
->Attributes
= Attributes
& (~EFI_VARIABLE_APPEND_WRITE
);
2471 VarNameOffset
= sizeof (VARIABLE_HEADER
);
2472 VarNameSize
= StrSize (VariableName
);
2474 (UINT8
*) ((UINTN
) NextVariable
+ VarNameOffset
),
2478 VarDataOffset
= VarNameOffset
+ VarNameSize
+ GET_PAD_SIZE (VarNameSize
);
2481 // If DataReady is TRUE, it means the variable data has been saved into
2482 // NextVariable during EFI_VARIABLE_APPEND_WRITE operation preparation.
2486 (UINT8
*) ((UINTN
) NextVariable
+ VarDataOffset
),
2492 CopyMem (&NextVariable
->VendorGuid
, VendorGuid
, sizeof (EFI_GUID
));
2494 // There will be pad bytes after Data, the NextVariable->NameSize and
2495 // NextVariable->DataSize should not include pad size so that variable
2496 // service can get actual size in GetVariable.
2498 NextVariable
->NameSize
= (UINT32
)VarNameSize
;
2499 NextVariable
->DataSize
= (UINT32
)DataSize
;
2502 // The actual size of the variable that stores in storage should
2503 // include pad size.
2505 VarSize
= VarDataOffset
+ DataSize
+ GET_PAD_SIZE (DataSize
);
2506 if ((Attributes
& EFI_VARIABLE_NON_VOLATILE
) != 0) {
2508 // Create a nonvolatile variable.
2512 IsCommonVariable
= FALSE
;
2513 IsCommonUserVariable
= FALSE
;
2514 if ((Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == 0) {
2515 IsCommonVariable
= TRUE
;
2516 IsCommonUserVariable
= IsUserVariable (NextVariable
);
2518 if ((((Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) != 0)
2519 && ((VarSize
+ mVariableModuleGlobal
->HwErrVariableTotalSize
) > PcdGet32 (PcdHwErrStorageSize
)))
2520 || (IsCommonVariable
&& ((VarSize
+ mVariableModuleGlobal
->CommonVariableTotalSize
) > mVariableModuleGlobal
->CommonVariableSpace
))
2521 || (IsCommonVariable
&& AtRuntime () && ((VarSize
+ mVariableModuleGlobal
->CommonVariableTotalSize
) > mVariableModuleGlobal
->CommonRuntimeVariableSpace
))
2522 || (IsCommonUserVariable
&& ((VarSize
+ mVariableModuleGlobal
->CommonUserVariableTotalSize
) > mVariableModuleGlobal
->CommonMaxUserVariableSpace
))) {
2524 if (IsCommonUserVariable
&& ((VarSize
+ mVariableModuleGlobal
->CommonUserVariableTotalSize
) > mVariableModuleGlobal
->CommonMaxUserVariableSpace
)) {
2525 RecordVarErrorFlag (VAR_ERROR_FLAG_USER_ERROR
, VariableName
, VendorGuid
, Attributes
, VarSize
);
2527 if (IsCommonVariable
&& ((VarSize
+ mVariableModuleGlobal
->CommonVariableTotalSize
) > mVariableModuleGlobal
->CommonRuntimeVariableSpace
)) {
2528 RecordVarErrorFlag (VAR_ERROR_FLAG_SYSTEM_ERROR
, VariableName
, VendorGuid
, Attributes
, VarSize
);
2530 Status
= EFI_OUT_OF_RESOURCES
;
2534 // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.
2537 mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
,
2538 &mVariableModuleGlobal
->NonVolatileLastVariableOffset
,
2542 HEADER_ALIGN (VarSize
),
2545 if (!EFI_ERROR (Status
)) {
2547 // The new variable has been integrated successfully during reclaiming.
2549 if (Variable
->CurrPtr
!= NULL
) {
2550 CacheVariable
->CurrPtr
= (VARIABLE_HEADER
*)((UINTN
) CacheVariable
->StartPtr
+ ((UINTN
) Variable
->CurrPtr
- (UINTN
) Variable
->StartPtr
));
2551 CacheVariable
->InDeletedTransitionPtr
= NULL
;
2553 UpdateVariableInfo (VariableName
, VendorGuid
, FALSE
, FALSE
, TRUE
, FALSE
, FALSE
);
2554 FlushHobVariableToFlash (VariableName
, VendorGuid
);
2556 if (IsCommonUserVariable
&& ((VarSize
+ mVariableModuleGlobal
->CommonUserVariableTotalSize
) > mVariableModuleGlobal
->CommonMaxUserVariableSpace
)) {
2557 RecordVarErrorFlag (VAR_ERROR_FLAG_USER_ERROR
, VariableName
, VendorGuid
, Attributes
, VarSize
);
2559 if (IsCommonVariable
&& ((VarSize
+ mVariableModuleGlobal
->CommonVariableTotalSize
) > mVariableModuleGlobal
->CommonVariableSpace
)) {
2560 RecordVarErrorFlag (VAR_ERROR_FLAG_SYSTEM_ERROR
, VariableName
, VendorGuid
, Attributes
, VarSize
);
2567 // 1. Write variable header
2568 // 2. Set variable state to header valid
2569 // 3. Write variable data
2570 // 4. Set variable state to valid
2575 CacheOffset
= mVariableModuleGlobal
->NonVolatileLastVariableOffset
;
2576 Status
= UpdateVariableStore (
2577 &mVariableModuleGlobal
->VariableGlobal
,
2581 mVariableModuleGlobal
->NonVolatileLastVariableOffset
,
2582 sizeof (VARIABLE_HEADER
),
2583 (UINT8
*) NextVariable
2586 if (EFI_ERROR (Status
)) {
2593 NextVariable
->State
= VAR_HEADER_VALID_ONLY
;
2594 Status
= UpdateVariableStore (
2595 &mVariableModuleGlobal
->VariableGlobal
,
2599 mVariableModuleGlobal
->NonVolatileLastVariableOffset
+ OFFSET_OF (VARIABLE_HEADER
, State
),
2601 &NextVariable
->State
2604 if (EFI_ERROR (Status
)) {
2610 Status
= UpdateVariableStore (
2611 &mVariableModuleGlobal
->VariableGlobal
,
2615 mVariableModuleGlobal
->NonVolatileLastVariableOffset
+ sizeof (VARIABLE_HEADER
),
2616 (UINT32
) VarSize
- sizeof (VARIABLE_HEADER
),
2617 (UINT8
*) NextVariable
+ sizeof (VARIABLE_HEADER
)
2620 if (EFI_ERROR (Status
)) {
2626 NextVariable
->State
= VAR_ADDED
;
2627 Status
= UpdateVariableStore (
2628 &mVariableModuleGlobal
->VariableGlobal
,
2632 mVariableModuleGlobal
->NonVolatileLastVariableOffset
+ OFFSET_OF (VARIABLE_HEADER
, State
),
2634 &NextVariable
->State
2637 if (EFI_ERROR (Status
)) {
2641 mVariableModuleGlobal
->NonVolatileLastVariableOffset
+= HEADER_ALIGN (VarSize
);
2643 if ((Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) != 0) {
2644 mVariableModuleGlobal
->HwErrVariableTotalSize
+= HEADER_ALIGN (VarSize
);
2646 mVariableModuleGlobal
->CommonVariableTotalSize
+= HEADER_ALIGN (VarSize
);
2647 if (IsCommonUserVariable
) {
2648 mVariableModuleGlobal
->CommonUserVariableTotalSize
+= HEADER_ALIGN (VarSize
);
2652 // update the memory copy of Flash region.
2654 CopyMem ((UINT8
*)mNvVariableCache
+ CacheOffset
, (UINT8
*)NextVariable
, VarSize
);
2657 // Create a volatile variable.
2661 if ((UINT32
) (VarSize
+ mVariableModuleGlobal
->VolatileLastVariableOffset
) >
2662 ((VARIABLE_STORE_HEADER
*) ((UINTN
) (mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
)))->Size
) {
2664 // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.
2667 mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
,
2668 &mVariableModuleGlobal
->VolatileLastVariableOffset
,
2672 HEADER_ALIGN (VarSize
),
2675 if (!EFI_ERROR (Status
)) {
2677 // The new variable has been integrated successfully during reclaiming.
2679 if (Variable
->CurrPtr
!= NULL
) {
2680 CacheVariable
->CurrPtr
= (VARIABLE_HEADER
*)((UINTN
) CacheVariable
->StartPtr
+ ((UINTN
) Variable
->CurrPtr
- (UINTN
) Variable
->StartPtr
));
2681 CacheVariable
->InDeletedTransitionPtr
= NULL
;
2683 UpdateVariableInfo (VariableName
, VendorGuid
, TRUE
, FALSE
, TRUE
, FALSE
, FALSE
);
2688 NextVariable
->State
= VAR_ADDED
;
2689 Status
= UpdateVariableStore (
2690 &mVariableModuleGlobal
->VariableGlobal
,
2694 mVariableModuleGlobal
->VolatileLastVariableOffset
,
2696 (UINT8
*) NextVariable
2699 if (EFI_ERROR (Status
)) {
2703 mVariableModuleGlobal
->VolatileLastVariableOffset
+= HEADER_ALIGN (VarSize
);
2707 // Mark the old variable as deleted.
2709 if (!EFI_ERROR (Status
) && Variable
->CurrPtr
!= NULL
) {
2710 if (Variable
->InDeletedTransitionPtr
!= NULL
) {
2712 // Both ADDED and IN_DELETED_TRANSITION old variable are present,
2713 // set IN_DELETED_TRANSITION one to DELETED state first.
2715 State
= Variable
->InDeletedTransitionPtr
->State
;
2716 State
&= VAR_DELETED
;
2717 Status
= UpdateVariableStore (
2718 &mVariableModuleGlobal
->VariableGlobal
,
2722 (UINTN
) &Variable
->InDeletedTransitionPtr
->State
,
2726 if (!EFI_ERROR (Status
)) {
2727 if (!Variable
->Volatile
) {
2728 ASSERT (CacheVariable
->InDeletedTransitionPtr
!= NULL
);
2729 CacheVariable
->InDeletedTransitionPtr
->State
= State
;
2736 State
= Variable
->CurrPtr
->State
;
2737 State
&= VAR_DELETED
;
2739 Status
= UpdateVariableStore (
2740 &mVariableModuleGlobal
->VariableGlobal
,
2744 (UINTN
) &Variable
->CurrPtr
->State
,
2748 if (!EFI_ERROR (Status
) && !Variable
->Volatile
) {
2749 CacheVariable
->CurrPtr
->State
= State
;
2753 if (!EFI_ERROR (Status
)) {
2754 UpdateVariableInfo (VariableName
, VendorGuid
, Volatile
, FALSE
, TRUE
, FALSE
, FALSE
);
2756 FlushHobVariableToFlash (VariableName
, VendorGuid
);
2765 Check if a Unicode character is a hexadecimal character.
2767 This function checks if a Unicode character is a
2768 hexadecimal character. The valid hexadecimal character is
2769 L'0' to L'9', L'a' to L'f', or L'A' to L'F'.
2772 @param Char The character to check against.
2774 @retval TRUE If the Char is a hexadecmial character.
2775 @retval FALSE If the Char is not a hexadecmial character.
2780 IsHexaDecimalDigitCharacter (
2784 return (BOOLEAN
) ((Char
>= L
'0' && Char
<= L
'9') || (Char
>= L
'A' && Char
<= L
'F') || (Char
>= L
'a' && Char
<= L
'f'));
2789 This code checks if variable is hardware error record variable or not.
2791 According to UEFI spec, hardware error record variable should use the EFI_HARDWARE_ERROR_VARIABLE VendorGuid
2792 and have the L"HwErrRec####" name convention, #### is a printed hex value and no 0x or h is included in the hex value.
2794 @param VariableName Pointer to variable name.
2795 @param VendorGuid Variable Vendor Guid.
2797 @retval TRUE Variable is hardware error record variable.
2798 @retval FALSE Variable is not hardware error record variable.
2803 IsHwErrRecVariable (
2804 IN CHAR16
*VariableName
,
2805 IN EFI_GUID
*VendorGuid
2808 if (!CompareGuid (VendorGuid
, &gEfiHardwareErrorVariableGuid
) ||
2809 (StrLen (VariableName
) != StrLen (L
"HwErrRec####")) ||
2810 (StrnCmp(VariableName
, L
"HwErrRec", StrLen (L
"HwErrRec")) != 0) ||
2811 !IsHexaDecimalDigitCharacter (VariableName
[0x8]) ||
2812 !IsHexaDecimalDigitCharacter (VariableName
[0x9]) ||
2813 !IsHexaDecimalDigitCharacter (VariableName
[0xA]) ||
2814 !IsHexaDecimalDigitCharacter (VariableName
[0xB])) {
2822 Mark a variable that will become read-only after leaving the DXE phase of execution.
2824 @param[in] This The VARIABLE_LOCK_PROTOCOL instance.
2825 @param[in] VariableName A pointer to the variable name that will be made read-only subsequently.
2826 @param[in] VendorGuid A pointer to the vendor GUID that will be made read-only subsequently.
2828 @retval EFI_SUCCESS The variable specified by the VariableName and the VendorGuid was marked
2829 as pending to be read-only.
2830 @retval EFI_INVALID_PARAMETER VariableName or VendorGuid is NULL.
2831 Or VariableName is an empty string.
2832 @retval EFI_ACCESS_DENIED EFI_END_OF_DXE_EVENT_GROUP_GUID or EFI_EVENT_GROUP_READY_TO_BOOT has
2833 already been signaled.
2834 @retval EFI_OUT_OF_RESOURCES There is not enough resource to hold the lock request.
2838 VariableLockRequestToLock (
2839 IN CONST EDKII_VARIABLE_LOCK_PROTOCOL
*This
,
2840 IN CHAR16
*VariableName
,
2841 IN EFI_GUID
*VendorGuid
2844 VARIABLE_ENTRY
*Entry
;
2847 VARIABLE_ENTRY
*LockedEntry
;
2849 if (VariableName
== NULL
|| VariableName
[0] == 0 || VendorGuid
== NULL
) {
2850 return EFI_INVALID_PARAMETER
;
2854 return EFI_ACCESS_DENIED
;
2857 Entry
= AllocateRuntimeZeroPool (sizeof (*Entry
) + StrSize (VariableName
));
2858 if (Entry
== NULL
) {
2859 return EFI_OUT_OF_RESOURCES
;
2862 DEBUG ((EFI_D_INFO
, "[Variable] Lock: %g:%s\n", VendorGuid
, VariableName
));
2864 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
2866 for ( Link
= GetFirstNode (&mLockedVariableList
)
2867 ; !IsNull (&mLockedVariableList
, Link
)
2868 ; Link
= GetNextNode (&mLockedVariableList
, Link
)
2870 LockedEntry
= BASE_CR (Link
, VARIABLE_ENTRY
, Link
);
2871 Name
= (CHAR16
*) ((UINTN
) LockedEntry
+ sizeof (*LockedEntry
));
2872 if (CompareGuid (&LockedEntry
->Guid
, VendorGuid
) && (StrCmp (Name
, VariableName
) == 0)) {
2877 Name
= (CHAR16
*) ((UINTN
) Entry
+ sizeof (*Entry
));
2878 StrnCpy (Name
, VariableName
, StrLen (VariableName
));
2879 CopyGuid (&Entry
->Guid
, VendorGuid
);
2880 InsertTailList (&mLockedVariableList
, &Entry
->Link
);
2883 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
2890 This code finds variable in storage blocks (Volatile or Non-Volatile).
2892 Caution: This function may receive untrusted input.
2893 This function may be invoked in SMM mode, and datasize is external input.
2894 This function will do basic validation, before parse the data.
2896 @param VariableName Name of Variable to be found.
2897 @param VendorGuid Variable vendor GUID.
2898 @param Attributes Attribute value of the variable found.
2899 @param DataSize Size of Data found. If size is less than the
2900 data, this value contains the required size.
2901 @param Data Data pointer.
2903 @return EFI_INVALID_PARAMETER Invalid parameter.
2904 @return EFI_SUCCESS Find the specified variable.
2905 @return EFI_NOT_FOUND Not found.
2906 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2911 VariableServiceGetVariable (
2912 IN CHAR16
*VariableName
,
2913 IN EFI_GUID
*VendorGuid
,
2914 OUT UINT32
*Attributes OPTIONAL
,
2915 IN OUT UINTN
*DataSize
,
2920 VARIABLE_POINTER_TRACK Variable
;
2923 if (VariableName
== NULL
|| VendorGuid
== NULL
|| DataSize
== NULL
) {
2924 return EFI_INVALID_PARAMETER
;
2927 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
2929 Status
= FindVariable (VariableName
, VendorGuid
, &Variable
, &mVariableModuleGlobal
->VariableGlobal
, FALSE
);
2930 if (Variable
.CurrPtr
== NULL
|| EFI_ERROR (Status
)) {
2937 VarDataSize
= DataSizeOfVariable (Variable
.CurrPtr
);
2938 ASSERT (VarDataSize
!= 0);
2940 if (*DataSize
>= VarDataSize
) {
2942 Status
= EFI_INVALID_PARAMETER
;
2946 CopyMem (Data
, GetVariableDataPtr (Variable
.CurrPtr
), VarDataSize
);
2947 if (Attributes
!= NULL
) {
2948 *Attributes
= Variable
.CurrPtr
->Attributes
;
2951 *DataSize
= VarDataSize
;
2952 UpdateVariableInfo (VariableName
, VendorGuid
, Variable
.Volatile
, TRUE
, FALSE
, FALSE
, FALSE
);
2954 Status
= EFI_SUCCESS
;
2957 *DataSize
= VarDataSize
;
2958 Status
= EFI_BUFFER_TOO_SMALL
;
2963 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
2971 This code Finds the Next available variable.
2973 Caution: This function may receive untrusted input.
2974 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2976 @param VariableNameSize Size of the variable name.
2977 @param VariableName Pointer to variable name.
2978 @param VendorGuid Variable Vendor Guid.
2980 @return EFI_INVALID_PARAMETER Invalid parameter.
2981 @return EFI_SUCCESS Find the specified variable.
2982 @return EFI_NOT_FOUND Not found.
2983 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2988 VariableServiceGetNextVariableName (
2989 IN OUT UINTN
*VariableNameSize
,
2990 IN OUT CHAR16
*VariableName
,
2991 IN OUT EFI_GUID
*VendorGuid
2994 VARIABLE_STORE_TYPE Type
;
2995 VARIABLE_POINTER_TRACK Variable
;
2996 VARIABLE_POINTER_TRACK VariableInHob
;
2997 VARIABLE_POINTER_TRACK VariablePtrTrack
;
3000 VARIABLE_STORE_HEADER
*VariableStoreHeader
[VariableStoreTypeMax
];
3002 if (VariableNameSize
== NULL
|| VariableName
== NULL
|| VendorGuid
== NULL
) {
3003 return EFI_INVALID_PARAMETER
;
3006 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
3008 Status
= FindVariable (VariableName
, VendorGuid
, &Variable
, &mVariableModuleGlobal
->VariableGlobal
, FALSE
);
3009 if (Variable
.CurrPtr
== NULL
|| EFI_ERROR (Status
)) {
3013 if (VariableName
[0] != 0) {
3015 // If variable name is not NULL, get next variable.
3017 Variable
.CurrPtr
= GetNextVariablePtr (Variable
.CurrPtr
);
3021 // 0: Volatile, 1: HOB, 2: Non-Volatile.
3022 // The index and attributes mapping must be kept in this order as FindVariable
3023 // makes use of this mapping to implement search algorithm.
3025 VariableStoreHeader
[VariableStoreTypeVolatile
] = (VARIABLE_STORE_HEADER
*) (UINTN
) mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
;
3026 VariableStoreHeader
[VariableStoreTypeHob
] = (VARIABLE_STORE_HEADER
*) (UINTN
) mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
;
3027 VariableStoreHeader
[VariableStoreTypeNv
] = mNvVariableCache
;
3031 // Switch from Volatile to HOB, to Non-Volatile.
3033 while (!IsValidVariableHeader (Variable
.CurrPtr
, Variable
.EndPtr
)) {
3035 // Find current storage index
3037 for (Type
= (VARIABLE_STORE_TYPE
) 0; Type
< VariableStoreTypeMax
; Type
++) {
3038 if ((VariableStoreHeader
[Type
] != NULL
) && (Variable
.StartPtr
== GetStartPointer (VariableStoreHeader
[Type
]))) {
3042 ASSERT (Type
< VariableStoreTypeMax
);
3044 // Switch to next storage
3046 for (Type
++; Type
< VariableStoreTypeMax
; Type
++) {
3047 if (VariableStoreHeader
[Type
] != NULL
) {
3052 // Capture the case that
3053 // 1. current storage is the last one, or
3054 // 2. no further storage
3056 if (Type
== VariableStoreTypeMax
) {
3057 Status
= EFI_NOT_FOUND
;
3060 Variable
.StartPtr
= GetStartPointer (VariableStoreHeader
[Type
]);
3061 Variable
.EndPtr
= GetEndPointer (VariableStoreHeader
[Type
]);
3062 Variable
.CurrPtr
= Variable
.StartPtr
;
3066 // Variable is found
3068 if (Variable
.CurrPtr
->State
== VAR_ADDED
|| Variable
.CurrPtr
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)) {
3069 if (!AtRuntime () || ((Variable
.CurrPtr
->Attributes
& EFI_VARIABLE_RUNTIME_ACCESS
) != 0)) {
3070 if (Variable
.CurrPtr
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)) {
3072 // If it is a IN_DELETED_TRANSITION variable,
3073 // and there is also a same ADDED one at the same time,
3076 VariablePtrTrack
.StartPtr
= Variable
.StartPtr
;
3077 VariablePtrTrack
.EndPtr
= Variable
.EndPtr
;
3078 Status
= FindVariableEx (
3079 GetVariableNamePtr (Variable
.CurrPtr
),
3080 &Variable
.CurrPtr
->VendorGuid
,
3084 if (!EFI_ERROR (Status
) && VariablePtrTrack
.CurrPtr
->State
== VAR_ADDED
) {
3085 Variable
.CurrPtr
= GetNextVariablePtr (Variable
.CurrPtr
);
3091 // Don't return NV variable when HOB overrides it
3093 if ((VariableStoreHeader
[VariableStoreTypeHob
] != NULL
) && (VariableStoreHeader
[VariableStoreTypeNv
] != NULL
) &&
3094 (Variable
.StartPtr
== GetStartPointer (VariableStoreHeader
[VariableStoreTypeNv
]))
3096 VariableInHob
.StartPtr
= GetStartPointer (VariableStoreHeader
[VariableStoreTypeHob
]);
3097 VariableInHob
.EndPtr
= GetEndPointer (VariableStoreHeader
[VariableStoreTypeHob
]);
3098 Status
= FindVariableEx (
3099 GetVariableNamePtr (Variable
.CurrPtr
),
3100 &Variable
.CurrPtr
->VendorGuid
,
3104 if (!EFI_ERROR (Status
)) {
3105 Variable
.CurrPtr
= GetNextVariablePtr (Variable
.CurrPtr
);
3110 VarNameSize
= NameSizeOfVariable (Variable
.CurrPtr
);
3111 ASSERT (VarNameSize
!= 0);
3113 if (VarNameSize
<= *VariableNameSize
) {
3114 CopyMem (VariableName
, GetVariableNamePtr (Variable
.CurrPtr
), VarNameSize
);
3115 CopyMem (VendorGuid
, &Variable
.CurrPtr
->VendorGuid
, sizeof (EFI_GUID
));
3116 Status
= EFI_SUCCESS
;
3118 Status
= EFI_BUFFER_TOO_SMALL
;
3121 *VariableNameSize
= VarNameSize
;
3126 Variable
.CurrPtr
= GetNextVariablePtr (Variable
.CurrPtr
);
3130 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
3136 This code sets variable in storage blocks (Volatile or Non-Volatile).
3138 Caution: This function may receive untrusted input.
3139 This function may be invoked in SMM mode, and datasize and data are external input.
3140 This function will do basic validation, before parse the data.
3141 This function will parse the authentication carefully to avoid security issues, like
3142 buffer overflow, integer overflow.
3143 This function will check attribute carefully to avoid authentication bypass.
3145 @param VariableName Name of Variable to be found.
3146 @param VendorGuid Variable vendor GUID.
3147 @param Attributes Attribute value of the variable found
3148 @param DataSize Size of Data found. If size is less than the
3149 data, this value contains the required size.
3150 @param Data Data pointer.
3152 @return EFI_INVALID_PARAMETER Invalid parameter.
3153 @return EFI_SUCCESS Set successfully.
3154 @return EFI_OUT_OF_RESOURCES Resource not enough to set variable.
3155 @return EFI_NOT_FOUND Not found.
3156 @return EFI_WRITE_PROTECTED Variable is read-only.
3161 VariableServiceSetVariable (
3162 IN CHAR16
*VariableName
,
3163 IN EFI_GUID
*VendorGuid
,
3164 IN UINT32 Attributes
,
3169 VARIABLE_POINTER_TRACK Variable
;
3171 VARIABLE_HEADER
*NextVariable
;
3172 EFI_PHYSICAL_ADDRESS Point
;
3175 VARIABLE_ENTRY
*Entry
;
3179 // Check input parameters.
3181 if (VariableName
== NULL
|| VariableName
[0] == 0 || VendorGuid
== NULL
) {
3182 return EFI_INVALID_PARAMETER
;
3185 if (DataSize
!= 0 && Data
== NULL
) {
3186 return EFI_INVALID_PARAMETER
;
3190 // Check for reserverd bit in variable attribute.
3192 if ((Attributes
& (~EFI_VARIABLE_ATTRIBUTES_MASK
)) != 0) {
3193 return EFI_INVALID_PARAMETER
;
3197 // Make sure if runtime bit is set, boot service bit is set also.
3199 if ((Attributes
& (EFI_VARIABLE_RUNTIME_ACCESS
| EFI_VARIABLE_BOOTSERVICE_ACCESS
)) == EFI_VARIABLE_RUNTIME_ACCESS
) {
3200 return EFI_INVALID_PARAMETER
;
3204 // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute
3205 // cannot be set both.
3207 if (((Attributes
& EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
)
3208 && ((Attributes
& EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
)) {
3209 return EFI_INVALID_PARAMETER
;
3212 if ((Attributes
& EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
) {
3213 if (DataSize
< AUTHINFO_SIZE
) {
3215 // Try to write Authenticated Variable without AuthInfo.
3217 return EFI_SECURITY_VIOLATION
;
3219 PayloadSize
= DataSize
- AUTHINFO_SIZE
;
3220 } else if ((Attributes
& EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
) {
3222 // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor.
3224 if (DataSize
< OFFSET_OF_AUTHINFO2_CERT_DATA
||
3225 ((EFI_VARIABLE_AUTHENTICATION_2
*) Data
)->AuthInfo
.Hdr
.dwLength
> DataSize
- (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2
, AuthInfo
)) ||
3226 ((EFI_VARIABLE_AUTHENTICATION_2
*) Data
)->AuthInfo
.Hdr
.dwLength
< OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID
, CertData
)) {
3227 return EFI_SECURITY_VIOLATION
;
3229 PayloadSize
= DataSize
- AUTHINFO2_SIZE (Data
);
3231 PayloadSize
= DataSize
;
3234 if ((UINTN
)(~0) - PayloadSize
< StrSize(VariableName
)){
3236 // Prevent whole variable size overflow
3238 return EFI_INVALID_PARAMETER
;
3242 // The size of the VariableName, including the Unicode Null in bytes plus
3243 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)
3244 // bytes for HwErrRec.
3246 if ((Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
3247 if (StrSize (VariableName
) + PayloadSize
> PcdGet32 (PcdMaxHardwareErrorVariableSize
) - sizeof (VARIABLE_HEADER
)) {
3248 return EFI_INVALID_PARAMETER
;
3250 if (!IsHwErrRecVariable(VariableName
, VendorGuid
)) {
3251 return EFI_INVALID_PARAMETER
;
3255 // The size of the VariableName, including the Unicode Null in bytes plus
3256 // the DataSize is limited to maximum size of Max(Auth)VariableSize bytes.
3258 if ((Attributes
& VARIABLE_ATTRIBUTE_AT_AW
) != 0) {
3259 if (StrSize (VariableName
) + PayloadSize
> mVariableModuleGlobal
->MaxAuthVariableSize
- sizeof (VARIABLE_HEADER
)) {
3260 return EFI_INVALID_PARAMETER
;
3263 if (StrSize (VariableName
) + PayloadSize
> mVariableModuleGlobal
->MaxVariableSize
- sizeof (VARIABLE_HEADER
)) {
3264 return EFI_INVALID_PARAMETER
;
3269 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
3272 // Consider reentrant in MCA/INIT/NMI. It needs be reupdated.
3274 if (1 < InterlockedIncrement (&mVariableModuleGlobal
->VariableGlobal
.ReentrantState
)) {
3275 Point
= mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
;
3277 // Parse non-volatile variable data and get last variable offset.
3279 NextVariable
= GetStartPointer ((VARIABLE_STORE_HEADER
*) (UINTN
) Point
);
3280 while (IsValidVariableHeader (NextVariable
, GetEndPointer ((VARIABLE_STORE_HEADER
*) (UINTN
) Point
))) {
3281 NextVariable
= GetNextVariablePtr (NextVariable
);
3283 mVariableModuleGlobal
->NonVolatileLastVariableOffset
= (UINTN
) NextVariable
- (UINTN
) Point
;
3286 if (mEndOfDxe
&& mEnableLocking
) {
3288 // Treat the variables listed in the forbidden variable list as read-only after leaving DXE phase.
3290 for ( Link
= GetFirstNode (&mLockedVariableList
)
3291 ; !IsNull (&mLockedVariableList
, Link
)
3292 ; Link
= GetNextNode (&mLockedVariableList
, Link
)
3294 Entry
= BASE_CR (Link
, VARIABLE_ENTRY
, Link
);
3295 Name
= (CHAR16
*) ((UINTN
) Entry
+ sizeof (*Entry
));
3296 if (CompareGuid (&Entry
->Guid
, VendorGuid
) && (StrCmp (Name
, VariableName
) == 0)) {
3297 Status
= EFI_WRITE_PROTECTED
;
3298 DEBUG ((EFI_D_INFO
, "[Variable]: Changing readonly variable after leaving DXE phase - %g:%s\n", VendorGuid
, VariableName
));
3304 Status
= InternalVarCheckSetVariableCheck (VariableName
, VendorGuid
, Attributes
, PayloadSize
, (VOID
*) ((UINTN
) Data
+ DataSize
- PayloadSize
));
3305 if (EFI_ERROR (Status
)) {
3310 // Check whether the input variable is already existed.
3312 Status
= FindVariable (VariableName
, VendorGuid
, &Variable
, &mVariableModuleGlobal
->VariableGlobal
, TRUE
);
3313 if (!EFI_ERROR (Status
)) {
3314 if (((Variable
.CurrPtr
->Attributes
& EFI_VARIABLE_RUNTIME_ACCESS
) == 0) && AtRuntime ()) {
3315 Status
= EFI_WRITE_PROTECTED
;
3318 if (Attributes
!= 0 && (Attributes
& (~EFI_VARIABLE_APPEND_WRITE
)) != Variable
.CurrPtr
->Attributes
) {
3320 // If a preexisting variable is rewritten with different attributes, SetVariable() shall not
3321 // modify the variable and shall return EFI_INVALID_PARAMETER. Two exceptions to this rule:
3322 // 1. No access attributes specified
3323 // 2. The only attribute differing is EFI_VARIABLE_APPEND_WRITE
3325 Status
= EFI_INVALID_PARAMETER
;
3326 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
));
3331 if (!FeaturePcdGet (PcdUefiVariableDefaultLangDeprecate
)) {
3333 // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.
3335 Status
= AutoUpdateLangVariable (VariableName
, Data
, DataSize
);
3336 if (EFI_ERROR (Status
)) {
3338 // The auto update operation failed, directly return to avoid inconsistency between PlatformLang and Lang.
3345 // Process PK, KEK, Sigdb seperately.
3347 if (CompareGuid (VendorGuid
, &gEfiGlobalVariableGuid
) && (StrCmp (VariableName
, EFI_PLATFORM_KEY_NAME
) == 0)){
3348 Status
= ProcessVarWithPk (VariableName
, VendorGuid
, Data
, DataSize
, &Variable
, Attributes
, TRUE
);
3349 } else if (CompareGuid (VendorGuid
, &gEfiGlobalVariableGuid
) && (StrCmp (VariableName
, EFI_KEY_EXCHANGE_KEY_NAME
) == 0)) {
3350 Status
= ProcessVarWithPk (VariableName
, VendorGuid
, Data
, DataSize
, &Variable
, Attributes
, FALSE
);
3351 } else if (CompareGuid (VendorGuid
, &gEfiImageSecurityDatabaseGuid
) &&
3352 ((StrCmp (VariableName
, EFI_IMAGE_SECURITY_DATABASE
) == 0) ||
3353 (StrCmp (VariableName
, EFI_IMAGE_SECURITY_DATABASE1
) == 0) ||
3354 (StrCmp (VariableName
, EFI_IMAGE_SECURITY_DATABASE2
) == 0)
3357 Status
= ProcessVarWithPk (VariableName
, VendorGuid
, Data
, DataSize
, &Variable
, Attributes
, FALSE
);
3358 if (EFI_ERROR (Status
)) {
3359 Status
= ProcessVarWithKek (VariableName
, VendorGuid
, Data
, DataSize
, &Variable
, Attributes
);
3362 Status
= ProcessVariable (VariableName
, VendorGuid
, Data
, DataSize
, &Variable
, Attributes
);
3366 InterlockedDecrement (&mVariableModuleGlobal
->VariableGlobal
.ReentrantState
);
3367 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
3369 if (!AtRuntime ()) {
3370 if (!EFI_ERROR (Status
)) {
3383 This code returns information about the EFI variables.
3385 Caution: This function may receive untrusted input.
3386 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
3388 @param Attributes Attributes bitmask to specify the type of variables
3389 on which to return information.
3390 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
3391 for the EFI variables associated with the attributes specified.
3392 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
3393 for EFI variables associated with the attributes specified.
3394 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
3395 associated with the attributes specified.
3397 @return EFI_SUCCESS Query successfully.
3402 VariableServiceQueryVariableInfoInternal (
3403 IN UINT32 Attributes
,
3404 OUT UINT64
*MaximumVariableStorageSize
,
3405 OUT UINT64
*RemainingVariableStorageSize
,
3406 OUT UINT64
*MaximumVariableSize
3409 VARIABLE_HEADER
*Variable
;
3410 VARIABLE_HEADER
*NextVariable
;
3411 UINT64 VariableSize
;
3412 VARIABLE_STORE_HEADER
*VariableStoreHeader
;
3413 UINT64 CommonVariableTotalSize
;
3414 UINT64 HwErrVariableTotalSize
;
3416 VARIABLE_POINTER_TRACK VariablePtrTrack
;
3418 CommonVariableTotalSize
= 0;
3419 HwErrVariableTotalSize
= 0;
3421 if((Attributes
& EFI_VARIABLE_NON_VOLATILE
) == 0) {
3423 // Query is Volatile related.
3425 VariableStoreHeader
= (VARIABLE_STORE_HEADER
*) ((UINTN
) mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
);
3428 // Query is Non-Volatile related.
3430 VariableStoreHeader
= mNvVariableCache
;
3434 // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize
3435 // with the storage size (excluding the storage header size).
3437 *MaximumVariableStorageSize
= VariableStoreHeader
->Size
- sizeof (VARIABLE_STORE_HEADER
);
3440 // Harware error record variable needs larger size.
3442 if ((Attributes
& (EFI_VARIABLE_NON_VOLATILE
| EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) == (EFI_VARIABLE_NON_VOLATILE
| EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) {
3443 *MaximumVariableStorageSize
= PcdGet32 (PcdHwErrStorageSize
);
3444 *MaximumVariableSize
= PcdGet32 (PcdMaxHardwareErrorVariableSize
) - sizeof (VARIABLE_HEADER
);
3446 if ((Attributes
& EFI_VARIABLE_NON_VOLATILE
) != 0) {
3448 *MaximumVariableStorageSize
= mVariableModuleGlobal
->CommonRuntimeVariableSpace
;
3450 *MaximumVariableStorageSize
= mVariableModuleGlobal
->CommonVariableSpace
;
3455 // Let *MaximumVariableSize be Max(Auth)VariableSize with the exception of the variable header size.
3457 if ((Attributes
& VARIABLE_ATTRIBUTE_AT_AW
) != 0) {
3458 *MaximumVariableSize
= mVariableModuleGlobal
->MaxAuthVariableSize
- sizeof (VARIABLE_HEADER
);
3460 *MaximumVariableSize
= mVariableModuleGlobal
->MaxVariableSize
- sizeof (VARIABLE_HEADER
);
3465 // Point to the starting address of the variables.
3467 Variable
= GetStartPointer (VariableStoreHeader
);
3470 // Now walk through the related variable store.
3472 while (IsValidVariableHeader (Variable
, GetEndPointer (VariableStoreHeader
))) {
3473 NextVariable
= GetNextVariablePtr (Variable
);
3474 VariableSize
= (UINT64
) (UINTN
) NextVariable
- (UINT64
) (UINTN
) Variable
;
3478 // We don't take the state of the variables in mind
3479 // when calculating RemainingVariableStorageSize,
3480 // since the space occupied by variables not marked with
3481 // VAR_ADDED is not allowed to be reclaimed in Runtime.
3483 if ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
3484 HwErrVariableTotalSize
+= VariableSize
;
3486 CommonVariableTotalSize
+= VariableSize
;
3490 // Only care about Variables with State VAR_ADDED, because
3491 // the space not marked as VAR_ADDED is reclaimable now.
3493 if (Variable
->State
== VAR_ADDED
) {
3494 if ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
3495 HwErrVariableTotalSize
+= VariableSize
;
3497 CommonVariableTotalSize
+= VariableSize
;
3499 } else if (Variable
->State
== (VAR_IN_DELETED_TRANSITION
& VAR_ADDED
)) {
3501 // If it is a IN_DELETED_TRANSITION variable,
3502 // and there is not also a same ADDED one at the same time,
3503 // this IN_DELETED_TRANSITION variable is valid.
3505 VariablePtrTrack
.StartPtr
= GetStartPointer (VariableStoreHeader
);
3506 VariablePtrTrack
.EndPtr
= GetEndPointer (VariableStoreHeader
);
3507 Status
= FindVariableEx (
3508 GetVariableNamePtr (Variable
),
3509 &Variable
->VendorGuid
,
3513 if (!EFI_ERROR (Status
) && VariablePtrTrack
.CurrPtr
->State
!= VAR_ADDED
) {
3514 if ((Variable
->Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
3515 HwErrVariableTotalSize
+= VariableSize
;
3517 CommonVariableTotalSize
+= VariableSize
;
3524 // Go to the next one.
3526 Variable
= NextVariable
;
3529 if ((Attributes
& EFI_VARIABLE_HARDWARE_ERROR_RECORD
) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
){
3530 *RemainingVariableStorageSize
= *MaximumVariableStorageSize
- HwErrVariableTotalSize
;
3532 if (*MaximumVariableStorageSize
< CommonVariableTotalSize
) {
3533 *RemainingVariableStorageSize
= 0;
3535 *RemainingVariableStorageSize
= *MaximumVariableStorageSize
- CommonVariableTotalSize
;
3539 if (*RemainingVariableStorageSize
< sizeof (VARIABLE_HEADER
)) {
3540 *MaximumVariableSize
= 0;
3541 } else if ((*RemainingVariableStorageSize
- sizeof (VARIABLE_HEADER
)) < *MaximumVariableSize
) {
3542 *MaximumVariableSize
= *RemainingVariableStorageSize
- sizeof (VARIABLE_HEADER
);
3550 This code returns information about the EFI variables.
3552 Caution: This function may receive untrusted input.
3553 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
3555 @param Attributes Attributes bitmask to specify the type of variables
3556 on which to return information.
3557 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
3558 for the EFI variables associated with the attributes specified.
3559 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
3560 for EFI variables associated with the attributes specified.
3561 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
3562 associated with the attributes specified.
3564 @return EFI_INVALID_PARAMETER An invalid combination of attribute bits was supplied.
3565 @return EFI_SUCCESS Query successfully.
3566 @return EFI_UNSUPPORTED The attribute is not supported on this platform.
3571 VariableServiceQueryVariableInfo (
3572 IN UINT32 Attributes
,
3573 OUT UINT64
*MaximumVariableStorageSize
,
3574 OUT UINT64
*RemainingVariableStorageSize
,
3575 OUT UINT64
*MaximumVariableSize
3580 if(MaximumVariableStorageSize
== NULL
|| RemainingVariableStorageSize
== NULL
|| MaximumVariableSize
== NULL
|| Attributes
== 0) {
3581 return EFI_INVALID_PARAMETER
;
3584 if ((Attributes
& VARIABLE_ATTRIBUTE_NV_BS_RT_AT_HR_AW
) == 0) {
3586 // Make sure the Attributes combination is supported by the platform.
3588 return EFI_UNSUPPORTED
;
3589 } else if ((Attributes
& (EFI_VARIABLE_RUNTIME_ACCESS
| EFI_VARIABLE_BOOTSERVICE_ACCESS
)) == EFI_VARIABLE_RUNTIME_ACCESS
) {
3591 // Make sure if runtime bit is set, boot service bit is set also.
3593 return EFI_INVALID_PARAMETER
;
3594 } else if (AtRuntime () && ((Attributes
& EFI_VARIABLE_RUNTIME_ACCESS
) == 0)) {
3596 // Make sure RT Attribute is set if we are in Runtime phase.
3598 return EFI_INVALID_PARAMETER
;
3599 } else if ((Attributes
& (EFI_VARIABLE_NON_VOLATILE
| EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD
) {
3601 // Make sure Hw Attribute is set with NV.
3603 return EFI_INVALID_PARAMETER
;
3606 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
3608 Status
= VariableServiceQueryVariableInfoInternal (
3610 MaximumVariableStorageSize
,
3611 RemainingVariableStorageSize
,
3615 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
);
3620 This function reclaims variable storage if free size is below the threshold.
3622 Caution: This function may be invoked at SMM mode.
3623 Care must be taken to make sure not security issue.
3632 UINTN RemainingCommonRuntimeVariableSpace
;
3633 UINTN RemainingHwErrVariableSpace
;
3634 STATIC BOOLEAN Reclaimed
;
3637 // This function will be called only once at EndOfDxe or ReadyToBoot event.
3644 Status
= EFI_SUCCESS
;
3646 if (mVariableModuleGlobal
->CommonRuntimeVariableSpace
< mVariableModuleGlobal
->CommonVariableTotalSize
) {
3647 RemainingCommonRuntimeVariableSpace
= 0;
3649 RemainingCommonRuntimeVariableSpace
= mVariableModuleGlobal
->CommonRuntimeVariableSpace
- mVariableModuleGlobal
->CommonVariableTotalSize
;
3652 RemainingHwErrVariableSpace
= PcdGet32 (PcdHwErrStorageSize
) - mVariableModuleGlobal
->HwErrVariableTotalSize
;
3655 // Check if the free area is below a threshold.
3657 if (((RemainingCommonRuntimeVariableSpace
< mVariableModuleGlobal
->MaxVariableSize
) ||
3658 (RemainingCommonRuntimeVariableSpace
< mVariableModuleGlobal
->MaxAuthVariableSize
)) ||
3659 ((PcdGet32 (PcdHwErrStorageSize
) != 0) &&
3660 (RemainingHwErrVariableSpace
< PcdGet32 (PcdMaxHardwareErrorVariableSize
)))){
3662 mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
,
3663 &mVariableModuleGlobal
->NonVolatileLastVariableOffset
,
3670 ASSERT_EFI_ERROR (Status
);
3675 Init non-volatile variable store.
3677 @retval EFI_SUCCESS Function successfully executed.
3678 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
3679 @retval EFI_VOLUME_CORRUPTED Variable Store or Firmware Volume for Variable Store is corrupted.
3683 InitNonVolatileVariableStore (
3687 EFI_FIRMWARE_VOLUME_HEADER
*FvHeader
;
3688 VARIABLE_HEADER
*Variable
;
3689 VARIABLE_HEADER
*NextVariable
;
3690 EFI_PHYSICAL_ADDRESS VariableStoreBase
;
3691 UINT64 VariableStoreLength
;
3693 EFI_HOB_GUID_TYPE
*GuidHob
;
3694 EFI_PHYSICAL_ADDRESS NvStorageBase
;
3695 UINT8
*NvStorageData
;
3696 UINT32 NvStorageSize
;
3697 FAULT_TOLERANT_WRITE_LAST_WRITE_DATA
*FtwLastWriteData
;
3698 UINT32 BackUpOffset
;
3700 UINT32 HwErrStorageSize
;
3701 UINT32 MaxUserNvVariableSpaceSize
;
3702 UINT32 BoottimeReservedNvVariableSpaceSize
;
3704 mVariableModuleGlobal
->FvbInstance
= NULL
;
3707 // Allocate runtime memory used for a memory copy of the FLASH region.
3708 // Keep the memory and the FLASH in sync as updates occur.
3710 NvStorageSize
= PcdGet32 (PcdFlashNvStorageVariableSize
);
3711 NvStorageData
= AllocateRuntimeZeroPool (NvStorageSize
);
3712 if (NvStorageData
== NULL
) {
3713 return EFI_OUT_OF_RESOURCES
;
3716 NvStorageBase
= (EFI_PHYSICAL_ADDRESS
) PcdGet64 (PcdFlashNvStorageVariableBase64
);
3717 if (NvStorageBase
== 0) {
3718 NvStorageBase
= (EFI_PHYSICAL_ADDRESS
) PcdGet32 (PcdFlashNvStorageVariableBase
);
3721 // Copy NV storage data to the memory buffer.
3723 CopyMem (NvStorageData
, (UINT8
*) (UINTN
) NvStorageBase
, NvStorageSize
);
3726 // Check the FTW last write data hob.
3728 GuidHob
= GetFirstGuidHob (&gEdkiiFaultTolerantWriteGuid
);
3729 if (GuidHob
!= NULL
) {
3730 FtwLastWriteData
= (FAULT_TOLERANT_WRITE_LAST_WRITE_DATA
*) GET_GUID_HOB_DATA (GuidHob
);
3731 if (FtwLastWriteData
->TargetAddress
== NvStorageBase
) {
3732 DEBUG ((EFI_D_INFO
, "Variable: NV storage is backed up in spare block: 0x%x\n", (UINTN
) FtwLastWriteData
->SpareAddress
));
3734 // Copy the backed up NV storage data to the memory buffer from spare block.
3736 CopyMem (NvStorageData
, (UINT8
*) (UINTN
) (FtwLastWriteData
->SpareAddress
), NvStorageSize
);
3737 } else if ((FtwLastWriteData
->TargetAddress
> NvStorageBase
) &&
3738 (FtwLastWriteData
->TargetAddress
< (NvStorageBase
+ NvStorageSize
))) {
3740 // Flash NV storage from the Offset is backed up in spare block.
3742 BackUpOffset
= (UINT32
) (FtwLastWriteData
->TargetAddress
- NvStorageBase
);
3743 BackUpSize
= NvStorageSize
- BackUpOffset
;
3744 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
));
3746 // Copy the partial backed up NV storage data to the memory buffer from spare block.
3748 CopyMem (NvStorageData
+ BackUpOffset
, (UINT8
*) (UINTN
) FtwLastWriteData
->SpareAddress
, BackUpSize
);
3752 FvHeader
= (EFI_FIRMWARE_VOLUME_HEADER
*) NvStorageData
;
3755 // Check if the Firmware Volume is not corrupted
3757 if ((FvHeader
->Signature
!= EFI_FVH_SIGNATURE
) || (!CompareGuid (&gEfiSystemNvDataFvGuid
, &FvHeader
->FileSystemGuid
))) {
3758 FreePool (NvStorageData
);
3759 DEBUG ((EFI_D_ERROR
, "Firmware Volume for Variable Store is corrupted\n"));
3760 return EFI_VOLUME_CORRUPTED
;
3763 VariableStoreBase
= (EFI_PHYSICAL_ADDRESS
) ((UINTN
) FvHeader
+ FvHeader
->HeaderLength
);
3764 VariableStoreLength
= (UINT64
) (NvStorageSize
- FvHeader
->HeaderLength
);
3766 mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
= VariableStoreBase
;
3767 mNvVariableCache
= (VARIABLE_STORE_HEADER
*) (UINTN
) VariableStoreBase
;
3768 if (GetVariableStoreStatus (mNvVariableCache
) != EfiValid
) {
3769 FreePool (NvStorageData
);
3770 DEBUG((EFI_D_ERROR
, "Variable Store header is corrupted\n"));
3771 return EFI_VOLUME_CORRUPTED
;
3773 ASSERT(mNvVariableCache
->Size
== VariableStoreLength
);
3776 ASSERT (sizeof (VARIABLE_STORE_HEADER
) <= VariableStoreLength
);
3778 HwErrStorageSize
= PcdGet32 (PcdHwErrStorageSize
);
3779 MaxUserNvVariableSpaceSize
= PcdGet32 (PcdMaxUserNvVariableSpaceSize
);
3780 BoottimeReservedNvVariableSpaceSize
= PcdGet32 (PcdBoottimeReservedNvVariableSpaceSize
);
3783 // Note that in EdkII variable driver implementation, Hardware Error Record type variable
3784 // is stored with common variable in the same NV region. So the platform integrator should
3785 // ensure that the value of PcdHwErrStorageSize is less than the value of
3786 // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).
3788 ASSERT (HwErrStorageSize
< (VariableStoreLength
- sizeof (VARIABLE_STORE_HEADER
)));
3790 // Ensure that the value of PcdMaxUserNvVariableSpaceSize is less than the value of
3791 // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).
3793 ASSERT (MaxUserNvVariableSpaceSize
< (VariableStoreLength
- sizeof (VARIABLE_STORE_HEADER
) - HwErrStorageSize
));
3795 // Ensure that the value of PcdBoottimeReservedNvVariableSpaceSize is less than the value of
3796 // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).
3798 ASSERT (BoottimeReservedNvVariableSpaceSize
< (VariableStoreLength
- sizeof (VARIABLE_STORE_HEADER
) - HwErrStorageSize
));
3800 mVariableModuleGlobal
->CommonVariableSpace
= ((UINTN
) VariableStoreLength
- sizeof (VARIABLE_STORE_HEADER
) - HwErrStorageSize
);
3801 mVariableModuleGlobal
->CommonMaxUserVariableSpace
= ((MaxUserNvVariableSpaceSize
!= 0) ? MaxUserNvVariableSpaceSize
: mVariableModuleGlobal
->CommonVariableSpace
);
3802 mVariableModuleGlobal
->CommonRuntimeVariableSpace
= mVariableModuleGlobal
->CommonVariableSpace
- BoottimeReservedNvVariableSpaceSize
;
3804 DEBUG ((EFI_D_INFO
, "Variable driver common space: 0x%x 0x%x 0x%x\n", mVariableModuleGlobal
->CommonVariableSpace
, mVariableModuleGlobal
->CommonMaxUserVariableSpace
, mVariableModuleGlobal
->CommonRuntimeVariableSpace
));
3807 // The max NV variable size should be < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).
3809 ASSERT (MAX_NV_VARIABLE_SIZE
< (VariableStoreLength
- sizeof (VARIABLE_STORE_HEADER
)));
3811 mVariableModuleGlobal
->MaxVariableSize
= PcdGet32 (PcdMaxVariableSize
);
3812 mVariableModuleGlobal
->MaxAuthVariableSize
= ((PcdGet32 (PcdMaxAuthVariableSize
) != 0) ? PcdGet32 (PcdMaxAuthVariableSize
) : mVariableModuleGlobal
->MaxVariableSize
);
3815 // Parse non-volatile variable data and get last variable offset.
3817 Variable
= GetStartPointer ((VARIABLE_STORE_HEADER
*)(UINTN
)VariableStoreBase
);
3818 while (IsValidVariableHeader (Variable
, GetEndPointer ((VARIABLE_STORE_HEADER
*)(UINTN
)VariableStoreBase
))) {
3819 NextVariable
= GetNextVariablePtr (Variable
);
3820 VariableSize
= (UINTN
) NextVariable
- (UINTN
) Variable
;
3821 if ((Variable
->Attributes
& (EFI_VARIABLE_NON_VOLATILE
| EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) == (EFI_VARIABLE_NON_VOLATILE
| EFI_VARIABLE_HARDWARE_ERROR_RECORD
)) {
3822 mVariableModuleGlobal
->HwErrVariableTotalSize
+= VariableSize
;
3824 mVariableModuleGlobal
->CommonVariableTotalSize
+= VariableSize
;
3827 Variable
= NextVariable
;
3829 mVariableModuleGlobal
->NonVolatileLastVariableOffset
= (UINTN
) Variable
- (UINTN
) VariableStoreBase
;
3835 Flush the HOB variable to flash.
3837 @param[in] VariableName Name of variable has been updated or deleted.
3838 @param[in] VendorGuid Guid of variable has been updated or deleted.
3842 FlushHobVariableToFlash (
3843 IN CHAR16
*VariableName
,
3844 IN EFI_GUID
*VendorGuid
3848 VARIABLE_STORE_HEADER
*VariableStoreHeader
;
3849 VARIABLE_HEADER
*Variable
;
3856 // Flush the HOB variable to flash.
3858 if (mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
!= 0) {
3859 VariableStoreHeader
= (VARIABLE_STORE_HEADER
*) (UINTN
) mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
;
3861 // Set HobVariableBase to 0, it can avoid SetVariable to call back.
3863 mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
= 0;
3864 for ( Variable
= GetStartPointer (VariableStoreHeader
)
3865 ; IsValidVariableHeader (Variable
, GetEndPointer (VariableStoreHeader
))
3866 ; Variable
= GetNextVariablePtr (Variable
)
3868 if (Variable
->State
!= VAR_ADDED
) {
3870 // The HOB variable has been set to DELETED state in local.
3874 ASSERT ((Variable
->Attributes
& EFI_VARIABLE_NON_VOLATILE
) != 0);
3875 if (VendorGuid
== NULL
|| VariableName
== NULL
||
3876 !CompareGuid (VendorGuid
, &Variable
->VendorGuid
) ||
3877 StrCmp (VariableName
, GetVariableNamePtr (Variable
)) != 0) {
3878 VariableData
= GetVariableDataPtr (Variable
);
3879 Status
= VariableServiceSetVariable (
3880 GetVariableNamePtr (Variable
),
3881 &Variable
->VendorGuid
,
3882 Variable
->Attributes
,
3886 DEBUG ((EFI_D_INFO
, "Variable driver flush the HOB variable to flash: %g %s %r\n", &Variable
->VendorGuid
, GetVariableNamePtr (Variable
), Status
));
3889 // The updated or deleted variable is matched with the HOB variable.
3890 // Don't break here because we will try to set other HOB variables
3891 // since this variable could be set successfully.
3893 Status
= EFI_SUCCESS
;
3895 if (!EFI_ERROR (Status
)) {
3897 // If set variable successful, or the updated or deleted variable is matched with the HOB variable,
3898 // set the HOB variable to DELETED state in local.
3900 DEBUG ((EFI_D_INFO
, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", &Variable
->VendorGuid
, GetVariableNamePtr (Variable
)));
3901 Variable
->State
&= VAR_DELETED
;
3908 // We still have HOB variable(s) not flushed in flash.
3910 mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
= (EFI_PHYSICAL_ADDRESS
) (UINTN
) VariableStoreHeader
;
3913 // All HOB variables have been flushed in flash.
3915 DEBUG ((EFI_D_INFO
, "Variable driver: all HOB variables have been flushed in flash.\n"));
3916 if (!AtRuntime ()) {
3917 FreePool ((VOID
*) VariableStoreHeader
);
3925 Initializes variable write service after FTW was ready.
3927 @retval EFI_SUCCESS Function successfully executed.
3928 @retval Others Fail to initialize the variable service.
3932 VariableWriteServiceInitialize (
3937 VARIABLE_STORE_HEADER
*VariableStoreHeader
;
3940 EFI_PHYSICAL_ADDRESS VariableStoreBase
;
3941 EFI_PHYSICAL_ADDRESS NvStorageBase
;
3943 NvStorageBase
= (EFI_PHYSICAL_ADDRESS
) PcdGet64 (PcdFlashNvStorageVariableBase64
);
3944 if (NvStorageBase
== 0) {
3945 NvStorageBase
= (EFI_PHYSICAL_ADDRESS
) PcdGet32 (PcdFlashNvStorageVariableBase
);
3947 VariableStoreBase
= NvStorageBase
+ (((EFI_FIRMWARE_VOLUME_HEADER
*)(UINTN
)(NvStorageBase
))->HeaderLength
);
3950 // Let NonVolatileVariableBase point to flash variable store base directly after FTW ready.
3952 mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
= VariableStoreBase
;
3953 VariableStoreHeader
= (VARIABLE_STORE_HEADER
*)(UINTN
)VariableStoreBase
;
3956 // Check if the free area is really free.
3958 for (Index
= mVariableModuleGlobal
->NonVolatileLastVariableOffset
; Index
< VariableStoreHeader
->Size
; Index
++) {
3959 Data
= ((UINT8
*) mNvVariableCache
)[Index
];
3962 // There must be something wrong in variable store, do reclaim operation.
3965 mVariableModuleGlobal
->VariableGlobal
.NonVolatileVariableBase
,
3966 &mVariableModuleGlobal
->NonVolatileLastVariableOffset
,
3973 if (EFI_ERROR (Status
)) {
3980 FlushHobVariableToFlash (NULL
, NULL
);
3983 // Authenticated variable initialize.
3985 Status
= AutenticatedVariableServiceInitialize (mVariableModuleGlobal
->MaxAuthVariableSize
- sizeof (VARIABLE_HEADER
));
3992 Initializes variable store area for non-volatile and volatile variable.
3994 @retval EFI_SUCCESS Function successfully executed.
3995 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
3999 VariableCommonInitialize (
4004 VARIABLE_STORE_HEADER
*VolatileVariableStore
;
4005 VARIABLE_STORE_HEADER
*VariableStoreHeader
;
4006 UINT64 VariableStoreLength
;
4008 EFI_HOB_GUID_TYPE
*GuidHob
;
4011 // Allocate runtime memory for variable driver global structure.
4013 mVariableModuleGlobal
= AllocateRuntimeZeroPool (sizeof (VARIABLE_MODULE_GLOBAL
));
4014 if (mVariableModuleGlobal
== NULL
) {
4015 return EFI_OUT_OF_RESOURCES
;
4018 InitializeLock (&mVariableModuleGlobal
->VariableGlobal
.VariableServicesLock
, TPL_NOTIFY
);
4021 // Get HOB variable store.
4023 GuidHob
= GetFirstGuidHob (&gEfiAuthenticatedVariableGuid
);
4024 if (GuidHob
!= NULL
) {
4025 VariableStoreHeader
= GET_GUID_HOB_DATA (GuidHob
);
4026 VariableStoreLength
= (UINT64
) (GuidHob
->Header
.HobLength
- sizeof (EFI_HOB_GUID_TYPE
));
4027 if (GetVariableStoreStatus (VariableStoreHeader
) == EfiValid
) {
4028 mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
= (EFI_PHYSICAL_ADDRESS
) (UINTN
) AllocateRuntimeCopyPool ((UINTN
) VariableStoreLength
, (VOID
*) VariableStoreHeader
);
4029 if (mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
== 0) {
4030 FreePool (mVariableModuleGlobal
);
4031 return EFI_OUT_OF_RESOURCES
;
4034 DEBUG ((EFI_D_ERROR
, "HOB Variable Store header is corrupted!\n"));
4039 // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.
4041 ScratchSize
= MAX_NV_VARIABLE_SIZE
;
4042 mVariableModuleGlobal
->ScratchBufferSize
= ScratchSize
;
4043 VolatileVariableStore
= AllocateRuntimePool (PcdGet32 (PcdVariableStoreSize
) + ScratchSize
);
4044 if (VolatileVariableStore
== NULL
) {
4045 if (mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
!= 0) {
4046 FreePool ((VOID
*) (UINTN
) mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
);
4048 FreePool (mVariableModuleGlobal
);
4049 return EFI_OUT_OF_RESOURCES
;
4052 SetMem (VolatileVariableStore
, PcdGet32 (PcdVariableStoreSize
) + ScratchSize
, 0xff);
4055 // Initialize Variable Specific Data.
4057 mVariableModuleGlobal
->VariableGlobal
.VolatileVariableBase
= (EFI_PHYSICAL_ADDRESS
) (UINTN
) VolatileVariableStore
;
4058 mVariableModuleGlobal
->VolatileLastVariableOffset
= (UINTN
) GetStartPointer (VolatileVariableStore
) - (UINTN
) VolatileVariableStore
;
4060 CopyGuid (&VolatileVariableStore
->Signature
, &gEfiAuthenticatedVariableGuid
);
4061 VolatileVariableStore
->Size
= PcdGet32 (PcdVariableStoreSize
);
4062 VolatileVariableStore
->Format
= VARIABLE_STORE_FORMATTED
;
4063 VolatileVariableStore
->State
= VARIABLE_STORE_HEALTHY
;
4064 VolatileVariableStore
->Reserved
= 0;
4065 VolatileVariableStore
->Reserved1
= 0;
4068 // Init non-volatile variable store.
4070 Status
= InitNonVolatileVariableStore ();
4071 if (EFI_ERROR (Status
)) {
4072 if (mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
!= 0) {
4073 FreePool ((VOID
*) (UINTN
) mVariableModuleGlobal
->VariableGlobal
.HobVariableBase
);
4075 FreePool (mVariableModuleGlobal
);
4076 FreePool (VolatileVariableStore
);
4084 Get the proper fvb handle and/or fvb protocol by the given Flash address.
4086 @param[in] Address The Flash address.
4087 @param[out] FvbHandle In output, if it is not NULL, it points to the proper FVB handle.
4088 @param[out] FvbProtocol In output, if it is not NULL, it points to the proper FVB protocol.
4092 GetFvbInfoByAddress (
4093 IN EFI_PHYSICAL_ADDRESS Address
,
4094 OUT EFI_HANDLE
*FvbHandle OPTIONAL
,
4095 OUT EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL
**FvbProtocol OPTIONAL
4099 EFI_HANDLE
*HandleBuffer
;
4102 EFI_PHYSICAL_ADDRESS FvbBaseAddress
;
4103 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL
*Fvb
;
4104 EFI_FVB_ATTRIBUTES_2 Attributes
;
4106 UINTN NumberOfBlocks
;
4108 HandleBuffer
= NULL
;
4110 // Get all FVB handles.
4112 Status
= GetFvbCountAndBuffer (&HandleCount
, &HandleBuffer
);
4113 if (EFI_ERROR (Status
)) {
4114 return EFI_NOT_FOUND
;
4118 // Get the FVB to access variable store.
4121 for (Index
= 0; Index
< HandleCount
; Index
+= 1, Status
= EFI_NOT_FOUND
, Fvb
= NULL
) {
4122 Status
= GetFvbByHandle (HandleBuffer
[Index
], &Fvb
);
4123 if (EFI_ERROR (Status
)) {
4124 Status
= EFI_NOT_FOUND
;
4129 // Ensure this FVB protocol supported Write operation.
4131 Status
= Fvb
->GetAttributes (Fvb
, &Attributes
);
4132 if (EFI_ERROR (Status
) || ((Attributes
& EFI_FVB2_WRITE_STATUS
) == 0)) {
4137 // Compare the address and select the right one.
4139 Status
= Fvb
->GetPhysicalAddress (Fvb
, &FvbBaseAddress
);
4140 if (EFI_ERROR (Status
)) {
4145 // Assume one FVB has one type of BlockSize.
4147 Status
= Fvb
->GetBlockSize (Fvb
, 0, &BlockSize
, &NumberOfBlocks
);
4148 if (EFI_ERROR (Status
)) {
4152 if ((Address
>= FvbBaseAddress
) && (Address
< (FvbBaseAddress
+ BlockSize
* NumberOfBlocks
))) {
4153 if (FvbHandle
!= NULL
) {
4154 *FvbHandle
= HandleBuffer
[Index
];
4156 if (FvbProtocol
!= NULL
) {
4159 Status
= EFI_SUCCESS
;
4163 FreePool (HandleBuffer
);
4166 Status
= EFI_NOT_FOUND
;