PageRenderTime 66ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 0ms

/opensource.apple.com/source/IOATAFamily/IOATAFamily-171.3.4/MacIOATA.cpp?txt

#
Unknown | 1292 lines | 949 code | 343 blank | 0 comment | 0 complexity | 75d5e5557eff033aaa38a7d457906721 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, GPL-2.0, BSD-3-Clause, GPL-3.0, MPL-2.0, LGPL-2.0, LGPL-2.1, CC-BY-SA-3.0, IPL-1.0, ISC, AGPL-1.0, AGPL-3.0, JSON, Apache-2.0, 0BSD
  1. /*
  2. * Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
  3. *
  4. * @APPLE_LICENSE_HEADER_START@
  5. *
  6. * The contents of this file constitute Original Code as defined in and
  7. * are subject to the Apple Public Source License Version 1.1 (the
  8. * "License"). You may not use this file except in compliance with the
  9. * License. Please obtain a copy of the License at
  10. * http://www.apple.com/publicsource and read it before using this file.
  11. *
  12. * This Original Code and all software distributed under the License are
  13. * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  14. * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
  15. * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
  17. * License for the specific language governing rights and limitations
  18. * under the License.
  19. *
  20. * @APPLE_LICENSE_HEADER_END@
  21. */
  22. /*
  23. *
  24. * MacIOATA.cpp
  25. *
  26. * class defining the portions of MacIO ATA cells which are shared
  27. * in common between OHare, Heathrow and Key Largo ATA Cells.
  28. * These controllers share a common register file layout, interrupt
  29. * source format and all use DBDMA engines. These are different from
  30. * other ATA controllers, such as most PCI-IDE and PC-Card ATA ports.
  31. * Each cell type has some distinctive features that must be implemented
  32. * by a specific driver subclass. As much common code as possible is
  33. * presented in this superclass.
  34. *
  35. *
  36. */
  37. #ifdef __ppc__
  38. #include <IOKit/IOTypes.h>
  39. #include "IOATATypes.h"
  40. #include "IOATAController.h"
  41. #include "IOATADevice.h"
  42. #include "IOATABusInfo.h"
  43. #include "IOATADevConfig.h"
  44. #include <IOKit/ppc/IODBDMA.h>
  45. #include <IOKit/IOMemoryCursor.h>
  46. #include <libkern/OSByteOrder.h>
  47. #include <libkern/OSAtomic.h>
  48. #include "MacIOATA.h"
  49. #include "IOATABusCommand.h"
  50. #ifdef DLOG
  51. #undef DLOG
  52. #endif
  53. //#define ATA_DEBUG 1
  54. #ifdef ATA_DEBUG
  55. #define DLOG(fmt, args...) IOLog(fmt, ## args)
  56. #else
  57. #define DLOG(fmt, args...)
  58. #endif
  59. // some day, we'll have an ATA recorder for IOKit
  60. #define ATARecordEventMACRO(type,param,bus,data) (void) (type); (void) (param); (void) (bus); (void) (data)
  61. #pragma mark -IOService Overrides -
  62. // 33 data descriptors + NOP + STOP
  63. #define kATAXferDMADesc 33
  64. #define kATAMaxDMADesc kATAXferDMADesc + 2
  65. // up to 256 ATA sectors per transfer
  66. #define kMaxATAXfer 512 * 256
  67. enum {
  68. /* Command.cmd operations*/
  69. OUTPUT_MORE = 0x00000000,
  70. OUTPUT_LAST = 0x10000000,
  71. INPUT_MORE = 0x20000000,
  72. INPUT_LAST = 0x30000000,
  73. STORE_QUAD = 0x40000000,
  74. LOAD_QUAD = 0x50000000,
  75. NOP_CMD = 0x60000000,
  76. STOP_CMD = 0x70000000,
  77. kdbdmaCmdMask = (long)0xF0000000
  78. };
  79. //---------------------------------------------------------------------------
  80. #define super IOATAController
  81. OSDefineMetaClass( MacIOATA, IOATAController )
  82. OSDefineAbstractStructors( MacIOATA, IOATAController )
  83. OSMetaClassDefineReservedUnused(MacIOATA, 0);
  84. OSMetaClassDefineReservedUnused(MacIOATA, 1);
  85. OSMetaClassDefineReservedUnused(MacIOATA, 2);
  86. OSMetaClassDefineReservedUnused(MacIOATA, 3);
  87. OSMetaClassDefineReservedUnused(MacIOATA, 4);
  88. OSMetaClassDefineReservedUnused(MacIOATA, 5);
  89. OSMetaClassDefineReservedUnused(MacIOATA, 6);
  90. OSMetaClassDefineReservedUnused(MacIOATA, 7);
  91. OSMetaClassDefineReservedUnused(MacIOATA, 8);
  92. OSMetaClassDefineReservedUnused(MacIOATA, 9);
  93. OSMetaClassDefineReservedUnused(MacIOATA, 10);
  94. OSMetaClassDefineReservedUnused(MacIOATA, 11);
  95. OSMetaClassDefineReservedUnused(MacIOATA, 12);
  96. OSMetaClassDefineReservedUnused(MacIOATA, 13);
  97. OSMetaClassDefineReservedUnused(MacIOATA, 14);
  98. OSMetaClassDefineReservedUnused(MacIOATA, 15);
  99. OSMetaClassDefineReservedUnused(MacIOATA, 16);
  100. OSMetaClassDefineReservedUnused(MacIOATA, 17);
  101. OSMetaClassDefineReservedUnused(MacIOATA, 18);
  102. OSMetaClassDefineReservedUnused(MacIOATA, 19);
  103. OSMetaClassDefineReservedUnused(MacIOATA, 20);
  104. //---------------------------------------------------------------------------
  105. bool
  106. MacIOATA::init(OSDictionary * properties)
  107. {
  108. // Initialize instance variables.
  109. DLOG("MacIOATA::init() starting\n");
  110. if (super::init(properties) == false)
  111. {
  112. DLOG("MacIOATA: super::init() failed\n");
  113. return false;
  114. }
  115. isMediaBay = false; // don't know yet
  116. isBusOnline = true; // if false, it means media bay has ejected.
  117. _baseAddressMap = 0;
  118. _dmaBaseMap = 0;
  119. _DMACursor = 0;
  120. _descriptors = 0;
  121. _descriptorsPhysical = 0;
  122. _devIntSrc = 0;
  123. _dmaIntSrc = 0;
  124. _dmaIntExpected = 0;
  125. _dmaState = MacIOATA::kATADMAInactive;
  126. _resyncInterrupts = false;
  127. DLOG("MacIOATA::init() done\n");
  128. return true;
  129. }
  130. /*---------------------------------------------------------------------------
  131. *
  132. * Override IOService start.
  133. *
  134. * Subclasses should override the start method, call the super::start
  135. * first then add interrupt sources and probe their busses for devices
  136. * and create device nubs as needed.
  137. ---------------------------------------------------------------------------*/
  138. bool
  139. MacIOATA::start(IOService *provider)
  140. {
  141. DLOG("MacIOATA::start() begin\n");
  142. // call start on the superclass
  143. if (!super::start( provider))
  144. {
  145. DLOG("MacIOATA: super::start() failed\n");
  146. return false;
  147. }
  148. // Allocate the DMA descriptor area
  149. if( ! allocDMAChannel() )
  150. {
  151. DLOG("MacIOATA: allocDMAChannel failed\n");
  152. return false;
  153. }
  154. // find the DMA interrupt source and attach it to the command gate
  155. // if we attach it first, then DMA interrupts will get priority for scheduling.
  156. if( ! createDMAInterrupt() )
  157. {
  158. DLOG("MacIOATA: createDMAInterrupt failed\n");
  159. return false;
  160. }
  161. // Find the interrupt source and attach it to the command gate
  162. if( ! createDeviceInterrupt() )
  163. {
  164. DLOG("MacIOATA: createDeviceInterrupts failed\n");
  165. return false;
  166. }
  167. // enable interrupt sources
  168. if( !enableInterrupt(0) /*|| !enableInterrupt(1)*/ )
  169. {
  170. DLOG("MacIOATA: enable ints failed\n");
  171. return false;
  172. }
  173. // check to see if this is a media-bay socket.
  174. OSData* nameToMatch = OSDynamicCast( OSData, provider->getProperty( "AAPL,manually-removable" ) );
  175. if ( nameToMatch != 0 )
  176. {
  177. DLOG("MacIOATA got Name property***************************************\n");
  178. isMediaBay = true;
  179. } else {
  180. DLOG("MacIOATA failed to get Name property!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!.\n");
  181. }
  182. DLOG("MacIOATA::start() done\n");
  183. return true;
  184. }
  185. /*---------------------------------------------------------------------------
  186. * free() - the pseudo destructor. Let go of what we don't need anymore.
  187. *
  188. *
  189. ---------------------------------------------------------------------------*/
  190. void
  191. MacIOATA::free()
  192. {
  193. freeDMAChannel();
  194. if( _baseAddressMap )
  195. _baseAddressMap->release();
  196. if(_dmaBaseMap)
  197. _dmaBaseMap->release();
  198. if(_DMACursor)
  199. _DMACursor->release();
  200. if(_dmaIntSrc)
  201. _dmaIntSrc->release();
  202. if(_devIntSrc)
  203. _devIntSrc->release();
  204. super::free();
  205. DLOG( "MacIOATA freed.\n");
  206. }
  207. #pragma mark -initialization-
  208. /*---------------------------------------------------------------------------
  209. *
  210. * Initialize the taskfile pointers to the addresses of the ATA registers
  211. * in the MacIO chip.
  212. *
  213. ---------------------------------------------------------------------------*/
  214. bool
  215. MacIOATA::configureTFPointers(void)
  216. {
  217. DLOG("MacIOATA configureTFPointers begin\n");
  218. // get the task file pointers
  219. _baseAddressMap = _provider->mapDeviceMemoryWithIndex(0);
  220. if( !_baseAddressMap )
  221. {
  222. DLOG("MacIOATA no base map\n");
  223. return false;
  224. }
  225. volatile UInt8* baseAddress = (volatile UInt8*)_baseAddressMap->getVirtualAddress();
  226. if( !baseAddress )
  227. {
  228. DLOG("MacIOATA no base address\n");
  229. return false;
  230. }
  231. // setup the taskfile pointers inherited from the superclass
  232. // this allows IOATAController to scan for drives during it's start()
  233. _tfDataReg = (volatile UInt16*) (baseAddress + 0x00);
  234. _tfFeatureReg = baseAddress + 0x10;
  235. _tfSCountReg = baseAddress + 0x20;
  236. _tfSectorNReg = baseAddress + 0x30;
  237. _tfCylLoReg = baseAddress + 0x40;
  238. _tfCylHiReg = baseAddress + 0x50;
  239. _tfSDHReg = baseAddress + 0x60;
  240. _tfStatusCmdReg = baseAddress + 0x70;
  241. _tfAltSDevCReg = baseAddress + 0x160;
  242. _timingConfigReg = (volatile UInt32*) (baseAddress + 0x200);
  243. DLOG("MacIOATA baseAdress = %lx\n", baseAddress);
  244. DLOG("MacIOATA configureTFPointers end\n");
  245. return true;
  246. }
  247. /*---------------------------------------------------------------------------
  248. *
  249. * allocate memory and resources for the DMA descriptors.
  250. *
  251. *
  252. ---------------------------------------------------------------------------*/
  253. bool
  254. MacIOATA::allocDMAChannel(void)
  255. {
  256. // map the DMA channel control registers into our address space.
  257. _dmaBaseMap = _provider->mapDeviceMemoryWithIndex(1);
  258. if( !_dmaBaseMap )
  259. {
  260. DLOG("MacIOATA no DMA map\n");
  261. return false;
  262. }
  263. // map into the logical address space of the kernel
  264. _dmaControlReg = (volatile IODBDMAChannelRegisters*)_dmaBaseMap->getVirtualAddress();
  265. if( !_dmaControlReg )
  266. {
  267. DLOG("MacIOATA no DMA address\n");
  268. return false;
  269. }
  270. // Now allocate a playground for channel descriptors
  271. // under ATA-5 and earlier, ATA commands are allowed a maximum of 256 * 512 byte
  272. // sectors on a single command. This works out to 1 + 32 * 4096 byte chunks of physical
  273. // memory if the page size is 4K and the memory is completely fragmented,
  274. // so we need a total of 33 descriptors, plus a stop and NO-OP command with
  275. // to generate the interrupt. This allows for full transfers without any pauses
  276. // to regenerate a DMA chain.
  277. // allocate 35 descriptors 33 memory commands + 1 No Op, + 1 Stop.
  278. // IODBDMA-Start panics unless memory is aligned on 0x10
  279. _descriptors = (IODBDMADescriptor*)IOMallocContiguous( sizeof(IODBDMADescriptor) * kATAMaxDMADesc,
  280. 0x10,
  281. &_descriptorsPhysical );
  282. if( ! _descriptors )
  283. {
  284. DLOG("MacIOATA alloc descriptors failed\n");
  285. return false;
  286. }
  287. _DMACursor = IODBDMAMemoryCursor::withSpecification(0xFFFE, /*64K - 2*/
  288. kMaxATAXfer /* Maybe should be unlimited? */
  289. /*inAlignment - byte aligned by default*/);
  290. if( ! _DMACursor )
  291. {
  292. DLOG("MacIOATA alloc DMACursor failed\n");
  293. return false;
  294. }
  295. // fill the chain with stop commands to initialize it.
  296. initATADMAChains(_descriptors);
  297. return true;
  298. }
  299. /*---------------------------------------------------------------------------
  300. *
  301. * deallocate memory and resources for the DMA descriptors.
  302. *
  303. *
  304. ---------------------------------------------------------------------------*/
  305. bool
  306. MacIOATA::freeDMAChannel(void)
  307. {
  308. if( _descriptors )
  309. {
  310. // make sure the engine is stopped
  311. stopDMA();
  312. // free the descriptor table.
  313. IOFreeContiguous( (void*) _descriptors,
  314. sizeof(IODBDMADescriptor) * kATAMaxDMADesc);
  315. }
  316. return true;
  317. }
  318. /*---------------------------------------------------------------------------
  319. *
  320. * connect the device (drive) interrupt to our workloop
  321. *
  322. *
  323. ---------------------------------------------------------------------------*/
  324. bool
  325. MacIOATA::createDeviceInterrupt(void)
  326. {
  327. // create a device interrupt source and attach it to the work loop
  328. _devIntSrc = IOInterruptEventSource::
  329. interruptEventSource( (OSObject *)this,
  330. (IOInterruptEventAction) &MacIOATA::deviceInterruptOccurred, _provider, 0);
  331. if( !_devIntSrc || _workLoop->addEventSource(_devIntSrc) )
  332. {
  333. DLOG("MacIOATA failed create dev intrpt source\n");
  334. return false;
  335. }
  336. _devIntSrc->enable();
  337. return true;
  338. }
  339. /*---------------------------------------------------------------------------
  340. *
  341. * static "action" function to connect to our object
  342. *
  343. ---------------------------------------------------------------------------*/
  344. void
  345. MacIOATA::deviceInterruptOccurred(OSObject * owner, IOInterruptEventSource *evtSrc, int count)
  346. {
  347. MacIOATA* self = (MacIOATA*) owner;
  348. self->handleDeviceInterrupt();
  349. }
  350. /*---------------------------------------------------------------------------
  351. *
  352. * connect the DMA interrupt to our workloop.
  353. *
  354. *
  355. ---------------------------------------------------------------------------*/
  356. bool
  357. MacIOATA::createDMAInterrupt(void)
  358. {
  359. // create a dma interrupt source and attach it to the work loop
  360. _dmaIntSrc = IOInterruptEventSource::
  361. interruptEventSource( (OSObject *)this,
  362. (IOInterruptEventAction) &MacIOATA::dmaInterruptOccurred,
  363. (IOService *) _provider,
  364. 1 ); // index 1 is the DMA interrupt.
  365. if( !_dmaIntSrc || _workLoop->addEventSource(_dmaIntSrc) )
  366. {
  367. DLOG("MacIOATA failed create dma intrp source\n");
  368. return false;
  369. }
  370. _dmaIntSrc->enable();
  371. return true;
  372. }
  373. /*---------------------------------------------------------------------------
  374. *
  375. * static "action" function to connect to our object
  376. *
  377. ---------------------------------------------------------------------------*/
  378. void
  379. MacIOATA::dmaInterruptOccurred(OSObject * owner, IOInterruptEventSource * evtSrc, int count)
  380. {
  381. MacIOATA* self = (MacIOATA*) owner;
  382. self->processDMAInterrupt( );
  383. }
  384. #pragma mark -DMA Interface-
  385. /*---------------------------------------------------------------------------
  386. *
  387. * Subclasses should take necessary action to create DMA channel programs,
  388. * for the current memory descriptor in _currentCommand and activate the
  389. * the DMA hardware
  390. ---------------------------------------------------------------------------*/
  391. IOReturn
  392. MacIOATA::startDMA( void )
  393. {
  394. IOReturn err = kATANoErr;
  395. // first make sure the engine is stopped.
  396. stopDMA();
  397. // reality check the memory descriptor in the current command
  398. // state flag
  399. _dmaState = kATADMAStarting;
  400. // create the channel commands
  401. err = createChannelCommands();
  402. if( err )
  403. {
  404. DLOG("MacIOATA error createChannelCmds err = %ld\n", (long int)err);
  405. return err;
  406. }
  407. // fire the engine
  408. activateDMAEngine();
  409. return err;
  410. }
  411. /*---------------------------------------------------------------------------
  412. * Subclasses should take all actions necesary to safely shutdown DMA engines
  413. * in any state of activity, whether finished, pending or stopped. Calling
  414. * this function must be harmless reguardless of the state of the engine.
  415. *
  416. ---------------------------------------------------------------------------*/
  417. IOReturn
  418. MacIOATA::stopDMA( void )
  419. {
  420. if(_dmaState != kATADMAInactive)
  421. shutDownATADMA();
  422. _dmaState = kATADMAInactive;
  423. return kATANoErr;
  424. }
  425. #pragma mark -DMA Implementation-
  426. //----------------------------------------------------------------------------------------
  427. // Function: InitATADMAChains
  428. // Description: Initializes the chains with STOP commands.
  429. //
  430. // Input: Pointer to the DBDMA descriptor area: descPtr
  431. //
  432. // Output: None
  433. //----------------------------------------------------------------------------------------
  434. void
  435. MacIOATA::initATADMAChains (IODBDMADescriptor* descPtr)
  436. {
  437. int i;
  438. /* Initialize the data-transfer DBDMA channel command descriptors. */
  439. /* These descriptors are altered to specify the desired transfer. */
  440. for (i = 0; i < kATAMaxDMADesc; i++)
  441. {
  442. IOMakeDBDMADescriptor( descPtr,
  443. kdbdmaStop,
  444. kdbdmaKeyStream0,
  445. kdbdmaIntNever,
  446. kdbdmaBranchNever,
  447. kdbdmaWaitNever,
  448. 0,
  449. 0);
  450. descPtr++;
  451. }
  452. }
  453. /*---------------------------------------------------------------------------
  454. *
  455. * Process the DMA interrupt. We are either done, need more DMA, or an error
  456. * occurred
  457. *
  458. ---------------------------------------------------------------------------*/
  459. void
  460. MacIOATA::processDMAInterrupt (void)
  461. {
  462. if( isBusOnline == false)
  463. {
  464. return;
  465. }
  466. if( _dmaIntExpected == false )
  467. {
  468. DLOG("MacIOATA DMA Int not expected\n");
  469. return;
  470. }
  471. // Make certain that the DMA state flags are consistent with machine state.
  472. _dmaIntExpected = false;
  473. // Bytes transferred by this DMA pass
  474. IOByteCount byteCount = 0;
  475. /* DMA is either finished or has erred. Decide which. */
  476. switch (_dmaState)
  477. {
  478. case kATADMAStatus:
  479. case kATADMAActive:
  480. //ATARecordEventMACRO(kAIMTapeName,'DMA ','stat','act1');
  481. /* DMA is running and we've gotten an interrupt. Check result. */
  482. if (scanATADMAChain(&byteCount))
  483. /* ataDmaState may be altered by ScanATADMAChain. */
  484. break; /* out of switch. Status is able to be interpreted. */
  485. default:
  486. /* We weren't expecting this interrupt, or the hardware shouldn't have sent it. */
  487. ATARecordEventMACRO('MacI','DMA ','Uxpt','Intr');
  488. shutDownATADMA();
  489. _dmaState = kATADMAError;
  490. return;
  491. break;
  492. }
  493. // update the actual byte count for this pass.
  494. _currentCommand->setActualTransfer(_currentCommand->getActualTransfer() + byteCount);
  495. /* Now the deciphering of the results of the data transfer: A valid interrupt
  496. * has occurred for one of 3 cases: 1) Fatal DMA error, 2) end of DMA, 3) more
  497. * DMA required.
  498. */
  499. switch (_dmaState)
  500. {
  501. case kATADMAActive:
  502. /*
  503. * DMA transfer only partially complete. The current chain of descriptors
  504. * (CCs) has completed correctly. Additional transfer needed.
  505. * Note: Clearing the DBDMA "run" bit has the effect of clearing
  506. * internal data FIFOs. To prevent data loss on multi-pass DMA operations,
  507. * DMA must not be stopped until the entire I/O is complete.
  508. */
  509. if (createChannelCommands())
  510. {
  511. ATARecordEventMACRO('MacI','DMA ','chan','err1');
  512. /* An OSErr has been reported - likely from a memory manager call. */
  513. _dmaState = kATADMAError; /* Take the blame for now. */
  514. return;
  515. }
  516. ATARecordEventMACRO('MacI',' DMA','rest','art.');
  517. //start the engine for another DMA pass.
  518. activateDMAEngine();
  519. break;
  520. case kATADMAStatus:
  521. /* Flag the DMA transfer as completed. */
  522. ATARecordEventMACRO('MacI','DMA ','stat','good');
  523. _dmaState = kATADMAComplete;
  524. stopDMA ();
  525. // may need some handling here in the event that the DMA int arrives
  526. // after the device interrupt.
  527. break;
  528. case kATADMAError:
  529. /*
  530. * The drive is expecting additional data transfer, but the DMA has croaked.
  531. * For now, let the device interrupt timeout happen.
  532. */
  533. ATARecordEventMACRO('MacI','DMA ','chan','err2');
  534. stopDMA ();
  535. break;
  536. default:
  537. break;
  538. }
  539. // if we meet a certain edge case condition, the drive may have emptied it's data
  540. // into the controller's fifo, but the DMA engine has not written data into system
  541. // memory yet, the drive may assert IRQ prior to the DMA engine. In this case, we defer the
  542. // handling of the device interrupt until the DMA engine signals completion.
  543. if( _resyncInterrupts == true )
  544. {
  545. _resyncInterrupts = false;
  546. handleDeviceInterrupt();
  547. }
  548. }
  549. void
  550. MacIOATA::stopDMAEngine(void)
  551. {
  552. /* Not doing DMA any more. Set up to ignore any DMA interrupts. */
  553. /* Leave other bits intact for error detection. */
  554. IODBDMAStop(_dmaControlReg);
  555. //IOSetDBDMAChannelControl( _dmaControlReg, IOClearDBDMAChannelControlBits(kdbdmaRun));
  556. //while (IOGetDBDMAChannelStatus(_dmaControlReg) & kdbdmaActive)
  557. // {;}
  558. }
  559. /*----------------------------------------------------------------------------------------
  560. // Function: activateDMAEngine
  561. // Description: Activate the DBDMA on the ATA bus associated with current device.
  562. engine will begin executing the command chain already programmed.
  563. // Input: None
  564. // Output: None
  565. //----------------------------------------------------------------------------------------*/
  566. void
  567. MacIOATA::activateDMAEngine(void)
  568. {
  569. if( IOGetDBDMAChannelStatus( _dmaControlReg) & kdbdmaActive )
  570. {
  571. /* For multiple DMA chain execution, don't stop the DMA or the FIFOs lose data.*/
  572. /* If DMA is active already (stray from an error?), shut it down cleanly. */
  573. shutDownATADMA();
  574. }
  575. IOSetDBDMACommandPtr( _dmaControlReg, (unsigned int) _descriptorsPhysical);
  576. /* Blastoff! */
  577. //ATARecordEventMACRO(kAIMTapeName,' dma','true','StDM');
  578. _dmaIntExpected = true;
  579. // IODBDMAStart will flush the FIFO by clearing the run-bit, causing multiple chain execution
  580. // to fail by losing whatever bytes may have accumulated in the ATA fifo.
  581. //IODBDMAStart(_dmaControlReg, (volatile IODBDMADescriptor *)_descriptorsPhysical);
  582. IOSetDBDMAChannelControl(_dmaControlReg, IOSetDBDMAChannelControlBits( kdbdmaRun | kdbdmaWake));
  583. }
  584. void
  585. MacIOATA::shutDownATADMA (void)
  586. {
  587. //ATARecordEventMACRO(kAIMTapeName,'Shut','Down',' DMA');
  588. // Disable interrupts while we flush the chain
  589. _dmaIntSrc->disable();
  590. stopDMAEngine();
  591. // Make certain that the DMA state flags are consistent with machine state.
  592. _dmaIntExpected = false;
  593. // set the state semaphore
  594. _dmaState = kATADMAInactive;
  595. // Reenable interrupts
  596. _dmaIntSrc->enable();
  597. }
  598. /*---------------------------------------------------------------------------
  599. *
  600. * create the DMA channel commands.
  601. *
  602. *
  603. ---------------------------------------------------------------------------*/
  604. IOReturn
  605. MacIOATA::createChannelCommands(void)
  606. {
  607. IOMemoryDescriptor* descriptor = _currentCommand->getBuffer();
  608. if( ! descriptor )
  609. {
  610. DLOG("drvMacIO nil buffer!\n");
  611. return -1;
  612. }
  613. // calculate remaining bytes in this transfer
  614. IOByteCount bytesRemaining = _currentCommand->getByteCount()
  615. - _currentCommand->getActualTransfer();
  616. // calculate position pointer
  617. IOByteCount xfrPosition = _currentCommand->getPosition() +
  618. _currentCommand->getActualTransfer();
  619. IOByteCount transferSize = 0;
  620. // have the DMA cursor fill out the addresses in the CC table
  621. // it will return the number of descriptors consumed.
  622. UInt32 segmentCount = _DMACursor->getPhysicalSegments(
  623. descriptor,
  624. xfrPosition,
  625. _descriptors,
  626. kATAXferDMADesc,
  627. bytesRemaining, // limit to the requested number of bytes in the event the descriptors is larger
  628. &transferSize);
  629. if( transferSize > bytesRemaining)
  630. {
  631. DLOG("drvMacIO DMA too long!!!\n");
  632. return -1;
  633. }
  634. if( segmentCount == 0)
  635. {
  636. DLOG("drvMacIO seg count 0!!!\n");
  637. return -1;
  638. }
  639. // check if the xfer satisfies the needed size
  640. if( transferSize < bytesRemaining )
  641. {
  642. // indicate we need to do more DMA when the interrupt happens
  643. _dmaState = kATADMAActive;
  644. DLOG("MacIOATA will make two passes\n");
  645. } else {
  646. // transfer is satisfied and only need to check status on interrupt.
  647. _dmaState = kATADMAStatus;
  648. DLOG("MacIOATA will make one pass\n");
  649. }
  650. UInt32 command = kdbdmaOutputMore;
  651. if( _currentCommand->getFlags() & mATAFlagIORead)
  652. {
  653. command = kdbdmaInputMore;
  654. }
  655. DLOG("MacIOATA making CC chain for %ld segs for xfersize %ld\n", segmentCount, transferSize);
  656. // now walk the descriptor chain and insert the commands
  657. for( UInt32 i = 0; i < segmentCount; i++)
  658. {
  659. IODBDMADescriptor* currDesc = & (_descriptors[i]);
  660. UInt32 addr = IOGetCCAddress(currDesc);
  661. UInt32 count = IOGetCCOperation(currDesc) & kdbdmaReqCountMask;
  662. OSSynchronizeIO();
  663. IOMakeDBDMADescriptor(currDesc,
  664. command,
  665. kdbdmaKeyStream0,
  666. kdbdmaIntNever,
  667. kdbdmaBranchNever,
  668. kdbdmaWaitNever,
  669. count,
  670. addr);
  671. DLOG("macIOATA desc# %ld at %x \n", i, currDesc );
  672. DLOG("addr = %lx count = %lx \n", addr, count );
  673. DLOG("%lx %lx %lx %lx\n", currDesc->operation, currDesc->address ,currDesc->cmdDep ,currDesc->result );
  674. }
  675. // insert a NOP + interrupt. after the last data command
  676. IOMakeDBDMADescriptor(&(_descriptors[segmentCount]),
  677. kdbdmaNop,
  678. kdbdmaKeyStream0,
  679. kdbdmaIntAlways,
  680. kdbdmaBranchNever,
  681. kdbdmaWaitNever,
  682. 0,
  683. 0);
  684. // insert a stop after the NOP command
  685. IOMakeDBDMADescriptor(&(_descriptors[segmentCount + 1]),
  686. kdbdmaStop,
  687. kdbdmaKeyStream0,
  688. kdbdmaIntNever,
  689. kdbdmaBranchNever,
  690. kdbdmaWaitNever,
  691. 0,
  692. 0);
  693. // chain is now ready for execution.
  694. return kATANoErr;
  695. }
  696. bool
  697. MacIOATA::scanATADMAChain (IOByteCount* byteCount)
  698. {
  699. volatile IODBDMADescriptor* descPtr = _descriptors;
  700. bool validState = true;
  701. *byteCount = 0; /* No bytes confirmed this DMA pass. */
  702. UInt32 descIndex = 0;
  703. /*
  704. * Parse the chain for completion status. Normal completion is
  705. * indicated by all expected CC status words contain just the
  706. * "run" and "active" bits, indicating that the DMA has executed the
  707. * chain element and updated the status.
  708. */
  709. while ((IOGetCCOperation(descPtr) & kdbdmaCmdMask) != STOP_CMD)
  710. {
  711. /* For speed, check the normal case - "run" and "active" bits and residual count == 0 */
  712. if ( (IOGetCCResult(descPtr) & 0x8C000000) == 0x84000000 )
  713. {
  714. /* The DMA has completed this channel command.*/
  715. *byteCount += (IOGetCCOperation(descPtr) & 0x0000FFFF); // low 16 bits are request count
  716. descPtr++; /* Advance pointer to the next DMA command */
  717. descIndex++;
  718. continue;
  719. }
  720. /* Get here if something's wrong with DMA execution. See whether hardware
  721. * is telling us something directly, or whether something amiss is noted
  722. * in the status written to memory.
  723. */
  724. if ((IOGetDBDMAChannelStatus(_dmaControlReg) & kdbdmaStatusDead) || ((IOGetCCResult(descPtr) & kdbdmaStatusRun)))
  725. {
  726. /*
  727. * Dead means fatal DMA error - hardware claims it failed. Report error
  728. * if dead or if the DMA was running when the interrupt occurred.
  729. */
  730. DLOG("MacIOATA DMA error state\n");
  731. DLOG("MacIOATA desc# %ld byte count %ld\n",descIndex, *byteCount);
  732. DLOG("ChanStat= %lx CCResult= %lx\n", IOGetDBDMAChannelStatus(_dmaControlReg), IOGetCCResult(descPtr) );
  733. _dmaState = kATADMAError;
  734. break; /* out of do/while loop */
  735. } else {
  736. /*
  737. * The DMA status indicates that command descriptor execution is not
  738. * responsible for the interrupt. Another case to ignore.
  739. */
  740. DLOG("MacIOATA DMA Invalid state\n");
  741. validState = false;
  742. break; /* Ignore the interrupt */
  743. }
  744. } /* end while !STOP_CMD */
  745. /* Return to caller, indicating whether dmaState is valid. */
  746. DLOG("MacIOATA desc# %ld byte count %ld\n",descIndex, *byteCount);
  747. return validState;
  748. }
  749. /*---------------------------------------------------------------------------
  750. *
  751. * handleDeviceInterrupt - overriden here so we can make sure that the DMA has
  752. * processed in the event the interrupts arrive out of order for some reason.
  753. *
  754. ---------------------------------------------------------------------------*/
  755. IOReturn
  756. MacIOATA::handleDeviceInterrupt(void)
  757. {
  758. if( isBusOnline == false)
  759. {
  760. return kIOReturnOffline;
  761. }
  762. // if we meet a certain edge case condition, the drive may have emptied it's data
  763. // into the controller's fifo, but the DMA engine has not written data into system
  764. // memory yet, the drive may assert IRQ prior to the DMA engine. In this case, we defer the
  765. // handling of the device interrupt until the DMA engine signals completion.
  766. if( _dmaIntExpected == true
  767. && _currentCommand->state == IOATAController::kATAStatus)
  768. {
  769. DLOG("MacIOATA, DMA int out of order\n");
  770. // read the device's status register in order to clear the IRQ assertion
  771. volatile UInt8 status = *_tfStatusCmdReg;
  772. OSSynchronizeIO();
  773. //if an error or check condition bit is set then DMA isn't going to happen at this
  774. // point. go ahead and allow the superclass to process it.
  775. if( status & 0x01 )
  776. {
  777. return super::handleDeviceInterrupt();
  778. }
  779. _resyncInterrupts = true;
  780. return kATANoErr;
  781. }
  782. return super::handleDeviceInterrupt();
  783. }
  784. /*---------------------------------------------------------------------------
  785. *
  786. * handleDeviceInterrupt - overriden here to allow for reporting of DMA errs
  787. *
  788. ---------------------------------------------------------------------------*/
  789. IOReturn
  790. MacIOATA::asyncStatus(void)
  791. {
  792. IOReturn err = super::asyncStatus();
  793. if( _dmaState == kATADMAError)
  794. {
  795. err = kATADMAErr;
  796. }
  797. return err;
  798. }
  799. /*---------------------------------------------------------------------------
  800. *
  801. * handleDeviceInterrupt - overriden here to allow clean up of DMA resyncInterrupt flag
  802. *
  803. ---------------------------------------------------------------------------*/
  804. void
  805. MacIOATA::handleTimeout( void )
  806. {
  807. if( isBusOnline == false)
  808. {
  809. return;
  810. }
  811. _resyncInterrupts = false;
  812. super::handleTimeout();
  813. }
  814. // media bay support
  815. IOReturn
  816. MacIOATA::message (UInt32 type, IOService* provider, void* argument)
  817. {
  818. switch( type )
  819. {
  820. case kATARemovedEvent:
  821. DLOG( "MacIOATA got removed event.\n");
  822. // mark the bus as dead.
  823. if(isBusOnline == true)
  824. {
  825. isBusOnline = false;
  826. // lock the queue, don't dispatch immediates or anything else.
  827. _queueState = IOATAController::kQueueLocked;
  828. // disable the interrupt source(s) and timers
  829. _dmaIntSrc->disable();
  830. _devIntSrc->disable();
  831. stopTimer();
  832. _workLoop->removeEventSource(_dmaIntSrc);
  833. _workLoop->removeEventSource(_devIntSrc);
  834. _workLoop->removeEventSource(_timer);
  835. //_provider->unregisterInterrupt(0);
  836. //_provider->unregisterInterrupt(1);
  837. // flush any commands in the queue
  838. handleQueueFlush();
  839. // if there's a command active then call through the command gate
  840. // and clean it up from inside the workloop.
  841. //
  842. if( _currentCommand != 0)
  843. {
  844. DLOG( "MacIOATA Calling cleanup bus.\n");
  845. _cmdGate->runAction( (IOCommandGate::Action)
  846. &MacIOATA::cleanUpAction,
  847. 0, // arg 0
  848. 0, // arg 1
  849. 0, 0); // arg2 arg 3
  850. }
  851. _workLoop->removeEventSource(_cmdGate);
  852. DLOG( "MacIOATA notify the clients.\n");
  853. terminate();
  854. }
  855. break;
  856. default:
  857. DLOG( "MacIOATA got some other event = %d\n", (int) type);
  858. return super::message(type, provider, argument);
  859. break;
  860. }
  861. return kATANoErr;
  862. }
  863. /*---------------------------------------------------------------------------
  864. *
  865. *
  866. *
  867. *
  868. ---------------------------------------------------------------------------*/
  869. IOReturn
  870. MacIOATA::handleQueueFlush( void )
  871. {
  872. UInt32 savedQstate = _queueState;
  873. _queueState = IOATAController::kQueueLocked;
  874. IOReturn errPerCommand = kIOReturnError;
  875. if( isBusOnline == false )
  876. {
  877. errPerCommand = kIOReturnOffline;
  878. }
  879. IOATABusCommand* cmdPtr = 0;
  880. while( cmdPtr = dequeueFirstCommand() )
  881. {
  882. cmdPtr->setResult(errPerCommand);
  883. cmdPtr->executeCallback();
  884. }
  885. _queueState = savedQstate;
  886. return kATANoErr;
  887. }
  888. /*---------------------------------------------------------------------------
  889. *
  890. *
  891. *
  892. *
  893. ---------------------------------------------------------------------------*/
  894. bool
  895. MacIOATA::checkTimeout( void )
  896. {
  897. if( isBusOnline == false )
  898. {
  899. // signal a timeout if we are within the workloop
  900. return true;
  901. }
  902. return super::checkTimeout();
  903. }
  904. /*---------------------------------------------------------------------------
  905. *
  906. * The main call which puts something on the work loop
  907. *
  908. ---------------------------------------------------------------------------*/
  909. IOReturn
  910. MacIOATA::executeCommand(IOATADevice* nub, IOATABusCommand* command)
  911. {
  912. if( isBusOnline == false)
  913. {
  914. return kIOReturnOffline;
  915. }
  916. return super::executeCommand(nub, command);
  917. }
  918. // called through the commandGate when I get a notification that a media bay has gone away
  919. void
  920. MacIOATA::cleanUpAction(OSObject * owner,
  921. void * arg0,
  922. void * arg1,
  923. void * /* arg2 */,
  924. void * /* arg3 */)
  925. {
  926. MacIOATA* self = (MacIOATA*) owner;
  927. self->cleanUpBus();
  928. }
  929. void
  930. MacIOATA::cleanUpBus(void)
  931. {
  932. if( _currentCommand != 0)
  933. {
  934. _currentCommand->setResult(kIOReturnOffline);
  935. _currentCommand->executeCallback();
  936. _currentCommand = 0;
  937. }
  938. }
  939. IOReturn
  940. MacIOATA::handleBusReset(void)
  941. {
  942. // if( _devIntSrc )
  943. // _devIntSrc->disable();
  944. IOReturn result = super::handleBusReset();
  945. // if( _devIntSrc )
  946. // _devIntSrc->enable();
  947. return result;
  948. }
  949. #endif // __ppc__