]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c
1. Update the logic of UpdateVariable() for updating variable from:
[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 CopyMem (CurrPtr, (UINT8*) PubKeyHeader, sizeof (VARIABLE_HEADER));
812 Variable = (VARIABLE_HEADER*) CurrPtr;
813 Variable->DataSize = NewPubKeySize;
814 StrCpy (GetVariableNamePtr (Variable), GetVariableNamePtr (PubKeyHeader));
815 CopyMem (GetVariableDataPtr (Variable), NewPubKeyStore, NewPubKeySize);
816 CurrPtr = (UINT8*) GetNextVariablePtr (Variable);
817 CommonVariableTotalSize += (UINTN) CurrPtr - (UINTN) Variable;
818 } else {
819 //
820 // Reinstall all ADDED variables as long as they are not identical to Updating Variable.
821 //
822 Variable = GetStartPointer (VariableStoreHeader);
823 while (IsValidVariableHeader (Variable)) {
824 NextVariable = GetNextVariablePtr (Variable);
825 if (Variable->State == VAR_ADDED) {
826 if (UpdatingVariable != NULL) {
827 if (UpdatingVariable == Variable) {
828 Variable = NextVariable;
829 continue;
830 }
831
832 VariableNameSize = NameSizeOfVariable(Variable);
833 UpdatingVariableNameSize = NameSizeOfVariable(UpdatingVariable);
834
835 VariableNamePtr = GetVariableNamePtr (Variable);
836 UpdatingVariableNamePtr = GetVariableNamePtr (UpdatingVariable);
837 if (CompareGuid (&Variable->VendorGuid, &UpdatingVariable->VendorGuid) &&
838 VariableNameSize == UpdatingVariableNameSize &&
839 CompareMem (VariableNamePtr, UpdatingVariableNamePtr, VariableNameSize) == 0 ) {
840 Variable = NextVariable;
841 continue;
842 }
843 }
844 VariableSize = (UINTN) NextVariable - (UINTN) Variable;
845 CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);
846 CurrPtr += VariableSize;
847 if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
848 HwErrVariableTotalSize += VariableSize;
849 } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
850 CommonVariableTotalSize += VariableSize;
851 }
852 }
853 Variable = NextVariable;
854 }
855
856 //
857 // Reinstall the variable being updated if it is not NULL.
858 //
859 if (UpdatingVariable != NULL) {
860 VariableSize = (UINTN)(GetNextVariablePtr (UpdatingVariable)) - (UINTN)UpdatingVariable;
861 CopyMem (CurrPtr, (UINT8 *) UpdatingVariable, VariableSize);
862 UpdatingPtrTrack->CurrPtr = (VARIABLE_HEADER *)((UINTN)UpdatingPtrTrack->StartPtr + ((UINTN)CurrPtr - (UINTN)GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer)));
863 UpdatingPtrTrack->InDeletedTransitionPtr = NULL;
864 CurrPtr += VariableSize;
865 if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
866 HwErrVariableTotalSize += VariableSize;
867 } else if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
868 CommonVariableTotalSize += VariableSize;
869 }
870 }
871
872 //
873 // Reinstall all in delete transition variables.
874 //
875 Variable = GetStartPointer (VariableStoreHeader);
876 while (IsValidVariableHeader (Variable)) {
877 NextVariable = GetNextVariablePtr (Variable);
878 if (Variable != UpdatingVariable && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
879
880 //
881 // Buffer has cached all ADDED variable.
882 // Per IN_DELETED variable, we have to guarantee that
883 // no ADDED one in previous buffer.
884 //
885
886 FoundAdded = FALSE;
887 AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);
888 while (IsValidVariableHeader (AddedVariable)) {
889 NextAddedVariable = GetNextVariablePtr (AddedVariable);
890 NameSize = NameSizeOfVariable (AddedVariable);
891 if (CompareGuid (&AddedVariable->VendorGuid, &Variable->VendorGuid) &&
892 NameSize == NameSizeOfVariable (Variable)
893 ) {
894 Point0 = (VOID *) GetVariableNamePtr (AddedVariable);
895 Point1 = (VOID *) GetVariableNamePtr (Variable);
896 if (CompareMem (Point0, Point1, NameSize) == 0) {
897 FoundAdded = TRUE;
898 break;
899 }
900 }
901 AddedVariable = NextAddedVariable;
902 }
903 if (!FoundAdded) {
904 //
905 // Promote VAR_IN_DELETED_TRANSITION to VAR_ADDED.
906 //
907 VariableSize = (UINTN) NextVariable - (UINTN) Variable;
908 CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);
909 ((VARIABLE_HEADER *) CurrPtr)->State = VAR_ADDED;
910 CurrPtr += VariableSize;
911 if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
912 HwErrVariableTotalSize += VariableSize;
913 } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
914 CommonVariableTotalSize += VariableSize;
915 }
916 }
917 }
918
919 Variable = NextVariable;
920 }
921 }
922
923 if (IsVolatile) {
924 //
925 // If volatile variable store, just copy valid buffer.
926 //
927 SetMem ((UINT8 *) (UINTN) VariableBase, VariableStoreHeader->Size, 0xff);
928 CopyMem ((UINT8 *) (UINTN) VariableBase, ValidBuffer, (UINTN) (CurrPtr - (UINT8 *) ValidBuffer));
929 Status = EFI_SUCCESS;
930 } else {
931 //
932 // If non-volatile variable store, perform FTW here.
933 //
934 Status = FtwVariableSpace (
935 VariableBase,
936 ValidBuffer,
937 (UINTN) (CurrPtr - (UINT8 *) ValidBuffer)
938 );
939 CopyMem (mNvVariableCache, (CHAR8 *)(UINTN)VariableBase, VariableStoreHeader->Size);
940 }
941 if (!EFI_ERROR (Status)) {
942 *LastVariableOffset = (UINTN) (CurrPtr - (UINT8 *) ValidBuffer);
943 if (!IsVolatile) {
944 mVariableModuleGlobal->HwErrVariableTotalSize = HwErrVariableTotalSize;
945 mVariableModuleGlobal->CommonVariableTotalSize = CommonVariableTotalSize;
946 }
947 } else {
948 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase);
949 while (IsValidVariableHeader (NextVariable)) {
950 VariableSize = NextVariable->NameSize + NextVariable->DataSize + sizeof (VARIABLE_HEADER);
951 if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
952 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VariableSize);
953 } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
954 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize);
955 }
956
957 NextVariable = GetNextVariablePtr (NextVariable);
958 }
959 *LastVariableOffset = (UINTN) NextVariable - (UINTN) VariableBase;
960 }
961
962 if (NewPubKeyStore != NULL) {
963 FreePool (NewPubKeyStore);
964 }
965
966 if (NewPubKeyIndex != NULL) {
967 FreePool (NewPubKeyIndex);
968 }
969
970 FreePool (ValidBuffer);
971
972 return Status;
973 }
974
975 /**
976 Find the variable in the specified variable store.
977
978 @param[in] VariableName Name of the variable to be found
979 @param[in] VendorGuid Vendor GUID to be found.
980 @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
981 check at runtime when searching variable.
982 @param[in, out] PtrTrack Variable Track Pointer structure that contains Variable Information.
983
984 @retval EFI_SUCCESS Variable found successfully
985 @retval EFI_NOT_FOUND Variable not found
986 **/
987 EFI_STATUS
988 FindVariableEx (
989 IN CHAR16 *VariableName,
990 IN EFI_GUID *VendorGuid,
991 IN BOOLEAN IgnoreRtCheck,
992 IN OUT VARIABLE_POINTER_TRACK *PtrTrack
993 )
994 {
995 VARIABLE_HEADER *InDeletedVariable;
996 VOID *Point;
997
998 PtrTrack->InDeletedTransitionPtr = NULL;
999
1000 //
1001 // Find the variable by walk through HOB, volatile and non-volatile variable store.
1002 //
1003 InDeletedVariable = NULL;
1004
1005 for ( PtrTrack->CurrPtr = PtrTrack->StartPtr
1006 ; (PtrTrack->CurrPtr < PtrTrack->EndPtr) && IsValidVariableHeader (PtrTrack->CurrPtr)
1007 ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr)
1008 ) {
1009 if (PtrTrack->CurrPtr->State == VAR_ADDED ||
1010 PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)
1011 ) {
1012 if (IgnoreRtCheck || !AtRuntime () || ((PtrTrack->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
1013 if (VariableName[0] == 0) {
1014 if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
1015 InDeletedVariable = PtrTrack->CurrPtr;
1016 } else {
1017 PtrTrack->InDeletedTransitionPtr = InDeletedVariable;
1018 return EFI_SUCCESS;
1019 }
1020 } else {
1021 if (CompareGuid (VendorGuid, &PtrTrack->CurrPtr->VendorGuid)) {
1022 Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr);
1023
1024 ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0);
1025 if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) {
1026 if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
1027 InDeletedVariable = PtrTrack->CurrPtr;
1028 } else {
1029 PtrTrack->InDeletedTransitionPtr = InDeletedVariable;
1030 return EFI_SUCCESS;
1031 }
1032 }
1033 }
1034 }
1035 }
1036 }
1037 }
1038
1039 PtrTrack->CurrPtr = InDeletedVariable;
1040 return (PtrTrack->CurrPtr == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS;
1041 }
1042
1043
1044 /**
1045 Finds variable in storage blocks of volatile and non-volatile storage areas.
1046
1047 This code finds variable in storage blocks of volatile and non-volatile storage areas.
1048 If VariableName is an empty string, then we just return the first
1049 qualified variable without comparing VariableName and VendorGuid.
1050 If IgnoreRtCheck is TRUE, then we ignore the EFI_VARIABLE_RUNTIME_ACCESS attribute check
1051 at runtime when searching existing variable, only VariableName and VendorGuid are compared.
1052 Otherwise, variables without EFI_VARIABLE_RUNTIME_ACCESS are not visible at runtime.
1053
1054 @param[in] VariableName Name of the variable to be found.
1055 @param[in] VendorGuid Vendor GUID to be found.
1056 @param[out] PtrTrack VARIABLE_POINTER_TRACK structure for output,
1057 including the range searched and the target position.
1058 @param[in] Global Pointer to VARIABLE_GLOBAL structure, including
1059 base of volatile variable storage area, base of
1060 NV variable storage area, and a lock.
1061 @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
1062 check at runtime when searching variable.
1063
1064 @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while
1065 VendorGuid is NULL.
1066 @retval EFI_SUCCESS Variable successfully found.
1067 @retval EFI_NOT_FOUND Variable not found
1068
1069 **/
1070 EFI_STATUS
1071 FindVariable (
1072 IN CHAR16 *VariableName,
1073 IN EFI_GUID *VendorGuid,
1074 OUT VARIABLE_POINTER_TRACK *PtrTrack,
1075 IN VARIABLE_GLOBAL *Global,
1076 IN BOOLEAN IgnoreRtCheck
1077 )
1078 {
1079 EFI_STATUS Status;
1080 VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
1081 VARIABLE_STORE_TYPE Type;
1082
1083 if (VariableName[0] != 0 && VendorGuid == NULL) {
1084 return EFI_INVALID_PARAMETER;
1085 }
1086
1087 //
1088 // 0: Volatile, 1: HOB, 2: Non-Volatile.
1089 // The index and attributes mapping must be kept in this order as RuntimeServiceGetNextVariableName
1090 // make use of this mapping to implement search algorithm.
1091 //
1092 VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) Global->VolatileVariableBase;
1093 VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) Global->HobVariableBase;
1094 VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
1095
1096 //
1097 // Find the variable by walk through HOB, volatile and non-volatile variable store.
1098 //
1099 for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
1100 if (VariableStoreHeader[Type] == NULL) {
1101 continue;
1102 }
1103
1104 PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader[Type]);
1105 PtrTrack->EndPtr = GetEndPointer (VariableStoreHeader[Type]);
1106 PtrTrack->Volatile = (BOOLEAN) (Type == VariableStoreTypeVolatile);
1107
1108 Status = FindVariableEx (VariableName, VendorGuid, IgnoreRtCheck, PtrTrack);
1109 if (!EFI_ERROR (Status)) {
1110 return Status;
1111 }
1112 }
1113 return EFI_NOT_FOUND;
1114 }
1115
1116 /**
1117 Get index from supported language codes according to language string.
1118
1119 This code is used to get corresponding index in supported language codes. It can handle
1120 RFC4646 and ISO639 language tags.
1121 In ISO639 language tags, take 3-characters as a delimitation to find matched string and calculate the index.
1122 In RFC4646 language tags, take semicolon as a delimitation to find matched string and calculate the index.
1123
1124 For example:
1125 SupportedLang = "engfraengfra"
1126 Lang = "eng"
1127 Iso639Language = TRUE
1128 The return value is "0".
1129 Another example:
1130 SupportedLang = "en;fr;en-US;fr-FR"
1131 Lang = "fr-FR"
1132 Iso639Language = FALSE
1133 The return value is "3".
1134
1135 @param SupportedLang Platform supported language codes.
1136 @param Lang Configured language.
1137 @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
1138
1139 @retval The index of language in the language codes.
1140
1141 **/
1142 UINTN
1143 GetIndexFromSupportedLangCodes(
1144 IN CHAR8 *SupportedLang,
1145 IN CHAR8 *Lang,
1146 IN BOOLEAN Iso639Language
1147 )
1148 {
1149 UINTN Index;
1150 UINTN CompareLength;
1151 UINTN LanguageLength;
1152
1153 if (Iso639Language) {
1154 CompareLength = ISO_639_2_ENTRY_SIZE;
1155 for (Index = 0; Index < AsciiStrLen (SupportedLang); Index += CompareLength) {
1156 if (AsciiStrnCmp (Lang, SupportedLang + Index, CompareLength) == 0) {
1157 //
1158 // Successfully find the index of Lang string in SupportedLang string.
1159 //
1160 Index = Index / CompareLength;
1161 return Index;
1162 }
1163 }
1164 ASSERT (FALSE);
1165 return 0;
1166 } else {
1167 //
1168 // Compare RFC4646 language code
1169 //
1170 Index = 0;
1171 for (LanguageLength = 0; Lang[LanguageLength] != '\0'; LanguageLength++);
1172
1173 for (Index = 0; *SupportedLang != '\0'; Index++, SupportedLang += CompareLength) {
1174 //
1175 // Skip ';' characters in SupportedLang
1176 //
1177 for (; *SupportedLang != '\0' && *SupportedLang == ';'; SupportedLang++);
1178 //
1179 // Determine the length of the next language code in SupportedLang
1180 //
1181 for (CompareLength = 0; SupportedLang[CompareLength] != '\0' && SupportedLang[CompareLength] != ';'; CompareLength++);
1182
1183 if ((CompareLength == LanguageLength) &&
1184 (AsciiStrnCmp (Lang, SupportedLang, CompareLength) == 0)) {
1185 //
1186 // Successfully find the index of Lang string in SupportedLang string.
1187 //
1188 return Index;
1189 }
1190 }
1191 ASSERT (FALSE);
1192 return 0;
1193 }
1194 }
1195
1196 /**
1197 Get language string from supported language codes according to index.
1198
1199 This code is used to get corresponding language strings in supported language codes. It can handle
1200 RFC4646 and ISO639 language tags.
1201 In ISO639 language tags, take 3-characters as a delimitation. Find language string according to the index.
1202 In RFC4646 language tags, take semicolon as a delimitation. Find language string according to the index.
1203
1204 For example:
1205 SupportedLang = "engfraengfra"
1206 Index = "1"
1207 Iso639Language = TRUE
1208 The return value is "fra".
1209 Another example:
1210 SupportedLang = "en;fr;en-US;fr-FR"
1211 Index = "1"
1212 Iso639Language = FALSE
1213 The return value is "fr".
1214
1215 @param SupportedLang Platform supported language codes.
1216 @param Index The index in supported language codes.
1217 @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
1218
1219 @retval The language string in the language codes.
1220
1221 **/
1222 CHAR8 *
1223 GetLangFromSupportedLangCodes (
1224 IN CHAR8 *SupportedLang,
1225 IN UINTN Index,
1226 IN BOOLEAN Iso639Language
1227 )
1228 {
1229 UINTN SubIndex;
1230 UINTN CompareLength;
1231 CHAR8 *Supported;
1232
1233 SubIndex = 0;
1234 Supported = SupportedLang;
1235 if (Iso639Language) {
1236 //
1237 // According to the index of Lang string in SupportedLang string to get the language.
1238 // This code will be invoked in RUNTIME, therefore there is not a memory allocate/free operation.
1239 // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.
1240 //
1241 CompareLength = ISO_639_2_ENTRY_SIZE;
1242 mVariableModuleGlobal->Lang[CompareLength] = '\0';
1243 return CopyMem (mVariableModuleGlobal->Lang, SupportedLang + Index * CompareLength, CompareLength);
1244
1245 } else {
1246 while (TRUE) {
1247 //
1248 // Take semicolon as delimitation, sequentially traverse supported language codes.
1249 //
1250 for (CompareLength = 0; *Supported != ';' && *Supported != '\0'; CompareLength++) {
1251 Supported++;
1252 }
1253 if ((*Supported == '\0') && (SubIndex != Index)) {
1254 //
1255 // Have completed the traverse, but not find corrsponding string.
1256 // This case is not allowed to happen.
1257 //
1258 ASSERT(FALSE);
1259 return NULL;
1260 }
1261 if (SubIndex == Index) {
1262 //
1263 // According to the index of Lang string in SupportedLang string to get the language.
1264 // As this code will be invoked in RUNTIME, therefore there is not memory allocate/free operation.
1265 // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.
1266 //
1267 mVariableModuleGlobal->PlatformLang[CompareLength] = '\0';
1268 return CopyMem (mVariableModuleGlobal->PlatformLang, Supported - CompareLength, CompareLength);
1269 }
1270 SubIndex++;
1271
1272 //
1273 // Skip ';' characters in Supported
1274 //
1275 for (; *Supported != '\0' && *Supported == ';'; Supported++);
1276 }
1277 }
1278 }
1279
1280 /**
1281 Returns a pointer to an allocated buffer that contains the best matching language
1282 from a set of supported languages.
1283
1284 This function supports both ISO 639-2 and RFC 4646 language codes, but language
1285 code types may not be mixed in a single call to this function. This function
1286 supports a variable argument list that allows the caller to pass in a prioritized
1287 list of language codes to test against all the language codes in SupportedLanguages.
1288
1289 If SupportedLanguages is NULL, then ASSERT().
1290
1291 @param[in] SupportedLanguages A pointer to a Null-terminated ASCII string that
1292 contains a set of language codes in the format
1293 specified by Iso639Language.
1294 @param[in] Iso639Language If TRUE, then all language codes are assumed to be
1295 in ISO 639-2 format. If FALSE, then all language
1296 codes are assumed to be in RFC 4646 language format
1297 @param[in] ... A variable argument list that contains pointers to
1298 Null-terminated ASCII strings that contain one or more
1299 language codes in the format specified by Iso639Language.
1300 The first language code from each of these language
1301 code lists is used to determine if it is an exact or
1302 close match to any of the language codes in
1303 SupportedLanguages. Close matches only apply to RFC 4646
1304 language codes, and the matching algorithm from RFC 4647
1305 is used to determine if a close match is present. If
1306 an exact or close match is found, then the matching
1307 language code from SupportedLanguages is returned. If
1308 no matches are found, then the next variable argument
1309 parameter is evaluated. The variable argument list
1310 is terminated by a NULL.
1311
1312 @retval NULL The best matching language could not be found in SupportedLanguages.
1313 @retval NULL There are not enough resources available to return the best matching
1314 language.
1315 @retval Other A pointer to a Null-terminated ASCII string that is the best matching
1316 language in SupportedLanguages.
1317
1318 **/
1319 CHAR8 *
1320 EFIAPI
1321 VariableGetBestLanguage (
1322 IN CONST CHAR8 *SupportedLanguages,
1323 IN BOOLEAN Iso639Language,
1324 ...
1325 )
1326 {
1327 VA_LIST Args;
1328 CHAR8 *Language;
1329 UINTN CompareLength;
1330 UINTN LanguageLength;
1331 CONST CHAR8 *Supported;
1332 CHAR8 *Buffer;
1333
1334 if (SupportedLanguages == NULL) {
1335 return NULL;
1336 }
1337
1338 VA_START (Args, Iso639Language);
1339 while ((Language = VA_ARG (Args, CHAR8 *)) != NULL) {
1340 //
1341 // Default to ISO 639-2 mode
1342 //
1343 CompareLength = 3;
1344 LanguageLength = MIN (3, AsciiStrLen (Language));
1345
1346 //
1347 // If in RFC 4646 mode, then determine the length of the first RFC 4646 language code in Language
1348 //
1349 if (!Iso639Language) {
1350 for (LanguageLength = 0; Language[LanguageLength] != 0 && Language[LanguageLength] != ';'; LanguageLength++);
1351 }
1352
1353 //
1354 // Trim back the length of Language used until it is empty
1355 //
1356 while (LanguageLength > 0) {
1357 //
1358 // Loop through all language codes in SupportedLanguages
1359 //
1360 for (Supported = SupportedLanguages; *Supported != '\0'; Supported += CompareLength) {
1361 //
1362 // In RFC 4646 mode, then Loop through all language codes in SupportedLanguages
1363 //
1364 if (!Iso639Language) {
1365 //
1366 // Skip ';' characters in Supported
1367 //
1368 for (; *Supported != '\0' && *Supported == ';'; Supported++);
1369 //
1370 // Determine the length of the next language code in Supported
1371 //
1372 for (CompareLength = 0; Supported[CompareLength] != 0 && Supported[CompareLength] != ';'; CompareLength++);
1373 //
1374 // If Language is longer than the Supported, then skip to the next language
1375 //
1376 if (LanguageLength > CompareLength) {
1377 continue;
1378 }
1379 }
1380 //
1381 // See if the first LanguageLength characters in Supported match Language
1382 //
1383 if (AsciiStrnCmp (Supported, Language, LanguageLength) == 0) {
1384 VA_END (Args);
1385
1386 Buffer = Iso639Language ? mVariableModuleGlobal->Lang : mVariableModuleGlobal->PlatformLang;
1387 Buffer[CompareLength] = '\0';
1388 return CopyMem (Buffer, Supported, CompareLength);
1389 }
1390 }
1391
1392 if (Iso639Language) {
1393 //
1394 // If ISO 639 mode, then each language can only be tested once
1395 //
1396 LanguageLength = 0;
1397 } else {
1398 //
1399 // If RFC 4646 mode, then trim Language from the right to the next '-' character
1400 //
1401 for (LanguageLength--; LanguageLength > 0 && Language[LanguageLength] != '-'; LanguageLength--);
1402 }
1403 }
1404 }
1405 VA_END (Args);
1406
1407 //
1408 // No matches were found
1409 //
1410 return NULL;
1411 }
1412
1413 /**
1414 Hook the operations in PlatformLangCodes, LangCodes, PlatformLang and Lang.
1415
1416 When setting Lang/LangCodes, simultaneously update PlatformLang/PlatformLangCodes.
1417
1418 According to UEFI spec, PlatformLangCodes/LangCodes are only set once in firmware initialization,
1419 and are read-only. Therefore, in variable driver, only store the original value for other use.
1420
1421 @param[in] VariableName Name of variable.
1422
1423 @param[in] Data Variable data.
1424
1425 @param[in] DataSize Size of data. 0 means delete.
1426
1427 **/
1428 VOID
1429 AutoUpdateLangVariable (
1430 IN CHAR16 *VariableName,
1431 IN VOID *Data,
1432 IN UINTN DataSize
1433 )
1434 {
1435 EFI_STATUS Status;
1436 CHAR8 *BestPlatformLang;
1437 CHAR8 *BestLang;
1438 UINTN Index;
1439 UINT32 Attributes;
1440 VARIABLE_POINTER_TRACK Variable;
1441 BOOLEAN SetLanguageCodes;
1442
1443 //
1444 // Don't do updates for delete operation
1445 //
1446 if (DataSize == 0) {
1447 return;
1448 }
1449
1450 SetLanguageCodes = FALSE;
1451
1452 if (StrCmp (VariableName, L"PlatformLangCodes") == 0) {
1453 //
1454 // PlatformLangCodes is a volatile variable, so it can not be updated at runtime.
1455 //
1456 if (AtRuntime ()) {
1457 return;
1458 }
1459
1460 SetLanguageCodes = TRUE;
1461
1462 //
1463 // According to UEFI spec, PlatformLangCodes is only set once in firmware initialization, and is read-only
1464 // Therefore, in variable driver, only store the original value for other use.
1465 //
1466 if (mVariableModuleGlobal->PlatformLangCodes != NULL) {
1467 FreePool (mVariableModuleGlobal->PlatformLangCodes);
1468 }
1469 mVariableModuleGlobal->PlatformLangCodes = AllocateRuntimeCopyPool (DataSize, Data);
1470 ASSERT (mVariableModuleGlobal->PlatformLangCodes != NULL);
1471
1472 //
1473 // PlatformLang holds a single language from PlatformLangCodes,
1474 // so the size of PlatformLangCodes is enough for the PlatformLang.
1475 //
1476 if (mVariableModuleGlobal->PlatformLang != NULL) {
1477 FreePool (mVariableModuleGlobal->PlatformLang);
1478 }
1479 mVariableModuleGlobal->PlatformLang = AllocateRuntimePool (DataSize);
1480 ASSERT (mVariableModuleGlobal->PlatformLang != NULL);
1481
1482 } else if (StrCmp (VariableName, L"LangCodes") == 0) {
1483 //
1484 // LangCodes is a volatile variable, so it can not be updated at runtime.
1485 //
1486 if (AtRuntime ()) {
1487 return;
1488 }
1489
1490 SetLanguageCodes = TRUE;
1491
1492 //
1493 // According to UEFI spec, LangCodes is only set once in firmware initialization, and is read-only
1494 // Therefore, in variable driver, only store the original value for other use.
1495 //
1496 if (mVariableModuleGlobal->LangCodes != NULL) {
1497 FreePool (mVariableModuleGlobal->LangCodes);
1498 }
1499 mVariableModuleGlobal->LangCodes = AllocateRuntimeCopyPool (DataSize, Data);
1500 ASSERT (mVariableModuleGlobal->LangCodes != NULL);
1501 }
1502
1503 if (SetLanguageCodes
1504 && (mVariableModuleGlobal->PlatformLangCodes != NULL)
1505 && (mVariableModuleGlobal->LangCodes != NULL)) {
1506 //
1507 // Update Lang if PlatformLang is already set
1508 // Update PlatformLang if Lang is already set
1509 //
1510 Status = FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1511 if (!EFI_ERROR (Status)) {
1512 //
1513 // Update Lang
1514 //
1515 VariableName = L"PlatformLang";
1516 Data = GetVariableDataPtr (Variable.CurrPtr);
1517 DataSize = Variable.CurrPtr->DataSize;
1518 } else {
1519 Status = FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1520 if (!EFI_ERROR (Status)) {
1521 //
1522 // Update PlatformLang
1523 //
1524 VariableName = L"Lang";
1525 Data = GetVariableDataPtr (Variable.CurrPtr);
1526 DataSize = Variable.CurrPtr->DataSize;
1527 } else {
1528 //
1529 // Neither PlatformLang nor Lang is set, directly return
1530 //
1531 return;
1532 }
1533 }
1534 }
1535
1536 //
1537 // According to UEFI spec, "Lang" and "PlatformLang" is NV|BS|RT attributions.
1538 //
1539 Attributes = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS;
1540
1541 if (StrCmp (VariableName, L"PlatformLang") == 0) {
1542 //
1543 // Update Lang when PlatformLangCodes/LangCodes were set.
1544 //
1545 if ((mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) {
1546 //
1547 // When setting PlatformLang, firstly get most matched language string from supported language codes.
1548 //
1549 BestPlatformLang = VariableGetBestLanguage (mVariableModuleGlobal->PlatformLangCodes, FALSE, Data, NULL);
1550 if (BestPlatformLang != NULL) {
1551 //
1552 // Get the corresponding index in language codes.
1553 //
1554 Index = GetIndexFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, BestPlatformLang, FALSE);
1555
1556 //
1557 // Get the corresponding ISO639 language tag according to RFC4646 language tag.
1558 //
1559 BestLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, Index, TRUE);
1560
1561 //
1562 // Successfully convert PlatformLang to Lang, and set the BestLang value into Lang variable simultaneously.
1563 //
1564 FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1565
1566 Status = UpdateVariable (L"Lang", &gEfiGlobalVariableGuid, BestLang,
1567 ISO_639_2_ENTRY_SIZE + 1, Attributes, 0, 0, &Variable, NULL);
1568
1569 DEBUG ((EFI_D_INFO, "Variable Driver Auto Update PlatformLang, PlatformLang:%a, Lang:%a\n", BestPlatformLang, BestLang));
1570
1571 ASSERT_EFI_ERROR(Status);
1572 }
1573 }
1574
1575 } else if (StrCmp (VariableName, L"Lang") == 0) {
1576 //
1577 // Update PlatformLang when PlatformLangCodes/LangCodes were set.
1578 //
1579 if ((mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) {
1580 //
1581 // When setting Lang, firstly get most matched language string from supported language codes.
1582 //
1583 BestLang = VariableGetBestLanguage (mVariableModuleGlobal->LangCodes, TRUE, Data, NULL);
1584 if (BestLang != NULL) {
1585 //
1586 // Get the corresponding index in language codes.
1587 //
1588 Index = GetIndexFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, BestLang, TRUE);
1589
1590 //
1591 // Get the corresponding RFC4646 language tag according to ISO639 language tag.
1592 //
1593 BestPlatformLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, Index, FALSE);
1594
1595 //
1596 // Successfully convert Lang to PlatformLang, and set the BestPlatformLang value into PlatformLang variable simultaneously.
1597 //
1598 FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
1599
1600 Status = UpdateVariable (L"PlatformLang", &gEfiGlobalVariableGuid, BestPlatformLang,
1601 AsciiStrSize (BestPlatformLang), Attributes, 0, 0, &Variable, NULL);
1602
1603 DEBUG ((EFI_D_INFO, "Variable Driver Auto Update Lang, Lang:%a, PlatformLang:%a\n", BestLang, BestPlatformLang));
1604 ASSERT_EFI_ERROR (Status);
1605 }
1606 }
1607 }
1608 }
1609
1610 /**
1611 Update the variable region with Variable information. If EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is set,
1612 index of associated public key is needed.
1613
1614 @param[in] VariableName Name of variable.
1615 @param[in] VendorGuid Guid of variable.
1616 @param[in] Data Variable data.
1617 @param[in] DataSize Size of data. 0 means delete.
1618 @param[in] Attributes Attributes of the variable.
1619 @param[in] KeyIndex Index of associated public key.
1620 @param[in] MonotonicCount Value of associated monotonic count.
1621 @param[in, out] CacheVariable The variable information which is used to keep track of variable usage.
1622 @param[in] TimeStamp Value of associated TimeStamp.
1623
1624 @retval EFI_SUCCESS The update operation is success.
1625 @retval EFI_OUT_OF_RESOURCES Variable region is full, can not write other data into this region.
1626
1627 **/
1628 EFI_STATUS
1629 UpdateVariable (
1630 IN CHAR16 *VariableName,
1631 IN EFI_GUID *VendorGuid,
1632 IN VOID *Data,
1633 IN UINTN DataSize,
1634 IN UINT32 Attributes OPTIONAL,
1635 IN UINT32 KeyIndex OPTIONAL,
1636 IN UINT64 MonotonicCount OPTIONAL,
1637 IN OUT VARIABLE_POINTER_TRACK *CacheVariable,
1638 IN EFI_TIME *TimeStamp OPTIONAL
1639 )
1640 {
1641 EFI_STATUS Status;
1642 VARIABLE_HEADER *NextVariable;
1643 UINTN ScratchSize;
1644 UINTN ScratchDataSize;
1645 UINTN NonVolatileVarableStoreSize;
1646 UINTN VarNameOffset;
1647 UINTN VarDataOffset;
1648 UINTN VarNameSize;
1649 UINTN VarSize;
1650 BOOLEAN Volatile;
1651 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
1652 UINT8 State;
1653 VARIABLE_POINTER_TRACK *Variable;
1654 VARIABLE_POINTER_TRACK NvVariable;
1655 VARIABLE_STORE_HEADER *VariableStoreHeader;
1656 UINTN CacheOffset;
1657 UINTN BufSize;
1658 UINTN DataOffset;
1659 UINTN RevBufSize;
1660
1661 if (mVariableModuleGlobal->FvbInstance == NULL) {
1662 //
1663 // The FVB protocol is not installed, so the EFI_VARIABLE_WRITE_ARCH_PROTOCOL is not installed.
1664 //
1665 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
1666 //
1667 // Trying to update NV variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
1668 //
1669 return EFI_NOT_AVAILABLE_YET;
1670 } else if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) {
1671 //
1672 // Trying to update volatile authenticated variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
1673 // The authenticated variable perhaps is not initialized, just return here.
1674 //
1675 return EFI_NOT_AVAILABLE_YET;
1676 }
1677 }
1678
1679 if ((CacheVariable->CurrPtr == NULL) || CacheVariable->Volatile) {
1680 Variable = CacheVariable;
1681 } else {
1682 //
1683 // Update/Delete existing NV variable.
1684 // CacheVariable points to the variable in the memory copy of Flash area
1685 // Now let Variable points to the same variable in Flash area.
1686 //
1687 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);
1688 Variable = &NvVariable;
1689 Variable->StartPtr = GetStartPointer (VariableStoreHeader);
1690 Variable->EndPtr = GetEndPointer (VariableStoreHeader);
1691 Variable->CurrPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr));
1692 if (CacheVariable->InDeletedTransitionPtr != NULL) {
1693 Variable->InDeletedTransitionPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->InDeletedTransitionPtr - (UINTN)CacheVariable->StartPtr));
1694 } else {
1695 Variable->InDeletedTransitionPtr = NULL;
1696 }
1697 Variable->Volatile = FALSE;
1698 }
1699
1700 Fvb = mVariableModuleGlobal->FvbInstance;
1701
1702 //
1703 // Tricky part: Use scratch data area at the end of volatile variable store
1704 // as a temporary storage.
1705 //
1706 NextVariable = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase));
1707 ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));
1708 ScratchDataSize = ScratchSize - sizeof (VARIABLE_HEADER) - StrSize (VariableName) - GET_PAD_SIZE (StrSize (VariableName));
1709
1710 if (Variable->CurrPtr != NULL) {
1711 //
1712 // Update/Delete existing variable.
1713 //
1714 if (AtRuntime ()) {
1715 //
1716 // If AtRuntime and the variable is Volatile and Runtime Access,
1717 // the volatile is ReadOnly, and SetVariable should be aborted and
1718 // return EFI_WRITE_PROTECTED.
1719 //
1720 if (Variable->Volatile) {
1721 Status = EFI_WRITE_PROTECTED;
1722 goto Done;
1723 }
1724 //
1725 // Only variable that have NV attributes can be updated/deleted in Runtime.
1726 //
1727 if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
1728 Status = EFI_INVALID_PARAMETER;
1729 goto Done;
1730 }
1731
1732 //
1733 // Only variable that have RT attributes can be updated/deleted in Runtime.
1734 //
1735 if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) {
1736 Status = EFI_INVALID_PARAMETER;
1737 goto Done;
1738 }
1739 }
1740
1741 //
1742 // Setting a data variable with no access, or zero DataSize attributes
1743 // causes it to be deleted.
1744 // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will
1745 // not delete the variable.
1746 //
1747 if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0))|| ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) {
1748 if (Variable->InDeletedTransitionPtr != NULL) {
1749 //
1750 // Both ADDED and IN_DELETED_TRANSITION variable are present,
1751 // set IN_DELETED_TRANSITION one to DELETED state first.
1752 //
1753 State = Variable->InDeletedTransitionPtr->State;
1754 State &= VAR_DELETED;
1755 Status = UpdateVariableStore (
1756 &mVariableModuleGlobal->VariableGlobal,
1757 Variable->Volatile,
1758 FALSE,
1759 Fvb,
1760 (UINTN) &Variable->InDeletedTransitionPtr->State,
1761 sizeof (UINT8),
1762 &State
1763 );
1764 if (!EFI_ERROR (Status)) {
1765 if (!Variable->Volatile) {
1766 CacheVariable->InDeletedTransitionPtr->State = State;
1767 }
1768 } else {
1769 goto Done;
1770 }
1771 }
1772
1773 State = Variable->CurrPtr->State;
1774 State &= VAR_DELETED;
1775
1776 Status = UpdateVariableStore (
1777 &mVariableModuleGlobal->VariableGlobal,
1778 Variable->Volatile,
1779 FALSE,
1780 Fvb,
1781 (UINTN) &Variable->CurrPtr->State,
1782 sizeof (UINT8),
1783 &State
1784 );
1785 if (!EFI_ERROR (Status)) {
1786 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE);
1787 if (!Variable->Volatile) {
1788 CacheVariable->CurrPtr->State = State;
1789 FlushHobVariableToFlash (VariableName, VendorGuid);
1790 }
1791 }
1792 goto Done;
1793 }
1794 //
1795 // If the variable is marked valid, and the same data has been passed in,
1796 // then return to the caller immediately.
1797 //
1798 if (DataSizeOfVariable (Variable->CurrPtr) == DataSize &&
1799 (CompareMem (Data, GetVariableDataPtr (Variable->CurrPtr), DataSize) == 0) &&
1800 ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) &&
1801 (TimeStamp == NULL)) {
1802 //
1803 // Variable content unchanged and no need to update timestamp, just return.
1804 //
1805 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);
1806 Status = EFI_SUCCESS;
1807 goto Done;
1808 } else if ((Variable->CurrPtr->State == VAR_ADDED) ||
1809 (Variable->CurrPtr->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION))) {
1810
1811 //
1812 // EFI_VARIABLE_APPEND_WRITE attribute only effects for existing variable
1813 //
1814 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) {
1815 //
1816 // Cache the previous variable data into StorageArea.
1817 //
1818 DataOffset = sizeof (VARIABLE_HEADER) + Variable->CurrPtr->NameSize + GET_PAD_SIZE (Variable->CurrPtr->NameSize);
1819 CopyMem (mStorageArea, (UINT8*)((UINTN) Variable->CurrPtr + DataOffset), Variable->CurrPtr->DataSize);
1820
1821 if (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) ||
1822 (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0))) {
1823 //
1824 // For variables with the GUID EFI_IMAGE_SECURITY_DATABASE_GUID (i.e. where the data
1825 // buffer is formatted as EFI_SIGNATURE_LIST), the driver shall not perform an append of
1826 // EFI_SIGNATURE_DATA values that are already part of the existing variable value.
1827 //
1828 BufSize = AppendSignatureList (mStorageArea, Variable->CurrPtr->DataSize, Data, DataSize);
1829 if (BufSize == Variable->CurrPtr->DataSize) {
1830 if ((TimeStamp == NULL) || CompareTimeStamp (TimeStamp, &Variable->CurrPtr->TimeStamp)) {
1831 //
1832 // New EFI_SIGNATURE_DATA is not found and timestamp is not later
1833 // than current timestamp, return EFI_SUCCESS directly.
1834 //
1835 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);
1836 Status = EFI_SUCCESS;
1837 goto Done;
1838 }
1839 }
1840 } else {
1841 //
1842 // For other Variables, append the new data to the end of previous data.
1843 //
1844 CopyMem ((UINT8*)((UINTN) mStorageArea + Variable->CurrPtr->DataSize), Data, DataSize);
1845 BufSize = Variable->CurrPtr->DataSize + DataSize;
1846 }
1847
1848 RevBufSize = MIN (PcdGet32 (PcdMaxVariableSize), ScratchDataSize);
1849 if (BufSize > RevBufSize) {
1850 //
1851 // If variable size (previous + current) is bigger than reserved buffer in runtime,
1852 // return EFI_OUT_OF_RESOURCES.
1853 //
1854 return EFI_OUT_OF_RESOURCES;
1855 }
1856
1857 //
1858 // Override Data and DataSize which are used for combined data area including previous and new data.
1859 //
1860 Data = mStorageArea;
1861 DataSize = BufSize;
1862 }
1863
1864 //
1865 // Mark the old variable as in delete transition.
1866 //
1867 State = Variable->CurrPtr->State;
1868 State &= VAR_IN_DELETED_TRANSITION;
1869
1870 Status = UpdateVariableStore (
1871 &mVariableModuleGlobal->VariableGlobal,
1872 Variable->Volatile,
1873 FALSE,
1874 Fvb,
1875 (UINTN) &Variable->CurrPtr->State,
1876 sizeof (UINT8),
1877 &State
1878 );
1879 if (EFI_ERROR (Status)) {
1880 goto Done;
1881 }
1882 if (!Variable->Volatile) {
1883 CacheVariable->CurrPtr->State = State;
1884 }
1885 }
1886 } else {
1887 //
1888 // Not found existing variable. Create a new variable.
1889 //
1890
1891 if ((DataSize == 0) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0)) {
1892 Status = EFI_SUCCESS;
1893 goto Done;
1894 }
1895
1896 //
1897 // Make sure we are trying to create a new variable.
1898 // Setting a data variable with zero DataSize or no access attributes means to delete it.
1899 //
1900 if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) {
1901 Status = EFI_NOT_FOUND;
1902 goto Done;
1903 }
1904
1905 //
1906 // Only variable have NV|RT attribute can be created in Runtime.
1907 //
1908 if (AtRuntime () &&
1909 (((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0))) {
1910 Status = EFI_INVALID_PARAMETER;
1911 goto Done;
1912 }
1913 }
1914
1915 //
1916 // Function part - create a new variable and copy the data.
1917 // Both update a variable and create a variable will come here.
1918
1919 SetMem (NextVariable, ScratchSize, 0xff);
1920
1921 NextVariable->StartId = VARIABLE_DATA;
1922 //
1923 // NextVariable->State = VAR_ADDED;
1924 //
1925 NextVariable->Reserved = 0;
1926 NextVariable->PubKeyIndex = KeyIndex;
1927 NextVariable->MonotonicCount = MonotonicCount;
1928 ZeroMem (&NextVariable->TimeStamp, sizeof (EFI_TIME));
1929
1930 if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&
1931 (TimeStamp != NULL)) {
1932 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) {
1933 CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
1934 } else {
1935 //
1936 // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only
1937 // when the new TimeStamp value is later than the current timestamp associated
1938 // with the variable, we need associate the new timestamp with the updated value.
1939 //
1940 if (Variable->CurrPtr != NULL) {
1941 if (CompareTimeStamp (&Variable->CurrPtr->TimeStamp, TimeStamp)) {
1942 CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
1943 }
1944 }
1945 }
1946 }
1947
1948 //
1949 // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned
1950 // Attributes bitmask parameter of a GetVariable() call.
1951 //
1952 NextVariable->Attributes = Attributes & (~EFI_VARIABLE_APPEND_WRITE);
1953
1954 VarNameOffset = sizeof (VARIABLE_HEADER);
1955 VarNameSize = StrSize (VariableName);
1956 CopyMem (
1957 (UINT8 *) ((UINTN) NextVariable + VarNameOffset),
1958 VariableName,
1959 VarNameSize
1960 );
1961 VarDataOffset = VarNameOffset + VarNameSize + GET_PAD_SIZE (VarNameSize);
1962 CopyMem (
1963 (UINT8 *) ((UINTN) NextVariable + VarDataOffset),
1964 Data,
1965 DataSize
1966 );
1967 CopyMem (&NextVariable->VendorGuid, VendorGuid, sizeof (EFI_GUID));
1968 //
1969 // There will be pad bytes after Data, the NextVariable->NameSize and
1970 // NextVariable->DataSize should not include pad size so that variable
1971 // service can get actual size in GetVariable.
1972 //
1973 NextVariable->NameSize = (UINT32)VarNameSize;
1974 NextVariable->DataSize = (UINT32)DataSize;
1975
1976 //
1977 // The actual size of the variable that stores in storage should
1978 // include pad size.
1979 //
1980 VarSize = VarDataOffset + DataSize + GET_PAD_SIZE (DataSize);
1981 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
1982 //
1983 // Create a nonvolatile variable.
1984 //
1985 Volatile = FALSE;
1986 NonVolatileVarableStoreSize = ((VARIABLE_STORE_HEADER *)(UINTN)(mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase))->Size;
1987 if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)
1988 && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))
1989 || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0)
1990 && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {
1991 if (AtRuntime ()) {
1992 Status = EFI_OUT_OF_RESOURCES;
1993 goto Done;
1994 }
1995 //
1996 // Perform garbage collection & reclaim operation.
1997 //
1998 Status = Reclaim (
1999 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
2000 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
2001 FALSE,
2002 Variable,
2003 FALSE,
2004 FALSE
2005 );
2006 if (EFI_ERROR (Status)) {
2007 goto Done;
2008 }
2009 //
2010 // If still no enough space, return out of resources.
2011 //
2012 if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)
2013 && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))
2014 || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0)
2015 && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {
2016 Status = EFI_OUT_OF_RESOURCES;
2017 goto Done;
2018 }
2019 if (Variable->CurrPtr != NULL) {
2020 CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
2021 CacheVariable->InDeletedTransitionPtr = NULL;
2022 }
2023 }
2024 //
2025 // Four steps
2026 // 1. Write variable header
2027 // 2. Set variable state to header valid
2028 // 3. Write variable data
2029 // 4. Set variable state to valid
2030 //
2031 //
2032 // Step 1:
2033 //
2034 CacheOffset = mVariableModuleGlobal->NonVolatileLastVariableOffset;
2035 Status = UpdateVariableStore (
2036 &mVariableModuleGlobal->VariableGlobal,
2037 FALSE,
2038 TRUE,
2039 Fvb,
2040 mVariableModuleGlobal->NonVolatileLastVariableOffset,
2041 sizeof (VARIABLE_HEADER),
2042 (UINT8 *) NextVariable
2043 );
2044
2045 if (EFI_ERROR (Status)) {
2046 goto Done;
2047 }
2048
2049 //
2050 // Step 2:
2051 //
2052 NextVariable->State = VAR_HEADER_VALID_ONLY;
2053 Status = UpdateVariableStore (
2054 &mVariableModuleGlobal->VariableGlobal,
2055 FALSE,
2056 TRUE,
2057 Fvb,
2058 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
2059 sizeof (UINT8),
2060 &NextVariable->State
2061 );
2062
2063 if (EFI_ERROR (Status)) {
2064 goto Done;
2065 }
2066 //
2067 // Step 3:
2068 //
2069 Status = UpdateVariableStore (
2070 &mVariableModuleGlobal->VariableGlobal,
2071 FALSE,
2072 TRUE,
2073 Fvb,
2074 mVariableModuleGlobal->NonVolatileLastVariableOffset + sizeof (VARIABLE_HEADER),
2075 (UINT32) VarSize - sizeof (VARIABLE_HEADER),
2076 (UINT8 *) NextVariable + sizeof (VARIABLE_HEADER)
2077 );
2078
2079 if (EFI_ERROR (Status)) {
2080 goto Done;
2081 }
2082 //
2083 // Step 4:
2084 //
2085 NextVariable->State = VAR_ADDED;
2086 Status = UpdateVariableStore (
2087 &mVariableModuleGlobal->VariableGlobal,
2088 FALSE,
2089 TRUE,
2090 Fvb,
2091 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
2092 sizeof (UINT8),
2093 &NextVariable->State
2094 );
2095
2096 if (EFI_ERROR (Status)) {
2097 goto Done;
2098 }
2099
2100 mVariableModuleGlobal->NonVolatileLastVariableOffset += HEADER_ALIGN (VarSize);
2101
2102 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
2103 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VarSize);
2104 } else {
2105 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VarSize);
2106 }
2107 //
2108 // update the memory copy of Flash region.
2109 //
2110 CopyMem ((UINT8 *)mNvVariableCache + CacheOffset, (UINT8 *)NextVariable, VarSize);
2111 } else {
2112 //
2113 // Create a volatile variable.
2114 //
2115 Volatile = TRUE;
2116
2117 if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >
2118 ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size) {
2119 //
2120 // Perform garbage collection & reclaim operation.
2121 //
2122 Status = Reclaim (
2123 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,
2124 &mVariableModuleGlobal->VolatileLastVariableOffset,
2125 TRUE,
2126 Variable,
2127 FALSE,
2128 FALSE
2129 );
2130 if (EFI_ERROR (Status)) {
2131 goto Done;
2132 }
2133 //
2134 // If still no enough space, return out of resources.
2135 //
2136 if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >
2137 ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size
2138 ) {
2139 Status = EFI_OUT_OF_RESOURCES;
2140 goto Done;
2141 }
2142 if (Variable->CurrPtr != NULL) {
2143 CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
2144 CacheVariable->InDeletedTransitionPtr = NULL;
2145 }
2146 }
2147
2148 NextVariable->State = VAR_ADDED;
2149 Status = UpdateVariableStore (
2150 &mVariableModuleGlobal->VariableGlobal,
2151 TRUE,
2152 TRUE,
2153 Fvb,
2154 mVariableModuleGlobal->VolatileLastVariableOffset,
2155 (UINT32) VarSize,
2156 (UINT8 *) NextVariable
2157 );
2158
2159 if (EFI_ERROR (Status)) {
2160 goto Done;
2161 }
2162
2163 mVariableModuleGlobal->VolatileLastVariableOffset += HEADER_ALIGN (VarSize);
2164 }
2165
2166 //
2167 // Mark the old variable as deleted.
2168 //
2169 if (!EFI_ERROR (Status) && Variable->CurrPtr != NULL) {
2170 if (Variable->InDeletedTransitionPtr != NULL) {
2171 //
2172 // Both ADDED and IN_DELETED_TRANSITION old variable are present,
2173 // set IN_DELETED_TRANSITION one to DELETED state first.
2174 //
2175 State = Variable->InDeletedTransitionPtr->State;
2176 State &= VAR_DELETED;
2177 Status = UpdateVariableStore (
2178 &mVariableModuleGlobal->VariableGlobal,
2179 Variable->Volatile,
2180 FALSE,
2181 Fvb,
2182 (UINTN) &Variable->InDeletedTransitionPtr->State,
2183 sizeof (UINT8),
2184 &State
2185 );
2186 if (!EFI_ERROR (Status)) {
2187 if (!Variable->Volatile) {
2188 CacheVariable->InDeletedTransitionPtr->State = State;
2189 }
2190 } else {
2191 goto Done;
2192 }
2193 }
2194
2195 State = Variable->CurrPtr->State;
2196 State &= VAR_DELETED;
2197
2198 Status = UpdateVariableStore (
2199 &mVariableModuleGlobal->VariableGlobal,
2200 Variable->Volatile,
2201 FALSE,
2202 Fvb,
2203 (UINTN) &Variable->CurrPtr->State,
2204 sizeof (UINT8),
2205 &State
2206 );
2207 if (!EFI_ERROR (Status) && !Variable->Volatile) {
2208 CacheVariable->CurrPtr->State = State;
2209 }
2210 }
2211
2212 if (!EFI_ERROR (Status)) {
2213 UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);
2214 if (!Volatile) {
2215 FlushHobVariableToFlash (VariableName, VendorGuid);
2216 }
2217 }
2218
2219 Done:
2220 return Status;
2221 }
2222
2223 /**
2224 Check if a Unicode character is a hexadecimal character.
2225
2226 This function checks if a Unicode character is a
2227 hexadecimal character. The valid hexadecimal character is
2228 L'0' to L'9', L'a' to L'f', or L'A' to L'F'.
2229
2230
2231 @param Char The character to check against.
2232
2233 @retval TRUE If the Char is a hexadecmial character.
2234 @retval FALSE If the Char is not a hexadecmial character.
2235
2236 **/
2237 BOOLEAN
2238 EFIAPI
2239 IsHexaDecimalDigitCharacter (
2240 IN CHAR16 Char
2241 )
2242 {
2243 return (BOOLEAN) ((Char >= L'0' && Char <= L'9') || (Char >= L'A' && Char <= L'F') || (Char >= L'a' && Char <= L'f'));
2244 }
2245
2246 /**
2247
2248 This code checks if variable is hardware error record variable or not.
2249
2250 According to UEFI spec, hardware error record variable should use the EFI_HARDWARE_ERROR_VARIABLE VendorGuid
2251 and have the L"HwErrRec####" name convention, #### is a printed hex value and no 0x or h is included in the hex value.
2252
2253 @param VariableName Pointer to variable name.
2254 @param VendorGuid Variable Vendor Guid.
2255
2256 @retval TRUE Variable is hardware error record variable.
2257 @retval FALSE Variable is not hardware error record variable.
2258
2259 **/
2260 BOOLEAN
2261 EFIAPI
2262 IsHwErrRecVariable (
2263 IN CHAR16 *VariableName,
2264 IN EFI_GUID *VendorGuid
2265 )
2266 {
2267 if (!CompareGuid (VendorGuid, &gEfiHardwareErrorVariableGuid) ||
2268 (StrLen (VariableName) != StrLen (L"HwErrRec####")) ||
2269 (StrnCmp(VariableName, L"HwErrRec", StrLen (L"HwErrRec")) != 0) ||
2270 !IsHexaDecimalDigitCharacter (VariableName[0x8]) ||
2271 !IsHexaDecimalDigitCharacter (VariableName[0x9]) ||
2272 !IsHexaDecimalDigitCharacter (VariableName[0xA]) ||
2273 !IsHexaDecimalDigitCharacter (VariableName[0xB])) {
2274 return FALSE;
2275 }
2276
2277 return TRUE;
2278 }
2279
2280 /**
2281 This code checks if variable should be treated as read-only variable.
2282
2283 @param[in] VariableName Name of the Variable.
2284 @param[in] VendorGuid GUID of the Variable.
2285
2286 @retval TRUE This variable is read-only variable.
2287 @retval FALSE This variable is NOT read-only variable.
2288
2289 **/
2290 BOOLEAN
2291 IsReadOnlyVariable (
2292 IN CHAR16 *VariableName,
2293 IN EFI_GUID *VendorGuid
2294 )
2295 {
2296 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid)) {
2297 if ((StrCmp (VariableName, EFI_SETUP_MODE_NAME) == 0) ||
2298 (StrCmp (VariableName, EFI_SIGNATURE_SUPPORT_NAME) == 0) ||
2299 (StrCmp (VariableName, EFI_SECURE_BOOT_MODE_NAME) == 0)) {
2300 return TRUE;
2301 }
2302 }
2303
2304 return FALSE;
2305 }
2306
2307 /**
2308
2309 This code finds variable in storage blocks (Volatile or Non-Volatile).
2310
2311 Caution: This function may receive untrusted input.
2312 This function may be invoked in SMM mode, and datasize is external input.
2313 This function will do basic validation, before parse the data.
2314
2315 @param VariableName Name of Variable to be found.
2316 @param VendorGuid Variable vendor GUID.
2317 @param Attributes Attribute value of the variable found.
2318 @param DataSize Size of Data found. If size is less than the
2319 data, this value contains the required size.
2320 @param Data Data pointer.
2321
2322 @return EFI_INVALID_PARAMETER Invalid parameter.
2323 @return EFI_SUCCESS Find the specified variable.
2324 @return EFI_NOT_FOUND Not found.
2325 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2326
2327 **/
2328 EFI_STATUS
2329 EFIAPI
2330 VariableServiceGetVariable (
2331 IN CHAR16 *VariableName,
2332 IN EFI_GUID *VendorGuid,
2333 OUT UINT32 *Attributes OPTIONAL,
2334 IN OUT UINTN *DataSize,
2335 OUT VOID *Data
2336 )
2337 {
2338 EFI_STATUS Status;
2339 VARIABLE_POINTER_TRACK Variable;
2340 UINTN VarDataSize;
2341
2342 if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {
2343 return EFI_INVALID_PARAMETER;
2344 }
2345
2346 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2347
2348 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2349 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2350 goto Done;
2351 }
2352
2353 //
2354 // Get data size
2355 //
2356 VarDataSize = DataSizeOfVariable (Variable.CurrPtr);
2357 ASSERT (VarDataSize != 0);
2358
2359 if (*DataSize >= VarDataSize) {
2360 if (Data == NULL) {
2361 Status = EFI_INVALID_PARAMETER;
2362 goto Done;
2363 }
2364
2365 CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr), VarDataSize);
2366 if (Attributes != NULL) {
2367 *Attributes = Variable.CurrPtr->Attributes;
2368 }
2369
2370 *DataSize = VarDataSize;
2371 UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);
2372
2373 Status = EFI_SUCCESS;
2374 goto Done;
2375 } else {
2376 *DataSize = VarDataSize;
2377 Status = EFI_BUFFER_TOO_SMALL;
2378 goto Done;
2379 }
2380
2381 Done:
2382 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2383 return Status;
2384 }
2385
2386
2387
2388 /**
2389
2390 This code Finds the Next available variable.
2391
2392 Caution: This function may receive untrusted input.
2393 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2394
2395 @param VariableNameSize Size of the variable name.
2396 @param VariableName Pointer to variable name.
2397 @param VendorGuid Variable Vendor Guid.
2398
2399 @return EFI_INVALID_PARAMETER Invalid parameter.
2400 @return EFI_SUCCESS Find the specified variable.
2401 @return EFI_NOT_FOUND Not found.
2402 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2403
2404 **/
2405 EFI_STATUS
2406 EFIAPI
2407 VariableServiceGetNextVariableName (
2408 IN OUT UINTN *VariableNameSize,
2409 IN OUT CHAR16 *VariableName,
2410 IN OUT EFI_GUID *VendorGuid
2411 )
2412 {
2413 VARIABLE_STORE_TYPE Type;
2414 VARIABLE_POINTER_TRACK Variable;
2415 VARIABLE_POINTER_TRACK VariableInHob;
2416 VARIABLE_POINTER_TRACK VariablePtrTrack;
2417 UINTN VarNameSize;
2418 EFI_STATUS Status;
2419 VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
2420
2421 if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
2422 return EFI_INVALID_PARAMETER;
2423 }
2424
2425 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2426
2427 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2428 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2429 goto Done;
2430 }
2431
2432 if (VariableName[0] != 0) {
2433 //
2434 // If variable name is not NULL, get next variable.
2435 //
2436 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2437 }
2438
2439 //
2440 // 0: Volatile, 1: HOB, 2: Non-Volatile.
2441 // The index and attributes mapping must be kept in this order as FindVariable
2442 // makes use of this mapping to implement search algorithm.
2443 //
2444 VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
2445 VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
2446 VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
2447
2448 while (TRUE) {
2449 //
2450 // Switch from Volatile to HOB, to Non-Volatile.
2451 //
2452 while ((Variable.CurrPtr >= Variable.EndPtr) ||
2453 (Variable.CurrPtr == NULL) ||
2454 !IsValidVariableHeader (Variable.CurrPtr)
2455 ) {
2456 //
2457 // Find current storage index
2458 //
2459 for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
2460 if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
2461 break;
2462 }
2463 }
2464 ASSERT (Type < VariableStoreTypeMax);
2465 //
2466 // Switch to next storage
2467 //
2468 for (Type++; Type < VariableStoreTypeMax; Type++) {
2469 if (VariableStoreHeader[Type] != NULL) {
2470 break;
2471 }
2472 }
2473 //
2474 // Capture the case that
2475 // 1. current storage is the last one, or
2476 // 2. no further storage
2477 //
2478 if (Type == VariableStoreTypeMax) {
2479 Status = EFI_NOT_FOUND;
2480 goto Done;
2481 }
2482 Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);
2483 Variable.EndPtr = GetEndPointer (VariableStoreHeader[Type]);
2484 Variable.CurrPtr = Variable.StartPtr;
2485 }
2486
2487 //
2488 // Variable is found
2489 //
2490 if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
2491 if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
2492 if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
2493 //
2494 // If it is a IN_DELETED_TRANSITION variable,
2495 // and there is also a same ADDED one at the same time,
2496 // don't return it.
2497 //
2498 VariablePtrTrack.StartPtr = Variable.StartPtr;
2499 VariablePtrTrack.EndPtr = Variable.EndPtr;
2500 Status = FindVariableEx (
2501 GetVariableNamePtr (Variable.CurrPtr),
2502 &Variable.CurrPtr->VendorGuid,
2503 FALSE,
2504 &VariablePtrTrack
2505 );
2506 if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
2507 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2508 continue;
2509 }
2510 }
2511
2512 //
2513 // Don't return NV variable when HOB overrides it
2514 //
2515 if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&
2516 (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))
2517 ) {
2518 VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);
2519 VariableInHob.EndPtr = GetEndPointer (VariableStoreHeader[VariableStoreTypeHob]);
2520 Status = FindVariableEx (
2521 GetVariableNamePtr (Variable.CurrPtr),
2522 &Variable.CurrPtr->VendorGuid,
2523 FALSE,
2524 &VariableInHob
2525 );
2526 if (!EFI_ERROR (Status)) {
2527 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2528 continue;
2529 }
2530 }
2531
2532 VarNameSize = NameSizeOfVariable (Variable.CurrPtr);
2533 ASSERT (VarNameSize != 0);
2534
2535 if (VarNameSize <= *VariableNameSize) {
2536 CopyMem (VariableName, GetVariableNamePtr (Variable.CurrPtr), VarNameSize);
2537 CopyMem (VendorGuid, &Variable.CurrPtr->VendorGuid, sizeof (EFI_GUID));
2538 Status = EFI_SUCCESS;
2539 } else {
2540 Status = EFI_BUFFER_TOO_SMALL;
2541 }
2542
2543 *VariableNameSize = VarNameSize;
2544 goto Done;
2545 }
2546 }
2547
2548 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2549 }
2550
2551 Done:
2552 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2553 return Status;
2554 }
2555
2556 /**
2557
2558 This code sets variable in storage blocks (Volatile or Non-Volatile).
2559
2560 Caution: This function may receive untrusted input.
2561 This function may be invoked in SMM mode, and datasize and data are external input.
2562 This function will do basic validation, before parse the data.
2563 This function will parse the authentication carefully to avoid security issues, like
2564 buffer overflow, integer overflow.
2565 This function will check attribute carefully to avoid authentication bypass.
2566
2567 @param VariableName Name of Variable to be found.
2568 @param VendorGuid Variable vendor GUID.
2569 @param Attributes Attribute value of the variable found
2570 @param DataSize Size of Data found. If size is less than the
2571 data, this value contains the required size.
2572 @param Data Data pointer.
2573
2574 @return EFI_INVALID_PARAMETER Invalid parameter.
2575 @return EFI_SUCCESS Set successfully.
2576 @return EFI_OUT_OF_RESOURCES Resource not enough to set variable.
2577 @return EFI_NOT_FOUND Not found.
2578 @return EFI_WRITE_PROTECTED Variable is read-only.
2579
2580 **/
2581 EFI_STATUS
2582 EFIAPI
2583 VariableServiceSetVariable (
2584 IN CHAR16 *VariableName,
2585 IN EFI_GUID *VendorGuid,
2586 IN UINT32 Attributes,
2587 IN UINTN DataSize,
2588 IN VOID *Data
2589 )
2590 {
2591 VARIABLE_POINTER_TRACK Variable;
2592 EFI_STATUS Status;
2593 VARIABLE_HEADER *NextVariable;
2594 EFI_PHYSICAL_ADDRESS Point;
2595 UINTN PayloadSize;
2596
2597 //
2598 // Check input parameters.
2599 //
2600 if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {
2601 return EFI_INVALID_PARAMETER;
2602 }
2603
2604 if (IsReadOnlyVariable (VariableName, VendorGuid)) {
2605 return EFI_WRITE_PROTECTED;
2606 }
2607
2608 if (DataSize != 0 && Data == NULL) {
2609 return EFI_INVALID_PARAMETER;
2610 }
2611
2612 //
2613 // Check for reserverd bit in variable attribute.
2614 //
2615 if ((Attributes & (~EFI_VARIABLE_ATTRIBUTES_MASK)) != 0) {
2616 return EFI_INVALID_PARAMETER;
2617 }
2618
2619 //
2620 // Make sure if runtime bit is set, boot service bit is set also.
2621 //
2622 if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
2623 return EFI_INVALID_PARAMETER;
2624 }
2625
2626 //
2627 // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute
2628 // cannot be set both.
2629 //
2630 if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)
2631 && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {
2632 return EFI_INVALID_PARAMETER;
2633 }
2634
2635 if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {
2636 if (DataSize < AUTHINFO_SIZE) {
2637 //
2638 // Try to write Authenticated Variable without AuthInfo.
2639 //
2640 return EFI_SECURITY_VIOLATION;
2641 }
2642 PayloadSize = DataSize - AUTHINFO_SIZE;
2643 } else if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {
2644 //
2645 // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor.
2646 //
2647 if (DataSize < OFFSET_OF_AUTHINFO2_CERT_DATA ||
2648 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength > DataSize - (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) ||
2649 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength < OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) {
2650 return EFI_SECURITY_VIOLATION;
2651 }
2652 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
2653 } else {
2654 PayloadSize = DataSize;
2655 }
2656
2657 //
2658 // The size of the VariableName, including the Unicode Null in bytes plus
2659 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)
2660 // bytes for HwErrRec, and PcdGet32 (PcdMaxVariableSize) bytes for the others.
2661 //
2662 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2663 if ((PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize)) ||
2664 (sizeof (VARIABLE_HEADER) + StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize))) {
2665 return EFI_INVALID_PARAMETER;
2666 }
2667 if (!IsHwErrRecVariable(VariableName, VendorGuid)) {
2668 return EFI_INVALID_PARAMETER;
2669 }
2670 } else {
2671 //
2672 // The size of the VariableName, including the Unicode Null in bytes plus
2673 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxVariableSize) bytes.
2674 //
2675 if ((PayloadSize > PcdGet32 (PcdMaxVariableSize)) ||
2676 (sizeof (VARIABLE_HEADER) + StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxVariableSize))) {
2677 return EFI_INVALID_PARAMETER;
2678 }
2679 }
2680
2681 if (AtRuntime ()) {
2682 //
2683 // HwErrRecSupport Global Variable identifies the level of hardware error record persistence
2684 // support implemented by the platform. This variable is only modified by firmware and is read-only to the OS.
2685 //
2686 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, L"HwErrRecSupport") == 0)) {
2687 return EFI_WRITE_PROTECTED;
2688 }
2689 }
2690
2691 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2692
2693 //
2694 // Consider reentrant in MCA/INIT/NMI. It needs be reupdated.
2695 //
2696 if (1 < InterlockedIncrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState)) {
2697 Point = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
2698 //
2699 // Parse non-volatile variable data and get last variable offset.
2700 //
2701 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point);
2702 while ((NextVariable < GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point))
2703 && IsValidVariableHeader (NextVariable)) {
2704 NextVariable = GetNextVariablePtr (NextVariable);
2705 }
2706 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point;
2707 }
2708
2709 //
2710 // Check whether the input variable is already existed.
2711 //
2712 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, TRUE);
2713 if (!EFI_ERROR (Status)) {
2714 if (((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) && AtRuntime ()) {
2715 return EFI_WRITE_PROTECTED;
2716 }
2717 }
2718
2719 //
2720 // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.
2721 //
2722 AutoUpdateLangVariable (VariableName, Data, DataSize);
2723 //
2724 // Process PK, KEK, Sigdb seperately.
2725 //
2726 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_PLATFORM_KEY_NAME) == 0)){
2727 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, TRUE);
2728 } else if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0)) {
2729 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, FALSE);
2730 } else if (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&
2731 ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))) {
2732 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, FALSE);
2733 if (EFI_ERROR (Status)) {
2734 Status = ProcessVarWithKek (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes);
2735 }
2736 } else {
2737 Status = ProcessVariable (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes);
2738 }
2739
2740 InterlockedDecrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState);
2741 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2742
2743 return Status;
2744 }
2745
2746 /**
2747
2748 This code returns information about the EFI variables.
2749
2750 Caution: This function may receive untrusted input.
2751 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2752
2753 @param Attributes Attributes bitmask to specify the type of variables
2754 on which to return information.
2755 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
2756 for the EFI variables associated with the attributes specified.
2757 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
2758 for EFI variables associated with the attributes specified.
2759 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
2760 associated with the attributes specified.
2761
2762 @return EFI_INVALID_PARAMETER An invalid combination of attribute bits was supplied.
2763 @return EFI_SUCCESS Query successfully.
2764 @return EFI_UNSUPPORTED The attribute is not supported on this platform.
2765
2766 **/
2767 EFI_STATUS
2768 EFIAPI
2769 VariableServiceQueryVariableInfo (
2770 IN UINT32 Attributes,
2771 OUT UINT64 *MaximumVariableStorageSize,
2772 OUT UINT64 *RemainingVariableStorageSize,
2773 OUT UINT64 *MaximumVariableSize
2774 )
2775 {
2776 VARIABLE_HEADER *Variable;
2777 VARIABLE_HEADER *NextVariable;
2778 UINT64 VariableSize;
2779 VARIABLE_STORE_HEADER *VariableStoreHeader;
2780 UINT64 CommonVariableTotalSize;
2781 UINT64 HwErrVariableTotalSize;
2782
2783 CommonVariableTotalSize = 0;
2784 HwErrVariableTotalSize = 0;
2785
2786 if(MaximumVariableStorageSize == NULL || RemainingVariableStorageSize == NULL || MaximumVariableSize == NULL || Attributes == 0) {
2787 return EFI_INVALID_PARAMETER;
2788 }
2789
2790 if((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == 0) {
2791 //
2792 // Make sure the Attributes combination is supported by the platform.
2793 //
2794 return EFI_UNSUPPORTED;
2795 } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
2796 //
2797 // Make sure if runtime bit is set, boot service bit is set also.
2798 //
2799 return EFI_INVALID_PARAMETER;
2800 } else if (AtRuntime () && ((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) {
2801 //
2802 // Make sure RT Attribute is set if we are in Runtime phase.
2803 //
2804 return EFI_INVALID_PARAMETER;
2805 } else if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2806 //
2807 // Make sure Hw Attribute is set with NV.
2808 //
2809 return EFI_INVALID_PARAMETER;
2810 }
2811
2812 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2813
2814 if((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
2815 //
2816 // Query is Volatile related.
2817 //
2818 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
2819 } else {
2820 //
2821 // Query is Non-Volatile related.
2822 //
2823 VariableStoreHeader = mNvVariableCache;
2824 }
2825
2826 //
2827 // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize
2828 // with the storage size (excluding the storage header size).
2829 //
2830 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);
2831
2832 //
2833 // Harware error record variable needs larger size.
2834 //
2835 if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
2836 *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize);
2837 *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER);
2838 } else {
2839 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
2840 ASSERT (PcdGet32 (PcdHwErrStorageSize) < VariableStoreHeader->Size);
2841 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize);
2842 }
2843
2844 //
2845 // Let *MaximumVariableSize be PcdGet32 (PcdMaxVariableSize) with the exception of the variable header size.
2846 //
2847 *MaximumVariableSize = PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER);
2848 }
2849
2850 //
2851 // Point to the starting address of the variables.
2852 //
2853 Variable = GetStartPointer (VariableStoreHeader);
2854
2855 //
2856 // Now walk through the related variable store.
2857 //
2858 while ((Variable < GetEndPointer (VariableStoreHeader)) && IsValidVariableHeader (Variable)) {
2859 NextVariable = GetNextVariablePtr (Variable);
2860 VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable;
2861
2862 if (AtRuntime ()) {
2863 //
2864 // We don't take the state of the variables in mind
2865 // when calculating RemainingVariableStorageSize,
2866 // since the space occupied by variables not marked with
2867 // VAR_ADDED is not allowed to be reclaimed in Runtime.
2868 //
2869 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2870 HwErrVariableTotalSize += VariableSize;
2871 } else {
2872 CommonVariableTotalSize += VariableSize;
2873 }
2874 } else {
2875 //
2876 // Only care about Variables with State VAR_ADDED, because
2877 // the space not marked as VAR_ADDED is reclaimable now.
2878 //
2879 if (Variable->State == VAR_ADDED) {
2880 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2881 HwErrVariableTotalSize += VariableSize;
2882 } else {
2883 CommonVariableTotalSize += VariableSize;
2884 }
2885 }
2886 }
2887
2888 //
2889 // Go to the next one.
2890 //
2891 Variable = NextVariable;
2892 }
2893
2894 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD){
2895 *RemainingVariableStorageSize = *MaximumVariableStorageSize - HwErrVariableTotalSize;
2896 }else {
2897 *RemainingVariableStorageSize = *MaximumVariableStorageSize - CommonVariableTotalSize;
2898 }
2899
2900 if (*RemainingVariableStorageSize < sizeof (VARIABLE_HEADER)) {
2901 *MaximumVariableSize = 0;
2902 } else if ((*RemainingVariableStorageSize - sizeof (VARIABLE_HEADER)) < *MaximumVariableSize) {
2903 *MaximumVariableSize = *RemainingVariableStorageSize - sizeof (VARIABLE_HEADER);
2904 }
2905
2906 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2907 return EFI_SUCCESS;
2908 }
2909
2910
2911 /**
2912 This function reclaims variable storage if free size is below the threshold.
2913
2914 Caution: This function may be invoked at SMM mode.
2915 Care must be taken to make sure not security issue.
2916
2917 **/
2918 VOID
2919 ReclaimForOS(
2920 VOID
2921 )
2922 {
2923 EFI_STATUS Status;
2924 UINTN CommonVariableSpace;
2925 UINTN RemainingCommonVariableSpace;
2926 UINTN RemainingHwErrVariableSpace;
2927
2928 Status = EFI_SUCCESS;
2929
2930 CommonVariableSpace = ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase)))->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32(PcdHwErrStorageSize); //Allowable max size of common variable storage space
2931
2932 RemainingCommonVariableSpace = CommonVariableSpace - mVariableModuleGlobal->CommonVariableTotalSize;
2933
2934 RemainingHwErrVariableSpace = PcdGet32 (PcdHwErrStorageSize) - mVariableModuleGlobal->HwErrVariableTotalSize;
2935 //
2936 // Check if the free area is blow a threshold.
2937 //
2938 if ((RemainingCommonVariableSpace < PcdGet32 (PcdMaxVariableSize))
2939 || ((PcdGet32 (PcdHwErrStorageSize) != 0) &&
2940 (RemainingHwErrVariableSpace < PcdGet32 (PcdMaxHardwareErrorVariableSize)))){
2941 Status = Reclaim (
2942 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
2943 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
2944 FALSE,
2945 NULL,
2946 FALSE,
2947 FALSE
2948 );
2949 ASSERT_EFI_ERROR (Status);
2950 }
2951 }
2952
2953 /**
2954 Flush the HOB variable to flash.
2955
2956 @param[in] VariableName Name of variable has been updated or deleted.
2957 @param[in] VendorGuid Guid of variable has been updated or deleted.
2958
2959 **/
2960 VOID
2961 FlushHobVariableToFlash (
2962 IN CHAR16 *VariableName,
2963 IN EFI_GUID *VendorGuid
2964 )
2965 {
2966 EFI_STATUS Status;
2967 VARIABLE_STORE_HEADER *VariableStoreHeader;
2968 VARIABLE_HEADER *Variable;
2969 VOID *VariableData;
2970 BOOLEAN ErrorFlag;
2971
2972 ErrorFlag = FALSE;
2973
2974 //
2975 // Flush the HOB variable to flash.
2976 //
2977 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
2978 VariableStoreHeader = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
2979 //
2980 // Set HobVariableBase to 0, it can avoid SetVariable to call back.
2981 //
2982 mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0;
2983 for ( Variable = GetStartPointer (VariableStoreHeader)
2984 ; (Variable < GetEndPointer (VariableStoreHeader) && IsValidVariableHeader (Variable))
2985 ; Variable = GetNextVariablePtr (Variable)
2986 ) {
2987 if (Variable->State != VAR_ADDED) {
2988 //
2989 // The HOB variable has been set to DELETED state in local.
2990 //
2991 continue;
2992 }
2993 ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0);
2994 if (VendorGuid == NULL || VariableName == NULL ||
2995 !CompareGuid (VendorGuid, &Variable->VendorGuid) ||
2996 StrCmp (VariableName, GetVariableNamePtr (Variable)) != 0) {
2997 VariableData = GetVariableDataPtr (Variable);
2998 Status = VariableServiceSetVariable (
2999 GetVariableNamePtr (Variable),
3000 &Variable->VendorGuid,
3001 Variable->Attributes,
3002 Variable->DataSize,
3003 VariableData
3004 );
3005 DEBUG ((EFI_D_INFO, "Variable driver flush the HOB variable to flash: %g %s %r\n", &Variable->VendorGuid, GetVariableNamePtr (Variable), Status));
3006 } else {
3007 //
3008 // The updated or deleted variable is matched with the HOB variable.
3009 // Don't break here because we will try to set other HOB variables
3010 // since this variable could be set successfully.
3011 //
3012 Status = EFI_SUCCESS;
3013 }
3014 if (!EFI_ERROR (Status)) {
3015 //
3016 // If set variable successful, or the updated or deleted variable is matched with the HOB variable,
3017 // set the HOB variable to DELETED state in local.
3018 //
3019 DEBUG ((EFI_D_INFO, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", &Variable->VendorGuid, GetVariableNamePtr (Variable)));
3020 Variable->State &= VAR_DELETED;
3021 } else {
3022 ErrorFlag = TRUE;
3023 }
3024 }
3025 if (ErrorFlag) {
3026 //
3027 // We still have HOB variable(s) not flushed in flash.
3028 //
3029 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStoreHeader;
3030 } else {
3031 //
3032 // All HOB variables have been flushed in flash.
3033 //
3034 DEBUG ((EFI_D_INFO, "Variable driver: all HOB variables have been flushed in flash.\n"));
3035 if (!AtRuntime ()) {
3036 FreePool ((VOID *) VariableStoreHeader);
3037 }
3038 }
3039 }
3040
3041 }
3042
3043 /**
3044 Initializes variable write service after FVB was ready.
3045
3046 @retval EFI_SUCCESS Function successfully executed.
3047 @retval Others Fail to initialize the variable service.
3048
3049 **/
3050 EFI_STATUS
3051 VariableWriteServiceInitialize (
3052 VOID
3053 )
3054 {
3055 EFI_STATUS Status;
3056 VARIABLE_STORE_HEADER *VariableStoreHeader;
3057 UINTN Index;
3058 UINT8 Data;
3059 EFI_PHYSICAL_ADDRESS VariableStoreBase;
3060
3061 VariableStoreBase = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
3062 VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;
3063
3064 //
3065 // Check if the free area is really free.
3066 //
3067 for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreHeader->Size; Index++) {
3068 Data = ((UINT8 *) mNvVariableCache)[Index];
3069 if (Data != 0xff) {
3070 //
3071 // There must be something wrong in variable store, do reclaim operation.
3072 //
3073 Status = Reclaim (
3074 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
3075 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
3076 FALSE,
3077 NULL,
3078 FALSE,
3079 TRUE
3080 );
3081 if (EFI_ERROR (Status)) {
3082 return Status;
3083 }
3084 break;
3085 }
3086 }
3087
3088 FlushHobVariableToFlash (NULL, NULL);
3089
3090 //
3091 // Authenticated variable initialize.
3092 //
3093 Status = AutenticatedVariableServiceInitialize ();
3094
3095 return Status;
3096 }
3097
3098
3099 /**
3100 Initializes variable store area for non-volatile and volatile variable.
3101
3102 @retval EFI_SUCCESS Function successfully executed.
3103 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
3104
3105 **/
3106 EFI_STATUS
3107 VariableCommonInitialize (
3108 VOID
3109 )
3110 {
3111 EFI_STATUS Status;
3112 VARIABLE_STORE_HEADER *VolatileVariableStore;
3113 VARIABLE_STORE_HEADER *VariableStoreHeader;
3114 VARIABLE_HEADER *NextVariable;
3115 EFI_PHYSICAL_ADDRESS TempVariableStoreHeader;
3116 EFI_PHYSICAL_ADDRESS VariableStoreBase;
3117 UINT64 VariableStoreLength;
3118 UINTN ScratchSize;
3119 UINTN VariableSize;
3120 EFI_HOB_GUID_TYPE *GuidHob;
3121
3122 //
3123 // Allocate runtime memory for variable driver global structure.
3124 //
3125 mVariableModuleGlobal = AllocateRuntimeZeroPool (sizeof (VARIABLE_MODULE_GLOBAL));
3126 if (mVariableModuleGlobal == NULL) {
3127 return EFI_OUT_OF_RESOURCES;
3128 }
3129
3130 InitializeLock (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);
3131
3132 //
3133 // Note that in EdkII variable driver implementation, Hardware Error Record type variable
3134 // is stored with common variable in the same NV region. So the platform integrator should
3135 // ensure that the value of PcdHwErrStorageSize is less than or equal to the value of
3136 // PcdFlashNvStorageVariableSize.
3137 //
3138 ASSERT (PcdGet32 (PcdHwErrStorageSize) <= PcdGet32 (PcdFlashNvStorageVariableSize));
3139
3140 //
3141 // Get HOB variable store.
3142 //
3143 GuidHob = GetFirstGuidHob (&gEfiAuthenticatedVariableGuid);
3144 if (GuidHob != NULL) {
3145 VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob);
3146 VariableStoreLength = (UINT64) (GuidHob->Header.HobLength - sizeof (EFI_HOB_GUID_TYPE));
3147 if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {
3148 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) AllocateRuntimeCopyPool ((UINTN) VariableStoreLength, (VOID *) VariableStoreHeader);
3149 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase == 0) {
3150 return EFI_OUT_OF_RESOURCES;
3151 }
3152 } else {
3153 DEBUG ((EFI_D_ERROR, "HOB Variable Store header is corrupted!\n"));
3154 }
3155 }
3156
3157 //
3158 // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.
3159 //
3160 ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));
3161 VolatileVariableStore = AllocateRuntimePool (PcdGet32 (PcdVariableStoreSize) + ScratchSize);
3162 if (VolatileVariableStore == NULL) {
3163 FreePool (mVariableModuleGlobal);
3164 return EFI_OUT_OF_RESOURCES;
3165 }
3166
3167 SetMem (VolatileVariableStore, PcdGet32 (PcdVariableStoreSize) + ScratchSize, 0xff);
3168
3169 //
3170 // Initialize Variable Specific Data.
3171 //
3172 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VolatileVariableStore;
3173 mVariableModuleGlobal->VolatileLastVariableOffset = (UINTN) GetStartPointer (VolatileVariableStore) - (UINTN) VolatileVariableStore;
3174 mVariableModuleGlobal->FvbInstance = NULL;
3175
3176 CopyGuid (&VolatileVariableStore->Signature, &gEfiAuthenticatedVariableGuid);
3177 VolatileVariableStore->Size = PcdGet32 (PcdVariableStoreSize);
3178 VolatileVariableStore->Format = VARIABLE_STORE_FORMATTED;
3179 VolatileVariableStore->State = VARIABLE_STORE_HEALTHY;
3180 VolatileVariableStore->Reserved = 0;
3181 VolatileVariableStore->Reserved1 = 0;
3182
3183 //
3184 // Get non-volatile variable store.
3185 //
3186
3187 TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);
3188 if (TempVariableStoreHeader == 0) {
3189 TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);
3190 }
3191
3192 //
3193 // Check if the Firmware Volume is not corrupted
3194 //
3195 if ((((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader))->Signature != EFI_FVH_SIGNATURE) ||
3196 (!CompareGuid (&gEfiSystemNvDataFvGuid, &((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader))->FileSystemGuid))) {
3197 Status = EFI_VOLUME_CORRUPTED;
3198 DEBUG ((EFI_D_ERROR, "Firmware Volume for Variable Store is corrupted\n"));
3199 goto Done;
3200 }
3201
3202 VariableStoreBase = TempVariableStoreHeader + \
3203 (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader)) -> HeaderLength);
3204 VariableStoreLength = (UINT64) PcdGet32 (PcdFlashNvStorageVariableSize) - \
3205 (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader)) -> HeaderLength);
3206
3207 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
3208 VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;
3209 if (GetVariableStoreStatus (VariableStoreHeader) != EfiValid) {
3210 Status = EFI_VOLUME_CORRUPTED;
3211 DEBUG((EFI_D_INFO, "Variable Store header is corrupted\n"));
3212 goto Done;
3213 }
3214 ASSERT(VariableStoreHeader->Size == VariableStoreLength);
3215
3216 //
3217 // Parse non-volatile variable data and get last variable offset.
3218 //
3219 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase);
3220 while (IsValidVariableHeader (NextVariable)) {
3221 VariableSize = NextVariable->NameSize + NextVariable->DataSize + sizeof (VARIABLE_HEADER);
3222 if ((NextVariable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
3223 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VariableSize);
3224 } else {
3225 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize);
3226 }
3227
3228 NextVariable = GetNextVariablePtr (NextVariable);
3229 }
3230
3231 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) VariableStoreBase;
3232
3233 //
3234 // Allocate runtime memory used for a memory copy of the FLASH region.
3235 // Keep the memory and the FLASH in sync as updates occur
3236 //
3237 mNvVariableCache = AllocateRuntimeZeroPool ((UINTN)VariableStoreLength);
3238 if (mNvVariableCache == NULL) {
3239 Status = EFI_OUT_OF_RESOURCES;
3240 goto Done;
3241 }
3242 CopyMem (mNvVariableCache, (CHAR8 *)(UINTN)VariableStoreBase, (UINTN)VariableStoreLength);
3243 Status = EFI_SUCCESS;
3244
3245 Done:
3246 if (EFI_ERROR (Status)) {
3247 FreePool (mVariableModuleGlobal);
3248 FreePool (VolatileVariableStore);
3249 }
3250
3251 return Status;
3252 }
3253
3254
3255 /**
3256 Get the proper fvb handle and/or fvb protocol by the given Flash address.
3257
3258 @param[in] Address The Flash address.
3259 @param[out] FvbHandle In output, if it is not NULL, it points to the proper FVB handle.
3260 @param[out] FvbProtocol In output, if it is not NULL, it points to the proper FVB protocol.
3261
3262 **/
3263 EFI_STATUS
3264 GetFvbInfoByAddress (
3265 IN EFI_PHYSICAL_ADDRESS Address,
3266 OUT EFI_HANDLE *FvbHandle OPTIONAL,
3267 OUT EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL **FvbProtocol OPTIONAL
3268 )
3269 {
3270 EFI_STATUS Status;
3271 EFI_HANDLE *HandleBuffer;
3272 UINTN HandleCount;
3273 UINTN Index;
3274 EFI_PHYSICAL_ADDRESS FvbBaseAddress;
3275 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
3276 EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
3277 EFI_FVB_ATTRIBUTES_2 Attributes;
3278
3279 //
3280 // Get all FVB handles.
3281 //
3282 Status = GetFvbCountAndBuffer (&HandleCount, &HandleBuffer);
3283 if (EFI_ERROR (Status)) {
3284 return EFI_NOT_FOUND;
3285 }
3286
3287 //
3288 // Get the FVB to access variable store.
3289 //
3290 Fvb = NULL;
3291 for (Index = 0; Index < HandleCount; Index += 1, Status = EFI_NOT_FOUND, Fvb = NULL) {
3292 Status = GetFvbByHandle (HandleBuffer[Index], &Fvb);
3293 if (EFI_ERROR (Status)) {
3294 Status = EFI_NOT_FOUND;
3295 break;
3296 }
3297
3298 //
3299 // Ensure this FVB protocol supported Write operation.
3300 //
3301 Status = Fvb->GetAttributes (Fvb, &Attributes);
3302 if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {
3303 continue;
3304 }
3305
3306 //
3307 // Compare the address and select the right one.
3308 //
3309 Status = Fvb->GetPhysicalAddress (Fvb, &FvbBaseAddress);
3310 if (EFI_ERROR (Status)) {
3311 continue;
3312 }
3313
3314 FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) FvbBaseAddress);
3315 if ((Address >= FvbBaseAddress) && (Address < (FvbBaseAddress + FwVolHeader->FvLength))) {
3316 if (FvbHandle != NULL) {
3317 *FvbHandle = HandleBuffer[Index];
3318 }
3319 if (FvbProtocol != NULL) {
3320 *FvbProtocol = Fvb;
3321 }
3322 Status = EFI_SUCCESS;
3323 break;
3324 }
3325 }
3326 FreePool (HandleBuffer);
3327
3328 if (Fvb == NULL) {
3329 Status = EFI_NOT_FOUND;
3330 }
3331
3332 return Status;
3333 }
3334