]> git.proxmox.com Git - mirror_edk2.git/blob - OvmfPkg/IoMmuDxe/AmdSevIoMmu.c
OvmfPkg/PlatformDxe: list "Platform.h" in the INF file
[mirror_edk2.git] / OvmfPkg / IoMmuDxe / AmdSevIoMmu.c
1 /** @file
2
3 The protocol provides support to allocate, free, map and umap a DMA buffer
4 for bus master (e.g PciHostBridge). When SEV is enabled, the DMA operations
5 must be performed on unencrypted buffer hence we use a bounce buffer to map
6 the guest buffer into an unencrypted DMA buffer.
7
8 Copyright (c) 2017, AMD Inc. All rights reserved.<BR>
9 Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
10
11 This program and the accompanying materials are licensed and made available
12 under the terms and conditions of the BSD License which accompanies this
13 distribution. The full text of the license may be found at
14 http://opensource.org/licenses/bsd-license.php
15
16 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
17 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
18
19 **/
20
21 #include "AmdSevIoMmu.h"
22
23 #define MAP_INFO_SIG SIGNATURE_64 ('M', 'A', 'P', '_', 'I', 'N', 'F', 'O')
24
25 typedef struct {
26 UINT64 Signature;
27 LIST_ENTRY Link;
28 EDKII_IOMMU_OPERATION Operation;
29 UINTN NumberOfBytes;
30 UINTN NumberOfPages;
31 EFI_PHYSICAL_ADDRESS CryptedAddress;
32 EFI_PHYSICAL_ADDRESS PlainTextAddress;
33 } MAP_INFO;
34
35 //
36 // List of the MAP_INFO structures that have been set up by IoMmuMap() and not
37 // yet torn down by IoMmuUnmap(). The list represents the full set of mappings
38 // currently in effect.
39 //
40 STATIC LIST_ENTRY mMapInfos = INITIALIZE_LIST_HEAD_VARIABLE (mMapInfos);
41
42 #define COMMON_BUFFER_SIG SIGNATURE_64 ('C', 'M', 'N', 'B', 'U', 'F', 'F', 'R')
43
44 //
45 // ASCII names for EDKII_IOMMU_OPERATION constants, for debug logging.
46 //
47 STATIC CONST CHAR8 * CONST
48 mBusMasterOperationName[EdkiiIoMmuOperationMaximum] = {
49 "Read",
50 "Write",
51 "CommonBuffer",
52 "Read64",
53 "Write64",
54 "CommonBuffer64"
55 };
56
57 //
58 // The following structure enables Map() and Unmap() to perform in-place
59 // decryption and encryption, respectively, for BusMasterCommonBuffer[64]
60 // operations, without dynamic memory allocation or release.
61 //
62 // Both COMMON_BUFFER_HEADER and COMMON_BUFFER_HEADER.StashBuffer are allocated
63 // by AllocateBuffer() and released by FreeBuffer().
64 //
65 #pragma pack (1)
66 typedef struct {
67 UINT64 Signature;
68
69 //
70 // Always allocated from EfiBootServicesData type memory, and always
71 // encrypted.
72 //
73 VOID *StashBuffer;
74
75 //
76 // Followed by the actual common buffer, starting at the next page.
77 //
78 } COMMON_BUFFER_HEADER;
79 #pragma pack ()
80
81 /**
82 Provides the controller-specific addresses required to access system memory
83 from a DMA bus master. On SEV guest, the DMA operations must be performed on
84 shared buffer hence we allocate a bounce buffer to map the HostAddress to a
85 DeviceAddress. The Encryption attribute is removed from the DeviceAddress
86 buffer.
87
88 @param This The protocol instance pointer.
89 @param Operation Indicates if the bus master is going to read or
90 write to system memory.
91 @param HostAddress The system memory address to map to the PCI
92 controller.
93 @param NumberOfBytes On input the number of bytes to map. On output
94 the number of bytes that were mapped.
95 @param DeviceAddress The resulting map address for the bus master
96 PCI controller to use to access the hosts
97 HostAddress.
98 @param Mapping A resulting value to pass to Unmap().
99
100 @retval EFI_SUCCESS The range was mapped for the returned
101 NumberOfBytes.
102 @retval EFI_UNSUPPORTED The HostAddress cannot be mapped as a common
103 buffer.
104 @retval EFI_INVALID_PARAMETER One or more parameters are invalid.
105 @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a
106 lack of resources.
107 @retval EFI_DEVICE_ERROR The system hardware could not map the requested
108 address.
109
110 **/
111 EFI_STATUS
112 EFIAPI
113 IoMmuMap (
114 IN EDKII_IOMMU_PROTOCOL *This,
115 IN EDKII_IOMMU_OPERATION Operation,
116 IN VOID *HostAddress,
117 IN OUT UINTN *NumberOfBytes,
118 OUT EFI_PHYSICAL_ADDRESS *DeviceAddress,
119 OUT VOID **Mapping
120 )
121 {
122 EFI_STATUS Status;
123 MAP_INFO *MapInfo;
124 EFI_ALLOCATE_TYPE AllocateType;
125 COMMON_BUFFER_HEADER *CommonBufferHeader;
126 VOID *DecryptionSource;
127
128 DEBUG ((
129 DEBUG_VERBOSE,
130 "%a: Operation=%a Host=0x%p Bytes=0x%Lx\n",
131 __FUNCTION__,
132 ((Operation >= 0 &&
133 Operation < ARRAY_SIZE (mBusMasterOperationName)) ?
134 mBusMasterOperationName[Operation] :
135 "Invalid"),
136 HostAddress,
137 (UINT64)((NumberOfBytes == NULL) ? 0 : *NumberOfBytes)
138 ));
139
140 if (HostAddress == NULL || NumberOfBytes == NULL || DeviceAddress == NULL ||
141 Mapping == NULL) {
142 return EFI_INVALID_PARAMETER;
143 }
144
145 //
146 // Allocate a MAP_INFO structure to remember the mapping when Unmap() is
147 // called later.
148 //
149 MapInfo = AllocatePool (sizeof (MAP_INFO));
150 if (MapInfo == NULL) {
151 Status = EFI_OUT_OF_RESOURCES;
152 goto Failed;
153 }
154
155 //
156 // Initialize the MAP_INFO structure, except the PlainTextAddress field
157 //
158 ZeroMem (&MapInfo->Link, sizeof MapInfo->Link);
159 MapInfo->Signature = MAP_INFO_SIG;
160 MapInfo->Operation = Operation;
161 MapInfo->NumberOfBytes = *NumberOfBytes;
162 MapInfo->NumberOfPages = EFI_SIZE_TO_PAGES (MapInfo->NumberOfBytes);
163 MapInfo->CryptedAddress = (UINTN)HostAddress;
164
165 //
166 // In the switch statement below, we point "MapInfo->PlainTextAddress" to the
167 // plaintext buffer, according to Operation. We also set "DecryptionSource".
168 //
169 MapInfo->PlainTextAddress = MAX_ADDRESS;
170 AllocateType = AllocateAnyPages;
171 DecryptionSource = (VOID *)(UINTN)MapInfo->CryptedAddress;
172 switch (Operation) {
173 //
174 // For BusMasterRead[64] and BusMasterWrite[64] operations, a bounce buffer
175 // is necessary regardless of whether the original (crypted) buffer crosses
176 // the 4GB limit or not -- we have to allocate a separate plaintext buffer.
177 // The only variable is whether the plaintext buffer should be under 4GB.
178 //
179 case EdkiiIoMmuOperationBusMasterRead:
180 case EdkiiIoMmuOperationBusMasterWrite:
181 MapInfo->PlainTextAddress = BASE_4GB - 1;
182 AllocateType = AllocateMaxAddress;
183 //
184 // fall through
185 //
186 case EdkiiIoMmuOperationBusMasterRead64:
187 case EdkiiIoMmuOperationBusMasterWrite64:
188 //
189 // Allocate the implicit plaintext bounce buffer.
190 //
191 Status = gBS->AllocatePages (
192 AllocateType,
193 EfiBootServicesData,
194 MapInfo->NumberOfPages,
195 &MapInfo->PlainTextAddress
196 );
197 if (EFI_ERROR (Status)) {
198 goto FreeMapInfo;
199 }
200 break;
201
202 //
203 // For BusMasterCommonBuffer[64] operations, a to-be-plaintext buffer and a
204 // stash buffer (for in-place decryption) have been allocated already, with
205 // AllocateBuffer(). We only check whether the address of the to-be-plaintext
206 // buffer is low enough for the requested operation.
207 //
208 case EdkiiIoMmuOperationBusMasterCommonBuffer:
209 if ((MapInfo->CryptedAddress > BASE_4GB) ||
210 (EFI_PAGES_TO_SIZE (MapInfo->NumberOfPages) >
211 BASE_4GB - MapInfo->CryptedAddress)) {
212 //
213 // CommonBuffer operations cannot be remapped. If the common buffer is
214 // above 4GB, then it is not possible to generate a mapping, so return an
215 // error.
216 //
217 Status = EFI_UNSUPPORTED;
218 goto FreeMapInfo;
219 }
220 //
221 // fall through
222 //
223 case EdkiiIoMmuOperationBusMasterCommonBuffer64:
224 //
225 // The buffer at MapInfo->CryptedAddress comes from AllocateBuffer().
226 //
227 MapInfo->PlainTextAddress = MapInfo->CryptedAddress;
228 //
229 // Stash the crypted data.
230 //
231 CommonBufferHeader = (COMMON_BUFFER_HEADER *)(
232 (UINTN)MapInfo->CryptedAddress - EFI_PAGE_SIZE
233 );
234 ASSERT (CommonBufferHeader->Signature == COMMON_BUFFER_SIG);
235 CopyMem (
236 CommonBufferHeader->StashBuffer,
237 (VOID *)(UINTN)MapInfo->CryptedAddress,
238 MapInfo->NumberOfBytes
239 );
240 //
241 // Point "DecryptionSource" to the stash buffer so that we decrypt
242 // it to the original location, after the switch statement.
243 //
244 DecryptionSource = CommonBufferHeader->StashBuffer;
245 break;
246
247 default:
248 //
249 // Operation is invalid
250 //
251 Status = EFI_INVALID_PARAMETER;
252 goto FreeMapInfo;
253 }
254
255 //
256 // Clear the memory encryption mask on the plaintext buffer.
257 //
258 Status = MemEncryptSevClearPageEncMask (
259 0,
260 MapInfo->PlainTextAddress,
261 MapInfo->NumberOfPages,
262 TRUE
263 );
264 ASSERT_EFI_ERROR (Status);
265 if (EFI_ERROR (Status)) {
266 CpuDeadLoop ();
267 }
268
269 //
270 // If this is a read operation from the Bus Master's point of view,
271 // then copy the contents of the real buffer into the mapped buffer
272 // so the Bus Master can read the contents of the real buffer.
273 //
274 // For BusMasterCommonBuffer[64] operations, the CopyMem() below will decrypt
275 // the original data (from the stash buffer) back to the original location.
276 //
277 if (Operation == EdkiiIoMmuOperationBusMasterRead ||
278 Operation == EdkiiIoMmuOperationBusMasterRead64 ||
279 Operation == EdkiiIoMmuOperationBusMasterCommonBuffer ||
280 Operation == EdkiiIoMmuOperationBusMasterCommonBuffer64) {
281 CopyMem (
282 (VOID *) (UINTN) MapInfo->PlainTextAddress,
283 DecryptionSource,
284 MapInfo->NumberOfBytes
285 );
286 }
287
288 //
289 // Track all MAP_INFO structures.
290 //
291 InsertHeadList (&mMapInfos, &MapInfo->Link);
292 //
293 // Populate output parameters.
294 //
295 *DeviceAddress = MapInfo->PlainTextAddress;
296 *Mapping = MapInfo;
297
298 DEBUG ((
299 DEBUG_VERBOSE,
300 "%a: Mapping=0x%p Device(PlainText)=0x%Lx Crypted=0x%Lx Pages=0x%Lx\n",
301 __FUNCTION__,
302 MapInfo,
303 MapInfo->PlainTextAddress,
304 MapInfo->CryptedAddress,
305 (UINT64)MapInfo->NumberOfPages
306 ));
307
308 return EFI_SUCCESS;
309
310 FreeMapInfo:
311 FreePool (MapInfo);
312
313 Failed:
314 *NumberOfBytes = 0;
315 return Status;
316 }
317
318 /**
319 Completes the Map() operation and releases any corresponding resources.
320
321 This is an internal worker function that only extends the Map() API with
322 the MemoryMapLocked parameter.
323
324 @param This The protocol instance pointer.
325 @param Mapping The mapping value returned from Map().
326 @param MemoryMapLocked The function is executing on the stack of
327 gBS->ExitBootServices(); changes to the UEFI
328 memory map are forbidden.
329
330 @retval EFI_SUCCESS The range was unmapped.
331 @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned by
332 Map().
333 @retval EFI_DEVICE_ERROR The data was not committed to the target system
334 memory.
335 **/
336 STATIC
337 EFI_STATUS
338 EFIAPI
339 IoMmuUnmapWorker (
340 IN EDKII_IOMMU_PROTOCOL *This,
341 IN VOID *Mapping,
342 IN BOOLEAN MemoryMapLocked
343 )
344 {
345 MAP_INFO *MapInfo;
346 EFI_STATUS Status;
347 COMMON_BUFFER_HEADER *CommonBufferHeader;
348 VOID *EncryptionTarget;
349
350 DEBUG ((
351 DEBUG_VERBOSE,
352 "%a: Mapping=0x%p MemoryMapLocked=%d\n",
353 __FUNCTION__,
354 Mapping,
355 MemoryMapLocked
356 ));
357
358 if (Mapping == NULL) {
359 return EFI_INVALID_PARAMETER;
360 }
361
362 MapInfo = (MAP_INFO *)Mapping;
363
364 //
365 // set CommonBufferHeader to suppress incorrect compiler/analyzer warnings
366 //
367 CommonBufferHeader = NULL;
368
369 //
370 // For BusMasterWrite[64] operations and BusMasterCommonBuffer[64] operations
371 // we have to encrypt the results, ultimately to the original place (i.e.,
372 // "MapInfo->CryptedAddress").
373 //
374 // For BusMasterCommonBuffer[64] operations however, this encryption has to
375 // land in-place, so divert the encryption to the stash buffer first.
376 //
377 EncryptionTarget = (VOID *)(UINTN)MapInfo->CryptedAddress;
378
379 switch (MapInfo->Operation) {
380 case EdkiiIoMmuOperationBusMasterCommonBuffer:
381 case EdkiiIoMmuOperationBusMasterCommonBuffer64:
382 ASSERT (MapInfo->PlainTextAddress == MapInfo->CryptedAddress);
383
384 CommonBufferHeader = (COMMON_BUFFER_HEADER *)(
385 (UINTN)MapInfo->PlainTextAddress - EFI_PAGE_SIZE
386 );
387 ASSERT (CommonBufferHeader->Signature == COMMON_BUFFER_SIG);
388 EncryptionTarget = CommonBufferHeader->StashBuffer;
389 //
390 // fall through
391 //
392
393 case EdkiiIoMmuOperationBusMasterWrite:
394 case EdkiiIoMmuOperationBusMasterWrite64:
395 CopyMem (
396 EncryptionTarget,
397 (VOID *) (UINTN) MapInfo->PlainTextAddress,
398 MapInfo->NumberOfBytes
399 );
400 break;
401
402 default:
403 //
404 // nothing to encrypt after BusMasterRead[64] operations
405 //
406 break;
407 }
408
409 //
410 // Restore the memory encryption mask on the area we used to hold the
411 // plaintext.
412 //
413 Status = MemEncryptSevSetPageEncMask (
414 0,
415 MapInfo->PlainTextAddress,
416 MapInfo->NumberOfPages,
417 TRUE
418 );
419 ASSERT_EFI_ERROR (Status);
420 if (EFI_ERROR (Status)) {
421 CpuDeadLoop ();
422 }
423
424 //
425 // For BusMasterCommonBuffer[64] operations, copy the stashed data to the
426 // original (now encrypted) location.
427 //
428 // For all other operations, fill the late bounce buffer (which existed as
429 // plaintext at some point) with zeros, and then release it (unless the UEFI
430 // memory map is locked).
431 //
432 if (MapInfo->Operation == EdkiiIoMmuOperationBusMasterCommonBuffer ||
433 MapInfo->Operation == EdkiiIoMmuOperationBusMasterCommonBuffer64) {
434 CopyMem (
435 (VOID *)(UINTN)MapInfo->CryptedAddress,
436 CommonBufferHeader->StashBuffer,
437 MapInfo->NumberOfBytes
438 );
439 } else {
440 ZeroMem (
441 (VOID *)(UINTN)MapInfo->PlainTextAddress,
442 EFI_PAGES_TO_SIZE (MapInfo->NumberOfPages)
443 );
444 if (!MemoryMapLocked) {
445 gBS->FreePages (MapInfo->PlainTextAddress, MapInfo->NumberOfPages);
446 }
447 }
448
449 //
450 // Forget the MAP_INFO structure, then free it (unless the UEFI memory map is
451 // locked).
452 //
453 RemoveEntryList (&MapInfo->Link);
454 if (!MemoryMapLocked) {
455 FreePool (MapInfo);
456 }
457
458 return EFI_SUCCESS;
459 }
460
461 /**
462 Completes the Map() operation and releases any corresponding resources.
463
464 @param This The protocol instance pointer.
465 @param Mapping The mapping value returned from Map().
466
467 @retval EFI_SUCCESS The range was unmapped.
468 @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned by
469 Map().
470 @retval EFI_DEVICE_ERROR The data was not committed to the target system
471 memory.
472 **/
473 EFI_STATUS
474 EFIAPI
475 IoMmuUnmap (
476 IN EDKII_IOMMU_PROTOCOL *This,
477 IN VOID *Mapping
478 )
479 {
480 return IoMmuUnmapWorker (
481 This,
482 Mapping,
483 FALSE // MemoryMapLocked
484 );
485 }
486
487 /**
488 Allocates pages that are suitable for an OperationBusMasterCommonBuffer or
489 OperationBusMasterCommonBuffer64 mapping.
490
491 @param This The protocol instance pointer.
492 @param Type This parameter is not used and must be ignored.
493 @param MemoryType The type of memory to allocate,
494 EfiBootServicesData or EfiRuntimeServicesData.
495 @param Pages The number of pages to allocate.
496 @param HostAddress A pointer to store the base system memory
497 address of the allocated range.
498 @param Attributes The requested bit mask of attributes for the
499 allocated range.
500
501 @retval EFI_SUCCESS The requested memory pages were allocated.
502 @retval EFI_UNSUPPORTED Attributes is unsupported. The only legal
503 attribute bits are MEMORY_WRITE_COMBINE and
504 MEMORY_CACHED.
505 @retval EFI_INVALID_PARAMETER One or more parameters are invalid.
506 @retval EFI_OUT_OF_RESOURCES The memory pages could not be allocated.
507
508 **/
509 EFI_STATUS
510 EFIAPI
511 IoMmuAllocateBuffer (
512 IN EDKII_IOMMU_PROTOCOL *This,
513 IN EFI_ALLOCATE_TYPE Type,
514 IN EFI_MEMORY_TYPE MemoryType,
515 IN UINTN Pages,
516 IN OUT VOID **HostAddress,
517 IN UINT64 Attributes
518 )
519 {
520 EFI_STATUS Status;
521 EFI_PHYSICAL_ADDRESS PhysicalAddress;
522 VOID *StashBuffer;
523 UINTN CommonBufferPages;
524 COMMON_BUFFER_HEADER *CommonBufferHeader;
525
526 DEBUG ((
527 DEBUG_VERBOSE,
528 "%a: MemoryType=%u Pages=0x%Lx Attributes=0x%Lx\n",
529 __FUNCTION__,
530 (UINT32)MemoryType,
531 (UINT64)Pages,
532 Attributes
533 ));
534
535 //
536 // Validate Attributes
537 //
538 if ((Attributes & EDKII_IOMMU_ATTRIBUTE_INVALID_FOR_ALLOCATE_BUFFER) != 0) {
539 return EFI_UNSUPPORTED;
540 }
541
542 //
543 // Check for invalid inputs
544 //
545 if (HostAddress == NULL) {
546 return EFI_INVALID_PARAMETER;
547 }
548
549 //
550 // The only valid memory types are EfiBootServicesData and
551 // EfiRuntimeServicesData
552 //
553 if (MemoryType != EfiBootServicesData &&
554 MemoryType != EfiRuntimeServicesData) {
555 return EFI_INVALID_PARAMETER;
556 }
557
558 //
559 // We'll need a header page for the COMMON_BUFFER_HEADER structure.
560 //
561 if (Pages > MAX_UINTN - 1) {
562 return EFI_OUT_OF_RESOURCES;
563 }
564 CommonBufferPages = Pages + 1;
565
566 //
567 // Allocate the stash in EfiBootServicesData type memory.
568 //
569 // Map() will temporarily save encrypted data in the stash for
570 // BusMasterCommonBuffer[64] operations, so the data can be decrypted to the
571 // original location.
572 //
573 // Unmap() will temporarily save plaintext data in the stash for
574 // BusMasterCommonBuffer[64] operations, so the data can be encrypted to the
575 // original location.
576 //
577 // StashBuffer always resides in encrypted memory.
578 //
579 StashBuffer = AllocatePages (Pages);
580 if (StashBuffer == NULL) {
581 return EFI_OUT_OF_RESOURCES;
582 }
583
584 PhysicalAddress = (UINTN)-1;
585 if ((Attributes & EDKII_IOMMU_ATTRIBUTE_DUAL_ADDRESS_CYCLE) == 0) {
586 //
587 // Limit allocations to memory below 4GB
588 //
589 PhysicalAddress = SIZE_4GB - 1;
590 }
591 Status = gBS->AllocatePages (
592 AllocateMaxAddress,
593 MemoryType,
594 CommonBufferPages,
595 &PhysicalAddress
596 );
597 if (EFI_ERROR (Status)) {
598 goto FreeStashBuffer;
599 }
600
601 CommonBufferHeader = (VOID *)(UINTN)PhysicalAddress;
602 PhysicalAddress += EFI_PAGE_SIZE;
603
604 CommonBufferHeader->Signature = COMMON_BUFFER_SIG;
605 CommonBufferHeader->StashBuffer = StashBuffer;
606
607 *HostAddress = (VOID *)(UINTN)PhysicalAddress;
608
609 DEBUG ((
610 DEBUG_VERBOSE,
611 "%a: Host=0x%Lx Stash=0x%p\n",
612 __FUNCTION__,
613 PhysicalAddress,
614 StashBuffer
615 ));
616 return EFI_SUCCESS;
617
618 FreeStashBuffer:
619 FreePages (StashBuffer, Pages);
620 return Status;
621 }
622
623 /**
624 Frees memory that was allocated with AllocateBuffer().
625
626 @param This The protocol instance pointer.
627 @param Pages The number of pages to free.
628 @param HostAddress The base system memory address of the allocated
629 range.
630
631 @retval EFI_SUCCESS The requested memory pages were freed.
632 @retval EFI_INVALID_PARAMETER The memory range specified by HostAddress and
633 Pages was not allocated with AllocateBuffer().
634
635 **/
636 EFI_STATUS
637 EFIAPI
638 IoMmuFreeBuffer (
639 IN EDKII_IOMMU_PROTOCOL *This,
640 IN UINTN Pages,
641 IN VOID *HostAddress
642 )
643 {
644 UINTN CommonBufferPages;
645 COMMON_BUFFER_HEADER *CommonBufferHeader;
646
647 DEBUG ((
648 DEBUG_VERBOSE,
649 "%a: Host=0x%p Pages=0x%Lx\n",
650 __FUNCTION__,
651 HostAddress,
652 (UINT64)Pages
653 ));
654
655 CommonBufferPages = Pages + 1;
656 CommonBufferHeader = (COMMON_BUFFER_HEADER *)(
657 (UINTN)HostAddress - EFI_PAGE_SIZE
658 );
659
660 //
661 // Check the signature.
662 //
663 ASSERT (CommonBufferHeader->Signature == COMMON_BUFFER_SIG);
664 if (CommonBufferHeader->Signature != COMMON_BUFFER_SIG) {
665 return EFI_INVALID_PARAMETER;
666 }
667
668 //
669 // Free the stash buffer. This buffer was always encrypted, so no need to
670 // zero it.
671 //
672 FreePages (CommonBufferHeader->StashBuffer, Pages);
673
674 //
675 // Release the common buffer itself. Unmap() has re-encrypted it in-place, so
676 // no need to zero it.
677 //
678 return gBS->FreePages ((UINTN)CommonBufferHeader, CommonBufferPages);
679 }
680
681
682 /**
683 Set IOMMU attribute for a system memory.
684
685 If the IOMMU protocol exists, the system memory cannot be used
686 for DMA by default.
687
688 When a device requests a DMA access for a system memory,
689 the device driver need use SetAttribute() to update the IOMMU
690 attribute to request DMA access (read and/or write).
691
692 The DeviceHandle is used to identify which device submits the request.
693 The IOMMU implementation need translate the device path to an IOMMU device
694 ID, and set IOMMU hardware register accordingly.
695 1) DeviceHandle can be a standard PCI device.
696 The memory for BusMasterRead need set EDKII_IOMMU_ACCESS_READ.
697 The memory for BusMasterWrite need set EDKII_IOMMU_ACCESS_WRITE.
698 The memory for BusMasterCommonBuffer need set
699 EDKII_IOMMU_ACCESS_READ|EDKII_IOMMU_ACCESS_WRITE.
700 After the memory is used, the memory need set 0 to keep it being
701 protected.
702 2) DeviceHandle can be an ACPI device (ISA, I2C, SPI, etc).
703 The memory for DMA access need set EDKII_IOMMU_ACCESS_READ and/or
704 EDKII_IOMMU_ACCESS_WRITE.
705
706 @param[in] This The protocol instance pointer.
707 @param[in] DeviceHandle The device who initiates the DMA access
708 request.
709 @param[in] Mapping The mapping value returned from Map().
710 @param[in] IoMmuAccess The IOMMU access.
711
712 @retval EFI_SUCCESS The IoMmuAccess is set for the memory range
713 specified by DeviceAddress and Length.
714 @retval EFI_INVALID_PARAMETER DeviceHandle is an invalid handle.
715 @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned by
716 Map().
717 @retval EFI_INVALID_PARAMETER IoMmuAccess specified an illegal combination
718 of access.
719 @retval EFI_UNSUPPORTED DeviceHandle is unknown by the IOMMU.
720 @retval EFI_UNSUPPORTED The bit mask of IoMmuAccess is not supported
721 by the IOMMU.
722 @retval EFI_UNSUPPORTED The IOMMU does not support the memory range
723 specified by Mapping.
724 @retval EFI_OUT_OF_RESOURCES There are not enough resources available to
725 modify the IOMMU access.
726 @retval EFI_DEVICE_ERROR The IOMMU device reported an error while
727 attempting the operation.
728
729 **/
730 EFI_STATUS
731 EFIAPI
732 IoMmuSetAttribute (
733 IN EDKII_IOMMU_PROTOCOL *This,
734 IN EFI_HANDLE DeviceHandle,
735 IN VOID *Mapping,
736 IN UINT64 IoMmuAccess
737 )
738 {
739 return EFI_UNSUPPORTED;
740 }
741
742 EDKII_IOMMU_PROTOCOL mAmdSev = {
743 EDKII_IOMMU_PROTOCOL_REVISION,
744 IoMmuSetAttribute,
745 IoMmuMap,
746 IoMmuUnmap,
747 IoMmuAllocateBuffer,
748 IoMmuFreeBuffer,
749 };
750
751 /**
752 Notification function that is queued when gBS->ExitBootServices() signals the
753 EFI_EVENT_GROUP_EXIT_BOOT_SERVICES event group. This function signals another
754 event, received as Context, and returns.
755
756 Signaling an event in this context is safe. The UEFI spec allows
757 gBS->SignalEvent() to return EFI_SUCCESS only; EFI_OUT_OF_RESOURCES is not
758 listed, hence memory is not allocated. The edk2 implementation also does not
759 release memory (and we only have to care about the edk2 implementation
760 because EDKII_IOMMU_PROTOCOL is edk2-specific anyway).
761
762 @param[in] Event Event whose notification function is being invoked.
763 Event is permitted to request the queueing of this
764 function at TPL_CALLBACK or TPL_NOTIFY task
765 priority level.
766
767 @param[in] EventToSignal Identifies the EFI_EVENT to signal. EventToSignal
768 is permitted to request the queueing of its
769 notification function only at TPL_CALLBACK level.
770 **/
771 STATIC
772 VOID
773 EFIAPI
774 AmdSevExitBoot (
775 IN EFI_EVENT Event,
776 IN VOID *EventToSignal
777 )
778 {
779 //
780 // (1) The NotifyFunctions of all the events in
781 // EFI_EVENT_GROUP_EXIT_BOOT_SERVICES will have been queued before
782 // AmdSevExitBoot() is entered.
783 //
784 // (2) AmdSevExitBoot() is executing minimally at TPL_CALLBACK.
785 //
786 // (3) AmdSevExitBoot() has been queued in unspecified order relative to the
787 // NotifyFunctions of all the other events in
788 // EFI_EVENT_GROUP_EXIT_BOOT_SERVICES whose NotifyTpl is the same as
789 // Event's.
790 //
791 // Consequences:
792 //
793 // - If Event's NotifyTpl is TPL_CALLBACK, then some other NotifyFunctions
794 // queued at TPL_CALLBACK may be invoked after AmdSevExitBoot() returns.
795 //
796 // - If Event's NotifyTpl is TPL_NOTIFY, then some other NotifyFunctions
797 // queued at TPL_NOTIFY may be invoked after AmdSevExitBoot() returns; plus
798 // *all* NotifyFunctions queued at TPL_CALLBACK will be invoked strictly
799 // after all NotifyFunctions queued at TPL_NOTIFY, including
800 // AmdSevExitBoot(), have been invoked.
801 //
802 // - By signaling EventToSignal here, whose NotifyTpl is TPL_CALLBACK, we
803 // queue EventToSignal's NotifyFunction after the NotifyFunctions of *all*
804 // events in EFI_EVENT_GROUP_EXIT_BOOT_SERVICES.
805 //
806 DEBUG ((DEBUG_VERBOSE, "%a\n", __FUNCTION__));
807 gBS->SignalEvent (EventToSignal);
808 }
809
810 /**
811 Notification function that is queued after the notification functions of all
812 events in the EFI_EVENT_GROUP_EXIT_BOOT_SERVICES event group. The same memory
813 map restrictions apply.
814
815 This function unmaps all currently existing IOMMU mappings.
816
817 @param[in] Event Event whose notification function is being invoked. Event
818 is permitted to request the queueing of this function
819 only at TPL_CALLBACK task priority level.
820
821 @param[in] Context Ignored.
822 **/
823 STATIC
824 VOID
825 EFIAPI
826 AmdSevUnmapAllMappings (
827 IN EFI_EVENT Event,
828 IN VOID *Context
829 )
830 {
831 LIST_ENTRY *Node;
832 LIST_ENTRY *NextNode;
833 MAP_INFO *MapInfo;
834
835 DEBUG ((DEBUG_VERBOSE, "%a\n", __FUNCTION__));
836
837 //
838 // All drivers that had set up IOMMU mappings have halted their respective
839 // controllers by now; tear down the mappings.
840 //
841 for (Node = GetFirstNode (&mMapInfos); Node != &mMapInfos; Node = NextNode) {
842 NextNode = GetNextNode (&mMapInfos, Node);
843 MapInfo = CR (Node, MAP_INFO, Link, MAP_INFO_SIG);
844 IoMmuUnmapWorker (
845 &mAmdSev, // This
846 MapInfo, // Mapping
847 TRUE // MemoryMapLocked
848 );
849 }
850 }
851
852 /**
853 Initialize Iommu Protocol.
854
855 **/
856 EFI_STATUS
857 EFIAPI
858 AmdSevInstallIoMmuProtocol (
859 VOID
860 )
861 {
862 EFI_STATUS Status;
863 EFI_EVENT UnmapAllMappingsEvent;
864 EFI_EVENT ExitBootEvent;
865 EFI_HANDLE Handle;
866
867 //
868 // Create the "late" event whose notification function will tear down all
869 // left-over IOMMU mappings.
870 //
871 Status = gBS->CreateEvent (
872 EVT_NOTIFY_SIGNAL, // Type
873 TPL_CALLBACK, // NotifyTpl
874 AmdSevUnmapAllMappings, // NotifyFunction
875 NULL, // NotifyContext
876 &UnmapAllMappingsEvent // Event
877 );
878 if (EFI_ERROR (Status)) {
879 return Status;
880 }
881
882 //
883 // Create the event whose notification function will be queued by
884 // gBS->ExitBootServices() and will signal the event created above.
885 //
886 Status = gBS->CreateEvent (
887 EVT_SIGNAL_EXIT_BOOT_SERVICES, // Type
888 TPL_CALLBACK, // NotifyTpl
889 AmdSevExitBoot, // NotifyFunction
890 UnmapAllMappingsEvent, // NotifyContext
891 &ExitBootEvent // Event
892 );
893 if (EFI_ERROR (Status)) {
894 goto CloseUnmapAllMappingsEvent;
895 }
896
897 Handle = NULL;
898 Status = gBS->InstallMultipleProtocolInterfaces (
899 &Handle,
900 &gEdkiiIoMmuProtocolGuid, &mAmdSev,
901 NULL
902 );
903 if (EFI_ERROR (Status)) {
904 goto CloseExitBootEvent;
905 }
906
907 return EFI_SUCCESS;
908
909 CloseExitBootEvent:
910 gBS->CloseEvent (ExitBootEvent);
911
912 CloseUnmapAllMappingsEvent:
913 gBS->CloseEvent (UnmapAllMappingsEvent);
914
915 return Status;
916 }