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