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