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