]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c
1. Remove “Force clear PK” feature in AuthVarialbe driver.
[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 - 2012, 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 Find the variable in the specified variable store.
720
721 @param[in] VariableName Name of the variable to be found
722 @param[in] VendorGuid Vendor GUID to be found.
723 @param[in] IgnoreRtAttribute Ignore RUNTIME_ACCESS attribute when searching variable.
724 @param[in, out] PtrTrack Variable Track Pointer structure that contains Variable Information.
725
726 @retval EFI_SUCCESS Variable found successfully
727 @retval EFI_NOT_FOUND Variable not found
728 **/
729 EFI_STATUS
730 FindVariableEx (
731 IN CHAR16 *VariableName,
732 IN EFI_GUID *VendorGuid,
733 IN BOOLEAN IgnoreRtAttribute,
734 IN OUT VARIABLE_POINTER_TRACK *PtrTrack
735 )
736 {
737 VARIABLE_HEADER *InDeletedVariable;
738 VOID *Point;
739
740 //
741 // Find the variable by walk through HOB, volatile and non-volatile variable store.
742 //
743 InDeletedVariable = NULL;
744
745 for ( PtrTrack->CurrPtr = PtrTrack->StartPtr
746 ; (PtrTrack->CurrPtr < PtrTrack->EndPtr) && IsValidVariableHeader (PtrTrack->CurrPtr)
747 ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr)
748 ) {
749 if (PtrTrack->CurrPtr->State == VAR_ADDED ||
750 PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)
751 ) {
752 if (IgnoreRtAttribute || !AtRuntime () || ((PtrTrack->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
753 if (VariableName[0] == 0) {
754 if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
755 InDeletedVariable = PtrTrack->CurrPtr;
756 } else {
757 return EFI_SUCCESS;
758 }
759 } else {
760 if (CompareGuid (VendorGuid, &PtrTrack->CurrPtr->VendorGuid)) {
761 Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr);
762
763 ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0);
764 if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) {
765 if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
766 InDeletedVariable = PtrTrack->CurrPtr;
767 } else {
768 return EFI_SUCCESS;
769 }
770 }
771 }
772 }
773 }
774 }
775 }
776
777 PtrTrack->CurrPtr = InDeletedVariable;
778 return (PtrTrack->CurrPtr == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS;
779 }
780
781
782 /**
783 Finds variable in storage blocks of volatile and non-volatile storage areas.
784
785 This code finds variable in storage blocks of volatile and non-volatile storage areas.
786 If VariableName is an empty string, then we just return the first
787 qualified variable without comparing VariableName and VendorGuid.
788 If IgnoreRtAttribute is TRUE, then we ignore the EFI_VARIABLE_RUNTIME_ACCESS Attribute
789 when searching existing variable, only VariableName and VendorGuid are compared.
790 Otherwise, variables with EFI_VARIABLE_RUNTIME_ACCESS are not visible at runtime.
791
792 @param[in] VariableName Name of the variable to be found.
793 @param[in] VendorGuid Vendor GUID to be found.
794 @param[out] PtrTrack VARIABLE_POINTER_TRACK structure for output,
795 including the range searched and the target position.
796 @param[in] Global Pointer to VARIABLE_GLOBAL structure, including
797 base of volatile variable storage area, base of
798 NV variable storage area, and a lock.
799 @param[in] IgnoreRtAttribute Ignore RUNTIME_ACCESS attribute when searching variable.
800
801 @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while
802 VendorGuid is NULL.
803 @retval EFI_SUCCESS Variable successfully found.
804 @retval EFI_NOT_FOUND Variable not found
805
806 **/
807 EFI_STATUS
808 FindVariable (
809 IN CHAR16 *VariableName,
810 IN EFI_GUID *VendorGuid,
811 OUT VARIABLE_POINTER_TRACK *PtrTrack,
812 IN VARIABLE_GLOBAL *Global,
813 IN BOOLEAN IgnoreRtAttribute
814 )
815 {
816 EFI_STATUS Status;
817 VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
818 VARIABLE_STORE_TYPE Type;
819
820 if (VariableName[0] != 0 && VendorGuid == NULL) {
821 return EFI_INVALID_PARAMETER;
822 }
823
824 //
825 // 0: Volatile, 1: HOB, 2: Non-Volatile.
826 // The index and attributes mapping must be kept in this order as RuntimeServiceGetNextVariableName
827 // make use of this mapping to implement search algorithm.
828 //
829 VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) Global->VolatileVariableBase;
830 VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) Global->HobVariableBase;
831 VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
832
833 //
834 // Find the variable by walk through HOB, volatile and non-volatile variable store.
835 //
836 for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
837 if (VariableStoreHeader[Type] == NULL) {
838 continue;
839 }
840
841 PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader[Type]);
842 PtrTrack->EndPtr = GetEndPointer (VariableStoreHeader[Type]);
843 PtrTrack->Volatile = (BOOLEAN) (Type == VariableStoreTypeVolatile);
844
845 Status = FindVariableEx (VariableName, VendorGuid, IgnoreRtAttribute, PtrTrack);
846 if (!EFI_ERROR (Status)) {
847 return Status;
848 }
849 }
850 return EFI_NOT_FOUND;
851 }
852
853 /**
854 Get index from supported language codes according to language string.
855
856 This code is used to get corresponding index in supported language codes. It can handle
857 RFC4646 and ISO639 language tags.
858 In ISO639 language tags, take 3-characters as a delimitation to find matched string and calculate the index.
859 In RFC4646 language tags, take semicolon as a delimitation to find matched string and calculate the index.
860
861 For example:
862 SupportedLang = "engfraengfra"
863 Lang = "eng"
864 Iso639Language = TRUE
865 The return value is "0".
866 Another example:
867 SupportedLang = "en;fr;en-US;fr-FR"
868 Lang = "fr-FR"
869 Iso639Language = FALSE
870 The return value is "3".
871
872 @param SupportedLang Platform supported language codes.
873 @param Lang Configured language.
874 @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
875
876 @retval The index of language in the language codes.
877
878 **/
879 UINTN
880 GetIndexFromSupportedLangCodes(
881 IN CHAR8 *SupportedLang,
882 IN CHAR8 *Lang,
883 IN BOOLEAN Iso639Language
884 )
885 {
886 UINTN Index;
887 UINTN CompareLength;
888 UINTN LanguageLength;
889
890 if (Iso639Language) {
891 CompareLength = ISO_639_2_ENTRY_SIZE;
892 for (Index = 0; Index < AsciiStrLen (SupportedLang); Index += CompareLength) {
893 if (AsciiStrnCmp (Lang, SupportedLang + Index, CompareLength) == 0) {
894 //
895 // Successfully find the index of Lang string in SupportedLang string.
896 //
897 Index = Index / CompareLength;
898 return Index;
899 }
900 }
901 ASSERT (FALSE);
902 return 0;
903 } else {
904 //
905 // Compare RFC4646 language code
906 //
907 Index = 0;
908 for (LanguageLength = 0; Lang[LanguageLength] != '\0'; LanguageLength++);
909
910 for (Index = 0; *SupportedLang != '\0'; Index++, SupportedLang += CompareLength) {
911 //
912 // Skip ';' characters in SupportedLang
913 //
914 for (; *SupportedLang != '\0' && *SupportedLang == ';'; SupportedLang++);
915 //
916 // Determine the length of the next language code in SupportedLang
917 //
918 for (CompareLength = 0; SupportedLang[CompareLength] != '\0' && SupportedLang[CompareLength] != ';'; CompareLength++);
919
920 if ((CompareLength == LanguageLength) &&
921 (AsciiStrnCmp (Lang, SupportedLang, CompareLength) == 0)) {
922 //
923 // Successfully find the index of Lang string in SupportedLang string.
924 //
925 return Index;
926 }
927 }
928 ASSERT (FALSE);
929 return 0;
930 }
931 }
932
933 /**
934 Get language string from supported language codes according to index.
935
936 This code is used to get corresponding language strings in supported language codes. It can handle
937 RFC4646 and ISO639 language tags.
938 In ISO639 language tags, take 3-characters as a delimitation. Find language string according to the index.
939 In RFC4646 language tags, take semicolon as a delimitation. Find language string according to the index.
940
941 For example:
942 SupportedLang = "engfraengfra"
943 Index = "1"
944 Iso639Language = TRUE
945 The return value is "fra".
946 Another example:
947 SupportedLang = "en;fr;en-US;fr-FR"
948 Index = "1"
949 Iso639Language = FALSE
950 The return value is "fr".
951
952 @param SupportedLang Platform supported language codes.
953 @param Index The index in supported language codes.
954 @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
955
956 @retval The language string in the language codes.
957
958 **/
959 CHAR8 *
960 GetLangFromSupportedLangCodes (
961 IN CHAR8 *SupportedLang,
962 IN UINTN Index,
963 IN BOOLEAN Iso639Language
964 )
965 {
966 UINTN SubIndex;
967 UINTN CompareLength;
968 CHAR8 *Supported;
969
970 SubIndex = 0;
971 Supported = SupportedLang;
972 if (Iso639Language) {
973 //
974 // According to the index of Lang string in SupportedLang string to get the language.
975 // This code will be invoked in RUNTIME, therefore there is not a memory allocate/free operation.
976 // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.
977 //
978 CompareLength = ISO_639_2_ENTRY_SIZE;
979 mVariableModuleGlobal->Lang[CompareLength] = '\0';
980 return CopyMem (mVariableModuleGlobal->Lang, SupportedLang + Index * CompareLength, CompareLength);
981
982 } else {
983 while (TRUE) {
984 //
985 // Take semicolon as delimitation, sequentially traverse supported language codes.
986 //
987 for (CompareLength = 0; *Supported != ';' && *Supported != '\0'; CompareLength++) {
988 Supported++;
989 }
990 if ((*Supported == '\0') && (SubIndex != Index)) {
991 //
992 // Have completed the traverse, but not find corrsponding string.
993 // This case is not allowed to happen.
994 //
995 ASSERT(FALSE);
996 return NULL;
997 }
998 if (SubIndex == Index) {
999 //
1000 // According to the index of Lang string in SupportedLang string to get the language.
1001 // As this code will be invoked in RUNTIME, therefore there is not memory allocate/free operation.
1002 // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.
1003 //
1004 mVariableModuleGlobal->PlatformLang[CompareLength] = '\0';
1005 return CopyMem (mVariableModuleGlobal->PlatformLang, Supported - CompareLength, CompareLength);
1006 }
1007 SubIndex++;
1008
1009 //
1010 // Skip ';' characters in Supported
1011 //
1012 for (; *Supported != '\0' && *Supported == ';'; Supported++);
1013 }
1014 }
1015 }
1016
1017 /**
1018 Returns a pointer to an allocated buffer that contains the best matching language
1019 from a set of supported languages.
1020
1021 This function supports both ISO 639-2 and RFC 4646 language codes, but language
1022 code types may not be mixed in a single call to this function. This function
1023 supports a variable argument list that allows the caller to pass in a prioritized
1024 list of language codes to test against all the language codes in SupportedLanguages.
1025
1026 If SupportedLanguages is NULL, then ASSERT().
1027
1028 @param[in] SupportedLanguages A pointer to a Null-terminated ASCII string that
1029 contains a set of language codes in the format
1030 specified by Iso639Language.
1031 @param[in] Iso639Language If TRUE, then all language codes are assumed to be
1032 in ISO 639-2 format. If FALSE, then all language
1033 codes are assumed to be in RFC 4646 language format
1034 @param[in] ... A variable argument list that contains pointers to
1035 Null-terminated ASCII strings that contain one or more
1036 language codes in the format specified by Iso639Language.
1037 The first language code from each of these language
1038 code lists is used to determine if it is an exact or
1039 close match to any of the language codes in
1040 SupportedLanguages. Close matches only apply to RFC 4646
1041 language codes, and the matching algorithm from RFC 4647
1042 is used to determine if a close match is present. If
1043 an exact or close match is found, then the matching
1044 language code from SupportedLanguages is returned. If
1045 no matches are found, then the next variable argument
1046 parameter is evaluated. The variable argument list
1047 is terminated by a NULL.
1048
1049 @retval NULL The best matching language could not be found in SupportedLanguages.
1050 @retval NULL There are not enough resources available to return the best matching
1051 language.
1052 @retval Other A pointer to a Null-terminated ASCII string that is the best matching
1053 language in SupportedLanguages.
1054
1055 **/
1056 CHAR8 *
1057 EFIAPI
1058 VariableGetBestLanguage (
1059 IN CONST CHAR8 *SupportedLanguages,
1060 IN BOOLEAN Iso639Language,
1061 ...
1062 )
1063 {
1064 VA_LIST Args;
1065 CHAR8 *Language;
1066 UINTN CompareLength;
1067 UINTN LanguageLength;
1068 CONST CHAR8 *Supported;
1069 CHAR8 *Buffer;
1070
1071 if (SupportedLanguages == NULL) {
1072 return NULL;
1073 }
1074
1075 VA_START (Args, Iso639Language);
1076 while ((Language = VA_ARG (Args, CHAR8 *)) != NULL) {
1077 //
1078 // Default to ISO 639-2 mode
1079 //
1080 CompareLength = 3;
1081 LanguageLength = MIN (3, AsciiStrLen (Language));
1082
1083 //
1084 // If in RFC 4646 mode, then determine the length of the first RFC 4646 language code in Language
1085 //
1086 if (!Iso639Language) {
1087 for (LanguageLength = 0; Language[LanguageLength] != 0 && Language[LanguageLength] != ';'; LanguageLength++);
1088 }
1089
1090 //
1091 // Trim back the length of Language used until it is empty
1092 //
1093 while (LanguageLength > 0) {
1094 //
1095 // Loop through all language codes in SupportedLanguages
1096 //
1097 for (Supported = SupportedLanguages; *Supported != '\0'; Supported += CompareLength) {
1098 //
1099 // In RFC 4646 mode, then Loop through all language codes in SupportedLanguages
1100 //
1101 if (!Iso639Language) {
1102 //
1103 // Skip ';' characters in Supported
1104 //
1105 for (; *Supported != '\0' && *Supported == ';'; Supported++);
1106 //
1107 // Determine the length of the next language code in Supported
1108 //
1109 for (CompareLength = 0; Supported[CompareLength] != 0 && Supported[CompareLength] != ';'; CompareLength++);
1110 //
1111 // If Language is longer than the Supported, then skip to the next language
1112 //
1113 if (LanguageLength > CompareLength) {
1114 continue;
1115 }
1116 }
1117 //
1118 // See if the first LanguageLength characters in Supported match Language
1119 //
1120 if (AsciiStrnCmp (Supported, Language, LanguageLength) == 0) {
1121 VA_END (Args);
1122
1123 Buffer = Iso639Language ? mVariableModuleGlobal->Lang : mVariableModuleGlobal->PlatformLang;
1124 Buffer[CompareLength] = '\0';
1125 return CopyMem (Buffer, Supported, CompareLength);
1126 }
1127 }
1128
1129 if (Iso639Language) {
1130 //
1131 // If ISO 639 mode, then each language can only be tested once
1132 //
1133 LanguageLength = 0;
1134 } else {
1135 //
1136 // If RFC 4646 mode, then trim Language from the right to the next '-' character
1137 //
1138 for (LanguageLength--; LanguageLength > 0 && Language[LanguageLength] != '-'; LanguageLength--);
1139 }
1140 }
1141 }
1142 VA_END (Args);
1143
1144 //
1145 // No matches were found
1146 //
1147 return NULL;
1148 }
1149
1150 /**
1151 Hook the operations in PlatformLangCodes, LangCodes, PlatformLang and Lang.
1152
1153 When setting Lang/LangCodes, simultaneously update PlatformLang/PlatformLangCodes.
1154
1155 According to UEFI spec, PlatformLangCodes/LangCodes are only set once in firmware initialization,
1156 and are read-only. Therefore, in variable driver, only store the original value for other use.
1157
1158 @param[in] VariableName Name of variable.
1159
1160 @param[in] Data Variable data.
1161
1162 @param[in] DataSize Size of data. 0 means delete.
1163
1164 **/
1165 VOID
1166 AutoUpdateLangVariable (
1167 IN CHAR16 *VariableName,
1168 IN VOID *Data,
1169 IN UINTN DataSize
1170 )
1171 {
1172 EFI_STATUS Status;
1173 CHAR8 *BestPlatformLang;
1174 CHAR8 *BestLang;
1175 UINTN Index;
1176 UINT32 Attributes;
1177 VARIABLE_POINTER_TRACK Variable;
1178 BOOLEAN SetLanguageCodes;
1179
1180 //
1181 // Don't do updates for delete operation
1182 //
1183 if (DataSize == 0) {
1184 return;
1185 }
1186
1187 SetLanguageCodes = FALSE;
1188
1189 if (StrCmp (VariableName, L"PlatformLangCodes") == 0) {
1190 //
1191 // PlatformLangCodes is a volatile variable, so it can not be updated at runtime.
1192 //
1193 if (AtRuntime ()) {
1194 return;
1195 }
1196
1197 SetLanguageCodes = TRUE;
1198
1199 //
1200 // According to UEFI spec, PlatformLangCodes is only set once in firmware initialization, and is read-only
1201 // Therefore, in variable driver, only store the original value for other use.
1202 //
1203 if (mVariableModuleGlobal->PlatformLangCodes != NULL) {
1204 FreePool (mVariableModuleGlobal->PlatformLangCodes);
1205 }
1206 mVariableModuleGlobal->PlatformLangCodes = AllocateRuntimeCopyPool (DataSize, Data);
1207 ASSERT (mVariableModuleGlobal->PlatformLangCodes != NULL);
1208
1209 //
1210 // PlatformLang holds a single language from PlatformLangCodes,
1211 // so the size of PlatformLangCodes is enough for the PlatformLang.
1212 //
1213 if (mVariableModuleGlobal->PlatformLang != NULL) {
1214 FreePool (mVariableModuleGlobal->PlatformLang);
1215 }
1216 mVariableModuleGlobal->PlatformLang = AllocateRuntimePool (DataSize);
1217 ASSERT (mVariableModuleGlobal->PlatformLang != NULL);
1218
1219 } else if (StrCmp (VariableName, L"LangCodes") == 0) {
1220 //
1221 // LangCodes is a volatile variable, so it can not be updated at runtime.
1222 //
1223 if (AtRuntime ()) {
1224 return;
1225 }
1226
1227 SetLanguageCodes = TRUE;
1228
1229 //
1230 // According to UEFI spec, LangCodes is only set once in firmware initialization, and is read-only
1231 // Therefore, in variable driver, only store the original value for other use.
1232 //
1233 if (mVariableModuleGlobal->LangCodes != NULL) {
1234 FreePool (mVariableModuleGlobal->LangCodes);
1235 }
1236 mVariableModuleGlobal->LangCodes = AllocateRuntimeCopyPool (DataSize, Data);
1237 ASSERT (mVariableModuleGlobal->LangCodes != NULL);
1238 }
1239
1240 if (SetLanguageCodes
1241 && (mVariableModuleGlobal->PlatformLangCodes != NULL)
1242 && (mVariableModuleGlobal->LangCodes != NULL)) {
1243 //
1244 // Update Lang if PlatformLang is already set
1245 // Update PlatformLang if Lang is already set
1246 //
1247 Status = FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1248 if (!EFI_ERROR (Status)) {
1249 //
1250 // Update Lang
1251 //
1252 VariableName = L"PlatformLang";
1253 Data = GetVariableDataPtr (Variable.CurrPtr);
1254 DataSize = Variable.CurrPtr->DataSize;
1255 } else {
1256 Status = FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1257 if (!EFI_ERROR (Status)) {
1258 //
1259 // Update PlatformLang
1260 //
1261 VariableName = L"Lang";
1262 Data = GetVariableDataPtr (Variable.CurrPtr);
1263 DataSize = Variable.CurrPtr->DataSize;
1264 } else {
1265 //
1266 // Neither PlatformLang nor Lang is set, directly return
1267 //
1268 return;
1269 }
1270 }
1271 }
1272
1273 //
1274 // According to UEFI spec, "Lang" and "PlatformLang" is NV|BS|RT attributions.
1275 //
1276 Attributes = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS;
1277
1278 if (StrCmp (VariableName, L"PlatformLang") == 0) {
1279 //
1280 // Update Lang when PlatformLangCodes/LangCodes were set.
1281 //
1282 if ((mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) {
1283 //
1284 // When setting PlatformLang, firstly get most matched language string from supported language codes.
1285 //
1286 BestPlatformLang = VariableGetBestLanguage (mVariableModuleGlobal->PlatformLangCodes, FALSE, Data, NULL);
1287 if (BestPlatformLang != NULL) {
1288 //
1289 // Get the corresponding index in language codes.
1290 //
1291 Index = GetIndexFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, BestPlatformLang, FALSE);
1292
1293 //
1294 // Get the corresponding ISO639 language tag according to RFC4646 language tag.
1295 //
1296 BestLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, Index, TRUE);
1297
1298 //
1299 // Successfully convert PlatformLang to Lang, and set the BestLang value into Lang variable simultaneously.
1300 //
1301 FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1302
1303 Status = UpdateVariable (L"Lang", &gEfiGlobalVariableGuid, BestLang,
1304 ISO_639_2_ENTRY_SIZE + 1, Attributes, 0, 0, &Variable, NULL);
1305
1306 DEBUG ((EFI_D_INFO, "Variable Driver Auto Update PlatformLang, PlatformLang:%a, Lang:%a\n", BestPlatformLang, BestLang));
1307
1308 ASSERT_EFI_ERROR(Status);
1309 }
1310 }
1311
1312 } else if (StrCmp (VariableName, L"Lang") == 0) {
1313 //
1314 // Update PlatformLang when PlatformLangCodes/LangCodes were set.
1315 //
1316 if ((mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) {
1317 //
1318 // When setting Lang, firstly get most matched language string from supported language codes.
1319 //
1320 BestLang = VariableGetBestLanguage (mVariableModuleGlobal->LangCodes, TRUE, Data, NULL);
1321 if (BestLang != NULL) {
1322 //
1323 // Get the corresponding index in language codes.
1324 //
1325 Index = GetIndexFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, BestLang, TRUE);
1326
1327 //
1328 // Get the corresponding RFC4646 language tag according to ISO639 language tag.
1329 //
1330 BestPlatformLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, Index, FALSE);
1331
1332 //
1333 // Successfully convert Lang to PlatformLang, and set the BestPlatformLang value into PlatformLang variable simultaneously.
1334 //
1335 FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1336
1337 Status = UpdateVariable (L"PlatformLang", &gEfiGlobalVariableGuid, BestPlatformLang,
1338 AsciiStrSize (BestPlatformLang), Attributes, 0, 0, &Variable, NULL);
1339
1340 DEBUG ((EFI_D_INFO, "Variable Driver Auto Update Lang, Lang:%a, PlatformLang:%a\n", BestLang, BestPlatformLang));
1341 ASSERT_EFI_ERROR (Status);
1342 }
1343 }
1344 }
1345 }
1346
1347 /**
1348 Update the variable region with Variable information. If EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is set,
1349 index of associated public key is needed.
1350
1351 @param[in] VariableName Name of variable.
1352 @param[in] VendorGuid Guid of variable.
1353 @param[in] Data Variable data.
1354 @param[in] DataSize Size of data. 0 means delete.
1355 @param[in] Attributes Attributes of the variable.
1356 @param[in] KeyIndex Index of associated public key.
1357 @param[in] MonotonicCount Value of associated monotonic count.
1358 @param[in] CacheVariable The variable information which is used to keep track of variable usage.
1359 @param[in] TimeStamp Value of associated TimeStamp.
1360
1361 @retval EFI_SUCCESS The update operation is success.
1362 @retval EFI_OUT_OF_RESOURCES Variable region is full, can not write other data into this region.
1363
1364 **/
1365 EFI_STATUS
1366 UpdateVariable (
1367 IN CHAR16 *VariableName,
1368 IN EFI_GUID *VendorGuid,
1369 IN VOID *Data,
1370 IN UINTN DataSize,
1371 IN UINT32 Attributes OPTIONAL,
1372 IN UINT32 KeyIndex OPTIONAL,
1373 IN UINT64 MonotonicCount OPTIONAL,
1374 IN VARIABLE_POINTER_TRACK *CacheVariable,
1375 IN EFI_TIME *TimeStamp OPTIONAL
1376 )
1377 {
1378 EFI_STATUS Status;
1379 VARIABLE_HEADER *NextVariable;
1380 UINTN ScratchSize;
1381 UINTN ScratchDataSize;
1382 UINTN NonVolatileVarableStoreSize;
1383 UINTN VarNameOffset;
1384 UINTN VarDataOffset;
1385 UINTN VarNameSize;
1386 UINTN VarSize;
1387 BOOLEAN Volatile;
1388 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
1389 UINT8 State;
1390 BOOLEAN Reclaimed;
1391 VARIABLE_POINTER_TRACK *Variable;
1392 VARIABLE_POINTER_TRACK NvVariable;
1393 VARIABLE_STORE_HEADER *VariableStoreHeader;
1394 UINTN CacheOffset;
1395 UINTN BufSize;
1396 UINTN DataOffset;
1397 UINTN RevBufSize;
1398
1399 if (mVariableModuleGlobal->FvbInstance == NULL) {
1400 //
1401 // The FVB protocol is not installed, so the EFI_VARIABLE_WRITE_ARCH_PROTOCOL is not installed.
1402 //
1403 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
1404 //
1405 // Trying to update NV variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
1406 //
1407 return EFI_NOT_AVAILABLE_YET;
1408 } else if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) {
1409 //
1410 // Trying to update volatile authenticated variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
1411 // The authenticated variable perhaps is not initialized, just return here.
1412 //
1413 return EFI_NOT_AVAILABLE_YET;
1414 }
1415 }
1416
1417 if ((CacheVariable->CurrPtr == NULL) || CacheVariable->Volatile) {
1418 Variable = CacheVariable;
1419 } else {
1420 //
1421 // Update/Delete existing NV variable.
1422 // CacheVariable points to the variable in the memory copy of Flash area
1423 // Now let Variable points to the same variable in Flash area.
1424 //
1425 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);
1426 Variable = &NvVariable;
1427 Variable->StartPtr = GetStartPointer (VariableStoreHeader);
1428 Variable->EndPtr = GetEndPointer (VariableStoreHeader);
1429 Variable->CurrPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr));
1430 Variable->Volatile = FALSE;
1431 }
1432
1433 Fvb = mVariableModuleGlobal->FvbInstance;
1434 Reclaimed = FALSE;
1435
1436 //
1437 // Tricky part: Use scratch data area at the end of volatile variable store
1438 // as a temporary storage.
1439 //
1440 NextVariable = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase));
1441 ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));
1442 ScratchDataSize = ScratchSize - sizeof (VARIABLE_HEADER) - StrSize (VariableName) - GET_PAD_SIZE (StrSize (VariableName));
1443
1444 if (Variable->CurrPtr != NULL) {
1445 //
1446 // Update/Delete existing variable.
1447 //
1448 if (AtRuntime ()) {
1449 //
1450 // If AtRuntime and the variable is Volatile and Runtime Access,
1451 // the volatile is ReadOnly, and SetVariable should be aborted and
1452 // return EFI_WRITE_PROTECTED.
1453 //
1454 if (Variable->Volatile) {
1455 Status = EFI_WRITE_PROTECTED;
1456 goto Done;
1457 }
1458 //
1459 // Only variable that have NV attributes can be updated/deleted in Runtime.
1460 //
1461 if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
1462 Status = EFI_INVALID_PARAMETER;
1463 goto Done;
1464 }
1465
1466 //
1467 // Only variable that have RT attributes can be updated/deleted in Runtime.
1468 //
1469 if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) {
1470 Status = EFI_INVALID_PARAMETER;
1471 goto Done;
1472 }
1473 }
1474
1475 //
1476 // Setting a data variable with no access, or zero DataSize attributes
1477 // causes it to be deleted.
1478 // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will
1479 // not delete the variable.
1480 //
1481 if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0))|| ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) {
1482 State = Variable->CurrPtr->State;
1483 State &= VAR_DELETED;
1484
1485 Status = UpdateVariableStore (
1486 &mVariableModuleGlobal->VariableGlobal,
1487 Variable->Volatile,
1488 FALSE,
1489 Fvb,
1490 (UINTN) &Variable->CurrPtr->State,
1491 sizeof (UINT8),
1492 &State
1493 );
1494 if (!EFI_ERROR (Status)) {
1495 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE);
1496 if (!Variable->Volatile) {
1497 CacheVariable->CurrPtr->State = State;
1498 }
1499 }
1500 goto Done;
1501 }
1502 //
1503 // If the variable is marked valid, and the same data has been passed in,
1504 // then return to the caller immediately.
1505 //
1506 if (DataSizeOfVariable (Variable->CurrPtr) == DataSize &&
1507 (CompareMem (Data, GetVariableDataPtr (Variable->CurrPtr), DataSize) == 0) &&
1508 ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) &&
1509 (TimeStamp == NULL)) {
1510 //
1511 // Variable content unchanged and no need to update timestamp, just return.
1512 //
1513 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);
1514 Status = EFI_SUCCESS;
1515 goto Done;
1516 } else if ((Variable->CurrPtr->State == VAR_ADDED) ||
1517 (Variable->CurrPtr->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION))) {
1518
1519 //
1520 // EFI_VARIABLE_APPEND_WRITE attribute only effects for existing variable
1521 //
1522 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) {
1523 //
1524 // Cache the previous variable data into StorageArea.
1525 //
1526 DataOffset = sizeof (VARIABLE_HEADER) + Variable->CurrPtr->NameSize + GET_PAD_SIZE (Variable->CurrPtr->NameSize);
1527 CopyMem (mStorageArea, (UINT8*)((UINTN) Variable->CurrPtr + DataOffset), Variable->CurrPtr->DataSize);
1528
1529 if (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) ||
1530 (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0))) {
1531 //
1532 // For variables with the GUID EFI_IMAGE_SECURITY_DATABASE_GUID (i.e. where the data
1533 // buffer is formatted as EFI_SIGNATURE_LIST), the driver shall not perform an append of
1534 // EFI_SIGNATURE_DATA values that are already part of the existing variable value.
1535 //
1536 BufSize = AppendSignatureList (mStorageArea, Variable->CurrPtr->DataSize, Data, DataSize);
1537 if (BufSize == Variable->CurrPtr->DataSize) {
1538 if ((TimeStamp == NULL) || CompareTimeStamp (TimeStamp, &Variable->CurrPtr->TimeStamp)) {
1539 //
1540 // New EFI_SIGNATURE_DATA is not found and timestamp is not later
1541 // than current timestamp, return EFI_SUCCESS directly.
1542 //
1543 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);
1544 Status = EFI_SUCCESS;
1545 goto Done;
1546 }
1547 }
1548 } else {
1549 //
1550 // For other Variables, append the new data to the end of previous data.
1551 //
1552 CopyMem ((UINT8*)((UINTN) mStorageArea + Variable->CurrPtr->DataSize), Data, DataSize);
1553 BufSize = Variable->CurrPtr->DataSize + DataSize;
1554 }
1555
1556 RevBufSize = MIN (PcdGet32 (PcdMaxVariableSize), ScratchDataSize);
1557 if (BufSize > RevBufSize) {
1558 //
1559 // If variable size (previous + current) is bigger than reserved buffer in runtime,
1560 // return EFI_OUT_OF_RESOURCES.
1561 //
1562 return EFI_OUT_OF_RESOURCES;
1563 }
1564
1565 //
1566 // Override Data and DataSize which are used for combined data area including previous and new data.
1567 //
1568 Data = mStorageArea;
1569 DataSize = BufSize;
1570 }
1571
1572 //
1573 // Mark the old variable as in delete transition.
1574 //
1575 State = Variable->CurrPtr->State;
1576 State &= VAR_IN_DELETED_TRANSITION;
1577
1578 Status = UpdateVariableStore (
1579 &mVariableModuleGlobal->VariableGlobal,
1580 Variable->Volatile,
1581 FALSE,
1582 Fvb,
1583 (UINTN) &Variable->CurrPtr->State,
1584 sizeof (UINT8),
1585 &State
1586 );
1587 if (EFI_ERROR (Status)) {
1588 goto Done;
1589 }
1590 if (!Variable->Volatile) {
1591 CacheVariable->CurrPtr->State = State;
1592 }
1593 }
1594 } else {
1595 //
1596 // Not found existing variable. Create a new variable.
1597 //
1598
1599 if ((DataSize == 0) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0)) {
1600 Status = EFI_SUCCESS;
1601 goto Done;
1602 }
1603
1604 //
1605 // Make sure we are trying to create a new variable.
1606 // Setting a data variable with zero DataSize or no access attributes means to delete it.
1607 //
1608 if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) {
1609 Status = EFI_NOT_FOUND;
1610 goto Done;
1611 }
1612
1613 //
1614 // Only variable have NV|RT attribute can be created in Runtime.
1615 //
1616 if (AtRuntime () &&
1617 (((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0))) {
1618 Status = EFI_INVALID_PARAMETER;
1619 goto Done;
1620 }
1621 }
1622
1623 //
1624 // Function part - create a new variable and copy the data.
1625 // Both update a variable and create a variable will come here.
1626
1627 SetMem (NextVariable, ScratchSize, 0xff);
1628
1629 NextVariable->StartId = VARIABLE_DATA;
1630 //
1631 // NextVariable->State = VAR_ADDED;
1632 //
1633 NextVariable->Reserved = 0;
1634 NextVariable->PubKeyIndex = KeyIndex;
1635 NextVariable->MonotonicCount = MonotonicCount;
1636 ZeroMem (&NextVariable->TimeStamp, sizeof (EFI_TIME));
1637
1638 if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&
1639 (TimeStamp != NULL)) {
1640 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) {
1641 CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
1642 } else {
1643 //
1644 // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only
1645 // when the new TimeStamp value is later than the current timestamp associated
1646 // with the variable, we need associate the new timestamp with the updated value.
1647 //
1648 if (Variable->CurrPtr != NULL) {
1649 if (CompareTimeStamp (&Variable->CurrPtr->TimeStamp, TimeStamp)) {
1650 CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
1651 }
1652 }
1653 }
1654 }
1655
1656 //
1657 // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned
1658 // Attributes bitmask parameter of a GetVariable() call.
1659 //
1660 NextVariable->Attributes = Attributes & (~EFI_VARIABLE_APPEND_WRITE);
1661
1662 VarNameOffset = sizeof (VARIABLE_HEADER);
1663 VarNameSize = StrSize (VariableName);
1664 CopyMem (
1665 (UINT8 *) ((UINTN) NextVariable + VarNameOffset),
1666 VariableName,
1667 VarNameSize
1668 );
1669 VarDataOffset = VarNameOffset + VarNameSize + GET_PAD_SIZE (VarNameSize);
1670 CopyMem (
1671 (UINT8 *) ((UINTN) NextVariable + VarDataOffset),
1672 Data,
1673 DataSize
1674 );
1675 CopyMem (&NextVariable->VendorGuid, VendorGuid, sizeof (EFI_GUID));
1676 //
1677 // There will be pad bytes after Data, the NextVariable->NameSize and
1678 // NextVariable->DataSize should not include pad size so that variable
1679 // service can get actual size in GetVariable.
1680 //
1681 NextVariable->NameSize = (UINT32)VarNameSize;
1682 NextVariable->DataSize = (UINT32)DataSize;
1683
1684 //
1685 // The actual size of the variable that stores in storage should
1686 // include pad size.
1687 //
1688 VarSize = VarDataOffset + DataSize + GET_PAD_SIZE (DataSize);
1689 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
1690 //
1691 // Create a nonvolatile variable.
1692 //
1693 Volatile = FALSE;
1694 NonVolatileVarableStoreSize = ((VARIABLE_STORE_HEADER *)(UINTN)(mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase))->Size;
1695 if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)
1696 && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))
1697 || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0)
1698 && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {
1699 if (AtRuntime ()) {
1700 Status = EFI_OUT_OF_RESOURCES;
1701 goto Done;
1702 }
1703 //
1704 // Perform garbage collection & reclaim operation.
1705 //
1706 Status = Reclaim (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
1707 &mVariableModuleGlobal->NonVolatileLastVariableOffset, FALSE, Variable->CurrPtr);
1708 if (EFI_ERROR (Status)) {
1709 goto Done;
1710 }
1711 //
1712 // If still no enough space, return out of resources.
1713 //
1714 if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)
1715 && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))
1716 || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0)
1717 && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {
1718 Status = EFI_OUT_OF_RESOURCES;
1719 goto Done;
1720 }
1721 Reclaimed = TRUE;
1722 }
1723 //
1724 // Four steps
1725 // 1. Write variable header
1726 // 2. Set variable state to header valid
1727 // 3. Write variable data
1728 // 4. Set variable state to valid
1729 //
1730 //
1731 // Step 1:
1732 //
1733 CacheOffset = mVariableModuleGlobal->NonVolatileLastVariableOffset;
1734 Status = UpdateVariableStore (
1735 &mVariableModuleGlobal->VariableGlobal,
1736 FALSE,
1737 TRUE,
1738 Fvb,
1739 mVariableModuleGlobal->NonVolatileLastVariableOffset,
1740 sizeof (VARIABLE_HEADER),
1741 (UINT8 *) NextVariable
1742 );
1743
1744 if (EFI_ERROR (Status)) {
1745 goto Done;
1746 }
1747
1748 //
1749 // Step 2:
1750 //
1751 NextVariable->State = VAR_HEADER_VALID_ONLY;
1752 Status = UpdateVariableStore (
1753 &mVariableModuleGlobal->VariableGlobal,
1754 FALSE,
1755 TRUE,
1756 Fvb,
1757 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
1758 sizeof (UINT8),
1759 &NextVariable->State
1760 );
1761
1762 if (EFI_ERROR (Status)) {
1763 goto Done;
1764 }
1765 //
1766 // Step 3:
1767 //
1768 Status = UpdateVariableStore (
1769 &mVariableModuleGlobal->VariableGlobal,
1770 FALSE,
1771 TRUE,
1772 Fvb,
1773 mVariableModuleGlobal->NonVolatileLastVariableOffset + sizeof (VARIABLE_HEADER),
1774 (UINT32) VarSize - sizeof (VARIABLE_HEADER),
1775 (UINT8 *) NextVariable + sizeof (VARIABLE_HEADER)
1776 );
1777
1778 if (EFI_ERROR (Status)) {
1779 goto Done;
1780 }
1781 //
1782 // Step 4:
1783 //
1784 NextVariable->State = VAR_ADDED;
1785 Status = UpdateVariableStore (
1786 &mVariableModuleGlobal->VariableGlobal,
1787 FALSE,
1788 TRUE,
1789 Fvb,
1790 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
1791 sizeof (UINT8),
1792 &NextVariable->State
1793 );
1794
1795 if (EFI_ERROR (Status)) {
1796 goto Done;
1797 }
1798
1799 mVariableModuleGlobal->NonVolatileLastVariableOffset += HEADER_ALIGN (VarSize);
1800
1801 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
1802 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VarSize);
1803 } else {
1804 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VarSize);
1805 }
1806 //
1807 // update the memory copy of Flash region.
1808 //
1809 CopyMem ((UINT8 *)mNvVariableCache + CacheOffset, (UINT8 *)NextVariable, VarSize);
1810 } else {
1811 //
1812 // Create a volatile variable.
1813 //
1814 Volatile = TRUE;
1815
1816 if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >
1817 ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size) {
1818 //
1819 // Perform garbage collection & reclaim operation.
1820 //
1821 Status = Reclaim (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,
1822 &mVariableModuleGlobal->VolatileLastVariableOffset, TRUE, Variable->CurrPtr);
1823 if (EFI_ERROR (Status)) {
1824 goto Done;
1825 }
1826 //
1827 // If still no enough space, return out of resources.
1828 //
1829 if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >
1830 ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size
1831 ) {
1832 Status = EFI_OUT_OF_RESOURCES;
1833 goto Done;
1834 }
1835 Reclaimed = TRUE;
1836 }
1837
1838 NextVariable->State = VAR_ADDED;
1839 Status = UpdateVariableStore (
1840 &mVariableModuleGlobal->VariableGlobal,
1841 TRUE,
1842 TRUE,
1843 Fvb,
1844 mVariableModuleGlobal->VolatileLastVariableOffset,
1845 (UINT32) VarSize,
1846 (UINT8 *) NextVariable
1847 );
1848
1849 if (EFI_ERROR (Status)) {
1850 goto Done;
1851 }
1852
1853 mVariableModuleGlobal->VolatileLastVariableOffset += HEADER_ALIGN (VarSize);
1854 }
1855
1856 //
1857 // Mark the old variable as deleted.
1858 //
1859 if (!Reclaimed && !EFI_ERROR (Status) && Variable->CurrPtr != NULL) {
1860 State = Variable->CurrPtr->State;
1861 State &= VAR_DELETED;
1862
1863 Status = UpdateVariableStore (
1864 &mVariableModuleGlobal->VariableGlobal,
1865 Variable->Volatile,
1866 FALSE,
1867 Fvb,
1868 (UINTN) &Variable->CurrPtr->State,
1869 sizeof (UINT8),
1870 &State
1871 );
1872 if (!EFI_ERROR (Status) && !Variable->Volatile) {
1873 CacheVariable->CurrPtr->State = State;
1874 }
1875 }
1876
1877 if (!EFI_ERROR (Status)) {
1878 UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);
1879 }
1880
1881 Done:
1882 return Status;
1883 }
1884
1885 /**
1886
1887 This code finds variable in storage blocks (Volatile or Non-Volatile).
1888
1889 @param VariableName Name of Variable to be found.
1890 @param VendorGuid Variable vendor GUID.
1891 @param Attributes Attribute value of the variable found.
1892 @param DataSize Size of Data found. If size is less than the
1893 data, this value contains the required size.
1894 @param Data Data pointer.
1895
1896 @return EFI_INVALID_PARAMETER Invalid parameter.
1897 @return EFI_SUCCESS Find the specified variable.
1898 @return EFI_NOT_FOUND Not found.
1899 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
1900
1901 **/
1902 EFI_STATUS
1903 EFIAPI
1904 VariableServiceGetVariable (
1905 IN CHAR16 *VariableName,
1906 IN EFI_GUID *VendorGuid,
1907 OUT UINT32 *Attributes OPTIONAL,
1908 IN OUT UINTN *DataSize,
1909 OUT VOID *Data
1910 )
1911 {
1912 EFI_STATUS Status;
1913 VARIABLE_POINTER_TRACK Variable;
1914 UINTN VarDataSize;
1915
1916 if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {
1917 return EFI_INVALID_PARAMETER;
1918 }
1919
1920 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
1921
1922 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1923 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
1924 goto Done;
1925 }
1926
1927 //
1928 // Get data size
1929 //
1930 VarDataSize = DataSizeOfVariable (Variable.CurrPtr);
1931 ASSERT (VarDataSize != 0);
1932
1933 if (*DataSize >= VarDataSize) {
1934 if (Data == NULL) {
1935 Status = EFI_INVALID_PARAMETER;
1936 goto Done;
1937 }
1938
1939 CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr), VarDataSize);
1940 if (Attributes != NULL) {
1941 *Attributes = Variable.CurrPtr->Attributes;
1942 }
1943
1944 *DataSize = VarDataSize;
1945 UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);
1946
1947 Status = EFI_SUCCESS;
1948 goto Done;
1949 } else {
1950 *DataSize = VarDataSize;
1951 Status = EFI_BUFFER_TOO_SMALL;
1952 goto Done;
1953 }
1954
1955 Done:
1956 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
1957 return Status;
1958 }
1959
1960
1961
1962 /**
1963
1964 This code Finds the Next available variable.
1965
1966 @param VariableNameSize Size of the variable name.
1967 @param VariableName Pointer to variable name.
1968 @param VendorGuid Variable Vendor Guid.
1969
1970 @return EFI_INVALID_PARAMETER Invalid parameter.
1971 @return EFI_SUCCESS Find the specified variable.
1972 @return EFI_NOT_FOUND Not found.
1973 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
1974
1975 **/
1976 EFI_STATUS
1977 EFIAPI
1978 VariableServiceGetNextVariableName (
1979 IN OUT UINTN *VariableNameSize,
1980 IN OUT CHAR16 *VariableName,
1981 IN OUT EFI_GUID *VendorGuid
1982 )
1983 {
1984 VARIABLE_STORE_TYPE Type;
1985 VARIABLE_POINTER_TRACK Variable;
1986 VARIABLE_POINTER_TRACK VariableInHob;
1987 UINTN VarNameSize;
1988 EFI_STATUS Status;
1989 VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
1990
1991 if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
1992 return EFI_INVALID_PARAMETER;
1993 }
1994
1995 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
1996
1997 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1998 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
1999 goto Done;
2000 }
2001
2002 if (VariableName[0] != 0) {
2003 //
2004 // If variable name is not NULL, get next variable.
2005 //
2006 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2007 }
2008
2009 //
2010 // 0: Volatile, 1: HOB, 2: Non-Volatile.
2011 // The index and attributes mapping must be kept in this order as FindVariable
2012 // makes use of this mapping to implement search algorithm.
2013 //
2014 VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
2015 VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
2016 VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
2017
2018 while (TRUE) {
2019 //
2020 // Switch from Volatile to HOB, to Non-Volatile.
2021 //
2022 while ((Variable.CurrPtr >= Variable.EndPtr) ||
2023 (Variable.CurrPtr == NULL) ||
2024 !IsValidVariableHeader (Variable.CurrPtr)
2025 ) {
2026 //
2027 // Find current storage index
2028 //
2029 for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
2030 if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
2031 break;
2032 }
2033 }
2034 ASSERT (Type < VariableStoreTypeMax);
2035 //
2036 // Switch to next storage
2037 //
2038 for (Type++; Type < VariableStoreTypeMax; Type++) {
2039 if (VariableStoreHeader[Type] != NULL) {
2040 break;
2041 }
2042 }
2043 //
2044 // Capture the case that
2045 // 1. current storage is the last one, or
2046 // 2. no further storage
2047 //
2048 if (Type == VariableStoreTypeMax) {
2049 Status = EFI_NOT_FOUND;
2050 goto Done;
2051 }
2052 Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);
2053 Variable.EndPtr = GetEndPointer (VariableStoreHeader[Type]);
2054 Variable.CurrPtr = Variable.StartPtr;
2055 }
2056
2057 //
2058 // Variable is found
2059 //
2060 if (Variable.CurrPtr->State == VAR_ADDED) {
2061 if ((AtRuntime () && ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) == 0) {
2062
2063 //
2064 // Don't return NV variable when HOB overrides it
2065 //
2066 if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&
2067 (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))
2068 ) {
2069 VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);
2070 VariableInHob.EndPtr = GetEndPointer (VariableStoreHeader[VariableStoreTypeHob]);
2071 Status = FindVariableEx (
2072 GetVariableNamePtr (Variable.CurrPtr),
2073 &Variable.CurrPtr->VendorGuid,
2074 FALSE,
2075 &VariableInHob
2076 );
2077 if (!EFI_ERROR (Status)) {
2078 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2079 continue;
2080 }
2081 }
2082
2083 VarNameSize = NameSizeOfVariable (Variable.CurrPtr);
2084 ASSERT (VarNameSize != 0);
2085
2086 if (VarNameSize <= *VariableNameSize) {
2087 CopyMem (VariableName, GetVariableNamePtr (Variable.CurrPtr), VarNameSize);
2088 CopyMem (VendorGuid, &Variable.CurrPtr->VendorGuid, sizeof (EFI_GUID));
2089 Status = EFI_SUCCESS;
2090 } else {
2091 Status = EFI_BUFFER_TOO_SMALL;
2092 }
2093
2094 *VariableNameSize = VarNameSize;
2095 goto Done;
2096 }
2097 }
2098
2099 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2100 }
2101
2102 Done:
2103 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2104 return Status;
2105 }
2106
2107 /**
2108
2109 This code sets variable in storage blocks (Volatile or Non-Volatile).
2110
2111 @param VariableName Name of Variable to be found.
2112 @param VendorGuid Variable vendor GUID.
2113 @param Attributes Attribute value of the variable found
2114 @param DataSize Size of Data found. If size is less than the
2115 data, this value contains the required size.
2116 @param Data Data pointer.
2117
2118 @return EFI_INVALID_PARAMETER Invalid parameter.
2119 @return EFI_SUCCESS Set successfully.
2120 @return EFI_OUT_OF_RESOURCES Resource not enough to set variable.
2121 @return EFI_NOT_FOUND Not found.
2122 @return EFI_WRITE_PROTECTED Variable is read-only.
2123
2124 **/
2125 EFI_STATUS
2126 EFIAPI
2127 VariableServiceSetVariable (
2128 IN CHAR16 *VariableName,
2129 IN EFI_GUID *VendorGuid,
2130 IN UINT32 Attributes,
2131 IN UINTN DataSize,
2132 IN VOID *Data
2133 )
2134 {
2135 VARIABLE_POINTER_TRACK Variable;
2136 EFI_STATUS Status;
2137 VARIABLE_HEADER *NextVariable;
2138 EFI_PHYSICAL_ADDRESS Point;
2139 UINTN PayloadSize;
2140
2141 //
2142 // Check input parameters.
2143 //
2144 if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {
2145 return EFI_INVALID_PARAMETER;
2146 }
2147
2148 if (DataSize != 0 && Data == NULL) {
2149 return EFI_INVALID_PARAMETER;
2150 }
2151
2152 //
2153 // Make sure if runtime bit is set, boot service bit is set also.
2154 //
2155 if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
2156 return EFI_INVALID_PARAMETER;
2157 }
2158
2159 //
2160 // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute
2161 // cannot be set both.
2162 //
2163 if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)
2164 && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {
2165 return EFI_INVALID_PARAMETER;
2166 }
2167
2168 if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {
2169 if (DataSize < AUTHINFO_SIZE) {
2170 //
2171 // Try to write Authenticated Variable without AuthInfo.
2172 //
2173 return EFI_SECURITY_VIOLATION;
2174 }
2175 PayloadSize = DataSize - AUTHINFO_SIZE;
2176 } else if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {
2177 //
2178 // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor.
2179 //
2180 if (DataSize < OFFSET_OF_AUTHINFO2_CERT_DATA ||
2181 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength > DataSize - (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) ||
2182 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength < OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) {
2183 return EFI_SECURITY_VIOLATION;
2184 }
2185 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
2186 } else {
2187 PayloadSize = DataSize;
2188 }
2189
2190 //
2191 // The size of the VariableName, including the Unicode Null in bytes plus
2192 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)
2193 // bytes for HwErrRec, and PcdGet32 (PcdMaxVariableSize) bytes for the others.
2194 //
2195 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2196 if ((PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize)) ||
2197 (sizeof (VARIABLE_HEADER) + StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize))) {
2198 return EFI_INVALID_PARAMETER;
2199 }
2200 //
2201 // According to UEFI spec, HARDWARE_ERROR_RECORD variable name convention should be L"HwErrRecXXXX".
2202 //
2203 if (StrnCmp(VariableName, L"HwErrRec", StrLen(L"HwErrRec")) != 0) {
2204 return EFI_INVALID_PARAMETER;
2205 }
2206 } else {
2207 //
2208 // The size of the VariableName, including the Unicode Null in bytes plus
2209 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxVariableSize) bytes.
2210 //
2211 if ((PayloadSize > PcdGet32 (PcdMaxVariableSize)) ||
2212 (sizeof (VARIABLE_HEADER) + StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxVariableSize))) {
2213 return EFI_INVALID_PARAMETER;
2214 }
2215 }
2216
2217 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2218
2219 //
2220 // Consider reentrant in MCA/INIT/NMI. It needs be reupdated.
2221 //
2222 if (1 < InterlockedIncrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState)) {
2223 Point = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
2224 //
2225 // Parse non-volatile variable data and get last variable offset.
2226 //
2227 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point);
2228 while ((NextVariable < GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point))
2229 && IsValidVariableHeader (NextVariable)) {
2230 NextVariable = GetNextVariablePtr (NextVariable);
2231 }
2232 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point;
2233 }
2234
2235 //
2236 // Check whether the input variable is already existed.
2237 //
2238 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, TRUE);
2239 if (!EFI_ERROR (Status)) {
2240 if (((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) && AtRuntime ()) {
2241 return EFI_WRITE_PROTECTED;
2242 }
2243 }
2244
2245 //
2246 // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.
2247 //
2248 AutoUpdateLangVariable (VariableName, Data, DataSize);
2249 //
2250 // Process PK, KEK, Sigdb seperately.
2251 //
2252 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_PLATFORM_KEY_NAME) == 0)){
2253 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, TRUE);
2254 } else if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0)) {
2255 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, FALSE);
2256 } else if (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&
2257 ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))) {
2258 Status = ProcessVarWithKek (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes);
2259 } else {
2260 Status = ProcessVariable (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes);
2261 }
2262
2263 InterlockedDecrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState);
2264 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2265
2266 return Status;
2267 }
2268
2269 /**
2270
2271 This code returns information about the EFI variables.
2272
2273 @param Attributes Attributes bitmask to specify the type of variables
2274 on which to return information.
2275 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
2276 for the EFI variables associated with the attributes specified.
2277 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
2278 for EFI variables associated with the attributes specified.
2279 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
2280 associated with the attributes specified.
2281
2282 @return EFI_INVALID_PARAMETER An invalid combination of attribute bits was supplied.
2283 @return EFI_SUCCESS Query successfully.
2284 @return EFI_UNSUPPORTED The attribute is not supported on this platform.
2285
2286 **/
2287 EFI_STATUS
2288 EFIAPI
2289 VariableServiceQueryVariableInfo (
2290 IN UINT32 Attributes,
2291 OUT UINT64 *MaximumVariableStorageSize,
2292 OUT UINT64 *RemainingVariableStorageSize,
2293 OUT UINT64 *MaximumVariableSize
2294 )
2295 {
2296 VARIABLE_HEADER *Variable;
2297 VARIABLE_HEADER *NextVariable;
2298 UINT64 VariableSize;
2299 VARIABLE_STORE_HEADER *VariableStoreHeader;
2300 UINT64 CommonVariableTotalSize;
2301 UINT64 HwErrVariableTotalSize;
2302
2303 CommonVariableTotalSize = 0;
2304 HwErrVariableTotalSize = 0;
2305
2306 if(MaximumVariableStorageSize == NULL || RemainingVariableStorageSize == NULL || MaximumVariableSize == NULL || Attributes == 0) {
2307 return EFI_INVALID_PARAMETER;
2308 }
2309
2310 if((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == 0) {
2311 //
2312 // Make sure the Attributes combination is supported by the platform.
2313 //
2314 return EFI_UNSUPPORTED;
2315 } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
2316 //
2317 // Make sure if runtime bit is set, boot service bit is set also.
2318 //
2319 return EFI_INVALID_PARAMETER;
2320 } else if (AtRuntime () && ((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) {
2321 //
2322 // Make sure RT Attribute is set if we are in Runtime phase.
2323 //
2324 return EFI_INVALID_PARAMETER;
2325 } else if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2326 //
2327 // Make sure Hw Attribute is set with NV.
2328 //
2329 return EFI_INVALID_PARAMETER;
2330 }
2331
2332 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2333
2334 if((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
2335 //
2336 // Query is Volatile related.
2337 //
2338 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
2339 } else {
2340 //
2341 // Query is Non-Volatile related.
2342 //
2343 VariableStoreHeader = mNvVariableCache;
2344 }
2345
2346 //
2347 // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize
2348 // with the storage size (excluding the storage header size).
2349 //
2350 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);
2351
2352 //
2353 // Harware error record variable needs larger size.
2354 //
2355 if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
2356 *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize);
2357 *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER);
2358 } else {
2359 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
2360 ASSERT (PcdGet32 (PcdHwErrStorageSize) < VariableStoreHeader->Size);
2361 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize);
2362 }
2363
2364 //
2365 // Let *MaximumVariableSize be PcdGet32 (PcdMaxVariableSize) with the exception of the variable header size.
2366 //
2367 *MaximumVariableSize = PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER);
2368 }
2369
2370 //
2371 // Point to the starting address of the variables.
2372 //
2373 Variable = GetStartPointer (VariableStoreHeader);
2374
2375 //
2376 // Now walk through the related variable store.
2377 //
2378 while ((Variable < GetEndPointer (VariableStoreHeader)) && IsValidVariableHeader (Variable)) {
2379 NextVariable = GetNextVariablePtr (Variable);
2380 VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable;
2381
2382 if (AtRuntime ()) {
2383 //
2384 // We don't take the state of the variables in mind
2385 // when calculating RemainingVariableStorageSize,
2386 // since the space occupied by variables not marked with
2387 // VAR_ADDED is not allowed to be reclaimed in Runtime.
2388 //
2389 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2390 HwErrVariableTotalSize += VariableSize;
2391 } else {
2392 CommonVariableTotalSize += VariableSize;
2393 }
2394 } else {
2395 //
2396 // Only care about Variables with State VAR_ADDED, because
2397 // the space not marked as VAR_ADDED is reclaimable now.
2398 //
2399 if (Variable->State == VAR_ADDED) {
2400 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2401 HwErrVariableTotalSize += VariableSize;
2402 } else {
2403 CommonVariableTotalSize += VariableSize;
2404 }
2405 }
2406 }
2407
2408 //
2409 // Go to the next one.
2410 //
2411 Variable = NextVariable;
2412 }
2413
2414 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD){
2415 *RemainingVariableStorageSize = *MaximumVariableStorageSize - HwErrVariableTotalSize;
2416 }else {
2417 *RemainingVariableStorageSize = *MaximumVariableStorageSize - CommonVariableTotalSize;
2418 }
2419
2420 if (*RemainingVariableStorageSize < sizeof (VARIABLE_HEADER)) {
2421 *MaximumVariableSize = 0;
2422 } else if ((*RemainingVariableStorageSize - sizeof (VARIABLE_HEADER)) < *MaximumVariableSize) {
2423 *MaximumVariableSize = *RemainingVariableStorageSize - sizeof (VARIABLE_HEADER);
2424 }
2425
2426 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2427 return EFI_SUCCESS;
2428 }
2429
2430
2431 /**
2432 This function reclaims variable storage if free size is below the threshold.
2433
2434 **/
2435 VOID
2436 ReclaimForOS(
2437 VOID
2438 )
2439 {
2440 EFI_STATUS Status;
2441 UINTN CommonVariableSpace;
2442 UINTN RemainingCommonVariableSpace;
2443 UINTN RemainingHwErrVariableSpace;
2444
2445 Status = EFI_SUCCESS;
2446
2447 CommonVariableSpace = ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase)))->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32(PcdHwErrStorageSize); //Allowable max size of common variable storage space
2448
2449 RemainingCommonVariableSpace = CommonVariableSpace - mVariableModuleGlobal->CommonVariableTotalSize;
2450
2451 RemainingHwErrVariableSpace = PcdGet32 (PcdHwErrStorageSize) - mVariableModuleGlobal->HwErrVariableTotalSize;
2452 //
2453 // Check if the free area is blow a threshold.
2454 //
2455 if ((RemainingCommonVariableSpace < PcdGet32 (PcdMaxVariableSize))
2456 || ((PcdGet32 (PcdHwErrStorageSize) != 0) &&
2457 (RemainingHwErrVariableSpace < PcdGet32 (PcdMaxHardwareErrorVariableSize)))){
2458 Status = Reclaim (
2459 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
2460 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
2461 FALSE,
2462 NULL
2463 );
2464 ASSERT_EFI_ERROR (Status);
2465 }
2466 }
2467
2468
2469 /**
2470 Initializes variable write service after FVB was ready.
2471
2472 @retval EFI_SUCCESS Function successfully executed.
2473 @retval Others Fail to initialize the variable service.
2474
2475 **/
2476 EFI_STATUS
2477 VariableWriteServiceInitialize (
2478 VOID
2479 )
2480 {
2481 EFI_STATUS Status;
2482 VARIABLE_STORE_HEADER *VariableStoreHeader;
2483 UINTN Index;
2484 UINT8 Data;
2485 EFI_PHYSICAL_ADDRESS VariableStoreBase;
2486 VARIABLE_HEADER *Variable;
2487 VOID *VariableData;
2488
2489 VariableStoreBase = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
2490 VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;
2491
2492 //
2493 // Check if the free area is really free.
2494 //
2495 for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreHeader->Size; Index++) {
2496 Data = ((UINT8 *) mNvVariableCache)[Index];
2497 if (Data != 0xff) {
2498 //
2499 // There must be something wrong in variable store, do reclaim operation.
2500 //
2501 Status = Reclaim (
2502 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
2503 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
2504 FALSE,
2505 NULL
2506 );
2507 if (EFI_ERROR (Status)) {
2508 return Status;
2509 }
2510 break;
2511 }
2512 }
2513
2514
2515 //
2516 // Flush the HOB variable to flash and invalidate HOB variable.
2517 //
2518 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
2519 //
2520 // Clear the HobVariableBase to avoid SetVariable() updating the variable in HOB
2521 //
2522 VariableStoreHeader = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
2523 mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0;
2524
2525 for ( Variable = GetStartPointer (VariableStoreHeader)
2526 ; (Variable < GetEndPointer (VariableStoreHeader) && IsValidVariableHeader (Variable))
2527 ; Variable = GetNextVariablePtr (Variable)
2528 ) {
2529 ASSERT (Variable->State == VAR_ADDED);
2530 ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0);
2531 VariableData = GetVariableDataPtr (Variable);
2532 Status = VariableServiceSetVariable (
2533 GetVariableNamePtr (Variable),
2534 &Variable->VendorGuid,
2535 Variable->Attributes,
2536 Variable->DataSize,
2537 VariableData
2538 );
2539 ASSERT_EFI_ERROR (Status);
2540 }
2541 }
2542
2543 //
2544 // Authenticated variable initialize.
2545 //
2546 Status = AutenticatedVariableServiceInitialize ();
2547
2548 return Status;
2549 }
2550
2551
2552 /**
2553 Initializes variable store area for non-volatile and volatile variable.
2554
2555 @retval EFI_SUCCESS Function successfully executed.
2556 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
2557
2558 **/
2559 EFI_STATUS
2560 VariableCommonInitialize (
2561 VOID
2562 )
2563 {
2564 EFI_STATUS Status;
2565 VARIABLE_STORE_HEADER *VolatileVariableStore;
2566 VARIABLE_STORE_HEADER *VariableStoreHeader;
2567 VARIABLE_HEADER *NextVariable;
2568 EFI_PHYSICAL_ADDRESS TempVariableStoreHeader;
2569 EFI_PHYSICAL_ADDRESS VariableStoreBase;
2570 UINT64 VariableStoreLength;
2571 UINTN ScratchSize;
2572 UINTN VariableSize;
2573 EFI_HOB_GUID_TYPE *GuidHob;
2574
2575 //
2576 // Allocate runtime memory for variable driver global structure.
2577 //
2578 mVariableModuleGlobal = AllocateRuntimeZeroPool (sizeof (VARIABLE_MODULE_GLOBAL));
2579 if (mVariableModuleGlobal == NULL) {
2580 return EFI_OUT_OF_RESOURCES;
2581 }
2582
2583 InitializeLock (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);
2584
2585 //
2586 // Note that in EdkII variable driver implementation, Hardware Error Record type variable
2587 // is stored with common variable in the same NV region. So the platform integrator should
2588 // ensure that the value of PcdHwErrStorageSize is less than or equal to the value of
2589 // PcdFlashNvStorageVariableSize.
2590 //
2591 ASSERT (PcdGet32 (PcdHwErrStorageSize) <= PcdGet32 (PcdFlashNvStorageVariableSize));
2592
2593 //
2594 // Get HOB variable store.
2595 //
2596 GuidHob = GetFirstGuidHob (&gEfiAuthenticatedVariableGuid);
2597 if (GuidHob != NULL) {
2598 VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob);
2599 if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {
2600 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStoreHeader;
2601 } else {
2602 DEBUG ((EFI_D_ERROR, "HOB Variable Store header is corrupted!\n"));
2603 }
2604 }
2605
2606 //
2607 // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.
2608 //
2609 ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));
2610 VolatileVariableStore = AllocateRuntimePool (PcdGet32 (PcdVariableStoreSize) + ScratchSize);
2611 if (VolatileVariableStore == NULL) {
2612 FreePool (mVariableModuleGlobal);
2613 return EFI_OUT_OF_RESOURCES;
2614 }
2615
2616 SetMem (VolatileVariableStore, PcdGet32 (PcdVariableStoreSize) + ScratchSize, 0xff);
2617
2618 //
2619 // Initialize Variable Specific Data.
2620 //
2621 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VolatileVariableStore;
2622 mVariableModuleGlobal->VolatileLastVariableOffset = (UINTN) GetStartPointer (VolatileVariableStore) - (UINTN) VolatileVariableStore;
2623 mVariableModuleGlobal->FvbInstance = NULL;
2624
2625 CopyGuid (&VolatileVariableStore->Signature, &gEfiAuthenticatedVariableGuid);
2626 VolatileVariableStore->Size = PcdGet32 (PcdVariableStoreSize);
2627 VolatileVariableStore->Format = VARIABLE_STORE_FORMATTED;
2628 VolatileVariableStore->State = VARIABLE_STORE_HEALTHY;
2629 VolatileVariableStore->Reserved = 0;
2630 VolatileVariableStore->Reserved1 = 0;
2631
2632 //
2633 // Get non-volatile variable store.
2634 //
2635
2636 TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);
2637 if (TempVariableStoreHeader == 0) {
2638 TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);
2639 }
2640
2641 //
2642 // Check if the Firmware Volume is not corrupted
2643 //
2644 if ((((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader))->Signature != EFI_FVH_SIGNATURE) ||
2645 (!CompareGuid (&gEfiSystemNvDataFvGuid, &((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader))->FileSystemGuid))) {
2646 Status = EFI_VOLUME_CORRUPTED;
2647 DEBUG ((EFI_D_ERROR, "Firmware Volume for Variable Store is corrupted\n"));
2648 goto Done;
2649 }
2650
2651 VariableStoreBase = TempVariableStoreHeader + \
2652 (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader)) -> HeaderLength);
2653 VariableStoreLength = (UINT64) PcdGet32 (PcdFlashNvStorageVariableSize) - \
2654 (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader)) -> HeaderLength);
2655
2656 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
2657 VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;
2658 if (GetVariableStoreStatus (VariableStoreHeader) != EfiValid) {
2659 Status = EFI_VOLUME_CORRUPTED;
2660 DEBUG((EFI_D_INFO, "Variable Store header is corrupted\n"));
2661 goto Done;
2662 }
2663 ASSERT(VariableStoreHeader->Size == VariableStoreLength);
2664
2665 //
2666 // Parse non-volatile variable data and get last variable offset.
2667 //
2668 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase);
2669 while (IsValidVariableHeader (NextVariable)) {
2670 VariableSize = NextVariable->NameSize + NextVariable->DataSize + sizeof (VARIABLE_HEADER);
2671 if ((NextVariable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
2672 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VariableSize);
2673 } else {
2674 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize);
2675 }
2676
2677 NextVariable = GetNextVariablePtr (NextVariable);
2678 }
2679
2680 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) VariableStoreBase;
2681
2682 //
2683 // Allocate runtime memory used for a memory copy of the FLASH region.
2684 // Keep the memory and the FLASH in sync as updates occur
2685 //
2686 mNvVariableCache = AllocateRuntimeZeroPool ((UINTN)VariableStoreLength);
2687 if (mNvVariableCache == NULL) {
2688 Status = EFI_OUT_OF_RESOURCES;
2689 goto Done;
2690 }
2691 CopyMem (mNvVariableCache, (CHAR8 *)(UINTN)VariableStoreBase, (UINTN)VariableStoreLength);
2692 Status = EFI_SUCCESS;
2693
2694 Done:
2695 if (EFI_ERROR (Status)) {
2696 FreePool (mVariableModuleGlobal);
2697 FreePool (VolatileVariableStore);
2698 }
2699
2700 return Status;
2701 }
2702
2703
2704 /**
2705 Get the proper fvb handle and/or fvb protocol by the given Flash address.
2706
2707 @param[in] Address The Flash address.
2708 @param[out] FvbHandle In output, if it is not NULL, it points to the proper FVB handle.
2709 @param[out] FvbProtocol In output, if it is not NULL, it points to the proper FVB protocol.
2710
2711 **/
2712 EFI_STATUS
2713 GetFvbInfoByAddress (
2714 IN EFI_PHYSICAL_ADDRESS Address,
2715 OUT EFI_HANDLE *FvbHandle OPTIONAL,
2716 OUT EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL **FvbProtocol OPTIONAL
2717 )
2718 {
2719 EFI_STATUS Status;
2720 EFI_HANDLE *HandleBuffer;
2721 UINTN HandleCount;
2722 UINTN Index;
2723 EFI_PHYSICAL_ADDRESS FvbBaseAddress;
2724 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
2725 EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
2726 EFI_FVB_ATTRIBUTES_2 Attributes;
2727
2728 //
2729 // Get all FVB handles.
2730 //
2731 Status = GetFvbCountAndBuffer (&HandleCount, &HandleBuffer);
2732 if (EFI_ERROR (Status)) {
2733 return EFI_NOT_FOUND;
2734 }
2735
2736 //
2737 // Get the FVB to access variable store.
2738 //
2739 Fvb = NULL;
2740 for (Index = 0; Index < HandleCount; Index += 1, Status = EFI_NOT_FOUND, Fvb = NULL) {
2741 Status = GetFvbByHandle (HandleBuffer[Index], &Fvb);
2742 if (EFI_ERROR (Status)) {
2743 Status = EFI_NOT_FOUND;
2744 break;
2745 }
2746
2747 //
2748 // Ensure this FVB protocol supported Write operation.
2749 //
2750 Status = Fvb->GetAttributes (Fvb, &Attributes);
2751 if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {
2752 continue;
2753 }
2754
2755 //
2756 // Compare the address and select the right one.
2757 //
2758 Status = Fvb->GetPhysicalAddress (Fvb, &FvbBaseAddress);
2759 if (EFI_ERROR (Status)) {
2760 continue;
2761 }
2762
2763 FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) FvbBaseAddress);
2764 if ((Address >= FvbBaseAddress) && (Address < (FvbBaseAddress + FwVolHeader->FvLength))) {
2765 if (FvbHandle != NULL) {
2766 *FvbHandle = HandleBuffer[Index];
2767 }
2768 if (FvbProtocol != NULL) {
2769 *FvbProtocol = Fvb;
2770 }
2771 Status = EFI_SUCCESS;
2772 break;
2773 }
2774 }
2775 FreePool (HandleBuffer);
2776
2777 if (Fvb == NULL) {
2778 Status = EFI_NOT_FOUND;
2779 }
2780
2781 return Status;
2782 }
2783