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