3c99367e7608777ec48354041eb281eb527e80a7
[mirror_edk2.git] / MdeModulePkg / Universal / Variable / RuntimeDxe / Variable.c
1 /** @file
2 The common variable operation routines shared by DXE_RUNTIME variable
3 module and DXE_SMM variable module.
4
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.
9
10 VariableServiceGetNextVariableName () and VariableServiceQueryVariableInfo() are external API.
11 They need check input parameter.
12
13 VariableServiceGetVariable() and VariableServiceSetVariable() are external API
14 to receive datasize and data buffer. The size should be checked carefully.
15
16 VariableServiceSetVariable() should also check authenticate data to avoid buffer overflow,
17 integer overflow. It should also check attribute to avoid authentication bypass.
18
19 Copyright (c) 2006 - 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
24
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.
27
28 **/
29
30 #include "Variable.h"
31
32 VARIABLE_MODULE_GLOBAL *mVariableModuleGlobal;
33
34 ///
35 /// Define a memory cache that improves the search performance for a variable.
36 ///
37 VARIABLE_STORE_HEADER *mNvVariableCache = NULL;
38
39 ///
40 /// The memory entry used for variable statistics data.
41 ///
42 VARIABLE_INFO_ENTRY *gVariableInfo = NULL;
43
44 ///
45 /// The list to store the variables which cannot be set after the EFI_END_OF_DXE_EVENT_GROUP_GUID
46 /// or EVT_GROUP_READY_TO_BOOT event.
47 ///
48 LIST_ENTRY mLockedVariableList = INITIALIZE_LIST_HEAD_VARIABLE (mLockedVariableList);
49
50 ///
51 /// The flag to indicate whether the platform has left the DXE phase of execution.
52 ///
53 BOOLEAN mEndOfDxe = FALSE;
54
55 ///
56 /// The flag to indicate whether the variable storage locking is enabled.
57 ///
58 BOOLEAN mEnableLocking = TRUE;
59
60 //
61 // It will record the current boot error flag before EndOfDxe.
62 //
63 VAR_ERROR_FLAG mCurrentBootVarErrFlag = VAR_ERROR_FLAG_NO_ERROR;
64
65 VARIABLE_ENTRY_PROPERTY mVariableEntryProperty[] = {
66 {
67 &gEdkiiVarErrorFlagGuid,
68 VAR_ERROR_FLAG_NAME,
69 {
70 VAR_CHECK_VARIABLE_PROPERTY_REVISION,
71 VAR_CHECK_VARIABLE_PROPERTY_READ_ONLY,
72 VARIABLE_ATTRIBUTE_NV_BS_RT,
73 sizeof (VAR_ERROR_FLAG),
74 sizeof (VAR_ERROR_FLAG)
75 }
76 },
77 };
78
79 AUTH_VAR_LIB_CONTEXT_IN mContextIn = {
80 AUTH_VAR_LIB_CONTEXT_IN_STRUCT_VERSION,
81 //
82 // StructSize, TO BE FILLED
83 //
84 0,
85 //
86 // MaxAuthVariableSize, TO BE FILLED
87 //
88 0,
89 VariableExLibFindVariable,
90 VariableExLibFindNextVariable,
91 VariableExLibUpdateVariable,
92 VariableExLibGetScratchBuffer,
93 VariableExLibCheckRemainingSpaceForConsistency,
94 VariableExLibAtRuntime,
95 };
96
97 AUTH_VAR_LIB_CONTEXT_OUT mContextOut;
98
99 /**
100
101 SecureBoot Hook for auth variable update.
102
103 @param[in] VariableName Name of Variable to be found.
104 @param[in] VendorGuid Variable vendor GUID.
105 **/
106 VOID
107 EFIAPI
108 SecureBootHook (
109 IN CHAR16 *VariableName,
110 IN EFI_GUID *VendorGuid
111 );
112
113 /**
114 Routine used to track statistical information about variable usage.
115 The data is stored in the EFI system table so it can be accessed later.
116 VariableInfo.efi can dump out the table. Only Boot Services variable
117 accesses are tracked by this code. The PcdVariableCollectStatistics
118 build flag controls if this feature is enabled.
119
120 A read that hits in the cache will have Read and Cache true for
121 the transaction. Data is allocated by this routine, but never
122 freed.
123
124 @param[in] VariableName Name of the Variable to track.
125 @param[in] VendorGuid Guid of the Variable to track.
126 @param[in] Volatile TRUE if volatile FALSE if non-volatile.
127 @param[in] Read TRUE if GetVariable() was called.
128 @param[in] Write TRUE if SetVariable() was called.
129 @param[in] Delete TRUE if deleted via SetVariable().
130 @param[in] Cache TRUE for a cache hit.
131
132 **/
133 VOID
134 UpdateVariableInfo (
135 IN CHAR16 *VariableName,
136 IN EFI_GUID *VendorGuid,
137 IN BOOLEAN Volatile,
138 IN BOOLEAN Read,
139 IN BOOLEAN Write,
140 IN BOOLEAN Delete,
141 IN BOOLEAN Cache
142 )
143 {
144 VARIABLE_INFO_ENTRY *Entry;
145
146 if (FeaturePcdGet (PcdVariableCollectStatistics)) {
147
148 if (AtRuntime ()) {
149 // Don't collect statistics at runtime.
150 return;
151 }
152
153 if (gVariableInfo == NULL) {
154 //
155 // On the first call allocate a entry and place a pointer to it in
156 // the EFI System Table.
157 //
158 gVariableInfo = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY));
159 ASSERT (gVariableInfo != NULL);
160
161 CopyGuid (&gVariableInfo->VendorGuid, VendorGuid);
162 gVariableInfo->Name = AllocateZeroPool (StrSize (VariableName));
163 ASSERT (gVariableInfo->Name != NULL);
164 StrCpyS (gVariableInfo->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);
165 gVariableInfo->Volatile = Volatile;
166 }
167
168
169 for (Entry = gVariableInfo; Entry != NULL; Entry = Entry->Next) {
170 if (CompareGuid (VendorGuid, &Entry->VendorGuid)) {
171 if (StrCmp (VariableName, Entry->Name) == 0) {
172 if (Read) {
173 Entry->ReadCount++;
174 }
175 if (Write) {
176 Entry->WriteCount++;
177 }
178 if (Delete) {
179 Entry->DeleteCount++;
180 }
181 if (Cache) {
182 Entry->CacheCount++;
183 }
184
185 return;
186 }
187 }
188
189 if (Entry->Next == NULL) {
190 //
191 // If the entry is not in the table add it.
192 // Next iteration of the loop will fill in the data.
193 //
194 Entry->Next = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY));
195 ASSERT (Entry->Next != NULL);
196
197 CopyGuid (&Entry->Next->VendorGuid, VendorGuid);
198 Entry->Next->Name = AllocateZeroPool (StrSize (VariableName));
199 ASSERT (Entry->Next->Name != NULL);
200 StrCpyS (Entry->Next->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);
201 Entry->Next->Volatile = Volatile;
202 }
203
204 }
205 }
206 }
207
208
209 /**
210
211 This code checks if variable header is valid or not.
212
213 @param Variable Pointer to the Variable Header.
214 @param VariableStoreEnd Pointer to the Variable Store End.
215
216 @retval TRUE Variable header is valid.
217 @retval FALSE Variable header is not valid.
218
219 **/
220 BOOLEAN
221 IsValidVariableHeader (
222 IN VARIABLE_HEADER *Variable,
223 IN VARIABLE_HEADER *VariableStoreEnd
224 )
225 {
226 if ((Variable == NULL) || (Variable >= VariableStoreEnd) || (Variable->StartId != VARIABLE_DATA)) {
227 //
228 // Variable is NULL or has reached the end of variable store,
229 // or the StartId is not correct.
230 //
231 return FALSE;
232 }
233
234 return TRUE;
235 }
236
237
238 /**
239
240 This function writes data to the FWH at the correct LBA even if the LBAs
241 are fragmented.
242
243 @param Global Pointer to VARAIBLE_GLOBAL structure.
244 @param Volatile Point out the Variable is Volatile or Non-Volatile.
245 @param SetByIndex TRUE if target pointer is given as index.
246 FALSE if target pointer is absolute.
247 @param Fvb Pointer to the writable FVB protocol.
248 @param DataPtrIndex Pointer to the Data from the end of VARIABLE_STORE_HEADER
249 structure.
250 @param DataSize Size of data to be written.
251 @param Buffer Pointer to the buffer from which data is written.
252
253 @retval EFI_INVALID_PARAMETER Parameters not valid.
254 @retval EFI_SUCCESS Variable store successfully updated.
255
256 **/
257 EFI_STATUS
258 UpdateVariableStore (
259 IN VARIABLE_GLOBAL *Global,
260 IN BOOLEAN Volatile,
261 IN BOOLEAN SetByIndex,
262 IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb,
263 IN UINTN DataPtrIndex,
264 IN UINT32 DataSize,
265 IN UINT8 *Buffer
266 )
267 {
268 EFI_FV_BLOCK_MAP_ENTRY *PtrBlockMapEntry;
269 UINTN BlockIndex2;
270 UINTN LinearOffset;
271 UINTN CurrWriteSize;
272 UINTN CurrWritePtr;
273 UINT8 *CurrBuffer;
274 EFI_LBA LbaNumber;
275 UINTN Size;
276 EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
277 VARIABLE_STORE_HEADER *VolatileBase;
278 EFI_PHYSICAL_ADDRESS FvVolHdr;
279 EFI_PHYSICAL_ADDRESS DataPtr;
280 EFI_STATUS Status;
281
282 FwVolHeader = NULL;
283 DataPtr = DataPtrIndex;
284
285 //
286 // Check if the Data is Volatile.
287 //
288 if (!Volatile) {
289 if (Fvb == NULL) {
290 return EFI_INVALID_PARAMETER;
291 }
292 Status = Fvb->GetPhysicalAddress(Fvb, &FvVolHdr);
293 ASSERT_EFI_ERROR (Status);
294
295 FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) FvVolHdr);
296 //
297 // Data Pointer should point to the actual Address where data is to be
298 // written.
299 //
300 if (SetByIndex) {
301 DataPtr += mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
302 }
303
304 if ((DataPtr + DataSize) >= ((EFI_PHYSICAL_ADDRESS) (UINTN) ((UINT8 *) FwVolHeader + FwVolHeader->FvLength))) {
305 return EFI_INVALID_PARAMETER;
306 }
307 } else {
308 //
309 // Data Pointer should point to the actual Address where data is to be
310 // written.
311 //
312 VolatileBase = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
313 if (SetByIndex) {
314 DataPtr += mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
315 }
316
317 if ((DataPtr + DataSize) >= ((UINTN) ((UINT8 *) VolatileBase + VolatileBase->Size))) {
318 return EFI_INVALID_PARAMETER;
319 }
320
321 //
322 // If Volatile Variable just do a simple mem copy.
323 //
324 CopyMem ((UINT8 *)(UINTN)DataPtr, Buffer, DataSize);
325 return EFI_SUCCESS;
326 }
327
328 //
329 // If we are here we are dealing with Non-Volatile Variables.
330 //
331 LinearOffset = (UINTN) FwVolHeader;
332 CurrWritePtr = (UINTN) DataPtr;
333 CurrWriteSize = DataSize;
334 CurrBuffer = Buffer;
335 LbaNumber = 0;
336
337 if (CurrWritePtr < LinearOffset) {
338 return EFI_INVALID_PARAMETER;
339 }
340
341 for (PtrBlockMapEntry = FwVolHeader->BlockMap; PtrBlockMapEntry->NumBlocks != 0; PtrBlockMapEntry++) {
342 for (BlockIndex2 = 0; BlockIndex2 < PtrBlockMapEntry->NumBlocks; BlockIndex2++) {
343 //
344 // Check to see if the Variable Writes are spanning through multiple
345 // blocks.
346 //
347 if ((CurrWritePtr >= LinearOffset) && (CurrWritePtr < LinearOffset + PtrBlockMapEntry->Length)) {
348 if ((CurrWritePtr + CurrWriteSize) <= (LinearOffset + PtrBlockMapEntry->Length)) {
349 Status = Fvb->Write (
350 Fvb,
351 LbaNumber,
352 (UINTN) (CurrWritePtr - LinearOffset),
353 &CurrWriteSize,
354 CurrBuffer
355 );
356 return Status;
357 } else {
358 Size = (UINT32) (LinearOffset + PtrBlockMapEntry->Length - CurrWritePtr);
359 Status = Fvb->Write (
360 Fvb,
361 LbaNumber,
362 (UINTN) (CurrWritePtr - LinearOffset),
363 &Size,
364 CurrBuffer
365 );
366 if (EFI_ERROR (Status)) {
367 return Status;
368 }
369
370 CurrWritePtr = LinearOffset + PtrBlockMapEntry->Length;
371 CurrBuffer = CurrBuffer + Size;
372 CurrWriteSize = CurrWriteSize - Size;
373 }
374 }
375
376 LinearOffset += PtrBlockMapEntry->Length;
377 LbaNumber++;
378 }
379 }
380
381 return EFI_SUCCESS;
382 }
383
384
385 /**
386
387 This code gets the current status of Variable Store.
388
389 @param VarStoreHeader Pointer to the Variable Store Header.
390
391 @retval EfiRaw Variable store status is raw.
392 @retval EfiValid Variable store status is valid.
393 @retval EfiInvalid Variable store status is invalid.
394
395 **/
396 VARIABLE_STORE_STATUS
397 GetVariableStoreStatus (
398 IN VARIABLE_STORE_HEADER *VarStoreHeader
399 )
400 {
401 if ((CompareGuid (&VarStoreHeader->Signature, &gEfiAuthenticatedVariableGuid) ||
402 CompareGuid (&VarStoreHeader->Signature, &gEfiVariableGuid)) &&
403 VarStoreHeader->Format == VARIABLE_STORE_FORMATTED &&
404 VarStoreHeader->State == VARIABLE_STORE_HEALTHY
405 ) {
406
407 return EfiValid;
408 } else if (((UINT32 *)(&VarStoreHeader->Signature))[0] == 0xffffffff &&
409 ((UINT32 *)(&VarStoreHeader->Signature))[1] == 0xffffffff &&
410 ((UINT32 *)(&VarStoreHeader->Signature))[2] == 0xffffffff &&
411 ((UINT32 *)(&VarStoreHeader->Signature))[3] == 0xffffffff &&
412 VarStoreHeader->Size == 0xffffffff &&
413 VarStoreHeader->Format == 0xff &&
414 VarStoreHeader->State == 0xff
415 ) {
416
417 return EfiRaw;
418 } else {
419 return EfiInvalid;
420 }
421 }
422
423 /**
424 This code gets the size of variable header.
425
426 @return Size of variable header in bytes in type UINTN.
427
428 **/
429 UINTN
430 GetVariableHeaderSize (
431 VOID
432 )
433 {
434 UINTN Value;
435
436 if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
437 Value = sizeof (AUTHENTICATED_VARIABLE_HEADER);
438 } else {
439 Value = sizeof (VARIABLE_HEADER);
440 }
441
442 return Value;
443 }
444
445 /**
446
447 This code gets the size of name of variable.
448
449 @param Variable Pointer to the Variable Header.
450
451 @return UINTN Size of variable in bytes.
452
453 **/
454 UINTN
455 NameSizeOfVariable (
456 IN VARIABLE_HEADER *Variable
457 )
458 {
459 AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
460
461 AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
462 if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
463 if (AuthVariable->State == (UINT8) (-1) ||
464 AuthVariable->DataSize == (UINT32) (-1) ||
465 AuthVariable->NameSize == (UINT32) (-1) ||
466 AuthVariable->Attributes == (UINT32) (-1)) {
467 return 0;
468 }
469 return (UINTN) AuthVariable->NameSize;
470 } else {
471 if (Variable->State == (UINT8) (-1) ||
472 Variable->DataSize == (UINT32) (-1) ||
473 Variable->NameSize == (UINT32) (-1) ||
474 Variable->Attributes == (UINT32) (-1)) {
475 return 0;
476 }
477 return (UINTN) Variable->NameSize;
478 }
479 }
480
481 /**
482 This code sets the size of name of variable.
483
484 @param[in] Variable Pointer to the Variable Header.
485 @param[in] NameSize Name size to set.
486
487 **/
488 VOID
489 SetNameSizeOfVariable (
490 IN VARIABLE_HEADER *Variable,
491 IN UINTN NameSize
492 )
493 {
494 AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
495
496 AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
497 if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
498 AuthVariable->NameSize = (UINT32) NameSize;
499 } else {
500 Variable->NameSize = (UINT32) NameSize;
501 }
502 }
503
504 /**
505
506 This code gets the size of variable data.
507
508 @param Variable Pointer to the Variable Header.
509
510 @return Size of variable in bytes.
511
512 **/
513 UINTN
514 DataSizeOfVariable (
515 IN VARIABLE_HEADER *Variable
516 )
517 {
518 AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
519
520 AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
521 if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
522 if (AuthVariable->State == (UINT8) (-1) ||
523 AuthVariable->DataSize == (UINT32) (-1) ||
524 AuthVariable->NameSize == (UINT32) (-1) ||
525 AuthVariable->Attributes == (UINT32) (-1)) {
526 return 0;
527 }
528 return (UINTN) AuthVariable->DataSize;
529 } else {
530 if (Variable->State == (UINT8) (-1) ||
531 Variable->DataSize == (UINT32) (-1) ||
532 Variable->NameSize == (UINT32) (-1) ||
533 Variable->Attributes == (UINT32) (-1)) {
534 return 0;
535 }
536 return (UINTN) Variable->DataSize;
537 }
538 }
539
540 /**
541 This code sets the size of variable data.
542
543 @param[in] Variable Pointer to the Variable Header.
544 @param[in] DataSize Data size to set.
545
546 **/
547 VOID
548 SetDataSizeOfVariable (
549 IN VARIABLE_HEADER *Variable,
550 IN UINTN DataSize
551 )
552 {
553 AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
554
555 AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
556 if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
557 AuthVariable->DataSize = (UINT32) DataSize;
558 } else {
559 Variable->DataSize = (UINT32) DataSize;
560 }
561 }
562
563 /**
564
565 This code gets the pointer to the variable name.
566
567 @param Variable Pointer to the Variable Header.
568
569 @return Pointer to Variable Name which is Unicode encoding.
570
571 **/
572 CHAR16 *
573 GetVariableNamePtr (
574 IN VARIABLE_HEADER *Variable
575 )
576 {
577 return (CHAR16 *) ((UINTN) Variable + GetVariableHeaderSize ());
578 }
579
580 /**
581 This code gets the pointer to the variable guid.
582
583 @param Variable Pointer to the Variable Header.
584
585 @return A EFI_GUID* pointer to Vendor Guid.
586
587 **/
588 EFI_GUID *
589 GetVendorGuidPtr (
590 IN VARIABLE_HEADER *Variable
591 )
592 {
593 AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
594
595 AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
596 if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
597 return &AuthVariable->VendorGuid;
598 } else {
599 return &Variable->VendorGuid;
600 }
601 }
602
603 /**
604
605 This code gets the pointer to the variable data.
606
607 @param Variable Pointer to the Variable Header.
608
609 @return Pointer to Variable Data.
610
611 **/
612 UINT8 *
613 GetVariableDataPtr (
614 IN VARIABLE_HEADER *Variable
615 )
616 {
617 UINTN Value;
618
619 //
620 // Be careful about pad size for alignment.
621 //
622 Value = (UINTN) GetVariableNamePtr (Variable);
623 Value += NameSizeOfVariable (Variable);
624 Value += GET_PAD_SIZE (NameSizeOfVariable (Variable));
625
626 return (UINT8 *) Value;
627 }
628
629 /**
630 This code gets the variable data offset related to variable header.
631
632 @param Variable Pointer to the Variable Header.
633
634 @return Variable Data offset.
635
636 **/
637 UINTN
638 GetVariableDataOffset (
639 IN VARIABLE_HEADER *Variable
640 )
641 {
642 UINTN Value;
643
644 //
645 // Be careful about pad size for alignment
646 //
647 Value = GetVariableHeaderSize ();
648 Value += NameSizeOfVariable (Variable);
649 Value += GET_PAD_SIZE (NameSizeOfVariable (Variable));
650
651 return Value;
652 }
653
654 /**
655
656 This code gets the pointer to the next variable header.
657
658 @param Variable Pointer to the Variable Header.
659
660 @return Pointer to next variable header.
661
662 **/
663 VARIABLE_HEADER *
664 GetNextVariablePtr (
665 IN VARIABLE_HEADER *Variable
666 )
667 {
668 UINTN Value;
669
670 Value = (UINTN) GetVariableDataPtr (Variable);
671 Value += DataSizeOfVariable (Variable);
672 Value += GET_PAD_SIZE (DataSizeOfVariable (Variable));
673
674 //
675 // Be careful about pad size for alignment.
676 //
677 return (VARIABLE_HEADER *) HEADER_ALIGN (Value);
678 }
679
680 /**
681
682 Gets the pointer to the first variable header in given variable store area.
683
684 @param VarStoreHeader Pointer to the Variable Store Header.
685
686 @return Pointer to the first variable header.
687
688 **/
689 VARIABLE_HEADER *
690 GetStartPointer (
691 IN VARIABLE_STORE_HEADER *VarStoreHeader
692 )
693 {
694 //
695 // The end of variable store.
696 //
697 return (VARIABLE_HEADER *) HEADER_ALIGN (VarStoreHeader + 1);
698 }
699
700 /**
701
702 Gets the pointer to the end of the variable storage area.
703
704 This function gets pointer to the end of the variable storage
705 area, according to the input variable store header.
706
707 @param VarStoreHeader Pointer to the Variable Store Header.
708
709 @return Pointer to the end of the variable storage area.
710
711 **/
712 VARIABLE_HEADER *
713 GetEndPointer (
714 IN VARIABLE_STORE_HEADER *VarStoreHeader
715 )
716 {
717 //
718 // The end of variable store
719 //
720 return (VARIABLE_HEADER *) HEADER_ALIGN ((UINTN) VarStoreHeader + VarStoreHeader->Size);
721 }
722
723 /**
724 Record variable error flag.
725
726 @param[in] Flag Variable error flag to record.
727 @param[in] VariableName Name of variable.
728 @param[in] VendorGuid Guid of variable.
729 @param[in] Attributes Attributes of the variable.
730 @param[in] VariableSize Size of the variable.
731
732 **/
733 VOID
734 RecordVarErrorFlag (
735 IN VAR_ERROR_FLAG Flag,
736 IN CHAR16 *VariableName,
737 IN EFI_GUID *VendorGuid,
738 IN UINT32 Attributes,
739 IN UINTN VariableSize
740 )
741 {
742 EFI_STATUS Status;
743 VARIABLE_POINTER_TRACK Variable;
744 VAR_ERROR_FLAG *VarErrFlag;
745 VAR_ERROR_FLAG TempFlag;
746
747 DEBUG_CODE (
748 DEBUG ((EFI_D_ERROR, "RecordVarErrorFlag (0x%02x) %s:%g - 0x%08x - 0x%x\n", Flag, VariableName, VendorGuid, Attributes, VariableSize));
749 if (Flag == VAR_ERROR_FLAG_SYSTEM_ERROR) {
750 if (AtRuntime ()) {
751 DEBUG ((EFI_D_ERROR, "CommonRuntimeVariableSpace = 0x%x - CommonVariableTotalSize = 0x%x\n", mVariableModuleGlobal->CommonRuntimeVariableSpace, mVariableModuleGlobal->CommonVariableTotalSize));
752 } else {
753 DEBUG ((EFI_D_ERROR, "CommonVariableSpace = 0x%x - CommonVariableTotalSize = 0x%x\n", mVariableModuleGlobal->CommonVariableSpace, mVariableModuleGlobal->CommonVariableTotalSize));
754 }
755 } else {
756 DEBUG ((EFI_D_ERROR, "CommonMaxUserVariableSpace = 0x%x - CommonUserVariableTotalSize = 0x%x\n", mVariableModuleGlobal->CommonMaxUserVariableSpace, mVariableModuleGlobal->CommonUserVariableTotalSize));
757 }
758 );
759
760 if (!mEndOfDxe) {
761 //
762 // Before EndOfDxe, just record the current boot variable error flag to local variable,
763 // and leave the variable error flag in NV flash as the last boot variable error flag.
764 // After EndOfDxe in InitializeVarErrorFlag (), the variable error flag in NV flash
765 // will be initialized to this local current boot variable error flag.
766 //
767 mCurrentBootVarErrFlag &= Flag;
768 return;
769 }
770
771 //
772 // Record error flag (it should have be initialized).
773 //
774 Status = FindVariable (
775 VAR_ERROR_FLAG_NAME,
776 &gEdkiiVarErrorFlagGuid,
777 &Variable,
778 &mVariableModuleGlobal->VariableGlobal,
779 FALSE
780 );
781 if (!EFI_ERROR (Status)) {
782 VarErrFlag = (VAR_ERROR_FLAG *) GetVariableDataPtr (Variable.CurrPtr);
783 TempFlag = *VarErrFlag;
784 TempFlag &= Flag;
785 if (TempFlag == *VarErrFlag) {
786 return;
787 }
788 Status = UpdateVariableStore (
789 &mVariableModuleGlobal->VariableGlobal,
790 FALSE,
791 FALSE,
792 mVariableModuleGlobal->FvbInstance,
793 (UINTN) VarErrFlag - (UINTN) mNvVariableCache + (UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
794 sizeof (TempFlag),
795 &TempFlag
796 );
797 if (!EFI_ERROR (Status)) {
798 //
799 // Update the data in NV cache.
800 //
801 *VarErrFlag = Flag;
802 }
803 }
804 }
805
806 /**
807 Initialize variable error flag.
808
809 Before EndOfDxe, the variable indicates the last boot variable error flag,
810 then it means the last boot variable error flag must be got before EndOfDxe.
811 After EndOfDxe, the variable indicates the current boot variable error flag,
812 then it means the current boot variable error flag must be got after EndOfDxe.
813
814 **/
815 VOID
816 InitializeVarErrorFlag (
817 VOID
818 )
819 {
820 EFI_STATUS Status;
821 VARIABLE_POINTER_TRACK Variable;
822 VAR_ERROR_FLAG Flag;
823 VAR_ERROR_FLAG VarErrFlag;
824
825 if (!mEndOfDxe) {
826 return;
827 }
828
829 Flag = mCurrentBootVarErrFlag;
830 DEBUG ((EFI_D_INFO, "Initialize variable error flag (%02x)\n", Flag));
831
832 Status = FindVariable (
833 VAR_ERROR_FLAG_NAME,
834 &gEdkiiVarErrorFlagGuid,
835 &Variable,
836 &mVariableModuleGlobal->VariableGlobal,
837 FALSE
838 );
839 if (!EFI_ERROR (Status)) {
840 VarErrFlag = *((VAR_ERROR_FLAG *) GetVariableDataPtr (Variable.CurrPtr));
841 if (VarErrFlag == Flag) {
842 return;
843 }
844 }
845
846 UpdateVariable (
847 VAR_ERROR_FLAG_NAME,
848 &gEdkiiVarErrorFlagGuid,
849 &Flag,
850 sizeof (Flag),
851 VARIABLE_ATTRIBUTE_NV_BS_RT,
852 0,
853 0,
854 &Variable,
855 NULL
856 );
857 }
858
859 /**
860 Is user variable?
861
862 @param[in] Variable Pointer to variable header.
863
864 @retval TRUE User variable.
865 @retval FALSE System variable.
866
867 **/
868 BOOLEAN
869 IsUserVariable (
870 IN VARIABLE_HEADER *Variable
871 )
872 {
873 VAR_CHECK_VARIABLE_PROPERTY Property;
874
875 //
876 // Only after End Of Dxe, the variables belong to system variable are fixed.
877 // If PcdMaxUserNvStorageVariableSize is 0, it means user variable share the same NV storage with system variable,
878 // then no need to check if the variable is user variable or not specially.
879 //
880 if (mEndOfDxe && (mVariableModuleGlobal->CommonMaxUserVariableSpace != mVariableModuleGlobal->CommonVariableSpace)) {
881 if (InternalVarCheckVariablePropertyGet (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &Property) == EFI_NOT_FOUND) {
882 return TRUE;
883 }
884 }
885 return FALSE;
886 }
887
888 /**
889 Calculate common user variable total size.
890
891 **/
892 VOID
893 CalculateCommonUserVariableTotalSize (
894 VOID
895 )
896 {
897 VARIABLE_HEADER *Variable;
898 VARIABLE_HEADER *NextVariable;
899 UINTN VariableSize;
900 VAR_CHECK_VARIABLE_PROPERTY Property;
901
902 //
903 // Only after End Of Dxe, the variables belong to system variable are fixed.
904 // If PcdMaxUserNvStorageVariableSize is 0, it means user variable share the same NV storage with system variable,
905 // then no need to calculate the common user variable total size specially.
906 //
907 if (mEndOfDxe && (mVariableModuleGlobal->CommonMaxUserVariableSpace != mVariableModuleGlobal->CommonVariableSpace)) {
908 Variable = GetStartPointer (mNvVariableCache);
909 while (IsValidVariableHeader (Variable, GetEndPointer (mNvVariableCache))) {
910 NextVariable = GetNextVariablePtr (Variable);
911 VariableSize = (UINTN) NextVariable - (UINTN) Variable;
912 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
913 if (InternalVarCheckVariablePropertyGet (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &Property) == EFI_NOT_FOUND) {
914 //
915 // No property, it is user variable.
916 //
917 mVariableModuleGlobal->CommonUserVariableTotalSize += VariableSize;
918 }
919 }
920
921 Variable = NextVariable;
922 }
923 }
924 }
925
926 /**
927 Initialize variable quota.
928
929 **/
930 VOID
931 InitializeVariableQuota (
932 VOID
933 )
934 {
935 STATIC BOOLEAN Initialized;
936
937 if (!mEndOfDxe || Initialized) {
938 return;
939 }
940 Initialized = TRUE;
941
942 InitializeVarErrorFlag ();
943 CalculateCommonUserVariableTotalSize ();
944 }
945
946 /**
947
948 Variable store garbage collection and reclaim operation.
949
950 @param[in] VariableBase Base address of variable store.
951 @param[out] LastVariableOffset Offset of last variable.
952 @param[in] IsVolatile The variable store is volatile or not;
953 if it is non-volatile, need FTW.
954 @param[in, out] UpdatingPtrTrack Pointer to updating variable pointer track structure.
955 @param[in] NewVariable Pointer to new variable.
956 @param[in] NewVariableSize New variable size.
957
958 @return EFI_SUCCESS Reclaim operation has finished successfully.
959 @return EFI_OUT_OF_RESOURCES No enough memory resources or variable space.
960 @return Others Unexpect error happened during reclaim operation.
961
962 **/
963 EFI_STATUS
964 Reclaim (
965 IN EFI_PHYSICAL_ADDRESS VariableBase,
966 OUT UINTN *LastVariableOffset,
967 IN BOOLEAN IsVolatile,
968 IN OUT VARIABLE_POINTER_TRACK *UpdatingPtrTrack,
969 IN VARIABLE_HEADER *NewVariable,
970 IN UINTN NewVariableSize
971 )
972 {
973 VARIABLE_HEADER *Variable;
974 VARIABLE_HEADER *AddedVariable;
975 VARIABLE_HEADER *NextVariable;
976 VARIABLE_HEADER *NextAddedVariable;
977 VARIABLE_STORE_HEADER *VariableStoreHeader;
978 UINT8 *ValidBuffer;
979 UINTN MaximumBufferSize;
980 UINTN VariableSize;
981 UINTN NameSize;
982 UINT8 *CurrPtr;
983 VOID *Point0;
984 VOID *Point1;
985 BOOLEAN FoundAdded;
986 EFI_STATUS Status;
987 UINTN CommonVariableTotalSize;
988 UINTN CommonUserVariableTotalSize;
989 UINTN HwErrVariableTotalSize;
990 VARIABLE_HEADER *UpdatingVariable;
991 VARIABLE_HEADER *UpdatingInDeletedTransition;
992
993 UpdatingVariable = NULL;
994 UpdatingInDeletedTransition = NULL;
995 if (UpdatingPtrTrack != NULL) {
996 UpdatingVariable = UpdatingPtrTrack->CurrPtr;
997 UpdatingInDeletedTransition = UpdatingPtrTrack->InDeletedTransitionPtr;
998 }
999
1000 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) VariableBase);
1001
1002 CommonVariableTotalSize = 0;
1003 CommonUserVariableTotalSize = 0;
1004 HwErrVariableTotalSize = 0;
1005
1006 if (IsVolatile) {
1007 //
1008 // Start Pointers for the variable.
1009 //
1010 Variable = GetStartPointer (VariableStoreHeader);
1011 MaximumBufferSize = sizeof (VARIABLE_STORE_HEADER);
1012
1013 while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
1014 NextVariable = GetNextVariablePtr (Variable);
1015 if ((Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) &&
1016 Variable != UpdatingVariable &&
1017 Variable != UpdatingInDeletedTransition
1018 ) {
1019 VariableSize = (UINTN) NextVariable - (UINTN) Variable;
1020 MaximumBufferSize += VariableSize;
1021 }
1022
1023 Variable = NextVariable;
1024 }
1025
1026 if (NewVariable != NULL) {
1027 //
1028 // Add the new variable size.
1029 //
1030 MaximumBufferSize += NewVariableSize;
1031 }
1032
1033 //
1034 // Reserve the 1 Bytes with Oxff to identify the
1035 // end of the variable buffer.
1036 //
1037 MaximumBufferSize += 1;
1038 ValidBuffer = AllocatePool (MaximumBufferSize);
1039 if (ValidBuffer == NULL) {
1040 return EFI_OUT_OF_RESOURCES;
1041 }
1042 } else {
1043 //
1044 // For NV variable reclaim, don't allocate pool here and just use mNvVariableCache
1045 // as the buffer to reduce SMRAM consumption for SMM variable driver.
1046 //
1047 MaximumBufferSize = mNvVariableCache->Size;
1048 ValidBuffer = (UINT8 *) mNvVariableCache;
1049 }
1050
1051 SetMem (ValidBuffer, MaximumBufferSize, 0xff);
1052
1053 //
1054 // Copy variable store header.
1055 //
1056 CopyMem (ValidBuffer, VariableStoreHeader, sizeof (VARIABLE_STORE_HEADER));
1057 CurrPtr = (UINT8 *) GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);
1058
1059 //
1060 // Reinstall all ADDED variables as long as they are not identical to Updating Variable.
1061 //
1062 Variable = GetStartPointer (VariableStoreHeader);
1063 while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
1064 NextVariable = GetNextVariablePtr (Variable);
1065 if (Variable != UpdatingVariable && Variable->State == VAR_ADDED) {
1066 VariableSize = (UINTN) NextVariable - (UINTN) Variable;
1067 CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);
1068 CurrPtr += VariableSize;
1069 if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
1070 HwErrVariableTotalSize += VariableSize;
1071 } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
1072 CommonVariableTotalSize += VariableSize;
1073 if (IsUserVariable (Variable)) {
1074 CommonUserVariableTotalSize += VariableSize;
1075 }
1076 }
1077 }
1078 Variable = NextVariable;
1079 }
1080
1081 //
1082 // Reinstall all in delete transition variables.
1083 //
1084 Variable = GetStartPointer (VariableStoreHeader);
1085 while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
1086 NextVariable = GetNextVariablePtr (Variable);
1087 if (Variable != UpdatingVariable && Variable != UpdatingInDeletedTransition && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
1088
1089 //
1090 // Buffer has cached all ADDED variable.
1091 // Per IN_DELETED variable, we have to guarantee that
1092 // no ADDED one in previous buffer.
1093 //
1094
1095 FoundAdded = FALSE;
1096 AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);
1097 while (IsValidVariableHeader (AddedVariable, GetEndPointer ((VARIABLE_STORE_HEADER *) ValidBuffer))) {
1098 NextAddedVariable = GetNextVariablePtr (AddedVariable);
1099 NameSize = NameSizeOfVariable (AddedVariable);
1100 if (CompareGuid (GetVendorGuidPtr (AddedVariable), GetVendorGuidPtr (Variable)) &&
1101 NameSize == NameSizeOfVariable (Variable)
1102 ) {
1103 Point0 = (VOID *) GetVariableNamePtr (AddedVariable);
1104 Point1 = (VOID *) GetVariableNamePtr (Variable);
1105 if (CompareMem (Point0, Point1, NameSize) == 0) {
1106 FoundAdded = TRUE;
1107 break;
1108 }
1109 }
1110 AddedVariable = NextAddedVariable;
1111 }
1112 if (!FoundAdded) {
1113 //
1114 // Promote VAR_IN_DELETED_TRANSITION to VAR_ADDED.
1115 //
1116 VariableSize = (UINTN) NextVariable - (UINTN) Variable;
1117 CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);
1118 ((VARIABLE_HEADER *) CurrPtr)->State = VAR_ADDED;
1119 CurrPtr += VariableSize;
1120 if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
1121 HwErrVariableTotalSize += VariableSize;
1122 } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
1123 CommonVariableTotalSize += VariableSize;
1124 if (IsUserVariable (Variable)) {
1125 CommonUserVariableTotalSize += VariableSize;
1126 }
1127 }
1128 }
1129 }
1130
1131 Variable = NextVariable;
1132 }
1133
1134 //
1135 // Install the new variable if it is not NULL.
1136 //
1137 if (NewVariable != NULL) {
1138 if ((UINTN) (CurrPtr - ValidBuffer) + NewVariableSize > VariableStoreHeader->Size) {
1139 //
1140 // No enough space to store the new variable.
1141 //
1142 Status = EFI_OUT_OF_RESOURCES;
1143 goto Done;
1144 }
1145 if (!IsVolatile) {
1146 if ((NewVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
1147 HwErrVariableTotalSize += NewVariableSize;
1148 } else if ((NewVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
1149 CommonVariableTotalSize += NewVariableSize;
1150 if (IsUserVariable (NewVariable)) {
1151 CommonUserVariableTotalSize += NewVariableSize;
1152 }
1153 }
1154 if ((HwErrVariableTotalSize > PcdGet32 (PcdHwErrStorageSize)) ||
1155 (CommonVariableTotalSize > mVariableModuleGlobal->CommonVariableSpace) ||
1156 (CommonUserVariableTotalSize > mVariableModuleGlobal->CommonMaxUserVariableSpace)) {
1157 //
1158 // No enough space to store the new variable by NV or NV+HR attribute.
1159 //
1160 Status = EFI_OUT_OF_RESOURCES;
1161 goto Done;
1162 }
1163 }
1164
1165 CopyMem (CurrPtr, (UINT8 *) NewVariable, NewVariableSize);
1166 ((VARIABLE_HEADER *) CurrPtr)->State = VAR_ADDED;
1167 if (UpdatingVariable != NULL) {
1168 UpdatingPtrTrack->CurrPtr = (VARIABLE_HEADER *)((UINTN)UpdatingPtrTrack->StartPtr + ((UINTN)CurrPtr - (UINTN)GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer)));
1169 UpdatingPtrTrack->InDeletedTransitionPtr = NULL;
1170 }
1171 CurrPtr += NewVariableSize;
1172 }
1173
1174 if (IsVolatile) {
1175 //
1176 // If volatile variable store, just copy valid buffer.
1177 //
1178 SetMem ((UINT8 *) (UINTN) VariableBase, VariableStoreHeader->Size, 0xff);
1179 CopyMem ((UINT8 *) (UINTN) VariableBase, ValidBuffer, (UINTN) (CurrPtr - ValidBuffer));
1180 *LastVariableOffset = (UINTN) (CurrPtr - ValidBuffer);
1181 Status = EFI_SUCCESS;
1182 } else {
1183 //
1184 // If non-volatile variable store, perform FTW here.
1185 //
1186 Status = FtwVariableSpace (
1187 VariableBase,
1188 (VARIABLE_STORE_HEADER *) ValidBuffer
1189 );
1190 if (!EFI_ERROR (Status)) {
1191 *LastVariableOffset = (UINTN) (CurrPtr - ValidBuffer);
1192 mVariableModuleGlobal->HwErrVariableTotalSize = HwErrVariableTotalSize;
1193 mVariableModuleGlobal->CommonVariableTotalSize = CommonVariableTotalSize;
1194 mVariableModuleGlobal->CommonUserVariableTotalSize = CommonUserVariableTotalSize;
1195 } else {
1196 Variable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase);
1197 while (IsValidVariableHeader (Variable, GetEndPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase))) {
1198 NextVariable = GetNextVariablePtr (Variable);
1199 VariableSize = (UINTN) NextVariable - (UINTN) Variable;
1200 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
1201 mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;
1202 } else if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
1203 mVariableModuleGlobal->CommonVariableTotalSize += VariableSize;
1204 if (IsUserVariable (Variable)) {
1205 mVariableModuleGlobal->CommonUserVariableTotalSize += VariableSize;
1206 }
1207 }
1208
1209 Variable = NextVariable;
1210 }
1211 *LastVariableOffset = (UINTN) Variable - (UINTN) VariableBase;
1212 }
1213 }
1214
1215 Done:
1216 if (IsVolatile) {
1217 FreePool (ValidBuffer);
1218 } else {
1219 //
1220 // For NV variable reclaim, we use mNvVariableCache as the buffer, so copy the data back.
1221 //
1222 CopyMem (mNvVariableCache, (UINT8 *)(UINTN)VariableBase, VariableStoreHeader->Size);
1223 }
1224
1225 return Status;
1226 }
1227
1228 /**
1229 Find the variable in the specified variable store.
1230
1231 @param[in] VariableName Name of the variable to be found
1232 @param[in] VendorGuid Vendor GUID to be found.
1233 @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
1234 check at runtime when searching variable.
1235 @param[in, out] PtrTrack Variable Track Pointer structure that contains Variable Information.
1236
1237 @retval EFI_SUCCESS Variable found successfully
1238 @retval EFI_NOT_FOUND Variable not found
1239 **/
1240 EFI_STATUS
1241 FindVariableEx (
1242 IN CHAR16 *VariableName,
1243 IN EFI_GUID *VendorGuid,
1244 IN BOOLEAN IgnoreRtCheck,
1245 IN OUT VARIABLE_POINTER_TRACK *PtrTrack
1246 )
1247 {
1248 VARIABLE_HEADER *InDeletedVariable;
1249 VOID *Point;
1250
1251 PtrTrack->InDeletedTransitionPtr = NULL;
1252
1253 //
1254 // Find the variable by walk through HOB, volatile and non-volatile variable store.
1255 //
1256 InDeletedVariable = NULL;
1257
1258 for ( PtrTrack->CurrPtr = PtrTrack->StartPtr
1259 ; IsValidVariableHeader (PtrTrack->CurrPtr, PtrTrack->EndPtr)
1260 ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr)
1261 ) {
1262 if (PtrTrack->CurrPtr->State == VAR_ADDED ||
1263 PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)
1264 ) {
1265 if (IgnoreRtCheck || !AtRuntime () || ((PtrTrack->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
1266 if (VariableName[0] == 0) {
1267 if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
1268 InDeletedVariable = PtrTrack->CurrPtr;
1269 } else {
1270 PtrTrack->InDeletedTransitionPtr = InDeletedVariable;
1271 return EFI_SUCCESS;
1272 }
1273 } else {
1274 if (CompareGuid (VendorGuid, GetVendorGuidPtr (PtrTrack->CurrPtr))) {
1275 Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr);
1276
1277 ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0);
1278 if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) {
1279 if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
1280 InDeletedVariable = PtrTrack->CurrPtr;
1281 } else {
1282 PtrTrack->InDeletedTransitionPtr = InDeletedVariable;
1283 return EFI_SUCCESS;
1284 }
1285 }
1286 }
1287 }
1288 }
1289 }
1290 }
1291
1292 PtrTrack->CurrPtr = InDeletedVariable;
1293 return (PtrTrack->CurrPtr == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS;
1294 }
1295
1296
1297 /**
1298 Finds variable in storage blocks of volatile and non-volatile storage areas.
1299
1300 This code finds variable in storage blocks of volatile and non-volatile storage areas.
1301 If VariableName is an empty string, then we just return the first
1302 qualified variable without comparing VariableName and VendorGuid.
1303 If IgnoreRtCheck is TRUE, then we ignore the EFI_VARIABLE_RUNTIME_ACCESS attribute check
1304 at runtime when searching existing variable, only VariableName and VendorGuid are compared.
1305 Otherwise, variables without EFI_VARIABLE_RUNTIME_ACCESS are not visible at runtime.
1306
1307 @param[in] VariableName Name of the variable to be found.
1308 @param[in] VendorGuid Vendor GUID to be found.
1309 @param[out] PtrTrack VARIABLE_POINTER_TRACK structure for output,
1310 including the range searched and the target position.
1311 @param[in] Global Pointer to VARIABLE_GLOBAL structure, including
1312 base of volatile variable storage area, base of
1313 NV variable storage area, and a lock.
1314 @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
1315 check at runtime when searching variable.
1316
1317 @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while
1318 VendorGuid is NULL.
1319 @retval EFI_SUCCESS Variable successfully found.
1320 @retval EFI_NOT_FOUND Variable not found
1321
1322 **/
1323 EFI_STATUS
1324 FindVariable (
1325 IN CHAR16 *VariableName,
1326 IN EFI_GUID *VendorGuid,
1327 OUT VARIABLE_POINTER_TRACK *PtrTrack,
1328 IN VARIABLE_GLOBAL *Global,
1329 IN BOOLEAN IgnoreRtCheck
1330 )
1331 {
1332 EFI_STATUS Status;
1333 VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
1334 VARIABLE_STORE_TYPE Type;
1335
1336 if (VariableName[0] != 0 && VendorGuid == NULL) {
1337 return EFI_INVALID_PARAMETER;
1338 }
1339
1340 //
1341 // 0: Volatile, 1: HOB, 2: Non-Volatile.
1342 // The index and attributes mapping must be kept in this order as RuntimeServiceGetNextVariableName
1343 // make use of this mapping to implement search algorithm.
1344 //
1345 VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) Global->VolatileVariableBase;
1346 VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) Global->HobVariableBase;
1347 VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
1348
1349 //
1350 // Find the variable by walk through HOB, volatile and non-volatile variable store.
1351 //
1352 for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
1353 if (VariableStoreHeader[Type] == NULL) {
1354 continue;
1355 }
1356
1357 PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader[Type]);
1358 PtrTrack->EndPtr = GetEndPointer (VariableStoreHeader[Type]);
1359 PtrTrack->Volatile = (BOOLEAN) (Type == VariableStoreTypeVolatile);
1360
1361 Status = FindVariableEx (VariableName, VendorGuid, IgnoreRtCheck, PtrTrack);
1362 if (!EFI_ERROR (Status)) {
1363 return Status;
1364 }
1365 }
1366 return EFI_NOT_FOUND;
1367 }
1368
1369 /**
1370 Get index from supported language codes according to language string.
1371
1372 This code is used to get corresponding index in supported language codes. It can handle
1373 RFC4646 and ISO639 language tags.
1374 In ISO639 language tags, take 3-characters as a delimitation to find matched string and calculate the index.
1375 In RFC4646 language tags, take semicolon as a delimitation to find matched string and calculate the index.
1376
1377 For example:
1378 SupportedLang = "engfraengfra"
1379 Lang = "eng"
1380 Iso639Language = TRUE
1381 The return value is "0".
1382 Another example:
1383 SupportedLang = "en;fr;en-US;fr-FR"
1384 Lang = "fr-FR"
1385 Iso639Language = FALSE
1386 The return value is "3".
1387
1388 @param SupportedLang Platform supported language codes.
1389 @param Lang Configured language.
1390 @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
1391
1392 @retval The index of language in the language codes.
1393
1394 **/
1395 UINTN
1396 GetIndexFromSupportedLangCodes(
1397 IN CHAR8 *SupportedLang,
1398 IN CHAR8 *Lang,
1399 IN BOOLEAN Iso639Language
1400 )
1401 {
1402 UINTN Index;
1403 UINTN CompareLength;
1404 UINTN LanguageLength;
1405
1406 if (Iso639Language) {
1407 CompareLength = ISO_639_2_ENTRY_SIZE;
1408 for (Index = 0; Index < AsciiStrLen (SupportedLang); Index += CompareLength) {
1409 if (AsciiStrnCmp (Lang, SupportedLang + Index, CompareLength) == 0) {
1410 //
1411 // Successfully find the index of Lang string in SupportedLang string.
1412 //
1413 Index = Index / CompareLength;
1414 return Index;
1415 }
1416 }
1417 ASSERT (FALSE);
1418 return 0;
1419 } else {
1420 //
1421 // Compare RFC4646 language code
1422 //
1423 Index = 0;
1424 for (LanguageLength = 0; Lang[LanguageLength] != '\0'; LanguageLength++);
1425
1426 for (Index = 0; *SupportedLang != '\0'; Index++, SupportedLang += CompareLength) {
1427 //
1428 // Skip ';' characters in SupportedLang
1429 //
1430 for (; *SupportedLang != '\0' && *SupportedLang == ';'; SupportedLang++);
1431 //
1432 // Determine the length of the next language code in SupportedLang
1433 //
1434 for (CompareLength = 0; SupportedLang[CompareLength] != '\0' && SupportedLang[CompareLength] != ';'; CompareLength++);
1435
1436 if ((CompareLength == LanguageLength) &&
1437 (AsciiStrnCmp (Lang, SupportedLang, CompareLength) == 0)) {
1438 //
1439 // Successfully find the index of Lang string in SupportedLang string.
1440 //
1441 return Index;
1442 }
1443 }
1444 ASSERT (FALSE);
1445 return 0;
1446 }
1447 }
1448
1449 /**
1450 Get language string from supported language codes according to index.
1451
1452 This code is used to get corresponding language strings in supported language codes. It can handle
1453 RFC4646 and ISO639 language tags.
1454 In ISO639 language tags, take 3-characters as a delimitation. Find language string according to the index.
1455 In RFC4646 language tags, take semicolon as a delimitation. Find language string according to the index.
1456
1457 For example:
1458 SupportedLang = "engfraengfra"
1459 Index = "1"
1460 Iso639Language = TRUE
1461 The return value is "fra".
1462 Another example:
1463 SupportedLang = "en;fr;en-US;fr-FR"
1464 Index = "1"
1465 Iso639Language = FALSE
1466 The return value is "fr".
1467
1468 @param SupportedLang Platform supported language codes.
1469 @param Index The index in supported language codes.
1470 @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
1471
1472 @retval The language string in the language codes.
1473
1474 **/
1475 CHAR8 *
1476 GetLangFromSupportedLangCodes (
1477 IN CHAR8 *SupportedLang,
1478 IN UINTN Index,
1479 IN BOOLEAN Iso639Language
1480 )
1481 {
1482 UINTN SubIndex;
1483 UINTN CompareLength;
1484 CHAR8 *Supported;
1485
1486 SubIndex = 0;
1487 Supported = SupportedLang;
1488 if (Iso639Language) {
1489 //
1490 // According to the index of Lang string in SupportedLang string to get the language.
1491 // This code will be invoked in RUNTIME, therefore there is not a memory allocate/free operation.
1492 // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.
1493 //
1494 CompareLength = ISO_639_2_ENTRY_SIZE;
1495 mVariableModuleGlobal->Lang[CompareLength] = '\0';
1496 return CopyMem (mVariableModuleGlobal->Lang, SupportedLang + Index * CompareLength, CompareLength);
1497
1498 } else {
1499 while (TRUE) {
1500 //
1501 // Take semicolon as delimitation, sequentially traverse supported language codes.
1502 //
1503 for (CompareLength = 0; *Supported != ';' && *Supported != '\0'; CompareLength++) {
1504 Supported++;
1505 }
1506 if ((*Supported == '\0') && (SubIndex != Index)) {
1507 //
1508 // Have completed the traverse, but not find corrsponding string.
1509 // This case is not allowed to happen.
1510 //
1511 ASSERT(FALSE);
1512 return NULL;
1513 }
1514 if (SubIndex == Index) {
1515 //
1516 // According to the index of Lang string in SupportedLang string to get the language.
1517 // As this code will be invoked in RUNTIME, therefore there is not memory allocate/free operation.
1518 // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.
1519 //
1520 mVariableModuleGlobal->PlatformLang[CompareLength] = '\0';
1521 return CopyMem (mVariableModuleGlobal->PlatformLang, Supported - CompareLength, CompareLength);
1522 }
1523 SubIndex++;
1524
1525 //
1526 // Skip ';' characters in Supported
1527 //
1528 for (; *Supported != '\0' && *Supported == ';'; Supported++);
1529 }
1530 }
1531 }
1532
1533 /**
1534 Returns a pointer to an allocated buffer that contains the best matching language
1535 from a set of supported languages.
1536
1537 This function supports both ISO 639-2 and RFC 4646 language codes, but language
1538 code types may not be mixed in a single call to this function. This function
1539 supports a variable argument list that allows the caller to pass in a prioritized
1540 list of language codes to test against all the language codes in SupportedLanguages.
1541
1542 If SupportedLanguages is NULL, then ASSERT().
1543
1544 @param[in] SupportedLanguages A pointer to a Null-terminated ASCII string that
1545 contains a set of language codes in the format
1546 specified by Iso639Language.
1547 @param[in] Iso639Language If TRUE, then all language codes are assumed to be
1548 in ISO 639-2 format. If FALSE, then all language
1549 codes are assumed to be in RFC 4646 language format
1550 @param[in] ... A variable argument list that contains pointers to
1551 Null-terminated ASCII strings that contain one or more
1552 language codes in the format specified by Iso639Language.
1553 The first language code from each of these language
1554 code lists is used to determine if it is an exact or
1555 close match to any of the language codes in
1556 SupportedLanguages. Close matches only apply to RFC 4646
1557 language codes, and the matching algorithm from RFC 4647
1558 is used to determine if a close match is present. If
1559 an exact or close match is found, then the matching
1560 language code from SupportedLanguages is returned. If
1561 no matches are found, then the next variable argument
1562 parameter is evaluated. The variable argument list
1563 is terminated by a NULL.
1564
1565 @retval NULL The best matching language could not be found in SupportedLanguages.
1566 @retval NULL There are not enough resources available to return the best matching
1567 language.
1568 @retval Other A pointer to a Null-terminated ASCII string that is the best matching
1569 language in SupportedLanguages.
1570
1571 **/
1572 CHAR8 *
1573 EFIAPI
1574 VariableGetBestLanguage (
1575 IN CONST CHAR8 *SupportedLanguages,
1576 IN BOOLEAN Iso639Language,
1577 ...
1578 )
1579 {
1580 VA_LIST Args;
1581 CHAR8 *Language;
1582 UINTN CompareLength;
1583 UINTN LanguageLength;
1584 CONST CHAR8 *Supported;
1585 CHAR8 *Buffer;
1586
1587 if (SupportedLanguages == NULL) {
1588 return NULL;
1589 }
1590
1591 VA_START (Args, Iso639Language);
1592 while ((Language = VA_ARG (Args, CHAR8 *)) != NULL) {
1593 //
1594 // Default to ISO 639-2 mode
1595 //
1596 CompareLength = 3;
1597 LanguageLength = MIN (3, AsciiStrLen (Language));
1598
1599 //
1600 // If in RFC 4646 mode, then determine the length of the first RFC 4646 language code in Language
1601 //
1602 if (!Iso639Language) {
1603 for (LanguageLength = 0; Language[LanguageLength] != 0 && Language[LanguageLength] != ';'; LanguageLength++);
1604 }
1605
1606 //
1607 // Trim back the length of Language used until it is empty
1608 //
1609 while (LanguageLength > 0) {
1610 //
1611 // Loop through all language codes in SupportedLanguages
1612 //
1613 for (Supported = SupportedLanguages; *Supported != '\0'; Supported += CompareLength) {
1614 //
1615 // In RFC 4646 mode, then Loop through all language codes in SupportedLanguages
1616 //
1617 if (!Iso639Language) {
1618 //
1619 // Skip ';' characters in Supported
1620 //
1621 for (; *Supported != '\0' && *Supported == ';'; Supported++);
1622 //
1623 // Determine the length of the next language code in Supported
1624 //
1625 for (CompareLength = 0; Supported[CompareLength] != 0 && Supported[CompareLength] != ';'; CompareLength++);
1626 //
1627 // If Language is longer than the Supported, then skip to the next language
1628 //
1629 if (LanguageLength > CompareLength) {
1630 continue;
1631 }
1632 }
1633 //
1634 // See if the first LanguageLength characters in Supported match Language
1635 //
1636 if (AsciiStrnCmp (Supported, Language, LanguageLength) == 0) {
1637 VA_END (Args);
1638
1639 Buffer = Iso639Language ? mVariableModuleGlobal->Lang : mVariableModuleGlobal->PlatformLang;
1640 Buffer[CompareLength] = '\0';
1641 return CopyMem (Buffer, Supported, CompareLength);
1642 }
1643 }
1644
1645 if (Iso639Language) {
1646 //
1647 // If ISO 639 mode, then each language can only be tested once
1648 //
1649 LanguageLength = 0;
1650 } else {
1651 //
1652 // If RFC 4646 mode, then trim Language from the right to the next '-' character
1653 //
1654 for (LanguageLength--; LanguageLength > 0 && Language[LanguageLength] != '-'; LanguageLength--);
1655 }
1656 }
1657 }
1658 VA_END (Args);
1659
1660 //
1661 // No matches were found
1662 //
1663 return NULL;
1664 }
1665
1666 /**
1667 This function is to check if the remaining variable space is enough to set
1668 all Variables from argument list successfully. The purpose of the check
1669 is to keep the consistency of the Variables to be in variable storage.
1670
1671 Note: Variables are assumed to be in same storage.
1672 The set sequence of Variables will be same with the sequence of VariableEntry from argument list,
1673 so follow the argument sequence to check the Variables.
1674
1675 @param[in] Attributes Variable attributes for Variable entries.
1676 @param[in] Marker VA_LIST style variable argument list.
1677 The variable argument list with type VARIABLE_ENTRY_CONSISTENCY *.
1678 A NULL terminates the list. The VariableSize of
1679 VARIABLE_ENTRY_CONSISTENCY is the variable data size as input.
1680 It will be changed to variable total size as output.
1681
1682 @retval TRUE Have enough variable space to set the Variables successfully.
1683 @retval FALSE No enough variable space to set the Variables successfully.
1684
1685 **/
1686 BOOLEAN
1687 EFIAPI
1688 CheckRemainingSpaceForConsistencyInternal (
1689 IN UINT32 Attributes,
1690 IN VA_LIST Marker
1691 )
1692 {
1693 EFI_STATUS Status;
1694 VA_LIST Args;
1695 VARIABLE_ENTRY_CONSISTENCY *VariableEntry;
1696 UINT64 MaximumVariableStorageSize;
1697 UINT64 RemainingVariableStorageSize;
1698 UINT64 MaximumVariableSize;
1699 UINTN TotalNeededSize;
1700 UINTN OriginalVarSize;
1701 VARIABLE_STORE_HEADER *VariableStoreHeader;
1702 VARIABLE_POINTER_TRACK VariablePtrTrack;
1703 VARIABLE_HEADER *NextVariable;
1704 UINTN VarNameSize;
1705 UINTN VarDataSize;
1706
1707 //
1708 // Non-Volatile related.
1709 //
1710 VariableStoreHeader = mNvVariableCache;
1711
1712 Status = VariableServiceQueryVariableInfoInternal (
1713 Attributes,
1714 &MaximumVariableStorageSize,
1715 &RemainingVariableStorageSize,
1716 &MaximumVariableSize
1717 );
1718 ASSERT_EFI_ERROR (Status);
1719
1720 TotalNeededSize = 0;
1721 Args = Marker;
1722 VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);
1723 while (VariableEntry != NULL) {
1724 //
1725 // Calculate variable total size.
1726 //
1727 VarNameSize = StrSize (VariableEntry->Name);
1728 VarNameSize += GET_PAD_SIZE (VarNameSize);
1729 VarDataSize = VariableEntry->VariableSize;
1730 VarDataSize += GET_PAD_SIZE (VarDataSize);
1731 VariableEntry->VariableSize = HEADER_ALIGN (GetVariableHeaderSize () + VarNameSize + VarDataSize);
1732
1733 TotalNeededSize += VariableEntry->VariableSize;
1734 VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);
1735 }
1736
1737 if (RemainingVariableStorageSize >= TotalNeededSize) {
1738 //
1739 // Already have enough space.
1740 //
1741 return TRUE;
1742 } else if (AtRuntime ()) {
1743 //
1744 // At runtime, no reclaim.
1745 // The original variable space of Variables can't be reused.
1746 //
1747 return FALSE;
1748 }
1749
1750 Args = Marker;
1751 VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);
1752 while (VariableEntry != NULL) {
1753 //
1754 // Check if Variable[Index] has been present and get its size.
1755 //
1756 OriginalVarSize = 0;
1757 VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader);
1758 VariablePtrTrack.EndPtr = GetEndPointer (VariableStoreHeader);
1759 Status = FindVariableEx (
1760 VariableEntry->Name,
1761 VariableEntry->Guid,
1762 FALSE,
1763 &VariablePtrTrack
1764 );
1765 if (!EFI_ERROR (Status)) {
1766 //
1767 // Get size of Variable[Index].
1768 //
1769 NextVariable = GetNextVariablePtr (VariablePtrTrack.CurrPtr);
1770 OriginalVarSize = (UINTN) NextVariable - (UINTN) VariablePtrTrack.CurrPtr;
1771 //
1772 // Add the original size of Variable[Index] to remaining variable storage size.
1773 //
1774 RemainingVariableStorageSize += OriginalVarSize;
1775 }
1776 if (VariableEntry->VariableSize > RemainingVariableStorageSize) {
1777 //
1778 // No enough space for Variable[Index].
1779 //
1780 return FALSE;
1781 }
1782 //
1783 // Sub the (new) size of Variable[Index] from remaining variable storage size.
1784 //
1785 RemainingVariableStorageSize -= VariableEntry->VariableSize;
1786 VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);
1787 }
1788
1789 return TRUE;
1790 }
1791
1792 /**
1793 This function is to check if the remaining variable space is enough to set
1794 all Variables from argument list successfully. The purpose of the check
1795 is to keep the consistency of the Variables to be in variable storage.
1796
1797 Note: Variables are assumed to be in same storage.
1798 The set sequence of Variables will be same with the sequence of VariableEntry from argument list,
1799 so follow the argument sequence to check the Variables.
1800
1801 @param[in] Attributes Variable attributes for Variable entries.
1802 @param ... The variable argument list with type VARIABLE_ENTRY_CONSISTENCY *.
1803 A NULL terminates the list. The VariableSize of
1804 VARIABLE_ENTRY_CONSISTENCY is the variable data size as input.
1805 It will be changed to variable total size as output.
1806
1807 @retval TRUE Have enough variable space to set the Variables successfully.
1808 @retval FALSE No enough variable space to set the Variables successfully.
1809
1810 **/
1811 BOOLEAN
1812 EFIAPI
1813 CheckRemainingSpaceForConsistency (
1814 IN UINT32 Attributes,
1815 ...
1816 )
1817 {
1818 VA_LIST Marker;
1819 BOOLEAN Return;
1820
1821 VA_START (Marker, Attributes);
1822
1823 Return = CheckRemainingSpaceForConsistencyInternal (Attributes, Marker);
1824
1825 VA_END (Marker);
1826
1827 return Return;
1828 }
1829
1830 /**
1831 Hook the operations in PlatformLangCodes, LangCodes, PlatformLang and Lang.
1832
1833 When setting Lang/LangCodes, simultaneously update PlatformLang/PlatformLangCodes.
1834
1835 According to UEFI spec, PlatformLangCodes/LangCodes are only set once in firmware initialization,
1836 and are read-only. Therefore, in variable driver, only store the original value for other use.
1837
1838 @param[in] VariableName Name of variable.
1839
1840 @param[in] Data Variable data.
1841
1842 @param[in] DataSize Size of data. 0 means delete.
1843
1844 @retval EFI_SUCCESS The update operation is successful or ignored.
1845 @retval EFI_WRITE_PROTECTED Update PlatformLangCodes/LangCodes at runtime.
1846 @retval EFI_OUT_OF_RESOURCES No enough variable space to do the update operation.
1847 @retval Others Other errors happened during the update operation.
1848
1849 **/
1850 EFI_STATUS
1851 AutoUpdateLangVariable (
1852 IN CHAR16 *VariableName,
1853 IN VOID *Data,
1854 IN UINTN DataSize
1855 )
1856 {
1857 EFI_STATUS Status;
1858 CHAR8 *BestPlatformLang;
1859 CHAR8 *BestLang;
1860 UINTN Index;
1861 UINT32 Attributes;
1862 VARIABLE_POINTER_TRACK Variable;
1863 BOOLEAN SetLanguageCodes;
1864 VARIABLE_ENTRY_CONSISTENCY VariableEntry[2];
1865
1866 //
1867 // Don't do updates for delete operation
1868 //
1869 if (DataSize == 0) {
1870 return EFI_SUCCESS;
1871 }
1872
1873 SetLanguageCodes = FALSE;
1874
1875 if (StrCmp (VariableName, EFI_PLATFORM_LANG_CODES_VARIABLE_NAME) == 0) {
1876 //
1877 // PlatformLangCodes is a volatile variable, so it can not be updated at runtime.
1878 //
1879 if (AtRuntime ()) {
1880 return EFI_WRITE_PROTECTED;
1881 }
1882
1883 SetLanguageCodes = TRUE;
1884
1885 //
1886 // According to UEFI spec, PlatformLangCodes is only set once in firmware initialization, and is read-only
1887 // Therefore, in variable driver, only store the original value for other use.
1888 //
1889 if (mVariableModuleGlobal->PlatformLangCodes != NULL) {
1890 FreePool (mVariableModuleGlobal->PlatformLangCodes);
1891 }
1892 mVariableModuleGlobal->PlatformLangCodes = AllocateRuntimeCopyPool (DataSize, Data);
1893 ASSERT (mVariableModuleGlobal->PlatformLangCodes != NULL);
1894
1895 //
1896 // PlatformLang holds a single language from PlatformLangCodes,
1897 // so the size of PlatformLangCodes is enough for the PlatformLang.
1898 //
1899 if (mVariableModuleGlobal->PlatformLang != NULL) {
1900 FreePool (mVariableModuleGlobal->PlatformLang);
1901 }
1902 mVariableModuleGlobal->PlatformLang = AllocateRuntimePool (DataSize);
1903 ASSERT (mVariableModuleGlobal->PlatformLang != NULL);
1904
1905 } else if (StrCmp (VariableName, EFI_LANG_CODES_VARIABLE_NAME) == 0) {
1906 //
1907 // LangCodes is a volatile variable, so it can not be updated at runtime.
1908 //
1909 if (AtRuntime ()) {
1910 return EFI_WRITE_PROTECTED;
1911 }
1912
1913 SetLanguageCodes = TRUE;
1914
1915 //
1916 // According to UEFI spec, LangCodes is only set once in firmware initialization, and is read-only
1917 // Therefore, in variable driver, only store the original value for other use.
1918 //
1919 if (mVariableModuleGlobal->LangCodes != NULL) {
1920 FreePool (mVariableModuleGlobal->LangCodes);
1921 }
1922 mVariableModuleGlobal->LangCodes = AllocateRuntimeCopyPool (DataSize, Data);
1923 ASSERT (mVariableModuleGlobal->LangCodes != NULL);
1924 }
1925
1926 if (SetLanguageCodes
1927 && (mVariableModuleGlobal->PlatformLangCodes != NULL)
1928 && (mVariableModuleGlobal->LangCodes != NULL)) {
1929 //
1930 // Update Lang if PlatformLang is already set
1931 // Update PlatformLang if Lang is already set
1932 //
1933 Status = FindVariable (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1934 if (!EFI_ERROR (Status)) {
1935 //
1936 // Update Lang
1937 //
1938 VariableName = EFI_PLATFORM_LANG_VARIABLE_NAME;
1939 Data = GetVariableDataPtr (Variable.CurrPtr);
1940 DataSize = DataSizeOfVariable (Variable.CurrPtr);
1941 } else {
1942 Status = FindVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1943 if (!EFI_ERROR (Status)) {
1944 //
1945 // Update PlatformLang
1946 //
1947 VariableName = EFI_LANG_VARIABLE_NAME;
1948 Data = GetVariableDataPtr (Variable.CurrPtr);
1949 DataSize = DataSizeOfVariable (Variable.CurrPtr);
1950 } else {
1951 //
1952 // Neither PlatformLang nor Lang is set, directly return
1953 //
1954 return EFI_SUCCESS;
1955 }
1956 }
1957 }
1958
1959 Status = EFI_SUCCESS;
1960
1961 //
1962 // According to UEFI spec, "Lang" and "PlatformLang" is NV|BS|RT attributions.
1963 //
1964 Attributes = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS;
1965
1966 if (StrCmp (VariableName, EFI_PLATFORM_LANG_VARIABLE_NAME) == 0) {
1967 //
1968 // Update Lang when PlatformLangCodes/LangCodes were set.
1969 //
1970 if ((mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) {
1971 //
1972 // When setting PlatformLang, firstly get most matched language string from supported language codes.
1973 //
1974 BestPlatformLang = VariableGetBestLanguage (mVariableModuleGlobal->PlatformLangCodes, FALSE, Data, NULL);
1975 if (BestPlatformLang != NULL) {
1976 //
1977 // Get the corresponding index in language codes.
1978 //
1979 Index = GetIndexFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, BestPlatformLang, FALSE);
1980
1981 //
1982 // Get the corresponding ISO639 language tag according to RFC4646 language tag.
1983 //
1984 BestLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, Index, TRUE);
1985
1986 //
1987 // Check the variable space for both Lang and PlatformLang variable.
1988 //
1989 VariableEntry[0].VariableSize = ISO_639_2_ENTRY_SIZE + 1;
1990 VariableEntry[0].Guid = &gEfiGlobalVariableGuid;
1991 VariableEntry[0].Name = EFI_LANG_VARIABLE_NAME;
1992
1993 VariableEntry[1].VariableSize = AsciiStrSize (BestPlatformLang);
1994 VariableEntry[1].Guid = &gEfiGlobalVariableGuid;
1995 VariableEntry[1].Name = EFI_PLATFORM_LANG_VARIABLE_NAME;
1996 if (!CheckRemainingSpaceForConsistency (VARIABLE_ATTRIBUTE_NV_BS_RT, &VariableEntry[0], &VariableEntry[1], NULL)) {
1997 //
1998 // No enough variable space to set both Lang and PlatformLang successfully.
1999 //
2000 Status = EFI_OUT_OF_RESOURCES;
2001 } else {
2002 //
2003 // Successfully convert PlatformLang to Lang, and set the BestLang value into Lang variable simultaneously.
2004 //
2005 FindVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2006
2007 Status = UpdateVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, BestLang,
2008 ISO_639_2_ENTRY_SIZE + 1, Attributes, 0, 0, &Variable, NULL);
2009 }
2010
2011 DEBUG ((EFI_D_INFO, "Variable Driver Auto Update PlatformLang, PlatformLang:%a, Lang:%a Status: %r\n", BestPlatformLang, BestLang, Status));
2012 }
2013 }
2014
2015 } else if (StrCmp (VariableName, EFI_LANG_VARIABLE_NAME) == 0) {
2016 //
2017 // Update PlatformLang when PlatformLangCodes/LangCodes were set.
2018 //
2019 if ((mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) {
2020 //
2021 // When setting Lang, firstly get most matched language string from supported language codes.
2022 //
2023 BestLang = VariableGetBestLanguage (mVariableModuleGlobal->LangCodes, TRUE, Data, NULL);
2024 if (BestLang != NULL) {
2025 //
2026 // Get the corresponding index in language codes.
2027 //
2028 Index = GetIndexFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, BestLang, TRUE);
2029
2030 //
2031 // Get the corresponding RFC4646 language tag according to ISO639 language tag.
2032 //
2033 BestPlatformLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, Index, FALSE);
2034
2035 //
2036 // Check the variable space for both PlatformLang and Lang variable.
2037 //
2038 VariableEntry[0].VariableSize = AsciiStrSize (BestPlatformLang);
2039 VariableEntry[0].Guid = &gEfiGlobalVariableGuid;
2040 VariableEntry[0].Name = EFI_PLATFORM_LANG_VARIABLE_NAME;
2041
2042 VariableEntry[1].VariableSize = ISO_639_2_ENTRY_SIZE + 1;
2043 VariableEntry[1].Guid = &gEfiGlobalVariableGuid;
2044 VariableEntry[1].Name = EFI_LANG_VARIABLE_NAME;
2045 if (!CheckRemainingSpaceForConsistency (VARIABLE_ATTRIBUTE_NV_BS_RT, &VariableEntry[0], &VariableEntry[1], NULL)) {
2046 //
2047 // No enough variable space to set both PlatformLang and Lang successfully.
2048 //
2049 Status = EFI_OUT_OF_RESOURCES;
2050 } else {
2051 //
2052 // Successfully convert Lang to PlatformLang, and set the BestPlatformLang value into PlatformLang variable simultaneously.
2053 //
2054 FindVariable (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2055
2056 Status = UpdateVariable (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, BestPlatformLang,
2057 AsciiStrSize (BestPlatformLang), Attributes, 0, 0, &Variable, NULL);
2058 }
2059
2060 DEBUG ((EFI_D_INFO, "Variable Driver Auto Update Lang, Lang:%a, PlatformLang:%a Status: %r\n", BestLang, BestPlatformLang, Status));
2061 }
2062 }
2063 }
2064
2065 if (SetLanguageCodes) {
2066 //
2067 // Continue to set PlatformLangCodes or LangCodes.
2068 //
2069 return EFI_SUCCESS;
2070 } else {
2071 return Status;
2072 }
2073 }
2074
2075 /**
2076 Compare two EFI_TIME data.
2077
2078
2079 @param FirstTime A pointer to the first EFI_TIME data.
2080 @param SecondTime A pointer to the second EFI_TIME data.
2081
2082 @retval TRUE The FirstTime is not later than the SecondTime.
2083 @retval FALSE The FirstTime is later than the SecondTime.
2084
2085 **/
2086 BOOLEAN
2087 VariableCompareTimeStampInternal (
2088 IN EFI_TIME *FirstTime,
2089 IN EFI_TIME *SecondTime
2090 )
2091 {
2092 if (FirstTime->Year != SecondTime->Year) {
2093 return (BOOLEAN) (FirstTime->Year < SecondTime->Year);
2094 } else if (FirstTime->Month != SecondTime->Month) {
2095 return (BOOLEAN) (FirstTime->Month < SecondTime->Month);
2096 } else if (FirstTime->Day != SecondTime->Day) {
2097 return (BOOLEAN) (FirstTime->Day < SecondTime->Day);
2098 } else if (FirstTime->Hour != SecondTime->Hour) {
2099 return (BOOLEAN) (FirstTime->Hour < SecondTime->Hour);
2100 } else if (FirstTime->Minute != SecondTime->Minute) {
2101 return (BOOLEAN) (FirstTime->Minute < SecondTime->Minute);
2102 }
2103
2104 return (BOOLEAN) (FirstTime->Second <= SecondTime->Second);
2105 }
2106
2107 /**
2108 Update the variable region with Variable information. If EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is set,
2109 index of associated public key is needed.
2110
2111 @param[in] VariableName Name of variable.
2112 @param[in] VendorGuid Guid of variable.
2113 @param[in] Data Variable data.
2114 @param[in] DataSize Size of data. 0 means delete.
2115 @param[in] Attributes Attributes of the variable.
2116 @param[in] KeyIndex Index of associated public key.
2117 @param[in] MonotonicCount Value of associated monotonic count.
2118 @param[in, out] CacheVariable The variable information which is used to keep track of variable usage.
2119 @param[in] TimeStamp Value of associated TimeStamp.
2120
2121 @retval EFI_SUCCESS The update operation is success.
2122 @retval EFI_OUT_OF_RESOURCES Variable region is full, can not write other data into this region.
2123
2124 **/
2125 EFI_STATUS
2126 UpdateVariable (
2127 IN CHAR16 *VariableName,
2128 IN EFI_GUID *VendorGuid,
2129 IN VOID *Data,
2130 IN UINTN DataSize,
2131 IN UINT32 Attributes OPTIONAL,
2132 IN UINT32 KeyIndex OPTIONAL,
2133 IN UINT64 MonotonicCount OPTIONAL,
2134 IN OUT VARIABLE_POINTER_TRACK *CacheVariable,
2135 IN EFI_TIME *TimeStamp OPTIONAL
2136 )
2137 {
2138 EFI_STATUS Status;
2139 VARIABLE_HEADER *NextVariable;
2140 UINTN ScratchSize;
2141 UINTN MaxDataSize;
2142 UINTN VarNameOffset;
2143 UINTN VarDataOffset;
2144 UINTN VarNameSize;
2145 UINTN VarSize;
2146 BOOLEAN Volatile;
2147 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
2148 UINT8 State;
2149 VARIABLE_POINTER_TRACK *Variable;
2150 VARIABLE_POINTER_TRACK NvVariable;
2151 VARIABLE_STORE_HEADER *VariableStoreHeader;
2152 UINTN CacheOffset;
2153 UINT8 *BufferForMerge;
2154 UINTN MergedBufSize;
2155 BOOLEAN DataReady;
2156 UINTN DataOffset;
2157 BOOLEAN IsCommonVariable;
2158 BOOLEAN IsCommonUserVariable;
2159 AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
2160
2161 if (mVariableModuleGlobal->FvbInstance == NULL) {
2162 //
2163 // The FVB protocol is not ready, so the EFI_VARIABLE_WRITE_ARCH_PROTOCOL is not installed.
2164 //
2165 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
2166 //
2167 // Trying to update NV variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
2168 //
2169 DEBUG ((EFI_D_ERROR, "Update NV variable before EFI_VARIABLE_WRITE_ARCH_PROTOCOL ready - %r\n", EFI_NOT_AVAILABLE_YET));
2170 return EFI_NOT_AVAILABLE_YET;
2171 } else if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
2172 //
2173 // Trying to update volatile authenticated variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
2174 // The authenticated variable perhaps is not initialized, just return here.
2175 //
2176 DEBUG ((EFI_D_ERROR, "Update AUTH variable before EFI_VARIABLE_WRITE_ARCH_PROTOCOL ready - %r\n", EFI_NOT_AVAILABLE_YET));
2177 return EFI_NOT_AVAILABLE_YET;
2178 }
2179 }
2180
2181 if ((CacheVariable->CurrPtr == NULL) || CacheVariable->Volatile) {
2182 Variable = CacheVariable;
2183 } else {
2184 //
2185 // Update/Delete existing NV variable.
2186 // CacheVariable points to the variable in the memory copy of Flash area
2187 // Now let Variable points to the same variable in Flash area.
2188 //
2189 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);
2190 Variable = &NvVariable;
2191 Variable->StartPtr = GetStartPointer (VariableStoreHeader);
2192 Variable->EndPtr = GetEndPointer (VariableStoreHeader);
2193 Variable->CurrPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr));
2194 if (CacheVariable->InDeletedTransitionPtr != NULL) {
2195 Variable->InDeletedTransitionPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->InDeletedTransitionPtr - (UINTN)CacheVariable->StartPtr));
2196 } else {
2197 Variable->InDeletedTransitionPtr = NULL;
2198 }
2199 Variable->Volatile = FALSE;
2200 }
2201
2202 Fvb = mVariableModuleGlobal->FvbInstance;
2203
2204 //
2205 // Tricky part: Use scratch data area at the end of volatile variable store
2206 // as a temporary storage.
2207 //
2208 NextVariable = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase));
2209 ScratchSize = mVariableModuleGlobal->ScratchBufferSize;
2210 SetMem (NextVariable, ScratchSize, 0xff);
2211 DataReady = FALSE;
2212
2213 if (Variable->CurrPtr != NULL) {
2214 //
2215 // Update/Delete existing variable.
2216 //
2217 if (AtRuntime ()) {
2218 //
2219 // If AtRuntime and the variable is Volatile and Runtime Access,
2220 // the volatile is ReadOnly, and SetVariable should be aborted and
2221 // return EFI_WRITE_PROTECTED.
2222 //
2223 if (Variable->Volatile) {
2224 Status = EFI_WRITE_PROTECTED;
2225 goto Done;
2226 }
2227 //
2228 // Only variable that have NV attributes can be updated/deleted in Runtime.
2229 //
2230 if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
2231 Status = EFI_INVALID_PARAMETER;
2232 goto Done;
2233 }
2234
2235 //
2236 // Only variable that have RT attributes can be updated/deleted in Runtime.
2237 //
2238 if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) {
2239 Status = EFI_INVALID_PARAMETER;
2240 goto Done;
2241 }
2242 }
2243
2244 //
2245 // Setting a data variable with no access, or zero DataSize attributes
2246 // causes it to be deleted.
2247 // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will
2248 // not delete the variable.
2249 //
2250 if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0))|| ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) {
2251 if (Variable->InDeletedTransitionPtr != NULL) {
2252 //
2253 // Both ADDED and IN_DELETED_TRANSITION variable are present,
2254 // set IN_DELETED_TRANSITION one to DELETED state first.
2255 //
2256 State = Variable->InDeletedTransitionPtr->State;
2257 State &= VAR_DELETED;
2258 Status = UpdateVariableStore (
2259 &mVariableModuleGlobal->VariableGlobal,
2260 Variable->Volatile,
2261 FALSE,
2262 Fvb,
2263 (UINTN) &Variable->InDeletedTransitionPtr->State,
2264 sizeof (UINT8),
2265 &State
2266 );
2267 if (!EFI_ERROR (Status)) {
2268 if (!Variable->Volatile) {
2269 ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
2270 CacheVariable->InDeletedTransitionPtr->State = State;
2271 }
2272 } else {
2273 goto Done;
2274 }
2275 }
2276
2277 State = Variable->CurrPtr->State;
2278 State &= VAR_DELETED;
2279
2280 Status = UpdateVariableStore (
2281 &mVariableModuleGlobal->VariableGlobal,
2282 Variable->Volatile,
2283 FALSE,
2284 Fvb,
2285 (UINTN) &Variable->CurrPtr->State,
2286 sizeof (UINT8),
2287 &State
2288 );
2289 if (!EFI_ERROR (Status)) {
2290 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE);
2291 if (!Variable->Volatile) {
2292 CacheVariable->CurrPtr->State = State;
2293 FlushHobVariableToFlash (VariableName, VendorGuid);
2294 }
2295 }
2296 goto Done;
2297 }
2298 //
2299 // If the variable is marked valid, and the same data has been passed in,
2300 // then return to the caller immediately.
2301 //
2302 if (DataSizeOfVariable (Variable->CurrPtr) == DataSize &&
2303 (CompareMem (Data, GetVariableDataPtr (Variable->CurrPtr), DataSize) == 0) &&
2304 ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) &&
2305 (TimeStamp == NULL)) {
2306 //
2307 // Variable content unchanged and no need to update timestamp, just return.
2308 //
2309 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);
2310 Status = EFI_SUCCESS;
2311 goto Done;
2312 } else if ((Variable->CurrPtr->State == VAR_ADDED) ||
2313 (Variable->CurrPtr->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION))) {
2314
2315 //
2316 // EFI_VARIABLE_APPEND_WRITE attribute only effects for existing variable.
2317 //
2318 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) {
2319 //
2320 // NOTE: From 0 to DataOffset of NextVariable is reserved for Variable Header and Name.
2321 // From DataOffset of NextVariable is to save the existing variable data.
2322 //
2323 DataOffset = GetVariableDataOffset (Variable->CurrPtr);
2324 BufferForMerge = (UINT8 *) ((UINTN) NextVariable + DataOffset);
2325 CopyMem (BufferForMerge, (UINT8 *) ((UINTN) Variable->CurrPtr + DataOffset), DataSizeOfVariable (Variable->CurrPtr));
2326
2327 //
2328 // Set Max Common/Auth Variable Data Size as default MaxDataSize.
2329 //
2330 if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
2331 MaxDataSize = mVariableModuleGlobal->MaxAuthVariableSize - DataOffset;
2332 } else {
2333 MaxDataSize = mVariableModuleGlobal->MaxVariableSize - DataOffset;
2334 }
2335
2336 //
2337 // Append the new data to the end of existing data.
2338 // Max Harware error record variable data size is different from common/auth variable.
2339 //
2340 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2341 MaxDataSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - DataOffset;
2342 }
2343
2344 if (DataSizeOfVariable (Variable->CurrPtr) + DataSize > MaxDataSize) {
2345 //
2346 // Existing data size + new data size exceed maximum variable size limitation.
2347 //
2348 Status = EFI_INVALID_PARAMETER;
2349 goto Done;
2350 }
2351 CopyMem ((UINT8*) ((UINTN) BufferForMerge + DataSizeOfVariable (Variable->CurrPtr)), Data, DataSize);
2352 MergedBufSize = DataSizeOfVariable (Variable->CurrPtr) + DataSize;
2353
2354 //
2355 // BufferForMerge(from DataOffset of NextVariable) has included the merged existing and new data.
2356 //
2357 Data = BufferForMerge;
2358 DataSize = MergedBufSize;
2359 DataReady = TRUE;
2360 }
2361
2362 //
2363 // Mark the old variable as in delete transition.
2364 //
2365 State = Variable->CurrPtr->State;
2366 State &= VAR_IN_DELETED_TRANSITION;
2367
2368 Status = UpdateVariableStore (
2369 &mVariableModuleGlobal->VariableGlobal,
2370 Variable->Volatile,
2371 FALSE,
2372 Fvb,
2373 (UINTN) &Variable->CurrPtr->State,
2374 sizeof (UINT8),
2375 &State
2376 );
2377 if (EFI_ERROR (Status)) {
2378 goto Done;
2379 }
2380 if (!Variable->Volatile) {
2381 CacheVariable->CurrPtr->State = State;
2382 }
2383 }
2384 } else {
2385 //
2386 // Not found existing variable. Create a new variable.
2387 //
2388
2389 if ((DataSize == 0) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0)) {
2390 Status = EFI_SUCCESS;
2391 goto Done;
2392 }
2393
2394 //
2395 // Make sure we are trying to create a new variable.
2396 // Setting a data variable with zero DataSize or no access attributes means to delete it.
2397 //
2398 if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) {
2399 Status = EFI_NOT_FOUND;
2400 goto Done;
2401 }
2402
2403 //
2404 // Only variable have NV|RT attribute can be created in Runtime.
2405 //
2406 if (AtRuntime () &&
2407 (((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0))) {
2408 Status = EFI_INVALID_PARAMETER;
2409 goto Done;
2410 }
2411 }
2412
2413 //
2414 // Function part - create a new variable and copy the data.
2415 // Both update a variable and create a variable will come here.
2416 //
2417 NextVariable->StartId = VARIABLE_DATA;
2418 //
2419 // NextVariable->State = VAR_ADDED;
2420 //
2421 NextVariable->Reserved = 0;
2422 if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
2423 AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) NextVariable;
2424 AuthVariable->PubKeyIndex = KeyIndex;
2425 AuthVariable->MonotonicCount = MonotonicCount;
2426 ZeroMem (&AuthVariable->TimeStamp, sizeof (EFI_TIME));
2427
2428 if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&
2429 (TimeStamp != NULL)) {
2430 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) {
2431 CopyMem (&AuthVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
2432 } else {
2433 //
2434 // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only
2435 // when the new TimeStamp value is later than the current timestamp associated
2436 // with the variable, we need associate the new timestamp with the updated value.
2437 //
2438 if (Variable->CurrPtr != NULL) {
2439 if (VariableCompareTimeStampInternal (&(((AUTHENTICATED_VARIABLE_HEADER *) Variable->CurrPtr)->TimeStamp), TimeStamp)) {
2440 CopyMem (&AuthVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
2441 }
2442 }
2443 }
2444 }
2445 }
2446
2447 //
2448 // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned
2449 // Attributes bitmask parameter of a GetVariable() call.
2450 //
2451 NextVariable->Attributes = Attributes & (~EFI_VARIABLE_APPEND_WRITE);
2452
2453 VarNameOffset = GetVariableHeaderSize ();
2454 VarNameSize = StrSize (VariableName);
2455 CopyMem (
2456 (UINT8 *) ((UINTN) NextVariable + VarNameOffset),
2457 VariableName,
2458 VarNameSize
2459 );
2460 VarDataOffset = VarNameOffset + VarNameSize + GET_PAD_SIZE (VarNameSize);
2461
2462 //
2463 // If DataReady is TRUE, it means the variable data has been saved into
2464 // NextVariable during EFI_VARIABLE_APPEND_WRITE operation preparation.
2465 //
2466 if (!DataReady) {
2467 CopyMem (
2468 (UINT8 *) ((UINTN) NextVariable + VarDataOffset),
2469 Data,
2470 DataSize
2471 );
2472 }
2473
2474 CopyMem (GetVendorGuidPtr (NextVariable), VendorGuid, sizeof (EFI_GUID));
2475 //
2476 // There will be pad bytes after Data, the NextVariable->NameSize and
2477 // NextVariable->DataSize should not include pad size so that variable
2478 // service can get actual size in GetVariable.
2479 //
2480 SetNameSizeOfVariable (NextVariable, VarNameSize);
2481 SetDataSizeOfVariable (NextVariable, DataSize);
2482
2483 //
2484 // The actual size of the variable that stores in storage should
2485 // include pad size.
2486 //
2487 VarSize = VarDataOffset + DataSize + GET_PAD_SIZE (DataSize);
2488 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
2489 //
2490 // Create a nonvolatile variable.
2491 //
2492 Volatile = FALSE;
2493
2494 IsCommonVariable = FALSE;
2495 IsCommonUserVariable = FALSE;
2496 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) {
2497 IsCommonVariable = TRUE;
2498 IsCommonUserVariable = IsUserVariable (NextVariable);
2499 }
2500 if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)
2501 && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))
2502 || (IsCommonVariable && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonVariableSpace))
2503 || (IsCommonVariable && AtRuntime () && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonRuntimeVariableSpace))
2504 || (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace))) {
2505 if (AtRuntime ()) {
2506 if (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace)) {
2507 RecordVarErrorFlag (VAR_ERROR_FLAG_USER_ERROR, VariableName, VendorGuid, Attributes, VarSize);
2508 }
2509 if (IsCommonVariable && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonRuntimeVariableSpace)) {
2510 RecordVarErrorFlag (VAR_ERROR_FLAG_SYSTEM_ERROR, VariableName, VendorGuid, Attributes, VarSize);
2511 }
2512 Status = EFI_OUT_OF_RESOURCES;
2513 goto Done;
2514 }
2515 //
2516 // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.
2517 //
2518 Status = Reclaim (
2519 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
2520 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
2521 FALSE,
2522 Variable,
2523 NextVariable,
2524 HEADER_ALIGN (VarSize)
2525 );
2526 if (!EFI_ERROR (Status)) {
2527 //
2528 // The new variable has been integrated successfully during reclaiming.
2529 //
2530 if (Variable->CurrPtr != NULL) {
2531 CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
2532 CacheVariable->InDeletedTransitionPtr = NULL;
2533 }
2534 UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, TRUE, FALSE, FALSE);
2535 FlushHobVariableToFlash (VariableName, VendorGuid);
2536 } else {
2537 if (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace)) {
2538 RecordVarErrorFlag (VAR_ERROR_FLAG_USER_ERROR, VariableName, VendorGuid, Attributes, VarSize);
2539 }
2540 if (IsCommonVariable && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonVariableSpace)) {
2541 RecordVarErrorFlag (VAR_ERROR_FLAG_SYSTEM_ERROR, VariableName, VendorGuid, Attributes, VarSize);
2542 }
2543 }
2544 goto Done;
2545 }
2546 //
2547 // Four steps
2548 // 1. Write variable header
2549 // 2. Set variable state to header valid
2550 // 3. Write variable data
2551 // 4. Set variable state to valid
2552 //
2553 //
2554 // Step 1:
2555 //
2556 CacheOffset = mVariableModuleGlobal->NonVolatileLastVariableOffset;
2557 Status = UpdateVariableStore (
2558 &mVariableModuleGlobal->VariableGlobal,
2559 FALSE,
2560 TRUE,
2561 Fvb,
2562 mVariableModuleGlobal->NonVolatileLastVariableOffset,
2563 (UINT32) GetVariableHeaderSize (),
2564 (UINT8 *) NextVariable
2565 );
2566
2567 if (EFI_ERROR (Status)) {
2568 goto Done;
2569 }
2570
2571 //
2572 // Step 2:
2573 //
2574 NextVariable->State = VAR_HEADER_VALID_ONLY;
2575 Status = UpdateVariableStore (
2576 &mVariableModuleGlobal->VariableGlobal,
2577 FALSE,
2578 TRUE,
2579 Fvb,
2580 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
2581 sizeof (UINT8),
2582 &NextVariable->State
2583 );
2584
2585 if (EFI_ERROR (Status)) {
2586 goto Done;
2587 }
2588 //
2589 // Step 3:
2590 //
2591 Status = UpdateVariableStore (
2592 &mVariableModuleGlobal->VariableGlobal,
2593 FALSE,
2594 TRUE,
2595 Fvb,
2596 mVariableModuleGlobal->NonVolatileLastVariableOffset + GetVariableHeaderSize (),
2597 (UINT32) (VarSize - GetVariableHeaderSize ()),
2598 (UINT8 *) NextVariable + GetVariableHeaderSize ()
2599 );
2600
2601 if (EFI_ERROR (Status)) {
2602 goto Done;
2603 }
2604 //
2605 // Step 4:
2606 //
2607 NextVariable->State = VAR_ADDED;
2608 Status = UpdateVariableStore (
2609 &mVariableModuleGlobal->VariableGlobal,
2610 FALSE,
2611 TRUE,
2612 Fvb,
2613 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
2614 sizeof (UINT8),
2615 &NextVariable->State
2616 );
2617
2618 if (EFI_ERROR (Status)) {
2619 goto Done;
2620 }
2621
2622 mVariableModuleGlobal->NonVolatileLastVariableOffset += HEADER_ALIGN (VarSize);
2623
2624 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
2625 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VarSize);
2626 } else {
2627 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VarSize);
2628 if (IsCommonUserVariable) {
2629 mVariableModuleGlobal->CommonUserVariableTotalSize += HEADER_ALIGN (VarSize);
2630 }
2631 }
2632 //
2633 // update the memory copy of Flash region.
2634 //
2635 CopyMem ((UINT8 *)mNvVariableCache + CacheOffset, (UINT8 *)NextVariable, VarSize);
2636 } else {
2637 //
2638 // Create a volatile variable.
2639 //
2640 Volatile = TRUE;
2641
2642 if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >
2643 ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size) {
2644 //
2645 // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.
2646 //
2647 Status = Reclaim (
2648 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,
2649 &mVariableModuleGlobal->VolatileLastVariableOffset,
2650 TRUE,
2651 Variable,
2652 NextVariable,
2653 HEADER_ALIGN (VarSize)
2654 );
2655 if (!EFI_ERROR (Status)) {
2656 //
2657 // The new variable has been integrated successfully during reclaiming.
2658 //
2659 if (Variable->CurrPtr != NULL) {
2660 CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
2661 CacheVariable->InDeletedTransitionPtr = NULL;
2662 }
2663 UpdateVariableInfo (VariableName, VendorGuid, TRUE, FALSE, TRUE, FALSE, FALSE);
2664 }
2665 goto Done;
2666 }
2667
2668 NextVariable->State = VAR_ADDED;
2669 Status = UpdateVariableStore (
2670 &mVariableModuleGlobal->VariableGlobal,
2671 TRUE,
2672 TRUE,
2673 Fvb,
2674 mVariableModuleGlobal->VolatileLastVariableOffset,
2675 (UINT32) VarSize,
2676 (UINT8 *) NextVariable
2677 );
2678
2679 if (EFI_ERROR (Status)) {
2680 goto Done;
2681 }
2682
2683 mVariableModuleGlobal->VolatileLastVariableOffset += HEADER_ALIGN (VarSize);
2684 }
2685
2686 //
2687 // Mark the old variable as deleted.
2688 //
2689 if (!EFI_ERROR (Status) && Variable->CurrPtr != NULL) {
2690 if (Variable->InDeletedTransitionPtr != NULL) {
2691 //
2692 // Both ADDED and IN_DELETED_TRANSITION old variable are present,
2693 // set IN_DELETED_TRANSITION one to DELETED state first.
2694 //
2695 State = Variable->InDeletedTransitionPtr->State;
2696 State &= VAR_DELETED;
2697 Status = UpdateVariableStore (
2698 &mVariableModuleGlobal->VariableGlobal,
2699 Variable->Volatile,
2700 FALSE,
2701 Fvb,
2702 (UINTN) &Variable->InDeletedTransitionPtr->State,
2703 sizeof (UINT8),
2704 &State
2705 );
2706 if (!EFI_ERROR (Status)) {
2707 if (!Variable->Volatile) {
2708 ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
2709 CacheVariable->InDeletedTransitionPtr->State = State;
2710 }
2711 } else {
2712 goto Done;
2713 }
2714 }
2715
2716 State = Variable->CurrPtr->State;
2717 State &= VAR_DELETED;
2718
2719 Status = UpdateVariableStore (
2720 &mVariableModuleGlobal->VariableGlobal,
2721 Variable->Volatile,
2722 FALSE,
2723 Fvb,
2724 (UINTN) &Variable->CurrPtr->State,
2725 sizeof (UINT8),
2726 &State
2727 );
2728 if (!EFI_ERROR (Status) && !Variable->Volatile) {
2729 CacheVariable->CurrPtr->State = State;
2730 }
2731 }
2732
2733 if (!EFI_ERROR (Status)) {
2734 UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);
2735 if (!Volatile) {
2736 FlushHobVariableToFlash (VariableName, VendorGuid);
2737 }
2738 }
2739
2740 Done:
2741 return Status;
2742 }
2743
2744 /**
2745 Check if a Unicode character is a hexadecimal character.
2746
2747 This function checks if a Unicode character is a
2748 hexadecimal character. The valid hexadecimal character is
2749 L'0' to L'9', L'a' to L'f', or L'A' to L'F'.
2750
2751
2752 @param Char The character to check against.
2753
2754 @retval TRUE If the Char is a hexadecmial character.
2755 @retval FALSE If the Char is not a hexadecmial character.
2756
2757 **/
2758 BOOLEAN
2759 EFIAPI
2760 IsHexaDecimalDigitCharacter (
2761 IN CHAR16 Char
2762 )
2763 {
2764 return (BOOLEAN) ((Char >= L'0' && Char <= L'9') || (Char >= L'A' && Char <= L'F') || (Char >= L'a' && Char <= L'f'));
2765 }
2766
2767 /**
2768
2769 This code checks if variable is hardware error record variable or not.
2770
2771 According to UEFI spec, hardware error record variable should use the EFI_HARDWARE_ERROR_VARIABLE VendorGuid
2772 and have the L"HwErrRec####" name convention, #### is a printed hex value and no 0x or h is included in the hex value.
2773
2774 @param VariableName Pointer to variable name.
2775 @param VendorGuid Variable Vendor Guid.
2776
2777 @retval TRUE Variable is hardware error record variable.
2778 @retval FALSE Variable is not hardware error record variable.
2779
2780 **/
2781 BOOLEAN
2782 EFIAPI
2783 IsHwErrRecVariable (
2784 IN CHAR16 *VariableName,
2785 IN EFI_GUID *VendorGuid
2786 )
2787 {
2788 if (!CompareGuid (VendorGuid, &gEfiHardwareErrorVariableGuid) ||
2789 (StrLen (VariableName) != StrLen (L"HwErrRec####")) ||
2790 (StrnCmp(VariableName, L"HwErrRec", StrLen (L"HwErrRec")) != 0) ||
2791 !IsHexaDecimalDigitCharacter (VariableName[0x8]) ||
2792 !IsHexaDecimalDigitCharacter (VariableName[0x9]) ||
2793 !IsHexaDecimalDigitCharacter (VariableName[0xA]) ||
2794 !IsHexaDecimalDigitCharacter (VariableName[0xB])) {
2795 return FALSE;
2796 }
2797
2798 return TRUE;
2799 }
2800
2801 /**
2802 Mark a variable that will become read-only after leaving the DXE phase of execution.
2803
2804
2805 @param[in] This The VARIABLE_LOCK_PROTOCOL instance.
2806 @param[in] VariableName A pointer to the variable name that will be made read-only subsequently.
2807 @param[in] VendorGuid A pointer to the vendor GUID that will be made read-only subsequently.
2808
2809 @retval EFI_SUCCESS The variable specified by the VariableName and the VendorGuid was marked
2810 as pending to be read-only.
2811 @retval EFI_INVALID_PARAMETER VariableName or VendorGuid is NULL.
2812 Or VariableName is an empty string.
2813 @retval EFI_ACCESS_DENIED EFI_END_OF_DXE_EVENT_GROUP_GUID or EFI_EVENT_GROUP_READY_TO_BOOT has
2814 already been signaled.
2815 @retval EFI_OUT_OF_RESOURCES There is not enough resource to hold the lock request.
2816 **/
2817 EFI_STATUS
2818 EFIAPI
2819 VariableLockRequestToLock (
2820 IN CONST EDKII_VARIABLE_LOCK_PROTOCOL *This,
2821 IN CHAR16 *VariableName,
2822 IN EFI_GUID *VendorGuid
2823 )
2824 {
2825 VARIABLE_ENTRY *Entry;
2826 CHAR16 *Name;
2827 LIST_ENTRY *Link;
2828 VARIABLE_ENTRY *LockedEntry;
2829
2830 if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {
2831 return EFI_INVALID_PARAMETER;
2832 }
2833
2834 if (mEndOfDxe) {
2835 return EFI_ACCESS_DENIED;
2836 }
2837
2838 Entry = AllocateRuntimeZeroPool (sizeof (*Entry) + StrSize (VariableName));
2839 if (Entry == NULL) {
2840 return EFI_OUT_OF_RESOURCES;
2841 }
2842
2843 DEBUG ((EFI_D_INFO, "[Variable] Lock: %g:%s\n", VendorGuid, VariableName));
2844
2845 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2846
2847 for ( Link = GetFirstNode (&mLockedVariableList)
2848 ; !IsNull (&mLockedVariableList, Link)
2849 ; Link = GetNextNode (&mLockedVariableList, Link)
2850 ) {
2851 LockedEntry = BASE_CR (Link, VARIABLE_ENTRY, Link);
2852 Name = (CHAR16 *) ((UINTN) LockedEntry + sizeof (*LockedEntry));
2853 if (CompareGuid (&LockedEntry->Guid, VendorGuid) && (StrCmp (Name, VariableName) == 0)) {
2854 goto Done;
2855 }
2856 }
2857
2858 Name = (CHAR16 *) ((UINTN) Entry + sizeof (*Entry));
2859 StrCpyS (Name, StrSize (VariableName)/sizeof(CHAR16), VariableName);
2860 CopyGuid (&Entry->Guid, VendorGuid);
2861 InsertTailList (&mLockedVariableList, &Entry->Link);
2862
2863 Done:
2864 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2865
2866 return EFI_SUCCESS;
2867 }
2868
2869 /**
2870
2871 This code finds variable in storage blocks (Volatile or Non-Volatile).
2872
2873 Caution: This function may receive untrusted input.
2874 This function may be invoked in SMM mode, and datasize is external input.
2875 This function will do basic validation, before parse the data.
2876
2877 @param VariableName Name of Variable to be found.
2878 @param VendorGuid Variable vendor GUID.
2879 @param Attributes Attribute value of the variable found.
2880 @param DataSize Size of Data found. If size is less than the
2881 data, this value contains the required size.
2882 @param Data Data pointer.
2883
2884 @return EFI_INVALID_PARAMETER Invalid parameter.
2885 @return EFI_SUCCESS Find the specified variable.
2886 @return EFI_NOT_FOUND Not found.
2887 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2888
2889 **/
2890 EFI_STATUS
2891 EFIAPI
2892 VariableServiceGetVariable (
2893 IN CHAR16 *VariableName,
2894 IN EFI_GUID *VendorGuid,
2895 OUT UINT32 *Attributes OPTIONAL,
2896 IN OUT UINTN *DataSize,
2897 OUT VOID *Data
2898 )
2899 {
2900 EFI_STATUS Status;
2901 VARIABLE_POINTER_TRACK Variable;
2902 UINTN VarDataSize;
2903
2904 if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {
2905 return EFI_INVALID_PARAMETER;
2906 }
2907
2908 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2909
2910 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2911 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2912 goto Done;
2913 }
2914
2915 //
2916 // Get data size
2917 //
2918 VarDataSize = DataSizeOfVariable (Variable.CurrPtr);
2919 ASSERT (VarDataSize != 0);
2920
2921 if (*DataSize >= VarDataSize) {
2922 if (Data == NULL) {
2923 Status = EFI_INVALID_PARAMETER;
2924 goto Done;
2925 }
2926
2927 CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr), VarDataSize);
2928 if (Attributes != NULL) {
2929 *Attributes = Variable.CurrPtr->Attributes;
2930 }
2931
2932 *DataSize = VarDataSize;
2933 UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);
2934
2935 Status = EFI_SUCCESS;
2936 goto Done;
2937 } else {
2938 *DataSize = VarDataSize;
2939 Status = EFI_BUFFER_TOO_SMALL;
2940 goto Done;
2941 }
2942
2943 Done:
2944 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2945 return Status;
2946 }
2947
2948 /**
2949 This code Finds the Next available variable.
2950
2951 Caution: This function may receive untrusted input.
2952 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2953
2954 @param[in] VariableName Pointer to variable name.
2955 @param[in] VendorGuid Variable Vendor Guid.
2956 @param[out] VariablePtr Pointer to variable header address.
2957
2958 @return EFI_SUCCESS Find the specified variable.
2959 @return EFI_NOT_FOUND Not found.
2960
2961 **/
2962 EFI_STATUS
2963 EFIAPI
2964 VariableServiceGetNextVariableInternal (
2965 IN CHAR16 *VariableName,
2966 IN EFI_GUID *VendorGuid,
2967 OUT VARIABLE_HEADER **VariablePtr
2968 )
2969 {
2970 VARIABLE_STORE_TYPE Type;
2971 VARIABLE_POINTER_TRACK Variable;
2972 VARIABLE_POINTER_TRACK VariableInHob;
2973 VARIABLE_POINTER_TRACK VariablePtrTrack;
2974 EFI_STATUS Status;
2975 VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
2976
2977 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2978 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2979 goto Done;
2980 }
2981
2982 if (VariableName[0] != 0) {
2983 //
2984 // If variable name is not NULL, get next variable.
2985 //
2986 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2987 }
2988
2989 //
2990 // 0: Volatile, 1: HOB, 2: Non-Volatile.
2991 // The index and attributes mapping must be kept in this order as FindVariable
2992 // makes use of this mapping to implement search algorithm.
2993 //
2994 VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
2995 VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
2996 VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
2997
2998 while (TRUE) {
2999 //
3000 // Switch from Volatile to HOB, to Non-Volatile.
3001 //
3002 while (!IsValidVariableHeader (Variable.CurrPtr, Variable.EndPtr)) {
3003 //
3004 // Find current storage index
3005 //
3006 for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
3007 if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
3008 break;
3009 }
3010 }
3011 ASSERT (Type < VariableStoreTypeMax);
3012 //
3013 // Switch to next storage
3014 //
3015 for (Type++; Type < VariableStoreTypeMax; Type++) {
3016 if (VariableStoreHeader[Type] != NULL) {
3017 break;
3018 }
3019 }
3020 //
3021 // Capture the case that
3022 // 1. current storage is the last one, or
3023 // 2. no further storage
3024 //
3025 if (Type == VariableStoreTypeMax) {
3026 Status = EFI_NOT_FOUND;
3027 goto Done;
3028 }
3029 Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);
3030 Variable.EndPtr = GetEndPointer (VariableStoreHeader[Type]);
3031 Variable.CurrPtr = Variable.StartPtr;
3032 }
3033
3034 //
3035 // Variable is found
3036 //
3037 if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
3038 if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
3039 if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
3040 //
3041 // If it is a IN_DELETED_TRANSITION variable,
3042 // and there is also a same ADDED one at the same time,
3043 // don't return it.
3044 //
3045 VariablePtrTrack.StartPtr = Variable.StartPtr;
3046 VariablePtrTrack.EndPtr = Variable.EndPtr;
3047 Status = FindVariableEx (
3048 GetVariableNamePtr (Variable.CurrPtr),
3049 GetVendorGuidPtr (Variable.CurrPtr),
3050 FALSE,
3051 &VariablePtrTrack
3052 );
3053 if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
3054 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
3055 continue;
3056 }
3057 }
3058
3059 //
3060 // Don't return NV variable when HOB overrides it
3061 //
3062 if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&
3063 (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))
3064 ) {
3065 VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);
3066 VariableInHob.EndPtr = GetEndPointer (VariableStoreHeader[VariableStoreTypeHob]);
3067 Status = FindVariableEx (
3068 GetVariableNamePtr (Variable.CurrPtr),
3069 GetVendorGuidPtr (Variable.CurrPtr),
3070 FALSE,
3071 &VariableInHob
3072 );
3073 if (!EFI_ERROR (Status)) {
3074 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
3075 continue;
3076 }
3077 }
3078
3079 *VariablePtr = Variable.CurrPtr;
3080 Status = EFI_SUCCESS;
3081 goto Done;
3082 }
3083 }
3084
3085 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
3086 }
3087
3088 Done:
3089 return Status;
3090 }
3091
3092 /**
3093
3094 This code Finds the Next available variable.
3095
3096 Caution: This function may receive untrusted input.
3097 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
3098
3099 @param VariableNameSize Size of the variable name.
3100 @param VariableName Pointer to variable name.
3101 @param VendorGuid Variable Vendor Guid.
3102
3103 @return EFI_INVALID_PARAMETER Invalid parameter.
3104 @return EFI_SUCCESS Find the specified variable.
3105 @return EFI_NOT_FOUND Not found.
3106 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
3107
3108 **/
3109 EFI_STATUS
3110 EFIAPI
3111 VariableServiceGetNextVariableName (
3112 IN OUT UINTN *VariableNameSize,
3113 IN OUT CHAR16 *VariableName,
3114 IN OUT EFI_GUID *VendorGuid
3115 )
3116 {
3117 EFI_STATUS Status;
3118 UINTN VarNameSize;
3119 VARIABLE_HEADER *VariablePtr;
3120
3121 if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
3122 return EFI_INVALID_PARAMETER;
3123 }
3124
3125 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3126
3127 Status = VariableServiceGetNextVariableInternal (VariableName, VendorGuid, &VariablePtr);
3128 if (!EFI_ERROR (Status)) {
3129 VarNameSize = NameSizeOfVariable (VariablePtr);
3130 ASSERT (VarNameSize != 0);
3131 if (VarNameSize <= *VariableNameSize) {
3132 CopyMem (VariableName, GetVariableNamePtr (VariablePtr), VarNameSize);
3133 CopyMem (VendorGuid, GetVendorGuidPtr (VariablePtr), sizeof (EFI_GUID));
3134 Status = EFI_SUCCESS;
3135 } else {
3136 Status = EFI_BUFFER_TOO_SMALL;
3137 }
3138
3139 *VariableNameSize = VarNameSize;
3140 }
3141
3142 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3143 return Status;
3144 }
3145
3146 /**
3147
3148 This code sets variable in storage blocks (Volatile or Non-Volatile).
3149
3150 Caution: This function may receive untrusted input.
3151 This function may be invoked in SMM mode, and datasize and data are external input.
3152 This function will do basic validation, before parse the data.
3153 This function will parse the authentication carefully to avoid security issues, like
3154 buffer overflow, integer overflow.
3155 This function will check attribute carefully to avoid authentication bypass.
3156
3157 @param VariableName Name of Variable to be found.
3158 @param VendorGuid Variable vendor GUID.
3159 @param Attributes Attribute value of the variable found
3160 @param DataSize Size of Data found. If size is less than the
3161 data, this value contains the required size.
3162 @param Data Data pointer.
3163
3164 @return EFI_INVALID_PARAMETER Invalid parameter.
3165 @return EFI_SUCCESS Set successfully.
3166 @return EFI_OUT_OF_RESOURCES Resource not enough to set variable.
3167 @return EFI_NOT_FOUND Not found.
3168 @return EFI_WRITE_PROTECTED Variable is read-only.
3169
3170 **/
3171 EFI_STATUS
3172 EFIAPI
3173 VariableServiceSetVariable (
3174 IN CHAR16 *VariableName,
3175 IN EFI_GUID *VendorGuid,
3176 IN UINT32 Attributes,
3177 IN UINTN DataSize,
3178 IN VOID *Data
3179 )
3180 {
3181 VARIABLE_POINTER_TRACK Variable;
3182 EFI_STATUS Status;
3183 VARIABLE_HEADER *NextVariable;
3184 EFI_PHYSICAL_ADDRESS Point;
3185 UINTN PayloadSize;
3186 LIST_ENTRY *Link;
3187 VARIABLE_ENTRY *Entry;
3188 CHAR16 *Name;
3189
3190 //
3191 // Check input parameters.
3192 //
3193 if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {
3194 return EFI_INVALID_PARAMETER;
3195 }
3196
3197 if (DataSize != 0 && Data == NULL) {
3198 return EFI_INVALID_PARAMETER;
3199 }
3200
3201 //
3202 // Check for reserverd bit in variable attribute.
3203 //
3204 if ((Attributes & (~EFI_VARIABLE_ATTRIBUTES_MASK)) != 0) {
3205 return EFI_INVALID_PARAMETER;
3206 }
3207
3208 //
3209 // Make sure if runtime bit is set, boot service bit is set also.
3210 //
3211 if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
3212 return EFI_INVALID_PARAMETER;
3213 } else if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
3214 if (!mVariableModuleGlobal->VariableGlobal.AuthSupport) {
3215 //
3216 // Not support authenticated variable write.
3217 //
3218 return EFI_INVALID_PARAMETER;
3219 }
3220 } else if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
3221 if (PcdGet32 (PcdHwErrStorageSize) == 0) {
3222 //
3223 // Not support harware error record variable variable.
3224 //
3225 return EFI_INVALID_PARAMETER;
3226 }
3227 }
3228
3229 //
3230 // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute
3231 // cannot be set both.
3232 //
3233 if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)
3234 && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {
3235 return EFI_INVALID_PARAMETER;
3236 }
3237
3238 if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {
3239 if (DataSize < AUTHINFO_SIZE) {
3240 //
3241 // Try to write Authenticated Variable without AuthInfo.
3242 //
3243 return EFI_SECURITY_VIOLATION;
3244 }
3245 PayloadSize = DataSize - AUTHINFO_SIZE;
3246 } else if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {
3247 //
3248 // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor.
3249 //
3250 if (DataSize < OFFSET_OF_AUTHINFO2_CERT_DATA ||
3251 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength > DataSize - (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) ||
3252 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength < OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) {
3253 return EFI_SECURITY_VIOLATION;
3254 }
3255 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
3256 } else {
3257 PayloadSize = DataSize;
3258 }
3259
3260 if ((UINTN)(~0) - PayloadSize < StrSize(VariableName)){
3261 //
3262 // Prevent whole variable size overflow
3263 //
3264 return EFI_INVALID_PARAMETER;
3265 }
3266
3267 //
3268 // The size of the VariableName, including the Unicode Null in bytes plus
3269 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)
3270 // bytes for HwErrRec#### variable.
3271 //
3272 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3273 if (StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize ()) {
3274 return EFI_INVALID_PARAMETER;
3275 }
3276 if (!IsHwErrRecVariable(VariableName, VendorGuid)) {
3277 return EFI_INVALID_PARAMETER;
3278 }
3279 } else {
3280 //
3281 // The size of the VariableName, including the Unicode Null in bytes plus
3282 // the DataSize is limited to maximum size of Max(Auth)VariableSize bytes.
3283 //
3284 if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
3285 if (StrSize (VariableName) + PayloadSize > mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ()) {
3286 return EFI_INVALID_PARAMETER;
3287 }
3288 } else {
3289 if (StrSize (VariableName) + PayloadSize > mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize ()) {
3290 return EFI_INVALID_PARAMETER;
3291 }
3292 }
3293 }
3294
3295 Status = InternalVarCheckSetVariableCheck (VariableName, VendorGuid, Attributes, PayloadSize, (VOID *) ((UINTN) Data + DataSize - PayloadSize));
3296 if (EFI_ERROR (Status)) {
3297 return Status;
3298 }
3299
3300 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3301
3302 //
3303 // Consider reentrant in MCA/INIT/NMI. It needs be reupdated.
3304 //
3305 if (1 < InterlockedIncrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState)) {
3306 Point = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
3307 //
3308 // Parse non-volatile variable data and get last variable offset.
3309 //
3310 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point);
3311 while (IsValidVariableHeader (NextVariable, GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point))) {
3312 NextVariable = GetNextVariablePtr (NextVariable);
3313 }
3314 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point;
3315 }
3316
3317 if (mEndOfDxe && mEnableLocking) {
3318 //
3319 // Treat the variables listed in the forbidden variable list as read-only after leaving DXE phase.
3320 //
3321 for ( Link = GetFirstNode (&mLockedVariableList)
3322 ; !IsNull (&mLockedVariableList, Link)
3323 ; Link = GetNextNode (&mLockedVariableList, Link)
3324 ) {
3325 Entry = BASE_CR (Link, VARIABLE_ENTRY, Link);
3326 Name = (CHAR16 *) ((UINTN) Entry + sizeof (*Entry));
3327 if (CompareGuid (&Entry->Guid, VendorGuid) && (StrCmp (Name, VariableName) == 0)) {
3328 Status = EFI_WRITE_PROTECTED;
3329 DEBUG ((EFI_D_INFO, "[Variable]: Changing readonly variable after leaving DXE phase - %g:%s\n", VendorGuid, VariableName));
3330 goto Done;
3331 }
3332 }
3333 }
3334
3335 //
3336 // Check whether the input variable is already existed.
3337 //
3338 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, TRUE);
3339 if (!EFI_ERROR (Status)) {
3340 if (((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) && AtRuntime ()) {
3341 Status = EFI_WRITE_PROTECTED;
3342 goto Done;
3343 }
3344 if (Attributes != 0 && (Attributes & (~EFI_VARIABLE_APPEND_WRITE)) != Variable.CurrPtr->Attributes) {
3345 //
3346 // If a preexisting variable is rewritten with different attributes, SetVariable() shall not
3347 // modify the variable and shall return EFI_INVALID_PARAMETER. Two exceptions to this rule:
3348 // 1. No access attributes specified
3349 // 2. The only attribute differing is EFI_VARIABLE_APPEND_WRITE
3350 //
3351 Status = EFI_INVALID_PARAMETER;
3352 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));
3353 goto Done;
3354 }
3355 }
3356
3357 if (!FeaturePcdGet (PcdUefiVariableDefaultLangDeprecate)) {
3358 //
3359 // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.
3360 //
3361 Status = AutoUpdateLangVariable (VariableName, Data, DataSize);
3362 if (EFI_ERROR (Status)) {
3363 //
3364 // The auto update operation failed, directly return to avoid inconsistency between PlatformLang and Lang.
3365 //
3366 goto Done;
3367 }
3368 }
3369
3370 if (mVariableModuleGlobal->VariableGlobal.AuthSupport) {
3371 Status = AuthVariableLibProcessVariable (VariableName, VendorGuid, Data, DataSize, Attributes);
3372 } else {
3373 Status = UpdateVariable (VariableName, VendorGuid, Data, DataSize, Attributes, 0, 0, &Variable, NULL);
3374 }
3375
3376 Done:
3377 InterlockedDecrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState);
3378 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3379
3380 if (!AtRuntime ()) {
3381 if (!EFI_ERROR (Status)) {
3382 SecureBootHook (
3383 VariableName,
3384 VendorGuid
3385 );
3386 }
3387 }
3388
3389 return Status;
3390 }
3391
3392 /**
3393
3394 This code returns information about the EFI variables.
3395
3396 Caution: This function may receive untrusted input.
3397 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
3398
3399 @param Attributes Attributes bitmask to specify the type of variables
3400 on which to return information.
3401 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
3402 for the EFI variables associated with the attributes specified.
3403 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
3404 for EFI variables associated with the attributes specified.
3405 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
3406 associated with the attributes specified.
3407
3408 @return EFI_SUCCESS Query successfully.
3409
3410 **/
3411 EFI_STATUS
3412 EFIAPI
3413 VariableServiceQueryVariableInfoInternal (
3414 IN UINT32 Attributes,
3415 OUT UINT64 *MaximumVariableStorageSize,
3416 OUT UINT64 *RemainingVariableStorageSize,
3417 OUT UINT64 *MaximumVariableSize
3418 )
3419 {
3420 VARIABLE_HEADER *Variable;
3421 VARIABLE_HEADER *NextVariable;
3422 UINT64 VariableSize;
3423 VARIABLE_STORE_HEADER *VariableStoreHeader;
3424 UINT64 CommonVariableTotalSize;
3425 UINT64 HwErrVariableTotalSize;
3426 EFI_STATUS Status;
3427 VARIABLE_POINTER_TRACK VariablePtrTrack;
3428
3429 CommonVariableTotalSize = 0;
3430 HwErrVariableTotalSize = 0;
3431
3432 if((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
3433 //
3434 // Query is Volatile related.
3435 //
3436 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
3437 } else {
3438 //
3439 // Query is Non-Volatile related.
3440 //
3441 VariableStoreHeader = mNvVariableCache;
3442 }
3443
3444 //
3445 // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize
3446 // with the storage size (excluding the storage header size).
3447 //
3448 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);
3449
3450 //
3451 // Harware error record variable needs larger size.
3452 //
3453 if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
3454 *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize);
3455 *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize ();
3456 } else {
3457 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
3458 if (AtRuntime ()) {
3459 *MaximumVariableStorageSize = mVariableModuleGlobal->CommonRuntimeVariableSpace;
3460 } else {
3461 *MaximumVariableStorageSize = mVariableModuleGlobal->CommonVariableSpace;
3462 }
3463 }
3464
3465 //
3466 // Let *MaximumVariableSize be Max(Auth)VariableSize with the exception of the variable header size.
3467 //
3468 if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
3469 *MaximumVariableSize = mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ();
3470 } else {
3471 *MaximumVariableSize = mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize ();
3472 }
3473 }
3474
3475 //
3476 // Point to the starting address of the variables.
3477 //
3478 Variable = GetStartPointer (VariableStoreHeader);
3479
3480 //
3481 // Now walk through the related variable store.
3482 //
3483 while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
3484 NextVariable = GetNextVariablePtr (Variable);
3485 VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable;
3486
3487 if (AtRuntime ()) {
3488 //
3489 // We don't take the state of the variables in mind
3490 // when calculating RemainingVariableStorageSize,
3491 // since the space occupied by variables not marked with
3492 // VAR_ADDED is not allowed to be reclaimed in Runtime.
3493 //
3494 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3495 HwErrVariableTotalSize += VariableSize;
3496 } else {
3497 CommonVariableTotalSize += VariableSize;
3498 }
3499 } else {
3500 //
3501 // Only care about Variables with State VAR_ADDED, because
3502 // the space not marked as VAR_ADDED is reclaimable now.
3503 //
3504 if (Variable->State == VAR_ADDED) {
3505 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3506 HwErrVariableTotalSize += VariableSize;
3507 } else {
3508 CommonVariableTotalSize += VariableSize;
3509 }
3510 } else if (Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
3511 //
3512 // If it is a IN_DELETED_TRANSITION variable,
3513 // and there is not also a same ADDED one at the same time,
3514 // this IN_DELETED_TRANSITION variable is valid.
3515 //
3516 VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader);
3517 VariablePtrTrack.EndPtr = GetEndPointer (VariableStoreHeader);
3518 Status = FindVariableEx (
3519 GetVariableNamePtr (Variable),
3520 GetVendorGuidPtr (Variable),
3521 FALSE,
3522 &VariablePtrTrack
3523 );
3524 if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State != VAR_ADDED) {
3525 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3526 HwErrVariableTotalSize += VariableSize;
3527 } else {
3528 CommonVariableTotalSize += VariableSize;
3529 }
3530 }
3531 }
3532 }
3533
3534 //
3535 // Go to the next one.
3536 //
3537 Variable = NextVariable;
3538 }
3539
3540 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD){
3541 *RemainingVariableStorageSize = *MaximumVariableStorageSize - HwErrVariableTotalSize;
3542 } else {
3543 if (*MaximumVariableStorageSize < CommonVariableTotalSize) {
3544 *RemainingVariableStorageSize = 0;