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