]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
MdeModulePkg Variable: Handle variable Attributes mismatch case
[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 //
2182 // Check if CacheVariable points to the variable in variable HOB.
2183 // If yes, let CacheVariable points to the variable in NV variable cache.
2184 //
2185 if ((CacheVariable->CurrPtr != NULL) &&
2186 (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) &&
2187 (CacheVariable->StartPtr == GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase))
2188 ) {
2189 CacheVariable->StartPtr = GetStartPointer (mNvVariableCache);
2190 CacheVariable->EndPtr = GetEndPointer (mNvVariableCache);
2191 CacheVariable->Volatile = FALSE;
2192 Status = FindVariableEx (VariableName, VendorGuid, FALSE, CacheVariable);
2193 if (CacheVariable->CurrPtr == NULL || EFI_ERROR (Status)) {
2194 //
2195 // There is no matched variable in NV variable cache.
2196 //
2197 if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0)) || (Attributes == 0)) {
2198 //
2199 // It is to delete variable,
2200 // go to delete this variable in variable HOB and
2201 // try to flush other variables from HOB to flash.
2202 //
2203 FlushHobVariableToFlash (VariableName, VendorGuid);
2204 return EFI_SUCCESS;
2205 }
2206 }
2207 }
2208
2209 if ((CacheVariable->CurrPtr == NULL) || CacheVariable->Volatile) {
2210 Variable = CacheVariable;
2211 } else {
2212 //
2213 // Update/Delete existing NV variable.
2214 // CacheVariable points to the variable in the memory copy of Flash area
2215 // Now let Variable points to the same variable in Flash area.
2216 //
2217 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);
2218 Variable = &NvVariable;
2219 Variable->StartPtr = GetStartPointer (VariableStoreHeader);
2220 Variable->EndPtr = GetEndPointer (VariableStoreHeader);
2221 Variable->CurrPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr));
2222 if (CacheVariable->InDeletedTransitionPtr != NULL) {
2223 Variable->InDeletedTransitionPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->InDeletedTransitionPtr - (UINTN)CacheVariable->StartPtr));
2224 } else {
2225 Variable->InDeletedTransitionPtr = NULL;
2226 }
2227 Variable->Volatile = FALSE;
2228 }
2229
2230 Fvb = mVariableModuleGlobal->FvbInstance;
2231
2232 //
2233 // Tricky part: Use scratch data area at the end of volatile variable store
2234 // as a temporary storage.
2235 //
2236 NextVariable = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase));
2237 ScratchSize = mVariableModuleGlobal->ScratchBufferSize;
2238 SetMem (NextVariable, ScratchSize, 0xff);
2239 DataReady = FALSE;
2240
2241 if (Variable->CurrPtr != NULL) {
2242 //
2243 // Update/Delete existing variable.
2244 //
2245 if (AtRuntime ()) {
2246 //
2247 // If AtRuntime and the variable is Volatile and Runtime Access,
2248 // the volatile is ReadOnly, and SetVariable should be aborted and
2249 // return EFI_WRITE_PROTECTED.
2250 //
2251 if (Variable->Volatile) {
2252 Status = EFI_WRITE_PROTECTED;
2253 goto Done;
2254 }
2255 //
2256 // Only variable that have NV attributes can be updated/deleted in Runtime.
2257 //
2258 if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
2259 Status = EFI_INVALID_PARAMETER;
2260 goto Done;
2261 }
2262
2263 //
2264 // Only variable that have RT attributes can be updated/deleted in Runtime.
2265 //
2266 if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) {
2267 Status = EFI_INVALID_PARAMETER;
2268 goto Done;
2269 }
2270 }
2271
2272 //
2273 // Setting a data variable with no access, or zero DataSize attributes
2274 // causes it to be deleted.
2275 // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will
2276 // not delete the variable.
2277 //
2278 if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0))|| ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) {
2279 if (Variable->InDeletedTransitionPtr != NULL) {
2280 //
2281 // Both ADDED and IN_DELETED_TRANSITION variable are present,
2282 // set IN_DELETED_TRANSITION one to DELETED state first.
2283 //
2284 State = Variable->InDeletedTransitionPtr->State;
2285 State &= VAR_DELETED;
2286 Status = UpdateVariableStore (
2287 &mVariableModuleGlobal->VariableGlobal,
2288 Variable->Volatile,
2289 FALSE,
2290 Fvb,
2291 (UINTN) &Variable->InDeletedTransitionPtr->State,
2292 sizeof (UINT8),
2293 &State
2294 );
2295 if (!EFI_ERROR (Status)) {
2296 if (!Variable->Volatile) {
2297 ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
2298 CacheVariable->InDeletedTransitionPtr->State = State;
2299 }
2300 } else {
2301 goto Done;
2302 }
2303 }
2304
2305 State = Variable->CurrPtr->State;
2306 State &= VAR_DELETED;
2307
2308 Status = UpdateVariableStore (
2309 &mVariableModuleGlobal->VariableGlobal,
2310 Variable->Volatile,
2311 FALSE,
2312 Fvb,
2313 (UINTN) &Variable->CurrPtr->State,
2314 sizeof (UINT8),
2315 &State
2316 );
2317 if (!EFI_ERROR (Status)) {
2318 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE);
2319 if (!Variable->Volatile) {
2320 CacheVariable->CurrPtr->State = State;
2321 FlushHobVariableToFlash (VariableName, VendorGuid);
2322 }
2323 }
2324 goto Done;
2325 }
2326 //
2327 // If the variable is marked valid, and the same data has been passed in,
2328 // then return to the caller immediately.
2329 //
2330 if (DataSizeOfVariable (Variable->CurrPtr) == DataSize &&
2331 (CompareMem (Data, GetVariableDataPtr (Variable->CurrPtr), DataSize) == 0) &&
2332 ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) &&
2333 (TimeStamp == NULL)) {
2334 //
2335 // Variable content unchanged and no need to update timestamp, just return.
2336 //
2337 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);
2338 Status = EFI_SUCCESS;
2339 goto Done;
2340 } else if ((Variable->CurrPtr->State == VAR_ADDED) ||
2341 (Variable->CurrPtr->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION))) {
2342
2343 //
2344 // EFI_VARIABLE_APPEND_WRITE attribute only effects for existing variable.
2345 //
2346 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) {
2347 //
2348 // NOTE: From 0 to DataOffset of NextVariable is reserved for Variable Header and Name.
2349 // From DataOffset of NextVariable is to save the existing variable data.
2350 //
2351 DataOffset = GetVariableDataOffset (Variable->CurrPtr);
2352 BufferForMerge = (UINT8 *) ((UINTN) NextVariable + DataOffset);
2353 CopyMem (BufferForMerge, (UINT8 *) ((UINTN) Variable->CurrPtr + DataOffset), DataSizeOfVariable (Variable->CurrPtr));
2354
2355 //
2356 // Set Max Common/Auth Variable Data Size as default MaxDataSize.
2357 //
2358 if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
2359 MaxDataSize = mVariableModuleGlobal->MaxAuthVariableSize - DataOffset;
2360 } else {
2361 MaxDataSize = mVariableModuleGlobal->MaxVariableSize - DataOffset;
2362 }
2363
2364 //
2365 // Append the new data to the end of existing data.
2366 // Max Harware error record variable data size is different from common/auth variable.
2367 //
2368 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2369 MaxDataSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - DataOffset;
2370 }
2371
2372 if (DataSizeOfVariable (Variable->CurrPtr) + DataSize > MaxDataSize) {
2373 //
2374 // Existing data size + new data size exceed maximum variable size limitation.
2375 //
2376 Status = EFI_INVALID_PARAMETER;
2377 goto Done;
2378 }
2379 CopyMem ((UINT8*) ((UINTN) BufferForMerge + DataSizeOfVariable (Variable->CurrPtr)), Data, DataSize);
2380 MergedBufSize = DataSizeOfVariable (Variable->CurrPtr) + DataSize;
2381
2382 //
2383 // BufferForMerge(from DataOffset of NextVariable) has included the merged existing and new data.
2384 //
2385 Data = BufferForMerge;
2386 DataSize = MergedBufSize;
2387 DataReady = TRUE;
2388 }
2389
2390 //
2391 // Mark the old variable as in delete transition.
2392 //
2393 State = Variable->CurrPtr->State;
2394 State &= VAR_IN_DELETED_TRANSITION;
2395
2396 Status = UpdateVariableStore (
2397 &mVariableModuleGlobal->VariableGlobal,
2398 Variable->Volatile,
2399 FALSE,
2400 Fvb,
2401 (UINTN) &Variable->CurrPtr->State,
2402 sizeof (UINT8),
2403 &State
2404 );
2405 if (EFI_ERROR (Status)) {
2406 goto Done;
2407 }
2408 if (!Variable->Volatile) {
2409 CacheVariable->CurrPtr->State = State;
2410 }
2411 }
2412 } else {
2413 //
2414 // Not found existing variable. Create a new variable.
2415 //
2416
2417 if ((DataSize == 0) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0)) {
2418 Status = EFI_SUCCESS;
2419 goto Done;
2420 }
2421
2422 //
2423 // Make sure we are trying to create a new variable.
2424 // Setting a data variable with zero DataSize or no access attributes means to delete it.
2425 //
2426 if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) {
2427 Status = EFI_NOT_FOUND;
2428 goto Done;
2429 }
2430
2431 //
2432 // Only variable have NV|RT attribute can be created in Runtime.
2433 //
2434 if (AtRuntime () &&
2435 (((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0))) {
2436 Status = EFI_INVALID_PARAMETER;
2437 goto Done;
2438 }
2439 }
2440
2441 //
2442 // Function part - create a new variable and copy the data.
2443 // Both update a variable and create a variable will come here.
2444 //
2445 NextVariable->StartId = VARIABLE_DATA;
2446 //
2447 // NextVariable->State = VAR_ADDED;
2448 //
2449 NextVariable->Reserved = 0;
2450 if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
2451 AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) NextVariable;
2452 AuthVariable->PubKeyIndex = KeyIndex;
2453 AuthVariable->MonotonicCount = MonotonicCount;
2454 ZeroMem (&AuthVariable->TimeStamp, sizeof (EFI_TIME));
2455
2456 if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&
2457 (TimeStamp != NULL)) {
2458 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) {
2459 CopyMem (&AuthVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
2460 } else {
2461 //
2462 // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only
2463 // when the new TimeStamp value is later than the current timestamp associated
2464 // with the variable, we need associate the new timestamp with the updated value.
2465 //
2466 if (Variable->CurrPtr != NULL) {
2467 if (VariableCompareTimeStampInternal (&(((AUTHENTICATED_VARIABLE_HEADER *) Variable->CurrPtr)->TimeStamp), TimeStamp)) {
2468 CopyMem (&AuthVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
2469 }
2470 }
2471 }
2472 }
2473 }
2474
2475 //
2476 // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned
2477 // Attributes bitmask parameter of a GetVariable() call.
2478 //
2479 NextVariable->Attributes = Attributes & (~EFI_VARIABLE_APPEND_WRITE);
2480
2481 VarNameOffset = GetVariableHeaderSize ();
2482 VarNameSize = StrSize (VariableName);
2483 CopyMem (
2484 (UINT8 *) ((UINTN) NextVariable + VarNameOffset),
2485 VariableName,
2486 VarNameSize
2487 );
2488 VarDataOffset = VarNameOffset + VarNameSize + GET_PAD_SIZE (VarNameSize);
2489
2490 //
2491 // If DataReady is TRUE, it means the variable data has been saved into
2492 // NextVariable during EFI_VARIABLE_APPEND_WRITE operation preparation.
2493 //
2494 if (!DataReady) {
2495 CopyMem (
2496 (UINT8 *) ((UINTN) NextVariable + VarDataOffset),
2497 Data,
2498 DataSize
2499 );
2500 }
2501
2502 CopyMem (GetVendorGuidPtr (NextVariable), VendorGuid, sizeof (EFI_GUID));
2503 //
2504 // There will be pad bytes after Data, the NextVariable->NameSize and
2505 // NextVariable->DataSize should not include pad size so that variable
2506 // service can get actual size in GetVariable.
2507 //
2508 SetNameSizeOfVariable (NextVariable, VarNameSize);
2509 SetDataSizeOfVariable (NextVariable, DataSize);
2510
2511 //
2512 // The actual size of the variable that stores in storage should
2513 // include pad size.
2514 //
2515 VarSize = VarDataOffset + DataSize + GET_PAD_SIZE (DataSize);
2516 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
2517 //
2518 // Create a nonvolatile variable.
2519 //
2520 Volatile = FALSE;
2521
2522 IsCommonVariable = FALSE;
2523 IsCommonUserVariable = FALSE;
2524 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) {
2525 IsCommonVariable = TRUE;
2526 IsCommonUserVariable = IsUserVariable (NextVariable);
2527 }
2528 if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)
2529 && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))
2530 || (IsCommonVariable && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonVariableSpace))
2531 || (IsCommonVariable && AtRuntime () && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonRuntimeVariableSpace))
2532 || (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace))) {
2533 if (AtRuntime ()) {
2534 if (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace)) {
2535 RecordVarErrorFlag (VAR_ERROR_FLAG_USER_ERROR, VariableName, VendorGuid, Attributes, VarSize);
2536 }
2537 if (IsCommonVariable && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonRuntimeVariableSpace)) {
2538 RecordVarErrorFlag (VAR_ERROR_FLAG_SYSTEM_ERROR, VariableName, VendorGuid, Attributes, VarSize);
2539 }
2540 Status = EFI_OUT_OF_RESOURCES;
2541 goto Done;
2542 }
2543 //
2544 // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.
2545 //
2546 Status = Reclaim (
2547 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
2548 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
2549 FALSE,
2550 Variable,
2551 NextVariable,
2552 HEADER_ALIGN (VarSize)
2553 );
2554 if (!EFI_ERROR (Status)) {
2555 //
2556 // The new variable has been integrated successfully during reclaiming.
2557 //
2558 if (Variable->CurrPtr != NULL) {
2559 CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
2560 CacheVariable->InDeletedTransitionPtr = NULL;
2561 }
2562 UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, TRUE, FALSE, FALSE);
2563 FlushHobVariableToFlash (VariableName, VendorGuid);
2564 } else {
2565 if (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace)) {
2566 RecordVarErrorFlag (VAR_ERROR_FLAG_USER_ERROR, VariableName, VendorGuid, Attributes, VarSize);
2567 }
2568 if (IsCommonVariable && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonVariableSpace)) {
2569 RecordVarErrorFlag (VAR_ERROR_FLAG_SYSTEM_ERROR, VariableName, VendorGuid, Attributes, VarSize);
2570 }
2571 }
2572 goto Done;
2573 }
2574 //
2575 // Four steps
2576 // 1. Write variable header
2577 // 2. Set variable state to header valid
2578 // 3. Write variable data
2579 // 4. Set variable state to valid
2580 //
2581 //
2582 // Step 1:
2583 //
2584 CacheOffset = mVariableModuleGlobal->NonVolatileLastVariableOffset;
2585 Status = UpdateVariableStore (
2586 &mVariableModuleGlobal->VariableGlobal,
2587 FALSE,
2588 TRUE,
2589 Fvb,
2590 mVariableModuleGlobal->NonVolatileLastVariableOffset,
2591 (UINT32) GetVariableHeaderSize (),
2592 (UINT8 *) NextVariable
2593 );
2594
2595 if (EFI_ERROR (Status)) {
2596 goto Done;
2597 }
2598
2599 //
2600 // Step 2:
2601 //
2602 NextVariable->State = VAR_HEADER_VALID_ONLY;
2603 Status = UpdateVariableStore (
2604 &mVariableModuleGlobal->VariableGlobal,
2605 FALSE,
2606 TRUE,
2607 Fvb,
2608 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
2609 sizeof (UINT8),
2610 &NextVariable->State
2611 );
2612
2613 if (EFI_ERROR (Status)) {
2614 goto Done;
2615 }
2616 //
2617 // Step 3:
2618 //
2619 Status = UpdateVariableStore (
2620 &mVariableModuleGlobal->VariableGlobal,
2621 FALSE,
2622 TRUE,
2623 Fvb,
2624 mVariableModuleGlobal->NonVolatileLastVariableOffset + GetVariableHeaderSize (),
2625 (UINT32) (VarSize - GetVariableHeaderSize ()),
2626 (UINT8 *) NextVariable + GetVariableHeaderSize ()
2627 );
2628
2629 if (EFI_ERROR (Status)) {
2630 goto Done;
2631 }
2632 //
2633 // Step 4:
2634 //
2635 NextVariable->State = VAR_ADDED;
2636 Status = UpdateVariableStore (
2637 &mVariableModuleGlobal->VariableGlobal,
2638 FALSE,
2639 TRUE,
2640 Fvb,
2641 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
2642 sizeof (UINT8),
2643 &NextVariable->State
2644 );
2645
2646 if (EFI_ERROR (Status)) {
2647 goto Done;
2648 }
2649
2650 mVariableModuleGlobal->NonVolatileLastVariableOffset += HEADER_ALIGN (VarSize);
2651
2652 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
2653 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VarSize);
2654 } else {
2655 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VarSize);
2656 if (IsCommonUserVariable) {
2657 mVariableModuleGlobal->CommonUserVariableTotalSize += HEADER_ALIGN (VarSize);
2658 }
2659 }
2660 //
2661 // update the memory copy of Flash region.
2662 //
2663 CopyMem ((UINT8 *)mNvVariableCache + CacheOffset, (UINT8 *)NextVariable, VarSize);
2664 } else {
2665 //
2666 // Create a volatile variable.
2667 //
2668 Volatile = TRUE;
2669
2670 if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >
2671 ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size) {
2672 //
2673 // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.
2674 //
2675 Status = Reclaim (
2676 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,
2677 &mVariableModuleGlobal->VolatileLastVariableOffset,
2678 TRUE,
2679 Variable,
2680 NextVariable,
2681 HEADER_ALIGN (VarSize)
2682 );
2683 if (!EFI_ERROR (Status)) {
2684 //
2685 // The new variable has been integrated successfully during reclaiming.
2686 //
2687 if (Variable->CurrPtr != NULL) {
2688 CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
2689 CacheVariable->InDeletedTransitionPtr = NULL;
2690 }
2691 UpdateVariableInfo (VariableName, VendorGuid, TRUE, FALSE, TRUE, FALSE, FALSE);
2692 }
2693 goto Done;
2694 }
2695
2696 NextVariable->State = VAR_ADDED;
2697 Status = UpdateVariableStore (
2698 &mVariableModuleGlobal->VariableGlobal,
2699 TRUE,
2700 TRUE,
2701 Fvb,
2702 mVariableModuleGlobal->VolatileLastVariableOffset,
2703 (UINT32) VarSize,
2704 (UINT8 *) NextVariable
2705 );
2706
2707 if (EFI_ERROR (Status)) {
2708 goto Done;
2709 }
2710
2711 mVariableModuleGlobal->VolatileLastVariableOffset += HEADER_ALIGN (VarSize);
2712 }
2713
2714 //
2715 // Mark the old variable as deleted.
2716 //
2717 if (!EFI_ERROR (Status) && Variable->CurrPtr != NULL) {
2718 if (Variable->InDeletedTransitionPtr != NULL) {
2719 //
2720 // Both ADDED and IN_DELETED_TRANSITION old variable are present,
2721 // set IN_DELETED_TRANSITION one to DELETED state first.
2722 //
2723 State = Variable->InDeletedTransitionPtr->State;
2724 State &= VAR_DELETED;
2725 Status = UpdateVariableStore (
2726 &mVariableModuleGlobal->VariableGlobal,
2727 Variable->Volatile,
2728 FALSE,
2729 Fvb,
2730 (UINTN) &Variable->InDeletedTransitionPtr->State,
2731 sizeof (UINT8),
2732 &State
2733 );
2734 if (!EFI_ERROR (Status)) {
2735 if (!Variable->Volatile) {
2736 ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
2737 CacheVariable->InDeletedTransitionPtr->State = State;
2738 }
2739 } else {
2740 goto Done;
2741 }
2742 }
2743
2744 State = Variable->CurrPtr->State;
2745 State &= VAR_DELETED;
2746
2747 Status = UpdateVariableStore (
2748 &mVariableModuleGlobal->VariableGlobal,
2749 Variable->Volatile,
2750 FALSE,
2751 Fvb,
2752 (UINTN) &Variable->CurrPtr->State,
2753 sizeof (UINT8),
2754 &State
2755 );
2756 if (!EFI_ERROR (Status) && !Variable->Volatile) {
2757 CacheVariable->CurrPtr->State = State;
2758 }
2759 }
2760
2761 if (!EFI_ERROR (Status)) {
2762 UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);
2763 if (!Volatile) {
2764 FlushHobVariableToFlash (VariableName, VendorGuid);
2765 }
2766 }
2767
2768 Done:
2769 return Status;
2770 }
2771
2772 /**
2773 Check if a Unicode character is a hexadecimal character.
2774
2775 This function checks if a Unicode character is a
2776 hexadecimal character. The valid hexadecimal character is
2777 L'0' to L'9', L'a' to L'f', or L'A' to L'F'.
2778
2779
2780 @param Char The character to check against.
2781
2782 @retval TRUE If the Char is a hexadecmial character.
2783 @retval FALSE If the Char is not a hexadecmial character.
2784
2785 **/
2786 BOOLEAN
2787 EFIAPI
2788 IsHexaDecimalDigitCharacter (
2789 IN CHAR16 Char
2790 )
2791 {
2792 return (BOOLEAN) ((Char >= L'0' && Char <= L'9') || (Char >= L'A' && Char <= L'F') || (Char >= L'a' && Char <= L'f'));
2793 }
2794
2795 /**
2796
2797 This code checks if variable is hardware error record variable or not.
2798
2799 According to UEFI spec, hardware error record variable should use the EFI_HARDWARE_ERROR_VARIABLE VendorGuid
2800 and have the L"HwErrRec####" name convention, #### is a printed hex value and no 0x or h is included in the hex value.
2801
2802 @param VariableName Pointer to variable name.
2803 @param VendorGuid Variable Vendor Guid.
2804
2805 @retval TRUE Variable is hardware error record variable.
2806 @retval FALSE Variable is not hardware error record variable.
2807
2808 **/
2809 BOOLEAN
2810 EFIAPI
2811 IsHwErrRecVariable (
2812 IN CHAR16 *VariableName,
2813 IN EFI_GUID *VendorGuid
2814 )
2815 {
2816 if (!CompareGuid (VendorGuid, &gEfiHardwareErrorVariableGuid) ||
2817 (StrLen (VariableName) != StrLen (L"HwErrRec####")) ||
2818 (StrnCmp(VariableName, L"HwErrRec", StrLen (L"HwErrRec")) != 0) ||
2819 !IsHexaDecimalDigitCharacter (VariableName[0x8]) ||
2820 !IsHexaDecimalDigitCharacter (VariableName[0x9]) ||
2821 !IsHexaDecimalDigitCharacter (VariableName[0xA]) ||
2822 !IsHexaDecimalDigitCharacter (VariableName[0xB])) {
2823 return FALSE;
2824 }
2825
2826 return TRUE;
2827 }
2828
2829 /**
2830 Mark a variable that will become read-only after leaving the DXE phase of execution.
2831
2832
2833 @param[in] This The VARIABLE_LOCK_PROTOCOL instance.
2834 @param[in] VariableName A pointer to the variable name that will be made read-only subsequently.
2835 @param[in] VendorGuid A pointer to the vendor GUID that will be made read-only subsequently.
2836
2837 @retval EFI_SUCCESS The variable specified by the VariableName and the VendorGuid was marked
2838 as pending to be read-only.
2839 @retval EFI_INVALID_PARAMETER VariableName or VendorGuid is NULL.
2840 Or VariableName is an empty string.
2841 @retval EFI_ACCESS_DENIED EFI_END_OF_DXE_EVENT_GROUP_GUID or EFI_EVENT_GROUP_READY_TO_BOOT has
2842 already been signaled.
2843 @retval EFI_OUT_OF_RESOURCES There is not enough resource to hold the lock request.
2844 **/
2845 EFI_STATUS
2846 EFIAPI
2847 VariableLockRequestToLock (
2848 IN CONST EDKII_VARIABLE_LOCK_PROTOCOL *This,
2849 IN CHAR16 *VariableName,
2850 IN EFI_GUID *VendorGuid
2851 )
2852 {
2853 VARIABLE_ENTRY *Entry;
2854 CHAR16 *Name;
2855 LIST_ENTRY *Link;
2856 VARIABLE_ENTRY *LockedEntry;
2857
2858 if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {
2859 return EFI_INVALID_PARAMETER;
2860 }
2861
2862 if (mEndOfDxe) {
2863 return EFI_ACCESS_DENIED;
2864 }
2865
2866 Entry = AllocateRuntimeZeroPool (sizeof (*Entry) + StrSize (VariableName));
2867 if (Entry == NULL) {
2868 return EFI_OUT_OF_RESOURCES;
2869 }
2870
2871 DEBUG ((EFI_D_INFO, "[Variable] Lock: %g:%s\n", VendorGuid, VariableName));
2872
2873 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2874
2875 for ( Link = GetFirstNode (&mLockedVariableList)
2876 ; !IsNull (&mLockedVariableList, Link)
2877 ; Link = GetNextNode (&mLockedVariableList, Link)
2878 ) {
2879 LockedEntry = BASE_CR (Link, VARIABLE_ENTRY, Link);
2880 Name = (CHAR16 *) ((UINTN) LockedEntry + sizeof (*LockedEntry));
2881 if (CompareGuid (&LockedEntry->Guid, VendorGuid) && (StrCmp (Name, VariableName) == 0)) {
2882 goto Done;
2883 }
2884 }
2885
2886 Name = (CHAR16 *) ((UINTN) Entry + sizeof (*Entry));
2887 StrCpyS (Name, StrSize (VariableName)/sizeof(CHAR16), VariableName);
2888 CopyGuid (&Entry->Guid, VendorGuid);
2889 InsertTailList (&mLockedVariableList, &Entry->Link);
2890
2891 Done:
2892 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2893
2894 return EFI_SUCCESS;
2895 }
2896
2897 /**
2898
2899 This code finds variable in storage blocks (Volatile or Non-Volatile).
2900
2901 Caution: This function may receive untrusted input.
2902 This function may be invoked in SMM mode, and datasize is external input.
2903 This function will do basic validation, before parse the data.
2904
2905 @param VariableName Name of Variable to be found.
2906 @param VendorGuid Variable vendor GUID.
2907 @param Attributes Attribute value of the variable found.
2908 @param DataSize Size of Data found. If size is less than the
2909 data, this value contains the required size.
2910 @param Data Data pointer.
2911
2912 @return EFI_INVALID_PARAMETER Invalid parameter.
2913 @return EFI_SUCCESS Find the specified variable.
2914 @return EFI_NOT_FOUND Not found.
2915 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2916
2917 **/
2918 EFI_STATUS
2919 EFIAPI
2920 VariableServiceGetVariable (
2921 IN CHAR16 *VariableName,
2922 IN EFI_GUID *VendorGuid,
2923 OUT UINT32 *Attributes OPTIONAL,
2924 IN OUT UINTN *DataSize,
2925 OUT VOID *Data
2926 )
2927 {
2928 EFI_STATUS Status;
2929 VARIABLE_POINTER_TRACK Variable;
2930 UINTN VarDataSize;
2931
2932 if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {
2933 return EFI_INVALID_PARAMETER;
2934 }
2935
2936 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2937
2938 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2939 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2940 goto Done;
2941 }
2942
2943 //
2944 // Get data size
2945 //
2946 VarDataSize = DataSizeOfVariable (Variable.CurrPtr);
2947 ASSERT (VarDataSize != 0);
2948
2949 if (*DataSize >= VarDataSize) {
2950 if (Data == NULL) {
2951 Status = EFI_INVALID_PARAMETER;
2952 goto Done;
2953 }
2954
2955 CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr), VarDataSize);
2956 if (Attributes != NULL) {
2957 *Attributes = Variable.CurrPtr->Attributes;
2958 }
2959
2960 *DataSize = VarDataSize;
2961 UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);
2962
2963 Status = EFI_SUCCESS;
2964 goto Done;
2965 } else {
2966 *DataSize = VarDataSize;
2967 Status = EFI_BUFFER_TOO_SMALL;
2968 goto Done;
2969 }
2970
2971 Done:
2972 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2973 return Status;
2974 }
2975
2976 /**
2977 This code Finds the Next available variable.
2978
2979 Caution: This function may receive untrusted input.
2980 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2981
2982 @param[in] VariableName Pointer to variable name.
2983 @param[in] VendorGuid Variable Vendor Guid.
2984 @param[out] VariablePtr Pointer to variable header address.
2985
2986 @return EFI_SUCCESS Find the specified variable.
2987 @return EFI_NOT_FOUND Not found.
2988
2989 **/
2990 EFI_STATUS
2991 EFIAPI
2992 VariableServiceGetNextVariableInternal (
2993 IN CHAR16 *VariableName,
2994 IN EFI_GUID *VendorGuid,
2995 OUT VARIABLE_HEADER **VariablePtr
2996 )
2997 {
2998 VARIABLE_STORE_TYPE Type;
2999 VARIABLE_POINTER_TRACK Variable;
3000 VARIABLE_POINTER_TRACK VariableInHob;
3001 VARIABLE_POINTER_TRACK VariablePtrTrack;
3002 EFI_STATUS Status;
3003 VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
3004
3005 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
3006 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
3007 goto Done;
3008 }
3009
3010 if (VariableName[0] != 0) {
3011 //
3012 // If variable name is not NULL, get next variable.
3013 //
3014 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
3015 }
3016
3017 //
3018 // 0: Volatile, 1: HOB, 2: Non-Volatile.
3019 // The index and attributes mapping must be kept in this order as FindVariable
3020 // makes use of this mapping to implement search algorithm.
3021 //
3022 VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
3023 VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
3024 VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
3025
3026 while (TRUE) {
3027 //
3028 // Switch from Volatile to HOB, to Non-Volatile.
3029 //
3030 while (!IsValidVariableHeader (Variable.CurrPtr, Variable.EndPtr)) {
3031 //
3032 // Find current storage index
3033 //
3034 for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
3035 if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
3036 break;
3037 }
3038 }
3039 ASSERT (Type < VariableStoreTypeMax);
3040 //
3041 // Switch to next storage
3042 //
3043 for (Type++; Type < VariableStoreTypeMax; Type++) {
3044 if (VariableStoreHeader[Type] != NULL) {
3045 break;
3046 }
3047 }
3048 //
3049 // Capture the case that
3050 // 1. current storage is the last one, or
3051 // 2. no further storage
3052 //
3053 if (Type == VariableStoreTypeMax) {
3054 Status = EFI_NOT_FOUND;
3055 goto Done;
3056 }
3057 Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);
3058 Variable.EndPtr = GetEndPointer (VariableStoreHeader[Type]);
3059 Variable.CurrPtr = Variable.StartPtr;
3060 }
3061
3062 //
3063 // Variable is found
3064 //
3065 if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
3066 if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
3067 if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
3068 //
3069 // If it is a IN_DELETED_TRANSITION variable,
3070 // and there is also a same ADDED one at the same time,
3071 // don't return it.
3072 //
3073 VariablePtrTrack.StartPtr = Variable.StartPtr;
3074 VariablePtrTrack.EndPtr = Variable.EndPtr;
3075 Status = FindVariableEx (
3076 GetVariableNamePtr (Variable.CurrPtr),
3077 GetVendorGuidPtr (Variable.CurrPtr),
3078 FALSE,
3079 &VariablePtrTrack
3080 );
3081 if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
3082 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
3083 continue;
3084 }
3085 }
3086
3087 //
3088 // Don't return NV variable when HOB overrides it
3089 //
3090 if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&
3091 (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))
3092 ) {
3093 VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);
3094 VariableInHob.EndPtr = GetEndPointer (VariableStoreHeader[VariableStoreTypeHob]);
3095 Status = FindVariableEx (
3096 GetVariableNamePtr (Variable.CurrPtr),
3097 GetVendorGuidPtr (Variable.CurrPtr),
3098 FALSE,
3099 &VariableInHob
3100 );
3101 if (!EFI_ERROR (Status)) {
3102 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
3103 continue;
3104 }
3105 }
3106
3107 *VariablePtr = Variable.CurrPtr;
3108 Status = EFI_SUCCESS;
3109 goto Done;
3110 }
3111 }
3112
3113 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
3114 }
3115
3116 Done:
3117 return Status;
3118 }
3119
3120 /**
3121
3122 This code Finds the Next available variable.
3123
3124 Caution: This function may receive untrusted input.
3125 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
3126
3127 @param VariableNameSize Size of the variable name.
3128 @param VariableName Pointer to variable name.
3129 @param VendorGuid Variable Vendor Guid.
3130
3131 @return EFI_INVALID_PARAMETER Invalid parameter.
3132 @return EFI_SUCCESS Find the specified variable.
3133 @return EFI_NOT_FOUND Not found.
3134 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
3135
3136 **/
3137 EFI_STATUS
3138 EFIAPI
3139 VariableServiceGetNextVariableName (
3140 IN OUT UINTN *VariableNameSize,
3141 IN OUT CHAR16 *VariableName,
3142 IN OUT EFI_GUID *VendorGuid
3143 )
3144 {
3145 EFI_STATUS Status;
3146 UINTN VarNameSize;
3147 VARIABLE_HEADER *VariablePtr;
3148
3149 if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
3150 return EFI_INVALID_PARAMETER;
3151 }
3152
3153 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3154
3155 Status = VariableServiceGetNextVariableInternal (VariableName, VendorGuid, &VariablePtr);
3156 if (!EFI_ERROR (Status)) {
3157 VarNameSize = NameSizeOfVariable (VariablePtr);
3158 ASSERT (VarNameSize != 0);
3159 if (VarNameSize <= *VariableNameSize) {
3160 CopyMem (VariableName, GetVariableNamePtr (VariablePtr), VarNameSize);
3161 CopyMem (VendorGuid, GetVendorGuidPtr (VariablePtr), sizeof (EFI_GUID));
3162 Status = EFI_SUCCESS;
3163 } else {
3164 Status = EFI_BUFFER_TOO_SMALL;
3165 }
3166
3167 *VariableNameSize = VarNameSize;
3168 }
3169
3170 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3171 return Status;
3172 }
3173
3174 /**
3175
3176 This code sets variable in storage blocks (Volatile or Non-Volatile).
3177
3178 Caution: This function may receive untrusted input.
3179 This function may be invoked in SMM mode, and datasize and data are external input.
3180 This function will do basic validation, before parse the data.
3181 This function will parse the authentication carefully to avoid security issues, like
3182 buffer overflow, integer overflow.
3183 This function will check attribute carefully to avoid authentication bypass.
3184
3185 @param VariableName Name of Variable to be found.
3186 @param VendorGuid Variable vendor GUID.
3187 @param Attributes Attribute value of the variable found
3188 @param DataSize Size of Data found. If size is less than the
3189 data, this value contains the required size.
3190 @param Data Data pointer.
3191
3192 @return EFI_INVALID_PARAMETER Invalid parameter.
3193 @return EFI_SUCCESS Set successfully.
3194 @return EFI_OUT_OF_RESOURCES Resource not enough to set variable.
3195 @return EFI_NOT_FOUND Not found.
3196 @return EFI_WRITE_PROTECTED Variable is read-only.
3197
3198 **/
3199 EFI_STATUS
3200 EFIAPI
3201 VariableServiceSetVariable (
3202 IN CHAR16 *VariableName,
3203 IN EFI_GUID *VendorGuid,
3204 IN UINT32 Attributes,
3205 IN UINTN DataSize,
3206 IN VOID *Data
3207 )
3208 {
3209 VARIABLE_POINTER_TRACK Variable;
3210 EFI_STATUS Status;
3211 VARIABLE_HEADER *NextVariable;
3212 EFI_PHYSICAL_ADDRESS Point;
3213 UINTN PayloadSize;
3214 LIST_ENTRY *Link;
3215 VARIABLE_ENTRY *Entry;
3216 CHAR16 *Name;
3217
3218 //
3219 // Check input parameters.
3220 //
3221 if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {
3222 return EFI_INVALID_PARAMETER;
3223 }
3224
3225 if (DataSize != 0 && Data == NULL) {
3226 return EFI_INVALID_PARAMETER;
3227 }
3228
3229 //
3230 // Check for reserverd bit in variable attribute.
3231 //
3232 if ((Attributes & (~EFI_VARIABLE_ATTRIBUTES_MASK)) != 0) {
3233 return EFI_INVALID_PARAMETER;
3234 }
3235
3236 //
3237 // Make sure if runtime bit is set, boot service bit is set also.
3238 //
3239 if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
3240 return EFI_INVALID_PARAMETER;
3241 } else if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
3242 if (!mVariableModuleGlobal->VariableGlobal.AuthSupport) {
3243 //
3244 // Not support authenticated variable write.
3245 //
3246 return EFI_INVALID_PARAMETER;
3247 }
3248 } else if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
3249 if (PcdGet32 (PcdHwErrStorageSize) == 0) {
3250 //
3251 // Not support harware error record variable variable.
3252 //
3253 return EFI_INVALID_PARAMETER;
3254 }
3255 }
3256
3257 //
3258 // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute
3259 // cannot be set both.
3260 //
3261 if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)
3262 && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {
3263 return EFI_INVALID_PARAMETER;
3264 }
3265
3266 if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {
3267 if (DataSize < AUTHINFO_SIZE) {
3268 //
3269 // Try to write Authenticated Variable without AuthInfo.
3270 //
3271 return EFI_SECURITY_VIOLATION;
3272 }
3273 PayloadSize = DataSize - AUTHINFO_SIZE;
3274 } else if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {
3275 //
3276 // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor.
3277 //
3278 if (DataSize < OFFSET_OF_AUTHINFO2_CERT_DATA ||
3279 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength > DataSize - (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) ||
3280 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength < OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) {
3281 return EFI_SECURITY_VIOLATION;
3282 }
3283 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
3284 } else {
3285 PayloadSize = DataSize;
3286 }
3287
3288 if ((UINTN)(~0) - PayloadSize < StrSize(VariableName)){
3289 //
3290 // Prevent whole variable size overflow
3291 //
3292 return EFI_INVALID_PARAMETER;
3293 }
3294
3295 //
3296 // The size of the VariableName, including the Unicode Null in bytes plus
3297 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)
3298 // bytes for HwErrRec#### variable.
3299 //
3300 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3301 if (StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize ()) {
3302 return EFI_INVALID_PARAMETER;
3303 }
3304 if (!IsHwErrRecVariable(VariableName, VendorGuid)) {
3305 return EFI_INVALID_PARAMETER;
3306 }
3307 } else {
3308 //
3309 // The size of the VariableName, including the Unicode Null in bytes plus
3310 // the DataSize is limited to maximum size of Max(Auth)VariableSize bytes.
3311 //
3312 if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
3313 if (StrSize (VariableName) + PayloadSize > mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ()) {
3314 return EFI_INVALID_PARAMETER;
3315 }
3316 } else {
3317 if (StrSize (VariableName) + PayloadSize > mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize ()) {
3318 return EFI_INVALID_PARAMETER;
3319 }
3320 }
3321 }
3322
3323 Status = InternalVarCheckSetVariableCheck (VariableName, VendorGuid, Attributes, PayloadSize, (VOID *) ((UINTN) Data + DataSize - PayloadSize));
3324 if (EFI_ERROR (Status)) {
3325 return Status;
3326 }
3327
3328 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3329
3330 //
3331 // Consider reentrant in MCA/INIT/NMI. It needs be reupdated.
3332 //
3333 if (1 < InterlockedIncrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState)) {
3334 Point = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
3335 //
3336 // Parse non-volatile variable data and get last variable offset.
3337 //
3338 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point);
3339 while (IsValidVariableHeader (NextVariable, GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point))) {
3340 NextVariable = GetNextVariablePtr (NextVariable);
3341 }
3342 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point;
3343 }
3344
3345 if (mEndOfDxe && mEnableLocking) {
3346 //
3347 // Treat the variables listed in the forbidden variable list as read-only after leaving DXE phase.
3348 //
3349 for ( Link = GetFirstNode (&mLockedVariableList)
3350 ; !IsNull (&mLockedVariableList, Link)
3351 ; Link = GetNextNode (&mLockedVariableList, Link)
3352 ) {
3353 Entry = BASE_CR (Link, VARIABLE_ENTRY, Link);
3354 Name = (CHAR16 *) ((UINTN) Entry + sizeof (*Entry));
3355 if (CompareGuid (&Entry->Guid, VendorGuid) && (StrCmp (Name, VariableName) == 0)) {
3356 Status = EFI_WRITE_PROTECTED;
3357 DEBUG ((EFI_D_INFO, "[Variable]: Changing readonly variable after leaving DXE phase - %g:%s\n", VendorGuid, VariableName));
3358 goto Done;
3359 }
3360 }
3361 }
3362
3363 //
3364 // Check whether the input variable is already existed.
3365 //
3366 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, TRUE);
3367 if (!EFI_ERROR (Status)) {
3368 if (((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) && AtRuntime ()) {
3369 Status = EFI_WRITE_PROTECTED;
3370 goto Done;
3371 }
3372 if (Attributes != 0 && (Attributes & (~EFI_VARIABLE_APPEND_WRITE)) != Variable.CurrPtr->Attributes) {
3373 //
3374 // If a preexisting variable is rewritten with different attributes, SetVariable() shall not
3375 // modify the variable and shall return EFI_INVALID_PARAMETER. Two exceptions to this rule:
3376 // 1. No access attributes specified
3377 // 2. The only attribute differing is EFI_VARIABLE_APPEND_WRITE
3378 //
3379 Status = EFI_INVALID_PARAMETER;
3380 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));
3381 goto Done;
3382 }
3383 }
3384
3385 if (!FeaturePcdGet (PcdUefiVariableDefaultLangDeprecate)) {
3386 //
3387 // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.
3388 //
3389 Status = AutoUpdateLangVariable (VariableName, Data, DataSize);
3390 if (EFI_ERROR (Status)) {
3391 //
3392 // The auto update operation failed, directly return to avoid inconsistency between PlatformLang and Lang.
3393 //
3394 goto Done;
3395 }
3396 }
3397
3398 if (mVariableModuleGlobal->VariableGlobal.AuthSupport) {
3399 Status = AuthVariableLibProcessVariable (VariableName, VendorGuid, Data, DataSize, Attributes);
3400 } else {
3401 Status = UpdateVariable (VariableName, VendorGuid, Data, DataSize, Attributes, 0, 0, &Variable, NULL);
3402 }
3403
3404 Done:
3405 InterlockedDecrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState);
3406 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3407
3408 if (!AtRuntime ()) {
3409 if (!EFI_ERROR (Status)) {
3410 SecureBootHook (
3411 VariableName,
3412 VendorGuid
3413 );
3414 }
3415 }
3416
3417 return Status;
3418 }
3419
3420 /**
3421
3422 This code returns information about the EFI variables.
3423
3424 Caution: This function may receive untrusted input.
3425 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
3426
3427 @param Attributes Attributes bitmask to specify the type of variables
3428 on which to return information.
3429 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
3430 for the EFI variables associated with the attributes specified.
3431 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
3432 for EFI variables associated with the attributes specified.
3433 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
3434 associated with the attributes specified.
3435
3436 @return EFI_SUCCESS Query successfully.
3437
3438 **/
3439 EFI_STATUS
3440 EFIAPI
3441 VariableServiceQueryVariableInfoInternal (
3442 IN UINT32 Attributes,
3443 OUT UINT64 *MaximumVariableStorageSize,
3444 OUT UINT64 *RemainingVariableStorageSize,
3445 OUT UINT64 *MaximumVariableSize
3446 )
3447 {
3448 VARIABLE_HEADER *Variable;
3449 VARIABLE_HEADER *NextVariable;
3450 UINT64 VariableSize;
3451 VARIABLE_STORE_HEADER *VariableStoreHeader;
3452 UINT64 CommonVariableTotalSize;
3453 UINT64 HwErrVariableTotalSize;
3454 EFI_STATUS Status;
3455 VARIABLE_POINTER_TRACK VariablePtrTrack;
3456
3457 CommonVariableTotalSize = 0;
3458 HwErrVariableTotalSize = 0;
3459
3460 if((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
3461 //
3462 // Query is Volatile related.
3463 //
3464 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
3465 } else {
3466 //
3467 // Query is Non-Volatile related.
3468 //
3469 VariableStoreHeader = mNvVariableCache;
3470 }
3471
3472 //
3473 // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize
3474 // with the storage size (excluding the storage header size).
3475 //
3476 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);
3477
3478 //
3479 // Harware error record variable needs larger size.
3480 //
3481 if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
3482 *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize);
3483 *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize ();
3484 } else {
3485 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
3486 if (AtRuntime ()) {
3487 *MaximumVariableStorageSize = mVariableModuleGlobal->CommonRuntimeVariableSpace;
3488 } else {
3489 *MaximumVariableStorageSize = mVariableModuleGlobal->CommonVariableSpace;
3490 }
3491 }
3492
3493 //
3494 // Let *MaximumVariableSize be Max(Auth)VariableSize with the exception of the variable header size.
3495 //
3496 if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
3497 *MaximumVariableSize = mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ();
3498 } else {
3499 *MaximumVariableSize = mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize ();
3500 }
3501 }
3502
3503 //
3504 // Point to the starting address of the variables.
3505 //
3506 Variable = GetStartPointer (VariableStoreHeader);
3507
3508 //
3509 // Now walk through the related variable store.
3510 //
3511 while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
3512 NextVariable = GetNextVariablePtr (Variable);
3513 VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable;
3514
3515 if (AtRuntime ()) {
3516 //
3517 // We don't take the state of the variables in mind
3518 // when calculating RemainingVariableStorageSize,
3519 // since the space occupied by variables not marked with
3520 // VAR_ADDED is not allowed to be reclaimed in Runtime.
3521 //
3522 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3523 HwErrVariableTotalSize += VariableSize;
3524 } else {
3525 CommonVariableTotalSize += VariableSize;
3526 }
3527 } else {
3528 //
3529 // Only care about Variables with State VAR_ADDED, because
3530 // the space not marked as VAR_ADDED is reclaimable now.
3531 //
3532 if (Variable->State == VAR_ADDED) {
3533 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3534 HwErrVariableTotalSize += VariableSize;
3535 } else {
3536 CommonVariableTotalSize += VariableSize;
3537 }
3538 } else if (Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
3539 //
3540 // If it is a IN_DELETED_TRANSITION variable,
3541 // and there is not also a same ADDED one at the same time,
3542 // this IN_DELETED_TRANSITION variable is valid.
3543 //
3544 VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader);
3545 VariablePtrTrack.EndPtr = GetEndPointer (VariableStoreHeader);
3546 Status = FindVariableEx (
3547 GetVariableNamePtr (Variable),
3548 GetVendorGuidPtr (Variable),
3549 FALSE,
3550 &VariablePtrTrack
3551 );
3552 if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State != VAR_ADDED) {
3553 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3554 HwErrVariableTotalSize += VariableSize;
3555 } else {
3556 CommonVariableTotalSize += VariableSize;
3557 }
3558 }
3559 }
3560 }
3561
3562 //
3563 // Go to the next one.
3564 //
3565 Variable = NextVariable;
3566 }
3567
3568 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD){
3569 *RemainingVariableStorageSize = *MaximumVariableStorageSize - HwErrVariableTotalSize;
3570 } else {
3571 if (*MaximumVariableStorageSize < CommonVariableTotalSize) {
3572 *RemainingVariableStorageSize = 0;
3573 } else {
3574 *RemainingVariableStorageSize = *MaximumVariableStorageSize - CommonVariableTotalSize;
3575 }
3576 }
3577
3578 if (*RemainingVariableStorageSize < GetVariableHeaderSize ()) {
3579 *MaximumVariableSize = 0;
3580 } else if ((*RemainingVariableStorageSize - GetVariableHeaderSize ()) < *MaximumVariableSize) {
3581 *MaximumVariableSize = *RemainingVariableStorageSize - GetVariableHeaderSize ();
3582 }
3583
3584 return EFI_SUCCESS;
3585 }
3586
3587 /**
3588
3589 This code returns information about the EFI variables.
3590
3591 Caution: This function may receive untrusted input.
3592 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
3593
3594 @param Attributes Attributes bitmask to specify the type of variables
3595 on which to return information.
3596 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
3597 for the EFI variables associated with the attributes specified.
3598 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
3599 for EFI variables associated with the attributes specified.
3600 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
3601 associated with the attributes specified.
3602
3603 @return EFI_INVALID_PARAMETER An invalid combination of attribute bits was supplied.
3604 @return EFI_SUCCESS Query successfully.
3605 @return EFI_UNSUPPORTED The attribute is not supported on this platform.
3606
3607 **/
3608 EFI_STATUS
3609 EFIAPI
3610 VariableServiceQueryVariableInfo (
3611 IN UINT32 Attributes,
3612 OUT UINT64 *MaximumVariableStorageSize,
3613 OUT UINT64 *RemainingVariableStorageSize,
3614 OUT UINT64 *MaximumVariableSize
3615 )
3616 {
3617 EFI_STATUS Status;
3618
3619 if(MaximumVariableStorageSize == NULL || RemainingVariableStorageSize == NULL || MaximumVariableSize == NULL || Attributes == 0) {
3620 return EFI_INVALID_PARAMETER;
3621 }
3622
3623 if ((Attributes & EFI_VARIABLE_ATTRIBUTES_MASK) == 0) {
3624 //
3625 // Make sure the Attributes combination is supported by the platform.
3626 //
3627 return EFI_UNSUPPORTED;
3628 } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
3629 //
3630 // Make sure if runtime bit is set, boot service bit is set also.
3631 //
3632 return EFI_INVALID_PARAMETER;
3633 } else if (AtRuntime () && ((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) {
3634 //
3635 // Make sure RT Attribute is set if we are in Runtime phase.
3636 //
3637 return EFI_INVALID_PARAMETER;
3638 } else if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3639 //
3640 // Make sure Hw Attribute is set with NV.
3641 //
3642 return EFI_INVALID_PARAMETER;
3643 } else if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
3644 if (!mVariableModuleGlobal->VariableGlobal.AuthSupport) {
3645 //
3646 // Not support authenticated variable write.
3647 //
3648 return EFI_UNSUPPORTED;
3649 }
3650 } else if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
3651 if (PcdGet32 (PcdHwErrStorageSize) == 0) {
3652 //
3653 // Not support harware error record variable variable.
3654 //
3655 return EFI_UNSUPPORTED;
3656 }
3657 }
3658
3659 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3660
3661 Status = VariableServiceQueryVariableInfoInternal (
3662 Attributes,
3663 MaximumVariableStorageSize,
3664 RemainingVariableStorageSize,
3665 MaximumVariableSize
3666 );
3667
3668 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3669 return Status;
3670 }
3671
3672 /**
3673 This function reclaims variable storage if free size is below the threshold.
3674
3675 Caution: This function may be invoked at SMM mode.
3676 Care must be taken to make sure not security issue.
3677
3678 **/
3679 VOID
3680 ReclaimForOS(
3681 VOID
3682 )
3683 {
3684 EFI_STATUS Status;
3685 UINTN RemainingCommonRuntimeVariableSpace;
3686 UINTN RemainingHwErrVariableSpace;
3687 STATIC BOOLEAN Reclaimed;
3688
3689 //
3690 // This function will be called only once at EndOfDxe or ReadyToBoot event.
3691 //
3692 if (Reclaimed) {
3693 return;
3694 }
3695 Reclaimed = TRUE;
3696
3697 Status = EFI_SUCCESS;
3698
3699 if (mVariableModuleGlobal->CommonRuntimeVariableSpace < mVariableModuleGlobal->CommonVariableTotalSize) {
3700 RemainingCommonRuntimeVariableSpace = 0;
3701 } else {
3702 RemainingCommonRuntimeVariableSpace = mVariableModuleGlobal->CommonRuntimeVariableSpace - mVariableModuleGlobal->CommonVariableTotalSize;
3703 }
3704
3705 RemainingHwErrVariableSpace = PcdGet32 (PcdHwErrStorageSize) - mVariableModuleGlobal->HwErrVariableTotalSize;
3706
3707 //
3708 // Check if the free area is below a threshold.
3709 //
3710 if (((RemainingCommonRuntimeVariableSpace < mVariableModuleGlobal->MaxVariableSize) ||
3711 (RemainingCommonRuntimeVariableSpace < mVariableModuleGlobal->MaxAuthVariableSize)) ||
3712 ((PcdGet32 (PcdHwErrStorageSize) != 0) &&
3713 (RemainingHwErrVariableSpace < PcdGet32 (PcdMaxHardwareErrorVariableSize)))){
3714 Status = Reclaim (
3715 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
3716 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
3717 FALSE,
3718 NULL,
3719 NULL,
3720 0
3721 );
3722 ASSERT_EFI_ERROR (Status);
3723 }
3724 }
3725
3726 /**
3727 Get non-volatile maximum variable size.
3728
3729 @return Non-volatile maximum variable size.
3730
3731 **/
3732 UINTN
3733 GetNonVolatileMaxVariableSize (
3734 VOID
3735 )
3736 {
3737 if (PcdGet32 (PcdHwErrStorageSize) != 0) {
3738 return MAX (MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxAuthVariableSize)),
3739 PcdGet32 (PcdMaxHardwareErrorVariableSize));
3740 } else {
3741 return MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxAuthVariableSize));
3742 }
3743 }
3744
3745 /**
3746 Init non-volatile variable store.
3747
3748 @param[out] NvFvHeader Output pointer to non-volatile FV header address.
3749
3750 @retval EFI_SUCCESS Function successfully executed.
3751 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
3752 @retval EFI_VOLUME_CORRUPTED Variable Store or Firmware Volume for Variable Store is corrupted.
3753
3754 **/
3755 EFI_STATUS
3756 InitNonVolatileVariableStore (
3757 OUT EFI_FIRMWARE_VOLUME_HEADER **NvFvHeader
3758 )
3759 {
3760 EFI_FIRMWARE_VOLUME_HEADER *FvHeader;
3761 VARIABLE_HEADER *Variable;
3762 VARIABLE_HEADER *NextVariable;
3763 EFI_PHYSICAL_ADDRESS VariableStoreBase;
3764 UINT64 VariableStoreLength;
3765 UINTN VariableSize;
3766 EFI_HOB_GUID_TYPE *GuidHob;
3767 EFI_PHYSICAL_ADDRESS NvStorageBase;
3768 UINT8 *NvStorageData;
3769 UINT32 NvStorageSize;
3770 FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *FtwLastWriteData;
3771 UINT32 BackUpOffset;
3772 UINT32 BackUpSize;
3773 UINT32 HwErrStorageSize;
3774 UINT32 MaxUserNvVariableSpaceSize;
3775 UINT32 BoottimeReservedNvVariableSpaceSize;
3776
3777 mVariableModuleGlobal->FvbInstance = NULL;
3778
3779 //
3780 // Allocate runtime memory used for a memory copy of the FLASH region.
3781 // Keep the memory and the FLASH in sync as updates occur.
3782 //
3783 NvStorageSize = PcdGet32 (PcdFlashNvStorageVariableSize);
3784 NvStorageData = AllocateRuntimeZeroPool (NvStorageSize);
3785 if (NvStorageData == NULL) {
3786 return EFI_OUT_OF_RESOURCES;
3787 }
3788
3789 NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);
3790 if (NvStorageBase == 0) {
3791 NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);
3792 }
3793 //
3794 // Copy NV storage data to the memory buffer.
3795 //
3796 CopyMem (NvStorageData, (UINT8 *) (UINTN) NvStorageBase, NvStorageSize);
3797
3798 //
3799 // Check the FTW last write data hob.
3800 //
3801 GuidHob = GetFirstGuidHob (&gEdkiiFaultTolerantWriteGuid);
3802 if (GuidHob != NULL) {
3803 FtwLastWriteData = (FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *) GET_GUID_HOB_DATA (GuidHob);
3804 if (FtwLastWriteData->TargetAddress == NvStorageBase) {
3805 DEBUG ((EFI_D_INFO, "Variable: NV storage is backed up in spare block: 0x%x\n", (UINTN) FtwLastWriteData->SpareAddress));
3806 //
3807 // Copy the backed up NV storage data to the memory buffer from spare block.
3808 //
3809 CopyMem (NvStorageData, (UINT8 *) (UINTN) (FtwLastWriteData->SpareAddress), NvStorageSize);
3810 } else if ((FtwLastWriteData->TargetAddress > NvStorageBase) &&
3811 (FtwLastWriteData->TargetAddress < (NvStorageBase + NvStorageSize))) {
3812 //
3813 // Flash NV storage from the Offset is backed up in spare block.
3814 //
3815 BackUpOffset = (UINT32) (FtwLastWriteData->TargetAddress - NvStorageBase);
3816 BackUpSize = NvStorageSize - BackUpOffset;
3817 DEBUG ((EFI_D_INFO, "Variable: High partial NV storage from offset: %x is backed up in spare block: 0x%x\n", BackUpOffset, (UINTN) FtwLastWriteData->SpareAddress));
3818 //
3819 // Copy the partial backed up NV storage data to the memory buffer from spare block.
3820 //
3821 CopyMem (NvStorageData + BackUpOffset, (UINT8 *) (UINTN) FtwLastWriteData->SpareAddress, BackUpSize);
3822 }
3823 }
3824
3825 FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) NvStorageData;
3826
3827 //
3828 // Check if the Firmware Volume is not corrupted
3829 //
3830 if ((FvHeader->Signature != EFI_FVH_SIGNATURE) || (!CompareGuid (&gEfiSystemNvDataFvGuid, &FvHeader->FileSystemGuid))) {
3831 FreePool (NvStorageData);
3832 DEBUG ((EFI_D_ERROR, "Firmware Volume for Variable Store is corrupted\n"));
3833 return EFI_VOLUME_CORRUPTED;
3834 }
3835
3836 VariableStoreBase = (EFI_PHYSICAL_ADDRESS) ((UINTN) FvHeader + FvHeader->HeaderLength);
3837 VariableStoreLength = (UINT64) (NvStorageSize - FvHeader->HeaderLength);
3838
3839 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
3840 mNvVariableCache = (VARIABLE_STORE_HEADER *) (UINTN) VariableStoreBase;
3841 if (GetVariableStoreStatus (mNvVariableCache) != EfiValid) {
3842 FreePool (NvStorageData);
3843 DEBUG((EFI_D_ERROR, "Variable Store header is corrupted\n"));
3844 return EFI_VOLUME_CORRUPTED;
3845 }
3846 ASSERT(mNvVariableCache->Size == VariableStoreLength);
3847
3848 ASSERT (sizeof (VARIABLE_STORE_HEADER) <= VariableStoreLength);
3849
3850 mVariableModuleGlobal->VariableGlobal.AuthFormat = (BOOLEAN)(CompareGuid (&mNvVariableCache->Signature, &gEfiAuthenticatedVariableGuid));
3851
3852 HwErrStorageSize = PcdGet32 (PcdHwErrStorageSize);
3853 MaxUserNvVariableSpaceSize = PcdGet32 (PcdMaxUserNvVariableSpaceSize);
3854 BoottimeReservedNvVariableSpaceSize = PcdGet32 (PcdBoottimeReservedNvVariableSpaceSize);
3855
3856 //
3857 // Note that in EdkII variable driver implementation, Hardware Error Record type variable
3858 // is stored with common variable in the same NV region. So the platform integrator should
3859 // ensure that the value of PcdHwErrStorageSize is less than the value of
3860 // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).
3861 //
3862 ASSERT (HwErrStorageSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)));
3863 //
3864 // Ensure that the value of PcdMaxUserNvVariableSpaceSize is less than the value of
3865 // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).
3866 //
3867 ASSERT (MaxUserNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize));
3868 //
3869 // Ensure that the value of PcdBoottimeReservedNvVariableSpaceSize is less than the value of
3870 // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).
3871 //
3872 ASSERT (BoottimeReservedNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize));
3873
3874 mVariableModuleGlobal->CommonVariableSpace = ((UINTN) VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize);
3875 mVariableModuleGlobal->CommonMaxUserVariableSpace = ((MaxUserNvVariableSpaceSize != 0) ? MaxUserNvVariableSpaceSize : mVariableModuleGlobal->CommonVariableSpace);
3876 mVariableModuleGlobal->CommonRuntimeVariableSpace = mVariableModuleGlobal->CommonVariableSpace - BoottimeReservedNvVariableSpaceSize;
3877
3878 DEBUG ((EFI_D_INFO, "Variable driver common space: 0x%x 0x%x 0x%x\n", mVariableModuleGlobal->CommonVariableSpace, mVariableModuleGlobal->CommonMaxUserVariableSpace, mVariableModuleGlobal->CommonRuntimeVariableSpace));
3879
3880 //
3881 // The max NV variable size should be < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).
3882 //
3883 ASSERT (GetNonVolatileMaxVariableSize () < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)));
3884
3885 mVariableModuleGlobal->MaxVariableSize = PcdGet32 (PcdMaxVariableSize);
3886 mVariableModuleGlobal->MaxAuthVariableSize = ((PcdGet32 (PcdMaxAuthVariableSize) != 0) ? PcdGet32 (PcdMaxAuthVariableSize) : mVariableModuleGlobal->MaxVariableSize);
3887
3888 //
3889 // Parse non-volatile variable data and get last variable offset.
3890 //
3891 Variable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase);
3892 while (IsValidVariableHeader (Variable, GetEndPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase))) {
3893 NextVariable = GetNextVariablePtr (Variable);
3894 VariableSize = (UINTN) NextVariable - (UINTN) Variable;
3895 if ((Variable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
3896 mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;
3897 } else {
3898 mVariableModuleGlobal->CommonVariableTotalSize += VariableSize;
3899 }
3900
3901 Variable = NextVariable;
3902 }
3903 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) Variable - (UINTN) VariableStoreBase;
3904
3905 *NvFvHeader = FvHeader;
3906 return EFI_SUCCESS;
3907 }
3908
3909 /**
3910 Flush the HOB variable to flash.
3911
3912 @param[in] VariableName Name of variable has been updated or deleted.
3913 @param[in] VendorGuid Guid of variable has been updated or deleted.
3914
3915 **/
3916 VOID
3917 FlushHobVariableToFlash (
3918 IN CHAR16 *VariableName,
3919 IN EFI_GUID *VendorGuid
3920 )
3921 {
3922 EFI_STATUS Status;
3923 VARIABLE_STORE_HEADER *VariableStoreHeader;
3924 VARIABLE_HEADER *Variable;
3925 VOID *VariableData;
3926 VARIABLE_POINTER_TRACK VariablePtrTrack;
3927 BOOLEAN ErrorFlag;
3928
3929 ErrorFlag = FALSE;
3930
3931 //
3932 // Flush the HOB variable to flash.
3933 //
3934 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
3935 VariableStoreHeader = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
3936 //
3937 // Set HobVariableBase to 0, it can avoid SetVariable to call back.
3938 //
3939 mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0;
3940 for ( Variable = GetStartPointer (VariableStoreHeader)
3941 ; IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))
3942 ; Variable = GetNextVariablePtr (Variable)
3943 ) {
3944 if (Variable->State != VAR_ADDED) {
3945 //
3946 // The HOB variable has been set to DELETED state in local.
3947 //
3948 continue;
3949 }
3950 ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0);
3951 if (VendorGuid == NULL || VariableName == NULL ||
3952 !CompareGuid (VendorGuid, GetVendorGuidPtr (Variable)) ||
3953 StrCmp (VariableName, GetVariableNamePtr (Variable)) != 0) {
3954 VariableData = GetVariableDataPtr (Variable);
3955 FindVariable (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &VariablePtrTrack, &mVariableModuleGlobal->VariableGlobal, FALSE);
3956 Status = UpdateVariable (
3957 GetVariableNamePtr (Variable),
3958 GetVendorGuidPtr (Variable),
3959 VariableData,
3960 DataSizeOfVariable (Variable),
3961 Variable->Attributes,
3962 0,
3963 0,
3964 &VariablePtrTrack,
3965 NULL
3966 );
3967 DEBUG ((EFI_D_INFO, "Variable driver flush the HOB variable to flash: %g %s %r\n", GetVendorGuidPtr (Variable), GetVariableNamePtr (Variable), Status));
3968 } else {
3969 //
3970 // The updated or deleted variable is matched with this HOB variable.
3971 // Don't break here because we will try to set other HOB variables
3972 // since this variable could be set successfully.
3973 //
3974 Status = EFI_SUCCESS;
3975 }
3976 if (!EFI_ERROR (Status)) {
3977 //
3978 // If set variable successful, or the updated or deleted variable is matched with the HOB variable,
3979 // set the HOB variable to DELETED state in local.
3980 //
3981 DEBUG ((EFI_D_INFO, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", GetVendorGuidPtr (Variable), GetVariableNamePtr (Variable)));
3982 Variable->State &= VAR_DELETED;
3983 } else {
3984 ErrorFlag = TRUE;
3985 }
3986 }
3987 if (ErrorFlag) {
3988 //
3989 // We still have HOB variable(s) not flushed in flash.
3990 //
3991 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStoreHeader;
3992 } else {
3993 //
3994 // All HOB variables have been flushed in flash.
3995 //
3996 DEBUG ((EFI_D_INFO, "Variable driver: all HOB variables have been flushed in flash.\n"));
3997 if (!AtRuntime ()) {
3998 FreePool ((VOID *) VariableStoreHeader);
3999 }
4000 }
4001 }
4002
4003 }
4004
4005 /**
4006 Initializes variable write service after FTW was ready.
4007
4008 @retval EFI_SUCCESS Function successfully executed.
4009 @retval Others Fail to initialize the variable service.
4010
4011 **/
4012 EFI_STATUS
4013 VariableWriteServiceInitialize (
4014 VOID
4015 )
4016 {
4017 EFI_STATUS Status;
4018 VARIABLE_STORE_HEADER *VariableStoreHeader;
4019 UINTN Index;
4020 UINT8 Data;
4021 EFI_PHYSICAL_ADDRESS VariableStoreBase;
4022 EFI_PHYSICAL_ADDRESS NvStorageBase;
4023 VARIABLE_ENTRY_PROPERTY *VariableEntry;
4024
4025 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
4026
4027 NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);
4028 if (NvStorageBase == 0) {
4029 NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);
4030 }
4031 VariableStoreBase = NvStorageBase + (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(NvStorageBase))->HeaderLength);
4032
4033 //
4034 // Let NonVolatileVariableBase point to flash variable store base directly after FTW ready.
4035 //
4036 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
4037 VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;
4038
4039 //
4040 // Check if the free area is really free.
4041 //
4042 for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreHeader->Size; Index++) {
4043 Data = ((UINT8 *) mNvVariableCache)[Index];
4044 if (Data != 0xff) {
4045 //
4046 // There must be something wrong in variable store, do reclaim operation.
4047 //
4048 Status = Reclaim (
4049 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
4050 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
4051 FALSE,
4052 NULL,
4053 NULL,
4054 0
4055 );
4056 if (EFI_ERROR (Status)) {
4057 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
4058 return Status;
4059 }
4060 break;
4061 }
4062 }
4063
4064 FlushHobVariableToFlash (NULL, NULL);
4065
4066 Status = EFI_SUCCESS;
4067 ZeroMem (&mContextOut, sizeof (mContextOut));
4068 if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
4069 //
4070 // Authenticated variable initialize.
4071 //
4072 mContextIn.StructSize = sizeof (AUTH_VAR_LIB_CONTEXT_IN);
4073 mContextIn.MaxAuthVariableSize = mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ();
4074 Status = AuthVariableLibInitialize (&mContextIn, &mContextOut);
4075 if (!EFI_ERROR (Status)) {
4076 DEBUG ((EFI_D_INFO, "Variable driver will work with auth variable support!\n"));
4077 mVariableModuleGlobal->VariableGlobal.AuthSupport = TRUE;
4078 if (mContextOut.AuthVarEntry != NULL) {
4079 for (Index = 0; Index < mContextOut.AuthVarEntryCount; Index++) {
4080 VariableEntry = &mContextOut.AuthVarEntry[Index];
4081 Status = InternalVarCheckVariablePropertySet (
4082 VariableEntry->Name,
4083 VariableEntry->Guid,
4084 &VariableEntry->VariableProperty
4085 );
4086 ASSERT_EFI_ERROR (Status);
4087 }
4088 }
4089 } else if (Status == EFI_UNSUPPORTED) {
4090 DEBUG ((EFI_D_INFO, "NOTICE - AuthVariableLibInitialize() returns %r!\n", Status));
4091 DEBUG ((EFI_D_INFO, "Variable driver will continue to work without auth variable support!\n"));
4092 mVariableModuleGlobal->VariableGlobal.AuthSupport = FALSE;
4093 Status = EFI_SUCCESS;
4094 }
4095 }
4096
4097 if (!EFI_ERROR (Status)) {
4098 for (Index = 0; Index < sizeof (mVariableEntryProperty) / sizeof (mVariableEntryProperty[0]); Index++) {
4099 VariableEntry = &mVariableEntryProperty[Index];
4100 Status = InternalVarCheckVariablePropertySet (VariableEntry->Name, VariableEntry->Guid, &VariableEntry->VariableProperty);
4101 ASSERT_EFI_ERROR (Status);
4102 }
4103 }
4104
4105 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
4106 return Status;
4107 }
4108
4109
4110 /**
4111 Initializes variable store area for non-volatile and volatile variable.
4112
4113 @retval EFI_SUCCESS Function successfully executed.
4114 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
4115
4116 **/
4117 EFI_STATUS
4118 VariableCommonInitialize (
4119 VOID
4120 )
4121 {
4122 EFI_STATUS Status;
4123 VARIABLE_STORE_HEADER *VolatileVariableStore;
4124 VARIABLE_STORE_HEADER *VariableStoreHeader;
4125 UINT64 VariableStoreLength;
4126 UINTN ScratchSize;
4127 EFI_HOB_GUID_TYPE *GuidHob;
4128 EFI_GUID *VariableGuid;
4129 EFI_FIRMWARE_VOLUME_HEADER *NvFvHeader;
4130
4131 //
4132 // Allocate runtime memory for variable driver global structure.
4133 //
4134 mVariableModuleGlobal = AllocateRuntimeZeroPool (sizeof (VARIABLE_MODULE_GLOBAL));
4135 if (mVariableModuleGlobal == NULL) {
4136 return EFI_OUT_OF_RESOURCES;
4137 }
4138
4139 InitializeLock (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);
4140
4141 //
4142 // Init non-volatile variable store.
4143 //
4144 NvFvHeader = NULL;
4145 Status = InitNonVolatileVariableStore (&NvFvHeader);
4146 if (EFI_ERROR (Status)) {
4147 FreePool (mVariableModuleGlobal);
4148 return Status;
4149 }
4150
4151 //
4152 // mVariableModuleGlobal->VariableGlobal.AuthFormat
4153 // has been initialized in InitNonVolatileVariableStore().
4154 //
4155 if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
4156 DEBUG ((EFI_D_INFO, "Variable driver will work with auth variable format!\n"));
4157 //
4158 // Set AuthSupport to FALSE first, VariableWriteServiceInitialize() will initialize it.
4159 //
4160 mVariableModuleGlobal->VariableGlobal.AuthSupport = FALSE;
4161 VariableGuid = &gEfiAuthenticatedVariableGuid;
4162 } else {
4163 DEBUG ((EFI_D_INFO, "Variable driver will work without auth variable support!\n"));
4164 mVariableModuleGlobal->VariableGlobal.AuthSupport = FALSE;
4165 VariableGuid = &gEfiVariableGuid;
4166 }
4167
4168 //
4169 // Get HOB variable store.
4170 //
4171 GuidHob = GetFirstGuidHob (VariableGuid);
4172 if (GuidHob != NULL) {
4173 VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob);
4174 VariableStoreLength = (UINT64) (GuidHob->Header.HobLength - sizeof (EFI_HOB_GUID_TYPE));
4175 if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {
4176 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) AllocateRuntimeCopyPool ((UINTN) VariableStoreLength, (VOID *) VariableStoreHeader);
4177 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase == 0) {
4178 FreePool (NvFvHeader);
4179 FreePool (mVariableModuleGlobal);
4180 return EFI_OUT_OF_RESOURCES;
4181 }
4182 } else {
4183 DEBUG ((EFI_D_ERROR, "HOB Variable Store header is corrupted!\n"));
4184 }
4185 }
4186
4187 //
4188 // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.
4189 //
4190 ScratchSize = GetNonVolatileMaxVariableSize ();
4191 mVariableModuleGlobal->ScratchBufferSize = ScratchSize;
4192 VolatileVariableStore = AllocateRuntimePool (PcdGet32 (PcdVariableStoreSize) + ScratchSize);
4193 if (VolatileVariableStore == NULL) {
4194 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
4195 FreePool ((VOID *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase);
4196 }
4197 FreePool (NvFvHeader);
4198 FreePool (mVariableModuleGlobal);
4199 return EFI_OUT_OF_RESOURCES;
4200 }
4201
4202 SetMem (VolatileVariableStore, PcdGet32 (PcdVariableStoreSize) + ScratchSize, 0xff);
4203
4204 //
4205 // Initialize Variable Specific Data.
4206 //
4207 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VolatileVariableStore;
4208 mVariableModuleGlobal->VolatileLastVariableOffset = (UINTN) GetStartPointer (VolatileVariableStore) - (UINTN) VolatileVariableStore;
4209
4210 CopyGuid (&VolatileVariableStore->Signature, VariableGuid);
4211 VolatileVariableStore->Size = PcdGet32 (PcdVariableStoreSize);
4212 VolatileVariableStore->Format = VARIABLE_STORE_FORMATTED;
4213 VolatileVariableStore->State = VARIABLE_STORE_HEALTHY;
4214 VolatileVariableStore->Reserved = 0;
4215 VolatileVariableStore->Reserved1 = 0;
4216
4217 return EFI_SUCCESS;
4218 }
4219
4220
4221 /**
4222 Get the proper fvb handle and/or fvb protocol by the given Flash address.
4223
4224 @param[in] Address The Flash address.
4225 @param[out] FvbHandle In output, if it is not NULL, it points to the proper FVB handle.
4226 @param[out] FvbProtocol In output, if it is not NULL, it points to the proper FVB protocol.
4227
4228 **/
4229 EFI_STATUS
4230 GetFvbInfoByAddress (
4231 IN EFI_PHYSICAL_ADDRESS Address,
4232 OUT EFI_HANDLE *FvbHandle OPTIONAL,
4233 OUT EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL **FvbProtocol OPTIONAL
4234 )
4235 {
4236 EFI_STATUS Status;
4237 EFI_HANDLE *HandleBuffer;
4238 UINTN HandleCount;
4239 UINTN Index;
4240 EFI_PHYSICAL_ADDRESS FvbBaseAddress;
4241 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
4242 EFI_FVB_ATTRIBUTES_2 Attributes;
4243 UINTN BlockSize;
4244 UINTN NumberOfBlocks;
4245
4246 HandleBuffer = NULL;
4247 //
4248 // Get all FVB handles.
4249 //
4250 Status = GetFvbCountAndBuffer (&HandleCount, &HandleBuffer);
4251 if (EFI_ERROR (Status)) {
4252 return EFI_NOT_FOUND;
4253 }
4254
4255 //
4256 // Get the FVB to access variable store.
4257 //
4258 Fvb = NULL;
4259 for (Index = 0; Index < HandleCount; Index += 1, Status = EFI_NOT_FOUND, Fvb = NULL) {
4260 Status = GetFvbByHandle (HandleBuffer[Index], &Fvb);
4261 if (EFI_ERROR (Status)) {
4262 Status = EFI_NOT_FOUND;
4263 break;
4264 }
4265
4266 //
4267 // Ensure this FVB protocol supported Write operation.
4268 //
4269 Status = Fvb->GetAttributes (Fvb, &Attributes);
4270 if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {
4271 continue;
4272 }
4273
4274 //
4275 // Compare the address and select the right one.
4276 //
4277 Status = Fvb->GetPhysicalAddress (Fvb, &FvbBaseAddress);
4278 if (EFI_ERROR (Status)) {
4279 continue;
4280 }
4281
4282 //
4283 // Assume one FVB has one type of BlockSize.
4284 //
4285 Status = Fvb->GetBlockSize (Fvb, 0, &BlockSize, &NumberOfBlocks);
4286 if (EFI_ERROR (Status)) {
4287 continue;
4288 }
4289
4290 if ((Address >= FvbBaseAddress) && (Address < (FvbBaseAddress + BlockSize * NumberOfBlocks))) {
4291 if (FvbHandle != NULL) {
4292 *FvbHandle = HandleBuffer[Index];
4293 }
4294 if (FvbProtocol != NULL) {
4295 *FvbProtocol = Fvb;
4296 }
4297 Status = EFI_SUCCESS;
4298 break;
4299 }
4300 }
4301 FreePool (HandleBuffer);
4302
4303 if (Fvb == NULL) {
4304 Status = EFI_NOT_FOUND;
4305 }
4306
4307 return Status;
4308 }
4309