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