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.

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