CcIoMmu.c 30 KB

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