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