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