]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c
1. Don't assume that flush the HOB variable to flash must be successful.
[mirror_edk2.git] / SecurityPkg / VariableAuthenticated / 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) 2009 - 2012, Intel Corporation. All rights reserved.<BR>
20 This program and the accompanying materials
21 are licensed and made available under the terms and conditions of the BSD License
22 which accompanies this distribution. The full text of the license may be found at
23 http://opensource.org/licenses/bsd-license.php
24
25 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
26 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
27
28 **/
29
30 #include "Variable.h"
31 #include "AuthService.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 /// The memory entry used for variable statistics data.
42 ///
43 VARIABLE_INFO_ENTRY *gVariableInfo = NULL;
44
45
46 /**
47 Routine used to track statistical information about variable usage.
48 The data is stored in the EFI system table so it can be accessed later.
49 VariableInfo.efi can dump out the table. Only Boot Services variable
50 accesses are tracked by this code. The PcdVariableCollectStatistics
51 build flag controls if this feature is enabled.
52
53 A read that hits in the cache will have Read and Cache true for
54 the transaction. Data is allocated by this routine, but never
55 freed.
56
57 @param[in] VariableName Name of the Variable to track.
58 @param[in] VendorGuid Guid of the Variable to track.
59 @param[in] Volatile TRUE if volatile FALSE if non-volatile.
60 @param[in] Read TRUE if GetVariable() was called.
61 @param[in] Write TRUE if SetVariable() was called.
62 @param[in] Delete TRUE if deleted via SetVariable().
63 @param[in] Cache TRUE for a cache hit.
64
65 **/
66 VOID
67 UpdateVariableInfo (
68 IN CHAR16 *VariableName,
69 IN EFI_GUID *VendorGuid,
70 IN BOOLEAN Volatile,
71 IN BOOLEAN Read,
72 IN BOOLEAN Write,
73 IN BOOLEAN Delete,
74 IN BOOLEAN Cache
75 )
76 {
77 VARIABLE_INFO_ENTRY *Entry;
78
79 if (FeaturePcdGet (PcdVariableCollectStatistics)) {
80
81 if (AtRuntime ()) {
82 // Don't collect statistics at runtime.
83 return;
84 }
85
86 if (gVariableInfo == NULL) {
87 //
88 // On the first call allocate a entry and place a pointer to it in
89 // the EFI System Table.
90 //
91 gVariableInfo = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY));
92 ASSERT (gVariableInfo != NULL);
93
94 CopyGuid (&gVariableInfo->VendorGuid, VendorGuid);
95 gVariableInfo->Name = AllocatePool (StrSize (VariableName));
96 ASSERT (gVariableInfo->Name != NULL);
97 StrCpy (gVariableInfo->Name, VariableName);
98 gVariableInfo->Volatile = Volatile;
99 }
100
101
102 for (Entry = gVariableInfo; Entry != NULL; Entry = Entry->Next) {
103 if (CompareGuid (VendorGuid, &Entry->VendorGuid)) {
104 if (StrCmp (VariableName, Entry->Name) == 0) {
105 if (Read) {
106 Entry->ReadCount++;
107 }
108 if (Write) {
109 Entry->WriteCount++;
110 }
111 if (Delete) {
112 Entry->DeleteCount++;
113 }
114 if (Cache) {
115 Entry->CacheCount++;
116 }
117
118 return;
119 }
120 }
121
122 if (Entry->Next == NULL) {
123 //
124 // If the entry is not in the table add it.
125 // Next iteration of the loop will fill in the data.
126 //
127 Entry->Next = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY));
128 ASSERT (Entry->Next != NULL);
129
130 CopyGuid (&Entry->Next->VendorGuid, VendorGuid);
131 Entry->Next->Name = AllocatePool (StrSize (VariableName));
132 ASSERT (Entry->Next->Name != NULL);
133 StrCpy (Entry->Next->Name, VariableName);
134 Entry->Next->Volatile = Volatile;
135 }
136
137 }
138 }
139 }
140
141
142 /**
143
144 This code checks if variable header is valid or not.
145
146 @param Variable Pointer to the Variable Header.
147
148 @retval TRUE Variable header is valid.
149 @retval FALSE Variable header is not valid.
150
151 **/
152 BOOLEAN
153 IsValidVariableHeader (
154 IN VARIABLE_HEADER *Variable
155 )
156 {
157 if (Variable == NULL || Variable->StartId != VARIABLE_DATA) {
158 return FALSE;
159 }
160
161 return TRUE;
162 }
163
164
165 /**
166
167 This function writes data to the FWH at the correct LBA even if the LBAs
168 are fragmented.
169
170 @param Global Pointer to VARAIBLE_GLOBAL structure.
171 @param Volatile Point out the Variable is Volatile or Non-Volatile.
172 @param SetByIndex TRUE if target pointer is given as index.
173 FALSE if target pointer is absolute.
174 @param Fvb Pointer to the writable FVB protocol.
175 @param DataPtrIndex Pointer to the Data from the end of VARIABLE_STORE_HEADER
176 structure.
177 @param DataSize Size of data to be written.
178 @param Buffer Pointer to the buffer from which data is written.
179
180 @retval EFI_INVALID_PARAMETER Parameters not valid.
181 @retval EFI_SUCCESS Variable store successfully updated.
182
183 **/
184 EFI_STATUS
185 UpdateVariableStore (
186 IN VARIABLE_GLOBAL *Global,
187 IN BOOLEAN Volatile,
188 IN BOOLEAN SetByIndex,
189 IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb,
190 IN UINTN DataPtrIndex,
191 IN UINT32 DataSize,
192 IN UINT8 *Buffer
193 )
194 {
195 EFI_FV_BLOCK_MAP_ENTRY *PtrBlockMapEntry;
196 UINTN BlockIndex2;
197 UINTN LinearOffset;
198 UINTN CurrWriteSize;
199 UINTN CurrWritePtr;
200 UINT8 *CurrBuffer;
201 EFI_LBA LbaNumber;
202 UINTN Size;
203 EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
204 VARIABLE_STORE_HEADER *VolatileBase;
205 EFI_PHYSICAL_ADDRESS FvVolHdr;
206 EFI_PHYSICAL_ADDRESS DataPtr;
207 EFI_STATUS Status;
208
209 FwVolHeader = NULL;
210 DataPtr = DataPtrIndex;
211
212 //
213 // Check if the Data is Volatile.
214 //
215 if (!Volatile) {
216 if (Fvb == NULL) {
217 return EFI_INVALID_PARAMETER;
218 }
219 Status = Fvb->GetPhysicalAddress(Fvb, &FvVolHdr);
220 ASSERT_EFI_ERROR (Status);
221
222 FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) FvVolHdr);
223 //
224 // Data Pointer should point to the actual Address where data is to be
225 // written.
226 //
227 if (SetByIndex) {
228 DataPtr += mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
229 }
230
231 if ((DataPtr + DataSize) >= ((EFI_PHYSICAL_ADDRESS) (UINTN) ((UINT8 *) FwVolHeader + FwVolHeader->FvLength))) {
232 return EFI_INVALID_PARAMETER;
233 }
234 } else {
235 //
236 // Data Pointer should point to the actual Address where data is to be
237 // written.
238 //
239 VolatileBase = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
240 if (SetByIndex) {
241 DataPtr += mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
242 }
243
244 if ((DataPtr + DataSize) >= ((UINTN) ((UINT8 *) VolatileBase + VolatileBase->Size))) {
245 return EFI_INVALID_PARAMETER;
246 }
247
248 //
249 // If Volatile Variable just do a simple mem copy.
250 //
251 CopyMem ((UINT8 *)(UINTN)DataPtr, Buffer, DataSize);
252 return EFI_SUCCESS;
253 }
254
255 //
256 // If we are here we are dealing with Non-Volatile Variables.
257 //
258 LinearOffset = (UINTN) FwVolHeader;
259 CurrWritePtr = (UINTN) DataPtr;
260 CurrWriteSize = DataSize;
261 CurrBuffer = Buffer;
262 LbaNumber = 0;
263
264 if (CurrWritePtr < LinearOffset) {
265 return EFI_INVALID_PARAMETER;
266 }
267
268 for (PtrBlockMapEntry = FwVolHeader->BlockMap; PtrBlockMapEntry->NumBlocks != 0; PtrBlockMapEntry++) {
269 for (BlockIndex2 = 0; BlockIndex2 < PtrBlockMapEntry->NumBlocks; BlockIndex2++) {
270 //
271 // Check to see if the Variable Writes are spanning through multiple
272 // blocks.
273 //
274 if ((CurrWritePtr >= LinearOffset) && (CurrWritePtr < LinearOffset + PtrBlockMapEntry->Length)) {
275 if ((CurrWritePtr + CurrWriteSize) <= (LinearOffset + PtrBlockMapEntry->Length)) {
276 Status = Fvb->Write (
277 Fvb,
278 LbaNumber,
279 (UINTN) (CurrWritePtr - LinearOffset),
280 &CurrWriteSize,
281 CurrBuffer
282 );
283 return Status;
284 } else {
285 Size = (UINT32) (LinearOffset + PtrBlockMapEntry->Length - CurrWritePtr);
286 Status = Fvb->Write (
287 Fvb,
288 LbaNumber,
289 (UINTN) (CurrWritePtr - LinearOffset),
290 &Size,
291 CurrBuffer
292 );
293 if (EFI_ERROR (Status)) {
294 return Status;
295 }
296
297 CurrWritePtr = LinearOffset + PtrBlockMapEntry->Length;
298 CurrBuffer = CurrBuffer + Size;
299 CurrWriteSize = CurrWriteSize - Size;
300 }
301 }
302
303 LinearOffset += PtrBlockMapEntry->Length;
304 LbaNumber++;
305 }
306 }
307
308 return EFI_SUCCESS;
309 }
310
311
312 /**
313
314 This code gets the current status of Variable Store.
315
316 @param VarStoreHeader Pointer to the Variable Store Header.
317
318 @retval EfiRaw Variable store status is raw.
319 @retval EfiValid Variable store status is valid.
320 @retval EfiInvalid Variable store status is invalid.
321
322 **/
323 VARIABLE_STORE_STATUS
324 GetVariableStoreStatus (
325 IN VARIABLE_STORE_HEADER *VarStoreHeader
326 )
327 {
328 if (CompareGuid (&VarStoreHeader->Signature, &gEfiAuthenticatedVariableGuid) &&
329 VarStoreHeader->Format == VARIABLE_STORE_FORMATTED &&
330 VarStoreHeader->State == VARIABLE_STORE_HEALTHY
331 ) {
332
333 return EfiValid;
334 } else if (((UINT32 *)(&VarStoreHeader->Signature))[0] == 0xffffffff &&
335 ((UINT32 *)(&VarStoreHeader->Signature))[1] == 0xffffffff &&
336 ((UINT32 *)(&VarStoreHeader->Signature))[2] == 0xffffffff &&
337 ((UINT32 *)(&VarStoreHeader->Signature))[3] == 0xffffffff &&
338 VarStoreHeader->Size == 0xffffffff &&
339 VarStoreHeader->Format == 0xff &&
340 VarStoreHeader->State == 0xff
341 ) {
342
343 return EfiRaw;
344 } else {
345 return EfiInvalid;
346 }
347 }
348
349
350 /**
351
352 This code gets the size of name of variable.
353
354 @param Variable Pointer to the Variable Header.
355
356 @return UINTN Size of variable in bytes.
357
358 **/
359 UINTN
360 NameSizeOfVariable (
361 IN VARIABLE_HEADER *Variable
362 )
363 {
364 if (Variable->State == (UINT8) (-1) ||
365 Variable->DataSize == (UINT32) (-1) ||
366 Variable->NameSize == (UINT32) (-1) ||
367 Variable->Attributes == (UINT32) (-1)) {
368 return 0;
369 }
370 return (UINTN) Variable->NameSize;
371 }
372
373 /**
374
375 This code gets the size of variable data.
376
377 @param Variable Pointer to the Variable Header.
378
379 @return Size of variable in bytes.
380
381 **/
382 UINTN
383 DataSizeOfVariable (
384 IN VARIABLE_HEADER *Variable
385 )
386 {
387 if (Variable->State == (UINT8) (-1) ||
388 Variable->DataSize == (UINT32) (-1) ||
389 Variable->NameSize == (UINT32) (-1) ||
390 Variable->Attributes == (UINT32) (-1)) {
391 return 0;
392 }
393 return (UINTN) Variable->DataSize;
394 }
395
396 /**
397
398 This code gets the pointer to the variable name.
399
400 @param Variable Pointer to the Variable Header.
401
402 @return Pointer to Variable Name which is Unicode encoding.
403
404 **/
405 CHAR16 *
406 GetVariableNamePtr (
407 IN VARIABLE_HEADER *Variable
408 )
409 {
410
411 return (CHAR16 *) (Variable + 1);
412 }
413
414 /**
415
416 This code gets the pointer to the variable data.
417
418 @param Variable Pointer to the Variable Header.
419
420 @return Pointer to Variable Data.
421
422 **/
423 UINT8 *
424 GetVariableDataPtr (
425 IN VARIABLE_HEADER *Variable
426 )
427 {
428 UINTN Value;
429
430 //
431 // Be careful about pad size for alignment.
432 //
433 Value = (UINTN) GetVariableNamePtr (Variable);
434 Value += NameSizeOfVariable (Variable);
435 Value += GET_PAD_SIZE (NameSizeOfVariable (Variable));
436
437 return (UINT8 *) Value;
438 }
439
440
441 /**
442
443 This code gets the pointer to the next variable header.
444
445 @param Variable Pointer to the Variable Header.
446
447 @return Pointer to next variable header.
448
449 **/
450 VARIABLE_HEADER *
451 GetNextVariablePtr (
452 IN VARIABLE_HEADER *Variable
453 )
454 {
455 UINTN Value;
456
457 if (!IsValidVariableHeader (Variable)) {
458 return NULL;
459 }
460
461 Value = (UINTN) GetVariableDataPtr (Variable);
462 Value += DataSizeOfVariable (Variable);
463 Value += GET_PAD_SIZE (DataSizeOfVariable (Variable));
464
465 //
466 // Be careful about pad size for alignment.
467 //
468 return (VARIABLE_HEADER *) HEADER_ALIGN (Value);
469 }
470
471 /**
472
473 Gets the pointer to the first variable header in given variable store area.
474
475 @param VarStoreHeader Pointer to the Variable Store Header.
476
477 @return Pointer to the first variable header.
478
479 **/
480 VARIABLE_HEADER *
481 GetStartPointer (
482 IN VARIABLE_STORE_HEADER *VarStoreHeader
483 )
484 {
485 //
486 // The end of variable store.
487 //
488 return (VARIABLE_HEADER *) HEADER_ALIGN (VarStoreHeader + 1);
489 }
490
491 /**
492
493 Gets the pointer to the end of the variable storage area.
494
495 This function gets pointer to the end of the variable storage
496 area, according to the input variable store header.
497
498 @param VarStoreHeader Pointer to the Variable Store Header.
499
500 @return Pointer to the end of the variable storage area.
501
502 **/
503 VARIABLE_HEADER *
504 GetEndPointer (
505 IN VARIABLE_STORE_HEADER *VarStoreHeader
506 )
507 {
508 //
509 // The end of variable store
510 //
511 return (VARIABLE_HEADER *) HEADER_ALIGN ((UINTN) VarStoreHeader + VarStoreHeader->Size);
512 }
513
514
515 /**
516
517 Variable store garbage collection and reclaim operation.
518
519 @param VariableBase Base address of variable store.
520 @param LastVariableOffset Offset of last variable.
521 @param IsVolatile The variable store is volatile or not;
522 if it is non-volatile, need FTW.
523 @param UpdatingVariable Pointer to updating variable.
524 @param ReclaimAnyway If TRUE, do reclaim anyway.
525
526 @return EFI_OUT_OF_RESOURCES
527 @return EFI_SUCCESS
528 @return Others
529
530 **/
531 EFI_STATUS
532 Reclaim (
533 IN EFI_PHYSICAL_ADDRESS VariableBase,
534 OUT UINTN *LastVariableOffset,
535 IN BOOLEAN IsVolatile,
536 IN VARIABLE_HEADER *UpdatingVariable,
537 IN BOOLEAN ReclaimAnyway
538 )
539 {
540 VARIABLE_HEADER *Variable;
541 VARIABLE_HEADER *AddedVariable;
542 VARIABLE_HEADER *NextVariable;
543 VARIABLE_HEADER *NextAddedVariable;
544 VARIABLE_STORE_HEADER *VariableStoreHeader;
545 UINT8 *ValidBuffer;
546 UINTN MaximumBufferSize;
547 UINTN VariableSize;
548 UINTN VariableNameSize;
549 UINTN UpdatingVariableNameSize;
550 UINTN NameSize;
551 UINT8 *CurrPtr;
552 VOID *Point0;
553 VOID *Point1;
554 BOOLEAN FoundAdded;
555 EFI_STATUS Status;
556 CHAR16 *VariableNamePtr;
557 CHAR16 *UpdatingVariableNamePtr;
558 UINTN CommonVariableTotalSize;
559 UINTN HwErrVariableTotalSize;
560 BOOLEAN NeedDoReclaim;
561
562 NeedDoReclaim = FALSE;
563 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) VariableBase);
564
565 CommonVariableTotalSize = 0;
566 HwErrVariableTotalSize = 0;
567
568 //
569 // Start Pointers for the variable.
570 //
571 Variable = GetStartPointer (VariableStoreHeader);
572 MaximumBufferSize = sizeof (VARIABLE_STORE_HEADER);
573
574 while (IsValidVariableHeader (Variable)) {
575 NextVariable = GetNextVariablePtr (Variable);
576 if (Variable->State == VAR_ADDED ||
577 Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)
578 ) {
579 VariableSize = (UINTN) NextVariable - (UINTN) Variable;
580 MaximumBufferSize += VariableSize;
581 } else {
582 NeedDoReclaim = TRUE;
583 }
584
585 Variable = NextVariable;
586 }
587
588 if (!ReclaimAnyway && !NeedDoReclaim) {
589 DEBUG ((EFI_D_INFO, "Variable driver: no DELETED variable found, so no variable space could be reclaimed.\n"));
590 return EFI_SUCCESS;
591 }
592
593 //
594 // Reserve the 1 Bytes with Oxff to identify the
595 // end of the variable buffer.
596 //
597 MaximumBufferSize += 1;
598 ValidBuffer = AllocatePool (MaximumBufferSize);
599 if (ValidBuffer == NULL) {
600 return EFI_OUT_OF_RESOURCES;
601 }
602
603 SetMem (ValidBuffer, MaximumBufferSize, 0xff);
604
605 //
606 // Copy variable store header.
607 //
608 CopyMem (ValidBuffer, VariableStoreHeader, sizeof (VARIABLE_STORE_HEADER));
609 CurrPtr = (UINT8 *) GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);
610
611 //
612 // Reinstall all ADDED variables as long as they are not identical to Updating Variable.
613 //
614 Variable = GetStartPointer (VariableStoreHeader);
615 while (IsValidVariableHeader (Variable)) {
616 NextVariable = GetNextVariablePtr (Variable);
617 if (Variable->State == VAR_ADDED) {
618 if (UpdatingVariable != NULL) {
619 if (UpdatingVariable == Variable) {
620 Variable = NextVariable;
621 continue;
622 }
623
624 VariableNameSize = NameSizeOfVariable(Variable);
625 UpdatingVariableNameSize = NameSizeOfVariable(UpdatingVariable);
626
627 VariableNamePtr = GetVariableNamePtr (Variable);
628 UpdatingVariableNamePtr = GetVariableNamePtr (UpdatingVariable);
629 if (CompareGuid (&Variable->VendorGuid, &UpdatingVariable->VendorGuid) &&
630 VariableNameSize == UpdatingVariableNameSize &&
631 CompareMem (VariableNamePtr, UpdatingVariableNamePtr, VariableNameSize) == 0 ) {
632 Variable = NextVariable;
633 continue;
634 }
635 }
636 VariableSize = (UINTN) NextVariable - (UINTN) Variable;
637 CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);
638 CurrPtr += VariableSize;
639 if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
640 HwErrVariableTotalSize += VariableSize;
641 } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
642 CommonVariableTotalSize += VariableSize;
643 }
644 }
645 Variable = NextVariable;
646 }
647
648 //
649 // Reinstall the variable being updated if it is not NULL.
650 //
651 if (UpdatingVariable != NULL) {
652 VariableSize = (UINTN)(GetNextVariablePtr (UpdatingVariable)) - (UINTN)UpdatingVariable;
653 CopyMem (CurrPtr, (UINT8 *) UpdatingVariable, VariableSize);
654 CurrPtr += VariableSize;
655 if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
656 HwErrVariableTotalSize += VariableSize;
657 } else if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
658 CommonVariableTotalSize += VariableSize;
659 }
660 }
661
662 //
663 // Reinstall all in delete transition variables.
664 //
665 Variable = GetStartPointer (VariableStoreHeader);
666 while (IsValidVariableHeader (Variable)) {
667 NextVariable = GetNextVariablePtr (Variable);
668 if (Variable != UpdatingVariable && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
669
670 //
671 // Buffer has cached all ADDED variable.
672 // Per IN_DELETED variable, we have to guarantee that
673 // no ADDED one in previous buffer.
674 //
675
676 FoundAdded = FALSE;
677 AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);
678 while (IsValidVariableHeader (AddedVariable)) {
679 NextAddedVariable = GetNextVariablePtr (AddedVariable);
680 NameSize = NameSizeOfVariable (AddedVariable);
681 if (CompareGuid (&AddedVariable->VendorGuid, &Variable->VendorGuid) &&
682 NameSize == NameSizeOfVariable (Variable)
683 ) {
684 Point0 = (VOID *) GetVariableNamePtr (AddedVariable);
685 Point1 = (VOID *) GetVariableNamePtr (Variable);
686 if (CompareMem (Point0, Point1, NameSizeOfVariable (AddedVariable)) == 0) {
687 FoundAdded = TRUE;
688 break;
689 }
690 }
691 AddedVariable = NextAddedVariable;
692 }
693 if (!FoundAdded) {
694 //
695 // Promote VAR_IN_DELETED_TRANSITION to VAR_ADDED.
696 //
697 VariableSize = (UINTN) NextVariable - (UINTN) Variable;
698 CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);
699 ((VARIABLE_HEADER *) CurrPtr)->State = VAR_ADDED;
700 CurrPtr += VariableSize;
701 if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
702 HwErrVariableTotalSize += VariableSize;
703 } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
704 CommonVariableTotalSize += VariableSize;
705 }
706 }
707 }
708
709 Variable = NextVariable;
710 }
711
712 if (IsVolatile) {
713 //
714 // If volatile variable store, just copy valid buffer.
715 //
716 SetMem ((UINT8 *) (UINTN) VariableBase, VariableStoreHeader->Size, 0xff);
717 CopyMem ((UINT8 *) (UINTN) VariableBase, ValidBuffer, (UINTN) (CurrPtr - (UINT8 *) ValidBuffer));
718 Status = EFI_SUCCESS;
719 } else {
720 //
721 // If non-volatile variable store, perform FTW here.
722 //
723 Status = FtwVariableSpace (
724 VariableBase,
725 ValidBuffer,
726 (UINTN) (CurrPtr - (UINT8 *) ValidBuffer)
727 );
728 CopyMem (mNvVariableCache, (CHAR8 *)(UINTN)VariableBase, VariableStoreHeader->Size);
729 }
730 if (!EFI_ERROR (Status)) {
731 *LastVariableOffset = (UINTN) (CurrPtr - (UINT8 *) ValidBuffer);
732 if (!IsVolatile) {
733 mVariableModuleGlobal->HwErrVariableTotalSize = HwErrVariableTotalSize;
734 mVariableModuleGlobal->CommonVariableTotalSize = CommonVariableTotalSize;
735 }
736 } else {
737 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase);
738 while (IsValidVariableHeader (NextVariable)) {
739 VariableSize = NextVariable->NameSize + NextVariable->DataSize + sizeof (VARIABLE_HEADER);
740 if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
741 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VariableSize);
742 } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
743 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize);
744 }
745
746 NextVariable = GetNextVariablePtr (NextVariable);
747 }
748 *LastVariableOffset = (UINTN) NextVariable - (UINTN) VariableBase;
749 }
750
751 FreePool (ValidBuffer);
752
753 return Status;
754 }
755
756 /**
757 Find the variable in the specified variable store.
758
759 @param[in] VariableName Name of the variable to be found
760 @param[in] VendorGuid Vendor GUID to be found.
761 @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
762 check at runtime when searching variable.
763 @param[in, out] PtrTrack Variable Track Pointer structure that contains Variable Information.
764
765 @retval EFI_SUCCESS Variable found successfully
766 @retval EFI_NOT_FOUND Variable not found
767 **/
768 EFI_STATUS
769 FindVariableEx (
770 IN CHAR16 *VariableName,
771 IN EFI_GUID *VendorGuid,
772 IN BOOLEAN IgnoreRtCheck,
773 IN OUT VARIABLE_POINTER_TRACK *PtrTrack
774 )
775 {
776 VARIABLE_HEADER *InDeletedVariable;
777 VOID *Point;
778
779 //
780 // Find the variable by walk through HOB, volatile and non-volatile variable store.
781 //
782 InDeletedVariable = NULL;
783
784 for ( PtrTrack->CurrPtr = PtrTrack->StartPtr
785 ; (PtrTrack->CurrPtr < PtrTrack->EndPtr) && IsValidVariableHeader (PtrTrack->CurrPtr)
786 ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr)
787 ) {
788 if (PtrTrack->CurrPtr->State == VAR_ADDED ||
789 PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)
790 ) {
791 if (IgnoreRtCheck || !AtRuntime () || ((PtrTrack->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
792 if (VariableName[0] == 0) {
793 if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
794 InDeletedVariable = PtrTrack->CurrPtr;
795 } else {
796 return EFI_SUCCESS;
797 }
798 } else {
799 if (CompareGuid (VendorGuid, &PtrTrack->CurrPtr->VendorGuid)) {
800 Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr);
801
802 ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0);
803 if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) {
804 if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
805 InDeletedVariable = PtrTrack->CurrPtr;
806 } else {
807 return EFI_SUCCESS;
808 }
809 }
810 }
811 }
812 }
813 }
814 }
815
816 PtrTrack->CurrPtr = InDeletedVariable;
817 return (PtrTrack->CurrPtr == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS;
818 }
819
820
821 /**
822 Finds variable in storage blocks of volatile and non-volatile storage areas.
823
824 This code finds variable in storage blocks of volatile and non-volatile storage areas.
825 If VariableName is an empty string, then we just return the first
826 qualified variable without comparing VariableName and VendorGuid.
827 If IgnoreRtCheck is TRUE, then we ignore the EFI_VARIABLE_RUNTIME_ACCESS attribute check
828 at runtime when searching existing variable, only VariableName and VendorGuid are compared.
829 Otherwise, variables without EFI_VARIABLE_RUNTIME_ACCESS are not visible at runtime.
830
831 @param[in] VariableName Name of the variable to be found.
832 @param[in] VendorGuid Vendor GUID to be found.
833 @param[out] PtrTrack VARIABLE_POINTER_TRACK structure for output,
834 including the range searched and the target position.
835 @param[in] Global Pointer to VARIABLE_GLOBAL structure, including
836 base of volatile variable storage area, base of
837 NV variable storage area, and a lock.
838 @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
839 check at runtime when searching variable.
840
841 @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while
842 VendorGuid is NULL.
843 @retval EFI_SUCCESS Variable successfully found.
844 @retval EFI_NOT_FOUND Variable not found
845
846 **/
847 EFI_STATUS
848 FindVariable (
849 IN CHAR16 *VariableName,
850 IN EFI_GUID *VendorGuid,
851 OUT VARIABLE_POINTER_TRACK *PtrTrack,
852 IN VARIABLE_GLOBAL *Global,
853 IN BOOLEAN IgnoreRtCheck
854 )
855 {
856 EFI_STATUS Status;
857 VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
858 VARIABLE_STORE_TYPE Type;
859
860 if (VariableName[0] != 0 && VendorGuid == NULL) {
861 return EFI_INVALID_PARAMETER;
862 }
863
864 //
865 // 0: Volatile, 1: HOB, 2: Non-Volatile.
866 // The index and attributes mapping must be kept in this order as RuntimeServiceGetNextVariableName
867 // make use of this mapping to implement search algorithm.
868 //
869 VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) Global->VolatileVariableBase;
870 VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) Global->HobVariableBase;
871 VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
872
873 //
874 // Find the variable by walk through HOB, volatile and non-volatile variable store.
875 //
876 for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
877 if (VariableStoreHeader[Type] == NULL) {
878 continue;
879 }
880
881 PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader[Type]);
882 PtrTrack->EndPtr = GetEndPointer (VariableStoreHeader[Type]);
883 PtrTrack->Volatile = (BOOLEAN) (Type == VariableStoreTypeVolatile);
884
885 Status = FindVariableEx (VariableName, VendorGuid, IgnoreRtCheck, PtrTrack);
886 if (!EFI_ERROR (Status)) {
887 return Status;
888 }
889 }
890 return EFI_NOT_FOUND;
891 }
892
893 /**
894 Get index from supported language codes according to language string.
895
896 This code is used to get corresponding index in supported language codes. It can handle
897 RFC4646 and ISO639 language tags.
898 In ISO639 language tags, take 3-characters as a delimitation to find matched string and calculate the index.
899 In RFC4646 language tags, take semicolon as a delimitation to find matched string and calculate the index.
900
901 For example:
902 SupportedLang = "engfraengfra"
903 Lang = "eng"
904 Iso639Language = TRUE
905 The return value is "0".
906 Another example:
907 SupportedLang = "en;fr;en-US;fr-FR"
908 Lang = "fr-FR"
909 Iso639Language = FALSE
910 The return value is "3".
911
912 @param SupportedLang Platform supported language codes.
913 @param Lang Configured language.
914 @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
915
916 @retval The index of language in the language codes.
917
918 **/
919 UINTN
920 GetIndexFromSupportedLangCodes(
921 IN CHAR8 *SupportedLang,
922 IN CHAR8 *Lang,
923 IN BOOLEAN Iso639Language
924 )
925 {
926 UINTN Index;
927 UINTN CompareLength;
928 UINTN LanguageLength;
929
930 if (Iso639Language) {
931 CompareLength = ISO_639_2_ENTRY_SIZE;
932 for (Index = 0; Index < AsciiStrLen (SupportedLang); Index += CompareLength) {
933 if (AsciiStrnCmp (Lang, SupportedLang + Index, CompareLength) == 0) {
934 //
935 // Successfully find the index of Lang string in SupportedLang string.
936 //
937 Index = Index / CompareLength;
938 return Index;
939 }
940 }
941 ASSERT (FALSE);
942 return 0;
943 } else {
944 //
945 // Compare RFC4646 language code
946 //
947 Index = 0;
948 for (LanguageLength = 0; Lang[LanguageLength] != '\0'; LanguageLength++);
949
950 for (Index = 0; *SupportedLang != '\0'; Index++, SupportedLang += CompareLength) {
951 //
952 // Skip ';' characters in SupportedLang
953 //
954 for (; *SupportedLang != '\0' && *SupportedLang == ';'; SupportedLang++);
955 //
956 // Determine the length of the next language code in SupportedLang
957 //
958 for (CompareLength = 0; SupportedLang[CompareLength] != '\0' && SupportedLang[CompareLength] != ';'; CompareLength++);
959
960 if ((CompareLength == LanguageLength) &&
961 (AsciiStrnCmp (Lang, SupportedLang, CompareLength) == 0)) {
962 //
963 // Successfully find the index of Lang string in SupportedLang string.
964 //
965 return Index;
966 }
967 }
968 ASSERT (FALSE);
969 return 0;
970 }
971 }
972
973 /**
974 Get language string from supported language codes according to index.
975
976 This code is used to get corresponding language strings in supported language codes. It can handle
977 RFC4646 and ISO639 language tags.
978 In ISO639 language tags, take 3-characters as a delimitation. Find language string according to the index.
979 In RFC4646 language tags, take semicolon as a delimitation. Find language string according to the index.
980
981 For example:
982 SupportedLang = "engfraengfra"
983 Index = "1"
984 Iso639Language = TRUE
985 The return value is "fra".
986 Another example:
987 SupportedLang = "en;fr;en-US;fr-FR"
988 Index = "1"
989 Iso639Language = FALSE
990 The return value is "fr".
991
992 @param SupportedLang Platform supported language codes.
993 @param Index The index in supported language codes.
994 @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
995
996 @retval The language string in the language codes.
997
998 **/
999 CHAR8 *
1000 GetLangFromSupportedLangCodes (
1001 IN CHAR8 *SupportedLang,
1002 IN UINTN Index,
1003 IN BOOLEAN Iso639Language
1004 )
1005 {
1006 UINTN SubIndex;
1007 UINTN CompareLength;
1008 CHAR8 *Supported;
1009
1010 SubIndex = 0;
1011 Supported = SupportedLang;
1012 if (Iso639Language) {
1013 //
1014 // According to the index of Lang string in SupportedLang string to get the language.
1015 // This code will be invoked in RUNTIME, therefore there is not a memory allocate/free operation.
1016 // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.
1017 //
1018 CompareLength = ISO_639_2_ENTRY_SIZE;
1019 mVariableModuleGlobal->Lang[CompareLength] = '\0';
1020 return CopyMem (mVariableModuleGlobal->Lang, SupportedLang + Index * CompareLength, CompareLength);
1021
1022 } else {
1023 while (TRUE) {
1024 //
1025 // Take semicolon as delimitation, sequentially traverse supported language codes.
1026 //
1027 for (CompareLength = 0; *Supported != ';' && *Supported != '\0'; CompareLength++) {
1028 Supported++;
1029 }
1030 if ((*Supported == '\0') && (SubIndex != Index)) {
1031 //
1032 // Have completed the traverse, but not find corrsponding string.
1033 // This case is not allowed to happen.
1034 //
1035 ASSERT(FALSE);
1036 return NULL;
1037 }
1038 if (SubIndex == Index) {
1039 //
1040 // According to the index of Lang string in SupportedLang string to get the language.
1041 // As this code will be invoked in RUNTIME, therefore there is not memory allocate/free operation.
1042 // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.
1043 //
1044 mVariableModuleGlobal->PlatformLang[CompareLength] = '\0';
1045 return CopyMem (mVariableModuleGlobal->PlatformLang, Supported - CompareLength, CompareLength);
1046 }
1047 SubIndex++;
1048
1049 //
1050 // Skip ';' characters in Supported
1051 //
1052 for (; *Supported != '\0' && *Supported == ';'; Supported++);
1053 }
1054 }
1055 }
1056
1057 /**
1058 Returns a pointer to an allocated buffer that contains the best matching language
1059 from a set of supported languages.
1060
1061 This function supports both ISO 639-2 and RFC 4646 language codes, but language
1062 code types may not be mixed in a single call to this function. This function
1063 supports a variable argument list that allows the caller to pass in a prioritized
1064 list of language codes to test against all the language codes in SupportedLanguages.
1065
1066 If SupportedLanguages is NULL, then ASSERT().
1067
1068 @param[in] SupportedLanguages A pointer to a Null-terminated ASCII string that
1069 contains a set of language codes in the format
1070 specified by Iso639Language.
1071 @param[in] Iso639Language If TRUE, then all language codes are assumed to be
1072 in ISO 639-2 format. If FALSE, then all language
1073 codes are assumed to be in RFC 4646 language format
1074 @param[in] ... A variable argument list that contains pointers to
1075 Null-terminated ASCII strings that contain one or more
1076 language codes in the format specified by Iso639Language.
1077 The first language code from each of these language
1078 code lists is used to determine if it is an exact or
1079 close match to any of the language codes in
1080 SupportedLanguages. Close matches only apply to RFC 4646
1081 language codes, and the matching algorithm from RFC 4647
1082 is used to determine if a close match is present. If
1083 an exact or close match is found, then the matching
1084 language code from SupportedLanguages is returned. If
1085 no matches are found, then the next variable argument
1086 parameter is evaluated. The variable argument list
1087 is terminated by a NULL.
1088
1089 @retval NULL The best matching language could not be found in SupportedLanguages.
1090 @retval NULL There are not enough resources available to return the best matching
1091 language.
1092 @retval Other A pointer to a Null-terminated ASCII string that is the best matching
1093 language in SupportedLanguages.
1094
1095 **/
1096 CHAR8 *
1097 EFIAPI
1098 VariableGetBestLanguage (
1099 IN CONST CHAR8 *SupportedLanguages,
1100 IN BOOLEAN Iso639Language,
1101 ...
1102 )
1103 {
1104 VA_LIST Args;
1105 CHAR8 *Language;
1106 UINTN CompareLength;
1107 UINTN LanguageLength;
1108 CONST CHAR8 *Supported;
1109 CHAR8 *Buffer;
1110
1111 if (SupportedLanguages == NULL) {
1112 return NULL;
1113 }
1114
1115 VA_START (Args, Iso639Language);
1116 while ((Language = VA_ARG (Args, CHAR8 *)) != NULL) {
1117 //
1118 // Default to ISO 639-2 mode
1119 //
1120 CompareLength = 3;
1121 LanguageLength = MIN (3, AsciiStrLen (Language));
1122
1123 //
1124 // If in RFC 4646 mode, then determine the length of the first RFC 4646 language code in Language
1125 //
1126 if (!Iso639Language) {
1127 for (LanguageLength = 0; Language[LanguageLength] != 0 && Language[LanguageLength] != ';'; LanguageLength++);
1128 }
1129
1130 //
1131 // Trim back the length of Language used until it is empty
1132 //
1133 while (LanguageLength > 0) {
1134 //
1135 // Loop through all language codes in SupportedLanguages
1136 //
1137 for (Supported = SupportedLanguages; *Supported != '\0'; Supported += CompareLength) {
1138 //
1139 // In RFC 4646 mode, then Loop through all language codes in SupportedLanguages
1140 //
1141 if (!Iso639Language) {
1142 //
1143 // Skip ';' characters in Supported
1144 //
1145 for (; *Supported != '\0' && *Supported == ';'; Supported++);
1146 //
1147 // Determine the length of the next language code in Supported
1148 //
1149 for (CompareLength = 0; Supported[CompareLength] != 0 && Supported[CompareLength] != ';'; CompareLength++);
1150 //
1151 // If Language is longer than the Supported, then skip to the next language
1152 //
1153 if (LanguageLength > CompareLength) {
1154 continue;
1155 }
1156 }
1157 //
1158 // See if the first LanguageLength characters in Supported match Language
1159 //
1160 if (AsciiStrnCmp (Supported, Language, LanguageLength) == 0) {
1161 VA_END (Args);
1162
1163 Buffer = Iso639Language ? mVariableModuleGlobal->Lang : mVariableModuleGlobal->PlatformLang;
1164 Buffer[CompareLength] = '\0';
1165 return CopyMem (Buffer, Supported, CompareLength);
1166 }
1167 }
1168
1169 if (Iso639Language) {
1170 //
1171 // If ISO 639 mode, then each language can only be tested once
1172 //
1173 LanguageLength = 0;
1174 } else {
1175 //
1176 // If RFC 4646 mode, then trim Language from the right to the next '-' character
1177 //
1178 for (LanguageLength--; LanguageLength > 0 && Language[LanguageLength] != '-'; LanguageLength--);
1179 }
1180 }
1181 }
1182 VA_END (Args);
1183
1184 //
1185 // No matches were found
1186 //
1187 return NULL;
1188 }
1189
1190 /**
1191 Hook the operations in PlatformLangCodes, LangCodes, PlatformLang and Lang.
1192
1193 When setting Lang/LangCodes, simultaneously update PlatformLang/PlatformLangCodes.
1194
1195 According to UEFI spec, PlatformLangCodes/LangCodes are only set once in firmware initialization,
1196 and are read-only. Therefore, in variable driver, only store the original value for other use.
1197
1198 @param[in] VariableName Name of variable.
1199
1200 @param[in] Data Variable data.
1201
1202 @param[in] DataSize Size of data. 0 means delete.
1203
1204 **/
1205 VOID
1206 AutoUpdateLangVariable (
1207 IN CHAR16 *VariableName,
1208 IN VOID *Data,
1209 IN UINTN DataSize
1210 )
1211 {
1212 EFI_STATUS Status;
1213 CHAR8 *BestPlatformLang;
1214 CHAR8 *BestLang;
1215 UINTN Index;
1216 UINT32 Attributes;
1217 VARIABLE_POINTER_TRACK Variable;
1218 BOOLEAN SetLanguageCodes;
1219
1220 //
1221 // Don't do updates for delete operation
1222 //
1223 if (DataSize == 0) {
1224 return;
1225 }
1226
1227 SetLanguageCodes = FALSE;
1228
1229 if (StrCmp (VariableName, L"PlatformLangCodes") == 0) {
1230 //
1231 // PlatformLangCodes is a volatile variable, so it can not be updated at runtime.
1232 //
1233 if (AtRuntime ()) {
1234 return;
1235 }
1236
1237 SetLanguageCodes = TRUE;
1238
1239 //
1240 // According to UEFI spec, PlatformLangCodes is only set once in firmware initialization, and is read-only
1241 // Therefore, in variable driver, only store the original value for other use.
1242 //
1243 if (mVariableModuleGlobal->PlatformLangCodes != NULL) {
1244 FreePool (mVariableModuleGlobal->PlatformLangCodes);
1245 }
1246 mVariableModuleGlobal->PlatformLangCodes = AllocateRuntimeCopyPool (DataSize, Data);
1247 ASSERT (mVariableModuleGlobal->PlatformLangCodes != NULL);
1248
1249 //
1250 // PlatformLang holds a single language from PlatformLangCodes,
1251 // so the size of PlatformLangCodes is enough for the PlatformLang.
1252 //
1253 if (mVariableModuleGlobal->PlatformLang != NULL) {
1254 FreePool (mVariableModuleGlobal->PlatformLang);
1255 }
1256 mVariableModuleGlobal->PlatformLang = AllocateRuntimePool (DataSize);
1257 ASSERT (mVariableModuleGlobal->PlatformLang != NULL);
1258
1259 } else if (StrCmp (VariableName, L"LangCodes") == 0) {
1260 //
1261 // LangCodes is a volatile variable, so it can not be updated at runtime.
1262 //
1263 if (AtRuntime ()) {
1264 return;
1265 }
1266
1267 SetLanguageCodes = TRUE;
1268
1269 //
1270 // According to UEFI spec, LangCodes is only set once in firmware initialization, and is read-only
1271 // Therefore, in variable driver, only store the original value for other use.
1272 //
1273 if (mVariableModuleGlobal->LangCodes != NULL) {
1274 FreePool (mVariableModuleGlobal->LangCodes);
1275 }
1276 mVariableModuleGlobal->LangCodes = AllocateRuntimeCopyPool (DataSize, Data);
1277 ASSERT (mVariableModuleGlobal->LangCodes != NULL);
1278 }
1279
1280 if (SetLanguageCodes
1281 && (mVariableModuleGlobal->PlatformLangCodes != NULL)
1282 && (mVariableModuleGlobal->LangCodes != NULL)) {
1283 //
1284 // Update Lang if PlatformLang is already set
1285 // Update PlatformLang if Lang is already set
1286 //
1287 Status = FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1288 if (!EFI_ERROR (Status)) {
1289 //
1290 // Update Lang
1291 //
1292 VariableName = L"PlatformLang";
1293 Data = GetVariableDataPtr (Variable.CurrPtr);
1294 DataSize = Variable.CurrPtr->DataSize;
1295 } else {
1296 Status = FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1297 if (!EFI_ERROR (Status)) {
1298 //
1299 // Update PlatformLang
1300 //
1301 VariableName = L"Lang";
1302 Data = GetVariableDataPtr (Variable.CurrPtr);
1303 DataSize = Variable.CurrPtr->DataSize;
1304 } else {
1305 //
1306 // Neither PlatformLang nor Lang is set, directly return
1307 //
1308 return;
1309 }
1310 }
1311 }
1312
1313 //
1314 // According to UEFI spec, "Lang" and "PlatformLang" is NV|BS|RT attributions.
1315 //
1316 Attributes = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS;
1317
1318 if (StrCmp (VariableName, L"PlatformLang") == 0) {
1319 //
1320 // Update Lang when PlatformLangCodes/LangCodes were set.
1321 //
1322 if ((mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) {
1323 //
1324 // When setting PlatformLang, firstly get most matched language string from supported language codes.
1325 //
1326 BestPlatformLang = VariableGetBestLanguage (mVariableModuleGlobal->PlatformLangCodes, FALSE, Data, NULL);
1327 if (BestPlatformLang != NULL) {
1328 //
1329 // Get the corresponding index in language codes.
1330 //
1331 Index = GetIndexFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, BestPlatformLang, FALSE);
1332
1333 //
1334 // Get the corresponding ISO639 language tag according to RFC4646 language tag.
1335 //
1336 BestLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, Index, TRUE);
1337
1338 //
1339 // Successfully convert PlatformLang to Lang, and set the BestLang value into Lang variable simultaneously.
1340 //
1341 FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1342
1343 Status = UpdateVariable (L"Lang", &gEfiGlobalVariableGuid, BestLang,
1344 ISO_639_2_ENTRY_SIZE + 1, Attributes, 0, 0, &Variable, NULL);
1345
1346 DEBUG ((EFI_D_INFO, "Variable Driver Auto Update PlatformLang, PlatformLang:%a, Lang:%a\n", BestPlatformLang, BestLang));
1347
1348 ASSERT_EFI_ERROR(Status);
1349 }
1350 }
1351
1352 } else if (StrCmp (VariableName, L"Lang") == 0) {
1353 //
1354 // Update PlatformLang when PlatformLangCodes/LangCodes were set.
1355 //
1356 if ((mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) {
1357 //
1358 // When setting Lang, firstly get most matched language string from supported language codes.
1359 //
1360 BestLang = VariableGetBestLanguage (mVariableModuleGlobal->LangCodes, TRUE, Data, NULL);
1361 if (BestLang != NULL) {
1362 //
1363 // Get the corresponding index in language codes.
1364 //
1365 Index = GetIndexFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, BestLang, TRUE);
1366
1367 //
1368 // Get the corresponding RFC4646 language tag according to ISO639 language tag.
1369 //
1370 BestPlatformLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, Index, FALSE);
1371
1372 //
1373 // Successfully convert Lang to PlatformLang, and set the BestPlatformLang value into PlatformLang variable simultaneously.
1374 //
1375 FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1376
1377 Status = UpdateVariable (L"PlatformLang", &gEfiGlobalVariableGuid, BestPlatformLang,
1378 AsciiStrSize (BestPlatformLang), Attributes, 0, 0, &Variable, NULL);
1379
1380 DEBUG ((EFI_D_INFO, "Variable Driver Auto Update Lang, Lang:%a, PlatformLang:%a\n", BestLang, BestPlatformLang));
1381 ASSERT_EFI_ERROR (Status);
1382 }
1383 }
1384 }
1385 }
1386
1387 /**
1388 Update the variable region with Variable information. If EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is set,
1389 index of associated public key is needed.
1390
1391 @param[in] VariableName Name of variable.
1392 @param[in] VendorGuid Guid of variable.
1393 @param[in] Data Variable data.
1394 @param[in] DataSize Size of data. 0 means delete.
1395 @param[in] Attributes Attributes of the variable.
1396 @param[in] KeyIndex Index of associated public key.
1397 @param[in] MonotonicCount Value of associated monotonic count.
1398 @param[in] CacheVariable The variable information which is used to keep track of variable usage.
1399 @param[in] TimeStamp Value of associated TimeStamp.
1400
1401 @retval EFI_SUCCESS The update operation is success.
1402 @retval EFI_OUT_OF_RESOURCES Variable region is full, can not write other data into this region.
1403
1404 **/
1405 EFI_STATUS
1406 UpdateVariable (
1407 IN CHAR16 *VariableName,
1408 IN EFI_GUID *VendorGuid,
1409 IN VOID *Data,
1410 IN UINTN DataSize,
1411 IN UINT32 Attributes OPTIONAL,
1412 IN UINT32 KeyIndex OPTIONAL,
1413 IN UINT64 MonotonicCount OPTIONAL,
1414 IN VARIABLE_POINTER_TRACK *CacheVariable,
1415 IN EFI_TIME *TimeStamp OPTIONAL
1416 )
1417 {
1418 EFI_STATUS Status;
1419 VARIABLE_HEADER *NextVariable;
1420 UINTN ScratchSize;
1421 UINTN ScratchDataSize;
1422 UINTN NonVolatileVarableStoreSize;
1423 UINTN VarNameOffset;
1424 UINTN VarDataOffset;
1425 UINTN VarNameSize;
1426 UINTN VarSize;
1427 BOOLEAN Volatile;
1428 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
1429 UINT8 State;
1430 BOOLEAN Reclaimed;
1431 VARIABLE_POINTER_TRACK *Variable;
1432 VARIABLE_POINTER_TRACK NvVariable;
1433 VARIABLE_STORE_HEADER *VariableStoreHeader;
1434 UINTN CacheOffset;
1435 UINTN BufSize;
1436 UINTN DataOffset;
1437 UINTN RevBufSize;
1438
1439 if (mVariableModuleGlobal->FvbInstance == NULL) {
1440 //
1441 // The FVB protocol is not installed, so the EFI_VARIABLE_WRITE_ARCH_PROTOCOL is not installed.
1442 //
1443 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
1444 //
1445 // Trying to update NV variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
1446 //
1447 return EFI_NOT_AVAILABLE_YET;
1448 } else if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) {
1449 //
1450 // Trying to update volatile authenticated variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
1451 // The authenticated variable perhaps is not initialized, just return here.
1452 //
1453 return EFI_NOT_AVAILABLE_YET;
1454 }
1455 }
1456
1457 if ((CacheVariable->CurrPtr == NULL) || CacheVariable->Volatile) {
1458 Variable = CacheVariable;
1459 } else {
1460 //
1461 // Update/Delete existing NV variable.
1462 // CacheVariable points to the variable in the memory copy of Flash area
1463 // Now let Variable points to the same variable in Flash area.
1464 //
1465 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);
1466 Variable = &NvVariable;
1467 Variable->StartPtr = GetStartPointer (VariableStoreHeader);
1468 Variable->EndPtr = GetEndPointer (VariableStoreHeader);
1469 Variable->CurrPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr));
1470 Variable->Volatile = FALSE;
1471 }
1472
1473 Fvb = mVariableModuleGlobal->FvbInstance;
1474 Reclaimed = FALSE;
1475
1476 //
1477 // Tricky part: Use scratch data area at the end of volatile variable store
1478 // as a temporary storage.
1479 //
1480 NextVariable = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase));
1481 ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));
1482 ScratchDataSize = ScratchSize - sizeof (VARIABLE_HEADER) - StrSize (VariableName) - GET_PAD_SIZE (StrSize (VariableName));
1483
1484 if (Variable->CurrPtr != NULL) {
1485 //
1486 // Update/Delete existing variable.
1487 //
1488 if (AtRuntime ()) {
1489 //
1490 // If AtRuntime and the variable is Volatile and Runtime Access,
1491 // the volatile is ReadOnly, and SetVariable should be aborted and
1492 // return EFI_WRITE_PROTECTED.
1493 //
1494 if (Variable->Volatile) {
1495 Status = EFI_WRITE_PROTECTED;
1496 goto Done;
1497 }
1498 //
1499 // Only variable that have NV attributes can be updated/deleted in Runtime.
1500 //
1501 if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
1502 Status = EFI_INVALID_PARAMETER;
1503 goto Done;
1504 }
1505
1506 //
1507 // Only variable that have RT attributes can be updated/deleted in Runtime.
1508 //
1509 if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) {
1510 Status = EFI_INVALID_PARAMETER;
1511 goto Done;
1512 }
1513 }
1514
1515 //
1516 // Setting a data variable with no access, or zero DataSize attributes
1517 // causes it to be deleted.
1518 // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will
1519 // not delete the variable.
1520 //
1521 if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0))|| ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) {
1522 State = Variable->CurrPtr->State;
1523 State &= VAR_DELETED;
1524
1525 Status = UpdateVariableStore (
1526 &mVariableModuleGlobal->VariableGlobal,
1527 Variable->Volatile,
1528 FALSE,
1529 Fvb,
1530 (UINTN) &Variable->CurrPtr->State,
1531 sizeof (UINT8),
1532 &State
1533 );
1534 if (!EFI_ERROR (Status)) {
1535 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE);
1536 if (!Variable->Volatile) {
1537 CacheVariable->CurrPtr->State = State;
1538 FlushHobVariableToFlash (VariableName, VendorGuid);
1539 }
1540 }
1541 goto Done;
1542 }
1543 //
1544 // If the variable is marked valid, and the same data has been passed in,
1545 // then return to the caller immediately.
1546 //
1547 if (DataSizeOfVariable (Variable->CurrPtr) == DataSize &&
1548 (CompareMem (Data, GetVariableDataPtr (Variable->CurrPtr), DataSize) == 0) &&
1549 ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) &&
1550 (TimeStamp == NULL)) {
1551 //
1552 // Variable content unchanged and no need to update timestamp, just return.
1553 //
1554 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);
1555 Status = EFI_SUCCESS;
1556 goto Done;
1557 } else if ((Variable->CurrPtr->State == VAR_ADDED) ||
1558 (Variable->CurrPtr->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION))) {
1559
1560 //
1561 // EFI_VARIABLE_APPEND_WRITE attribute only effects for existing variable
1562 //
1563 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) {
1564 //
1565 // Cache the previous variable data into StorageArea.
1566 //
1567 DataOffset = sizeof (VARIABLE_HEADER) + Variable->CurrPtr->NameSize + GET_PAD_SIZE (Variable->CurrPtr->NameSize);
1568 CopyMem (mStorageArea, (UINT8*)((UINTN) Variable->CurrPtr + DataOffset), Variable->CurrPtr->DataSize);
1569
1570 if (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) ||
1571 (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0))) {
1572 //
1573 // For variables with the GUID EFI_IMAGE_SECURITY_DATABASE_GUID (i.e. where the data
1574 // buffer is formatted as EFI_SIGNATURE_LIST), the driver shall not perform an append of
1575 // EFI_SIGNATURE_DATA values that are already part of the existing variable value.
1576 //
1577 BufSize = AppendSignatureList (mStorageArea, Variable->CurrPtr->DataSize, Data, DataSize);
1578 if (BufSize == Variable->CurrPtr->DataSize) {
1579 if ((TimeStamp == NULL) || CompareTimeStamp (TimeStamp, &Variable->CurrPtr->TimeStamp)) {
1580 //
1581 // New EFI_SIGNATURE_DATA is not found and timestamp is not later
1582 // than current timestamp, return EFI_SUCCESS directly.
1583 //
1584 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);
1585 Status = EFI_SUCCESS;
1586 goto Done;
1587 }
1588 }
1589 } else {
1590 //
1591 // For other Variables, append the new data to the end of previous data.
1592 //
1593 CopyMem ((UINT8*)((UINTN) mStorageArea + Variable->CurrPtr->DataSize), Data, DataSize);
1594 BufSize = Variable->CurrPtr->DataSize + DataSize;
1595 }
1596
1597 RevBufSize = MIN (PcdGet32 (PcdMaxVariableSize), ScratchDataSize);
1598 if (BufSize > RevBufSize) {
1599 //
1600 // If variable size (previous + current) is bigger than reserved buffer in runtime,
1601 // return EFI_OUT_OF_RESOURCES.
1602 //
1603 return EFI_OUT_OF_RESOURCES;
1604 }
1605
1606 //
1607 // Override Data and DataSize which are used for combined data area including previous and new data.
1608 //
1609 Data = mStorageArea;
1610 DataSize = BufSize;
1611 }
1612
1613 //
1614 // Mark the old variable as in delete transition.
1615 //
1616 State = Variable->CurrPtr->State;
1617 State &= VAR_IN_DELETED_TRANSITION;
1618
1619 Status = UpdateVariableStore (
1620 &mVariableModuleGlobal->VariableGlobal,
1621 Variable->Volatile,
1622 FALSE,
1623 Fvb,
1624 (UINTN) &Variable->CurrPtr->State,
1625 sizeof (UINT8),
1626 &State
1627 );
1628 if (EFI_ERROR (Status)) {
1629 goto Done;
1630 }
1631 if (!Variable->Volatile) {
1632 CacheVariable->CurrPtr->State = State;
1633 }
1634 }
1635 } else {
1636 //
1637 // Not found existing variable. Create a new variable.
1638 //
1639
1640 if ((DataSize == 0) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0)) {
1641 Status = EFI_SUCCESS;
1642 goto Done;
1643 }
1644
1645 //
1646 // Make sure we are trying to create a new variable.
1647 // Setting a data variable with zero DataSize or no access attributes means to delete it.
1648 //
1649 if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) {
1650 Status = EFI_NOT_FOUND;
1651 goto Done;
1652 }
1653
1654 //
1655 // Only variable have NV|RT attribute can be created in Runtime.
1656 //
1657 if (AtRuntime () &&
1658 (((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0))) {
1659 Status = EFI_INVALID_PARAMETER;
1660 goto Done;
1661 }
1662 }
1663
1664 //
1665 // Function part - create a new variable and copy the data.
1666 // Both update a variable and create a variable will come here.
1667
1668 SetMem (NextVariable, ScratchSize, 0xff);
1669
1670 NextVariable->StartId = VARIABLE_DATA;
1671 //
1672 // NextVariable->State = VAR_ADDED;
1673 //
1674 NextVariable->Reserved = 0;
1675 NextVariable->PubKeyIndex = KeyIndex;
1676 NextVariable->MonotonicCount = MonotonicCount;
1677 ZeroMem (&NextVariable->TimeStamp, sizeof (EFI_TIME));
1678
1679 if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&
1680 (TimeStamp != NULL)) {
1681 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) {
1682 CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
1683 } else {
1684 //
1685 // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only
1686 // when the new TimeStamp value is later than the current timestamp associated
1687 // with the variable, we need associate the new timestamp with the updated value.
1688 //
1689 if (Variable->CurrPtr != NULL) {
1690 if (CompareTimeStamp (&Variable->CurrPtr->TimeStamp, TimeStamp)) {
1691 CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
1692 }
1693 }
1694 }
1695 }
1696
1697 //
1698 // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned
1699 // Attributes bitmask parameter of a GetVariable() call.
1700 //
1701 NextVariable->Attributes = Attributes & (~EFI_VARIABLE_APPEND_WRITE);
1702
1703 VarNameOffset = sizeof (VARIABLE_HEADER);
1704 VarNameSize = StrSize (VariableName);
1705 CopyMem (
1706 (UINT8 *) ((UINTN) NextVariable + VarNameOffset),
1707 VariableName,
1708 VarNameSize
1709 );
1710 VarDataOffset = VarNameOffset + VarNameSize + GET_PAD_SIZE (VarNameSize);
1711 CopyMem (
1712 (UINT8 *) ((UINTN) NextVariable + VarDataOffset),
1713 Data,
1714 DataSize
1715 );
1716 CopyMem (&NextVariable->VendorGuid, VendorGuid, sizeof (EFI_GUID));
1717 //
1718 // There will be pad bytes after Data, the NextVariable->NameSize and
1719 // NextVariable->DataSize should not include pad size so that variable
1720 // service can get actual size in GetVariable.
1721 //
1722 NextVariable->NameSize = (UINT32)VarNameSize;
1723 NextVariable->DataSize = (UINT32)DataSize;
1724
1725 //
1726 // The actual size of the variable that stores in storage should
1727 // include pad size.
1728 //
1729 VarSize = VarDataOffset + DataSize + GET_PAD_SIZE (DataSize);
1730 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
1731 //
1732 // Create a nonvolatile variable.
1733 //
1734 Volatile = FALSE;
1735 NonVolatileVarableStoreSize = ((VARIABLE_STORE_HEADER *)(UINTN)(mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase))->Size;
1736 if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)
1737 && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))
1738 || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0)
1739 && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {
1740 if (AtRuntime ()) {
1741 Status = EFI_OUT_OF_RESOURCES;
1742 goto Done;
1743 }
1744 //
1745 // Perform garbage collection & reclaim operation.
1746 //
1747 Status = Reclaim (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
1748 &mVariableModuleGlobal->NonVolatileLastVariableOffset, FALSE, Variable->CurrPtr, FALSE);
1749 if (EFI_ERROR (Status)) {
1750 goto Done;
1751 }
1752 //
1753 // If still no enough space, return out of resources.
1754 //
1755 if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)
1756 && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))
1757 || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0)
1758 && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {
1759 Status = EFI_OUT_OF_RESOURCES;
1760 goto Done;
1761 }
1762 Reclaimed = TRUE;
1763 }
1764 //
1765 // Four steps
1766 // 1. Write variable header
1767 // 2. Set variable state to header valid
1768 // 3. Write variable data
1769 // 4. Set variable state to valid
1770 //
1771 //
1772 // Step 1:
1773 //
1774 CacheOffset = mVariableModuleGlobal->NonVolatileLastVariableOffset;
1775 Status = UpdateVariableStore (
1776 &mVariableModuleGlobal->VariableGlobal,
1777 FALSE,
1778 TRUE,
1779 Fvb,
1780 mVariableModuleGlobal->NonVolatileLastVariableOffset,
1781 sizeof (VARIABLE_HEADER),
1782 (UINT8 *) NextVariable
1783 );
1784
1785 if (EFI_ERROR (Status)) {
1786 goto Done;
1787 }
1788
1789 //
1790 // Step 2:
1791 //
1792 NextVariable->State = VAR_HEADER_VALID_ONLY;
1793 Status = UpdateVariableStore (
1794 &mVariableModuleGlobal->VariableGlobal,
1795 FALSE,
1796 TRUE,
1797 Fvb,
1798 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
1799 sizeof (UINT8),
1800 &NextVariable->State
1801 );
1802
1803 if (EFI_ERROR (Status)) {
1804 goto Done;
1805 }
1806 //
1807 // Step 3:
1808 //
1809 Status = UpdateVariableStore (
1810 &mVariableModuleGlobal->VariableGlobal,
1811 FALSE,
1812 TRUE,
1813 Fvb,
1814 mVariableModuleGlobal->NonVolatileLastVariableOffset + sizeof (VARIABLE_HEADER),
1815 (UINT32) VarSize - sizeof (VARIABLE_HEADER),
1816 (UINT8 *) NextVariable + sizeof (VARIABLE_HEADER)
1817 );
1818
1819 if (EFI_ERROR (Status)) {
1820 goto Done;
1821 }
1822 //
1823 // Step 4:
1824 //
1825 NextVariable->State = VAR_ADDED;
1826 Status = UpdateVariableStore (
1827 &mVariableModuleGlobal->VariableGlobal,
1828 FALSE,
1829 TRUE,
1830 Fvb,
1831 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
1832 sizeof (UINT8),
1833 &NextVariable->State
1834 );
1835
1836 if (EFI_ERROR (Status)) {
1837 goto Done;
1838 }
1839
1840 mVariableModuleGlobal->NonVolatileLastVariableOffset += HEADER_ALIGN (VarSize);
1841
1842 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
1843 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VarSize);
1844 } else {
1845 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VarSize);
1846 }
1847 //
1848 // update the memory copy of Flash region.
1849 //
1850 CopyMem ((UINT8 *)mNvVariableCache + CacheOffset, (UINT8 *)NextVariable, VarSize);
1851 } else {
1852 //
1853 // Create a volatile variable.
1854 //
1855 Volatile = TRUE;
1856
1857 if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >
1858 ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size) {
1859 //
1860 // Perform garbage collection & reclaim operation.
1861 //
1862 Status = Reclaim (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,
1863 &mVariableModuleGlobal->VolatileLastVariableOffset, TRUE, Variable->CurrPtr, FALSE);
1864 if (EFI_ERROR (Status)) {
1865 goto Done;
1866 }
1867 //
1868 // If still no enough space, return out of resources.
1869 //
1870 if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >
1871 ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size
1872 ) {
1873 Status = EFI_OUT_OF_RESOURCES;
1874 goto Done;
1875 }
1876 Reclaimed = TRUE;
1877 }
1878
1879 NextVariable->State = VAR_ADDED;
1880 Status = UpdateVariableStore (
1881 &mVariableModuleGlobal->VariableGlobal,
1882 TRUE,
1883 TRUE,
1884 Fvb,
1885 mVariableModuleGlobal->VolatileLastVariableOffset,
1886 (UINT32) VarSize,
1887 (UINT8 *) NextVariable
1888 );
1889
1890 if (EFI_ERROR (Status)) {
1891 goto Done;
1892 }
1893
1894 mVariableModuleGlobal->VolatileLastVariableOffset += HEADER_ALIGN (VarSize);
1895 }
1896
1897 //
1898 // Mark the old variable as deleted.
1899 //
1900 if (!Reclaimed && !EFI_ERROR (Status) && Variable->CurrPtr != NULL) {
1901 State = Variable->CurrPtr->State;
1902 State &= VAR_DELETED;
1903
1904 Status = UpdateVariableStore (
1905 &mVariableModuleGlobal->VariableGlobal,
1906 Variable->Volatile,
1907 FALSE,
1908 Fvb,
1909 (UINTN) &Variable->CurrPtr->State,
1910 sizeof (UINT8),
1911 &State
1912 );
1913 if (!EFI_ERROR (Status) && !Variable->Volatile) {
1914 CacheVariable->CurrPtr->State = State;
1915 }
1916 }
1917
1918 if (!EFI_ERROR (Status)) {
1919 UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);
1920 if (!Volatile) {
1921 FlushHobVariableToFlash (VariableName, VendorGuid);
1922 }
1923 }
1924
1925 Done:
1926 return Status;
1927 }
1928
1929 /**
1930 Check if a Unicode character is a hexadecimal character.
1931
1932 This function checks if a Unicode character is a
1933 hexadecimal character. The valid hexadecimal character is
1934 L'0' to L'9', L'a' to L'f', or L'A' to L'F'.
1935
1936
1937 @param Char The character to check against.
1938
1939 @retval TRUE If the Char is a hexadecmial character.
1940 @retval FALSE If the Char is not a hexadecmial character.
1941
1942 **/
1943 BOOLEAN
1944 EFIAPI
1945 IsHexaDecimalDigitCharacter (
1946 IN CHAR16 Char
1947 )
1948 {
1949 return (BOOLEAN) ((Char >= L'0' && Char <= L'9') || (Char >= L'A' && Char <= L'F') || (Char >= L'a' && Char <= L'f'));
1950 }
1951
1952 /**
1953
1954 This code checks if variable is hardware error record variable or not.
1955
1956 According to UEFI spec, hardware error record variable should use the EFI_HARDWARE_ERROR_VARIABLE VendorGuid
1957 and have the L"HwErrRec####" name convention, #### is a printed hex value and no 0x or h is included in the hex value.
1958
1959 @param VariableName Pointer to variable name.
1960 @param VendorGuid Variable Vendor Guid.
1961
1962 @retval TRUE Variable is hardware error record variable.
1963 @retval FALSE Variable is not hardware error record variable.
1964
1965 **/
1966 BOOLEAN
1967 EFIAPI
1968 IsHwErrRecVariable (
1969 IN CHAR16 *VariableName,
1970 IN EFI_GUID *VendorGuid
1971 )
1972 {
1973 if (!CompareGuid (VendorGuid, &gEfiHardwareErrorVariableGuid) ||
1974 (StrLen (VariableName) != StrLen (L"HwErrRec####")) ||
1975 (StrnCmp(VariableName, L"HwErrRec", StrLen (L"HwErrRec")) != 0) ||
1976 !IsHexaDecimalDigitCharacter (VariableName[0x8]) ||
1977 !IsHexaDecimalDigitCharacter (VariableName[0x9]) ||
1978 !IsHexaDecimalDigitCharacter (VariableName[0xA]) ||
1979 !IsHexaDecimalDigitCharacter (VariableName[0xB])) {
1980 return FALSE;
1981 }
1982
1983 return TRUE;
1984 }
1985
1986 /**
1987 This code checks if variable should be treated as read-only variable.
1988
1989 @param[in] VariableName Name of the Variable.
1990 @param[in] VendorGuid GUID of the Variable.
1991
1992 @retval TRUE This variable is read-only variable.
1993 @retval FALSE This variable is NOT read-only variable.
1994
1995 **/
1996 BOOLEAN
1997 IsReadOnlyVariable (
1998 IN CHAR16 *VariableName,
1999 IN EFI_GUID *VendorGuid
2000 )
2001 {
2002 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid)) {
2003 if ((StrCmp (VariableName, EFI_SETUP_MODE_NAME) == 0) ||
2004 (StrCmp (VariableName, EFI_SIGNATURE_SUPPORT_NAME) == 0) ||
2005 (StrCmp (VariableName, EFI_SECURE_BOOT_MODE_NAME) == 0)) {
2006 return TRUE;
2007 }
2008 }
2009
2010 return FALSE;
2011 }
2012
2013 /**
2014
2015 This code finds variable in storage blocks (Volatile or Non-Volatile).
2016
2017 Caution: This function may receive untrusted input.
2018 This function may be invoked in SMM mode, and datasize is external input.
2019 This function will do basic validation, before parse the data.
2020
2021 @param VariableName Name of Variable to be found.
2022 @param VendorGuid Variable vendor GUID.
2023 @param Attributes Attribute value of the variable found.
2024 @param DataSize Size of Data found. If size is less than the
2025 data, this value contains the required size.
2026 @param Data Data pointer.
2027
2028 @return EFI_INVALID_PARAMETER Invalid parameter.
2029 @return EFI_SUCCESS Find the specified variable.
2030 @return EFI_NOT_FOUND Not found.
2031 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2032
2033 **/
2034 EFI_STATUS
2035 EFIAPI
2036 VariableServiceGetVariable (
2037 IN CHAR16 *VariableName,
2038 IN EFI_GUID *VendorGuid,
2039 OUT UINT32 *Attributes OPTIONAL,
2040 IN OUT UINTN *DataSize,
2041 OUT VOID *Data
2042 )
2043 {
2044 EFI_STATUS Status;
2045 VARIABLE_POINTER_TRACK Variable;
2046 UINTN VarDataSize;
2047
2048 if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {
2049 return EFI_INVALID_PARAMETER;
2050 }
2051
2052 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2053
2054 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2055 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2056 goto Done;
2057 }
2058
2059 //
2060 // Get data size
2061 //
2062 VarDataSize = DataSizeOfVariable (Variable.CurrPtr);
2063 ASSERT (VarDataSize != 0);
2064
2065 if (*DataSize >= VarDataSize) {
2066 if (Data == NULL) {
2067 Status = EFI_INVALID_PARAMETER;
2068 goto Done;
2069 }
2070
2071 CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr), VarDataSize);
2072 if (Attributes != NULL) {
2073 *Attributes = Variable.CurrPtr->Attributes;
2074 }
2075
2076 *DataSize = VarDataSize;
2077 UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);
2078
2079 Status = EFI_SUCCESS;
2080 goto Done;
2081 } else {
2082 *DataSize = VarDataSize;
2083 Status = EFI_BUFFER_TOO_SMALL;
2084 goto Done;
2085 }
2086
2087 Done:
2088 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2089 return Status;
2090 }
2091
2092
2093
2094 /**
2095
2096 This code Finds the Next available variable.
2097
2098 Caution: This function may receive untrusted input.
2099 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2100
2101 @param VariableNameSize Size of the variable name.
2102 @param VariableName Pointer to variable name.
2103 @param VendorGuid Variable Vendor Guid.
2104
2105 @return EFI_INVALID_PARAMETER Invalid parameter.
2106 @return EFI_SUCCESS Find the specified variable.
2107 @return EFI_NOT_FOUND Not found.
2108 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2109
2110 **/
2111 EFI_STATUS
2112 EFIAPI
2113 VariableServiceGetNextVariableName (
2114 IN OUT UINTN *VariableNameSize,
2115 IN OUT CHAR16 *VariableName,
2116 IN OUT EFI_GUID *VendorGuid
2117 )
2118 {
2119 VARIABLE_STORE_TYPE Type;
2120 VARIABLE_POINTER_TRACK Variable;
2121 VARIABLE_POINTER_TRACK VariableInHob;
2122 UINTN VarNameSize;
2123 EFI_STATUS Status;
2124 VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
2125
2126 if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
2127 return EFI_INVALID_PARAMETER;
2128 }
2129
2130 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2131
2132 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2133 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2134 goto Done;
2135 }
2136
2137 if (VariableName[0] != 0) {
2138 //
2139 // If variable name is not NULL, get next variable.
2140 //
2141 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2142 }
2143
2144 //
2145 // 0: Volatile, 1: HOB, 2: Non-Volatile.
2146 // The index and attributes mapping must be kept in this order as FindVariable
2147 // makes use of this mapping to implement search algorithm.
2148 //
2149 VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
2150 VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
2151 VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
2152
2153 while (TRUE) {
2154 //
2155 // Switch from Volatile to HOB, to Non-Volatile.
2156 //
2157 while ((Variable.CurrPtr >= Variable.EndPtr) ||
2158 (Variable.CurrPtr == NULL) ||
2159 !IsValidVariableHeader (Variable.CurrPtr)
2160 ) {
2161 //
2162 // Find current storage index
2163 //
2164 for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
2165 if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
2166 break;
2167 }
2168 }
2169 ASSERT (Type < VariableStoreTypeMax);
2170 //
2171 // Switch to next storage
2172 //
2173 for (Type++; Type < VariableStoreTypeMax; Type++) {
2174 if (VariableStoreHeader[Type] != NULL) {
2175 break;
2176 }
2177 }
2178 //
2179 // Capture the case that
2180 // 1. current storage is the last one, or
2181 // 2. no further storage
2182 //
2183 if (Type == VariableStoreTypeMax) {
2184 Status = EFI_NOT_FOUND;
2185 goto Done;
2186 }
2187 Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);
2188 Variable.EndPtr = GetEndPointer (VariableStoreHeader[Type]);
2189 Variable.CurrPtr = Variable.StartPtr;
2190 }
2191
2192 //
2193 // Variable is found
2194 //
2195 if (Variable.CurrPtr->State == VAR_ADDED) {
2196 if ((AtRuntime () && ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) == 0) {
2197
2198 //
2199 // Don't return NV variable when HOB overrides it
2200 //
2201 if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&
2202 (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))
2203 ) {
2204 VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);
2205 VariableInHob.EndPtr = GetEndPointer (VariableStoreHeader[VariableStoreTypeHob]);
2206 Status = FindVariableEx (
2207 GetVariableNamePtr (Variable.CurrPtr),
2208 &Variable.CurrPtr->VendorGuid,
2209 FALSE,
2210 &VariableInHob
2211 );
2212 if (!EFI_ERROR (Status)) {
2213 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2214 continue;
2215 }
2216 }
2217
2218 VarNameSize = NameSizeOfVariable (Variable.CurrPtr);
2219 ASSERT (VarNameSize != 0);
2220
2221 if (VarNameSize <= *VariableNameSize) {
2222 CopyMem (VariableName, GetVariableNamePtr (Variable.CurrPtr), VarNameSize);
2223 CopyMem (VendorGuid, &Variable.CurrPtr->VendorGuid, sizeof (EFI_GUID));
2224 Status = EFI_SUCCESS;
2225 } else {
2226 Status = EFI_BUFFER_TOO_SMALL;
2227 }
2228
2229 *VariableNameSize = VarNameSize;
2230 goto Done;
2231 }
2232 }
2233
2234 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2235 }
2236
2237 Done:
2238 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2239 return Status;
2240 }
2241
2242 /**
2243
2244 This code sets variable in storage blocks (Volatile or Non-Volatile).
2245
2246 Caution: This function may receive untrusted input.
2247 This function may be invoked in SMM mode, and datasize and data are external input.
2248 This function will do basic validation, before parse the data.
2249 This function will parse the authentication carefully to avoid security issues, like
2250 buffer overflow, integer overflow.
2251 This function will check attribute carefully to avoid authentication bypass.
2252
2253 @param VariableName Name of Variable to be found.
2254 @param VendorGuid Variable vendor GUID.
2255 @param Attributes Attribute value of the variable found
2256 @param DataSize Size of Data found. If size is less than the
2257 data, this value contains the required size.
2258 @param Data Data pointer.
2259
2260 @return EFI_INVALID_PARAMETER Invalid parameter.
2261 @return EFI_SUCCESS Set successfully.
2262 @return EFI_OUT_OF_RESOURCES Resource not enough to set variable.
2263 @return EFI_NOT_FOUND Not found.
2264 @return EFI_WRITE_PROTECTED Variable is read-only.
2265
2266 **/
2267 EFI_STATUS
2268 EFIAPI
2269 VariableServiceSetVariable (
2270 IN CHAR16 *VariableName,
2271 IN EFI_GUID *VendorGuid,
2272 IN UINT32 Attributes,
2273 IN UINTN DataSize,
2274 IN VOID *Data
2275 )
2276 {
2277 VARIABLE_POINTER_TRACK Variable;
2278 EFI_STATUS Status;
2279 VARIABLE_HEADER *NextVariable;
2280 EFI_PHYSICAL_ADDRESS Point;
2281 UINTN PayloadSize;
2282
2283 //
2284 // Check input parameters.
2285 //
2286 if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {
2287 return EFI_INVALID_PARAMETER;
2288 }
2289
2290 if (IsReadOnlyVariable (VariableName, VendorGuid)) {
2291 return EFI_WRITE_PROTECTED;
2292 }
2293
2294 if (DataSize != 0 && Data == NULL) {
2295 return EFI_INVALID_PARAMETER;
2296 }
2297
2298 //
2299 // Check for reserverd bit in variable attribute.
2300 //
2301 if ((Attributes & (~EFI_VARIABLE_ATTRIBUTES_MASK)) != 0) {
2302 return EFI_INVALID_PARAMETER;
2303 }
2304
2305 //
2306 // Make sure if runtime bit is set, boot service bit is set also.
2307 //
2308 if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
2309 return EFI_INVALID_PARAMETER;
2310 }
2311
2312 //
2313 // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute
2314 // cannot be set both.
2315 //
2316 if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)
2317 && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {
2318 return EFI_INVALID_PARAMETER;
2319 }
2320
2321 if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {
2322 if (DataSize < AUTHINFO_SIZE) {
2323 //
2324 // Try to write Authenticated Variable without AuthInfo.
2325 //
2326 return EFI_SECURITY_VIOLATION;
2327 }
2328 PayloadSize = DataSize - AUTHINFO_SIZE;
2329 } else if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {
2330 //
2331 // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor.
2332 //
2333 if (DataSize < OFFSET_OF_AUTHINFO2_CERT_DATA ||
2334 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength > DataSize - (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) ||
2335 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength < OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) {
2336 return EFI_SECURITY_VIOLATION;
2337 }
2338 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
2339 } else {
2340 PayloadSize = DataSize;
2341 }
2342
2343 //
2344 // The size of the VariableName, including the Unicode Null in bytes plus
2345 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)
2346 // bytes for HwErrRec, and PcdGet32 (PcdMaxVariableSize) bytes for the others.
2347 //
2348 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2349 if ((PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize)) ||
2350 (sizeof (VARIABLE_HEADER) + StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize))) {
2351 return EFI_INVALID_PARAMETER;
2352 }
2353 if (!IsHwErrRecVariable(VariableName, VendorGuid)) {
2354 return EFI_INVALID_PARAMETER;
2355 }
2356 } else {
2357 //
2358 // The size of the VariableName, including the Unicode Null in bytes plus
2359 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxVariableSize) bytes.
2360 //
2361 if ((PayloadSize > PcdGet32 (PcdMaxVariableSize)) ||
2362 (sizeof (VARIABLE_HEADER) + StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxVariableSize))) {
2363 return EFI_INVALID_PARAMETER;
2364 }
2365 }
2366
2367 if (AtRuntime ()) {
2368 //
2369 // HwErrRecSupport Global Variable identifies the level of hardware error record persistence
2370 // support implemented by the platform. This variable is only modified by firmware and is read-only to the OS.
2371 //
2372 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, L"HwErrRecSupport") == 0)) {
2373 return EFI_WRITE_PROTECTED;
2374 }
2375 }
2376
2377 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2378
2379 //
2380 // Consider reentrant in MCA/INIT/NMI. It needs be reupdated.
2381 //
2382 if (1 < InterlockedIncrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState)) {
2383 Point = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
2384 //
2385 // Parse non-volatile variable data and get last variable offset.
2386 //
2387 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point);
2388 while ((NextVariable < GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point))
2389 && IsValidVariableHeader (NextVariable)) {
2390 NextVariable = GetNextVariablePtr (NextVariable);
2391 }
2392 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point;
2393 }
2394
2395 //
2396 // Check whether the input variable is already existed.
2397 //
2398 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, TRUE);
2399 if (!EFI_ERROR (Status)) {
2400 if (((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) && AtRuntime ()) {
2401 return EFI_WRITE_PROTECTED;
2402 }
2403 }
2404
2405 //
2406 // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.
2407 //
2408 AutoUpdateLangVariable (VariableName, Data, DataSize);
2409 //
2410 // Process PK, KEK, Sigdb seperately.
2411 //
2412 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_PLATFORM_KEY_NAME) == 0)){
2413 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, TRUE);
2414 } else if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0)) {
2415 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, FALSE);
2416 } else if (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&
2417 ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))) {
2418 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, FALSE);
2419 if (EFI_ERROR (Status)) {
2420 Status = ProcessVarWithKek (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes);
2421 }
2422 } else {
2423 Status = ProcessVariable (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes);
2424 }
2425
2426 InterlockedDecrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState);
2427 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2428
2429 return Status;
2430 }
2431
2432 /**
2433
2434 This code returns information about the EFI variables.
2435
2436 Caution: This function may receive untrusted input.
2437 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2438
2439 @param Attributes Attributes bitmask to specify the type of variables
2440 on which to return information.
2441 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
2442 for the EFI variables associated with the attributes specified.
2443 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
2444 for EFI variables associated with the attributes specified.
2445 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
2446 associated with the attributes specified.
2447
2448 @return EFI_INVALID_PARAMETER An invalid combination of attribute bits was supplied.
2449 @return EFI_SUCCESS Query successfully.
2450 @return EFI_UNSUPPORTED The attribute is not supported on this platform.
2451
2452 **/
2453 EFI_STATUS
2454 EFIAPI
2455 VariableServiceQueryVariableInfo (
2456 IN UINT32 Attributes,
2457 OUT UINT64 *MaximumVariableStorageSize,
2458 OUT UINT64 *RemainingVariableStorageSize,
2459 OUT UINT64 *MaximumVariableSize
2460 )
2461 {
2462 VARIABLE_HEADER *Variable;
2463 VARIABLE_HEADER *NextVariable;
2464 UINT64 VariableSize;
2465 VARIABLE_STORE_HEADER *VariableStoreHeader;
2466 UINT64 CommonVariableTotalSize;
2467 UINT64 HwErrVariableTotalSize;
2468
2469 CommonVariableTotalSize = 0;
2470 HwErrVariableTotalSize = 0;
2471
2472 if(MaximumVariableStorageSize == NULL || RemainingVariableStorageSize == NULL || MaximumVariableSize == NULL || Attributes == 0) {
2473 return EFI_INVALID_PARAMETER;
2474 }
2475
2476 if((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == 0) {
2477 //
2478 // Make sure the Attributes combination is supported by the platform.
2479 //
2480 return EFI_UNSUPPORTED;
2481 } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
2482 //
2483 // Make sure if runtime bit is set, boot service bit is set also.
2484 //
2485 return EFI_INVALID_PARAMETER;
2486 } else if (AtRuntime () && ((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) {
2487 //
2488 // Make sure RT Attribute is set if we are in Runtime phase.
2489 //
2490 return EFI_INVALID_PARAMETER;
2491 } else if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2492 //
2493 // Make sure Hw Attribute is set with NV.
2494 //
2495 return EFI_INVALID_PARAMETER;
2496 }
2497
2498 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2499
2500 if((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
2501 //
2502 // Query is Volatile related.
2503 //
2504 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
2505 } else {
2506 //
2507 // Query is Non-Volatile related.
2508 //
2509 VariableStoreHeader = mNvVariableCache;
2510 }
2511
2512 //
2513 // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize
2514 // with the storage size (excluding the storage header size).
2515 //
2516 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);
2517
2518 //
2519 // Harware error record variable needs larger size.
2520 //
2521 if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
2522 *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize);
2523 *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER);
2524 } else {
2525 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
2526 ASSERT (PcdGet32 (PcdHwErrStorageSize) < VariableStoreHeader->Size);
2527 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize);
2528 }
2529
2530 //
2531 // Let *MaximumVariableSize be PcdGet32 (PcdMaxVariableSize) with the exception of the variable header size.
2532 //
2533 *MaximumVariableSize = PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER);
2534 }
2535
2536 //
2537 // Point to the starting address of the variables.
2538 //
2539 Variable = GetStartPointer (VariableStoreHeader);
2540
2541 //
2542 // Now walk through the related variable store.
2543 //
2544 while ((Variable < GetEndPointer (VariableStoreHeader)) && IsValidVariableHeader (Variable)) {
2545 NextVariable = GetNextVariablePtr (Variable);
2546 VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable;
2547
2548 if (AtRuntime ()) {
2549 //
2550 // We don't take the state of the variables in mind
2551 // when calculating RemainingVariableStorageSize,
2552 // since the space occupied by variables not marked with
2553 // VAR_ADDED is not allowed to be reclaimed in Runtime.
2554 //
2555 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2556 HwErrVariableTotalSize += VariableSize;
2557 } else {
2558 CommonVariableTotalSize += VariableSize;
2559 }
2560 } else {
2561 //
2562 // Only care about Variables with State VAR_ADDED, because
2563 // the space not marked as VAR_ADDED is reclaimable now.
2564 //
2565 if (Variable->State == VAR_ADDED) {
2566 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2567 HwErrVariableTotalSize += VariableSize;
2568 } else {
2569 CommonVariableTotalSize += VariableSize;
2570 }
2571 }
2572 }
2573
2574 //
2575 // Go to the next one.
2576 //
2577 Variable = NextVariable;
2578 }
2579
2580 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD){
2581 *RemainingVariableStorageSize = *MaximumVariableStorageSize - HwErrVariableTotalSize;
2582 }else {
2583 *RemainingVariableStorageSize = *MaximumVariableStorageSize - CommonVariableTotalSize;
2584 }
2585
2586 if (*RemainingVariableStorageSize < sizeof (VARIABLE_HEADER)) {
2587 *MaximumVariableSize = 0;
2588 } else if ((*RemainingVariableStorageSize - sizeof (VARIABLE_HEADER)) < *MaximumVariableSize) {
2589 *MaximumVariableSize = *RemainingVariableStorageSize - sizeof (VARIABLE_HEADER);
2590 }
2591
2592 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2593 return EFI_SUCCESS;
2594 }
2595
2596
2597 /**
2598 This function reclaims variable storage if free size is below the threshold.
2599
2600 Caution: This function may be invoked at SMM mode.
2601 Care must be taken to make sure not security issue.
2602
2603 **/
2604 VOID
2605 ReclaimForOS(
2606 VOID
2607 )
2608 {
2609 EFI_STATUS Status;
2610 UINTN CommonVariableSpace;
2611 UINTN RemainingCommonVariableSpace;
2612 UINTN RemainingHwErrVariableSpace;
2613
2614 Status = EFI_SUCCESS;
2615
2616 CommonVariableSpace = ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase)))->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32(PcdHwErrStorageSize); //Allowable max size of common variable storage space
2617
2618 RemainingCommonVariableSpace = CommonVariableSpace - mVariableModuleGlobal->CommonVariableTotalSize;
2619
2620 RemainingHwErrVariableSpace = PcdGet32 (PcdHwErrStorageSize) - mVariableModuleGlobal->HwErrVariableTotalSize;
2621 //
2622 // Check if the free area is blow a threshold.
2623 //
2624 if ((RemainingCommonVariableSpace < PcdGet32 (PcdMaxVariableSize))
2625 || ((PcdGet32 (PcdHwErrStorageSize) != 0) &&
2626 (RemainingHwErrVariableSpace < PcdGet32 (PcdMaxHardwareErrorVariableSize)))){
2627 Status = Reclaim (
2628 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
2629 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
2630 FALSE,
2631 NULL,
2632 FALSE
2633 );
2634 ASSERT_EFI_ERROR (Status);
2635 }
2636 }
2637
2638 /**
2639 Flush the HOB variable to flash.
2640
2641 @param[in] VariableName Name of variable has been updated or deleted.
2642 @param[in] VendorGuid Guid of variable has been updated or deleted.
2643
2644 **/
2645 VOID
2646 FlushHobVariableToFlash (
2647 IN CHAR16 *VariableName,
2648 IN EFI_GUID *VendorGuid
2649 )
2650 {
2651 EFI_STATUS Status;
2652 VARIABLE_STORE_HEADER *VariableStoreHeader;
2653 VARIABLE_HEADER *Variable;
2654 VOID *VariableData;
2655 BOOLEAN ErrorFlag;
2656
2657 ErrorFlag = FALSE;
2658
2659 //
2660 // Flush the HOB variable to flash.
2661 //
2662 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
2663 VariableStoreHeader = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
2664 //
2665 // Set HobVariableBase to 0, it can avoid SetVariable to call back.
2666 //
2667 mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0;
2668 for ( Variable = GetStartPointer (VariableStoreHeader)
2669 ; (Variable < GetEndPointer (VariableStoreHeader) && IsValidVariableHeader (Variable))
2670 ; Variable = GetNextVariablePtr (Variable)
2671 ) {
2672 if (Variable->State != VAR_ADDED) {
2673 //
2674 // The HOB variable has been set to DELETED state in local.
2675 //
2676 continue;
2677 }
2678 ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0);
2679 if (VendorGuid == NULL || VariableName == NULL ||
2680 !CompareGuid (VendorGuid, &Variable->VendorGuid) ||
2681 StrCmp (VariableName, GetVariableNamePtr (Variable)) != 0) {
2682 VariableData = GetVariableDataPtr (Variable);
2683 Status = VariableServiceSetVariable (
2684 GetVariableNamePtr (Variable),
2685 &Variable->VendorGuid,
2686 Variable->Attributes,
2687 Variable->DataSize,
2688 VariableData
2689 );
2690 DEBUG ((EFI_D_INFO, "Variable driver flush the HOB variable to flash: %g %s %r\n", &Variable->VendorGuid, GetVariableNamePtr (Variable), Status));
2691 } else {
2692 //
2693 // The updated or deleted variable is matched with the HOB variable.
2694 // Don't break here because we will try to set other HOB variables
2695 // since this variable could be set successfully.
2696 //
2697 Status = EFI_SUCCESS;
2698 }
2699 if (!EFI_ERROR (Status)) {
2700 //
2701 // If set variable successful, or the updated or deleted variable is matched with the HOB variable,
2702 // set the HOB variable to DELETED state in local.
2703 //
2704 DEBUG ((EFI_D_INFO, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", &Variable->VendorGuid, GetVariableNamePtr (Variable)));
2705 Variable->State &= VAR_DELETED;
2706 } else {
2707 ErrorFlag = TRUE;
2708 }
2709 }
2710 if (ErrorFlag) {
2711 //
2712 // We still have HOB variable(s) not flushed in flash.
2713 //
2714 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStoreHeader;
2715 } else {
2716 //
2717 // All HOB variables have been flushed in flash.
2718 //
2719 DEBUG ((EFI_D_INFO, "Variable driver: all HOB variables have been flushed in flash.\n"));
2720 if (!AtRuntime ()) {
2721 FreePool ((VOID *) VariableStoreHeader);
2722 }
2723 }
2724 }
2725
2726 }
2727
2728 /**
2729 Initializes variable write service after FVB was ready.
2730
2731 @retval EFI_SUCCESS Function successfully executed.
2732 @retval Others Fail to initialize the variable service.
2733
2734 **/
2735 EFI_STATUS
2736 VariableWriteServiceInitialize (
2737 VOID
2738 )
2739 {
2740 EFI_STATUS Status;
2741 VARIABLE_STORE_HEADER *VariableStoreHeader;
2742 UINTN Index;
2743 UINT8 Data;
2744 EFI_PHYSICAL_ADDRESS VariableStoreBase;
2745
2746 VariableStoreBase = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
2747 VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;
2748
2749 //
2750 // Check if the free area is really free.
2751 //
2752 for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreHeader->Size; Index++) {
2753 Data = ((UINT8 *) mNvVariableCache)[Index];
2754 if (Data != 0xff) {
2755 //
2756 // There must be something wrong in variable store, do reclaim operation.
2757 //
2758 Status = Reclaim (
2759 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
2760 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
2761 FALSE,
2762 NULL,
2763 TRUE
2764 );
2765 if (EFI_ERROR (Status)) {
2766 return Status;
2767 }
2768 break;
2769 }
2770 }
2771
2772 FlushHobVariableToFlash (NULL, NULL);
2773
2774 //
2775 // Authenticated variable initialize.
2776 //
2777 Status = AutenticatedVariableServiceInitialize ();
2778
2779 return Status;
2780 }
2781
2782
2783 /**
2784 Initializes variable store area for non-volatile and volatile variable.
2785
2786 @retval EFI_SUCCESS Function successfully executed.
2787 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
2788
2789 **/
2790 EFI_STATUS
2791 VariableCommonInitialize (
2792 VOID
2793 )
2794 {
2795 EFI_STATUS Status;
2796 VARIABLE_STORE_HEADER *VolatileVariableStore;
2797 VARIABLE_STORE_HEADER *VariableStoreHeader;
2798 VARIABLE_HEADER *NextVariable;
2799 EFI_PHYSICAL_ADDRESS TempVariableStoreHeader;
2800 EFI_PHYSICAL_ADDRESS VariableStoreBase;
2801 UINT64 VariableStoreLength;
2802 UINTN ScratchSize;
2803 UINTN VariableSize;
2804 EFI_HOB_GUID_TYPE *GuidHob;
2805
2806 //
2807 // Allocate runtime memory for variable driver global structure.
2808 //
2809 mVariableModuleGlobal = AllocateRuntimeZeroPool (sizeof (VARIABLE_MODULE_GLOBAL));
2810 if (mVariableModuleGlobal == NULL) {
2811 return EFI_OUT_OF_RESOURCES;
2812 }
2813
2814 InitializeLock (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);
2815
2816 //
2817 // Note that in EdkII variable driver implementation, Hardware Error Record type variable
2818 // is stored with common variable in the same NV region. So the platform integrator should
2819 // ensure that the value of PcdHwErrStorageSize is less than or equal to the value of
2820 // PcdFlashNvStorageVariableSize.
2821 //
2822 ASSERT (PcdGet32 (PcdHwErrStorageSize) <= PcdGet32 (PcdFlashNvStorageVariableSize));
2823
2824 //
2825 // Get HOB variable store.
2826 //
2827 GuidHob = GetFirstGuidHob (&gEfiAuthenticatedVariableGuid);
2828 if (GuidHob != NULL) {
2829 VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob);
2830 VariableStoreLength = (UINT64) (GuidHob->Header.HobLength - sizeof (EFI_HOB_GUID_TYPE));
2831 if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {
2832 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) AllocateRuntimeCopyPool ((UINTN) VariableStoreLength, (VOID *) VariableStoreHeader);
2833 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase == 0) {
2834 return EFI_OUT_OF_RESOURCES;
2835 }
2836 } else {
2837 DEBUG ((EFI_D_ERROR, "HOB Variable Store header is corrupted!\n"));
2838 }
2839 }
2840
2841 //
2842 // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.
2843 //
2844 ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));
2845 VolatileVariableStore = AllocateRuntimePool (PcdGet32 (PcdVariableStoreSize) + ScratchSize);
2846 if (VolatileVariableStore == NULL) {
2847 FreePool (mVariableModuleGlobal);
2848 return EFI_OUT_OF_RESOURCES;
2849 }
2850
2851 SetMem (VolatileVariableStore, PcdGet32 (PcdVariableStoreSize) + ScratchSize, 0xff);
2852
2853 //
2854 // Initialize Variable Specific Data.
2855 //
2856 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VolatileVariableStore;
2857 mVariableModuleGlobal->VolatileLastVariableOffset = (UINTN) GetStartPointer (VolatileVariableStore) - (UINTN) VolatileVariableStore;
2858 mVariableModuleGlobal->FvbInstance = NULL;
2859
2860 CopyGuid (&VolatileVariableStore->Signature, &gEfiAuthenticatedVariableGuid);
2861 VolatileVariableStore->Size = PcdGet32 (PcdVariableStoreSize);
2862 VolatileVariableStore->Format = VARIABLE_STORE_FORMATTED;
2863 VolatileVariableStore->State = VARIABLE_STORE_HEALTHY;
2864 VolatileVariableStore->Reserved = 0;
2865 VolatileVariableStore->Reserved1 = 0;
2866
2867 //
2868 // Get non-volatile variable store.
2869 //
2870
2871 TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);
2872 if (TempVariableStoreHeader == 0) {
2873 TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);
2874 }
2875
2876 //
2877 // Check if the Firmware Volume is not corrupted
2878 //
2879 if ((((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader))->Signature != EFI_FVH_SIGNATURE) ||
2880 (!CompareGuid (&gEfiSystemNvDataFvGuid, &((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader))->FileSystemGuid))) {
2881 Status = EFI_VOLUME_CORRUPTED;
2882 DEBUG ((EFI_D_ERROR, "Firmware Volume for Variable Store is corrupted\n"));
2883 goto Done;
2884 }
2885
2886 VariableStoreBase = TempVariableStoreHeader + \
2887 (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader)) -> HeaderLength);
2888 VariableStoreLength = (UINT64) PcdGet32 (PcdFlashNvStorageVariableSize) - \
2889 (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader)) -> HeaderLength);
2890
2891 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
2892 VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;
2893 if (GetVariableStoreStatus (VariableStoreHeader) != EfiValid) {
2894 Status = EFI_VOLUME_CORRUPTED;
2895 DEBUG((EFI_D_INFO, "Variable Store header is corrupted\n"));
2896 goto Done;
2897 }
2898 ASSERT(VariableStoreHeader->Size == VariableStoreLength);
2899
2900 //
2901 // Parse non-volatile variable data and get last variable offset.
2902 //
2903 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase);
2904 while (IsValidVariableHeader (NextVariable)) {
2905 VariableSize = NextVariable->NameSize + NextVariable->DataSize + sizeof (VARIABLE_HEADER);
2906 if ((NextVariable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
2907 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VariableSize);
2908 } else {
2909 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize);
2910 }
2911
2912 NextVariable = GetNextVariablePtr (NextVariable);
2913 }
2914
2915 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) VariableStoreBase;
2916
2917 //
2918 // Allocate runtime memory used for a memory copy of the FLASH region.
2919 // Keep the memory and the FLASH in sync as updates occur
2920 //
2921 mNvVariableCache = AllocateRuntimeZeroPool ((UINTN)VariableStoreLength);
2922 if (mNvVariableCache == NULL) {
2923 Status = EFI_OUT_OF_RESOURCES;
2924 goto Done;
2925 }
2926 CopyMem (mNvVariableCache, (CHAR8 *)(UINTN)VariableStoreBase, (UINTN)VariableStoreLength);
2927 Status = EFI_SUCCESS;
2928
2929 Done:
2930 if (EFI_ERROR (Status)) {
2931 FreePool (mVariableModuleGlobal);
2932 FreePool (VolatileVariableStore);
2933 }
2934
2935 return Status;
2936 }
2937
2938
2939 /**
2940 Get the proper fvb handle and/or fvb protocol by the given Flash address.
2941
2942 @param[in] Address The Flash address.
2943 @param[out] FvbHandle In output, if it is not NULL, it points to the proper FVB handle.
2944 @param[out] FvbProtocol In output, if it is not NULL, it points to the proper FVB protocol.
2945
2946 **/
2947 EFI_STATUS
2948 GetFvbInfoByAddress (
2949 IN EFI_PHYSICAL_ADDRESS Address,
2950 OUT EFI_HANDLE *FvbHandle OPTIONAL,
2951 OUT EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL **FvbProtocol OPTIONAL
2952 )
2953 {
2954 EFI_STATUS Status;
2955 EFI_HANDLE *HandleBuffer;
2956 UINTN HandleCount;
2957 UINTN Index;
2958 EFI_PHYSICAL_ADDRESS FvbBaseAddress;
2959 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
2960 EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
2961 EFI_FVB_ATTRIBUTES_2 Attributes;
2962
2963 //
2964 // Get all FVB handles.
2965 //
2966 Status = GetFvbCountAndBuffer (&HandleCount, &HandleBuffer);
2967 if (EFI_ERROR (Status)) {
2968 return EFI_NOT_FOUND;
2969 }
2970
2971 //
2972 // Get the FVB to access variable store.
2973 //
2974 Fvb = NULL;
2975 for (Index = 0; Index < HandleCount; Index += 1, Status = EFI_NOT_FOUND, Fvb = NULL) {
2976 Status = GetFvbByHandle (HandleBuffer[Index], &Fvb);
2977 if (EFI_ERROR (Status)) {
2978 Status = EFI_NOT_FOUND;
2979 break;
2980 }
2981
2982 //
2983 // Ensure this FVB protocol supported Write operation.
2984 //
2985 Status = Fvb->GetAttributes (Fvb, &Attributes);
2986 if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {
2987 continue;
2988 }
2989
2990 //
2991 // Compare the address and select the right one.
2992 //
2993 Status = Fvb->GetPhysicalAddress (Fvb, &FvbBaseAddress);
2994 if (EFI_ERROR (Status)) {
2995 continue;
2996 }
2997
2998 FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) FvbBaseAddress);
2999 if ((Address >= FvbBaseAddress) && (Address < (FvbBaseAddress + FwVolHeader->FvLength))) {
3000 if (FvbHandle != NULL) {
3001 *FvbHandle = HandleBuffer[Index];
3002 }
3003 if (FvbProtocol != NULL) {
3004 *FvbProtocol = Fvb;
3005 }
3006 Status = EFI_SUCCESS;
3007 break;
3008 }
3009 }
3010 FreePool (HandleBuffer);
3011
3012 if (Fvb == NULL) {
3013 Status = EFI_NOT_FOUND;
3014 }
3015
3016 return Status;
3017 }
3018