]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c
Fix memory overflow & VariableSize check issue for SetVariable append write.
[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 MaxDataSize;
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
1668 if (mVariableModuleGlobal->FvbInstance == NULL) {
1669 //
1670 // The FVB protocol is not installed, so the EFI_VARIABLE_WRITE_ARCH_PROTOCOL is not installed.
1671 //
1672 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
1673 //
1674 // Trying to update NV variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
1675 //
1676 return EFI_NOT_AVAILABLE_YET;
1677 } else if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) {
1678 //
1679 // Trying to update volatile authenticated variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
1680 // The authenticated variable perhaps is not initialized, just return here.
1681 //
1682 return EFI_NOT_AVAILABLE_YET;
1683 }
1684 }
1685
1686 if ((CacheVariable->CurrPtr == NULL) || CacheVariable->Volatile) {
1687 Variable = CacheVariable;
1688 } else {
1689 //
1690 // Update/Delete existing NV variable.
1691 // CacheVariable points to the variable in the memory copy of Flash area
1692 // Now let Variable points to the same variable in Flash area.
1693 //
1694 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);
1695 Variable = &NvVariable;
1696 Variable->StartPtr = GetStartPointer (VariableStoreHeader);
1697 Variable->EndPtr = GetEndPointer (VariableStoreHeader);
1698 Variable->CurrPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr));
1699 if (CacheVariable->InDeletedTransitionPtr != NULL) {
1700 Variable->InDeletedTransitionPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->InDeletedTransitionPtr - (UINTN)CacheVariable->StartPtr));
1701 } else {
1702 Variable->InDeletedTransitionPtr = NULL;
1703 }
1704 Variable->Volatile = FALSE;
1705 }
1706
1707 Fvb = mVariableModuleGlobal->FvbInstance;
1708
1709 //
1710 // Tricky part: Use scratch data area at the end of volatile variable store
1711 // as a temporary storage.
1712 //
1713 NextVariable = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase));
1714 ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));
1715
1716
1717 if (Variable->CurrPtr != NULL) {
1718 //
1719 // Update/Delete existing variable.
1720 //
1721 if (AtRuntime ()) {
1722 //
1723 // If AtRuntime and the variable is Volatile and Runtime Access,
1724 // the volatile is ReadOnly, and SetVariable should be aborted and
1725 // return EFI_WRITE_PROTECTED.
1726 //
1727 if (Variable->Volatile) {
1728 Status = EFI_WRITE_PROTECTED;
1729 goto Done;
1730 }
1731 //
1732 // Only variable that have NV attributes can be updated/deleted in Runtime.
1733 //
1734 if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
1735 Status = EFI_INVALID_PARAMETER;
1736 goto Done;
1737 }
1738
1739 //
1740 // Only variable that have RT attributes can be updated/deleted in Runtime.
1741 //
1742 if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) {
1743 Status = EFI_INVALID_PARAMETER;
1744 goto Done;
1745 }
1746 }
1747
1748 //
1749 // Setting a data variable with no access, or zero DataSize attributes
1750 // causes it to be deleted.
1751 // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will
1752 // not delete the variable.
1753 //
1754 if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0))|| ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) {
1755 if (Variable->InDeletedTransitionPtr != NULL) {
1756 //
1757 // Both ADDED and IN_DELETED_TRANSITION variable are present,
1758 // set IN_DELETED_TRANSITION one to DELETED state first.
1759 //
1760 State = Variable->InDeletedTransitionPtr->State;
1761 State &= VAR_DELETED;
1762 Status = UpdateVariableStore (
1763 &mVariableModuleGlobal->VariableGlobal,
1764 Variable->Volatile,
1765 FALSE,
1766 Fvb,
1767 (UINTN) &Variable->InDeletedTransitionPtr->State,
1768 sizeof (UINT8),
1769 &State
1770 );
1771 if (!EFI_ERROR (Status)) {
1772 if (!Variable->Volatile) {
1773 ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
1774 CacheVariable->InDeletedTransitionPtr->State = State;
1775 }
1776 } else {
1777 goto Done;
1778 }
1779 }
1780
1781 State = Variable->CurrPtr->State;
1782 State &= VAR_DELETED;
1783
1784 Status = UpdateVariableStore (
1785 &mVariableModuleGlobal->VariableGlobal,
1786 Variable->Volatile,
1787 FALSE,
1788 Fvb,
1789 (UINTN) &Variable->CurrPtr->State,
1790 sizeof (UINT8),
1791 &State
1792 );
1793 if (!EFI_ERROR (Status)) {
1794 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE);
1795 if (!Variable->Volatile) {
1796 CacheVariable->CurrPtr->State = State;
1797 FlushHobVariableToFlash (VariableName, VendorGuid);
1798 }
1799 }
1800 goto Done;
1801 }
1802 //
1803 // If the variable is marked valid, and the same data has been passed in,
1804 // then return to the caller immediately.
1805 //
1806 if (DataSizeOfVariable (Variable->CurrPtr) == DataSize &&
1807 (CompareMem (Data, GetVariableDataPtr (Variable->CurrPtr), DataSize) == 0) &&
1808 ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) &&
1809 (TimeStamp == NULL)) {
1810 //
1811 // Variable content unchanged and no need to update timestamp, just return.
1812 //
1813 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);
1814 Status = EFI_SUCCESS;
1815 goto Done;
1816 } else if ((Variable->CurrPtr->State == VAR_ADDED) ||
1817 (Variable->CurrPtr->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION))) {
1818
1819 //
1820 // EFI_VARIABLE_APPEND_WRITE attribute only effects for existing variable
1821 //
1822 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) {
1823 //
1824 // Cache the previous variable data into StorageArea.
1825 //
1826 DataOffset = sizeof (VARIABLE_HEADER) + Variable->CurrPtr->NameSize + GET_PAD_SIZE (Variable->CurrPtr->NameSize);
1827 CopyMem (mStorageArea, (UINT8*)((UINTN) Variable->CurrPtr + DataOffset), Variable->CurrPtr->DataSize);
1828
1829 //
1830 // Set Max Common Variable Data Size as default MaxDataSize
1831 //
1832 MaxDataSize = PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER) - StrSize (VariableName) - GET_PAD_SIZE (StrSize (VariableName));
1833
1834
1835 if ((CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&
1836 ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))) ||
1837 (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0))) {
1838
1839 //
1840 // For variables with formatted as EFI_SIGNATURE_LIST, the driver shall not perform an append of
1841 // EFI_SIGNATURE_DATA values that are already part of the existing variable value.
1842 //
1843 Status = AppendSignatureList (
1844 mStorageArea,
1845 Variable->CurrPtr->DataSize,
1846 MaxDataSize - Variable->CurrPtr->DataSize,
1847 Data,
1848 DataSize,
1849 &BufSize
1850 );
1851 if (Status == EFI_BUFFER_TOO_SMALL) {
1852 //
1853 // Signture List is too long, Failed to Append
1854 //
1855 Status = EFI_INVALID_PARAMETER;
1856 goto Done;
1857 }
1858
1859 if (BufSize == Variable->CurrPtr->DataSize) {
1860 if ((TimeStamp == NULL) || CompareTimeStamp (TimeStamp, &Variable->CurrPtr->TimeStamp)) {
1861 //
1862 // New EFI_SIGNATURE_DATA is not found and timestamp is not later
1863 // than current timestamp, return EFI_SUCCESS directly.
1864 //
1865 UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);
1866 Status = EFI_SUCCESS;
1867 goto Done;
1868 }
1869 }
1870 } else {
1871 //
1872 // For other Variables, append the new data to the end of previous data.
1873 // Max Harware error record variable data size is different from common variable
1874 //
1875 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
1876 MaxDataSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER) - StrSize (VariableName) - GET_PAD_SIZE (StrSize (VariableName));
1877 }
1878
1879 if (Variable->CurrPtr->DataSize + DataSize > MaxDataSize) {
1880 //
1881 // Exsiting data + Appended data exceed maximum variable size limitation
1882 //
1883 Status = EFI_INVALID_PARAMETER;
1884 goto Done;
1885 }
1886 CopyMem ((UINT8*)((UINTN) mStorageArea + Variable->CurrPtr->DataSize), Data, DataSize);
1887 BufSize = Variable->CurrPtr->DataSize + DataSize;
1888 }
1889
1890 //
1891 // Override Data and DataSize which are used for combined data area including previous and new data.
1892 //
1893 Data = mStorageArea;
1894 DataSize = BufSize;
1895 }
1896
1897 //
1898 // Mark the old variable as in delete transition.
1899 //
1900 State = Variable->CurrPtr->State;
1901 State &= VAR_IN_DELETED_TRANSITION;
1902
1903 Status = UpdateVariableStore (
1904 &mVariableModuleGlobal->VariableGlobal,
1905 Variable->Volatile,
1906 FALSE,
1907 Fvb,
1908 (UINTN) &Variable->CurrPtr->State,
1909 sizeof (UINT8),
1910 &State
1911 );
1912 if (EFI_ERROR (Status)) {
1913 goto Done;
1914 }
1915 if (!Variable->Volatile) {
1916 CacheVariable->CurrPtr->State = State;
1917 }
1918 }
1919 } else {
1920 //
1921 // Not found existing variable. Create a new variable.
1922 //
1923
1924 if ((DataSize == 0) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0)) {
1925 Status = EFI_SUCCESS;
1926 goto Done;
1927 }
1928
1929 //
1930 // Make sure we are trying to create a new variable.
1931 // Setting a data variable with zero DataSize or no access attributes means to delete it.
1932 //
1933 if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) {
1934 Status = EFI_NOT_FOUND;
1935 goto Done;
1936 }
1937
1938 //
1939 // Only variable have NV|RT attribute can be created in Runtime.
1940 //
1941 if (AtRuntime () &&
1942 (((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0))) {
1943 Status = EFI_INVALID_PARAMETER;
1944 goto Done;
1945 }
1946 }
1947
1948 //
1949 // Function part - create a new variable and copy the data.
1950 // Both update a variable and create a variable will come here.
1951
1952 SetMem (NextVariable, ScratchSize, 0xff);
1953
1954 NextVariable->StartId = VARIABLE_DATA;
1955 //
1956 // NextVariable->State = VAR_ADDED;
1957 //
1958 NextVariable->Reserved = 0;
1959 NextVariable->PubKeyIndex = KeyIndex;
1960 NextVariable->MonotonicCount = MonotonicCount;
1961 ZeroMem (&NextVariable->TimeStamp, sizeof (EFI_TIME));
1962
1963 if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&
1964 (TimeStamp != NULL)) {
1965 if ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) {
1966 CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
1967 } else {
1968 //
1969 // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only
1970 // when the new TimeStamp value is later than the current timestamp associated
1971 // with the variable, we need associate the new timestamp with the updated value.
1972 //
1973 if (Variable->CurrPtr != NULL) {
1974 if (CompareTimeStamp (&Variable->CurrPtr->TimeStamp, TimeStamp)) {
1975 CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
1976 }
1977 }
1978 }
1979 }
1980
1981 //
1982 // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned
1983 // Attributes bitmask parameter of a GetVariable() call.
1984 //
1985 NextVariable->Attributes = Attributes & (~EFI_VARIABLE_APPEND_WRITE);
1986
1987 VarNameOffset = sizeof (VARIABLE_HEADER);
1988 VarNameSize = StrSize (VariableName);
1989 CopyMem (
1990 (UINT8 *) ((UINTN) NextVariable + VarNameOffset),
1991 VariableName,
1992 VarNameSize
1993 );
1994 VarDataOffset = VarNameOffset + VarNameSize + GET_PAD_SIZE (VarNameSize);
1995 CopyMem (
1996 (UINT8 *) ((UINTN) NextVariable + VarDataOffset),
1997 Data,
1998 DataSize
1999 );
2000 CopyMem (&NextVariable->VendorGuid, VendorGuid, sizeof (EFI_GUID));
2001 //
2002 // There will be pad bytes after Data, the NextVariable->NameSize and
2003 // NextVariable->DataSize should not include pad size so that variable
2004 // service can get actual size in GetVariable.
2005 //
2006 NextVariable->NameSize = (UINT32)VarNameSize;
2007 NextVariable->DataSize = (UINT32)DataSize;
2008
2009 //
2010 // The actual size of the variable that stores in storage should
2011 // include pad size.
2012 //
2013 VarSize = VarDataOffset + DataSize + GET_PAD_SIZE (DataSize);
2014 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
2015 //
2016 // Create a nonvolatile variable.
2017 //
2018 Volatile = FALSE;
2019 NonVolatileVarableStoreSize = ((VARIABLE_STORE_HEADER *)(UINTN)(mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase))->Size;
2020 if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)
2021 && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))
2022 || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0)
2023 && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {
2024 if (AtRuntime ()) {
2025 Status = EFI_OUT_OF_RESOURCES;
2026 goto Done;
2027 }
2028 //
2029 // Perform garbage collection & reclaim operation.
2030 //
2031 Status = Reclaim (
2032 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
2033 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
2034 FALSE,
2035 Variable,
2036 FALSE,
2037 FALSE
2038 );
2039 if (EFI_ERROR (Status)) {
2040 goto Done;
2041 }
2042 //
2043 // If still no enough space, return out of resources.
2044 //
2045 if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)
2046 && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))
2047 || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0)
2048 && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {
2049 Status = EFI_OUT_OF_RESOURCES;
2050 goto Done;
2051 }
2052 if (Variable->CurrPtr != NULL) {
2053 CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
2054 CacheVariable->InDeletedTransitionPtr = NULL;
2055 }
2056 }
2057 //
2058 // Four steps
2059 // 1. Write variable header
2060 // 2. Set variable state to header valid
2061 // 3. Write variable data
2062 // 4. Set variable state to valid
2063 //
2064 //
2065 // Step 1:
2066 //
2067 CacheOffset = mVariableModuleGlobal->NonVolatileLastVariableOffset;
2068 Status = UpdateVariableStore (
2069 &mVariableModuleGlobal->VariableGlobal,
2070 FALSE,
2071 TRUE,
2072 Fvb,
2073 mVariableModuleGlobal->NonVolatileLastVariableOffset,
2074 sizeof (VARIABLE_HEADER),
2075 (UINT8 *) NextVariable
2076 );
2077
2078 if (EFI_ERROR (Status)) {
2079 goto Done;
2080 }
2081
2082 //
2083 // Step 2:
2084 //
2085 NextVariable->State = VAR_HEADER_VALID_ONLY;
2086 Status = UpdateVariableStore (
2087 &mVariableModuleGlobal->VariableGlobal,
2088 FALSE,
2089 TRUE,
2090 Fvb,
2091 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
2092 sizeof (UINT8),
2093 &NextVariable->State
2094 );
2095
2096 if (EFI_ERROR (Status)) {
2097 goto Done;
2098 }
2099 //
2100 // Step 3:
2101 //
2102 Status = UpdateVariableStore (
2103 &mVariableModuleGlobal->VariableGlobal,
2104 FALSE,
2105 TRUE,
2106 Fvb,
2107 mVariableModuleGlobal->NonVolatileLastVariableOffset + sizeof (VARIABLE_HEADER),
2108 (UINT32) VarSize - sizeof (VARIABLE_HEADER),
2109 (UINT8 *) NextVariable + sizeof (VARIABLE_HEADER)
2110 );
2111
2112 if (EFI_ERROR (Status)) {
2113 goto Done;
2114 }
2115 //
2116 // Step 4:
2117 //
2118 NextVariable->State = VAR_ADDED;
2119 Status = UpdateVariableStore (
2120 &mVariableModuleGlobal->VariableGlobal,
2121 FALSE,
2122 TRUE,
2123 Fvb,
2124 mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
2125 sizeof (UINT8),
2126 &NextVariable->State
2127 );
2128
2129 if (EFI_ERROR (Status)) {
2130 goto Done;
2131 }
2132
2133 mVariableModuleGlobal->NonVolatileLastVariableOffset += HEADER_ALIGN (VarSize);
2134
2135 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
2136 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VarSize);
2137 } else {
2138 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VarSize);
2139 }
2140 //
2141 // update the memory copy of Flash region.
2142 //
2143 CopyMem ((UINT8 *)mNvVariableCache + CacheOffset, (UINT8 *)NextVariable, VarSize);
2144 } else {
2145 //
2146 // Create a volatile variable.
2147 //
2148 Volatile = TRUE;
2149
2150 if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >
2151 ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size) {
2152 //
2153 // Perform garbage collection & reclaim operation.
2154 //
2155 Status = Reclaim (
2156 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,
2157 &mVariableModuleGlobal->VolatileLastVariableOffset,
2158 TRUE,
2159 Variable,
2160 FALSE,
2161 FALSE
2162 );
2163 if (EFI_ERROR (Status)) {
2164 goto Done;
2165 }
2166 //
2167 // If still no enough space, return out of resources.
2168 //
2169 if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >
2170 ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size
2171 ) {
2172 Status = EFI_OUT_OF_RESOURCES;
2173 goto Done;
2174 }
2175 if (Variable->CurrPtr != NULL) {
2176 CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
2177 CacheVariable->InDeletedTransitionPtr = NULL;
2178 }
2179 }
2180
2181 NextVariable->State = VAR_ADDED;
2182 Status = UpdateVariableStore (
2183 &mVariableModuleGlobal->VariableGlobal,
2184 TRUE,
2185 TRUE,
2186 Fvb,
2187 mVariableModuleGlobal->VolatileLastVariableOffset,
2188 (UINT32) VarSize,
2189 (UINT8 *) NextVariable
2190 );
2191
2192 if (EFI_ERROR (Status)) {
2193 goto Done;
2194 }
2195
2196 mVariableModuleGlobal->VolatileLastVariableOffset += HEADER_ALIGN (VarSize);
2197 }
2198
2199 //
2200 // Mark the old variable as deleted.
2201 //
2202 if (!EFI_ERROR (Status) && Variable->CurrPtr != NULL) {
2203 if (Variable->InDeletedTransitionPtr != NULL) {
2204 //
2205 // Both ADDED and IN_DELETED_TRANSITION old variable are present,
2206 // set IN_DELETED_TRANSITION one to DELETED state first.
2207 //
2208 State = Variable->InDeletedTransitionPtr->State;
2209 State &= VAR_DELETED;
2210 Status = UpdateVariableStore (
2211 &mVariableModuleGlobal->VariableGlobal,
2212 Variable->Volatile,
2213 FALSE,
2214 Fvb,
2215 (UINTN) &Variable->InDeletedTransitionPtr->State,
2216 sizeof (UINT8),
2217 &State
2218 );
2219 if (!EFI_ERROR (Status)) {
2220 if (!Variable->Volatile) {
2221 ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
2222 CacheVariable->InDeletedTransitionPtr->State = State;
2223 }
2224 } else {
2225 goto Done;
2226 }
2227 }
2228
2229 State = Variable->CurrPtr->State;
2230 State &= VAR_DELETED;
2231
2232 Status = UpdateVariableStore (
2233 &mVariableModuleGlobal->VariableGlobal,
2234 Variable->Volatile,
2235 FALSE,
2236 Fvb,
2237 (UINTN) &Variable->CurrPtr->State,
2238 sizeof (UINT8),
2239 &State
2240 );
2241 if (!EFI_ERROR (Status) && !Variable->Volatile) {
2242 CacheVariable->CurrPtr->State = State;
2243 }
2244 }
2245
2246 if (!EFI_ERROR (Status)) {
2247 UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);
2248 if (!Volatile) {
2249 FlushHobVariableToFlash (VariableName, VendorGuid);
2250 }
2251 }
2252
2253 Done:
2254 return Status;
2255 }
2256
2257 /**
2258 Check if a Unicode character is a hexadecimal character.
2259
2260 This function checks if a Unicode character is a
2261 hexadecimal character. The valid hexadecimal character is
2262 L'0' to L'9', L'a' to L'f', or L'A' to L'F'.
2263
2264
2265 @param Char The character to check against.
2266
2267 @retval TRUE If the Char is a hexadecmial character.
2268 @retval FALSE If the Char is not a hexadecmial character.
2269
2270 **/
2271 BOOLEAN
2272 EFIAPI
2273 IsHexaDecimalDigitCharacter (
2274 IN CHAR16 Char
2275 )
2276 {
2277 return (BOOLEAN) ((Char >= L'0' && Char <= L'9') || (Char >= L'A' && Char <= L'F') || (Char >= L'a' && Char <= L'f'));
2278 }
2279
2280 /**
2281
2282 This code checks if variable is hardware error record variable or not.
2283
2284 According to UEFI spec, hardware error record variable should use the EFI_HARDWARE_ERROR_VARIABLE VendorGuid
2285 and have the L"HwErrRec####" name convention, #### is a printed hex value and no 0x or h is included in the hex value.
2286
2287 @param VariableName Pointer to variable name.
2288 @param VendorGuid Variable Vendor Guid.
2289
2290 @retval TRUE Variable is hardware error record variable.
2291 @retval FALSE Variable is not hardware error record variable.
2292
2293 **/
2294 BOOLEAN
2295 EFIAPI
2296 IsHwErrRecVariable (
2297 IN CHAR16 *VariableName,
2298 IN EFI_GUID *VendorGuid
2299 )
2300 {
2301 if (!CompareGuid (VendorGuid, &gEfiHardwareErrorVariableGuid) ||
2302 (StrLen (VariableName) != StrLen (L"HwErrRec####")) ||
2303 (StrnCmp(VariableName, L"HwErrRec", StrLen (L"HwErrRec")) != 0) ||
2304 !IsHexaDecimalDigitCharacter (VariableName[0x8]) ||
2305 !IsHexaDecimalDigitCharacter (VariableName[0x9]) ||
2306 !IsHexaDecimalDigitCharacter (VariableName[0xA]) ||
2307 !IsHexaDecimalDigitCharacter (VariableName[0xB])) {
2308 return FALSE;
2309 }
2310
2311 return TRUE;
2312 }
2313
2314 /**
2315 This code checks if variable should be treated as read-only variable.
2316
2317 @param[in] VariableName Name of the Variable.
2318 @param[in] VendorGuid GUID of the Variable.
2319
2320 @retval TRUE This variable is read-only variable.
2321 @retval FALSE This variable is NOT read-only variable.
2322
2323 **/
2324 BOOLEAN
2325 IsReadOnlyVariable (
2326 IN CHAR16 *VariableName,
2327 IN EFI_GUID *VendorGuid
2328 )
2329 {
2330 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid)) {
2331 if ((StrCmp (VariableName, EFI_SETUP_MODE_NAME) == 0) ||
2332 (StrCmp (VariableName, EFI_SIGNATURE_SUPPORT_NAME) == 0) ||
2333 (StrCmp (VariableName, EFI_SECURE_BOOT_MODE_NAME) == 0)) {
2334 return TRUE;
2335 }
2336 }
2337
2338 return FALSE;
2339 }
2340
2341 /**
2342
2343 This code finds variable in storage blocks (Volatile or Non-Volatile).
2344
2345 Caution: This function may receive untrusted input.
2346 This function may be invoked in SMM mode, and datasize is external input.
2347 This function will do basic validation, before parse the data.
2348
2349 @param VariableName Name of Variable to be found.
2350 @param VendorGuid Variable vendor GUID.
2351 @param Attributes Attribute value of the variable found.
2352 @param DataSize Size of Data found. If size is less than the
2353 data, this value contains the required size.
2354 @param Data Data pointer.
2355
2356 @return EFI_INVALID_PARAMETER Invalid parameter.
2357 @return EFI_SUCCESS Find the specified variable.
2358 @return EFI_NOT_FOUND Not found.
2359 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2360
2361 **/
2362 EFI_STATUS
2363 EFIAPI
2364 VariableServiceGetVariable (
2365 IN CHAR16 *VariableName,
2366 IN EFI_GUID *VendorGuid,
2367 OUT UINT32 *Attributes OPTIONAL,
2368 IN OUT UINTN *DataSize,
2369 OUT VOID *Data
2370 )
2371 {
2372 EFI_STATUS Status;
2373 VARIABLE_POINTER_TRACK Variable;
2374 UINTN VarDataSize;
2375
2376 if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {
2377 return EFI_INVALID_PARAMETER;
2378 }
2379
2380 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2381
2382 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2383 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2384 goto Done;
2385 }
2386
2387 //
2388 // Get data size
2389 //
2390 VarDataSize = DataSizeOfVariable (Variable.CurrPtr);
2391 ASSERT (VarDataSize != 0);
2392
2393 if (*DataSize >= VarDataSize) {
2394 if (Data == NULL) {
2395 Status = EFI_INVALID_PARAMETER;
2396 goto Done;
2397 }
2398
2399 CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr), VarDataSize);
2400 if (Attributes != NULL) {
2401 *Attributes = Variable.CurrPtr->Attributes;
2402 }
2403
2404 *DataSize = VarDataSize;
2405 UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);
2406
2407 Status = EFI_SUCCESS;
2408 goto Done;
2409 } else {
2410 *DataSize = VarDataSize;
2411 Status = EFI_BUFFER_TOO_SMALL;
2412 goto Done;
2413 }
2414
2415 Done:
2416 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2417 return Status;
2418 }
2419
2420
2421
2422 /**
2423
2424 This code Finds the Next available variable.
2425
2426 Caution: This function may receive untrusted input.
2427 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2428
2429 @param VariableNameSize Size of the variable name.
2430 @param VariableName Pointer to variable name.
2431 @param VendorGuid Variable Vendor Guid.
2432
2433 @return EFI_INVALID_PARAMETER Invalid parameter.
2434 @return EFI_SUCCESS Find the specified variable.
2435 @return EFI_NOT_FOUND Not found.
2436 @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
2437
2438 **/
2439 EFI_STATUS
2440 EFIAPI
2441 VariableServiceGetNextVariableName (
2442 IN OUT UINTN *VariableNameSize,
2443 IN OUT CHAR16 *VariableName,
2444 IN OUT EFI_GUID *VendorGuid
2445 )
2446 {
2447 VARIABLE_STORE_TYPE Type;
2448 VARIABLE_POINTER_TRACK Variable;
2449 VARIABLE_POINTER_TRACK VariableInHob;
2450 VARIABLE_POINTER_TRACK VariablePtrTrack;
2451 UINTN VarNameSize;
2452 EFI_STATUS Status;
2453 VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
2454
2455 if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
2456 return EFI_INVALID_PARAMETER;
2457 }
2458
2459 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2460
2461 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
2462 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
2463 goto Done;
2464 }
2465
2466 if (VariableName[0] != 0) {
2467 //
2468 // If variable name is not NULL, get next variable.
2469 //
2470 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2471 }
2472
2473 //
2474 // 0: Volatile, 1: HOB, 2: Non-Volatile.
2475 // The index and attributes mapping must be kept in this order as FindVariable
2476 // makes use of this mapping to implement search algorithm.
2477 //
2478 VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
2479 VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
2480 VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
2481
2482 while (TRUE) {
2483 //
2484 // Switch from Volatile to HOB, to Non-Volatile.
2485 //
2486 while ((Variable.CurrPtr >= Variable.EndPtr) ||
2487 (Variable.CurrPtr == NULL) ||
2488 !IsValidVariableHeader (Variable.CurrPtr)
2489 ) {
2490 //
2491 // Find current storage index
2492 //
2493 for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
2494 if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
2495 break;
2496 }
2497 }
2498 ASSERT (Type < VariableStoreTypeMax);
2499 //
2500 // Switch to next storage
2501 //
2502 for (Type++; Type < VariableStoreTypeMax; Type++) {
2503 if (VariableStoreHeader[Type] != NULL) {
2504 break;
2505 }
2506 }
2507 //
2508 // Capture the case that
2509 // 1. current storage is the last one, or
2510 // 2. no further storage
2511 //
2512 if (Type == VariableStoreTypeMax) {
2513 Status = EFI_NOT_FOUND;
2514 goto Done;
2515 }
2516 Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);
2517 Variable.EndPtr = GetEndPointer (VariableStoreHeader[Type]);
2518 Variable.CurrPtr = Variable.StartPtr;
2519 }
2520
2521 //
2522 // Variable is found
2523 //
2524 if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
2525 if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
2526 if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
2527 //
2528 // If it is a IN_DELETED_TRANSITION variable,
2529 // and there is also a same ADDED one at the same time,
2530 // don't return it.
2531 //
2532 VariablePtrTrack.StartPtr = Variable.StartPtr;
2533 VariablePtrTrack.EndPtr = Variable.EndPtr;
2534 Status = FindVariableEx (
2535 GetVariableNamePtr (Variable.CurrPtr),
2536 &Variable.CurrPtr->VendorGuid,
2537 FALSE,
2538 &VariablePtrTrack
2539 );
2540 if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
2541 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2542 continue;
2543 }
2544 }
2545
2546 //
2547 // Don't return NV variable when HOB overrides it
2548 //
2549 if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&
2550 (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))
2551 ) {
2552 VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);
2553 VariableInHob.EndPtr = GetEndPointer (VariableStoreHeader[VariableStoreTypeHob]);
2554 Status = FindVariableEx (
2555 GetVariableNamePtr (Variable.CurrPtr),
2556 &Variable.CurrPtr->VendorGuid,
2557 FALSE,
2558 &VariableInHob
2559 );
2560 if (!EFI_ERROR (Status)) {
2561 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2562 continue;
2563 }
2564 }
2565
2566 VarNameSize = NameSizeOfVariable (Variable.CurrPtr);
2567 ASSERT (VarNameSize != 0);
2568
2569 if (VarNameSize <= *VariableNameSize) {
2570 CopyMem (VariableName, GetVariableNamePtr (Variable.CurrPtr), VarNameSize);
2571 CopyMem (VendorGuid, &Variable.CurrPtr->VendorGuid, sizeof (EFI_GUID));
2572 Status = EFI_SUCCESS;
2573 } else {
2574 Status = EFI_BUFFER_TOO_SMALL;
2575 }
2576
2577 *VariableNameSize = VarNameSize;
2578 goto Done;
2579 }
2580 }
2581
2582 Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
2583 }
2584
2585 Done:
2586 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2587 return Status;
2588 }
2589
2590 /**
2591
2592 This code sets variable in storage blocks (Volatile or Non-Volatile).
2593
2594 Caution: This function may receive untrusted input.
2595 This function may be invoked in SMM mode, and datasize and data are external input.
2596 This function will do basic validation, before parse the data.
2597 This function will parse the authentication carefully to avoid security issues, like
2598 buffer overflow, integer overflow.
2599 This function will check attribute carefully to avoid authentication bypass.
2600
2601 @param VariableName Name of Variable to be found.
2602 @param VendorGuid Variable vendor GUID.
2603 @param Attributes Attribute value of the variable found
2604 @param DataSize Size of Data found. If size is less than the
2605 data, this value contains the required size.
2606 @param Data Data pointer.
2607
2608 @return EFI_INVALID_PARAMETER Invalid parameter.
2609 @return EFI_SUCCESS Set successfully.
2610 @return EFI_OUT_OF_RESOURCES Resource not enough to set variable.
2611 @return EFI_NOT_FOUND Not found.
2612 @return EFI_WRITE_PROTECTED Variable is read-only.
2613
2614 **/
2615 EFI_STATUS
2616 EFIAPI
2617 VariableServiceSetVariable (
2618 IN CHAR16 *VariableName,
2619 IN EFI_GUID *VendorGuid,
2620 IN UINT32 Attributes,
2621 IN UINTN DataSize,
2622 IN VOID *Data
2623 )
2624 {
2625 VARIABLE_POINTER_TRACK Variable;
2626 EFI_STATUS Status;
2627 VARIABLE_HEADER *NextVariable;
2628 EFI_PHYSICAL_ADDRESS Point;
2629 UINTN PayloadSize;
2630
2631 //
2632 // Check input parameters.
2633 //
2634 if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {
2635 return EFI_INVALID_PARAMETER;
2636 }
2637
2638 if (IsReadOnlyVariable (VariableName, VendorGuid)) {
2639 return EFI_WRITE_PROTECTED;
2640 }
2641
2642 if (DataSize != 0 && Data == NULL) {
2643 return EFI_INVALID_PARAMETER;
2644 }
2645
2646 //
2647 // Check for reserverd bit in variable attribute.
2648 //
2649 if ((Attributes & (~EFI_VARIABLE_ATTRIBUTES_MASK)) != 0) {
2650 return EFI_INVALID_PARAMETER;
2651 }
2652
2653 //
2654 // Make sure if runtime bit is set, boot service bit is set also.
2655 //
2656 if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
2657 return EFI_INVALID_PARAMETER;
2658 }
2659
2660 //
2661 // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute
2662 // cannot be set both.
2663 //
2664 if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)
2665 && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {
2666 return EFI_INVALID_PARAMETER;
2667 }
2668
2669 if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {
2670 if (DataSize < AUTHINFO_SIZE) {
2671 //
2672 // Try to write Authenticated Variable without AuthInfo.
2673 //
2674 return EFI_SECURITY_VIOLATION;
2675 }
2676 PayloadSize = DataSize - AUTHINFO_SIZE;
2677 } else if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {
2678 //
2679 // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor.
2680 //
2681 if (DataSize < OFFSET_OF_AUTHINFO2_CERT_DATA ||
2682 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength > DataSize - (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) ||
2683 ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength < OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) {
2684 return EFI_SECURITY_VIOLATION;
2685 }
2686 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
2687 } else {
2688 PayloadSize = DataSize;
2689 }
2690
2691 if ((UINTN)(~0) - PayloadSize < StrSize(VariableName)){
2692 //
2693 // Prevent whole variable size overflow
2694 //
2695 return EFI_INVALID_PARAMETER;
2696 }
2697
2698 //
2699 // The size of the VariableName, including the Unicode Null in bytes plus
2700 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)
2701 // bytes for HwErrRec, and PcdGet32 (PcdMaxVariableSize) bytes for the others.
2702 //
2703 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2704 if (StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER)) {
2705 return EFI_INVALID_PARAMETER;
2706 }
2707 if (!IsHwErrRecVariable(VariableName, VendorGuid)) {
2708 return EFI_INVALID_PARAMETER;
2709 }
2710 } else {
2711 //
2712 // The size of the VariableName, including the Unicode Null in bytes plus
2713 // the DataSize is limited to maximum size of PcdGet32 (PcdMaxVariableSize) bytes.
2714 //
2715 if (StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER)) {
2716 return EFI_INVALID_PARAMETER;
2717 }
2718 }
2719
2720 if (AtRuntime ()) {
2721 //
2722 // HwErrRecSupport Global Variable identifies the level of hardware error record persistence
2723 // support implemented by the platform. This variable is only modified by firmware and is read-only to the OS.
2724 //
2725 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, L"HwErrRecSupport") == 0)) {
2726 return EFI_WRITE_PROTECTED;
2727 }
2728 }
2729
2730 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2731
2732 //
2733 // Consider reentrant in MCA/INIT/NMI. It needs be reupdated.
2734 //
2735 if (1 < InterlockedIncrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState)) {
2736 Point = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
2737 //
2738 // Parse non-volatile variable data and get last variable offset.
2739 //
2740 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point);
2741 while ((NextVariable < GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point))
2742 && IsValidVariableHeader (NextVariable)) {
2743 NextVariable = GetNextVariablePtr (NextVariable);
2744 }
2745 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point;
2746 }
2747
2748 //
2749 // Check whether the input variable is already existed.
2750 //
2751 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, TRUE);
2752 if (!EFI_ERROR (Status)) {
2753 if (((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) && AtRuntime ()) {
2754 return EFI_WRITE_PROTECTED;
2755 }
2756 }
2757
2758 //
2759 // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.
2760 //
2761 AutoUpdateLangVariable (VariableName, Data, DataSize);
2762 //
2763 // Process PK, KEK, Sigdb seperately.
2764 //
2765 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_PLATFORM_KEY_NAME) == 0)){
2766 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, TRUE);
2767 } else if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0)) {
2768 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, FALSE);
2769 } else if (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&
2770 ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))) {
2771 Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, FALSE);
2772 if (EFI_ERROR (Status)) {
2773 Status = ProcessVarWithKek (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes);
2774 }
2775 } else {
2776 Status = ProcessVariable (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes);
2777 }
2778
2779 InterlockedDecrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState);
2780 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2781
2782 return Status;
2783 }
2784
2785 /**
2786
2787 This code returns information about the EFI variables.
2788
2789 Caution: This function may receive untrusted input.
2790 This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
2791
2792 @param Attributes Attributes bitmask to specify the type of variables
2793 on which to return information.
2794 @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
2795 for the EFI variables associated with the attributes specified.
2796 @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
2797 for EFI variables associated with the attributes specified.
2798 @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
2799 associated with the attributes specified.
2800
2801 @return EFI_INVALID_PARAMETER An invalid combination of attribute bits was supplied.
2802 @return EFI_SUCCESS Query successfully.
2803 @return EFI_UNSUPPORTED The attribute is not supported on this platform.
2804
2805 **/
2806 EFI_STATUS
2807 EFIAPI
2808 VariableServiceQueryVariableInfo (
2809 IN UINT32 Attributes,
2810 OUT UINT64 *MaximumVariableStorageSize,
2811 OUT UINT64 *RemainingVariableStorageSize,
2812 OUT UINT64 *MaximumVariableSize
2813 )
2814 {
2815 VARIABLE_HEADER *Variable;
2816 VARIABLE_HEADER *NextVariable;
2817 UINT64 VariableSize;
2818 VARIABLE_STORE_HEADER *VariableStoreHeader;
2819 UINT64 CommonVariableTotalSize;
2820 UINT64 HwErrVariableTotalSize;
2821
2822 CommonVariableTotalSize = 0;
2823 HwErrVariableTotalSize = 0;
2824
2825 if(MaximumVariableStorageSize == NULL || RemainingVariableStorageSize == NULL || MaximumVariableSize == NULL || Attributes == 0) {
2826 return EFI_INVALID_PARAMETER;
2827 }
2828
2829 if((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == 0) {
2830 //
2831 // Make sure the Attributes combination is supported by the platform.
2832 //
2833 return EFI_UNSUPPORTED;
2834 } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
2835 //
2836 // Make sure if runtime bit is set, boot service bit is set also.
2837 //
2838 return EFI_INVALID_PARAMETER;
2839 } else if (AtRuntime () && ((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) {
2840 //
2841 // Make sure RT Attribute is set if we are in Runtime phase.
2842 //
2843 return EFI_INVALID_PARAMETER;
2844 } else if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2845 //
2846 // Make sure Hw Attribute is set with NV.
2847 //
2848 return EFI_INVALID_PARAMETER;
2849 }
2850
2851 AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2852
2853 if((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
2854 //
2855 // Query is Volatile related.
2856 //
2857 VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
2858 } else {
2859 //
2860 // Query is Non-Volatile related.
2861 //
2862 VariableStoreHeader = mNvVariableCache;
2863 }
2864
2865 //
2866 // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize
2867 // with the storage size (excluding the storage header size).
2868 //
2869 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);
2870
2871 //
2872 // Harware error record variable needs larger size.
2873 //
2874 if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
2875 *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize);
2876 *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER);
2877 } else {
2878 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
2879 ASSERT (PcdGet32 (PcdHwErrStorageSize) < VariableStoreHeader->Size);
2880 *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize);
2881 }
2882
2883 //
2884 // Let *MaximumVariableSize be PcdGet32 (PcdMaxVariableSize) with the exception of the variable header size.
2885 //
2886 *MaximumVariableSize = PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER);
2887 }
2888
2889 //
2890 // Point to the starting address of the variables.
2891 //
2892 Variable = GetStartPointer (VariableStoreHeader);
2893
2894 //
2895 // Now walk through the related variable store.
2896 //
2897 while ((Variable < GetEndPointer (VariableStoreHeader)) && IsValidVariableHeader (Variable)) {
2898 NextVariable = GetNextVariablePtr (Variable);
2899 VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable;
2900
2901 if (AtRuntime ()) {
2902 //
2903 // We don't take the state of the variables in mind
2904 // when calculating RemainingVariableStorageSize,
2905 // since the space occupied by variables not marked with
2906 // VAR_ADDED is not allowed to be reclaimed in Runtime.
2907 //
2908 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2909 HwErrVariableTotalSize += VariableSize;
2910 } else {
2911 CommonVariableTotalSize += VariableSize;
2912 }
2913 } else {
2914 //
2915 // Only care about Variables with State VAR_ADDED, because
2916 // the space not marked as VAR_ADDED is reclaimable now.
2917 //
2918 if (Variable->State == VAR_ADDED) {
2919 if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
2920 HwErrVariableTotalSize += VariableSize;
2921 } else {
2922 CommonVariableTotalSize += VariableSize;
2923 }
2924 }
2925 }
2926
2927 //
2928 // Go to the next one.
2929 //
2930 Variable = NextVariable;
2931 }
2932
2933 if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD){
2934 *RemainingVariableStorageSize = *MaximumVariableStorageSize - HwErrVariableTotalSize;
2935 }else {
2936 *RemainingVariableStorageSize = *MaximumVariableStorageSize - CommonVariableTotalSize;
2937 }
2938
2939 if (*RemainingVariableStorageSize < sizeof (VARIABLE_HEADER)) {
2940 *MaximumVariableSize = 0;
2941 } else if ((*RemainingVariableStorageSize - sizeof (VARIABLE_HEADER)) < *MaximumVariableSize) {
2942 *MaximumVariableSize = *RemainingVariableStorageSize - sizeof (VARIABLE_HEADER);
2943 }
2944
2945 ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
2946 return EFI_SUCCESS;
2947 }
2948
2949
2950 /**
2951 This function reclaims variable storage if free size is below the threshold.
2952
2953 Caution: This function may be invoked at SMM mode.
2954 Care must be taken to make sure not security issue.
2955
2956 **/
2957 VOID
2958 ReclaimForOS(
2959 VOID
2960 )
2961 {
2962 EFI_STATUS Status;
2963 UINTN CommonVariableSpace;
2964 UINTN RemainingCommonVariableSpace;
2965 UINTN RemainingHwErrVariableSpace;
2966
2967 Status = EFI_SUCCESS;
2968
2969 CommonVariableSpace = ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase)))->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32(PcdHwErrStorageSize); //Allowable max size of common variable storage space
2970
2971 RemainingCommonVariableSpace = CommonVariableSpace - mVariableModuleGlobal->CommonVariableTotalSize;
2972
2973 RemainingHwErrVariableSpace = PcdGet32 (PcdHwErrStorageSize) - mVariableModuleGlobal->HwErrVariableTotalSize;
2974 //
2975 // Check if the free area is blow a threshold.
2976 //
2977 if ((RemainingCommonVariableSpace < PcdGet32 (PcdMaxVariableSize))
2978 || ((PcdGet32 (PcdHwErrStorageSize) != 0) &&
2979 (RemainingHwErrVariableSpace < PcdGet32 (PcdMaxHardwareErrorVariableSize)))){
2980 Status = Reclaim (
2981 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
2982 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
2983 FALSE,
2984 NULL,
2985 FALSE,
2986 FALSE
2987 );
2988 ASSERT_EFI_ERROR (Status);
2989 }
2990 }
2991
2992 /**
2993 Flush the HOB variable to flash.
2994
2995 @param[in] VariableName Name of variable has been updated or deleted.
2996 @param[in] VendorGuid Guid of variable has been updated or deleted.
2997
2998 **/
2999 VOID
3000 FlushHobVariableToFlash (
3001 IN CHAR16 *VariableName,
3002 IN EFI_GUID *VendorGuid
3003 )
3004 {
3005 EFI_STATUS Status;
3006 VARIABLE_STORE_HEADER *VariableStoreHeader;
3007 VARIABLE_HEADER *Variable;
3008 VOID *VariableData;
3009 BOOLEAN ErrorFlag;
3010
3011 ErrorFlag = FALSE;
3012
3013 //
3014 // Flush the HOB variable to flash.
3015 //
3016 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
3017 VariableStoreHeader = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
3018 //
3019 // Set HobVariableBase to 0, it can avoid SetVariable to call back.
3020 //
3021 mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0;
3022 for ( Variable = GetStartPointer (VariableStoreHeader)
3023 ; (Variable < GetEndPointer (VariableStoreHeader) && IsValidVariableHeader (Variable))
3024 ; Variable = GetNextVariablePtr (Variable)
3025 ) {
3026 if (Variable->State != VAR_ADDED) {
3027 //
3028 // The HOB variable has been set to DELETED state in local.
3029 //
3030 continue;
3031 }
3032 ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0);
3033 if (VendorGuid == NULL || VariableName == NULL ||
3034 !CompareGuid (VendorGuid, &Variable->VendorGuid) ||
3035 StrCmp (VariableName, GetVariableNamePtr (Variable)) != 0) {
3036 VariableData = GetVariableDataPtr (Variable);
3037 Status = VariableServiceSetVariable (
3038 GetVariableNamePtr (Variable),
3039 &Variable->VendorGuid,
3040 Variable->Attributes,
3041 Variable->DataSize,
3042 VariableData
3043 );
3044 DEBUG ((EFI_D_INFO, "Variable driver flush the HOB variable to flash: %g %s %r\n", &Variable->VendorGuid, GetVariableNamePtr (Variable), Status));
3045 } else {
3046 //
3047 // The updated or deleted variable is matched with the HOB variable.
3048 // Don't break here because we will try to set other HOB variables
3049 // since this variable could be set successfully.
3050 //
3051 Status = EFI_SUCCESS;
3052 }
3053 if (!EFI_ERROR (Status)) {
3054 //
3055 // If set variable successful, or the updated or deleted variable is matched with the HOB variable,
3056 // set the HOB variable to DELETED state in local.
3057 //
3058 DEBUG ((EFI_D_INFO, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", &Variable->VendorGuid, GetVariableNamePtr (Variable)));
3059 Variable->State &= VAR_DELETED;
3060 } else {
3061 ErrorFlag = TRUE;
3062 }
3063 }
3064 if (ErrorFlag) {
3065 //
3066 // We still have HOB variable(s) not flushed in flash.
3067 //
3068 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStoreHeader;
3069 } else {
3070 //
3071 // All HOB variables have been flushed in flash.
3072 //
3073 DEBUG ((EFI_D_INFO, "Variable driver: all HOB variables have been flushed in flash.\n"));
3074 if (!AtRuntime ()) {
3075 FreePool ((VOID *) VariableStoreHeader);
3076 }
3077 }
3078 }
3079
3080 }
3081
3082 /**
3083 Initializes variable write service after FVB was ready.
3084
3085 @retval EFI_SUCCESS Function successfully executed.
3086 @retval Others Fail to initialize the variable service.
3087
3088 **/
3089 EFI_STATUS
3090 VariableWriteServiceInitialize (
3091 VOID
3092 )
3093 {
3094 EFI_STATUS Status;
3095 VARIABLE_STORE_HEADER *VariableStoreHeader;
3096 UINTN Index;
3097 UINT8 Data;
3098 EFI_PHYSICAL_ADDRESS VariableStoreBase;
3099
3100 VariableStoreBase = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
3101 VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;
3102
3103 //
3104 // Check if the free area is really free.
3105 //
3106 for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreHeader->Size; Index++) {
3107 Data = ((UINT8 *) mNvVariableCache)[Index];
3108 if (Data != 0xff) {
3109 //
3110 // There must be something wrong in variable store, do reclaim operation.
3111 //
3112 Status = Reclaim (
3113 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
3114 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
3115 FALSE,
3116 NULL,
3117 FALSE,
3118 TRUE
3119 );
3120 if (EFI_ERROR (Status)) {
3121 return Status;
3122 }
3123 break;
3124 }
3125 }
3126
3127 FlushHobVariableToFlash (NULL, NULL);
3128
3129 //
3130 // Authenticated variable initialize.
3131 //
3132 Status = AutenticatedVariableServiceInitialize ();
3133
3134 return Status;
3135 }
3136
3137
3138 /**
3139 Initializes variable store area for non-volatile and volatile variable.
3140
3141 @retval EFI_SUCCESS Function successfully executed.
3142 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
3143
3144 **/
3145 EFI_STATUS
3146 VariableCommonInitialize (
3147 VOID
3148 )
3149 {
3150 EFI_STATUS Status;
3151 VARIABLE_STORE_HEADER *VolatileVariableStore;
3152 VARIABLE_STORE_HEADER *VariableStoreHeader;
3153 VARIABLE_HEADER *NextVariable;
3154 EFI_PHYSICAL_ADDRESS TempVariableStoreHeader;
3155 EFI_PHYSICAL_ADDRESS VariableStoreBase;
3156 UINT64 VariableStoreLength;
3157 UINTN ScratchSize;
3158 UINTN VariableSize;
3159 EFI_HOB_GUID_TYPE *GuidHob;
3160
3161 //
3162 // Allocate runtime memory for variable driver global structure.
3163 //
3164 mVariableModuleGlobal = AllocateRuntimeZeroPool (sizeof (VARIABLE_MODULE_GLOBAL));
3165 if (mVariableModuleGlobal == NULL) {
3166 return EFI_OUT_OF_RESOURCES;
3167 }
3168
3169 InitializeLock (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);
3170
3171 //
3172 // Note that in EdkII variable driver implementation, Hardware Error Record type variable
3173 // is stored with common variable in the same NV region. So the platform integrator should
3174 // ensure that the value of PcdHwErrStorageSize is less than or equal to the value of
3175 // PcdFlashNvStorageVariableSize.
3176 //
3177 ASSERT (PcdGet32 (PcdHwErrStorageSize) <= PcdGet32 (PcdFlashNvStorageVariableSize));
3178
3179 //
3180 // Get HOB variable store.
3181 //
3182 GuidHob = GetFirstGuidHob (&gEfiAuthenticatedVariableGuid);
3183 if (GuidHob != NULL) {
3184 VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob);
3185 VariableStoreLength = (UINT64) (GuidHob->Header.HobLength - sizeof (EFI_HOB_GUID_TYPE));
3186 if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {
3187 mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) AllocateRuntimeCopyPool ((UINTN) VariableStoreLength, (VOID *) VariableStoreHeader);
3188 if (mVariableModuleGlobal->VariableGlobal.HobVariableBase == 0) {
3189 return EFI_OUT_OF_RESOURCES;
3190 }
3191 } else {
3192 DEBUG ((EFI_D_ERROR, "HOB Variable Store header is corrupted!\n"));
3193 }
3194 }
3195
3196 //
3197 // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.
3198 //
3199 ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));
3200 VolatileVariableStore = AllocateRuntimePool (PcdGet32 (PcdVariableStoreSize) + ScratchSize);
3201 if (VolatileVariableStore == NULL) {
3202 FreePool (mVariableModuleGlobal);
3203 return EFI_OUT_OF_RESOURCES;
3204 }
3205
3206 SetMem (VolatileVariableStore, PcdGet32 (PcdVariableStoreSize) + ScratchSize, 0xff);
3207
3208 //
3209 // Initialize Variable Specific Data.
3210 //
3211 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VolatileVariableStore;
3212 mVariableModuleGlobal->VolatileLastVariableOffset = (UINTN) GetStartPointer (VolatileVariableStore) - (UINTN) VolatileVariableStore;
3213 mVariableModuleGlobal->FvbInstance = NULL;
3214
3215 CopyGuid (&VolatileVariableStore->Signature, &gEfiAuthenticatedVariableGuid);
3216 VolatileVariableStore->Size = PcdGet32 (PcdVariableStoreSize);
3217 VolatileVariableStore->Format = VARIABLE_STORE_FORMATTED;
3218 VolatileVariableStore->State = VARIABLE_STORE_HEALTHY;
3219 VolatileVariableStore->Reserved = 0;
3220 VolatileVariableStore->Reserved1 = 0;
3221
3222 //
3223 // Get non-volatile variable store.
3224 //
3225
3226 TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);
3227 if (TempVariableStoreHeader == 0) {
3228 TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);
3229 }
3230
3231 //
3232 // Check if the Firmware Volume is not corrupted
3233 //
3234 if ((((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader))->Signature != EFI_FVH_SIGNATURE) ||
3235 (!CompareGuid (&gEfiSystemNvDataFvGuid, &((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader))->FileSystemGuid))) {
3236 Status = EFI_VOLUME_CORRUPTED;
3237 DEBUG ((EFI_D_ERROR, "Firmware Volume for Variable Store is corrupted\n"));
3238 goto Done;
3239 }
3240
3241 VariableStoreBase = TempVariableStoreHeader + \
3242 (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader)) -> HeaderLength);
3243 VariableStoreLength = (UINT64) PcdGet32 (PcdFlashNvStorageVariableSize) - \
3244 (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader)) -> HeaderLength);
3245
3246 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
3247 VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;
3248 if (GetVariableStoreStatus (VariableStoreHeader) != EfiValid) {
3249 Status = EFI_VOLUME_CORRUPTED;
3250 DEBUG((EFI_D_INFO, "Variable Store header is corrupted\n"));
3251 goto Done;
3252 }
3253 ASSERT(VariableStoreHeader->Size == VariableStoreLength);
3254
3255 //
3256 // The max variable or hardware error variable size should be < variable store size.
3257 //
3258 ASSERT(MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize)) < VariableStoreLength);
3259
3260 //
3261 // Parse non-volatile variable data and get last variable offset.
3262 //
3263 NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase);
3264 while (IsValidVariableHeader (NextVariable)) {
3265 VariableSize = NextVariable->NameSize + NextVariable->DataSize + sizeof (VARIABLE_HEADER);
3266 if ((NextVariable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
3267 mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VariableSize);
3268 } else {
3269 mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize);
3270 }
3271
3272 NextVariable = GetNextVariablePtr (NextVariable);
3273 }
3274
3275 mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) VariableStoreBase;
3276
3277 //
3278 // Allocate runtime memory used for a memory copy of the FLASH region.
3279 // Keep the memory and the FLASH in sync as updates occur
3280 //
3281 mNvVariableCache = AllocateRuntimeZeroPool ((UINTN)VariableStoreLength);
3282 if (mNvVariableCache == NULL) {
3283 Status = EFI_OUT_OF_RESOURCES;
3284 goto Done;
3285 }
3286 CopyMem (mNvVariableCache, (CHAR8 *)(UINTN)VariableStoreBase, (UINTN)VariableStoreLength);
3287 Status = EFI_SUCCESS;
3288
3289 Done:
3290 if (EFI_ERROR (Status)) {
3291 FreePool (mVariableModuleGlobal);
3292 FreePool (VolatileVariableStore);
3293 }
3294
3295 return Status;
3296 }
3297
3298
3299 /**
3300 Get the proper fvb handle and/or fvb protocol by the given Flash address.
3301
3302 @param[in] Address The Flash address.
3303 @param[out] FvbHandle In output, if it is not NULL, it points to the proper FVB handle.
3304 @param[out] FvbProtocol In output, if it is not NULL, it points to the proper FVB protocol.
3305
3306 **/
3307 EFI_STATUS
3308 GetFvbInfoByAddress (
3309 IN EFI_PHYSICAL_ADDRESS Address,
3310 OUT EFI_HANDLE *FvbHandle OPTIONAL,
3311 OUT EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL **FvbProtocol OPTIONAL
3312 )
3313 {
3314 EFI_STATUS Status;
3315 EFI_HANDLE *HandleBuffer;
3316 UINTN HandleCount;
3317 UINTN Index;
3318 EFI_PHYSICAL_ADDRESS FvbBaseAddress;
3319 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
3320 EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
3321 EFI_FVB_ATTRIBUTES_2 Attributes;
3322
3323 //
3324 // Get all FVB handles.
3325 //
3326 Status = GetFvbCountAndBuffer (&HandleCount, &HandleBuffer);
3327 if (EFI_ERROR (Status)) {
3328 return EFI_NOT_FOUND;
3329 }
3330
3331 //
3332 // Get the FVB to access variable store.
3333 //
3334 Fvb = NULL;
3335 for (Index = 0; Index < HandleCount; Index += 1, Status = EFI_NOT_FOUND, Fvb = NULL) {
3336 Status = GetFvbByHandle (HandleBuffer[Index], &Fvb);
3337 if (EFI_ERROR (Status)) {
3338 Status = EFI_NOT_FOUND;
3339 break;
3340 }
3341
3342 //
3343 // Ensure this FVB protocol supported Write operation.
3344 //
3345 Status = Fvb->GetAttributes (Fvb, &Attributes);
3346 if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {
3347 continue;
3348 }
3349
3350 //
3351 // Compare the address and select the right one.
3352 //
3353 Status = Fvb->GetPhysicalAddress (Fvb, &FvbBaseAddress);
3354 if (EFI_ERROR (Status)) {
3355 continue;
3356 }
3357
3358 FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) FvbBaseAddress);
3359 if ((Address >= FvbBaseAddress) && (Address < (FvbBaseAddress + FwVolHeader->FvLength))) {
3360 if (FvbHandle != NULL) {
3361 *FvbHandle = HandleBuffer[Index];
3362 }
3363 if (FvbProtocol != NULL) {
3364 *FvbProtocol = Fvb;
3365 }
3366 Status = EFI_SUCCESS;
3367 break;
3368 }
3369 }
3370 FreePool (HandleBuffer);
3371
3372 if (Fvb == NULL) {
3373 Status = EFI_NOT_FOUND;
3374 }
3375
3376 return Status;
3377 }
3378