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