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