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