]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Universal/Variable/RuntimeDxe/VariableDxe.c
MdeModulePkg: Connect VariablePolicy business logic to VariableServices
[mirror_edk2.git] / MdeModulePkg / Universal / Variable / RuntimeDxe / VariableDxe.c
1 /** @file
2 Implement all four UEFI Runtime Variable services for the nonvolatile
3 and volatile storage space and install variable architecture protocol.
4
5 Copyright (C) 2013, Red Hat, Inc.
6 Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.<BR>
7 (C) Copyright 2015 Hewlett Packard Enterprise Development LP<BR>
8 Copyright (c) Microsoft Corporation.
9 SPDX-License-Identifier: BSD-2-Clause-Patent
10
11 **/
12
13 #include "Variable.h"
14
15 #include <Protocol/VariablePolicy.h>
16 #include <Library/VariablePolicyLib.h>
17
18 EFI_STATUS
19 EFIAPI
20 ProtocolIsVariablePolicyEnabled (
21 OUT BOOLEAN *State
22 );
23
24 EFI_HANDLE mHandle = NULL;
25 EFI_EVENT mVirtualAddressChangeEvent = NULL;
26 VOID *mFtwRegistration = NULL;
27 VOID ***mVarCheckAddressPointer = NULL;
28 UINTN mVarCheckAddressPointerCount = 0;
29 EDKII_VARIABLE_LOCK_PROTOCOL mVariableLock = { VariableLockRequestToLock };
30 EDKII_VARIABLE_POLICY_PROTOCOL mVariablePolicyProtocol = { EDKII_VARIABLE_POLICY_PROTOCOL_REVISION,
31 DisableVariablePolicy,
32 ProtocolIsVariablePolicyEnabled,
33 RegisterVariablePolicy,
34 DumpVariablePolicy,
35 LockVariablePolicy };
36 EDKII_VAR_CHECK_PROTOCOL mVarCheck = { VarCheckRegisterSetVariableCheckHandler,
37 VarCheckVariablePropertySet,
38 VarCheckVariablePropertyGet };
39
40 /**
41 Some Secure Boot Policy Variable may update following other variable changes(SecureBoot follows PK change, etc).
42 Record their initial State when variable write service is ready.
43
44 **/
45 VOID
46 EFIAPI
47 RecordSecureBootPolicyVarData(
48 VOID
49 );
50
51 /**
52 Return TRUE if ExitBootServices () has been called.
53
54 @retval TRUE If ExitBootServices () has been called.
55 **/
56 BOOLEAN
57 AtRuntime (
58 VOID
59 )
60 {
61 return EfiAtRuntime ();
62 }
63
64
65 /**
66 Initializes a basic mutual exclusion lock.
67
68 This function initializes a basic mutual exclusion lock to the released state
69 and returns the lock. Each lock provides mutual exclusion access at its task
70 priority level. Since there is no preemption or multiprocessor support in EFI,
71 acquiring the lock only consists of raising to the locks TPL.
72 If Lock is NULL, then ASSERT().
73 If Priority is not a valid TPL value, then ASSERT().
74
75 @param Lock A pointer to the lock data structure to initialize.
76 @param Priority EFI TPL is associated with the lock.
77
78 @return The lock.
79
80 **/
81 EFI_LOCK *
82 InitializeLock (
83 IN OUT EFI_LOCK *Lock,
84 IN EFI_TPL Priority
85 )
86 {
87 return EfiInitializeLock (Lock, Priority);
88 }
89
90
91 /**
92 Acquires lock only at boot time. Simply returns at runtime.
93
94 This is a temperary function that will be removed when
95 EfiAcquireLock() in UefiLib can handle the call in UEFI
96 Runtimer driver in RT phase.
97 It calls EfiAcquireLock() at boot time, and simply returns
98 at runtime.
99
100 @param Lock A pointer to the lock to acquire.
101
102 **/
103 VOID
104 AcquireLockOnlyAtBootTime (
105 IN EFI_LOCK *Lock
106 )
107 {
108 if (!AtRuntime ()) {
109 EfiAcquireLock (Lock);
110 }
111 }
112
113
114 /**
115 Releases lock only at boot time. Simply returns at runtime.
116
117 This is a temperary function which will be removed when
118 EfiReleaseLock() in UefiLib can handle the call in UEFI
119 Runtimer driver in RT phase.
120 It calls EfiReleaseLock() at boot time and simply returns
121 at runtime.
122
123 @param Lock A pointer to the lock to release.
124
125 **/
126 VOID
127 ReleaseLockOnlyAtBootTime (
128 IN EFI_LOCK *Lock
129 )
130 {
131 if (!AtRuntime ()) {
132 EfiReleaseLock (Lock);
133 }
134 }
135
136 /**
137 Retrieve the Fault Tolerent Write protocol interface.
138
139 @param[out] FtwProtocol The interface of Ftw protocol
140
141 @retval EFI_SUCCESS The FTW protocol instance was found and returned in FtwProtocol.
142 @retval EFI_NOT_FOUND The FTW protocol instance was not found.
143 @retval EFI_INVALID_PARAMETER SarProtocol is NULL.
144
145 **/
146 EFI_STATUS
147 GetFtwProtocol (
148 OUT VOID **FtwProtocol
149 )
150 {
151 EFI_STATUS Status;
152
153 //
154 // Locate Fault Tolerent Write protocol
155 //
156 Status = gBS->LocateProtocol (
157 &gEfiFaultTolerantWriteProtocolGuid,
158 NULL,
159 FtwProtocol
160 );
161 return Status;
162 }
163
164 /**
165 Retrieve the FVB protocol interface by HANDLE.
166
167 @param[in] FvBlockHandle The handle of FVB protocol that provides services for
168 reading, writing, and erasing the target block.
169 @param[out] FvBlock The interface of FVB protocol
170
171 @retval EFI_SUCCESS The interface information for the specified protocol was returned.
172 @retval EFI_UNSUPPORTED The device does not support the FVB protocol.
173 @retval EFI_INVALID_PARAMETER FvBlockHandle is not a valid EFI_HANDLE or FvBlock is NULL.
174
175 **/
176 EFI_STATUS
177 GetFvbByHandle (
178 IN EFI_HANDLE FvBlockHandle,
179 OUT EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL **FvBlock
180 )
181 {
182 //
183 // To get the FVB protocol interface on the handle
184 //
185 return gBS->HandleProtocol (
186 FvBlockHandle,
187 &gEfiFirmwareVolumeBlockProtocolGuid,
188 (VOID **) FvBlock
189 );
190 }
191
192
193 /**
194 Function returns an array of handles that support the FVB protocol
195 in a buffer allocated from pool.
196
197 @param[out] NumberHandles The number of handles returned in Buffer.
198 @param[out] Buffer A pointer to the buffer to return the requested
199 array of handles that support FVB protocol.
200
201 @retval EFI_SUCCESS The array of handles was returned in Buffer, and the number of
202 handles in Buffer was returned in NumberHandles.
203 @retval EFI_NOT_FOUND No FVB handle was found.
204 @retval EFI_OUT_OF_RESOURCES There is not enough pool memory to store the matching results.
205 @retval EFI_INVALID_PARAMETER NumberHandles is NULL or Buffer is NULL.
206
207 **/
208 EFI_STATUS
209 GetFvbCountAndBuffer (
210 OUT UINTN *NumberHandles,
211 OUT EFI_HANDLE **Buffer
212 )
213 {
214 EFI_STATUS Status;
215
216 //
217 // Locate all handles of Fvb protocol
218 //
219 Status = gBS->LocateHandleBuffer (
220 ByProtocol,
221 &gEfiFirmwareVolumeBlockProtocolGuid,
222 NULL,
223 NumberHandles,
224 Buffer
225 );
226 return Status;
227 }
228
229
230 /**
231 Notification function of EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE.
232
233 This is a notification function registered on EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.
234 It convers pointer to new virtual address.
235
236 @param Event Event whose notification function is being invoked.
237 @param Context Pointer to the notification function's context.
238
239 **/
240 VOID
241 EFIAPI
242 VariableClassAddressChangeEvent (
243 IN EFI_EVENT Event,
244 IN VOID *Context
245 )
246 {
247 UINTN Index;
248
249 if (mVariableModuleGlobal->FvbInstance != NULL) {
250 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->GetBlockSize);
251 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->GetPhysicalAddress);
252 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->GetAttributes);
253 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->SetAttributes);
254 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->Read);
255 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->Write);
256 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->EraseBlocks);
257 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance);
258 }
259 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->PlatformLangCodes);
260 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->LangCodes);
261 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->PlatformLang);
262 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);
263 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
264 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->VariableGlobal.HobVariableBase);
265 EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal);
266 EfiConvertPointer (0x0, (VOID **) &mNvVariableCache);
267 EfiConvertPointer (0x0, (VOID **) &mNvFvHeaderCache);
268
269 if (mAuthContextOut.AddressPointer != NULL) {
270 for (Index = 0; Index < mAuthContextOut.AddressPointerCount; Index++) {
271 EfiConvertPointer (0x0, (VOID **) mAuthContextOut.AddressPointer[Index]);
272 }
273 }
274
275 if (mVarCheckAddressPointer != NULL) {
276 for (Index = 0; Index < mVarCheckAddressPointerCount; Index++) {
277 EfiConvertPointer (0x0, (VOID **) mVarCheckAddressPointer[Index]);
278 }
279 }
280 }
281
282
283 /**
284 Notification function of EVT_GROUP_READY_TO_BOOT event group.
285
286 This is a notification function registered on EVT_GROUP_READY_TO_BOOT event group.
287 When the Boot Manager is about to load and execute a boot option, it reclaims variable
288 storage if free size is below the threshold.
289
290 @param Event Event whose notification function is being invoked.
291 @param Context Pointer to the notification function's context.
292
293 **/
294 VOID
295 EFIAPI
296 OnReadyToBoot (
297 EFI_EVENT Event,
298 VOID *Context
299 )
300 {
301 EFI_STATUS Status;
302
303 if (!mEndOfDxe) {
304 MorLockInitAtEndOfDxe ();
305
306 Status = LockVariablePolicy ();
307 ASSERT_EFI_ERROR (Status);
308 //
309 // Set the End Of DXE bit in case the EFI_END_OF_DXE_EVENT_GROUP_GUID event is not signaled.
310 //
311 mEndOfDxe = TRUE;
312 mVarCheckAddressPointer = VarCheckLibInitializeAtEndOfDxe (&mVarCheckAddressPointerCount);
313 //
314 // The initialization for variable quota.
315 //
316 InitializeVariableQuota ();
317 }
318 ReclaimForOS ();
319 if (FeaturePcdGet (PcdVariableCollectStatistics)) {
320 if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
321 gBS->InstallConfigurationTable (&gEfiAuthenticatedVariableGuid, gVariableInfo);
322 } else {
323 gBS->InstallConfigurationTable (&gEfiVariableGuid, gVariableInfo);
324 }
325 }
326
327 gBS->CloseEvent (Event);
328 }
329
330 /**
331 Notification function of EFI_END_OF_DXE_EVENT_GROUP_GUID event group.
332
333 This is a notification function registered on EFI_END_OF_DXE_EVENT_GROUP_GUID event group.
334
335 @param Event Event whose notification function is being invoked.
336 @param Context Pointer to the notification function's context.
337
338 **/
339 VOID
340 EFIAPI
341 OnEndOfDxe (
342 EFI_EVENT Event,
343 VOID *Context
344 )
345 {
346 EFI_STATUS Status;
347
348 DEBUG ((EFI_D_INFO, "[Variable]END_OF_DXE is signaled\n"));
349 MorLockInitAtEndOfDxe ();
350 Status = LockVariablePolicy ();
351 ASSERT_EFI_ERROR (Status);
352 mEndOfDxe = TRUE;
353 mVarCheckAddressPointer = VarCheckLibInitializeAtEndOfDxe (&mVarCheckAddressPointerCount);
354 //
355 // The initialization for variable quota.
356 //
357 InitializeVariableQuota ();
358 if (PcdGetBool (PcdReclaimVariableSpaceAtEndOfDxe)) {
359 ReclaimForOS ();
360 }
361
362 gBS->CloseEvent (Event);
363 }
364
365 /**
366 Initializes variable write service for DXE.
367
368 **/
369 VOID
370 VariableWriteServiceInitializeDxe (
371 VOID
372 )
373 {
374 EFI_STATUS Status;
375
376 Status = VariableWriteServiceInitialize ();
377 if (EFI_ERROR (Status)) {
378 DEBUG ((DEBUG_ERROR, "Variable write service initialization failed. Status = %r\n", Status));
379 }
380
381 //
382 // Some Secure Boot Policy Var (SecureBoot, etc) updates following other
383 // Secure Boot Policy Variable change. Record their initial value.
384 //
385 RecordSecureBootPolicyVarData();
386
387 //
388 // Install the Variable Write Architectural protocol.
389 //
390 Status = gBS->InstallProtocolInterface (
391 &mHandle,
392 &gEfiVariableWriteArchProtocolGuid,
393 EFI_NATIVE_INTERFACE,
394 NULL
395 );
396 ASSERT_EFI_ERROR (Status);
397 }
398
399 /**
400 Fault Tolerant Write protocol notification event handler.
401
402 Non-Volatile variable write may needs FTW protocol to reclaim when
403 writting variable.
404
405 @param[in] Event Event whose notification function is being invoked.
406 @param[in] Context Pointer to the notification function's context.
407
408 **/
409 VOID
410 EFIAPI
411 FtwNotificationEvent (
412 IN EFI_EVENT Event,
413 IN VOID *Context
414 )
415 {
416 EFI_STATUS Status;
417 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol;
418 EFI_FAULT_TOLERANT_WRITE_PROTOCOL *FtwProtocol;
419 EFI_PHYSICAL_ADDRESS NvStorageVariableBase;
420 EFI_GCD_MEMORY_SPACE_DESCRIPTOR GcdDescriptor;
421 EFI_PHYSICAL_ADDRESS BaseAddress;
422 UINT64 Length;
423 EFI_PHYSICAL_ADDRESS VariableStoreBase;
424 UINT64 VariableStoreLength;
425 UINTN FtwMaxBlockSize;
426
427 //
428 // Ensure FTW protocol is installed.
429 //
430 Status = GetFtwProtocol ((VOID**) &FtwProtocol);
431 if (EFI_ERROR (Status)) {
432 return ;
433 }
434
435 Status = FtwProtocol->GetMaxBlockSize (FtwProtocol, &FtwMaxBlockSize);
436 if (!EFI_ERROR (Status)) {
437 ASSERT (PcdGet32 (PcdFlashNvStorageVariableSize) <= FtwMaxBlockSize);
438 }
439
440 NvStorageVariableBase = NV_STORAGE_VARIABLE_BASE;
441 VariableStoreBase = NvStorageVariableBase + mNvFvHeaderCache->HeaderLength;
442
443 //
444 // Let NonVolatileVariableBase point to flash variable store base directly after FTW ready.
445 //
446 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
447
448 //
449 // Find the proper FVB protocol for variable.
450 //
451 Status = GetFvbInfoByAddress (NvStorageVariableBase, NULL, &FvbProtocol);
452 if (EFI_ERROR (Status)) {
453 return ;
454 }
455 mVariableModuleGlobal->FvbInstance = FvbProtocol;
456
457 //
458 // Mark the variable storage region of the FLASH as RUNTIME.
459 //
460 VariableStoreLength = mNvVariableCache->Size;
461 BaseAddress = VariableStoreBase & (~EFI_PAGE_MASK);
462 Length = VariableStoreLength + (VariableStoreBase - BaseAddress);
463 Length = (Length + EFI_PAGE_SIZE - 1) & (~EFI_PAGE_MASK);
464
465 Status = gDS->GetMemorySpaceDescriptor (BaseAddress, &GcdDescriptor);
466 if (EFI_ERROR (Status)) {
467 DEBUG ((DEBUG_WARN, "Variable driver failed to get flash memory attribute.\n"));
468 } else {
469 if ((GcdDescriptor.Attributes & EFI_MEMORY_RUNTIME) == 0) {
470 Status = gDS->SetMemorySpaceAttributes (
471 BaseAddress,
472 Length,
473 GcdDescriptor.Attributes | EFI_MEMORY_RUNTIME
474 );
475 if (EFI_ERROR (Status)) {
476 DEBUG ((DEBUG_WARN, "Variable driver failed to add EFI_MEMORY_RUNTIME attribute to Flash.\n"));
477 }
478 }
479 }
480
481 //
482 // Initializes variable write service after FTW was ready.
483 //
484 VariableWriteServiceInitializeDxe ();
485
486 //
487 // Close the notify event to avoid install gEfiVariableWriteArchProtocolGuid again.
488 //
489 gBS->CloseEvent (Event);
490
491 }
492
493
494 /**
495 This API function returns whether or not the policy engine is
496 currently being enforced.
497
498 @param[out] State Pointer to a return value for whether the policy enforcement
499 is currently enabled.
500
501 @retval EFI_SUCCESS
502 @retval Others An error has prevented this command from completing.
503
504 **/
505 EFI_STATUS
506 EFIAPI
507 ProtocolIsVariablePolicyEnabled (
508 OUT BOOLEAN *State
509 )
510 {
511 *State = IsVariablePolicyEnabled ();
512 return EFI_SUCCESS;
513 }
514
515
516 /**
517 Variable Driver main entry point. The Variable driver places the 4 EFI
518 runtime services in the EFI System Table and installs arch protocols
519 for variable read and write services being available. It also registers
520 a notification function for an EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.
521
522 @param[in] ImageHandle The firmware allocated handle for the EFI image.
523 @param[in] SystemTable A pointer to the EFI System Table.
524
525 @retval EFI_SUCCESS Variable service successfully initialized.
526
527 **/
528 EFI_STATUS
529 EFIAPI
530 VariableServiceInitialize (
531 IN EFI_HANDLE ImageHandle,
532 IN EFI_SYSTEM_TABLE *SystemTable
533 )
534 {
535 EFI_STATUS Status;
536 EFI_EVENT ReadyToBootEvent;
537 EFI_EVENT EndOfDxeEvent;
538
539 Status = VariableCommonInitialize ();
540 ASSERT_EFI_ERROR (Status);
541
542 Status = gBS->InstallMultipleProtocolInterfaces (
543 &mHandle,
544 &gEdkiiVariableLockProtocolGuid,
545 &mVariableLock,
546 NULL
547 );
548 ASSERT_EFI_ERROR (Status);
549
550 Status = gBS->InstallMultipleProtocolInterfaces (
551 &mHandle,
552 &gEdkiiVarCheckProtocolGuid,
553 &mVarCheck,
554 NULL
555 );
556 ASSERT_EFI_ERROR (Status);
557
558 SystemTable->RuntimeServices->GetVariable = VariableServiceGetVariable;
559 SystemTable->RuntimeServices->GetNextVariableName = VariableServiceGetNextVariableName;
560 SystemTable->RuntimeServices->SetVariable = VariableServiceSetVariable;
561 SystemTable->RuntimeServices->QueryVariableInfo = VariableServiceQueryVariableInfo;
562
563 //
564 // Now install the Variable Runtime Architectural protocol on a new handle.
565 //
566 Status = gBS->InstallProtocolInterface (
567 &mHandle,
568 &gEfiVariableArchProtocolGuid,
569 EFI_NATIVE_INTERFACE,
570 NULL
571 );
572 ASSERT_EFI_ERROR (Status);
573
574 if (!PcdGetBool (PcdEmuVariableNvModeEnable)) {
575 //
576 // Register FtwNotificationEvent () notify function.
577 //
578 EfiCreateProtocolNotifyEvent (
579 &gEfiFaultTolerantWriteProtocolGuid,
580 TPL_CALLBACK,
581 FtwNotificationEvent,
582 (VOID *)SystemTable,
583 &mFtwRegistration
584 );
585 } else {
586 //
587 // Emulated non-volatile variable mode does not depend on FVB and FTW.
588 //
589 VariableWriteServiceInitializeDxe ();
590 }
591
592 Status = gBS->CreateEventEx (
593 EVT_NOTIFY_SIGNAL,
594 TPL_NOTIFY,
595 VariableClassAddressChangeEvent,
596 NULL,
597 &gEfiEventVirtualAddressChangeGuid,
598 &mVirtualAddressChangeEvent
599 );
600 ASSERT_EFI_ERROR (Status);
601
602 //
603 // Register the event handling function to reclaim variable for OS usage.
604 //
605 Status = EfiCreateEventReadyToBootEx (
606 TPL_NOTIFY,
607 OnReadyToBoot,
608 NULL,
609 &ReadyToBootEvent
610 );
611 ASSERT_EFI_ERROR (Status);
612
613 //
614 // Register the event handling function to set the End Of DXE flag.
615 //
616 Status = gBS->CreateEventEx (
617 EVT_NOTIFY_SIGNAL,
618 TPL_CALLBACK,
619 OnEndOfDxe,
620 NULL,
621 &gEfiEndOfDxeEventGroupGuid,
622 &EndOfDxeEvent
623 );
624 ASSERT_EFI_ERROR (Status);
625
626 // Register and initialize the VariablePolicy engine.
627 Status = InitVariablePolicyLib (VariableServiceGetVariable);
628 ASSERT_EFI_ERROR (Status);
629 Status = VarCheckRegisterSetVariableCheckHandler (ValidateSetVariable);
630 ASSERT_EFI_ERROR (Status);
631 Status = gBS->InstallMultipleProtocolInterfaces (
632 &mHandle,
633 &gEdkiiVariablePolicyProtocolGuid,
634 &mVariablePolicyProtocol,
635 NULL
636 );
637 ASSERT_EFI_ERROR (Status);
638
639 return EFI_SUCCESS;
640 }
641