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