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