]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
MdeModulePkg Variable: Enhance the code logic about VariableLock
[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 LIST_ENTRY *Link;
2422 VARIABLE_ENTRY *LockedEntry;
2423
2424 if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {
2425 return EFI_INVALID_PARAMETER;
2426 }
2427
2428 if (mEndOfDxe) {
2429 return EFI_ACCESS_DENIED;
2430 }
2431
2432 Entry = AllocateRuntimeZeroPool (sizeof (*Entry) + StrSize (VariableName));
2433 if (Entry == NULL) {
2434 return EFI_OUT_OF_RESOURCES;
2435 }
2436
2437 DEBUG ((EFI_D_INFO, "[Variable] Lock: %g:%s\n", VendorGuid, VariableName));
2438
2439 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2440
2441 for ( Link = GetFirstNode (&mLockedVariableList)
2442 ; !IsNull (&mLockedVariableList, Link)
2443 ; Link = GetNextNode (&mLockedVariableList, Link)
2444 ) {
2445 LockedEntry = BASE_CR (Link, VARIABLE_ENTRY, Link);
2446 Name = (CHAR16 *) ((UINTN) LockedEntry + sizeof (*LockedEntry));
2447 if (CompareGuid (&LockedEntry->Guid, VendorGuid) && (StrCmp (Name, VariableName) == 0)) {
2448 goto Done;
2449 }
2450 }
2451
2452 Name = (CHAR16 *) ((UINTN) Entry + sizeof (*Entry));
2453 StrnCpy (Name, VariableName, StrLen (VariableName));
2454 CopyGuid (&Entry->Guid, VendorGuid);
2455 InsertTailList (&mLockedVariableList, &Entry->Link);
2456
2457 Done:
2458 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2459
2460 return EFI_SUCCESS;
2461 }
2462
2463 /**
2464
2465 This code finds variable in storage blocks (Volatile or Non-Volatile).
2466
2467 Caution: This function may receive untrusted input.
2468 This function may be invoked in SMM mode, and datasize is external input.
2469 This function will do basic validation, before parse the data.
2470
2471 @param VariableName Name of Variable to be found.
2472 @param VendorGuid Variable vendor GUID.
2473 @param Attributes Attribute value of the variable found.
2474 @param DataSize Size of Data found. If size is less than the
2475 data, this value contains the required size.
2476 @param Data Data pointer.
2477
2478 @return EFI_INVALID_PARAMETER Invalid parameter.
2479 @return EFI_SUCCESS Find the specified variable.
2480 @return EFI_NOT_FOUND Not found.
2481 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2482
2483 **/
2484 EFI_STATUS
2485 EFIAPI
2486 VariableServiceGetVariable (
2487 IN CHAR16 *VariableName,
2488 IN EFI_GUID *VendorGuid,
2489 OUT UINT32 *Attributes OPTIONAL,
2490 IN OUT UINTN *DataSize,
2491 OUT VOID *Data
2492 )
2493 {
2494 EFI_STATUS Status;
2495 VARIABLE_POINTER_TRACK Variable;
2496 UINTN VarDataSize;
2497
2498 if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {
2499 return EFI_INVALID_PARAMETER;
2500 }
2501
2502 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2503
2504 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2505 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2506 goto Done;
2507 }
2508
2509 //
2510 // Get data size
2511 //
2512 VarDataSize = DataSizeOfVariable (Variable.CurrPtr);
2513 ASSERT (VarDataSize != 0);
2514
2515 if (*DataSize >= VarDataSize) {
2516 if (Data == NULL) {
2517 Status = EFI_INVALID_PARAMETER;
2518 goto Done;
2519 }
2520
2521 CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr), VarDataSize);
2522 if (Attributes != NULL) {
2523 *Attributes = Variable.CurrPtr->Attributes;
2524 }
2525
2526 *DataSize = VarDataSize;
2527 UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);
2528
2529 Status = EFI_SUCCESS;
2530 goto Done;
2531 } else {
2532 *DataSize = VarDataSize;
2533 Status = EFI_BUFFER_TOO_SMALL;
2534 goto Done;
2535 }
2536
2537 Done:
2538 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2539 return Status;
2540 }
2541
2542
2543
2544 /**
2545
2546 This code Finds the Next available variable.
2547
2548 Caution: This function may receive untrusted input.
2549 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2550
2551 @param VariableNameSize Size of the variable name.
2552 @param VariableName Pointer to variable name.
2553 @param VendorGuid Variable Vendor Guid.
2554
2555 @return EFI_INVALID_PARAMETER Invalid parameter.
2556 @return EFI_SUCCESS Find the specified variable.
2557 @return EFI_NOT_FOUND Not found.
2558 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2559
2560 **/
2561 EFI_STATUS
2562 EFIAPI
2563 VariableServiceGetNextVariableName (
2564 IN OUT UINTN *VariableNameSize,
2565 IN OUT CHAR16 *VariableName,
2566 IN OUT EFI_GUID *VendorGuid
2567 )
2568 {
2569 VARIABLE_STORE_TYPE Type;
2570 VARIABLE_POINTER_TRACK Variable;
2571 VARIABLE_POINTER_TRACK VariableInHob;
2572 VARIABLE_POINTER_TRACK VariablePtrTrack;
2573 UINTN VarNameSize;
2574 EFI_STATUS Status;
2575 VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
2576
2577 if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
2578 return EFI_INVALID_PARAMETER;
2579 }
2580
2581 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2582
2583 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2584 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2585 goto Done;
2586 }
2587
2588 if (VariableName[0] != 0) {
2589 //
2590 // If variable name is not NULL, get next variable.
2591 //
2592 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2593 }
2594
2595 //
2596 // 0: Volatile, 1: HOB, 2: Non-Volatile.
2597 // The index and attributes mapping must be kept in this order as FindVariable
2598 // makes use of this mapping to implement search algorithm.
2599 //
2600 VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
2601 VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
2602 VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
2603
2604 while (TRUE) {
2605 //
2606 // Switch from Volatile to HOB, to Non-Volatile.
2607 //
2608 while (!IsValidVariableHeader (Variable.CurrPtr, Variable.EndPtr)) {
2609 //
2610 // Find current storage index
2611 //
2612 for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
2613 if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
2614 break;
2615 }
2616 }
2617 ASSERT (Type < VariableStoreTypeMax);
2618 //
2619 // Switch to next storage
2620 //
2621 for (Type++; Type < VariableStoreTypeMax; Type++) {
2622 if (VariableStoreHeader[Type] != NULL) {
2623 break;
2624 }
2625 }
2626 //
2627 // Capture the case that
2628 // 1. current storage is the last one, or
2629 // 2. no further storage
2630 //
2631 if (Type == VariableStoreTypeMax) {
2632 Status = EFI_NOT_FOUND;
2633 goto Done;
2634 }
2635 Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);
2636 Variable.EndPtr = GetEndPointer (VariableStoreHeader[Type]);
2637 Variable.CurrPtr = Variable.StartPtr;
2638 }
2639
2640 //
2641 // Variable is found
2642 //
2643 if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
2644 if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
2645 if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
2646 //
2647 // If it is a IN_DELETED_TRANSITION variable,
2648 // and there is also a same ADDED one at the same time,
2649 // don't return it.
2650 //
2651 VariablePtrTrack.StartPtr = Variable.StartPtr;
2652 VariablePtrTrack.EndPtr = Variable.EndPtr;
2653 Status = FindVariableEx (
2654 GetVariableNamePtr (Variable.CurrPtr),
2655 &Variable.CurrPtr->VendorGuid,
2656 FALSE,
2657 &VariablePtrTrack
2658 );
2659 if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
2660 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2661 continue;
2662 }
2663 }
2664
2665 //
2666 // Don't return NV variable when HOB overrides it
2667 //
2668 if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&
2669 (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))
2670 ) {
2671 VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);
2672 VariableInHob.EndPtr = GetEndPointer (VariableStoreHeader[VariableStoreTypeHob]);
2673 Status = FindVariableEx (
2674 GetVariableNamePtr (Variable.CurrPtr),
2675 &Variable.CurrPtr->VendorGuid,
2676 FALSE,
2677 &VariableInHob
2678 );
2679 if (!EFI_ERROR (Status)) {
2680 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2681 continue;
2682 }
2683 }
2684
2685 VarNameSize = NameSizeOfVariable (Variable.CurrPtr);
2686 ASSERT (VarNameSize != 0);
2687
2688 if (VarNameSize <= *VariableNameSize) {
2689 CopyMem (VariableName, GetVariableNamePtr (Variable.CurrPtr), VarNameSize);
2690 CopyMem (VendorGuid, &Variable.CurrPtr->VendorGuid, sizeof (EFI_GUID));
2691 Status = EFI_SUCCESS;
2692 } else {
2693 Status = EFI_BUFFER_TOO_SMALL;
2694 }
2695
2696 *VariableNameSize = VarNameSize;
2697 goto Done;
2698 }
2699 }
2700
2701 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2702 }
2703
2704 Done:
2705 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2706 return Status;
2707 }
2708
2709 /**
2710
2711 This code sets variable in storage blocks (Volatile or Non-Volatile).
2712
2713 Caution: This function may receive untrusted input.
2714 This function may be invoked in SMM mode, and datasize and data are external input.
2715 This function will do basic validation, before parse the data.
2716
2717 @param VariableName Name of Variable to be found.
2718 @param VendorGuid Variable vendor GUID.
2719 @param Attributes Attribute value of the variable found
2720 @param DataSize Size of Data found. If size is less than the
2721 data, this value contains the required size.
2722 @param Data Data pointer.
2723
2724 @return EFI_INVALID_PARAMETER Invalid parameter.
2725 @return EFI_SUCCESS Set successfully.
2726 @return EFI_OUT_OF_RESOURCES Resource not enough to set variable.
2727 @return EFI_NOT_FOUND Not found.
2728 @return EFI_WRITE_PROTECTED Variable is read-only.
2729
2730 **/
2731 EFI_STATUS
2732 EFIAPI
2733 VariableServiceSetVariable (
2734 IN CHAR16 *VariableName,
2735 IN EFI_GUID *VendorGuid,
2736 IN UINT32 Attributes,
2737 IN UINTN DataSize,
2738 IN VOID *Data
2739 )
2740 {
2741 VARIABLE_POINTER_TRACK Variable;
2742 EFI_STATUS Status;
2743 VARIABLE_HEADER *NextVariable;
2744 EFI_PHYSICAL_ADDRESS Point;
2745 LIST_ENTRY *Link;
2746 VARIABLE_ENTRY *Entry;
2747 CHAR16 *Name;
2748
2749 //
2750 // Check input parameters.
2751 //
2752 if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {
2753 return EFI_INVALID_PARAMETER;
2754 }
2755
2756 if (DataSize != 0 && Data == NULL) {
2757 return EFI_INVALID_PARAMETER;
2758 }
2759
2760 //
2761 // Not support authenticated or append variable write yet.
2762 //
2763 if ((Attributes & (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_APPEND_WRITE)) != 0) {
2764 return EFI_INVALID_PARAMETER;
2765 }
2766
2767 //
2768 // Make sure if runtime bit is set, boot service bit is set also.
2769 //
2770 if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
2771 return EFI_INVALID_PARAMETER;
2772 }
2773
2774 if ((UINTN)(~0) - DataSize < StrSize(VariableName)){
2775 //
2776 // Prevent whole variable size overflow
2777 //
2778 return EFI_INVALID_PARAMETER;
2779 }
2780
2781 //
2782 // The size of the VariableName, including the Unicode Null in bytes plus
2783 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)
2784 // bytes for HwErrRec, and PcdGet32 (PcdMaxVariableSize) bytes for the others.
2785 //
2786 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2787 if ( StrSize (VariableName) + DataSize > PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER)) {
2788 return EFI_INVALID_PARAMETER;
2789 }
2790 if (!IsHwErrRecVariable(VariableName, VendorGuid)) {
2791 return EFI_INVALID_PARAMETER;
2792 }
2793 } else {
2794 //
2795 // The size of the VariableName, including the Unicode Null in bytes plus
2796 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxVariableSize) bytes.
2797 //
2798 if (StrSize (VariableName) + DataSize > PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER)) {
2799 return EFI_INVALID_PARAMETER;
2800 }
2801 }
2802
2803 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2804
2805 //
2806 // Consider reentrant in MCA/INIT/NMI. It needs be reupdated.
2807 //
2808 if (1 < InterlockedIncrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState)) {
2809 Point = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
2810 //
2811 // Parse non-volatile variable data and get last variable offset.
2812 //
2813 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point);
2814 while (IsValidVariableHeader (NextVariable, GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point))) {
2815 NextVariable = GetNextVariablePtr (NextVariable);
2816 }
2817 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point;
2818 }
2819
2820 if (mEndOfDxe && mEnableLocking) {
2821 //
2822 // Treat the variables listed in the forbidden variable list as read-only after leaving DXE phase.
2823 //
2824 for ( Link = GetFirstNode (&mLockedVariableList)
2825 ; !IsNull (&mLockedVariableList, Link)
2826 ; Link = GetNextNode (&mLockedVariableList, Link)
2827 ) {
2828 Entry = BASE_CR (Link, VARIABLE_ENTRY, Link);
2829 Name = (CHAR16 *) ((UINTN) Entry + sizeof (*Entry));
2830 if (CompareGuid (&Entry->Guid, VendorGuid) && (StrCmp (Name, VariableName) == 0)) {
2831 Status = EFI_WRITE_PROTECTED;
2832 DEBUG ((EFI_D_INFO, "[Variable]: Changing readonly variable after leaving DXE phase - %g:%s\n", VendorGuid, VariableName));
2833 goto Done;
2834 }
2835 }
2836 }
2837
2838 Status = InternalVarCheckSetVariableCheck (VariableName, VendorGuid, Attributes, DataSize, Data);
2839 if (EFI_ERROR (Status)) {
2840 goto Done;
2841 }
2842
2843 //
2844 // Check whether the input variable is already existed.
2845 //
2846 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, TRUE);
2847 if (!EFI_ERROR (Status)) {
2848 if (((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) && AtRuntime ()) {
2849 Status = EFI_WRITE_PROTECTED;
2850 goto Done;
2851 }
2852 if (Attributes != 0 && Attributes != Variable.CurrPtr->Attributes) {
2853 //
2854 // If a preexisting variable is rewritten with different attributes, SetVariable() shall not
2855 // modify the variable and shall return EFI_INVALID_PARAMETER. Two exceptions to this rule:
2856 // 1. No access attributes specified
2857 // 2. The only attribute differing is EFI_VARIABLE_APPEND_WRITE
2858 //
2859 Status = EFI_INVALID_PARAMETER;
2860 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));
2861 goto Done;
2862 }
2863 }
2864
2865 if (!FeaturePcdGet (PcdUefiVariableDefaultLangDeprecate)) {
2866 //
2867 // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.
2868 //
2869 Status = AutoUpdateLangVariable (VariableName, Data, DataSize);
2870 if (EFI_ERROR (Status)) {
2871 //
2872 // The auto update operation failed, directly return to avoid inconsistency between PlatformLang and Lang.
2873 //
2874 goto Done;
2875 }
2876 }
2877
2878 Status = UpdateVariable (VariableName, VendorGuid, Data, DataSize, Attributes, &Variable);
2879
2880 Done:
2881 InterlockedDecrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState);
2882 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2883
2884 return Status;
2885 }
2886
2887 /**
2888
2889 This code returns information about the EFI variables.
2890
2891 Caution: This function may receive untrusted input.
2892 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2893
2894 @param Attributes Attributes bitmask to specify the type of variables
2895 on which to return information.
2896 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
2897 for the EFI variables associated with the attributes specified.
2898 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
2899 for EFI variables associated with the attributes specified.
2900 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
2901 associated with the attributes specified.
2902
2903 @return EFI_SUCCESS Query successfully.
2904
2905 **/
2906 EFI_STATUS
2907 EFIAPI
2908 VariableServiceQueryVariableInfoInternal (
2909 IN UINT32 Attributes,
2910 OUT UINT64 *MaximumVariableStorageSize,
2911 OUT UINT64 *RemainingVariableStorageSize,
2912 OUT UINT64 *MaximumVariableSize
2913 )
2914 {
2915 VARIABLE_HEADER *Variable;
2916 VARIABLE_HEADER *NextVariable;
2917 UINT64 VariableSize;
2918 VARIABLE_STORE_HEADER *VariableStoreHeader;
2919 UINT64 CommonVariableTotalSize;
2920 UINT64 HwErrVariableTotalSize;
2921 EFI_STATUS Status;
2922 VARIABLE_POINTER_TRACK VariablePtrTrack;
2923
2924 CommonVariableTotalSize = 0;
2925 HwErrVariableTotalSize = 0;
2926
2927 if((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
2928 //
2929 // Query is Volatile related.
2930 //
2931 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
2932 } else {
2933 //
2934 // Query is Non-Volatile related.
2935 //
2936 VariableStoreHeader = mNvVariableCache;
2937 }
2938
2939 //
2940 // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize
2941 // with the storage size (excluding the storage header size).
2942 //
2943 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);
2944
2945 //
2946 // Harware error record variable needs larger size.
2947 //
2948 if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
2949 *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize);
2950 *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER);
2951 } else {
2952 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
2953 if (AtRuntime ()) {
2954 *MaximumVariableStorageSize = mVariableModuleGlobal->CommonRuntimeVariableSpace;
2955 } else {
2956 *MaximumVariableStorageSize = mVariableModuleGlobal->CommonVariableSpace;
2957 }
2958 }
2959
2960 //
2961 // Let *MaximumVariableSize be PcdGet32 (PcdMaxVariableSize) with the exception of the variable header size.
2962 //
2963 *MaximumVariableSize = PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER);
2964 }
2965
2966 //
2967 // Point to the starting address of the variables.
2968 //
2969 Variable = GetStartPointer (VariableStoreHeader);
2970
2971 //
2972 // Now walk through the related variable store.
2973 //
2974 while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
2975 NextVariable = GetNextVariablePtr (Variable);
2976 VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable;
2977
2978 if (AtRuntime ()) {
2979 //
2980 // We don't take the state of the variables in mind
2981 // when calculating RemainingVariableStorageSize,
2982 // since the space occupied by variables not marked with
2983 // VAR_ADDED is not allowed to be reclaimed in Runtime.
2984 //
2985 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2986 HwErrVariableTotalSize += VariableSize;
2987 } else {
2988 CommonVariableTotalSize += VariableSize;
2989 }
2990 } else {
2991 //
2992 // Only care about Variables with State VAR_ADDED, because
2993 // the space not marked as VAR_ADDED is reclaimable now.
2994 //
2995 if (Variable->State == VAR_ADDED) {
2996 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2997 HwErrVariableTotalSize += VariableSize;
2998 } else {
2999 CommonVariableTotalSize += VariableSize;
3000 }
3001 } else if (Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
3002 //
3003 // If it is a IN_DELETED_TRANSITION variable,
3004 // and there is not also a same ADDED one at the same time,
3005 // this IN_DELETED_TRANSITION variable is valid.
3006 //
3007 VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader);
3008 VariablePtrTrack.EndPtr = GetEndPointer (VariableStoreHeader);
3009 Status = FindVariableEx (
3010 GetVariableNamePtr (Variable),
3011 &Variable->VendorGuid,
3012 FALSE,
3013 &VariablePtrTrack
3014 );
3015 if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State != VAR_ADDED) {
3016 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3017 HwErrVariableTotalSize += VariableSize;
3018 } else {
3019 CommonVariableTotalSize += VariableSize;
3020 }
3021 }
3022 }
3023 }
3024
3025 //
3026 // Go to the next one.
3027 //
3028 Variable = NextVariable;
3029 }
3030
3031 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD){
3032 *RemainingVariableStorageSize = *MaximumVariableStorageSize - HwErrVariableTotalSize;
3033 } else {
3034 if (*MaximumVariableStorageSize < CommonVariableTotalSize) {
3035 *RemainingVariableStorageSize = 0;
3036 } else {
3037 *RemainingVariableStorageSize = *MaximumVariableStorageSize - CommonVariableTotalSize;
3038 }
3039 }
3040
3041 if (*RemainingVariableStorageSize < sizeof (VARIABLE_HEADER)) {
3042 *MaximumVariableSize = 0;
3043 } else if ((*RemainingVariableStorageSize - sizeof (VARIABLE_HEADER)) < *MaximumVariableSize) {
3044 *MaximumVariableSize = *RemainingVariableStorageSize - sizeof (VARIABLE_HEADER);
3045 }
3046
3047 return EFI_SUCCESS;
3048 }
3049
3050 /**
3051
3052 This code returns information about the EFI variables.
3053
3054 Caution: This function may receive untrusted input.
3055 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
3056
3057 @param Attributes Attributes bitmask to specify the type of variables
3058 on which to return information.
3059 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
3060 for the EFI variables associated with the attributes specified.
3061 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
3062 for EFI variables associated with the attributes specified.
3063 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
3064 associated with the attributes specified.
3065
3066 @return EFI_INVALID_PARAMETER An invalid combination of attribute bits was supplied.
3067 @return EFI_SUCCESS Query successfully.
3068 @return EFI_UNSUPPORTED The attribute is not supported on this platform.
3069
3070 **/
3071 EFI_STATUS
3072 EFIAPI
3073 VariableServiceQueryVariableInfo (
3074 IN UINT32 Attributes,
3075 OUT UINT64 *MaximumVariableStorageSize,
3076 OUT UINT64 *RemainingVariableStorageSize,
3077 OUT UINT64 *MaximumVariableSize
3078 )
3079 {
3080 EFI_STATUS Status;
3081
3082 if(MaximumVariableStorageSize == NULL || RemainingVariableStorageSize == NULL || MaximumVariableSize == NULL || Attributes == 0) {
3083 return EFI_INVALID_PARAMETER;
3084 }
3085
3086 if((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == 0) {
3087 //
3088 // Make sure the Attributes combination is supported by the platform.
3089 //
3090 return EFI_UNSUPPORTED;
3091 } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
3092 //
3093 // Make sure if runtime bit is set, boot service bit is set also.
3094 //
3095 return EFI_INVALID_PARAMETER;
3096 } else if (AtRuntime () && ((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) {
3097 //
3098 // Make sure RT Attribute is set if we are in Runtime phase.
3099 //
3100 return EFI_INVALID_PARAMETER;
3101 } else if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3102 //
3103 // Make sure Hw Attribute is set with NV.
3104 //
3105 return EFI_INVALID_PARAMETER;
3106 } else if ((Attributes & (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_APPEND_WRITE)) != 0) {
3107 //
3108 // Not support authenticated or append variable write yet.
3109 //
3110 return EFI_UNSUPPORTED;
3111 }
3112
3113 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3114
3115 Status = VariableServiceQueryVariableInfoInternal (
3116 Attributes,
3117 MaximumVariableStorageSize,
3118 RemainingVariableStorageSize,
3119 MaximumVariableSize
3120 );
3121
3122 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3123 return Status;
3124 }
3125
3126 /**
3127 This function reclaims variable storage if free size is below the threshold.
3128
3129 Caution: This function may be invoked at SMM mode.
3130 Care must be taken to make sure not security issue.
3131
3132 **/
3133 VOID
3134 ReclaimForOS(
3135 VOID
3136 )
3137 {
3138 EFI_STATUS Status;
3139 UINTN RemainingCommonRuntimeVariableSpace;
3140 UINTN RemainingHwErrVariableSpace;
3141 STATIC BOOLEAN Reclaimed;
3142
3143 //
3144 // This function will be called only once at EndOfDxe or ReadyToBoot event.
3145 //
3146 if (Reclaimed) {
3147 return;
3148 }
3149 Reclaimed = TRUE;
3150
3151 Status = EFI_SUCCESS;
3152
3153 if (mVariableModuleGlobal->CommonRuntimeVariableSpace < mVariableModuleGlobal->CommonVariableTotalSize) {
3154 RemainingCommonRuntimeVariableSpace = 0;
3155 } else {
3156 RemainingCommonRuntimeVariableSpace = mVariableModuleGlobal->CommonRuntimeVariableSpace - mVariableModuleGlobal->CommonVariableTotalSize;
3157 }
3158
3159 RemainingHwErrVariableSpace = PcdGet32 (PcdHwErrStorageSize) - mVariableModuleGlobal->HwErrVariableTotalSize;
3160 //
3161 // Check if the free area is below a threshold.
3162 //
3163 if ((RemainingCommonRuntimeVariableSpace < PcdGet32 (PcdMaxVariableSize))
3164 || ((PcdGet32 (PcdHwErrStorageSize) != 0) &&
3165 (RemainingHwErrVariableSpace < PcdGet32 (PcdMaxHardwareErrorVariableSize)))){
3166 Status = Reclaim (
3167 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
3168 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
3169 FALSE,
3170 NULL,
3171 NULL,
3172 0
3173 );
3174 ASSERT_EFI_ERROR (Status);
3175 }
3176 }
3177
3178 /**
3179 Init non-volatile variable store.
3180
3181 @retval EFI_SUCCESS Function successfully executed.
3182 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
3183 @retval EFI_VOLUME_CORRUPTED Variable Store or Firmware Volume for Variable Store is corrupted.
3184
3185 **/
3186 EFI_STATUS
3187 InitNonVolatileVariableStore (
3188 VOID
3189 )
3190 {
3191 EFI_FIRMWARE_VOLUME_HEADER *FvHeader;
3192 VARIABLE_HEADER *Variable;
3193 VARIABLE_HEADER *NextVariable;
3194 EFI_PHYSICAL_ADDRESS VariableStoreBase;
3195 UINT64 VariableStoreLength;
3196 UINTN VariableSize;
3197 EFI_HOB_GUID_TYPE *GuidHob;
3198 EFI_PHYSICAL_ADDRESS NvStorageBase;
3199 UINT8 *NvStorageData;
3200 UINT32 NvStorageSize;
3201 FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *FtwLastWriteData;
3202 UINT32 BackUpOffset;
3203 UINT32 BackUpSize;
3204 UINT32 HwErrStorageSize;
3205 UINT32 MaxUserNvVariableSpaceSize;
3206 UINT32 BoottimeReservedNvVariableSpaceSize;
3207
3208 mVariableModuleGlobal->FvbInstance = NULL;
3209
3210 //
3211 // Allocate runtime memory used for a memory copy of the FLASH region.
3212 // Keep the memory and the FLASH in sync as updates occur.
3213 //
3214 NvStorageSize = PcdGet32 (PcdFlashNvStorageVariableSize);
3215 NvStorageData = AllocateRuntimeZeroPool (NvStorageSize);
3216 if (NvStorageData == NULL) {
3217 return EFI_OUT_OF_RESOURCES;
3218 }
3219
3220 NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);
3221 if (NvStorageBase == 0) {
3222 NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);
3223 }
3224 //
3225 // Copy NV storage data to the memory buffer.
3226 //
3227 CopyMem (NvStorageData, (UINT8 *) (UINTN) NvStorageBase, NvStorageSize);
3228
3229 //
3230 // Check the FTW last write data hob.
3231 //
3232 GuidHob = GetFirstGuidHob (&gEdkiiFaultTolerantWriteGuid);
3233 if (GuidHob != NULL) {
3234 FtwLastWriteData = (FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *) GET_GUID_HOB_DATA (GuidHob);
3235 if (FtwLastWriteData->TargetAddress == NvStorageBase) {
3236 DEBUG ((EFI_D_INFO, "Variable: NV storage is backed up in spare block: 0x%x\n", (UINTN) FtwLastWriteData->SpareAddress));
3237 //
3238 // Copy the backed up NV storage data to the memory buffer from spare block.
3239 //
3240 CopyMem (NvStorageData, (UINT8 *) (UINTN) (FtwLastWriteData->SpareAddress), NvStorageSize);
3241 } else if ((FtwLastWriteData->TargetAddress > NvStorageBase) &&
3242 (FtwLastWriteData->TargetAddress < (NvStorageBase + NvStorageSize))) {
3243 //
3244 // Flash NV storage from the offset is backed up in spare block.
3245 //
3246 BackUpOffset = (UINT32) (FtwLastWriteData->TargetAddress - NvStorageBase);
3247 BackUpSize = NvStorageSize - BackUpOffset;
3248 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));
3249 //
3250 // Copy the partial backed up NV storage data to the memory buffer from spare block.
3251 //
3252 CopyMem (NvStorageData + BackUpOffset, (UINT8 *) (UINTN) FtwLastWriteData->SpareAddress, BackUpSize);
3253 }
3254 }
3255
3256 FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) NvStorageData;
3257
3258 //
3259 // Check if the Firmware Volume is not corrupted
3260 //
3261 if ((FvHeader->Signature != EFI_FVH_SIGNATURE) || (!CompareGuid (&gEfiSystemNvDataFvGuid, &FvHeader->FileSystemGuid))) {
3262 FreePool (NvStorageData);
3263 DEBUG ((EFI_D_ERROR, "Firmware Volume for Variable Store is corrupted\n"));
3264 return EFI_VOLUME_CORRUPTED;
3265 }
3266
3267 VariableStoreBase = (EFI_PHYSICAL_ADDRESS) ((UINTN) FvHeader + FvHeader->HeaderLength);
3268 VariableStoreLength = (UINT64) (NvStorageSize - FvHeader->HeaderLength);
3269
3270 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
3271 mNvVariableCache = (VARIABLE_STORE_HEADER *) (UINTN) VariableStoreBase;
3272 if (GetVariableStoreStatus (mNvVariableCache) != EfiValid) {
3273 FreePool (NvStorageData);
3274 DEBUG((EFI_D_ERROR, "Variable Store header is corrupted\n"));
3275 return EFI_VOLUME_CORRUPTED;
3276 }
3277 ASSERT(mNvVariableCache->Size == VariableStoreLength);
3278
3279
3280 ASSERT (sizeof (VARIABLE_STORE_HEADER) <= VariableStoreLength);
3281
3282 HwErrStorageSize = PcdGet32 (PcdHwErrStorageSize);
3283 MaxUserNvVariableSpaceSize = PcdGet32 (PcdMaxUserNvVariableSpaceSize);
3284 BoottimeReservedNvVariableSpaceSize = PcdGet32 (PcdBoottimeReservedNvVariableSpaceSize);
3285
3286 //
3287 // Note that in EdkII variable driver implementation, Hardware Error Record type variable
3288 // is stored with common variable in the same NV region. So the platform integrator should
3289 // ensure that the value of PcdHwErrStorageSize is less than the value of
3290 // VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).
3291 //
3292 ASSERT (HwErrStorageSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)));
3293 //
3294 // Ensure that the value of PcdMaxUserNvVariableSpaceSize is less than the value of
3295 // VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).
3296 //
3297 ASSERT (MaxUserNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize));
3298 //
3299 // Ensure that the value of PcdBoottimeReservedNvVariableSpaceSize is less than the value of
3300 // VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).
3301 //
3302 ASSERT (BoottimeReservedNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize));
3303
3304 mVariableModuleGlobal->CommonVariableSpace = ((UINTN) VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize);
3305 mVariableModuleGlobal->CommonMaxUserVariableSpace = ((MaxUserNvVariableSpaceSize != 0) ? MaxUserNvVariableSpaceSize : mVariableModuleGlobal->CommonVariableSpace);
3306 mVariableModuleGlobal->CommonRuntimeVariableSpace = mVariableModuleGlobal->CommonVariableSpace - BoottimeReservedNvVariableSpaceSize;
3307
3308 DEBUG ((EFI_D_INFO, "Variable driver common space: 0x%x 0x%x 0x%x\n", mVariableModuleGlobal->CommonVariableSpace, mVariableModuleGlobal->CommonMaxUserVariableSpace, mVariableModuleGlobal->CommonRuntimeVariableSpace));
3309
3310 //
3311 // The max variable or hardware error variable size should be < variable store size.
3312 //
3313 ASSERT(MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize)) < VariableStoreLength);
3314
3315 //
3316 // Parse non-volatile variable data and get last variable offset.
3317 //
3318 Variable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase);
3319 while (IsValidVariableHeader (Variable, GetEndPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase))) {
3320 NextVariable = GetNextVariablePtr (Variable);
3321 VariableSize = (UINTN) NextVariable - (UINTN) Variable;
3322 if ((Variable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
3323 mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;
3324 } else {
3325 mVariableModuleGlobal->CommonVariableTotalSize += VariableSize;
3326 }
3327
3328 Variable = NextVariable;
3329 }
3330 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) Variable - (UINTN) VariableStoreBase;
3331
3332 return EFI_SUCCESS;
3333 }
3334
3335 /**
3336 Flush the HOB variable to flash.
3337
3338 @param[in] VariableName Name of variable has been updated or deleted.
3339 @param[in] VendorGuid Guid of variable has been updated or deleted.
3340
3341 **/
3342 VOID
3343 FlushHobVariableToFlash (
3344 IN CHAR16 *VariableName,
3345 IN EFI_GUID *VendorGuid
3346 )
3347 {
3348 EFI_STATUS Status;
3349 VARIABLE_STORE_HEADER *VariableStoreHeader;
3350 VARIABLE_HEADER *Variable;
3351 VOID *VariableData;
3352 BOOLEAN ErrorFlag;
3353
3354 ErrorFlag = FALSE;
3355
3356 //
3357 // Flush the HOB variable to flash.
3358 //
3359 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
3360 VariableStoreHeader = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
3361 //
3362 // Set HobVariableBase to 0, it can avoid SetVariable to call back.
3363 //
3364 mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0;
3365 for ( Variable = GetStartPointer (VariableStoreHeader)
3366 ; IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))
3367 ; Variable = GetNextVariablePtr (Variable)
3368 ) {
3369 if (Variable->State != VAR_ADDED) {
3370 //
3371 // The HOB variable has been set to DELETED state in local.
3372 //
3373 continue;
3374 }
3375 ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0);
3376 if (VendorGuid == NULL || VariableName == NULL ||
3377 !CompareGuid (VendorGuid, &Variable->VendorGuid) ||
3378 StrCmp (VariableName, GetVariableNamePtr (Variable)) != 0) {
3379 VariableData = GetVariableDataPtr (Variable);
3380 Status = VariableServiceSetVariable (
3381 GetVariableNamePtr (Variable),
3382 &Variable->VendorGuid,
3383 Variable->Attributes,
3384 Variable->DataSize,
3385 VariableData
3386 );
3387 DEBUG ((EFI_D_INFO, "Variable driver flush the HOB variable to flash: %g %s %r\n", &Variable->VendorGuid, GetVariableNamePtr (Variable), Status));
3388 } else {
3389 //
3390 // The updated or deleted variable is matched with the HOB variable.
3391 // Don't break here because we will try to set other HOB variables
3392 // since this variable could be set successfully.
3393 //
3394 Status = EFI_SUCCESS;
3395 }
3396 if (!EFI_ERROR (Status)) {
3397 //
3398 // If set variable successful, or the updated or deleted variable is matched with the HOB variable,
3399 // set the HOB variable to DELETED state in local.
3400 //
3401 DEBUG ((EFI_D_INFO, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", &Variable->VendorGuid, GetVariableNamePtr (Variable)));
3402 Variable->State &= VAR_DELETED;
3403 } else {
3404 ErrorFlag = TRUE;
3405 }
3406 }
3407 if (ErrorFlag) {
3408 //
3409 // We still have HOB variable(s) not flushed in flash.
3410 //
3411 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStoreHeader;
3412 } else {
3413 //
3414 // All HOB variables have been flushed in flash.
3415 //
3416 DEBUG ((EFI_D_INFO, "Variable driver: all HOB variables have been flushed in flash.\n"));
3417 if (!AtRuntime ()) {
3418 FreePool ((VOID *) VariableStoreHeader);
3419 }
3420 }
3421 }
3422
3423 }
3424
3425 /**
3426 Initializes variable write service after FTW was ready.
3427
3428 @retval EFI_SUCCESS Function successfully executed.
3429 @retval Others Fail to initialize the variable service.
3430
3431 **/
3432 EFI_STATUS
3433 VariableWriteServiceInitialize (
3434 VOID
3435 )
3436 {
3437 EFI_STATUS Status;
3438 VARIABLE_STORE_HEADER *VariableStoreHeader;
3439 UINTN Index;
3440 UINT8 Data;
3441 EFI_PHYSICAL_ADDRESS VariableStoreBase;
3442 EFI_PHYSICAL_ADDRESS NvStorageBase;
3443
3444 NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);
3445 if (NvStorageBase == 0) {
3446 NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);
3447 }
3448 VariableStoreBase = NvStorageBase + (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(NvStorageBase))->HeaderLength);
3449
3450 //
3451 // Let NonVolatileVariableBase point to flash variable store base directly after FTW ready.
3452 //
3453 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
3454 VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;
3455
3456 //
3457 // Check if the free area is really free.
3458 //
3459 for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreHeader->Size; Index++) {
3460 Data = ((UINT8 *) mNvVariableCache)[Index];
3461 if (Data != 0xff) {
3462 //
3463 // There must be something wrong in variable store, do reclaim operation.
3464 //
3465 Status = Reclaim (
3466 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
3467 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
3468 FALSE,
3469 NULL,
3470 NULL,
3471 0
3472 );
3473 if (EFI_ERROR (Status)) {
3474 return Status;
3475 }
3476 break;
3477 }
3478 }
3479
3480 FlushHobVariableToFlash (NULL, NULL);
3481
3482 return EFI_SUCCESS;
3483 }
3484
3485
3486 /**
3487 Initializes variable store area for non-volatile and volatile variable.
3488
3489 @retval EFI_SUCCESS Function successfully executed.
3490 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
3491
3492 **/
3493 EFI_STATUS
3494 VariableCommonInitialize (
3495 VOID
3496 )
3497 {
3498 EFI_STATUS Status;
3499 VARIABLE_STORE_HEADER *VolatileVariableStore;
3500 VARIABLE_STORE_HEADER *VariableStoreHeader;
3501 UINT64 VariableStoreLength;
3502 UINTN ScratchSize;
3503 EFI_HOB_GUID_TYPE *GuidHob;
3504
3505 //
3506 // Allocate runtime memory for variable driver global structure.
3507 //
3508 mVariableModuleGlobal = AllocateRuntimeZeroPool (sizeof (VARIABLE_MODULE_GLOBAL));
3509 if (mVariableModuleGlobal == NULL) {
3510 return EFI_OUT_OF_RESOURCES;
3511 }
3512
3513 InitializeLock (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);
3514
3515 //
3516 // Get HOB variable store.
3517 //
3518 GuidHob = GetFirstGuidHob (&gEfiVariableGuid);
3519 if (GuidHob != NULL) {
3520 VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob);
3521 VariableStoreLength = (UINT64) (GuidHob->Header.HobLength - sizeof (EFI_HOB_GUID_TYPE));
3522 if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {
3523 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) AllocateRuntimeCopyPool ((UINTN) VariableStoreLength, (VOID *) VariableStoreHeader);
3524 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase == 0) {
3525 FreePool (mVariableModuleGlobal);
3526 return EFI_OUT_OF_RESOURCES;
3527 }
3528 } else {
3529 DEBUG ((EFI_D_ERROR, "HOB Variable Store header is corrupted!\n"));
3530 }
3531 }
3532
3533 //
3534 // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.
3535 //
3536 ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));
3537 VolatileVariableStore = AllocateRuntimePool (PcdGet32 (PcdVariableStoreSize) + ScratchSize);
3538 if (VolatileVariableStore == NULL) {
3539 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
3540 FreePool ((VOID *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase);
3541 }
3542 FreePool (mVariableModuleGlobal);
3543 return EFI_OUT_OF_RESOURCES;
3544 }
3545
3546 SetMem (VolatileVariableStore, PcdGet32 (PcdVariableStoreSize) + ScratchSize, 0xff);
3547
3548 //
3549 // Initialize Variable Specific Data.
3550 //
3551 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VolatileVariableStore;
3552 mVariableModuleGlobal->VolatileLastVariableOffset = (UINTN) GetStartPointer (VolatileVariableStore) - (UINTN) VolatileVariableStore;
3553
3554 CopyGuid (&VolatileVariableStore->Signature, &gEfiVariableGuid);
3555 VolatileVariableStore->Size = PcdGet32 (PcdVariableStoreSize);
3556 VolatileVariableStore->Format = VARIABLE_STORE_FORMATTED;
3557 VolatileVariableStore->State = VARIABLE_STORE_HEALTHY;
3558 VolatileVariableStore->Reserved = 0;
3559 VolatileVariableStore->Reserved1 = 0;
3560
3561 //
3562 // Init non-volatile variable store.
3563 //
3564 Status = InitNonVolatileVariableStore ();
3565 if (EFI_ERROR (Status)) {
3566 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
3567 FreePool ((VOID *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase);
3568 }
3569 FreePool (mVariableModuleGlobal);
3570 FreePool (VolatileVariableStore);
3571 }
3572
3573 return Status;
3574 }
3575
3576
3577 /**
3578 Get the proper fvb handle and/or fvb protocol by the given Flash address.
3579
3580 @param[in] Address The Flash address.
3581 @param[out] FvbHandle In output, if it is not NULL, it points to the proper FVB handle.
3582 @param[out] FvbProtocol In output, if it is not NULL, it points to the proper FVB protocol.
3583
3584 **/
3585 EFI_STATUS
3586 GetFvbInfoByAddress (
3587 IN EFI_PHYSICAL_ADDRESS Address,
3588 OUT EFI_HANDLE *FvbHandle OPTIONAL,
3589 OUT EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL **FvbProtocol OPTIONAL
3590 )
3591 {
3592 EFI_STATUS Status;
3593 EFI_HANDLE *HandleBuffer;
3594 UINTN HandleCount;
3595 UINTN Index;
3596 EFI_PHYSICAL_ADDRESS FvbBaseAddress;
3597 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
3598 EFI_FVB_ATTRIBUTES_2 Attributes;
3599 UINTN BlockSize;
3600 UINTN NumberOfBlocks;
3601
3602 HandleBuffer = NULL;
3603
3604 //
3605 // Get all FVB handles.
3606 //
3607 Status = GetFvbCountAndBuffer (&HandleCount, &HandleBuffer);
3608 if (EFI_ERROR (Status)) {
3609 return EFI_NOT_FOUND;
3610 }
3611
3612 //
3613 // Get the FVB to access variable store.
3614 //
3615 Fvb = NULL;
3616 for (Index = 0; Index < HandleCount; Index += 1, Status = EFI_NOT_FOUND, Fvb = NULL) {
3617 Status = GetFvbByHandle (HandleBuffer[Index], &Fvb);
3618 if (EFI_ERROR (Status)) {
3619 Status = EFI_NOT_FOUND;
3620 break;
3621 }
3622
3623 //
3624 // Ensure this FVB protocol supported Write operation.
3625 //
3626 Status = Fvb->GetAttributes (Fvb, &Attributes);
3627 if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {
3628 continue;
3629 }
3630
3631 //
3632 // Compare the address and select the right one.
3633 //
3634 Status = Fvb->GetPhysicalAddress (Fvb, &FvbBaseAddress);
3635 if (EFI_ERROR (Status)) {
3636 continue;
3637 }
3638
3639 //
3640 // Assume one FVB has one type of BlockSize.
3641 //
3642 Status = Fvb->GetBlockSize (Fvb, 0, &BlockSize, &NumberOfBlocks);
3643 if (EFI_ERROR (Status)) {
3644 continue;
3645 }
3646
3647 if ((Address >= FvbBaseAddress) && (Address < (FvbBaseAddress + BlockSize * NumberOfBlocks))) {
3648 if (FvbHandle != NULL) {
3649 *FvbHandle = HandleBuffer[Index];
3650 }
3651 if (FvbProtocol != NULL) {
3652 *FvbProtocol = Fvb;
3653 }
3654 Status = EFI_SUCCESS;
3655 break;
3656 }
3657 }
3658 FreePool (HandleBuffer);
3659
3660 if (Fvb == NULL) {
3661 Status = EFI_NOT_FOUND;
3662 }
3663
3664 return Status;
3665 }
3666