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