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