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