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