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