Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2182 lines
58 KiB

  1. /*++
  2. Copyright (c) 1989 Microsoft Corporation
  3. Module Name:
  4. ixhwsup.c
  5. Abstract:
  6. This module contains the IoXxx routines for the NT I/O system that
  7. are hardware dependent. Were these routines not hardware dependent,
  8. they would reside in the iosubs.c module.
  9. Author:
  10. Darryl E. Havens (darrylh) 11-Apr-1990
  11. Environment:
  12. Kernel mode
  13. Revision History:
  14. --*/
  15. #include "halp.h"
  16. #include "halpnpp.h"
  17. #include "eisa.h"
  18. #define COMMON_BUFFER_ALLOCATION_ATTEMPTS 5
  19. #ifdef ACPI_HAL
  20. //
  21. // Interface to the F-type control methods
  22. //
  23. extern ISA_FTYPE_DMA_INTERFACE HalpFDMAInterface;
  24. #endif
  25. #define HAL_WCB_DRIVER_BUFFER 1
  26. typedef struct _HAL_WAIT_CONTEXT_BLOCK {
  27. ULONG Flags;
  28. PMDL Mdl;
  29. PMDL DmaMdl;
  30. PVOID MapRegisterBase;
  31. PVOID CurrentVa;
  32. ULONG Length;
  33. ULONG NumberOfMapRegisters;
  34. union {
  35. struct {
  36. WAIT_CONTEXT_BLOCK Wcb;
  37. PDRIVER_LIST_CONTROL DriverExecutionRoutine;
  38. PVOID DriverContext;
  39. PIRP CurrentIrp;
  40. PADAPTER_OBJECT AdapterObject;
  41. BOOLEAN WriteToDevice;
  42. };
  43. SCATTER_GATHER_LIST ScatterGather;
  44. };
  45. } HAL_WAIT_CONTEXT_BLOCK, *PHAL_WAIT_CONTEXT_BLOCK;
  46. //
  47. // Due to Intel chipset bugs, we can only do
  48. // certain processor power management functions
  49. // when there is no DMA traffic. So we need to
  50. // know. The nature of the bug (in the PIIX4)
  51. // chip is such that we really only care about
  52. // transactions from the IDE controller in PIIX4.
  53. // And it uses the scatter/gather functions.
  54. //
  55. // Only the UP acpi hals require this value to be
  56. // tracked.
  57. //
  58. LONG HalpOutstandingScatterGatherCount = 0;
  59. extern KSPIN_LOCK HalpDmaAdapterListLock;
  60. extern LIST_ENTRY HalpDmaAdapterList;
  61. HALP_MOVE_MEMORY_ROUTINE HalpMoveMemory = RtlMoveMemory;
  62. #if defined(TRACK_SCATTER_GATHER_COUNT)
  63. #define INCREMENT_SCATTER_GATHER_COUNT() \
  64. InterlockedIncrement(&HalpOutstandingScatterGatherCount)
  65. #define DECREMENT_SCATTER_GATHER_COUNT() \
  66. InterlockedDecrement(&HalpOutstandingScatterGatherCount)
  67. #else
  68. #define INCREMENT_SCATTER_GATHER_COUNT()
  69. #define DECREMENT_SCATTER_GATHER_COUNT()
  70. #endif
  71. VOID
  72. HalpGrowMapBufferWorker(
  73. IN PVOID Context
  74. );
  75. IO_ALLOCATION_ACTION
  76. HalpAllocateAdapterCallback (
  77. IN struct _DEVICE_OBJECT *DeviceObject,
  78. IN struct _IRP *Irp,
  79. IN PVOID MapRegisterBase,
  80. IN PVOID Context
  81. );
  82. static KSPIN_LOCK HalpReservedPageLock;
  83. static PVOID HalpReservedPages = NULL;
  84. static PFN_NUMBER HalpReservedPageMdl[(sizeof(MDL)/sizeof(PFN_NUMBER)) + 2];
  85. VOID
  86. HalpInitReservedPages(
  87. VOID
  88. )
  89. /*++
  90. Routine Description:
  91. Initalize the data structures necessary to continue DMA
  92. during low memory conditions
  93. Aruments:
  94. None
  95. Reurn Value:
  96. None
  97. --*/
  98. {
  99. PMDL Mdl;
  100. HalpReservedPages = MmAllocateMappingAddress(PAGE_SIZE, HAL_POOL_TAG);
  101. ASSERT(HalpReservedPages);
  102. Mdl = (PMDL)&HalpReservedPageMdl;
  103. MmInitializeMdl(Mdl, NULL, PAGE_SIZE);
  104. Mdl->MdlFlags |= MDL_PAGES_LOCKED;
  105. KeInitializeSpinLock(&HalpReservedPageLock);
  106. }
  107. VOID
  108. HalpCopyBufferMapSafe(
  109. IN PMDL Mdl,
  110. IN PTRANSLATION_ENTRY TranslationEntry,
  111. IN PVOID CurrentVa,
  112. IN ULONG Length,
  113. IN BOOLEAN WriteToDevice
  114. )
  115. /*++
  116. Routine Description:
  117. This routine copies the specific data between an unmapped user buffer
  118. and the map register buffer. We will map and unmap each page of the
  119. transfer using our emergency reserved mapping
  120. Arguments:
  121. Mdl - Pointer to the MDL that describes the pages of memory that are
  122. being read or written.
  123. TranslationEntry - The address of the base map register that has been
  124. allocated to the device driver for use in mapping
  125. the transfer.
  126. CurrentVa - Current virtual address in the buffer described by the MDL
  127. that the transfer is being done to or from.
  128. Length - The length of the transfer. This determines the number of map
  129. registers that need to be written to map the transfer.
  130. WriteToDevice - Boolean value that indicates whether this is a write
  131. to the device from memory (TRUE), or vice versa.
  132. Return Value:
  133. None
  134. --*/
  135. {
  136. PCCHAR bufferAddress;
  137. PCCHAR mapAddress;
  138. ULONG bytesLeft;
  139. ULONG bytesThisCopy;
  140. ULONG bufferPageOffset;
  141. PTRANSLATION_ENTRY translationEntry;
  142. KIRQL Irql;
  143. PMDL ReserveMdl;
  144. MEMORY_CACHING_TYPE MCFlavor;
  145. PPFN_NUMBER SrcPFrame;
  146. PPFN_NUMBER ReservePFrame;
  147. //
  148. // Synchronize access to our reserve page data structures
  149. //
  150. KeAcquireSpinLock(&HalpReservedPageLock, &Irql);
  151. //
  152. // Get local copies of Length and TranslationEntry as they will be
  153. // decremented/incremented respectively
  154. //
  155. bytesLeft = Length;
  156. translationEntry = TranslationEntry;
  157. //
  158. // Find the PFN in our caller's MDL that describes the first page in
  159. // physical memory that we need to access
  160. //
  161. SrcPFrame = MmGetMdlPfnArray(Mdl);
  162. SrcPFrame += ((ULONG_PTR)CurrentVa - (ULONG_PTR)MmGetMdlBaseVa(Mdl)) >>
  163. PAGE_SHIFT;
  164. //
  165. // Initialize our reserve MDL's StartVa and ByteOffset
  166. //
  167. ReserveMdl = (PMDL)&HalpReservedPageMdl;
  168. ReservePFrame = MmGetMdlPfnArray(ReserveMdl);
  169. ReserveMdl->StartVa = (PVOID)PAGE_ALIGN(CurrentVa);
  170. ReserveMdl->ByteOffset = BYTE_OFFSET(CurrentVa);
  171. ReserveMdl->ByteCount = PAGE_SIZE - ReserveMdl->ByteOffset;
  172. //
  173. // Copy the data one translation entry at a time
  174. //
  175. while (bytesLeft > 0) {
  176. //
  177. // Copy current source PFN into our reserve MDL
  178. //
  179. *ReservePFrame = *SrcPFrame;
  180. //
  181. // Enumerate thru cache flavors until we get our reserve mapping
  182. //
  183. bufferAddress = NULL;
  184. for (MCFlavor = MmNonCached;
  185. MCFlavor < MmMaximumCacheType;
  186. MCFlavor++) {
  187. bufferAddress =
  188. MmMapLockedPagesWithReservedMapping(HalpReservedPages,
  189. HAL_POOL_TAG,
  190. ReserveMdl,
  191. MCFlavor);
  192. if (bufferAddress != NULL) {
  193. break;
  194. }
  195. }
  196. //
  197. // Could not establish a reserve mapping, we're totally screwed!
  198. //
  199. if (bufferAddress == NULL) {
  200. KeBugCheckEx(HAL_MEMORY_ALLOCATION,
  201. PAGE_SIZE,
  202. 0xEF02,
  203. (ULONG_PTR)__FILE__,
  204. __LINE__
  205. );
  206. }
  207. //
  208. // Find the buffer offset within the page
  209. //
  210. // N.B. bufferPageOffset can only be non-zero on the first iteration
  211. //
  212. bufferPageOffset = BYTE_OFFSET(bufferAddress);
  213. //
  214. // Copy from bufferAddress up to the next page boundary...
  215. //
  216. bytesThisCopy = PAGE_SIZE - bufferPageOffset;
  217. //
  218. // ...but no more than bytesLeft
  219. //
  220. if (bytesThisCopy > bytesLeft) {
  221. bytesThisCopy = bytesLeft;
  222. }
  223. //
  224. // Calculate the base address of this translation entry and the
  225. // offset into it.
  226. //
  227. mapAddress = (PCCHAR) translationEntry->VirtualAddress +
  228. bufferPageOffset;
  229. //
  230. // Copy up to one page
  231. //
  232. if (WriteToDevice) {
  233. HalpMoveMemory( mapAddress, bufferAddress, bytesThisCopy );
  234. } else {
  235. RtlCopyMemory( bufferAddress, mapAddress, bytesThisCopy );
  236. }
  237. //
  238. // Update locals and process the next translation entry.
  239. //
  240. bytesLeft -= bytesThisCopy;
  241. translationEntry += 1;
  242. MmUnmapReservedMapping(HalpReservedPages, HAL_POOL_TAG, ReserveMdl);
  243. SrcPFrame++;
  244. ReserveMdl->ByteOffset = 0;
  245. (PCCHAR)ReserveMdl->StartVa += PAGE_SIZE;
  246. ReserveMdl->ByteCount = (PAGE_SIZE > bytesLeft) ? bytesLeft: PAGE_SIZE;
  247. }
  248. KeReleaseSpinLock(&HalpReservedPageLock, Irql);
  249. }
  250. VOID
  251. HalpCopyBufferMap(
  252. IN PMDL Mdl,
  253. IN PTRANSLATION_ENTRY TranslationEntry,
  254. IN PVOID CurrentVa,
  255. IN ULONG Length,
  256. IN BOOLEAN WriteToDevice
  257. )
  258. /*++
  259. Routine Description:
  260. This routine copies the specific data between the user's buffer and the
  261. map register buffer. First a the user buffer is mapped if necessary, then
  262. the data is copied. Finally the user buffer will be unmapped if
  263. necessary.
  264. Arguments:
  265. Mdl - Pointer to the MDL that describes the pages of memory that are
  266. being read or written.
  267. TranslationEntry - The address of the base map register that has been
  268. allocated to the device driver for use in mapping the transfer.
  269. CurrentVa - Current virtual address in the buffer described by the MDL
  270. that the transfer is being done to or from.
  271. Length - The length of the transfer. This determines the number of map
  272. registers that need to be written to map the transfer.
  273. WriteToDevice - Boolean value that indicates whether this is a write
  274. to the device from memory (TRUE), or vice versa.
  275. Return Value:
  276. None.
  277. --*/
  278. {
  279. PCCHAR bufferAddress;
  280. PCCHAR mapAddress;
  281. ULONG bytesLeft;
  282. ULONG bytesThisCopy;
  283. ULONG bufferPageOffset;
  284. PTRANSLATION_ENTRY translationEntry;
  285. NTSTATUS Status;
  286. //
  287. // Get the system address of the MDL, if we run out of PTEs try safe
  288. // method
  289. //
  290. bufferAddress = MmGetSystemAddressForMdlSafe(Mdl, HighPagePriority);
  291. if (bufferAddress == NULL) {
  292. //
  293. // Our caller's buffer is unmapped, and the memory manager is out
  294. // of PTEs, try to use reserve page method
  295. //
  296. if (HalpReservedPages != NULL) {
  297. HalpCopyBufferMapSafe(Mdl,
  298. TranslationEntry,
  299. CurrentVa,
  300. Length,
  301. WriteToDevice);
  302. return;
  303. }
  304. //
  305. // The DMA transfer cannot be completed, the system is now unstable
  306. //
  307. KeBugCheckEx(HAL_MEMORY_ALLOCATION,
  308. PAGE_SIZE,
  309. 0xEF01,
  310. (ULONG_PTR)__FILE__,
  311. __LINE__
  312. );
  313. }
  314. //
  315. // Calculate the actual start of the buffer based on the system VA and
  316. // the current VA.
  317. //
  318. bufferAddress += (PCCHAR) CurrentVa - (PCCHAR) MmGetMdlVirtualAddress(Mdl);
  319. //
  320. // Get local copies of Length and TranslationEntry as they will be
  321. // decremented/incremented respectively.
  322. //
  323. bytesLeft = Length;
  324. translationEntry = TranslationEntry;
  325. //
  326. // Copy the data one translation entry at a time.
  327. //
  328. while (bytesLeft > 0) {
  329. //
  330. // Find the buffer offset within the page.
  331. //
  332. // N.B. bufferPageOffset can only be non-zero on the first iteration.
  333. //
  334. bufferPageOffset = BYTE_OFFSET(bufferAddress);
  335. //
  336. // Copy from bufferAddress up to the next page boundary...
  337. //
  338. bytesThisCopy = PAGE_SIZE - bufferPageOffset;
  339. //
  340. // ...but no more than bytesLeft.
  341. //
  342. if (bytesThisCopy > bytesLeft) {
  343. bytesThisCopy = bytesLeft;
  344. }
  345. //
  346. // Calculate the base address of this translation entry and the
  347. // offset into it.
  348. //
  349. mapAddress = (PCCHAR) translationEntry->VirtualAddress +
  350. bufferPageOffset;
  351. //
  352. // Copy up to one page.
  353. //
  354. if (WriteToDevice) {
  355. HalpMoveMemory( mapAddress, bufferAddress, bytesThisCopy );
  356. } else {
  357. RtlCopyMemory( bufferAddress, mapAddress, bytesThisCopy );
  358. }
  359. //
  360. // Update locals and process the next translation entry.
  361. //
  362. bytesLeft -= bytesThisCopy;
  363. bufferAddress += bytesThisCopy;
  364. translationEntry += 1;
  365. }
  366. }
  367. PVOID
  368. HalAllocateCommonBuffer(
  369. IN PADAPTER_OBJECT AdapterObject,
  370. IN ULONG Length,
  371. OUT PPHYSICAL_ADDRESS LogicalAddress,
  372. IN BOOLEAN CacheEnabled
  373. )
  374. /*++
  375. Routine Description:
  376. This function allocates the memory for a common buffer and maps it so that
  377. it can be accessed by a master device and the CPU.
  378. Arguments:
  379. AdapterObject - Supplies a pointer to the adapter object used by this
  380. device.
  381. Length - Supplies the length of the common buffer to be allocated.
  382. LogicalAddress - Returns the logical address of the common buffer.
  383. CacheEnable - Indicates whether the memeory is cached or not.
  384. Return Value:
  385. Returns the virtual address of the common buffer. If the buffer cannot be
  386. allocated then NULL is returned.
  387. --*/
  388. {
  389. PSINGLE_LIST_ENTRY virtualAddress;
  390. PHYSICAL_ADDRESS minPhysicalAddress;
  391. PHYSICAL_ADDRESS maxPhysicalAddress;
  392. PHYSICAL_ADDRESS logicalAddress;
  393. PHYSICAL_ADDRESS boundaryPhysicalAddress;
  394. ULONGLONG boundaryMask;
  395. UNREFERENCED_PARAMETER( CacheEnabled );
  396. //
  397. // Determine the maximum physical address that this adapter can handle.
  398. //
  399. minPhysicalAddress.QuadPart = 0;
  400. maxPhysicalAddress = HalpGetAdapterMaximumPhysicalAddress( AdapterObject );
  401. //
  402. // Determine the boundary mask for this adapter.
  403. //
  404. if (HalpBusType != MACHINE_TYPE_ISA ||
  405. AdapterObject->MasterDevice != FALSE) {
  406. //
  407. // This is not an ISA system. The buffer must not cross a 4GB boundary.
  408. // It is predicted that most adapters are incapable of reliably
  409. // transferring across a 4GB boundary.
  410. //
  411. boundaryPhysicalAddress.QuadPart = 0x0000000100000000;
  412. boundaryMask = 0xFFFFFFFF00000000;
  413. } else {
  414. //
  415. // This is an ISA system the common buffer cannot cross a 64K boundary.
  416. //
  417. boundaryPhysicalAddress.QuadPart = 0x10000;
  418. boundaryMask = 0xFFFFFFFFFFFF0000;
  419. }
  420. //
  421. // Allocate a contiguous buffer.
  422. //
  423. virtualAddress = MmAllocateContiguousMemorySpecifyCache(
  424. Length,
  425. minPhysicalAddress,
  426. maxPhysicalAddress,
  427. boundaryPhysicalAddress,
  428. MmCached );
  429. if (virtualAddress != NULL) {
  430. //
  431. // Got a buffer, get the physical/logical address and see if it
  432. // meets our conditions.
  433. //
  434. logicalAddress = MmGetPhysicalAddress( virtualAddress );
  435. #if DBG
  436. ASSERT (((logicalAddress.QuadPart ^
  437. (logicalAddress.QuadPart + Length - 1)) & boundaryMask) == 0);
  438. #endif
  439. *LogicalAddress = logicalAddress;
  440. }
  441. return virtualAddress;
  442. }
  443. BOOLEAN
  444. HalFlushCommonBuffer(
  445. IN PADAPTER_OBJECT AdapterObject,
  446. IN ULONG Length,
  447. IN PHYSICAL_ADDRESS LogicalAddress,
  448. IN PVOID VirtualAddress
  449. )
  450. /*++
  451. Routine Description:
  452. This function is called to flush any hardware adapter buffers when the
  453. driver needs to read data written by an I/O master device to a common
  454. buffer.
  455. Arguments:
  456. AdapterObject - Supplies a pointer to the adapter object used by this
  457. device.
  458. Length - Supplies the length of the common buffer. This should be the same
  459. value used for the allocation of the buffer.
  460. LogicalAddress - Supplies the logical address of the common buffer. This
  461. must be the same value return by HalAllocateCommonBuffer.
  462. VirtualAddress - Supplies the virtual address of the common buffer. This
  463. must be the same value return by HalAllocateCommonBuffer.
  464. Return Value:
  465. Returns TRUE if no errors were detected. Otherwise, FALSE is returned.
  466. --*/
  467. {
  468. UNREFERENCED_PARAMETER( AdapterObject );
  469. UNREFERENCED_PARAMETER( Length );
  470. UNREFERENCED_PARAMETER( LogicalAddress );
  471. UNREFERENCED_PARAMETER( VirtualAddress );
  472. return(TRUE);
  473. }
  474. VOID
  475. HalFreeCommonBuffer(
  476. IN PADAPTER_OBJECT AdapterObject,
  477. IN ULONG Length,
  478. IN PHYSICAL_ADDRESS LogicalAddress,
  479. IN PVOID VirtualAddress,
  480. IN BOOLEAN CacheEnabled
  481. )
  482. /*++
  483. Routine Description:
  484. This function frees a common buffer and all of the resources it uses.
  485. Arguments:
  486. AdapterObject - Supplies a pointer to the adapter object used by this
  487. device.
  488. Length - Supplies the length of the common buffer. This should be the same
  489. value used for the allocation of the buffer.
  490. LogicalAddress - Supplies the logical address of the common buffer. This
  491. must be the same value returned by HalAllocateCommonBuffer.
  492. VirtualAddress - Supplies the virtual address of the common buffer. This
  493. must be the same value returned by HalAllocateCommonBuffer.
  494. CacheEnable - Indicates whether the memory is cached or not.
  495. Return Value:
  496. None
  497. --*/
  498. {
  499. UNREFERENCED_PARAMETER( AdapterObject );
  500. UNREFERENCED_PARAMETER( Length );
  501. UNREFERENCED_PARAMETER( LogicalAddress );
  502. UNREFERENCED_PARAMETER( CacheEnabled );
  503. MmFreeContiguousMemory (VirtualAddress);
  504. }
  505. NTSTATUS
  506. HalCalculateScatterGatherListSize(
  507. IN PADAPTER_OBJECT AdapterObject,
  508. IN OPTIONAL PMDL Mdl,
  509. IN PVOID CurrentVa,
  510. IN ULONG Length,
  511. OUT PULONG ScatterGatherListSize,
  512. OUT OPTIONAL PULONG pNumberOfMapRegisters
  513. )
  514. /*++
  515. Routine Description:
  516. This routine calculates the size of the scatter/gather list that
  517. needs to be allocated for a given virtual address range or MDL.
  518. Arguments:
  519. AdapterObject - Pointer to the adapter control object to allocate to the
  520. driver.
  521. Mdl - Pointer to the MDL that describes the pages of memory that are being
  522. read or written.
  523. CurrentVa - Current virtual address in the buffer described by the MDL
  524. that the transfer is being done to or from.
  525. Length - Supplies the length of the transfer.
  526. Return Value:
  527. Returns STATUS_SUCCESS unless too many map registers are requested or
  528. memory for the scatter/gather list could not be allocated.
  529. Notes:
  530. --*/
  531. {
  532. PHAL_WAIT_CONTEXT_BLOCK WaitBlock;
  533. PMDL TempMdl;
  534. PSCATTER_GATHER_LIST ScatterGather;
  535. PSCATTER_GATHER_ELEMENT Element;
  536. ULONG NumberOfMapRegisters;
  537. ULONG ContextSize;
  538. ULONG TransferLength;
  539. ULONG MdlLength;
  540. PUCHAR MdlVa;
  541. NTSTATUS Status;
  542. PULONG PageFrame;
  543. ULONG PageOffset;
  544. if (ARGUMENT_PRESENT(Mdl)) {
  545. MdlVa = MmGetMdlVirtualAddress(Mdl);
  546. //
  547. // Calculate the number of required map registers.
  548. //
  549. TempMdl = Mdl;
  550. TransferLength =
  551. TempMdl->ByteCount - (ULONG)((PUCHAR) CurrentVa - MdlVa);
  552. MdlLength = TransferLength;
  553. PageOffset = BYTE_OFFSET(CurrentVa);
  554. NumberOfMapRegisters = 0;
  555. //
  556. // The virtual address should fit in the first MDL.
  557. //
  558. ASSERT((ULONG)((PUCHAR)CurrentVa - MdlVa) <= TempMdl->ByteCount);
  559. //
  560. // Loop through the any chained MDLs accumulating the the required
  561. // number of map registers.
  562. //
  563. while (TransferLength < Length && TempMdl->Next != NULL) {
  564. NumberOfMapRegisters += (PageOffset + MdlLength + PAGE_SIZE - 1) >>
  565. PAGE_SHIFT;
  566. TempMdl = TempMdl->Next;
  567. PageOffset = TempMdl->ByteOffset;
  568. MdlLength = TempMdl->ByteCount;
  569. TransferLength += MdlLength;
  570. }
  571. if ((TransferLength + PAGE_SIZE) < (Length + PageOffset )) {
  572. ASSERT(TransferLength >= Length);
  573. return(STATUS_BUFFER_TOO_SMALL);
  574. }
  575. //
  576. // Calculate the last number of map registers based on the requested
  577. // length not the length of the last MDL.
  578. //
  579. ASSERT( TransferLength <= MdlLength + Length );
  580. NumberOfMapRegisters += (PageOffset + Length + MdlLength - TransferLength +
  581. PAGE_SIZE - 1) >> PAGE_SHIFT;
  582. if (NumberOfMapRegisters > AdapterObject->MapRegistersPerChannel) {
  583. return(STATUS_INSUFFICIENT_RESOURCES);
  584. }
  585. } else {
  586. //
  587. // Determine the number of pages required to map the buffer described
  588. // by CurrentVa and Length.
  589. //
  590. NumberOfMapRegisters = ADDRESS_AND_SIZE_TO_SPAN_PAGES(CurrentVa, Length);
  591. }
  592. //
  593. // Calculate how much memory is required for the context structure.
  594. //
  595. ContextSize = NumberOfMapRegisters * sizeof( SCATTER_GATHER_ELEMENT ) +
  596. sizeof( SCATTER_GATHER_LIST );
  597. //
  598. // If the adapter does not need map registers then most of this code
  599. // can be bypassed. Just build the scatter/gather list and give it
  600. // to the caller.
  601. //
  602. if (AdapterObject->NeedsMapRegisters) {
  603. ContextSize += FIELD_OFFSET( HAL_WAIT_CONTEXT_BLOCK, ScatterGather );
  604. if (ContextSize < sizeof( HAL_WAIT_CONTEXT_BLOCK )) {
  605. ContextSize = sizeof( HAL_WAIT_CONTEXT_BLOCK );
  606. }
  607. }
  608. //
  609. // Return the list size.
  610. //
  611. *ScatterGatherListSize = ContextSize;
  612. if (pNumberOfMapRegisters) {
  613. *pNumberOfMapRegisters = NumberOfMapRegisters;
  614. }
  615. return( STATUS_SUCCESS );
  616. }
  617. NTSTATUS
  618. HalGetScatterGatherList (
  619. IN PADAPTER_OBJECT AdapterObject,
  620. IN PDEVICE_OBJECT DeviceObject,
  621. IN PMDL Mdl,
  622. IN PVOID CurrentVa,
  623. IN ULONG Length,
  624. IN PDRIVER_LIST_CONTROL ExecutionRoutine,
  625. IN PVOID Context,
  626. IN BOOLEAN WriteToDevice
  627. )
  628. {
  629. return (HalBuildScatterGatherList(AdapterObject,
  630. DeviceObject,
  631. Mdl,
  632. CurrentVa,
  633. Length,
  634. ExecutionRoutine,
  635. Context,
  636. WriteToDevice,
  637. NULL,
  638. 0
  639. ));
  640. }
  641. NTSTATUS
  642. HalBuildScatterGatherList (
  643. IN PADAPTER_OBJECT AdapterObject,
  644. IN PDEVICE_OBJECT DeviceObject,
  645. IN PMDL Mdl,
  646. IN PVOID CurrentVa,
  647. IN ULONG Length,
  648. IN PDRIVER_LIST_CONTROL ExecutionRoutine,
  649. IN PVOID Context,
  650. IN BOOLEAN WriteToDevice,
  651. IN PVOID ScatterGatherBuffer,
  652. IN ULONG ScatterGatherBufferLength
  653. )
  654. /*++
  655. Routine Description:
  656. This routine allocates the adapter channel specified by the adapter
  657. object. Next a scatter/gather list is built based on the MDL, the
  658. CurrentVa and the requested Length. Finally the driver's execution
  659. function is called with the scatter/gather list. The adapter is
  660. released when after the execution function returns.
  661. The scatter/gather list is allocated if a buffer is not passed and is
  662. freed by calling PutScatterGatherList.
  663. Arguments:
  664. AdapterObject - Pointer to the adapter control object to allocate to the
  665. driver.
  666. DeviceObject - Pointer to the device object that is allocating the
  667. adapter.
  668. Mdl - Pointer to the MDL that describes the pages of memory that are being
  669. read or written.
  670. CurrentVa - Current virtual address in the buffer described by the MDL
  671. that the transfer is being done to or from.
  672. Length - Supplies the length of the transfer.
  673. ExecutionRoutine - The address of the driver's execution routine that is
  674. invoked once the adapter channel (and possibly map registers) have been
  675. allocated.
  676. Context - An untyped longword context parameter passed to the driver's
  677. execution routine.
  678. WriteToDevice - Supplies the value that indicates whether this is a
  679. write to the device from memory (TRUE), or vice versa.
  680. Return Value:
  681. 
  682. Returns STATUS_SUCCESS unless too many map registers are requested or
  683. memory for the scatter/gather list could not be allocated.
  684. Notes:
  685. Note that this routine MUST be invoked at DISPATCH_LEVEL or above.
  686. The data in the buffer cannot be accessed until the put scatter/gather function has been called.
  687. --*/
  688. {
  689. PHAL_WAIT_CONTEXT_BLOCK WaitBlock;
  690. PMDL TempMdl;
  691. PSCATTER_GATHER_LIST ScatterGather;
  692. PSCATTER_GATHER_ELEMENT Element;
  693. ULONG NumberOfMapRegisters;
  694. ULONG ContextSize;
  695. ULONG TransferLength;
  696. ULONG MdlLength;
  697. PUCHAR MdlVa;
  698. NTSTATUS Status;
  699. PPFN_NUMBER PageFrame;
  700. ULONG PageOffset;
  701. if (!Mdl) {
  702. return (STATUS_INVALID_PARAMETER);
  703. }
  704. Status = HalCalculateScatterGatherListSize(AdapterObject,
  705. Mdl,
  706. CurrentVa,
  707. Length,
  708. &ContextSize,
  709. &NumberOfMapRegisters
  710. );
  711. if (!NT_SUCCESS(Status)) {
  712. return (Status);
  713. }
  714. //
  715. // If the adapter does not need map registers then most of this code
  716. // can be bypassed. Just build the scatter/gather list and give it
  717. // to the caller.
  718. //
  719. INCREMENT_SCATTER_GATHER_COUNT();
  720. if (!AdapterObject->NeedsMapRegisters) {
  721. if (ScatterGatherBuffer) {
  722. if (ScatterGatherBufferLength < ContextSize) {
  723. DECREMENT_SCATTER_GATHER_COUNT();
  724. return (STATUS_BUFFER_TOO_SMALL);
  725. }
  726. ScatterGather = ScatterGatherBuffer;
  727. } else {
  728. ScatterGather = ExAllocatePoolWithTag( NonPagedPool,
  729. ContextSize,
  730. HAL_POOL_TAG );
  731. if (ScatterGather == NULL) {
  732. DECREMENT_SCATTER_GATHER_COUNT();
  733. return( STATUS_INSUFFICIENT_RESOURCES );
  734. }
  735. }
  736. MdlVa = MmGetMdlVirtualAddress(Mdl);
  737. ScatterGather->Reserved = 0;
  738. Element = ScatterGather->Elements;
  739. TempMdl = Mdl;
  740. TransferLength = Length;
  741. MdlLength = TempMdl->ByteCount - (ULONG)((PUCHAR) CurrentVa - MdlVa);
  742. PageOffset = BYTE_OFFSET(CurrentVa);
  743. //
  744. // Calculate where to start in the MDL.
  745. //
  746. PageFrame = MmGetMdlPfnArray(TempMdl);
  747. PageFrame += ((ULONG_PTR) CurrentVa - ((ULONG_PTR) MdlVa & ~(PAGE_SIZE - 1)))
  748. >> PAGE_SHIFT;
  749. //
  750. // Loop build the list for each MDL.
  751. //
  752. while (TransferLength > 0) {
  753. if (MdlLength > TransferLength) {
  754. MdlLength = TransferLength;
  755. }
  756. TransferLength -= MdlLength;
  757. //
  758. // Loop building the list for the elements within the MDL.
  759. //
  760. while (MdlLength > 0) {
  761. //
  762. // Compute the starting address of the transfer.
  763. //
  764. Element->Address.QuadPart =
  765. ((ULONGLONG)*PageFrame << PAGE_SHIFT) + PageOffset;
  766. Element->Length = PAGE_SIZE - PageOffset;
  767. if (Element->Length > MdlLength ) {
  768. Element->Length = MdlLength;
  769. }
  770. ASSERT( (ULONG) MdlLength >= Element->Length );
  771. MdlLength -= Element->Length;
  772. //
  773. // Combine contiguous pages.
  774. //
  775. if (Element != ScatterGather->Elements ) {
  776. if (Element->Address.QuadPart ==
  777. (Element - 1)->Address.QuadPart + (Element - 1)->Length) {
  778. //
  779. // Add the new length to the old length.
  780. //
  781. (Element - 1)->Length += Element->Length;
  782. //
  783. // Reuse the current element.
  784. //
  785. Element--;
  786. }
  787. }
  788. PageOffset = 0;
  789. Element++;
  790. PageFrame++;
  791. }
  792. if (TempMdl->Next == NULL) {
  793. //
  794. // There are a few cases where the buffer described by the MDL
  795. // is less than the transfer length. This occurs when the
  796. // file system is transfering the last page of the file and
  797. // MM defines the MDL to be the file size and the file system
  798. // rounds the write up to a sector. This extra should never
  799. // cross a page boundary. Add this extra to the length of
  800. // the last element.
  801. //
  802. ASSERT(((Element - 1)->Length & (PAGE_SIZE - 1)) + TransferLength <= PAGE_SIZE );
  803. (Element - 1)->Length += TransferLength;
  804. break;
  805. }
  806. //
  807. // Advance to the next MDL. Update the current VA and the MdlLength.
  808. //
  809. TempMdl = TempMdl->Next;
  810. PageOffset = MmGetMdlByteOffset(TempMdl);
  811. MdlLength = TempMdl->ByteCount;
  812. PageFrame = MmGetMdlPfnArray(TempMdl);
  813. }
  814. //
  815. // Set the number of elements actually used.
  816. //
  817. ScatterGather->NumberOfElements = Element - ScatterGather->Elements;
  818. if (ScatterGatherBuffer) {
  819. ScatterGather->Reserved = HAL_WCB_DRIVER_BUFFER;
  820. }
  821. //
  822. // Call the driver with the scatter/gather list.
  823. //
  824. ExecutionRoutine( DeviceObject,
  825. DeviceObject->CurrentIrp,
  826. ScatterGather,
  827. Context );
  828. return STATUS_SUCCESS;
  829. }
  830. if (ScatterGatherBuffer) {
  831. if (ScatterGatherBufferLength < ContextSize) {
  832. DECREMENT_SCATTER_GATHER_COUNT();
  833. return (STATUS_BUFFER_TOO_SMALL);
  834. }
  835. WaitBlock = ScatterGatherBuffer;
  836. } else {
  837. WaitBlock = ExAllocatePoolWithTag(NonPagedPool, ContextSize, HAL_POOL_TAG);
  838. if (WaitBlock == NULL) {
  839. DECREMENT_SCATTER_GATHER_COUNT();
  840. return( STATUS_INSUFFICIENT_RESOURCES );
  841. }
  842. }
  843. //
  844. // Save the interesting data in the wait block.
  845. //
  846. if (ScatterGatherBuffer) {
  847. WaitBlock->Flags |= HAL_WCB_DRIVER_BUFFER;
  848. } else {
  849. WaitBlock->Flags = 0;
  850. }
  851. WaitBlock->Mdl = Mdl;
  852. WaitBlock->DmaMdl = NULL;
  853. WaitBlock->CurrentVa = CurrentVa;
  854. WaitBlock->Length = Length;
  855. WaitBlock->DriverExecutionRoutine = ExecutionRoutine;
  856. WaitBlock->DriverContext = Context;
  857. WaitBlock->AdapterObject = AdapterObject;
  858. WaitBlock->WriteToDevice = WriteToDevice;
  859. WaitBlock->NumberOfMapRegisters = NumberOfMapRegisters;
  860. WaitBlock->Wcb.DeviceContext = WaitBlock;
  861. WaitBlock->Wcb.DeviceObject = DeviceObject;
  862. WaitBlock->Wcb.CurrentIrp = DeviceObject->CurrentIrp;
  863. //
  864. // Call the HAL to allocate the adapter channel.
  865. // HalpAllocateAdapterCallback will fill in the scatter/gather list.
  866. //
  867. Status = HalAllocateAdapterChannel( AdapterObject,
  868. &WaitBlock->Wcb,
  869. NumberOfMapRegisters,
  870. HalpAllocateAdapterCallback );
  871. //
  872. // If HalAllocateAdapterChannel failed then free the wait block.
  873. //
  874. if (!NT_SUCCESS( Status)) {
  875. DECREMENT_SCATTER_GATHER_COUNT();
  876. ExFreePool( WaitBlock );
  877. }
  878. return( Status );
  879. }
  880. VOID
  881. HalPutScatterGatherList (
  882. IN PADAPTER_OBJECT AdapterObject,
  883. IN PSCATTER_GATHER_LIST ScatterGather,
  884. IN BOOLEAN WriteToDevice
  885. )
  886. /*++
  887. Routine Description:
  888. This function frees the map registers allocated for the scatter gather list. It can also free the
  889. scatter gather buffer and any associated MDLs.
  890. Arguments:
  891. ScatterGather - The scatter gather buffer
  892. WriteToDevice - Supplies the value that indicates whether this is a
  893. write to the device from memory (TRUE), or vice versa.
  894. Return Value:
  895. Returns a success or error status.
  896. --*/
  897. {
  898. PHAL_WAIT_CONTEXT_BLOCK WaitBlock = (PVOID) ScatterGather->Reserved;
  899. PTRANSLATION_ENTRY TranslationEntry;
  900. ULONG TransferLength;
  901. ULONG MdlLength;
  902. PMDL Mdl;
  903. PMDL tempMdl;
  904. PMDL nextMdl;
  905. PUCHAR CurrentVa;
  906. DECREMENT_SCATTER_GATHER_COUNT();
  907. //
  908. // If the reserved field was empty then just free the list and return.
  909. //
  910. if (WaitBlock == NULL) {
  911. ASSERT(!AdapterObject->NeedsMapRegisters);
  912. ExFreePool( ScatterGather );
  913. return;
  914. }
  915. if (WaitBlock == (PVOID)HAL_WCB_DRIVER_BUFFER) {
  916. ASSERT(!AdapterObject->NeedsMapRegisters);
  917. return;
  918. }
  919. ASSERT( WaitBlock == CONTAINING_RECORD( ScatterGather, HAL_WAIT_CONTEXT_BLOCK, ScatterGather ));
  920. //
  921. // Setup for the first MDL. We expect the MDL pointer to be pointing
  922. // at the first used MDL.
  923. //
  924. Mdl = WaitBlock->Mdl;
  925. CurrentVa = WaitBlock->CurrentVa;
  926. #if DBG
  927. ASSERT( CurrentVa >= (PUCHAR) MmGetMdlVirtualAddress(Mdl));
  928. if (MmGetMdlVirtualAddress(Mdl) < (PVOID)((PUCHAR) MmGetMdlVirtualAddress(Mdl) + Mdl->ByteCount )) {
  929. ASSERT( CurrentVa < (PUCHAR) MmGetMdlVirtualAddress(Mdl) + Mdl->ByteCount );
  930. }
  931. #endif
  932. MdlLength = Mdl->ByteCount - (ULONG)(CurrentVa - (PUCHAR) MmGetMdlVirtualAddress(Mdl));
  933. TransferLength = WaitBlock->Length;
  934. TranslationEntry = WaitBlock->MapRegisterBase;
  935. //
  936. // Loop through the used MDLs, calling IoFlushAdapterBuffers.
  937. //
  938. while (TransferLength > 0) {
  939. //
  940. // Do not perform a flush for buffers of zero length.
  941. //
  942. if (MdlLength > 0) {
  943. if (MdlLength > TransferLength) {
  944. MdlLength = TransferLength;
  945. }
  946. TransferLength -= MdlLength;
  947. IoFlushAdapterBuffers( AdapterObject,
  948. Mdl,
  949. TranslationEntry,
  950. CurrentVa,
  951. MdlLength,
  952. WriteToDevice );
  953. TranslationEntry += ADDRESS_AND_SIZE_TO_SPAN_PAGES( CurrentVa,
  954. MdlLength );
  955. }
  956. if (Mdl->Next == NULL) {
  957. break;
  958. }
  959. //
  960. // Advance to the next MDL. Update the current VA and the MdlLength.
  961. //
  962. Mdl = Mdl->Next;
  963. CurrentVa = MmGetMdlVirtualAddress(Mdl);
  964. MdlLength = Mdl->ByteCount;
  965. }
  966. IoFreeMapRegisters( AdapterObject,
  967. WaitBlock->MapRegisterBase,
  968. WaitBlock->NumberOfMapRegisters
  969. );
  970. if (WaitBlock->DmaMdl) {
  971. tempMdl = WaitBlock->DmaMdl;
  972. while (tempMdl) {
  973. nextMdl = tempMdl->Next;
  974. //
  975. // If the MDL was mapped by the driver unmap it here.
  976. //
  977. if (tempMdl->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) {
  978. MmUnmapLockedPages(tempMdl->MappedSystemVa, tempMdl);
  979. }
  980. IoFreeMdl(tempMdl);
  981. tempMdl = nextMdl;
  982. }
  983. }
  984. if (!(WaitBlock->Flags & HAL_WCB_DRIVER_BUFFER)) {
  985. ExFreePool( WaitBlock );
  986. }
  987. }
  988. IO_ALLOCATION_ACTION
  989. HalpAllocateAdapterCallback (
  990. IN struct _DEVICE_OBJECT *DeviceObject,
  991. IN struct _IRP *Irp,
  992. IN PVOID MapRegisterBase,
  993. IN PVOID Context
  994. )
  995. /*++
  996. Routine Description:
  997. This routine is called when the adapter object and map registers are
  998. available for the data transfer. This routines saves the map register
  999. base away. If all of the required bases have not been saved then it
  1000. returns. Otherwise it routine builds the entire scatter/gather
  1001. list by calling IoMapTransfer. After the list is built it is passed to
  1002. the driver.
  1003. Arguments:
  1004. DeviceObject - Pointer to the device object that is allocating the
  1005. adapter.
  1006. Irp - Supplies the map register offset assigned for this callback.
  1007. MapRegisterBase - Supplies the map register base for use by the adapter
  1008. routines.
  1009. Context - Supplies a pointer to the xhal wait contorl block.
  1010. Return Value:
  1011. Returns DeallocateObjectKeepRegisters.
  1012. --*/
  1013. {
  1014. PHAL_WAIT_CONTEXT_BLOCK WaitBlock = Context;
  1015. ULONG TransferLength;
  1016. LONG MdlLength;
  1017. PMDL Mdl;
  1018. PUCHAR CurrentVa;
  1019. PSCATTER_GATHER_LIST ScatterGather;
  1020. PSCATTER_GATHER_ELEMENT Element;
  1021. PTRANSLATION_ENTRY TranslationEntry = MapRegisterBase;
  1022. PTRANSLATION_ENTRY NextEntry;
  1023. PDRIVER_LIST_CONTROL DriverExecutionRoutine;
  1024. PVOID DriverContext;
  1025. PIRP CurrentIrp;
  1026. PADAPTER_OBJECT AdapterObject;
  1027. BOOLEAN WriteToDevice;
  1028. //
  1029. // Save the map register base.
  1030. //
  1031. WaitBlock->MapRegisterBase = MapRegisterBase;
  1032. //
  1033. // Save the data that will be overwritten by the scatter gather list.
  1034. //
  1035. DriverExecutionRoutine = WaitBlock->DriverExecutionRoutine;
  1036. DriverContext = WaitBlock->DriverContext;
  1037. CurrentIrp = WaitBlock->Wcb.CurrentIrp;
  1038. AdapterObject = WaitBlock->AdapterObject;
  1039. WriteToDevice = WaitBlock->WriteToDevice;
  1040. //
  1041. // Put the scatter gatther list after wait block. Add a back pointer to
  1042. // the beginning of the wait block.
  1043. //
  1044. ScatterGather = &WaitBlock->ScatterGather;
  1045. ScatterGather->Reserved = (ULONG_PTR) WaitBlock;
  1046. Element = ScatterGather->Elements;
  1047. //
  1048. // Setup for the first MDL. We expect the MDL pointer to be pointing
  1049. // at the first used MDL.
  1050. //
  1051. Mdl = WaitBlock->Mdl;
  1052. CurrentVa = WaitBlock->CurrentVa;
  1053. #if DBG
  1054. ASSERT( CurrentVa >= (PUCHAR) MmGetMdlVirtualAddress(Mdl));
  1055. if (MmGetMdlVirtualAddress(Mdl) < (PVOID)((PUCHAR) MmGetMdlVirtualAddress(Mdl) + Mdl->ByteCount )) {
  1056. ASSERT( CurrentVa < (PUCHAR) MmGetMdlVirtualAddress(Mdl) + Mdl->ByteCount );
  1057. }
  1058. #endif
  1059. MdlLength = Mdl->ByteCount - (ULONG)(CurrentVa - (PUCHAR) MmGetMdlVirtualAddress(Mdl));
  1060. TransferLength = WaitBlock->Length;
  1061. //
  1062. // Loop building the list for each MDL.
  1063. //
  1064. while (TransferLength > 0) {
  1065. if ((ULONG) MdlLength > TransferLength) {
  1066. MdlLength = TransferLength;
  1067. }
  1068. TransferLength -= MdlLength;
  1069. NextEntry = TranslationEntry;
  1070. if (MdlLength > 0) {
  1071. NextEntry += ADDRESS_AND_SIZE_TO_SPAN_PAGES( CurrentVa,
  1072. MdlLength );
  1073. }
  1074. //
  1075. // Loop building the list for the elments within an MDL.
  1076. //
  1077. while (MdlLength > 0) {
  1078. Element->Length = MdlLength;
  1079. Element->Address = IoMapTransfer( AdapterObject,
  1080. Mdl,
  1081. MapRegisterBase,
  1082. CurrentVa,
  1083. &Element->Length,
  1084. WriteToDevice );
  1085. ASSERT( (ULONG) MdlLength >= Element->Length );
  1086. MdlLength -= Element->Length;
  1087. CurrentVa += Element->Length;
  1088. Element++;
  1089. }
  1090. if (Mdl->Next == NULL) {
  1091. //
  1092. // There are a few cases where the buffer described by the MDL
  1093. // is less than the transfer length. This occurs when the
  1094. // file system transfering the last page of file and MM defines
  1095. // the MDL to be the file size and the file system rounds the write
  1096. // up to a sector. This extra should never cross a page
  1097. // boundary. Add this extra to the length of the last element.
  1098. //
  1099. ASSERT(((Element - 1)->Length & (PAGE_SIZE - 1)) + TransferLength <= PAGE_SIZE );
  1100. (Element - 1)->Length += TransferLength;
  1101. break;
  1102. }
  1103. //
  1104. // Advance to the next MDL. Update the current VA and the MdlLength.
  1105. //
  1106. Mdl = Mdl->Next;
  1107. CurrentVa = MmGetMdlVirtualAddress(Mdl);
  1108. MdlLength = Mdl->ByteCount;
  1109. TranslationEntry = NextEntry;
  1110. }
  1111. //
  1112. // Set the number of elements actually used.
  1113. //
  1114. ScatterGather->NumberOfElements = Element - ScatterGather->Elements;
  1115. //
  1116. // Call the driver with the scatter/gather list.
  1117. //
  1118. DriverExecutionRoutine( DeviceObject,
  1119. CurrentIrp,
  1120. ScatterGather,
  1121. DriverContext );
  1122. return( DeallocateObjectKeepRegisters );
  1123. }
  1124. VOID
  1125. IoFreeAdapterChannel(
  1126. IN PADAPTER_OBJECT AdapterObject
  1127. )
  1128. /*++
  1129. Routine Description:
  1130. This routine is invoked to deallocate the specified adapter object.
  1131. Any map registers that were allocated are also automatically deallocated.
  1132. No checks are made to ensure that the adapter is really allocated to
  1133. a device object. However, if it is not, the kernel will bugcheck.
  1134. If another device is waiting in the queue to allocate the adapter object
  1135. it will be pulled from the queue and its execution routine will be
  1136. invoked.
  1137. Arguments:
  1138. AdapterObject - Pointer to the adapter object to be deallocated.
  1139. Return Value:
  1140. None.
  1141. --*/
  1142. {
  1143. PKDEVICE_QUEUE_ENTRY Packet;
  1144. PWAIT_CONTEXT_BLOCK Wcb;
  1145. PADAPTER_OBJECT MasterAdapter;
  1146. BOOLEAN Busy = FALSE;
  1147. IO_ALLOCATION_ACTION Action;
  1148. KIRQL Irql;
  1149. LONG MapRegisterNumber;
  1150. //
  1151. // Begin by getting the address of the master adapter.
  1152. //
  1153. MasterAdapter = AdapterObject->MasterAdapter;
  1154. //
  1155. // Pull requests of the adapter's device wait queue as long as the
  1156. // adapter is free and there are sufficient map registers available.
  1157. //
  1158. while( TRUE ) {
  1159. //
  1160. // Begin by checking to see whether there are any map registers that
  1161. // need to be deallocated. If so, then deallocate them now.
  1162. //
  1163. if (AdapterObject->NumberOfMapRegisters != 0) {
  1164. IoFreeMapRegisters( AdapterObject,
  1165. AdapterObject->MapRegisterBase,
  1166. AdapterObject->NumberOfMapRegisters
  1167. );
  1168. }
  1169. //
  1170. // Simply remove the next entry from the adapter's device wait queue.
  1171. // If one was successfully removed, allocate any map registers that it
  1172. // requires and invoke its execution routine.
  1173. //
  1174. Packet = KeRemoveDeviceQueue( &AdapterObject->ChannelWaitQueue );
  1175. if (Packet == NULL) {
  1176. //
  1177. // There are no more requests - break out of the loop.
  1178. //
  1179. break;
  1180. }
  1181. Wcb = CONTAINING_RECORD( Packet,
  1182. WAIT_CONTEXT_BLOCK,
  1183. WaitQueueEntry );
  1184. AdapterObject->CurrentWcb = Wcb;
  1185. AdapterObject->NumberOfMapRegisters = Wcb->NumberOfMapRegisters;
  1186. //
  1187. // Check to see whether this driver wishes to allocate any map
  1188. // registers. If so, then queue the device object to the master
  1189. // adapter queue to wait for them to become available. If the driver
  1190. // wants map registers, ensure that this adapter has enough total
  1191. // map registers to satisfy the request.
  1192. //
  1193. if (Wcb->NumberOfMapRegisters != 0 &&
  1194. AdapterObject->MasterAdapter != NULL) {
  1195. //
  1196. // Lock the map register bit map and the adapter queue in the
  1197. // master adapter object. The channel structure offset is used as
  1198. // a hint for the register search.
  1199. //
  1200. KeAcquireSpinLock( &MasterAdapter->SpinLock, &Irql );
  1201. MapRegisterNumber = -1;
  1202. if (IsListEmpty( &MasterAdapter->AdapterQueue)) {
  1203. MapRegisterNumber = RtlFindClearBitsAndSet( MasterAdapter->MapRegisters,
  1204. Wcb->NumberOfMapRegisters,
  1205. 0
  1206. );
  1207. }
  1208. if (MapRegisterNumber == -1) {
  1209. //PBUFFER_GROW_WORK_ITEM bufferWorkItem;
  1210. //
  1211. // There were not enough free map registers. Queue this request
  1212. // on the master adapter where it will wait until some registers
  1213. // are deallocated.
  1214. //
  1215. InsertTailList( &MasterAdapter->AdapterQueue,
  1216. &AdapterObject->AdapterQueue
  1217. );
  1218. Busy = 1;
  1219. //
  1220. // Queue a work item to grow the map registers
  1221. //
  1222. #if 0
  1223. bufferWorkItem =
  1224. ExAllocatePoolWithTag( NonPagedPool,
  1225. sizeof(BUFFER_GROW_WORK_ITEM),
  1226. HAL_POOL_TAG);
  1227. if (bufferWorkItem != NULL) {
  1228. ExInitializeWorkItem( &bufferWorkItem->WorkItem,
  1229. HalpGrowMapBufferWorker,
  1230. bufferWorkItem );
  1231. bufferWorkItem->AdapterObject = AdapterObject;
  1232. bufferWorkItem->MapRegisterCount =
  1233. Wcb->NumberOfMapRegisters;
  1234. ExQueueWorkItem( &bufferWorkItem->WorkItem,
  1235. DelayedWorkQueue );
  1236. }
  1237. #endif
  1238. } else {
  1239. AdapterObject->MapRegisterBase = ((PTRANSLATION_ENTRY)
  1240. MasterAdapter->MapRegisterBase + MapRegisterNumber);
  1241. //
  1242. // Set the no scatter/gather flag if scatter/gather is not
  1243. // supported.
  1244. //
  1245. if (!AdapterObject->ScatterGather) {
  1246. AdapterObject->MapRegisterBase = (PVOID)
  1247. ((ULONG_PTR) AdapterObject->MapRegisterBase | NO_SCATTER_GATHER);
  1248. }
  1249. }
  1250. KeReleaseSpinLock( &MasterAdapter->SpinLock, Irql );
  1251. } else {
  1252. AdapterObject->MapRegisterBase = NULL;
  1253. AdapterObject->NumberOfMapRegisters = 0;
  1254. }
  1255. //
  1256. // If there were either enough map registers available or no map
  1257. // registers needed to be allocated, invoke the driver's execution
  1258. // routine now.
  1259. //
  1260. if (!Busy) {
  1261. AdapterObject->CurrentWcb = Wcb;
  1262. Action = Wcb->DeviceRoutine( Wcb->DeviceObject,
  1263. Wcb->CurrentIrp,
  1264. AdapterObject->MapRegisterBase,
  1265. Wcb->DeviceContext );
  1266. //
  1267. // If the execution routine would like to have the adapter
  1268. // deallocated, then release the adapter object.
  1269. //
  1270. if (Action == KeepObject) {
  1271. //
  1272. // This request wants to keep the channel a while so break
  1273. // out of the loop.
  1274. //
  1275. break;
  1276. }
  1277. //
  1278. // If the driver wants to keep the map registers then set the
  1279. // number allocated to 0. This keeps the deallocation routine
  1280. // from deallocating them.
  1281. //
  1282. if (Action == DeallocateObjectKeepRegisters) {
  1283. AdapterObject->NumberOfMapRegisters = 0;
  1284. }
  1285. } else {
  1286. //
  1287. // This request did not get the requested number of map registers so
  1288. // break out of the loop.
  1289. //
  1290. break;
  1291. }
  1292. }
  1293. }
  1294. VOID
  1295. IoFreeMapRegisters(
  1296. PADAPTER_OBJECT AdapterObject,
  1297. PVOID MapRegisterBase,
  1298. ULONG NumberOfMapRegisters
  1299. )
  1300. /*++
  1301. Routine Description:
  1302. If NumberOfMapRegisters != 0, this routine deallocates the map registers
  1303. for the adapter.
  1304. If there are any queued adapters waiting then an attempt is made to allocate
  1305. the next entry.
  1306. Arguments:
  1307. AdapterObject - The adapter object where the map registers should be
  1308. returned to.
  1309. MapRegisterBase - The map register base of the registers to be deallocated.
  1310. NumberOfMapRegisters - The number of registers to be deallocated.
  1311. Return Value:
  1312. None
  1313. --+*/
  1314. {
  1315. PADAPTER_OBJECT MasterAdapter;
  1316. LONG MapRegisterNumber;
  1317. PWAIT_CONTEXT_BLOCK Wcb;
  1318. PLIST_ENTRY Packet;
  1319. IO_ALLOCATION_ACTION Action;
  1320. KIRQL Irql;
  1321. //
  1322. // Begin by getting the address of the master adapter.
  1323. //
  1324. if (AdapterObject->MasterAdapter != NULL && MapRegisterBase != NULL) {
  1325. MasterAdapter = AdapterObject->MasterAdapter;
  1326. } else {
  1327. //
  1328. // There are no map registers to return.
  1329. //
  1330. return;
  1331. }
  1332. if (NumberOfMapRegisters != 0) {
  1333. //
  1334. // Strip the no scatter/gather flag.
  1335. //
  1336. MapRegisterBase = (PVOID) ((ULONG_PTR) MapRegisterBase & ~NO_SCATTER_GATHER);
  1337. MapRegisterNumber = (ULONG)((PTRANSLATION_ENTRY) MapRegisterBase -
  1338. (PTRANSLATION_ENTRY) MasterAdapter->MapRegisterBase);
  1339. //
  1340. // Acquire the master adapter spinlock which locks the adapter queue and the
  1341. // bit map for the map registers.
  1342. //
  1343. KeAcquireSpinLock(&MasterAdapter->SpinLock,&Irql);
  1344. //
  1345. // Return the registers to the bit map.
  1346. //
  1347. RtlClearBits( MasterAdapter->MapRegisters,
  1348. MapRegisterNumber,
  1349. NumberOfMapRegisters
  1350. );
  1351. } else {
  1352. KeAcquireSpinLock(&MasterAdapter->SpinLock,&Irql);
  1353. }
  1354. //
  1355. // Process any requests waiting for map registers in the adapter queue.
  1356. // Requests are processed until a request cannot be satisfied or until
  1357. // there are no more requests in the queue.
  1358. //
  1359. while(TRUE) {
  1360. if ( IsListEmpty(&MasterAdapter->AdapterQueue) ){
  1361. break;
  1362. }
  1363. Packet = RemoveHeadList( &MasterAdapter->AdapterQueue );
  1364. AdapterObject = CONTAINING_RECORD( Packet,
  1365. ADAPTER_OBJECT,
  1366. AdapterQueue
  1367. );
  1368. Wcb = AdapterObject->CurrentWcb;
  1369. //
  1370. // Attempt to allocate map registers for this request. Use the previous
  1371. // register base as a hint.
  1372. //
  1373. MapRegisterNumber = RtlFindClearBitsAndSet( MasterAdapter->MapRegisters,
  1374. AdapterObject->NumberOfMapRegisters,
  1375. MasterAdapter->NumberOfMapRegisters
  1376. );
  1377. if (MapRegisterNumber == -1) {
  1378. //
  1379. // There were not enough free map registers. Put this request back on
  1380. // the adapter queue where is came from.
  1381. //
  1382. InsertHeadList( &MasterAdapter->AdapterQueue,
  1383. &AdapterObject->AdapterQueue
  1384. );
  1385. break;
  1386. }
  1387. KeReleaseSpinLock( &MasterAdapter->SpinLock, Irql );
  1388. AdapterObject->MapRegisterBase = (PVOID) ((PTRANSLATION_ENTRY)
  1389. MasterAdapter->MapRegisterBase + MapRegisterNumber);
  1390. //
  1391. // Set the no scatter/gather flag if scatter/gather not
  1392. // supported.
  1393. //
  1394. if (!AdapterObject->ScatterGather) {
  1395. AdapterObject->MapRegisterBase = (PVOID)
  1396. ((ULONG_PTR) AdapterObject->MapRegisterBase | NO_SCATTER_GATHER);
  1397. }
  1398. //
  1399. // Invoke the driver's execution routine now.
  1400. //
  1401. Action = Wcb->DeviceRoutine( Wcb->DeviceObject,
  1402. Wcb->CurrentIrp,
  1403. AdapterObject->MapRegisterBase,
  1404. Wcb->DeviceContext );
  1405. //
  1406. // If the driver wishes to keep the map registers then set the number
  1407. // allocated to zero and set the action to deallocate object.
  1408. //
  1409. if (Action == DeallocateObjectKeepRegisters) {
  1410. AdapterObject->NumberOfMapRegisters = 0;
  1411. Action = DeallocateObject;
  1412. }
  1413. //
  1414. // If the driver would like to have the adapter deallocated,
  1415. // then deallocate any map registers allocated and then release
  1416. // the adapter object.
  1417. //
  1418. if (Action == DeallocateObject) {
  1419. //
  1420. // The map registers registers are deallocated here rather than in
  1421. // IoFreeAdapterChannel. This limits the number of times
  1422. // this routine can be called recursively possibly overflowing
  1423. // the stack. The worst case occurs if there is a pending
  1424. // request for the adapter that uses map registers and whos
  1425. // excution routine decallocates the adapter. In that case if there
  1426. // are no requests in the master adapter queue, then IoFreeMapRegisters
  1427. // will get called again.
  1428. //
  1429. if (AdapterObject->NumberOfMapRegisters != 0) {
  1430. //
  1431. // Deallocate the map registers and clear the count so that
  1432. // IoFreeAdapterChannel will not deallocate them again.
  1433. //
  1434. KeAcquireSpinLock( &MasterAdapter->SpinLock, &Irql );
  1435. RtlClearBits( MasterAdapter->MapRegisters,
  1436. MapRegisterNumber,
  1437. AdapterObject->NumberOfMapRegisters
  1438. );
  1439. AdapterObject->NumberOfMapRegisters = 0;
  1440. KeReleaseSpinLock( &MasterAdapter->SpinLock, Irql );
  1441. }
  1442. IoFreeAdapterChannel( AdapterObject );
  1443. }
  1444. KeAcquireSpinLock( &MasterAdapter->SpinLock, &Irql );
  1445. }
  1446. KeReleaseSpinLock( &MasterAdapter->SpinLock, Irql );
  1447. }
  1448. VOID
  1449. HalPutDmaAdapter(
  1450. IN PADAPTER_OBJECT AdapterObject
  1451. )
  1452. /*++
  1453. Routine Description:
  1454. This routine frees the DMA adapter if it is not one of the common
  1455. DMA channel adapters.
  1456. Arguments:
  1457. AdapterObject - Supplies a pointer to the DMA adapter to be freed.
  1458. Return Value:
  1459. None.
  1460. --*/
  1461. {
  1462. KIRQL Irql;
  1463. //
  1464. // This adapter can be freed if the channel number is zero and
  1465. // it is not the channel zero adapter.
  1466. //
  1467. if ( AdapterObject->ChannelNumber == 0xFF ) {
  1468. //
  1469. // Remove this adapter from our list
  1470. //
  1471. KeAcquireSpinLock(&HalpDmaAdapterListLock,&Irql);
  1472. RemoveEntryList(&AdapterObject->AdapterList);
  1473. KeReleaseSpinLock(&HalpDmaAdapterListLock, Irql);
  1474. ObDereferenceObject( AdapterObject );
  1475. }
  1476. #ifdef ACPI_HAL
  1477. //
  1478. // Deal with Slave Objects that are F-Type, if we have F-DMA support
  1479. //
  1480. if (HalpFDMAInterface.IsaReleaseFTypeChannel &&
  1481. (AdapterObject->ChannelNumber >= 0) &&
  1482. (AdapterObject->ChannelNumber < EISA_DMA_CHANNELS)) {
  1483. HalpFDMAInterface.IsaReleaseFTypeChannel(NULL,AdapterObject->ChannelNumber);
  1484. }
  1485. #endif
  1486. }
  1487. struct _DMA_ADAPTER *
  1488. HaliGetDmaAdapter(
  1489. IN PVOID Context,
  1490. IN struct _DEVICE_DESCRIPTION *DeviceDescriptor,
  1491. OUT PULONG NumberOfMapRegisters
  1492. )
  1493. /*++
  1494. Routine Description:
  1495. This function is a wrapper for HalGetAdapter. Is is called through
  1496. the HAL dispatch table.
  1497. Arguments:
  1498. Context - Unused.
  1499. DeviceDescriptor - Supplies the device descriptor used to allocate the dma
  1500. adapter object.
  1501. NubmerOfMapRegisters - Returns the maximum number of map registers a device
  1502. can allocate at one time.
  1503. Return Value:
  1504. Returns a DMA adapter or NULL.
  1505. --*/
  1506. {
  1507. return (PDMA_ADAPTER) HalGetAdapter( DeviceDescriptor, NumberOfMapRegisters );
  1508. }
  1509. NTSTATUS
  1510. HalBuildMdlFromScatterGatherList(
  1511. IN PADAPTER_OBJECT AdapterObject,
  1512. IN PSCATTER_GATHER_LIST ScatterGather,
  1513. IN PMDL OriginalMdl,
  1514. OUT PMDL *TargetMdl
  1515. )
  1516. /*++
  1517. Routine Description:
  1518. This function builds an MDL from the scatter gather list. This is so if a driver wants to
  1519. construct a virtual address for the DMA buffer and write to it. The target MDL is freed when the
  1520. caller calls HalPutScatterGatherList.
  1521. Arguments:
  1522. ScatterGather - The scatter gather buffer from which to build the MDL.
  1523. OriginalMdl - The MDL used to build the scatter gather list (using HalGet or HalBuild API)
  1524. TargetMdl - Returns the new MDL in this.
  1525. Return Value:
  1526. Returns a success or error status.
  1527. --*/
  1528. {
  1529. PMDL tempMdl;
  1530. PMDL newMdl;
  1531. PMDL targetMdl;
  1532. PMDL prevMdl;
  1533. PMDL nextMdl;
  1534. CSHORT mdlFlags;
  1535. PHAL_WAIT_CONTEXT_BLOCK WaitBlock = (PVOID) ScatterGather->Reserved;
  1536. ULONG i,j;
  1537. PSCATTER_GATHER_ELEMENT element;
  1538. PPFN_NUMBER pfnArray;
  1539. ULONG pageFrame;
  1540. ULONG nPages;
  1541. if (!OriginalMdl) {
  1542. return STATUS_INVALID_PARAMETER;
  1543. }
  1544. if (!AdapterObject->NeedsMapRegisters) {
  1545. *TargetMdl = OriginalMdl;
  1546. return STATUS_SUCCESS;
  1547. }
  1548. //
  1549. // If this API is called more than once
  1550. if (WaitBlock && WaitBlock->DmaMdl) {
  1551. return (STATUS_NONE_MAPPED);
  1552. }
  1553. //
  1554. // Allocate a chain of target MDLs
  1555. //
  1556. prevMdl = NULL;
  1557. targetMdl = NULL;
  1558. for (tempMdl = OriginalMdl; tempMdl; tempMdl = tempMdl->Next) {
  1559. PVOID va;
  1560. ULONG byteCount;
  1561. if(tempMdl == OriginalMdl) {
  1562. va = WaitBlock->CurrentVa;
  1563. //
  1564. // This may be a little more than necessary.
  1565. //
  1566. byteCount = MmGetMdlByteCount(tempMdl);
  1567. } else {
  1568. va = MmGetMdlVirtualAddress(tempMdl);
  1569. byteCount = MmGetMdlByteCount(tempMdl);
  1570. }
  1571. newMdl = IoAllocateMdl(va, byteCount, FALSE, FALSE, NULL);
  1572. if (!newMdl) {
  1573. //
  1574. // Clean up previous allocated MDLs
  1575. //
  1576. tempMdl = targetMdl;
  1577. while (tempMdl) {
  1578. nextMdl = tempMdl->Next;
  1579. IoFreeMdl(tempMdl);
  1580. tempMdl = nextMdl;
  1581. }
  1582. return (STATUS_INSUFFICIENT_RESOURCES);
  1583. }
  1584. if (!prevMdl) {
  1585. prevMdl = newMdl;
  1586. targetMdl = newMdl;
  1587. } else {
  1588. prevMdl->Next = newMdl;
  1589. prevMdl = newMdl;
  1590. }
  1591. }
  1592. tempMdl = OriginalMdl;
  1593. element = ScatterGather->Elements;
  1594. for (tempMdl = targetMdl; tempMdl; tempMdl = tempMdl->Next) {
  1595. targetMdl->MdlFlags |= MDL_PAGES_LOCKED;
  1596. pfnArray = MmGetMdlPfnArray(tempMdl);
  1597. for (i = 0; i < ScatterGather->NumberOfElements; i++, element++) {
  1598. nPages = BYTES_TO_PAGES(BYTE_OFFSET(element->Address.QuadPart) + element->Length);
  1599. pageFrame = (ULONG)(element->Address.QuadPart >> PAGE_SHIFT);
  1600. for (j = 0; j < nPages; j++) {
  1601. *pfnArray = pageFrame + j;
  1602. pfnArray++;
  1603. ASSERT((PVOID)pfnArray <= (PVOID)((PCHAR)tempMdl + tempMdl->Size));
  1604. }
  1605. }
  1606. }
  1607. *TargetMdl = targetMdl;
  1608. if (WaitBlock) {
  1609. WaitBlock->DmaMdl = targetMdl;
  1610. }
  1611. return STATUS_SUCCESS;
  1612. }