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