Leaked source code of windows server 2003
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.

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