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