]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c
cb0f2baf9d3ff8f79f193406b6cb13d7a2691826
[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 (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0))) {
2113 //
2114 // For variables with formatted as EFI_SIGNATURE_LIST, the driver shall not perform an append of
2115 // EFI_SIGNATURE_DATA values that are already part of the existing variable value.
2116 //
2117 Status = AppendSignatureList (
2118 BufferForMerge,
2119 Variable->CurrPtr->DataSize,
2120 MaxDataSize - Variable->CurrPtr->DataSize,
2121 Data,
2122 DataSize,
2123 &MergedBufSize
2124 );
2125 if (Status == EFI_BUFFER_TOO_SMALL) {
2126 //
2127 // Signature List is too long, Failed to Append.
2128 //
2129 Status = EFI_INVALID_PARAMETER;
2130 goto Done;
2131 }
2132
2133 if (MergedBufSize == Variable->CurrPtr->DataSize) {
2134 if ((TimeStamp == NULL) || CompareTimeStamp (TimeStamp, &Variable->CurrPtr->TimeStamp)) {
2135 //
2136 // New EFI_SIGNATURE_DATA is not found and timestamp is not later
2137 // than current timestamp, return EFI_SUCCESS directly.
2138 //
2139 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);
2140 Status = EFI_SUCCESS;
2141 goto Done;
2142 }
2143 }
2144 } else {
2145 //
2146 // For other Variables, append the new data to the end of existing data.
2147 // Max Harware error record variable data size is different from common variable
2148 //
2149 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2150 MaxDataSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - DataOffset;
2151 }
2152
2153 if (Variable->CurrPtr->DataSize + DataSize > MaxDataSize) {
2154 //
2155 // Existing data size + new data size exceed maximum variable size limitation.
2156 //
2157 Status = EFI_INVALID_PARAMETER;
2158 goto Done;
2159 }
2160 CopyMem ((UINT8*) ((UINTN) BufferForMerge + Variable->CurrPtr->DataSize), Data, DataSize);
2161 MergedBufSize = Variable->CurrPtr->DataSize + DataSize;
2162 }
2163
2164 //
2165 // BufferForMerge(from DataOffset of NextVariable) has included the merged existing and new data.
2166 //
2167 Data = BufferForMerge;
2168 DataSize = MergedBufSize;
2169 DataReady = TRUE;
2170 }
2171
2172 //
2173 // Mark the old variable as in delete transition.
2174 //
2175 State = Variable->CurrPtr->State;
2176 State &= VAR_IN_DELETED_TRANSITION;
2177
2178 Status = UpdateVariableStore (
2179 &mVariableModuleGlobal->VariableGlobal,
2180 Variable->Volatile,
2181 FALSE,
2182 Fvb,
2183 (UINTN) &Variable->CurrPtr->State,
2184 sizeof (UINT8),
2185 &State
2186 );
2187 if (EFI_ERROR (Status)) {
2188 goto Done;
2189 }
2190 if (!Variable->Volatile) {
2191 CacheVariable->CurrPtr->State = State;
2192 }
2193 }
2194 } else {
2195 //
2196 // Not found existing variable. Create a new variable.
2197 //
2198
2199 if ((DataSize == 0) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0)) {
2200 Status = EFI_SUCCESS;
2201 goto Done;
2202 }
2203
2204 //
2205 // Make sure we are trying to create a new variable.
2206 // Setting a data variable with zero DataSize or no access attributes means to delete it.
2207 //
2208 if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) {
2209 Status = EFI_NOT_FOUND;
2210 goto Done;
2211 }
2212
2213 //
2214 // Only variable have NV|RT attribute can be created in Runtime.
2215 //
2216 if (AtRuntime () &&
2217 (((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0))) {
2218 Status = EFI_INVALID_PARAMETER;
2219 goto Done;
2220 }
2221 }
2222
2223 //
2224 // Function part - create a new variable and copy the data.
2225 // Both update a variable and create a variable will come here.
2226 //
2227 NextVariable->StartId = VARIABLE_DATA;
2228 //
2229 // NextVariable->State = VAR_ADDED;
2230 //
2231 NextVariable->Reserved = 0;
2232 NextVariable->PubKeyIndex = KeyIndex;
2233 NextVariable->MonotonicCount = MonotonicCount;
2234 ZeroMem (&NextVariable->TimeStamp, sizeof (EFI_TIME));
2235
2236 if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&
2237 (TimeStamp != NULL)) {
2238 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) {
2239 CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
2240 } else {
2241 //
2242 // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only
2243 // when the new TimeStamp value is later than the current timestamp associated
2244 // with the variable, we need associate the new timestamp with the updated value.
2245 //
2246 if (Variable->CurrPtr != NULL) {
2247 if (CompareTimeStamp (&Variable->CurrPtr->TimeStamp, TimeStamp)) {
2248 CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
2249 }
2250 }
2251 }
2252 }
2253
2254 //
2255 // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned
2256 // Attributes bitmask parameter of a GetVariable() call.
2257 //
2258 NextVariable->Attributes = Attributes & (~EFI_VARIABLE_APPEND_WRITE);
2259
2260 VarNameOffset = sizeof (VARIABLE_HEADER);
2261 VarNameSize = StrSize (VariableName);
2262 CopyMem (
2263 (UINT8 *) ((UINTN) NextVariable + VarNameOffset),
2264 VariableName,
2265 VarNameSize
2266 );
2267 VarDataOffset = VarNameOffset + VarNameSize + GET_PAD_SIZE (VarNameSize);
2268
2269 //
2270 // If DataReady is TRUE, it means the variable data has been saved into
2271 // NextVariable during EFI_VARIABLE_APPEND_WRITE operation preparation.
2272 //
2273 if (!DataReady) {
2274 CopyMem (
2275 (UINT8 *) ((UINTN) NextVariable + VarDataOffset),
2276 Data,
2277 DataSize
2278 );
2279 }
2280
2281 CopyMem (&NextVariable->VendorGuid, VendorGuid, sizeof (EFI_GUID));
2282 //
2283 // There will be pad bytes after Data, the NextVariable->NameSize and
2284 // NextVariable->DataSize should not include pad size so that variable
2285 // service can get actual size in GetVariable.
2286 //
2287 NextVariable->NameSize = (UINT32)VarNameSize;
2288 NextVariable->DataSize = (UINT32)DataSize;
2289
2290 //
2291 // The actual size of the variable that stores in storage should
2292 // include pad size.
2293 //
2294 VarSize = VarDataOffset + DataSize + GET_PAD_SIZE (DataSize);
2295 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
2296 //
2297 // Create a nonvolatile variable.
2298 //
2299 Volatile = FALSE;
2300 NonVolatileVarableStoreSize = ((VARIABLE_STORE_HEADER *)(UINTN)(mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase))->Size;
2301 if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)
2302 && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))
2303 || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0)
2304 && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {
2305 if (AtRuntime ()) {
2306 Status = EFI_OUT_OF_RESOURCES;
2307 goto Done;
2308 }
2309 //
2310 // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.
2311 //
2312 Status = Reclaim (
2313 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
2314 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
2315 FALSE,
2316 Variable,
2317 NextVariable,
2318 HEADER_ALIGN (VarSize),
2319 FALSE
2320 );
2321 if (!EFI_ERROR (Status)) {
2322 //
2323 // The new variable has been integrated successfully during reclaiming.
2324 //
2325 if (Variable->CurrPtr != NULL) {
2326 CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
2327 CacheVariable->InDeletedTransitionPtr = NULL;
2328 }
2329 UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, TRUE, FALSE, FALSE);
2330 FlushHobVariableToFlash (VariableName, VendorGuid);
2331 }
2332 goto Done;
2333 }
2334 //
2335 // Four steps
2336 // 1. Write variable header
2337 // 2. Set variable state to header valid
2338 // 3. Write variable data
2339 // 4. Set variable state to valid
2340 //
2341 //
2342 // Step 1:
2343 //
2344 CacheOffset = mVariableModuleGlobal->NonVolatileLastVariableOffset;
2345 Status = UpdateVariableStore (
2346 &mVariableModuleGlobal->VariableGlobal,
2347 FALSE,
2348 TRUE,
2349 Fvb,
2350 mVariableModuleGlobal->NonVolatileLastVariableOffset,
2351 sizeof (VARIABLE_HEADER),
2352 (UINT8 *) NextVariable
2353 );
2354
2355 if (EFI_ERROR (Status)) {
2356 goto Done;
2357 }
2358
2359 //
2360 // Step 2:
2361 //
2362 NextVariable->State = VAR_HEADER_VALID_ONLY;
2363 Status = UpdateVariableStore (
2364 &mVariableModuleGlobal->VariableGlobal,
2365 FALSE,
2366 TRUE,
2367 Fvb,
2368 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
2369 sizeof (UINT8),
2370 &NextVariable->State
2371 );
2372
2373 if (EFI_ERROR (Status)) {
2374 goto Done;
2375 }
2376 //
2377 // Step 3:
2378 //
2379 Status = UpdateVariableStore (
2380 &mVariableModuleGlobal->VariableGlobal,
2381 FALSE,
2382 TRUE,
2383 Fvb,
2384 mVariableModuleGlobal->NonVolatileLastVariableOffset + sizeof (VARIABLE_HEADER),
2385 (UINT32) VarSize - sizeof (VARIABLE_HEADER),
2386 (UINT8 *) NextVariable + sizeof (VARIABLE_HEADER)
2387 );
2388
2389 if (EFI_ERROR (Status)) {
2390 goto Done;
2391 }
2392 //
2393 // Step 4:
2394 //
2395 NextVariable->State = VAR_ADDED;
2396 Status = UpdateVariableStore (
2397 &mVariableModuleGlobal->VariableGlobal,
2398 FALSE,
2399 TRUE,
2400 Fvb,
2401 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
2402 sizeof (UINT8),
2403 &NextVariable->State
2404 );
2405
2406 if (EFI_ERROR (Status)) {
2407 goto Done;
2408 }
2409
2410 mVariableModuleGlobal->NonVolatileLastVariableOffset += HEADER_ALIGN (VarSize);
2411
2412 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
2413 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VarSize);
2414 } else {
2415 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VarSize);
2416 }
2417 //
2418 // update the memory copy of Flash region.
2419 //
2420 CopyMem ((UINT8 *)mNvVariableCache + CacheOffset, (UINT8 *)NextVariable, VarSize);
2421 } else {
2422 //
2423 // Create a volatile variable.
2424 //
2425 Volatile = TRUE;
2426
2427 if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >
2428 ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size) {
2429 //
2430 // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.
2431 //
2432 Status = Reclaim (
2433 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,
2434 &mVariableModuleGlobal->VolatileLastVariableOffset,
2435 TRUE,
2436 Variable,
2437 NextVariable,
2438 HEADER_ALIGN (VarSize),
2439 FALSE
2440 );
2441 if (!EFI_ERROR (Status)) {
2442 //
2443 // The new variable has been integrated successfully during reclaiming.
2444 //
2445 if (Variable->CurrPtr != NULL) {
2446 CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
2447 CacheVariable->InDeletedTransitionPtr = NULL;
2448 }
2449 UpdateVariableInfo (VariableName, VendorGuid, TRUE, FALSE, TRUE, FALSE, FALSE);
2450 }
2451 goto Done;
2452 }
2453
2454 NextVariable->State = VAR_ADDED;
2455 Status = UpdateVariableStore (
2456 &mVariableModuleGlobal->VariableGlobal,
2457 TRUE,
2458 TRUE,
2459 Fvb,
2460 mVariableModuleGlobal->VolatileLastVariableOffset,
2461 (UINT32) VarSize,
2462 (UINT8 *) NextVariable
2463 );
2464
2465 if (EFI_ERROR (Status)) {
2466 goto Done;
2467 }
2468
2469 mVariableModuleGlobal->VolatileLastVariableOffset += HEADER_ALIGN (VarSize);
2470 }
2471
2472 //
2473 // Mark the old variable as deleted.
2474 //
2475 if (!EFI_ERROR (Status) && Variable->CurrPtr != NULL) {
2476 if (Variable->InDeletedTransitionPtr != NULL) {
2477 //
2478 // Both ADDED and IN_DELETED_TRANSITION old variable are present,
2479 // set IN_DELETED_TRANSITION one to DELETED state first.
2480 //
2481 State = Variable->InDeletedTransitionPtr->State;
2482 State &= VAR_DELETED;
2483 Status = UpdateVariableStore (
2484 &mVariableModuleGlobal->VariableGlobal,
2485 Variable->Volatile,
2486 FALSE,
2487 Fvb,
2488 (UINTN) &Variable->InDeletedTransitionPtr->State,
2489 sizeof (UINT8),
2490 &State
2491 );
2492 if (!EFI_ERROR (Status)) {
2493 if (!Variable->Volatile) {
2494 ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
2495 CacheVariable->InDeletedTransitionPtr->State = State;
2496 }
2497 } else {
2498 goto Done;
2499 }
2500 }
2501
2502 State = Variable->CurrPtr->State;
2503 State &= VAR_DELETED;
2504
2505 Status = UpdateVariableStore (
2506 &mVariableModuleGlobal->VariableGlobal,
2507 Variable->Volatile,
2508 FALSE,
2509 Fvb,
2510 (UINTN) &Variable->CurrPtr->State,
2511 sizeof (UINT8),
2512 &State
2513 );
2514 if (!EFI_ERROR (Status) && !Variable->Volatile) {
2515 CacheVariable->CurrPtr->State = State;
2516 }
2517 }
2518
2519 if (!EFI_ERROR (Status)) {
2520 UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);
2521 if (!Volatile) {
2522 FlushHobVariableToFlash (VariableName, VendorGuid);
2523 }
2524 }
2525
2526 Done:
2527 return Status;
2528 }
2529
2530 /**
2531 Check if a Unicode character is a hexadecimal character.
2532
2533 This function checks if a Unicode character is a
2534 hexadecimal character. The valid hexadecimal character is
2535 L'0' to L'9', L'a' to L'f', or L'A' to L'F'.
2536
2537
2538 @param Char The character to check against.
2539
2540 @retval TRUE If the Char is a hexadecmial character.
2541 @retval FALSE If the Char is not a hexadecmial character.
2542
2543 **/
2544 BOOLEAN
2545 EFIAPI
2546 IsHexaDecimalDigitCharacter (
2547 IN CHAR16 Char
2548 )
2549 {
2550 return (BOOLEAN) ((Char >= L'0' && Char <= L'9') || (Char >= L'A' && Char <= L'F') || (Char >= L'a' && Char <= L'f'));
2551 }
2552
2553 /**
2554
2555 This code checks if variable is hardware error record variable or not.
2556
2557 According to UEFI spec, hardware error record variable should use the EFI_HARDWARE_ERROR_VARIABLE VendorGuid
2558 and have the L"HwErrRec####" name convention, #### is a printed hex value and no 0x or h is included in the hex value.
2559
2560 @param VariableName Pointer to variable name.
2561 @param VendorGuid Variable Vendor Guid.
2562
2563 @retval TRUE Variable is hardware error record variable.
2564 @retval FALSE Variable is not hardware error record variable.
2565
2566 **/
2567 BOOLEAN
2568 EFIAPI
2569 IsHwErrRecVariable (
2570 IN CHAR16 *VariableName,
2571 IN EFI_GUID *VendorGuid
2572 )
2573 {
2574 if (!CompareGuid (VendorGuid, &gEfiHardwareErrorVariableGuid) ||
2575 (StrLen (VariableName) != StrLen (L"HwErrRec####")) ||
2576 (StrnCmp(VariableName, L"HwErrRec", StrLen (L"HwErrRec")) != 0) ||
2577 !IsHexaDecimalDigitCharacter (VariableName[0x8]) ||
2578 !IsHexaDecimalDigitCharacter (VariableName[0x9]) ||
2579 !IsHexaDecimalDigitCharacter (VariableName[0xA]) ||
2580 !IsHexaDecimalDigitCharacter (VariableName[0xB])) {
2581 return FALSE;
2582 }
2583
2584 return TRUE;
2585 }
2586
2587 /**
2588 This code checks if variable guid is global variable guid first.
2589 If yes, further check if variable name is in mGlobalVariableList or mGlobalVariableList2 and attributes matched.
2590
2591 @param[in] VariableName Pointer to variable name.
2592 @param[in] VendorGuid Variable Vendor Guid.
2593 @param[in] Attributes Attributes of the variable.
2594
2595 @retval EFI_SUCCESS Variable is not global variable, or Variable is global variable, variable name is in the lists and attributes matched.
2596 @retval EFI_INVALID_PARAMETER Variable is global variable, but variable name is not in the lists or attributes unmatched.
2597
2598 **/
2599 EFI_STATUS
2600 EFIAPI
2601 CheckEfiGlobalVariable (
2602 IN CHAR16 *VariableName,
2603 IN EFI_GUID *VendorGuid,
2604 IN UINT32 Attributes
2605 )
2606 {
2607 UINTN Index;
2608 UINTN NameLength;
2609
2610 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid)){
2611 //
2612 // Try list 1, exactly match.
2613 //
2614 for (Index = 0; Index < sizeof (mGlobalVariableList)/sizeof (mGlobalVariableList[0]); Index++) {
2615 if ((StrCmp (mGlobalVariableList[Index].Name, VariableName) == 0) &&
2616 (Attributes == 0 || (Attributes & (~EFI_VARIABLE_APPEND_WRITE)) == mGlobalVariableList[Index].Attributes)) {
2617 return EFI_SUCCESS;
2618 }
2619 }
2620
2621 //
2622 // Try list 2.
2623 //
2624 NameLength = StrLen (VariableName) - 4;
2625 for (Index = 0; Index < sizeof (mGlobalVariableList2)/sizeof (mGlobalVariableList2[0]); Index++) {
2626 if ((StrLen (VariableName) == StrLen (mGlobalVariableList2[Index].Name)) &&
2627 (StrnCmp (mGlobalVariableList2[Index].Name, VariableName, NameLength) == 0) &&
2628 IsHexaDecimalDigitCharacter (VariableName[NameLength]) &&
2629 IsHexaDecimalDigitCharacter (VariableName[NameLength + 1]) &&
2630 IsHexaDecimalDigitCharacter (VariableName[NameLength + 2]) &&
2631 IsHexaDecimalDigitCharacter (VariableName[NameLength + 3]) &&
2632 (Attributes == 0 || (Attributes & (~EFI_VARIABLE_APPEND_WRITE)) == mGlobalVariableList2[Index].Attributes)) {
2633 return EFI_SUCCESS;
2634 }
2635 }
2636
2637 DEBUG ((EFI_D_INFO, "[Variable]: set global variable with invalid variable name or attributes - %g:%s:%x\n", VendorGuid, VariableName, Attributes));
2638 return EFI_INVALID_PARAMETER;
2639 }
2640
2641 return EFI_SUCCESS;
2642 }
2643
2644 /**
2645 Mark a variable that will become read-only after leaving the DXE phase of execution.
2646
2647 @param[in] This The VARIABLE_LOCK_PROTOCOL instance.
2648 @param[in] VariableName A pointer to the variable name that will be made read-only subsequently.
2649 @param[in] VendorGuid A pointer to the vendor GUID that will be made read-only subsequently.
2650
2651 @retval EFI_SUCCESS The variable specified by the VariableName and the VendorGuid was marked
2652 as pending to be read-only.
2653 @retval EFI_INVALID_PARAMETER VariableName or VendorGuid is NULL.
2654 Or VariableName is an empty string.
2655 @retval EFI_ACCESS_DENIED EFI_END_OF_DXE_EVENT_GROUP_GUID or EFI_EVENT_GROUP_READY_TO_BOOT has
2656 already been signaled.
2657 @retval EFI_OUT_OF_RESOURCES There is not enough resource to hold the lock request.
2658 **/
2659 EFI_STATUS
2660 EFIAPI
2661 VariableLockRequestToLock (
2662 IN CONST EDKII_VARIABLE_LOCK_PROTOCOL *This,
2663 IN CHAR16 *VariableName,
2664 IN EFI_GUID *VendorGuid
2665 )
2666 {
2667 VARIABLE_ENTRY *Entry;
2668
2669 if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {
2670 return EFI_INVALID_PARAMETER;
2671 }
2672
2673 if (mEndOfDxe) {
2674 return EFI_ACCESS_DENIED;
2675 }
2676
2677 Entry = AllocateRuntimePool (sizeof (*Entry) + StrSize (VariableName));
2678 if (Entry == NULL) {
2679 return EFI_OUT_OF_RESOURCES;
2680 }
2681
2682 DEBUG ((EFI_D_INFO, "[Variable] Lock: %g:%s\n", VendorGuid, VariableName));
2683
2684 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2685
2686 Entry->Name = (CHAR16 *) (Entry + 1);
2687 StrCpy (Entry->Name, VariableName);
2688 CopyGuid (&Entry->Guid, VendorGuid);
2689 InsertTailList (&mLockedVariableList, &Entry->Link);
2690
2691 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2692
2693 return EFI_SUCCESS;
2694 }
2695
2696 /**
2697 This code checks if variable should be treated as read-only variable.
2698
2699 @param[in] VariableName Name of the Variable.
2700 @param[in] VendorGuid GUID of the Variable.
2701
2702 @retval TRUE This variable is read-only variable.
2703 @retval FALSE This variable is NOT read-only variable.
2704
2705 **/
2706 BOOLEAN
2707 IsReadOnlyVariable (
2708 IN CHAR16 *VariableName,
2709 IN EFI_GUID *VendorGuid
2710 )
2711 {
2712 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid)) {
2713 if ((StrCmp (VariableName, EFI_SETUP_MODE_NAME) == 0) ||
2714 (StrCmp (VariableName, EFI_SIGNATURE_SUPPORT_NAME) == 0) ||
2715 (StrCmp (VariableName, EFI_SECURE_BOOT_MODE_NAME) == 0) ||
2716 (StrCmp (VariableName, EFI_VENDOR_KEYS_VARIABLE_NAME) == 0) ||
2717 (StrCmp (VariableName, EFI_KEK_DEFAULT_VARIABLE_NAME) == 0) ||
2718 (StrCmp (VariableName, EFI_PK_DEFAULT_VARIABLE_NAME) == 0) ||
2719 (StrCmp (VariableName, EFI_DB_DEFAULT_VARIABLE_NAME) == 0) ||
2720 (StrCmp (VariableName, EFI_DBX_DEFAULT_VARIABLE_NAME) == 0) ||
2721 (StrCmp (VariableName, EFI_DBT_DEFAULT_VARIABLE_NAME) == 0)) {
2722 return TRUE;
2723 }
2724 }
2725
2726 return FALSE;
2727 }
2728
2729 /**
2730
2731 This code finds variable in storage blocks (Volatile or Non-Volatile).
2732
2733 Caution: This function may receive untrusted input.
2734 This function may be invoked in SMM mode, and datasize is external input.
2735 This function will do basic validation, before parse the data.
2736
2737 @param VariableName Name of Variable to be found.
2738 @param VendorGuid Variable vendor GUID.
2739 @param Attributes Attribute value of the variable found.
2740 @param DataSize Size of Data found. If size is less than the
2741 data, this value contains the required size.
2742 @param Data Data pointer.
2743
2744 @return EFI_INVALID_PARAMETER Invalid parameter.
2745 @return EFI_SUCCESS Find the specified variable.
2746 @return EFI_NOT_FOUND Not found.
2747 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2748
2749 **/
2750 EFI_STATUS
2751 EFIAPI
2752 VariableServiceGetVariable (
2753 IN CHAR16 *VariableName,
2754 IN EFI_GUID *VendorGuid,
2755 OUT UINT32 *Attributes OPTIONAL,
2756 IN OUT UINTN *DataSize,
2757 OUT VOID *Data
2758 )
2759 {
2760 EFI_STATUS Status;
2761 VARIABLE_POINTER_TRACK Variable;
2762 UINTN VarDataSize;
2763
2764 if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {
2765 return EFI_INVALID_PARAMETER;
2766 }
2767
2768 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2769
2770 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2771 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2772 goto Done;
2773 }
2774
2775 //
2776 // Get data size
2777 //
2778 VarDataSize = DataSizeOfVariable (Variable.CurrPtr);
2779 ASSERT (VarDataSize != 0);
2780
2781 if (*DataSize >= VarDataSize) {
2782 if (Data == NULL) {
2783 Status = EFI_INVALID_PARAMETER;
2784 goto Done;
2785 }
2786
2787 CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr), VarDataSize);
2788 if (Attributes != NULL) {
2789 *Attributes = Variable.CurrPtr->Attributes;
2790 }
2791
2792 *DataSize = VarDataSize;
2793 UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);
2794
2795 Status = EFI_SUCCESS;
2796 goto Done;
2797 } else {
2798 *DataSize = VarDataSize;
2799 Status = EFI_BUFFER_TOO_SMALL;
2800 goto Done;
2801 }
2802
2803 Done:
2804 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2805 return Status;
2806 }
2807
2808
2809
2810 /**
2811
2812 This code Finds the Next available variable.
2813
2814 Caution: This function may receive untrusted input.
2815 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2816
2817 @param VariableNameSize Size of the variable name.
2818 @param VariableName Pointer to variable name.
2819 @param VendorGuid Variable Vendor Guid.
2820
2821 @return EFI_INVALID_PARAMETER Invalid parameter.
2822 @return EFI_SUCCESS Find the specified variable.
2823 @return EFI_NOT_FOUND Not found.
2824 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2825
2826 **/
2827 EFI_STATUS
2828 EFIAPI
2829 VariableServiceGetNextVariableName (
2830 IN OUT UINTN *VariableNameSize,
2831 IN OUT CHAR16 *VariableName,
2832 IN OUT EFI_GUID *VendorGuid
2833 )
2834 {
2835 VARIABLE_STORE_TYPE Type;
2836 VARIABLE_POINTER_TRACK Variable;
2837 VARIABLE_POINTER_TRACK VariableInHob;
2838 VARIABLE_POINTER_TRACK VariablePtrTrack;
2839 UINTN VarNameSize;
2840 EFI_STATUS Status;
2841 VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
2842
2843 if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
2844 return EFI_INVALID_PARAMETER;
2845 }
2846
2847 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2848
2849 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2850 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2851 goto Done;
2852 }
2853
2854 if (VariableName[0] != 0) {
2855 //
2856 // If variable name is not NULL, get next variable.
2857 //
2858 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2859 }
2860
2861 //
2862 // 0: Volatile, 1: HOB, 2: Non-Volatile.
2863 // The index and attributes mapping must be kept in this order as FindVariable
2864 // makes use of this mapping to implement search algorithm.
2865 //
2866 VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
2867 VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
2868 VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
2869
2870 while (TRUE) {
2871 //
2872 // Switch from Volatile to HOB, to Non-Volatile.
2873 //
2874 while (!IsValidVariableHeader (Variable.CurrPtr, Variable.EndPtr)) {
2875 //
2876 // Find current storage index
2877 //
2878 for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
2879 if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
2880 break;
2881 }
2882 }
2883 ASSERT (Type < VariableStoreTypeMax);
2884 //
2885 // Switch to next storage
2886 //
2887 for (Type++; Type < VariableStoreTypeMax; Type++) {
2888 if (VariableStoreHeader[Type] != NULL) {
2889 break;
2890 }
2891 }
2892 //
2893 // Capture the case that
2894 // 1. current storage is the last one, or
2895 // 2. no further storage
2896 //
2897 if (Type == VariableStoreTypeMax) {
2898 Status = EFI_NOT_FOUND;
2899 goto Done;
2900 }
2901 Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);
2902 Variable.EndPtr = GetEndPointer (VariableStoreHeader[Type]);
2903 Variable.CurrPtr = Variable.StartPtr;
2904 }
2905
2906 //
2907 // Variable is found
2908 //
2909 if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
2910 if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
2911 if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
2912 //
2913 // If it is a IN_DELETED_TRANSITION variable,
2914 // and there is also a same ADDED one at the same time,
2915 // don't return it.
2916 //
2917 VariablePtrTrack.StartPtr = Variable.StartPtr;
2918 VariablePtrTrack.EndPtr = Variable.EndPtr;
2919 Status = FindVariableEx (
2920 GetVariableNamePtr (Variable.CurrPtr),
2921 &Variable.CurrPtr->VendorGuid,
2922 FALSE,
2923 &VariablePtrTrack
2924 );
2925 if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
2926 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2927 continue;
2928 }
2929 }
2930
2931 //
2932 // Don't return NV variable when HOB overrides it
2933 //
2934 if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&
2935 (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))
2936 ) {
2937 VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);
2938 VariableInHob.EndPtr = GetEndPointer (VariableStoreHeader[VariableStoreTypeHob]);
2939 Status = FindVariableEx (
2940 GetVariableNamePtr (Variable.CurrPtr),
2941 &Variable.CurrPtr->VendorGuid,
2942 FALSE,
2943 &VariableInHob
2944 );
2945 if (!EFI_ERROR (Status)) {
2946 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2947 continue;
2948 }
2949 }
2950
2951 VarNameSize = NameSizeOfVariable (Variable.CurrPtr);
2952 ASSERT (VarNameSize != 0);
2953
2954 if (VarNameSize <= *VariableNameSize) {
2955 CopyMem (VariableName, GetVariableNamePtr (Variable.CurrPtr), VarNameSize);
2956 CopyMem (VendorGuid, &Variable.CurrPtr->VendorGuid, sizeof (EFI_GUID));
2957 Status = EFI_SUCCESS;
2958 } else {
2959 Status = EFI_BUFFER_TOO_SMALL;
2960 }
2961
2962 *VariableNameSize = VarNameSize;
2963 goto Done;
2964 }
2965 }
2966
2967 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2968 }
2969
2970 Done:
2971 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2972 return Status;
2973 }
2974
2975 /**
2976
2977 This code sets variable in storage blocks (Volatile or Non-Volatile).
2978
2979 Caution: This function may receive untrusted input.
2980 This function may be invoked in SMM mode, and datasize and data are external input.
2981 This function will do basic validation, before parse the data.
2982 This function will parse the authentication carefully to avoid security issues, like
2983 buffer overflow, integer overflow.
2984 This function will check attribute carefully to avoid authentication bypass.
2985
2986 @param VariableName Name of Variable to be found.
2987 @param VendorGuid Variable vendor GUID.
2988 @param Attributes Attribute value of the variable found
2989 @param DataSize Size of Data found. If size is less than the
2990 data, this value contains the required size.
2991 @param Data Data pointer.
2992
2993 @return EFI_INVALID_PARAMETER Invalid parameter.
2994 @return EFI_SUCCESS Set successfully.
2995 @return EFI_OUT_OF_RESOURCES Resource not enough to set variable.
2996 @return EFI_NOT_FOUND Not found.
2997 @return EFI_WRITE_PROTECTED Variable is read-only.
2998
2999 **/
3000 EFI_STATUS
3001 EFIAPI
3002 VariableServiceSetVariable (
3003 IN CHAR16 *VariableName,
3004 IN EFI_GUID *VendorGuid,
3005 IN UINT32 Attributes,
3006 IN UINTN DataSize,
3007 IN VOID *Data
3008 )
3009 {
3010 VARIABLE_POINTER_TRACK Variable;
3011 EFI_STATUS Status;
3012 VARIABLE_HEADER *NextVariable;
3013 EFI_PHYSICAL_ADDRESS Point;
3014 UINTN PayloadSize;
3015 LIST_ENTRY *Link;
3016 VARIABLE_ENTRY *Entry;
3017
3018 //
3019 // Check input parameters.
3020 //
3021 if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {
3022 return EFI_INVALID_PARAMETER;
3023 }
3024
3025 if (IsReadOnlyVariable (VariableName, VendorGuid)) {
3026 return EFI_WRITE_PROTECTED;
3027 }
3028
3029 if (DataSize != 0 && Data == NULL) {
3030 return EFI_INVALID_PARAMETER;
3031 }
3032
3033 //
3034 // Check for reserverd bit in variable attribute.
3035 //
3036 if ((Attributes & (~EFI_VARIABLE_ATTRIBUTES_MASK)) != 0) {
3037 return EFI_INVALID_PARAMETER;
3038 }
3039
3040 //
3041 // Make sure if runtime bit is set, boot service bit is set also.
3042 //
3043 if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
3044 return EFI_INVALID_PARAMETER;
3045 }
3046
3047 //
3048 // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute
3049 // cannot be set both.
3050 //
3051 if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)
3052 && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {
3053 return EFI_INVALID_PARAMETER;
3054 }
3055
3056 if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {
3057 if (DataSize < AUTHINFO_SIZE) {
3058 //
3059 // Try to write Authenticated Variable without AuthInfo.
3060 //
3061 return EFI_SECURITY_VIOLATION;
3062 }
3063 PayloadSize = DataSize - AUTHINFO_SIZE;
3064 } else if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {
3065 //
3066 // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor.
3067 //
3068 if (DataSize < OFFSET_OF_AUTHINFO2_CERT_DATA ||
3069 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength > DataSize - (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) ||
3070 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength < OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) {
3071 return EFI_SECURITY_VIOLATION;
3072 }
3073 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
3074 } else {
3075 PayloadSize = DataSize;
3076 }
3077
3078 if ((UINTN)(~0) - PayloadSize < StrSize(VariableName)){
3079 //
3080 // Prevent whole variable size overflow
3081 //
3082 return EFI_INVALID_PARAMETER;
3083 }
3084
3085 //
3086 // The size of the VariableName, including the Unicode Null in bytes plus
3087 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)
3088 // bytes for HwErrRec, and PcdGet32 (PcdMaxVariableSize) bytes for the others.
3089 //
3090 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3091 if (StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER)) {
3092 return EFI_INVALID_PARAMETER;
3093 }
3094 if (!IsHwErrRecVariable(VariableName, VendorGuid)) {
3095 return EFI_INVALID_PARAMETER;
3096 }
3097 } else {
3098 //
3099 // The size of the VariableName, including the Unicode Null in bytes plus
3100 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxVariableSize) bytes.
3101 //
3102 if (StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER)) {
3103 return EFI_INVALID_PARAMETER;
3104 }
3105 }
3106
3107 Status = CheckEfiGlobalVariable (VariableName, VendorGuid, Attributes);
3108 if (EFI_ERROR (Status)) {
3109 return Status;
3110 }
3111
3112 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3113
3114 //
3115 // Consider reentrant in MCA/INIT/NMI. It needs be reupdated.
3116 //
3117 if (1 < InterlockedIncrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState)) {
3118 Point = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
3119 //
3120 // Parse non-volatile variable data and get last variable offset.
3121 //
3122 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point);
3123 while (IsValidVariableHeader (NextVariable, GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point))) {
3124 NextVariable = GetNextVariablePtr (NextVariable);
3125 }
3126 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point;
3127 }
3128
3129 if (mEndOfDxe && mEnableLocking) {
3130 //
3131 // Treat the variables listed in the forbidden variable list as read-only after leaving DXE phase.
3132 //
3133 for ( Link = GetFirstNode (&mLockedVariableList)
3134 ; !IsNull (&mLockedVariableList, Link)
3135 ; Link = GetNextNode (&mLockedVariableList, Link)
3136 ) {
3137 Entry = BASE_CR (Link, VARIABLE_ENTRY, Link);
3138 if (CompareGuid (&Entry->Guid, VendorGuid) && (StrCmp (Entry->Name, VariableName) == 0)) {
3139 Status = EFI_WRITE_PROTECTED;
3140 DEBUG ((EFI_D_INFO, "[Variable]: Changing readonly variable after leaving DXE phase - %g:%s\n", VendorGuid, VariableName));
3141 goto Done;
3142 }
3143 }
3144 }
3145
3146 //
3147 // Check whether the input variable is already existed.
3148 //
3149 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, TRUE);
3150 if (!EFI_ERROR (Status)) {
3151 if (((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) && AtRuntime ()) {
3152 Status = EFI_WRITE_PROTECTED;
3153 goto Done;
3154 }
3155 if (Attributes != 0 && (Attributes & (~EFI_VARIABLE_APPEND_WRITE)) != Variable.CurrPtr->Attributes) {
3156 //
3157 // If a preexisting variable is rewritten with different attributes, SetVariable() shall not
3158 // modify the variable and shall return EFI_INVALID_PARAMETER. Two exceptions to this rule:
3159 // 1. No access attributes specified
3160 // 2. The only attribute differing is EFI_VARIABLE_APPEND_WRITE
3161 //
3162 Status = EFI_INVALID_PARAMETER;
3163 goto Done;
3164 }
3165 }
3166
3167 if (!FeaturePcdGet (PcdUefiVariableDefaultLangDeprecate)) {
3168 //
3169 // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.
3170 //
3171 Status = AutoUpdateLangVariable (VariableName, Data, DataSize);
3172 if (EFI_ERROR (Status)) {
3173 //
3174 // The auto update operation failed, directly return to avoid inconsistency between PlatformLang and Lang.
3175 //
3176 goto Done;
3177 }
3178 }
3179
3180 //
3181 // Process PK, KEK, Sigdb seperately.
3182 //
3183 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_PLATFORM_KEY_NAME) == 0)){
3184 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, TRUE);
3185 } else if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0)) {
3186 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, FALSE);
3187 } else if (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&
3188 ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))) {
3189 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, FALSE);
3190 if (EFI_ERROR (Status)) {
3191 Status = ProcessVarWithKek (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes);
3192 }
3193 } else {
3194 Status = ProcessVariable (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes);
3195 }
3196
3197 Done:
3198 InterlockedDecrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState);
3199 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3200
3201 if (!AtRuntime ()) {
3202 if (!EFI_ERROR (Status)) {
3203 SecureBootHook (
3204 VariableName,
3205 VendorGuid
3206 );
3207 }
3208 }
3209
3210 return Status;
3211 }
3212
3213 /**
3214
3215 This code returns information about the EFI variables.
3216
3217 Caution: This function may receive untrusted input.
3218 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
3219
3220 @param Attributes Attributes bitmask to specify the type of variables
3221 on which to return information.
3222 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
3223 for the EFI variables associated with the attributes specified.
3224 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
3225 for EFI variables associated with the attributes specified.
3226 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
3227 associated with the attributes specified.
3228
3229 @return EFI_SUCCESS Query successfully.
3230
3231 **/
3232 EFI_STATUS
3233 EFIAPI
3234 VariableServiceQueryVariableInfoInternal (
3235 IN UINT32 Attributes,
3236 OUT UINT64 *MaximumVariableStorageSize,
3237 OUT UINT64 *RemainingVariableStorageSize,
3238 OUT UINT64 *MaximumVariableSize
3239 )
3240 {
3241 VARIABLE_HEADER *Variable;
3242 VARIABLE_HEADER *NextVariable;
3243 UINT64 VariableSize;
3244 VARIABLE_STORE_HEADER *VariableStoreHeader;
3245 UINT64 CommonVariableTotalSize;
3246 UINT64 HwErrVariableTotalSize;
3247 EFI_STATUS Status;
3248 VARIABLE_POINTER_TRACK VariablePtrTrack;
3249
3250 CommonVariableTotalSize = 0;
3251 HwErrVariableTotalSize = 0;
3252
3253 if((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
3254 //
3255 // Query is Volatile related.
3256 //
3257 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
3258 } else {
3259 //
3260 // Query is Non-Volatile related.
3261 //
3262 VariableStoreHeader = mNvVariableCache;
3263 }
3264
3265 //
3266 // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize
3267 // with the storage size (excluding the storage header size).
3268 //
3269 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);
3270
3271 //
3272 // Harware error record variable needs larger size.
3273 //
3274 if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
3275 *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize);
3276 *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER);
3277 } else {
3278 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
3279 ASSERT (PcdGet32 (PcdHwErrStorageSize) < VariableStoreHeader->Size);
3280 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize);
3281 }
3282
3283 //
3284 // Let *MaximumVariableSize be PcdGet32 (PcdMaxVariableSize) with the exception of the variable header size.
3285 //
3286 *MaximumVariableSize = PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER);
3287 }
3288
3289 //
3290 // Point to the starting address of the variables.
3291 //
3292 Variable = GetStartPointer (VariableStoreHeader);
3293
3294 //
3295 // Now walk through the related variable store.
3296 //
3297 while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
3298 NextVariable = GetNextVariablePtr (Variable);
3299 VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable;
3300
3301 if (AtRuntime ()) {
3302 //
3303 // We don't take the state of the variables in mind
3304 // when calculating RemainingVariableStorageSize,
3305 // since the space occupied by variables not marked with
3306 // VAR_ADDED is not allowed to be reclaimed in Runtime.
3307 //
3308 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3309 HwErrVariableTotalSize += VariableSize;
3310 } else {
3311 CommonVariableTotalSize += VariableSize;
3312 }
3313 } else {
3314 //
3315 // Only care about Variables with State VAR_ADDED, because
3316 // the space not marked as VAR_ADDED is reclaimable now.
3317 //
3318 if (Variable->State == VAR_ADDED) {
3319 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3320 HwErrVariableTotalSize += VariableSize;
3321 } else {
3322 CommonVariableTotalSize += VariableSize;
3323 }
3324 } else if (Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
3325 //
3326 // If it is a IN_DELETED_TRANSITION variable,
3327 // and there is not also a same ADDED one at the same time,
3328 // this IN_DELETED_TRANSITION variable is valid.
3329 //
3330 VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader);
3331 VariablePtrTrack.EndPtr = GetEndPointer (VariableStoreHeader);
3332 Status = FindVariableEx (
3333 GetVariableNamePtr (Variable),
3334 &Variable->VendorGuid,
3335 FALSE,
3336 &VariablePtrTrack
3337 );
3338 if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State != VAR_ADDED) {
3339 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3340 HwErrVariableTotalSize += VariableSize;
3341 } else {
3342 CommonVariableTotalSize += VariableSize;
3343 }
3344 }
3345 }
3346 }
3347
3348 //
3349 // Go to the next one.
3350 //
3351 Variable = NextVariable;
3352 }
3353
3354 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD){
3355 *RemainingVariableStorageSize = *MaximumVariableStorageSize - HwErrVariableTotalSize;
3356 }else {
3357 *RemainingVariableStorageSize = *MaximumVariableStorageSize - CommonVariableTotalSize;
3358 }
3359
3360 if (*RemainingVariableStorageSize < sizeof (VARIABLE_HEADER)) {
3361 *MaximumVariableSize = 0;
3362 } else if ((*RemainingVariableStorageSize - sizeof (VARIABLE_HEADER)) < *MaximumVariableSize) {
3363 *MaximumVariableSize = *RemainingVariableStorageSize - sizeof (VARIABLE_HEADER);
3364 }
3365
3366 return EFI_SUCCESS;
3367 }
3368
3369 /**
3370
3371 This code returns information about the EFI variables.
3372
3373 Caution: This function may receive untrusted input.
3374 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
3375
3376 @param Attributes Attributes bitmask to specify the type of variables
3377 on which to return information.
3378 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
3379 for the EFI variables associated with the attributes specified.
3380 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
3381 for EFI variables associated with the attributes specified.
3382 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
3383 associated with the attributes specified.
3384
3385 @return EFI_INVALID_PARAMETER An invalid combination of attribute bits was supplied.
3386 @return EFI_SUCCESS Query successfully.
3387 @return EFI_UNSUPPORTED The attribute is not supported on this platform.
3388
3389 **/
3390 EFI_STATUS
3391 EFIAPI
3392 VariableServiceQueryVariableInfo (
3393 IN UINT32 Attributes,
3394 OUT UINT64 *MaximumVariableStorageSize,
3395 OUT UINT64 *RemainingVariableStorageSize,
3396 OUT UINT64 *MaximumVariableSize
3397 )
3398 {
3399 EFI_STATUS Status;
3400
3401 if(MaximumVariableStorageSize == NULL || RemainingVariableStorageSize == NULL || MaximumVariableSize == NULL || Attributes == 0) {
3402 return EFI_INVALID_PARAMETER;
3403 }
3404
3405 if((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == 0) {
3406 //
3407 // Make sure the Attributes combination is supported by the platform.
3408 //
3409 return EFI_UNSUPPORTED;
3410 } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
3411 //
3412 // Make sure if runtime bit is set, boot service bit is set also.
3413 //
3414 return EFI_INVALID_PARAMETER;
3415 } else if (AtRuntime () && ((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) {
3416 //
3417 // Make sure RT Attribute is set if we are in Runtime phase.
3418 //
3419 return EFI_INVALID_PARAMETER;
3420 } else if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
3421 //
3422 // Make sure Hw Attribute is set with NV.
3423 //
3424 return EFI_INVALID_PARAMETER;
3425 }
3426
3427 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3428
3429 Status = VariableServiceQueryVariableInfoInternal (
3430 Attributes,
3431 MaximumVariableStorageSize,
3432 RemainingVariableStorageSize,
3433 MaximumVariableSize
3434 );
3435
3436 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
3437 return Status;
3438 }
3439
3440 /**
3441 This function reclaims variable storage if free size is below the threshold.
3442
3443 Caution: This function may be invoked at SMM mode.
3444 Care must be taken to make sure not security issue.
3445
3446 **/
3447 VOID
3448 ReclaimForOS(
3449 VOID
3450 )
3451 {
3452 EFI_STATUS Status;
3453 UINTN CommonVariableSpace;
3454 UINTN RemainingCommonVariableSpace;
3455 UINTN RemainingHwErrVariableSpace;
3456
3457 Status = EFI_SUCCESS;
3458
3459 CommonVariableSpace = ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase)))->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32(PcdHwErrStorageSize); //Allowable max size of common variable storage space
3460
3461 RemainingCommonVariableSpace = CommonVariableSpace - mVariableModuleGlobal->CommonVariableTotalSize;
3462
3463 RemainingHwErrVariableSpace = PcdGet32 (PcdHwErrStorageSize) - mVariableModuleGlobal->HwErrVariableTotalSize;
3464 //
3465 // Check if the free area is blow a threshold.
3466 //
3467 if ((RemainingCommonVariableSpace < PcdGet32 (PcdMaxVariableSize))
3468 || ((PcdGet32 (PcdHwErrStorageSize) != 0) &&
3469 (RemainingHwErrVariableSpace < PcdGet32 (PcdMaxHardwareErrorVariableSize)))){
3470 Status = Reclaim (
3471 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
3472 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
3473 FALSE,
3474 NULL,
3475 NULL,
3476 0,
3477 FALSE
3478 );
3479 ASSERT_EFI_ERROR (Status);
3480 }
3481 }
3482
3483 /**
3484 Init non-volatile variable store.
3485
3486 @retval EFI_SUCCESS Function successfully executed.
3487 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
3488 @retval EFI_VOLUME_CORRUPTED Variable Store or Firmware Volume for Variable Store is corrupted.
3489
3490 **/
3491 EFI_STATUS
3492 InitNonVolatileVariableStore (
3493 VOID
3494 )
3495 {
3496 EFI_FIRMWARE_VOLUME_HEADER *FvHeader;
3497 VARIABLE_HEADER *NextVariable;
3498 EFI_PHYSICAL_ADDRESS VariableStoreBase;
3499 UINT64 VariableStoreLength;
3500 UINTN VariableSize;
3501 EFI_HOB_GUID_TYPE *GuidHob;
3502 EFI_PHYSICAL_ADDRESS NvStorageBase;
3503 UINT8 *NvStorageData;
3504 UINT32 NvStorageSize;
3505 FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *FtwLastWriteData;
3506 UINT32 BackUpOffset;
3507 UINT32 BackUpSize;
3508
3509 mVariableModuleGlobal->FvbInstance = NULL;
3510
3511 //
3512 // Note that in EdkII variable driver implementation, Hardware Error Record type variable
3513 // is stored with common variable in the same NV region. So the platform integrator should
3514 // ensure that the value of PcdHwErrStorageSize is less than or equal to the value of
3515 // PcdFlashNvStorageVariableSize.
3516 //
3517 ASSERT (PcdGet32 (PcdHwErrStorageSize) <= PcdGet32 (PcdFlashNvStorageVariableSize));
3518
3519 //
3520 // Allocate runtime memory used for a memory copy of the FLASH region.
3521 // Keep the memory and the FLASH in sync as updates occur.
3522 //
3523 NvStorageSize = PcdGet32 (PcdFlashNvStorageVariableSize);
3524 NvStorageData = AllocateRuntimeZeroPool (NvStorageSize);
3525 if (NvStorageData == NULL) {
3526 return EFI_OUT_OF_RESOURCES;
3527 }
3528
3529 NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);
3530 if (NvStorageBase == 0) {
3531 NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);
3532 }
3533 //
3534 // Copy NV storage data to the memory buffer.
3535 //
3536 CopyMem (NvStorageData, (UINT8 *) (UINTN) NvStorageBase, NvStorageSize);
3537
3538 //
3539 // Check the FTW last write data hob.
3540 //
3541 GuidHob = GetFirstGuidHob (&gEdkiiFaultTolerantWriteGuid);
3542 if (GuidHob != NULL) {
3543 FtwLastWriteData = (FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *) GET_GUID_HOB_DATA (GuidHob);
3544 if (FtwLastWriteData->TargetAddress == NvStorageBase) {
3545 DEBUG ((EFI_D_INFO, "Variable: NV storage is backed up in spare block: 0x%x\n", (UINTN) FtwLastWriteData->SpareAddress));
3546 //
3547 // Copy the backed up NV storage data to the memory buffer from spare block.
3548 //
3549 CopyMem (NvStorageData, (UINT8 *) (UINTN) (FtwLastWriteData->SpareAddress), NvStorageSize);
3550 } else if ((FtwLastWriteData->TargetAddress > NvStorageBase) &&
3551 (FtwLastWriteData->TargetAddress < (NvStorageBase + NvStorageSize))) {
3552 //
3553 // Flash NV storage from the Offset is backed up in spare block.
3554 //
3555 BackUpOffset = (UINT32) (FtwLastWriteData->TargetAddress - NvStorageBase);
3556 BackUpSize = NvStorageSize - BackUpOffset;
3557 DEBUG ((EFI_D_INFO, "Variable: High partial NV storage from offset: %x is backed up in spare block: 0x%x\n", BackUpOffset, (UINTN) FtwLastWriteData->SpareAddress));
3558 //
3559 // Copy the partial backed up NV storage data to the memory buffer from spare block.
3560 //
3561 CopyMem (NvStorageData + BackUpOffset, (UINT8 *) (UINTN) FtwLastWriteData->SpareAddress, BackUpSize);
3562 }
3563 }
3564
3565 FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) NvStorageData;
3566
3567 //
3568 // Check if the Firmware Volume is not corrupted
3569 //
3570 if ((FvHeader->Signature != EFI_FVH_SIGNATURE) || (!CompareGuid (&gEfiSystemNvDataFvGuid, &FvHeader->FileSystemGuid))) {
3571 FreePool (NvStorageData);
3572 DEBUG ((EFI_D_ERROR, "Firmware Volume for Variable Store is corrupted\n"));
3573 return EFI_VOLUME_CORRUPTED;
3574 }
3575
3576 VariableStoreBase = (EFI_PHYSICAL_ADDRESS) ((UINTN) FvHeader + FvHeader->HeaderLength);
3577 VariableStoreLength = (UINT64) (NvStorageSize - FvHeader->HeaderLength);
3578
3579 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
3580 mNvVariableCache = (VARIABLE_STORE_HEADER *) (UINTN) VariableStoreBase;
3581 if (GetVariableStoreStatus (mNvVariableCache) != EfiValid) {
3582 FreePool (NvStorageData);
3583 DEBUG((EFI_D_ERROR, "Variable Store header is corrupted\n"));
3584 return EFI_VOLUME_CORRUPTED;
3585 }
3586 ASSERT(mNvVariableCache->Size == VariableStoreLength);
3587
3588 //
3589 // The max variable or hardware error variable size should be < variable store size.
3590 //
3591 ASSERT(MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize)) < VariableStoreLength);
3592
3593 //
3594 // Parse non-volatile variable data and get last variable offset.
3595 //
3596 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase);
3597 while (IsValidVariableHeader (NextVariable, GetEndPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase))) {
3598 VariableSize = NextVariable->NameSize + NextVariable->DataSize + sizeof (VARIABLE_HEADER);
3599 if ((NextVariable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
3600 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VariableSize);
3601 } else {
3602 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize);
3603 }
3604
3605 NextVariable = GetNextVariablePtr (NextVariable);
3606 }
3607 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) VariableStoreBase;
3608
3609 return EFI_SUCCESS;
3610 }
3611
3612 /**
3613 Flush the HOB variable to flash.
3614
3615 @param[in] VariableName Name of variable has been updated or deleted.
3616 @param[in] VendorGuid Guid of variable has been updated or deleted.
3617
3618 **/
3619 VOID
3620 FlushHobVariableToFlash (
3621 IN CHAR16 *VariableName,
3622 IN EFI_GUID *VendorGuid
3623 )
3624 {
3625 EFI_STATUS Status;
3626 VARIABLE_STORE_HEADER *VariableStoreHeader;
3627 VARIABLE_HEADER *Variable;
3628 VOID *VariableData;
3629 BOOLEAN ErrorFlag;
3630
3631 ErrorFlag = FALSE;
3632
3633 //
3634 // Flush the HOB variable to flash.
3635 //
3636 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
3637 VariableStoreHeader = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
3638 //
3639 // Set HobVariableBase to 0, it can avoid SetVariable to call back.
3640 //
3641 mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0;
3642 for ( Variable = GetStartPointer (VariableStoreHeader)
3643 ; IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))
3644 ; Variable = GetNextVariablePtr (Variable)
3645 ) {
3646 if (Variable->State != VAR_ADDED) {
3647 //
3648 // The HOB variable has been set to DELETED state in local.
3649 //
3650 continue;
3651 }
3652 ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0);
3653 if (VendorGuid == NULL || VariableName == NULL ||
3654 !CompareGuid (VendorGuid, &Variable->VendorGuid) ||
3655 StrCmp (VariableName, GetVariableNamePtr (Variable)) != 0) {
3656 VariableData = GetVariableDataPtr (Variable);
3657 Status = VariableServiceSetVariable (
3658 GetVariableNamePtr (Variable),
3659 &Variable->VendorGuid,
3660 Variable->Attributes,
3661 Variable->DataSize,
3662 VariableData
3663 );
3664 DEBUG ((EFI_D_INFO, "Variable driver flush the HOB variable to flash: %g %s %r\n", &Variable->VendorGuid, GetVariableNamePtr (Variable), Status));
3665 } else {
3666 //
3667 // The updated or deleted variable is matched with the HOB variable.
3668 // Don't break here because we will try to set other HOB variables
3669 // since this variable could be set successfully.
3670 //
3671 Status = EFI_SUCCESS;
3672 }
3673 if (!EFI_ERROR (Status)) {
3674 //
3675 // If set variable successful, or the updated or deleted variable is matched with the HOB variable,
3676 // set the HOB variable to DELETED state in local.
3677 //
3678 DEBUG ((EFI_D_INFO, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", &Variable->VendorGuid, GetVariableNamePtr (Variable)));
3679 Variable->State &= VAR_DELETED;
3680 } else {
3681 ErrorFlag = TRUE;
3682 }
3683 }
3684 if (ErrorFlag) {
3685 //
3686 // We still have HOB variable(s) not flushed in flash.
3687 //
3688 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStoreHeader;
3689 } else {
3690 //
3691 // All HOB variables have been flushed in flash.
3692 //
3693 DEBUG ((EFI_D_INFO, "Variable driver: all HOB variables have been flushed in flash.\n"));
3694 if (!AtRuntime ()) {
3695 FreePool ((VOID *) VariableStoreHeader);
3696 }
3697 }
3698 }
3699
3700 }
3701
3702 /**
3703 Initializes variable write service after FTW was ready.
3704
3705 @retval EFI_SUCCESS Function successfully executed.
3706 @retval Others Fail to initialize the variable service.
3707
3708 **/
3709 EFI_STATUS
3710 VariableWriteServiceInitialize (
3711 VOID
3712 )
3713 {
3714 EFI_STATUS Status;
3715 VARIABLE_STORE_HEADER *VariableStoreHeader;
3716 UINTN Index;
3717 UINT8 Data;
3718 EFI_PHYSICAL_ADDRESS VariableStoreBase;
3719 EFI_PHYSICAL_ADDRESS NvStorageBase;
3720
3721 NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);
3722 if (NvStorageBase == 0) {
3723 NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);
3724 }
3725 VariableStoreBase = NvStorageBase + (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(NvStorageBase))->HeaderLength);
3726
3727 //
3728 // Let NonVolatileVariableBase point to flash variable store base directly after FTW ready.
3729 //
3730 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
3731 VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;
3732
3733 //
3734 // Check if the free area is really free.
3735 //
3736 for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreHeader->Size; Index++) {
3737 Data = ((UINT8 *) mNvVariableCache)[Index];
3738 if (Data != 0xff) {
3739 //
3740 // There must be something wrong in variable store, do reclaim operation.
3741 //
3742 Status = Reclaim (
3743 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
3744 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
3745 FALSE,
3746 NULL,
3747 NULL,
3748 0,
3749 FALSE
3750 );
3751 if (EFI_ERROR (Status)) {
3752 return Status;
3753 }
3754 break;
3755 }
3756 }
3757
3758 FlushHobVariableToFlash (NULL, NULL);
3759
3760 //
3761 // Authenticated variable initialize.
3762 //
3763 Status = AutenticatedVariableServiceInitialize ();
3764
3765 return Status;
3766 }
3767
3768
3769 /**
3770 Initializes variable store area for non-volatile and volatile variable.
3771
3772 @retval EFI_SUCCESS Function successfully executed.
3773 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
3774
3775 **/
3776 EFI_STATUS
3777 VariableCommonInitialize (
3778 VOID
3779 )
3780 {
3781 EFI_STATUS Status;
3782 VARIABLE_STORE_HEADER *VolatileVariableStore;
3783 VARIABLE_STORE_HEADER *VariableStoreHeader;
3784 UINT64 VariableStoreLength;
3785 UINTN ScratchSize;
3786 EFI_HOB_GUID_TYPE *GuidHob;
3787
3788 //
3789 // Allocate runtime memory for variable driver global structure.
3790 //
3791 mVariableModuleGlobal = AllocateRuntimeZeroPool (sizeof (VARIABLE_MODULE_GLOBAL));
3792 if (mVariableModuleGlobal == NULL) {
3793 return EFI_OUT_OF_RESOURCES;
3794 }
3795
3796 InitializeLock (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);
3797
3798 //
3799 // Get HOB variable store.
3800 //
3801 GuidHob = GetFirstGuidHob (&gEfiAuthenticatedVariableGuid);
3802 if (GuidHob != NULL) {
3803 VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob);
3804 VariableStoreLength = (UINT64) (GuidHob->Header.HobLength - sizeof (EFI_HOB_GUID_TYPE));
3805 if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {
3806 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) AllocateRuntimeCopyPool ((UINTN) VariableStoreLength, (VOID *) VariableStoreHeader);
3807 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase == 0) {
3808 FreePool (mVariableModuleGlobal);
3809 return EFI_OUT_OF_RESOURCES;
3810 }
3811 } else {
3812 DEBUG ((EFI_D_ERROR, "HOB Variable Store header is corrupted!\n"));
3813 }
3814 }
3815
3816 //
3817 // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.
3818 //
3819 ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));
3820 VolatileVariableStore = AllocateRuntimePool (PcdGet32 (PcdVariableStoreSize) + ScratchSize);
3821 if (VolatileVariableStore == NULL) {
3822 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
3823 FreePool ((VOID *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase);
3824 }
3825 FreePool (mVariableModuleGlobal);
3826 return EFI_OUT_OF_RESOURCES;
3827 }
3828
3829 SetMem (VolatileVariableStore, PcdGet32 (PcdVariableStoreSize) + ScratchSize, 0xff);
3830
3831 //
3832 // Initialize Variable Specific Data.
3833 //
3834 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VolatileVariableStore;
3835 mVariableModuleGlobal->VolatileLastVariableOffset = (UINTN) GetStartPointer (VolatileVariableStore) - (UINTN) VolatileVariableStore;
3836
3837 CopyGuid (&VolatileVariableStore->Signature, &gEfiAuthenticatedVariableGuid);
3838 VolatileVariableStore->Size = PcdGet32 (PcdVariableStoreSize);
3839 VolatileVariableStore->Format = VARIABLE_STORE_FORMATTED;
3840 VolatileVariableStore->State = VARIABLE_STORE_HEALTHY;
3841 VolatileVariableStore->Reserved = 0;
3842 VolatileVariableStore->Reserved1 = 0;
3843
3844 //
3845 // Init non-volatile variable store.
3846 //
3847 Status = InitNonVolatileVariableStore ();
3848 if (EFI_ERROR (Status)) {
3849 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
3850 FreePool ((VOID *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase);
3851 }
3852 FreePool (mVariableModuleGlobal);
3853 FreePool (VolatileVariableStore);
3854 }
3855
3856 return Status;
3857 }
3858
3859
3860 /**
3861 Get the proper fvb handle and/or fvb protocol by the given Flash address.
3862
3863 @param[in] Address The Flash address.
3864 @param[out] FvbHandle In output, if it is not NULL, it points to the proper FVB handle.
3865 @param[out] FvbProtocol In output, if it is not NULL, it points to the proper FVB protocol.
3866
3867 **/
3868 EFI_STATUS
3869 GetFvbInfoByAddress (
3870 IN EFI_PHYSICAL_ADDRESS Address,
3871 OUT EFI_HANDLE *FvbHandle OPTIONAL,
3872 OUT EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL **FvbProtocol OPTIONAL
3873 )
3874 {
3875 EFI_STATUS Status;
3876 EFI_HANDLE *HandleBuffer;
3877 UINTN HandleCount;
3878 UINTN Index;
3879 EFI_PHYSICAL_ADDRESS FvbBaseAddress;
3880 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
3881 EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
3882 EFI_FVB_ATTRIBUTES_2 Attributes;
3883
3884 HandleBuffer = NULL;
3885 //
3886 // Get all FVB handles.
3887 //
3888 Status = GetFvbCountAndBuffer (&HandleCount, &HandleBuffer);
3889 if (EFI_ERROR (Status)) {
3890 return EFI_NOT_FOUND;
3891 }
3892
3893 //
3894 // Get the FVB to access variable store.
3895 //
3896 Fvb = NULL;
3897 for (Index = 0; Index < HandleCount; Index += 1, Status = EFI_NOT_FOUND, Fvb = NULL) {
3898 Status = GetFvbByHandle (HandleBuffer[Index], &Fvb);
3899 if (EFI_ERROR (Status)) {
3900 Status = EFI_NOT_FOUND;
3901 break;
3902 }
3903
3904 //
3905 // Ensure this FVB protocol supported Write operation.
3906 //
3907 Status = Fvb->GetAttributes (Fvb, &Attributes);
3908 if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {
3909 continue;
3910 }
3911
3912 //
3913 // Compare the address and select the right one.
3914 //
3915 Status = Fvb->GetPhysicalAddress (Fvb, &FvbBaseAddress);
3916 if (EFI_ERROR (Status)) {
3917 continue;
3918 }
3919
3920 FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) FvbBaseAddress);
3921 if ((Address >= FvbBaseAddress) && (Address < (FvbBaseAddress + FwVolHeader->FvLength))) {
3922 if (FvbHandle != NULL) {
3923 *FvbHandle = HandleBuffer[Index];
3924 }
3925 if (FvbProtocol != NULL) {
3926 *FvbProtocol = Fvb;
3927 }
3928 Status = EFI_SUCCESS;
3929 break;
3930 }
3931 }
3932 FreePool (HandleBuffer);
3933
3934 if (Fvb == NULL) {
3935 Status = EFI_NOT_FOUND;
3936 }
3937
3938 return Status;
3939 }
3940