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