1/* 2 * Copyright (c) 2000-2008 Apple Inc. All rights reserved. 3 * 4 * @APPLE_LICENSE_HEADER_START@ 5 * 6 * This file contains Original Code and/or Modifications of Original Code 7 * as defined in and that are subject to the Apple Public Source License 8 * Version 2.0 (the 'License'). You may not use this file except in 9 * compliance with the License. Please obtain a copy of the License at 10 * http://www.opensource.apple.com/apsl/ and read it before using this 11 * file. 12 * 13 * The Original Code and all software distributed under the License are 14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER 15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, 16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, 17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. 18 * Please see the License for the specific language governing rights and 19 * limitations under the License. 20 * 21 * @APPLE_LICENSE_HEADER_END@ 22 */ 23// BSD includes 24#include <sys/sysctl.h> 25 26// IOKit includes 27#include <libkern/OSAtomic.h> 28#include <IOKit/IOMemoryDescriptor.h> 29#include <IOKit/IOCommandGate.h> 30#include <IOKit/IOWorkLoop.h> 31#include <IOKit/IOKitKeys.h> 32#include <IOKit/ata/IOATATypes.h> 33#include <IOKit/ata/IOATADevConfig.h> 34#include <IOKit/ata/IOATABusInfo.h> 35#include <IOKit/ata/IOATACommand.h> 36#include <IOKit/scsi/SCSICommandOperationCodes.h> 37#include <IOKit/scsi/SCSITask.h> 38#include <IOKit/scsi/SCSITaskDefinition.h> // Remove me when API is available for IsAutosenseRequested() 39 40#include "IOATAPIProtocolTransport.h" 41#include "IOATAPIProtocolTransportTimeStamps.h" 42#include "IOATAPIProtocolTransportDebugging.h" 43 44#include <IOKit/storage/ata/IOATAFamilyPriv.h> 45#include <IOKit/IOTimeStamp.h> 46 47 48#define ATAPI_PROTOCOL_TRANSPORT_DEBUGGING_LEVEL 0 49 50#if ( ATAPI_PROTOCOL_TRANSPORT_DEBUGGING_LEVEL >= 1 ) 51#define PANIC_NOW(x) IOPanic x 52#else 53#define PANIC_NOW(x) 54#endif 55 56#if ( ATAPI_PROTOCOL_TRANSPORT_DEBUGGING_LEVEL >= 2 ) 57#define ERROR_LOG(x) IOLog x 58#else 59#define ERROR_LOG(x) 60#endif 61 62#if ( ATAPI_PROTOCOL_TRANSPORT_DEBUGGING_LEVEL >= 3 ) 63#define STATUS_LOG(x) IOLog x 64#else 65#define STATUS_LOG(x) 66#endif 67 68#define DEBUG_UNUSED( X ) ( void )( X ) 69 70 71// Timeout values used by the ATAPI Driver 72enum 73{ 74 kNoTimeout = 0, // Constant to indicate no timeout 75 k1SecondTimeout = 1000, // 1000 mS = 1 Sec 76 k10SecondTimeout = 10 * k1SecondTimeout, 77 k30SecondTimeout = 3 * k10SecondTimeout, 78 k45SecondTimeout = 45000, 79 k100Milliseconds = 100 80}; 81 82enum 83{ 84 kMaxATAPIPacketSize = 16, // Max ATAPI packet size 85 kATAPICommandLength = 12, // ATAPI command length 86 kATAPIIdentifyPacketDeviceDataSize = 512 // 512 byte identify data 87}; 88 89enum 90{ 91 kATAPICheckConditionBit = 0, 92 kATAPIDeviceBusyBit = 8 93}; 94 95enum 96{ 97 kATAPICheckConditionMask = ( 1 << kATAPICheckConditionBit ), 98 kATAPIDeviceBusyMask = ( 1 << kATAPIDeviceBusyBit ) 99}; 100 101// Configuration state machine 102enum 103{ 104 kPIOTransferModeSetup = 1, 105 kPIOTransferModeDone = 2, 106 kDMATransferModeDone = 3 107}; 108 109struct ATAPIConfigData 110{ 111 IOATAPIProtocolTransport * self; 112 UInt32 state; 113 bool done; 114}; 115typedef struct ATAPIConfigData ATAPIConfigData; 116 117#define kIOATAPICommandPoolSize 1 118 119enum 120{ 121 kATAPICommandBusyBit = 0, 122 kATAPIRequestSenseNeededBit = 1 123}; 124 125enum 126{ 127 kATAPICommandBusyMask = ( 1 << kATAPICommandBusyBit ), 128 kATAPIRequestSenseNeededMask = ( 1 << kATAPIRequestSenseNeededBit ) 129}; 130 131enum 132{ 133 kODDMediaNotifyValue0 = 0, 134 kODDMediaNotifyValue1 = 1 135}; 136 137#define kATAPI5SecondsInNanoseconds ( 5LL * 1000LL * 1000LL * 1000LL ) 138 139#define fSemaphore reserved->fSemaphore 140#define fMediaNotifyValue reserved->fMediaNotifyValue 141 142#define super IOSCSIProtocolServices 143OSDefineMetaClassAndStructors ( IOATAPIProtocolTransport, IOSCSIProtocolServices ); 144 145 146//----------------------------------------------------------------------------- 147// Class 148//----------------------------------------------------------------------------- 149 150class ATAPITransportGlobals 151{ 152 153public: 154 155 // Constructor 156 ATAPITransportGlobals ( void ); 157 158 // Destructor 159 virtual ~ATAPITransportGlobals ( void ); 160 161}; 162 163 164//----------------------------------------------------------------------------- 165// Prototypes 166//----------------------------------------------------------------------------- 167 168static inline void 169RecordATAPITimeStamp ( 170 unsigned int code, 171 unsigned int a = 0, unsigned int b = 0, 172 unsigned int c = 0, unsigned int d = 0 ); 173 174static int 175ATAPITransportSysctl ( 176 struct sysctl_oid * oidp, 177 void * arg1, 178 int arg2, 179 struct sysctl_req * req ); 180 181 182//----------------------------------------------------------------------------- 183// Globals 184//----------------------------------------------------------------------------- 185static ATAPITransportGlobals gATAPIGlobals; 186UInt32 gATAPIDebugFlags = 0; 187 188SYSCTL_PROC ( _debug, OID_AUTO, ATAPITransport, CTLFLAG_RW, 0, 0, ATAPITransportSysctl, "ATAPITransport", "ATAPI Transport debug interface" ); 189 190 191#pragma mark Public Methods 192 193 194//----------------------------------------------------------------------------- 195// ATAPITransportSysctl - Sysctl handler. [PRIVATE] 196//----------------------------------------------------------------------------- 197 198static int 199ATAPITransportSysctl ( struct sysctl_oid * oidp, void * arg1, int arg2, struct sysctl_req * req ) 200{ 201 202 int error = 0; 203 ATAPISysctlArgs sysctlArgs; 204 205 DEBUG_UNUSED ( oidp ); 206 DEBUG_UNUSED ( arg1 ); 207 DEBUG_UNUSED ( arg2 ); 208 209 ERROR_LOG ( ( "+ATAPITransportSysctl: gATAPIDebugFlags = 0x%08X\n", ( unsigned int ) gATAPIDebugFlags ) ); 210 211 error = SYSCTL_IN ( req, &sysctlArgs, sizeof ( sysctlArgs ) ); 212 if ( ( error == 0 ) && ( sysctlArgs.type == kATAPITypeDebug ) ) 213 { 214 215 if ( sysctlArgs.operation == kATAPIOperationGetFlags ) 216 { 217 218 sysctlArgs.debugFlags = gATAPIDebugFlags; 219 error = SYSCTL_OUT ( req, &sysctlArgs, sizeof ( sysctlArgs ) ); 220 221 } 222 223 else if ( sysctlArgs.operation == kATAPIOperationSetFlags ) 224 { 225 gATAPIDebugFlags = sysctlArgs.debugFlags; 226 } 227 228 } 229 230 STATUS_LOG ( ( "-ATAPITransportSysctl: gATAPIDebugFlags = 0x%08X\n", ( unsigned int ) gATAPIDebugFlags ) ); 231 232 return error; 233 234} 235 236 237//----------------------------------------------------------------------------- 238// Default Constructor 239//----------------------------------------------------------------------------- 240 241ATAPITransportGlobals::ATAPITransportGlobals ( void ) 242{ 243 244 int debugFlags; 245 246 STATUS_LOG ( ( "+ATAPITransportGlobals::ATAPITransportGlobals\n" ) ); 247 248 if ( PE_parse_boot_argn ( "ATAPIdisk", &debugFlags, sizeof ( debugFlags ) ) ) 249 { 250 251 gATAPIDebugFlags = debugFlags; 252 253 } 254 255 // Register our sysctl interface 256 sysctl_register_oid ( &sysctl__debug_ATAPITransport ); 257 258 STATUS_LOG ( ( "-ATAPITransportGlobals::ATAPITransportGlobals\n" ) ); 259 260} 261 262 263//----------------------------------------------------------------------------- 264// Destructor 265//----------------------------------------------------------------------------- 266 267ATAPITransportGlobals::~ATAPITransportGlobals ( void ) 268{ 269 270 STATUS_LOG ( ( "+~ATAPITransportGlobals::ATAPITransportGlobals\n" ) ); 271 272 // Unregister our sysctl interface 273 sysctl_unregister_oid ( &sysctl__debug_ATAPITransport ); 274 275 STATUS_LOG ( ( "-~ATAPITransportGlobals::ATAPITransportGlobals\n" ) ); 276 277} 278 279 280//-------------------------------------------------------------------------------------- 281// init - Initialization 282//-------------------------------------------------------------------------------------- 283 284bool 285IOATAPIProtocolTransport::init ( OSDictionary * propTable ) 286{ 287 288 STATUS_LOG ( ( "IOATAPIProtocolTransport::init entering\n" ) ); 289 290 // Run this by our superclass 291 if ( super::init ( propTable ) == false ) 292 { 293 294 STATUS_LOG ( ( "IOATAPIProtocolTransport::init superclass init returned false\n" ) ); 295 return false; 296 297 } 298 299 STATUS_LOG ( ( "IOATAPIProtocolTransport::init returning true\n" ) ); 300 301 return true; 302 303} 304 305 306//-------------------------------------------------------------------------------------- 307// start - Start our services 308//-------------------------------------------------------------------------------------- 309 310bool 311IOATAPIProtocolTransport::start ( IOService * provider ) 312{ 313 314 IOWorkLoop * workLoop = NULL; 315 OSDictionary * dict = NULL; 316 IOService * powerProvider = NULL; 317 OSNumber * mediaNotifyValue = NULL; 318 319 STATUS_LOG ( ( "IOATAPIProtocolTransport::start called\n" ) ); 320 321 fATAUnitID = kATAInvalidDeviceID; 322 fATADeviceType = kUnknownATADeviceType; 323 fPhysicallyConnected = true; 324 325 reserved = IONew ( ExpansionData, 1 ); 326 if ( reserved == NULL ) 327 { 328 return false; 329 } 330 bzero ( reserved, sizeof ( ExpansionData ) ); 331 332 dict = OSDynamicCast ( OSDictionary, getProperty ( kIOPropertyATAPIMassStorageCharacteristics ) ); 333 if ( dict != NULL ) 334 { 335 336 OSString * string = NULL; 337 338 string = OSDynamicCast ( OSString, dict->getObject ( kATAVendorPropertyKey ) ); 339 if ( string != NULL ) 340 { 341 342 const char * cString1 = NULL; 343 const char * cString2 = NULL; 344 345 cString1 = ( ( OSString * ) provider->getProperty ( kATAVendorPropertyKey ) )->getCStringNoCopy ( ); 346 cString2 = string->getCStringNoCopy ( ); 347 348 STATUS_LOG ( ( "device model = %s\n", cString1 ) ); 349 STATUS_LOG ( ( "ATAPI Device Characteristics device model = %s\n", cString2 ) ); 350 351 if ( strncmp ( cString1, cString2, string->getLength ( ) ) ) 352 { 353 354 // Not a match to what is in the dictionary, so this workaround driver 355 // should not be loaded. Short circuit out and let another driver attempt 356 // to load. 357 return false; 358 359 } 360 361 } 362 363 else 364 { 365 STATUS_LOG ( ( "ATAPI Mass Storage dictionary has no device model string\n" ) ); 366 } 367 368 } 369 370 else 371 { 372 STATUS_LOG ( ( "No ATAPI Mass Storage dictionary\n" ) ); 373 } 374 375 mediaNotifyValue = OSDynamicCast ( OSNumber, getProperty ( "media-notify", gIOServicePlane ) ); 376 377 if ( mediaNotifyValue != NULL ) 378 { 379 fMediaNotifyValue = mediaNotifyValue->unsigned32BitValue ( ); 380 } 381 382 else 383 { 384 fMediaNotifyValue = kODDMediaNotifyValue0; 385 } 386 387 // First call start() in our superclass 388 if ( super::start ( provider ) == false ) 389 return false; 390 391 // Cache our provider 392 fATADevice = OSDynamicCast ( IOATADevice, provider ); 393 if ( fATADevice == NULL ) 394 { 395 396 ERROR_LOG ( ( "Error in dynamic cast\n" ) ); 397 // Error in the dynamic cast, so get out 398 return false; 399 400 } 401 402 // Find out if the device type is ATAPI 403 if ( fATADevice->getDeviceType ( ) != ReportATAPIDeviceType ( ) ) 404 { 405 406 ERROR_LOG ( ( "exiting, not an ATAPI device.\n" ) ); 407 return false; 408 409 } 410 411 // Open the thing below us 412 if ( fATADevice->open ( this ) == false ) 413 { 414 415 ERROR_LOG ( ( "device wouldn't open\n" ) ); 416 // It wouldn't open, so bail 417 return false; 418 419 } 420 421 fATAUnitID = fATADevice->getUnitID ( ); 422 fATADeviceType = fATADevice->getDeviceType ( ); 423 424 STATUS_LOG ( ( "unit ID is %d\n", ( UInt8 ) fATAUnitID ) ); 425 STATUS_LOG ( ( "deviceType is %d\n", ( UInt8 ) fATADeviceType ) ); 426 427 RecordATAPITimeStamp ( 428 ATAPI_TRACE ( kATADeviceInfo ), 429 ( unsigned int ) ( uintptr_t ) this, 430 ( unsigned int ) fATAUnitID, 431 ( unsigned int ) fATADeviceType ); 432 433 bzero ( fDeviceIdentifyData, kATAPIIdentifyPacketDeviceDataSize ); 434 435 fDeviceIdentifyBuffer = IOMemoryDescriptor::withAddress ( ( void * ) fDeviceIdentifyData, 436 kATAPIIdentifyPacketDeviceDataSize, 437 kIODirectionIn ); 438 439 if ( fDeviceIdentifyBuffer == NULL ) 440 { 441 442 ERROR_LOG ( ( "fDeviceIdentifyBuffer == NULL.\n" ) ); 443 goto CLOSE_DEVICE_ERROR; 444 445 } 446 447 fCommandGate = GetCommandGate ( ); 448 workLoop = getWorkLoop ( ); 449 450 fCommandPool = IOCommandPool::withWorkLoop ( workLoop ); 451 if ( fCommandPool == NULL ) 452 { 453 454 ERROR_LOG ( ( "fCommandPool == NULL.\n" ) ); 455 goto RELEASE_IDENTIFY_DEVICE_BUFFER_ERROR; 456 457 } 458 459 fPollingThread = thread_call_allocate ( 460 ( thread_call_func_t ) IOATAPIProtocolTransport::sPollStatusRegister, 461 ( thread_call_param_t ) this ); 462 463 if ( fPollingThread == NULL ) 464 { 465 466 ERROR_LOG ( ( "fPollingThread allocation failed.\n" ) ); 467 goto RELEASE_COMMAND_POOL_ERROR; 468 469 } 470 471 // Pre-allocate some command objects 472 AllocateATACommandObjects ( ); 473 474 // Inspect the provider 475 if ( InspectDevice ( fATADevice ) == false ) 476 { 477 478 ERROR_LOG ( ( "InspectDevice returned false.\n" ) ); 479 goto DEALLOCATE_COMMANDS_ERROR; 480 481 } 482 483 // Initialize the power provider to default 484 powerProvider = provider; 485 powerProvider->retain ( ); 486 487 // Look to see if we are the slave device and there is a master 488 // device on the bus. 489 if ( fATAUnitID == kATADevice1DeviceID ) 490 { 491 492 IOService * obj; 493 OSIterator * iter; 494 OSNumber * deviceNumber; 495 496 STATUS_LOG ( ( "We are the slave, find a master.\n" ) ); 497 498 // We are the slave. Find a master. 499 obj = provider->getProvider ( ); 500 501 iter = obj->getChildIterator ( gIOServicePlane ); 502 if ( iter != NULL ) 503 { 504 505 STATUS_LOG ( ( "Got an iterator.\n" ) ); 506 507 while ( ( obj = ( IOService * ) iter->getNextObject ( ) ) != NULL ) 508 { 509 510 STATUS_LOG ( ( "Looping over objects.\n" ) ); 511 512 if ( obj == provider ) 513 continue; 514 515 STATUS_LOG ( ( "Check the IOUnit property.\n" ) ); 516 517 deviceNumber = OSDynamicCast ( OSNumber, obj->getProperty ( "IOUnit" ) ); 518 if ( deviceNumber != NULL ) 519 { 520 521 STATUS_LOG ( ( "Found the IOUnit property.\n" ) ); 522 523 if ( deviceNumber->unsigned8BitValue ( ) == kATADevice0DeviceID ) 524 { 525 526 IOService * possibleProvider = NULL; 527 IOReturn status = kIOReturnSuccess; 528 529 // Wait upto 5 seconds for matching to finish on master device. 530 status = obj->waitQuiet ( kATAPI5SecondsInNanoseconds ); 531 if ( status == kIOReturnTimeout ) 532 { 533 break; 534 } 535 536 // Find this object's child to get the item which is the master. 537 possibleProvider = ( IOService * ) obj->getChildEntry ( gIOServicePlane ); 538 if ( possibleProvider != NULL ) 539 { 540 541 STATUS_LOG ( ( "Found the master.\n" ) ); 542 543 // This is our new power provider. 544 powerProvider->release ( ); 545 powerProvider = possibleProvider; 546 powerProvider->retain ( ); 547 break; 548 549 } 550 551 } 552 553 } 554 555 } 556 557 iter->release ( ); 558 559 } 560 561 } 562 563 InitializePowerManagement ( powerProvider ); 564 565 powerProvider->release ( ); 566 567 STATUS_LOG ( ( "IOATAPIProtocolTransport::start complete\n" ) ); 568 569 dict = OSDictionary::withCapacity ( 1 ); 570 if ( dict != NULL ) 571 { 572 573 // Copy some properties into the dictionary. 574 dict->setObject ( kATAUnitNumberKey, fATADevice->getProperty ( kATAUnitNumberKey ) ); 575 setProperty ( kIOPropertyProtocolCharacteristicsKey, dict ); 576 dict->release ( ); 577 578 } 579 580 registerService ( ); 581 return true; 582 583 584DEALLOCATE_COMMANDS_ERROR: 585 586 DeallocateATACommandObjects ( ); 587 588 589RELEASE_COMMAND_POOL_ERROR: 590 591 if ( fCommandPool != NULL ) 592 fCommandPool->release ( ); 593 594 595RELEASE_IDENTIFY_DEVICE_BUFFER_ERROR: 596 597 if ( fDeviceIdentifyBuffer != NULL ) 598 fDeviceIdentifyBuffer->release ( ); 599 600 601CLOSE_DEVICE_ERROR: 602 603 fATADevice->close ( this ); 604 return false; 605 606} 607 608 609//-------------------------------------------------------------------------------------- 610// stop - Stop our services 611//-------------------------------------------------------------------------------------- 612 613void 614IOATAPIProtocolTransport::stop ( IOService * provider ) 615{ 616 617 STATUS_LOG ( ( "IOATAPIProtocolTransport::stop called\n" ) ); 618 619 // Call super's stop 620 super::stop ( provider ); 621 622} 623 624 625//-------------------------------------------------------------------------------------- 626// free - Called to free any resources we allocated. 627//-------------------------------------------------------------------------------------- 628 629void 630IOATAPIProtocolTransport::free ( void ) 631{ 632 633 if ( fCommandPool != NULL ) 634 { 635 636 fCommandPool->release ( ); 637 fCommandPool = NULL; 638 639 } 640 641 if ( reserved != NULL ) 642 { 643 IODelete ( reserved, ExpansionData, 1 ); 644 reserved = NULL; 645 } 646 647 if ( fPollingThread != NULL ) 648 { 649 650 thread_call_cancel ( fPollingThread ); 651 thread_call_free ( fPollingThread ); 652 fPollingThread = NULL; 653 654 } 655 656 super::free ( ); 657 658} 659 660 661#pragma mark Protected Methods 662 663 664//-------------------------------------------------------------------------------------- 665// ReportATAPIDeviceType - Report the type of the device (ATA vs. ATAPI). 666//-------------------------------------------------------------------------------------- 667 668ataDeviceType 669IOATAPIProtocolTransport::ReportATAPIDeviceType ( void ) const 670{ 671 672 return kATAPIDeviceType; 673 674} 675 676 677//-------------------------------------------------------------------------------------- 678// SendSCSICommand - Sends a SCSI Command to the provider bus 679//-------------------------------------------------------------------------------------- 680 681bool 682IOATAPIProtocolTransport::SendSCSICommand ( SCSITaskIdentifier request, 683 SCSIServiceResponse * serviceResponse, 684 SCSITaskStatus * taskStatus ) 685{ 686 687 SCSICommandDescriptorBlock cdb; 688 UInt16 commandLength = 0; 689 IOATACommand * cmd = NULL; 690 ATAPIClientData * clientData = NULL; 691 UInt16 atapiCommandLength = kATAPICommandLength; 692 UInt32 flags = 0; 693 UInt64 requestCount = 0; 694 UInt32 timeoutDuration = 0; 695 bool shouldUseDMA = true; 696 697 STATUS_LOG ( ( "IOATAPIProtocolTransport::SendSCSICommand called\n" ) ); 698 699 if ( OSBitOrAtomic ( kATAPICommandBusyMask, &fSemaphore ) & kATAPICommandBusyMask ) 700 { 701 STATUS_LOG ( ( "Command in use, returning false\n" ) ); 702 703 RecordATAPITimeStamp ( 704 ATAPI_TRACE ( kATASendSCSICommandFailed ), 705 ( unsigned int ) ( uintptr_t ) this, 706 ( unsigned int ) fATAUnitID, 707 ( unsigned int ) ( uintptr_t ) request ); 708 709 return false; 710 } 711 712 if ( fSemaphore & kATAPIRequestSenseNeededMask ) 713 { 714 715 STATUS_LOG ( ( "kATAPIRequestSenseNeededMask set\n" ) ); 716 717 if ( GetTaskExecutionMode ( request ) != kSCSITaskMode_Autosense ) 718 { 719 720 STATUS_LOG ( ( "Not an autosense command, returning false.\n" ) ); 721 OSBitAndAtomic ( ~kATAPICommandBusyMask, &fSemaphore ); 722 723 RecordATAPITimeStamp ( 724 ATAPI_TRACE ( kATASendSCSICommandFailed ), 725 ( unsigned int ) ( uintptr_t ) this, 726 ( unsigned int ) fATAUnitID, 727 ( unsigned int ) ( uintptr_t ) request ); 728 729 return false; 730 731 } 732 733 STATUS_LOG ( ( "Clearing kATAPIRequestSenseNeededMask.\n" ) ); 734 OSBitAndAtomic ( ~kATAPIRequestSenseNeededMask, &fSemaphore ); 735 736 } 737 738 // get command and context objects 739 cmd = GetATACommandObject ( ); 740 741 clientData = ( ATAPIClientData * ) cmd->refCon; 742 *serviceResponse = kSCSIServiceResponse_Request_In_Process; 743 *taskStatus = kSCSITaskStatus_No_Status; 744 745 RecordATAPITimeStamp ( 746 ATAPI_TRACE ( kATASendSCSICommand ), 747 ( unsigned int ) ( uintptr_t ) this, 748 ( unsigned int ) fATAUnitID, 749 ( unsigned int ) ( uintptr_t ) cmd, 750 ( unsigned int ) ( uintptr_t ) request ); 751 752 if ( fPhysicallyConnected == false ) 753 { 754 755 // device is disconnected - we can not service command request 756 *serviceResponse = kSCSIServiceResponse_SERVICE_DELIVERY_OR_TARGET_FAILURE; 757 ReturnATACommandObject ( cmd ); 758 OSBitAndAtomic ( ~kATAPICommandBusyMask, &fSemaphore ); 759 760 RecordATAPITimeStamp ( 761 ATAPI_TRACE ( kATASendSCSICommandFailed ), 762 ( unsigned int ) ( uintptr_t ) this, 763 ( unsigned int ) fATAUnitID, 764 ( unsigned int ) ( uintptr_t ) request ); 765 766 return false; 767 768 } 769 770 GetCommandDescriptorBlock ( request, &cdb ); 771 commandLength = GetCommandDescriptorBlockSize ( request ); 772 if ( commandLength == kSCSICDBSize_6Byte ) 773 { 774 775 STATUS_LOG ( ( "cdb = %02x:%02x:%02x:%02x:%02x:%02x\n", cdb[0], cdb[1], 776 cdb[2], cdb[3], cdb[4], cdb[5] ) ); 777 778 } 779 780 else if ( commandLength == kSCSICDBSize_10Byte ) 781 { 782 783 STATUS_LOG ( ( "cdb = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", cdb[0], 784 cdb[1], cdb[2], cdb[3], cdb[4], cdb[5], cdb[6], cdb[7], cdb[8], 785 cdb[9] ) ); 786 787 } 788 789 else if ( commandLength == kSCSICDBSize_12Byte ) 790 { 791 792 STATUS_LOG ( ( "cdb = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", cdb[0], 793 cdb[1], cdb[2], cdb[3], cdb[4], cdb[5], cdb[6], cdb[7], cdb[8], 794 cdb[9], cdb[10], cdb[11] ) ); 795 796 } 797 798 else if ( commandLength == kSCSICDBSize_16Byte ) 799 { 800 801 STATUS_LOG ( ( "cdb = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", cdb[0], 802 cdb[1], cdb[2], cdb[3], cdb[4], cdb[5], cdb[6], cdb[7], cdb[8], 803 cdb[9], cdb[10], cdb[11], cdb[12], cdb[13], cdb[14], cdb[15] ) ); 804 805 } 806 807 cmd->zeroCommand ( ); 808 809 // Start filling in the command 810 cmd->setUnit ( fATAUnitID ); 811 cmd->setBuffer ( GetDataBuffer ( request ) ); 812 cmd->setPosition ( GetDataBufferOffset ( request ) ); 813 cmd->setByteCount ( GetRequestedDataTransferCount ( request ) ); 814 cmd->setCommand ( kPACKET ); 815 816 timeoutDuration = GetTimeoutDuration ( request ); 817 if ( timeoutDuration == 0 ) 818 { 819 820 // Find out what the timeout duration is. Since timeouts of zero requested from 821 // the layer above us mean the maximum timeout possible and ATA has no concept of 822 // infinite timeouts on commands, set it to the max possible. 823 timeoutDuration = 0xFFFFFFFF; 824 825 } 826 827 cmd->setTimeoutMS ( timeoutDuration ); 828 829 // Configure the flags for this command 830 flags = mATAFlagProtocolATAPI | mATAFlagUseConfigSpeed /* | mATAFlagLEDEnable */; 831 flags = flags | ( GetDataTransferDirection ( request ) == kSCSIDataTransfer_FromTargetToInitiator ? mATAFlagIORead : 0 ); 832 flags = flags | ( GetDataTransferDirection ( request ) == kSCSIDataTransfer_FromInitiatorToTarget ? mATAFlagIOWrite : 0 ); 833 834 requestCount = GetRequestedDataTransferCount ( request ); 835 836 // Check if this is an operation we should even use DMA on. This is really ugly, but it gains us some 837 // performance on reads and writes. 838 if ( ( cdb[0] == kSCSICmd_READ_6 ) || ( cdb[0] == kSCSICmd_READ_10 ) || ( cdb[0] == kSCSICmd_READ_12 ) || 839 ( cdb[0] == kSCSICmd_READ_CD ) || ( cdb[0] == kSCSICmd_READ_CD_MSF ) || ( cdb[0] == kSCSICmd_WRITE_AND_VERIFY_10 ) || 840 ( cdb[0] == kSCSICmd_WRITE_6 ) || ( cdb[0] == kSCSICmd_WRITE_10 ) || ( cdb[0] == kSCSICmd_WRITE_12 ) ) 841 { 842 shouldUseDMA = true; 843 } 844 845 else 846 { 847 shouldUseDMA = false; 848 } 849 850 if ( ( GetDataTransferDirection ( request ) != kSCSIDataTransfer_NoDataTransfer ) && 851 ( ( fUltraDMAMode | fDMAMode ) != 0 ) && shouldUseDMA ) 852 { 853 854 UInt8 features = mATAPIuseDMA; 855 856 flags = flags | mATAFlagUseDMA; 857 858 // Set the features register 859 cmd->setFeatures ( features ); 860 861 } 862 863 cmd->setFlags ( flags ); 864 865 // Set the cylinder registers 866 if ( GetRequestedDataTransferCount ( request ) != 0 ) 867 { 868 869 UInt64 requestCount = GetRequestedDataTransferCount ( request ); 870 871 if ( requestCount >= 0x10000 ) 872 { 873 874 // Cap the amount of PIO data that can be transferred in one interrupt 875 // so we don't try to hog the cpu while doing PIO transfers. 876 877 // Look and see if the caller is asking for 2352 byte transfers (CDDA) 878 // if so, then use a multiple of 2352 bytes for the chunk size 879 if ( ( requestCount % 2352 ) == 0 ) 880 { 881 882 requestCount = ( 0xFFFF / 2352 ) * 2352; 883 884 } 885 886 // Caller is asking for non-CDDA data reads, so we use 62k to get the largest 887 // size transfer less than 64k we possibly can which uses even block multiples 888 else 889 { 890 891 requestCount = 0xF800; 892 893 } 894 895 } 896 897 UInt8 requestHi = ( requestCount & 0xFF00 ) >> 8; 898 UInt8 requestLo = requestCount & 0x00FF; 899 900 cmd->setCylHi ( requestHi ); 901 cmd->setCylLo ( requestLo ); 902 903 } 904 905 cmd->setOpcode ( kATAPIFnExecIO ); 906 // set the device head to the correct unit 907 cmd->setDevice_Head ( fATAUnitID << 4 ); 908 cmd->setRegMask ( ( ataRegMask ) ( mATAErrFeaturesValid | mATAStatusCmdValid ) ); 909 910 IOReturn theErr = cmd->setPacketCommand ( atapiCommandLength, ( UInt8 * ) cdb ); 911 if ( theErr != kATANoErr ) 912 { 913 914 STATUS_LOG ( ( "IOATAPIProtocolTransport::SendSCSICommand setPacketCommand returned error = %ld\n", theErr ) ); 915 916 } 917 918 // Setup our context 919 clientData->self = this; 920 clientData->scsiTask = request; 921 922 cmd->setCallbackPtr ( &sSCSITaskCallbackProc ); 923 924 fATADevice->executeCommand ( cmd ); 925 926 return true; 927 928} 929 930 931//-------------------------------------------------------------------------------------- 932// SCSITaskCallbackFunction - virtual callback routine which calls CompleteSCSITask 933//-------------------------------------------------------------------------------------- 934 935void 936IOATAPIProtocolTransport::SCSITaskCallbackFunction ( IOATACommand * cmd, 937 SCSITaskIdentifier scsiTask ) 938{ 939 940 ATAPIClientData * clientData = NULL; 941 IOReturn result; 942 UInt64 bytesTransferred; 943 944 STATUS_LOG ( ( "IOATAPIProtocolTransport::SCSITaskCallbackFunction entering\n" ) ); 945 946 clientData = ( ATAPIClientData * ) cmd->refCon; 947 948 result = cmd->getResult ( ); 949 bytesTransferred = cmd->getActualTransfer ( ); 950 951 ReturnATACommandObject ( cmd ); 952 953 switch ( result ) 954 { 955 956 case kATANoErr: 957 { 958 959 STATUS_LOG ( ( "IOATAPIProtocolTransport::SCSITaskCallbackFunction result = noErr\n" ) ); 960 SetRealizedDataTransferCount ( scsiTask, bytesTransferred ); 961 CompleteSCSITask ( scsiTask, 962 kSCSIServiceResponse_TASK_COMPLETE, 963 kSCSITaskStatus_GOOD ); 964 965 } 966 break; 967 968 case kATAErrDevBusy: 969 case kATATimeoutErr: 970 { 971 972 SCSITaskStatus taskStatus = kSCSITaskStatus_No_Status; 973 974 if ( result == kATATimeoutErr ) 975 taskStatus = kSCSITaskStatus_TaskTimeoutOccurred; 976 977 else if ( result == kATAErrDevBusy ) 978 taskStatus = kSCSITaskStatus_DeviceNotResponding; 979 980 // Reset the device because the device is hung 981 clientData->self->ResetATAPIDevice ( ); 982 SetRealizedDataTransferCount ( scsiTask, bytesTransferred ); 983 CompleteSCSITask ( scsiTask, 984 kSCSIServiceResponse_SERVICE_DELIVERY_OR_TARGET_FAILURE, 985 taskStatus ); 986 987 // Since we reset the device, message the upper layer to check its configuration 988 // and do anything it needs to do 989 SendNotification_VerifyDeviceState ( ); 990 991 STATUS_LOG ( ( "IOATAPIProtocolTransport::SCSITaskCallbackFunction result = %ld.\n", result ) ); 992 993 } 994 break; 995 996 case kATADeviceError: 997 { 998 999 // CHK bit is set, so the device indicates CheckCondition 1000 SetRealizedDataTransferCount ( scsiTask, bytesTransferred ); 1001 1002 SCSITask * request = OSDynamicCast ( SCSITask, scsiTask ); 1003 1004 if ( request->IsAutosenseRequested ( ) == true ) 1005 { 1006 OSBitOrAtomic ( kATAPIRequestSenseNeededMask, &fSemaphore ); 1007 } 1008 1009 CompleteSCSITask ( scsiTask, 1010 kSCSIServiceResponse_TASK_COMPLETE, 1011 kSCSITaskStatus_CHECK_CONDITION ); 1012 1013 STATUS_LOG ( ( "IOATAPIProtocolTransport::SCSITaskCallbackFunction result = %ld.\n", result ) ); 1014 1015 } 1016 break; 1017 1018 case kATAModeNotSupported: 1019 case kATADevIntNoCmd: 1020 case kATADMAErr: 1021 default: 1022 { 1023 1024 STATUS_LOG ( ( "IOATAPIProtocolTransport::SCSITaskCallbackFunction result = %ld.\n", result ) ); 1025 SetRealizedDataTransferCount ( scsiTask, bytesTransferred ); 1026 CompleteSCSITask ( scsiTask, 1027 kSCSIServiceResponse_SERVICE_DELIVERY_OR_TARGET_FAILURE, 1028 kSCSITaskStatus_DeliveryFailure ); 1029 1030 } 1031 break; 1032 1033 } 1034 1035} 1036 1037 1038//-------------------------------------------------------------------------------------- 1039// CompleteSCSITask - Called to complete a SCSI Command 1040//-------------------------------------------------------------------------------------- 1041 1042void 1043IOATAPIProtocolTransport::CompleteSCSITask ( SCSITaskIdentifier request, 1044 SCSIServiceResponse serviceResponse, 1045 SCSITaskStatus taskStatus ) 1046{ 1047 1048 STATUS_LOG ( ( "IOATAPIProtocolTransport::CompleteSCSITask called\n" ) ); 1049 1050 RecordATAPITimeStamp ( 1051 ATAPI_TRACE ( kATACompleteSCSICommand ), 1052 ( unsigned int ) ( uintptr_t ) this, 1053 ( unsigned int ) fATAUnitID, 1054 ( unsigned int ) ( uintptr_t ) request, 1055 ( serviceResponse << 8 ) | taskStatus ); 1056 1057 OSBitAndAtomic ( ~kATAPICommandBusyMask, &fSemaphore ); 1058 CommandCompleted ( request, serviceResponse, taskStatus ); 1059 1060} 1061 1062 1063//-------------------------------------------------------------------------------------- 1064// AbortSCSICommand - Aborts a SCSI Command 1065//-------------------------------------------------------------------------------------- 1066 1067SCSIServiceResponse 1068IOATAPIProtocolTransport::AbortSCSICommand ( SCSITaskIdentifier request ) 1069{ 1070 1071 RecordATAPITimeStamp ( 1072 ATAPI_TRACE ( kATAAbort ), 1073 ( unsigned int ) ( uintptr_t ) this, 1074 ( unsigned int ) fATAUnitID, 1075 ( unsigned int ) ( uintptr_t ) request ); 1076 1077 return kSCSIServiceResponse_SERVICE_DELIVERY_OR_TARGET_FAILURE; 1078} 1079 1080 1081//-------------------------------------------------------------------------------------- 1082// IsProtocolServiceSupported - Returns true if feature is supported 1083//-------------------------------------------------------------------------------------- 1084 1085bool 1086IOATAPIProtocolTransport::IsProtocolServiceSupported ( SCSIProtocolFeature feature, 1087 void * serviceValue ) 1088{ 1089 1090 bool isSupported = false; 1091 1092 STATUS_LOG ( ( "IOATAPIProtocolTransport::IsProtocolServiceSupported called\n" ) ); 1093 1094 switch ( feature ) 1095 { 1096 1097 case kSCSIProtocolFeature_ProtocolSpecificPolling: 1098 // ATAPI supports low-power polling. 1099 isSupported = true; 1100 break; 1101 1102 case kSCSIProtocolFeature_ProtocolSpecificSleepCommand: 1103 // ATAPI supports ATA SLEEP command. 1104 isSupported = true; 1105 break; 1106 1107 case kSCSIProtocolFeature_ProtocolSpecificPowerOff: 1108 // does platform support power off? 1109 isSupported = ( fMediaNotifyValue != kODDMediaNotifyValue0 ); 1110 break; 1111 1112 case kSCSIProtocolFeature_ACA: 1113 // ATAPI does not support Auto Contingent Allegiance 1114 case kSCSIProtocolFeature_CPUInDiskMode: 1115 // ATAPI does not support cpu in disk mode 1116 case kSCSIProtocolFeature_GetMaximumLogicalUnitNumber: 1117 // ATAPI does not support more than one logical unit. 1118 default: 1119 // Some other feature ATAPI doesn't know about, probably means 1120 // it isn't supported... 1121 break; 1122 1123 } 1124 1125 return isSupported; 1126 1127} 1128 1129 1130//-------------------------------------------------------------------------------------- 1131// HandleProtocolServiceFeature - Returns true if feature is handled successfully 1132//-------------------------------------------------------------------------------------- 1133 1134bool 1135IOATAPIProtocolTransport::HandleProtocolServiceFeature ( SCSIProtocolFeature feature, 1136 void * serviceValue ) 1137{ 1138 1139 bool isSupported = false; 1140 1141 STATUS_LOG ( ( "IOATAPIProtocolTransport::HandleProtocolServiceFeature called\n" ) ); 1142 1143 switch ( feature ) 1144 { 1145 1146 case kSCSIProtocolFeature_ProtocolSpecificPolling: 1147 // We’re being told to do protocol specific polling 1148 if ( serviceValue != NULL ) 1149 { 1150 1151 UInt32 value = *( UInt32 * ) serviceValue; 1152 1153 if ( value != 0 ) 1154 { 1155 1156 // start low power polling 1157 1158 bool resetOccurred = false; 1159 1160 STATUS_LOG ( ( "Enabling polling of ATA Status register\n" ) ); 1161 1162 fCommandGate->runAction ( ( IOCommandGate::Action ) 1163 &IOATAPIProtocolTransport::sSetWakeupResetOccurred, 1164 ( void * ) resetOccurred ); 1165 1166 EnablePollingOfStatusRegister ( ); 1167 isSupported = true; 1168 1169 } 1170 1171 if ( value == 0 ) 1172 { 1173 1174 // stop low power polling 1175 1176 STATUS_LOG ( ( "Disabling polling of ATA Status register\n" ) ); 1177 1178 DisablePollingOfStatusRegister ( ); 1179 isSupported = true; 1180 1181 } 1182 1183 } 1184 1185 break; 1186 1187 case kSCSIProtocolFeature_ProtocolSpecificSleepCommand: 1188 1189 // We’re being told to do protocol specific sleep 1190 1191 if ( serviceValue != NULL ) 1192 { 1193 1194 UInt32 value = *( UInt32 * ) serviceValue; 1195 1196 if ( value != 0 ) 1197 { 1198 1199 STATUS_LOG ( ( "Sending ATA sleep command\n" ) ); 1200 1201 ( void ) SendATASleepCommand ( ); 1202 isSupported = true; 1203 1204 } 1205 1206 } 1207 1208 break; 1209 1210 case kSCSIProtocolFeature_ProtocolSpecificPowerOff: 1211 1212 // We’re being told to cut power to the drive OFF 1213 1214 RecordATAPITimeStamp ( ATAPI_TRACE ( kATAPowerOnReset ), 1215 ( unsigned int ) ( uintptr_t ) this, 1216 ( unsigned int ) fATAUnitID, 1217 ( unsigned int ) fATADeviceType ); 1218 1219 ( void ) TurnDrivePowerOff ( ); 1220 1221 break; 1222 1223 default: 1224 1225 break; 1226 1227 } 1228 1229 return isSupported; 1230 1231} 1232 1233 1234//-------------------------------------------------------------------------------------- 1235// HandlePowerOn - Power management routine to handle power state transition 1236//-------------------------------------------------------------------------------------- 1237 1238 1239IOReturn 1240IOATAPIProtocolTransport::HandlePowerOn ( void ) 1241{ 1242 1243 IOReturn status = kIOReturnSuccess; 1244 bool resetOccurred = false; 1245 1246 1247 STATUS_LOG ( ( "%s%s::%s called%s\n", "\033[36m", 1248 getName ( ), __FUNCTION__, "\033[0m" ) ); 1249 1250 fCommandGate->runAction ( ( IOCommandGate::Action ) 1251 &IOATAPIProtocolTransport::sCheckWakeupResetOccurred, 1252 ( void * ) &resetOccurred ); 1253 1254 if ( !resetOccurred ) 1255 { 1256 1257 STATUS_LOG ( ( "%s fWakeUpResetOccurred is false, resetting device %s\n", 1258 "\033[36m", getName ( ), __FUNCTION__, "\033[0m" ) ); 1259 1260 RecordATAPITimeStamp ( 1261 ATAPI_TRACE ( kATAPowerOnReset ), 1262 ( unsigned int ) ( uintptr_t ) this, 1263 ( unsigned int ) fATAUnitID, 1264 ( unsigned int ) fATADeviceType ); 1265 1266 // We aren't on a shared bus, so we need to reset the device 1267 status = ResetATAPIDevice ( ); 1268 1269 } 1270 1271 else 1272 { 1273 1274 STATUS_LOG ( ( "%s fWakeUpResetOccurred is true, NO reset needed %s\n", 1275 "\033[36m", getName ( ), __FUNCTION__, "\033[0m" ) ); 1276 1277 RecordATAPITimeStamp ( 1278 ATAPI_TRACE ( kATAPowerOnNoReset ), 1279 ( unsigned int ) ( uintptr_t ) this, 1280 ( unsigned int ) fATAUnitID, 1281 ( unsigned int ) fATADeviceType ); 1282 1283 } 1284 1285 return status; 1286 1287} 1288 1289 1290//-------------------------------------------------------------------------------------- 1291// HandlePowerOff - Power managment routine to handle power state transition 1292//-------------------------------------------------------------------------------------- 1293 1294 1295IOReturn 1296IOATAPIProtocolTransport::HandlePowerOff ( void ) 1297{ 1298 1299 IOReturn status = kIOReturnSuccess; 1300 bool resetOccurred = false; 1301 1302 RecordATAPITimeStamp ( 1303 ATAPI_TRACE ( kATAHandlePowerOff ), 1304 ( unsigned int ) ( uintptr_t ) this, 1305 ( unsigned int ) fATAUnitID, 1306 ( unsigned int ) fATADeviceType ); 1307 1308 fCommandGate->runAction ( ( IOCommandGate::Action ) 1309 &IOATAPIProtocolTransport::sSetWakeupResetOccurred, 1310 ( void * ) resetOccurred ); 1311 1312 return status; 1313 1314} 1315 1316 1317//-------------------------------------------------------------------------------------- 1318// sSCSITaskCallbackProc - static callback routine which calls through to the virtual 1319// routine 1320//-------------------------------------------------------------------------------------- 1321 1322void 1323IOATAPIProtocolTransport::sSCSITaskCallbackProc ( IOATACommand * cmd ) 1324{ 1325 1326 SCSITaskIdentifier scsiTask; 1327 ATAPIClientData clientData; 1328 IOATAPIProtocolTransport * self = NULL; 1329 1330 STATUS_LOG ( ( "IOATAPIProtocolTransport::ATACallbackProc entering.\n" ) ); 1331 1332 // Pull the clientData out of the command 1333 bcopy ( cmd->refCon, &clientData, sizeof ( clientData ) ); 1334 1335 // Get the scsiTask and a pointer to self from the clientData 1336 scsiTask = clientData.scsiTask; 1337 self = clientData.self; 1338 1339 STATUS_LOG ( ( "IOATAPIProtocolTransport::ATACallbackProc calling virtual callback...\n" ) ); 1340 1341 // Call through to virtual callback 1342 self->SCSITaskCallbackFunction ( cmd, scsiTask ); 1343 1344} 1345 1346 1347//--------------------------------------------------------------------------- 1348// InspectDevice - Fetch information about the ATAPI device nub. 1349//--------------------------------------------------------------------------- 1350 1351bool 1352IOATAPIProtocolTransport::InspectDevice ( IOATADevice * ataDevice ) 1353{ 1354 1355 OSString * string = NULL; 1356 IOReturn theErr = kIOReturnSuccess; 1357 1358 // Fetch ATA device information from the nub. 1359 string = OSDynamicCast ( OSString, 1360 ataDevice->getProperty ( kATAVendorPropertyKey ) ); 1361 1362 if ( string != NULL ) 1363 { 1364 1365 strncpy ( fModel, string->getCStringNoCopy ( ), kSizeOfATAModelString ); 1366 fModel[kSizeOfATAModelString] = '\0'; 1367 1368 } 1369 1370 string = OSDynamicCast ( OSString, 1371 ataDevice->getProperty ( kATARevisionPropertyKey ) ); 1372 1373 if ( string != NULL ) 1374 { 1375 1376 strncpy ( fRevision, string->getCStringNoCopy ( ), kSizeOfATARevisionString ); 1377 fRevision[kSizeOfATARevisionString] = '\0'; 1378 1379 } 1380 1381 theErr = IdentifyAndConfigureATAPIDevice ( ); 1382 1383 if ( theErr != kIOReturnSuccess ) 1384 { 1385 1386 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyAndConfigureATAPIDevice theErr = %ld\n", ( UInt32 ) theErr ) ); 1387 return false; 1388 1389 } 1390 1391 return true; 1392 1393} 1394 1395 1396//-------------------------------------------------------------------------------------- 1397// sATACallbackSync - static synchronous callback routine 1398//-------------------------------------------------------------------------------------- 1399 1400void 1401IOATAPIProtocolTransport::sATACallbackSync ( IOATACommand * cmd ) 1402{ 1403 1404 ATAPIConfigData * configData; 1405 IOATAPIProtocolTransport * self; 1406 1407 STATUS_LOG ( ( "IOATAPIProtocolTransport::sATACallbackSync entering\n" ) ); 1408 1409 configData = ( ATAPIConfigData * ) cmd->refCon; 1410 1411 if ( cmd->getResult ( ) != kATANoErr ) 1412 { 1413 1414 STATUS_LOG ( ( "Command result error = %ld\n", cmd->getResult ( ) ) ); 1415 1416 } 1417 1418 STATUS_LOG ( ( "signalling command completion\n" ) ); 1419 1420 configData->done = true; 1421 1422 self = configData->self; 1423 1424 self->fCommandGate->commandWakeup ( configData, false ); 1425 1426} 1427 1428 1429//-------------------------------------------------------------------------------------- 1430// sATAPIConfigStateMachine - state machine for configuration commands 1431//-------------------------------------------------------------------------------------- 1432 1433void 1434IOATAPIProtocolTransport::sATAPIConfigStateMachine ( IOATACommand * cmd ) 1435{ 1436 1437 ATAPIConfigData * configData; 1438 IOATAPIProtocolTransport * driver; 1439 IOReturn status; 1440 1441 STATUS_LOG ( ( "IOATAPIProtocolTransport::sATAPIConfigStateMachine entering\n" ) ); 1442 1443 configData = ( ATAPIConfigData * ) cmd->refCon; 1444 status = cmd->getResult ( ); 1445 driver = configData->self; 1446 1447 switch ( configData->state ) 1448 { 1449 1450 case kPIOTransferModeSetup: 1451 configData->state = kPIOTransferModeDone; 1452 driver->SetPIOTransferMode ( cmd, false ); 1453 break; 1454 1455 case kPIOTransferModeDone: 1456 if ( ( driver->fUltraDMAMode != 0 ) || ( driver->fDMAMode != 0 ) ) 1457 { 1458 configData->state = kDMATransferModeDone; 1459 driver->SetDMATransferMode ( cmd, false ); 1460 break; 1461 } 1462 1463 // Intentional fall through in case device doesn't support DMA 1464 case kDMATransferModeDone: 1465 configData->done = true; 1466 driver->fCommandGate->commandWakeup ( configData, false ); 1467 break; 1468 1469 default: 1470 PANIC_NOW ( ( "sATAPIConfigStateMachine unexpected state\n" ) ); 1471 break; 1472 1473 } 1474 1475} 1476 1477 1478//-------------------------------------------------------------------------------------- 1479// sATAPIResetCallback - static asynchronous callback routine for resets 1480//-------------------------------------------------------------------------------------- 1481 1482void 1483IOATAPIProtocolTransport::sATAPIResetCallback ( IOATACommand * cmd ) 1484{ 1485 1486 IOATAPIProtocolTransport * xptDriver; 1487 1488 STATUS_LOG ( ( "IOATAPIProtocolTransport::sATAPIResetCallback entering\n" ) ); 1489 1490 xptDriver = ( IOATAPIProtocolTransport * ) cmd->refCon; 1491 xptDriver->fWakeUpResetOccurred = true; 1492 xptDriver->fResetInProgress = false; 1493 1494 RecordATAPITimeStamp ( 1495 ATAPI_TRACE ( kATAResetComplete ), 1496 ( unsigned int ) xptDriver->fATAUnitID ); 1497 1498} 1499 1500 1501//-------------------------------------------------------------------------------------- 1502// sATAPIVoidCallback - callback that does nothing 1503//-------------------------------------------------------------------------------------- 1504 1505void 1506IOATAPIProtocolTransport::sATAPIVoidCallback ( IOATACommand * cmd ) 1507{ 1508 return; 1509} 1510 1511 1512//-------------------------------------------------------------------------------------- 1513// sPollStatusRegister - Callout method for thread_call_enter_delayed. 1514//-------------------------------------------------------------------------------------- 1515 1516void 1517IOATAPIProtocolTransport::sPollStatusRegister ( void * driver, void * refCon ) 1518{ 1519 1520 IOATAPIProtocolTransport * xptDriver; 1521 1522 xptDriver = ( IOATAPIProtocolTransport * ) driver; 1523 xptDriver->PollStatusRegister ( refCon ); 1524 1525} 1526 1527 1528//-------------------------------------------------------------------------------------- 1529// sPollStatusRegisterCallback - Callback method for PollStatusRegister(). 1530//-------------------------------------------------------------------------------------- 1531 1532void 1533IOATAPIProtocolTransport::sPollStatusRegisterCallback ( IOATACommand * cmd ) 1534{ 1535 1536 IOATAPIProtocolTransport * xptDriver = NULL; 1537 ATAPIClientData * clientData = NULL; 1538 1539 clientData = ( ATAPIClientData * ) cmd->refCon; 1540 xptDriver = ( IOATAPIProtocolTransport * ) clientData->self; 1541 1542 xptDriver->PollStatusRegisterCallback ( cmd ); 1543 1544} 1545 1546 1547//-------------------------------------------------------------------------------------- 1548// AllocateATACommandObjects - allocates ATA command objects 1549//-------------------------------------------------------------------------------------- 1550 1551void 1552IOATAPIProtocolTransport::AllocateATACommandObjects ( void ) 1553{ 1554 1555 STATUS_LOG ( ( "IOATAPIProtocolTransport::AllocateATACommandObjects entering\n" ) ); 1556 1557 IOATACommand * cmd = NULL; 1558 ATAPIClientData * clientData = NULL; 1559 ATAPIConfigData * configData = NULL; 1560 1561 // First allocate our reserve command 1562 fResetCommand = fATADevice->allocCommand ( ); 1563 assert ( fResetCommand != NULL ); 1564 1565 fConfigCommand = fATADevice->allocCommand ( ); 1566 assert ( fConfigCommand != NULL ); 1567 configData = ( ATAPIConfigData * ) IOMalloc ( sizeof ( ATAPIConfigData ) ); 1568 assert ( configData != NULL ); 1569 bzero ( configData, sizeof ( ATAPIConfigData ) ); 1570 fConfigCommand->refCon = ( void * ) configData; 1571 1572 fIdentifyCommand = fATADevice->allocCommand ( ); 1573 assert ( fIdentifyCommand != NULL ); 1574 clientData = ( ATAPIClientData * ) IOMalloc ( sizeof ( ATAPIClientData ) ); 1575 assert ( clientData != NULL ); 1576 bzero ( clientData, sizeof ( ATAPIClientData ) ); 1577 fIdentifyCommand->refCon = ( void * ) clientData; 1578 1579 for ( UInt32 index = 0; index < kIOATAPICommandPoolSize; index++ ) 1580 { 1581 1582 // Allocate the command 1583 cmd = fATADevice->allocCommand ( ); 1584 assert ( cmd != NULL ); 1585 1586 // Allocate the command clientData 1587 clientData = ( ATAPIClientData * ) IOMalloc ( sizeof ( ATAPIClientData ) ); 1588 assert ( clientData != NULL ); 1589 bzero ( clientData, sizeof ( ATAPIClientData ) ); 1590 1591 // set the back pointers to each other 1592 cmd->refCon = ( void * ) clientData; 1593 clientData->cmd = cmd; 1594 1595 STATUS_LOG ( ( "adding command to pool\n" ) ); 1596 1597 // Enqueue the command in the free list 1598 fCommandPool->returnCommand ( cmd ); 1599 1600 } 1601 1602 STATUS_LOG ( ( "IOATAPIProtocolTransport::AllocateATACommandObjects exiting\n" ) ); 1603 1604} 1605 1606 1607//-------------------------------------------------------------------------------------- 1608// DeallocateATACommandObjects - deallocates ATA command objects 1609//-------------------------------------------------------------------------------------- 1610 1611void 1612IOATAPIProtocolTransport::DeallocateATACommandObjects ( void ) 1613{ 1614 1615 STATUS_LOG ( ( "IOATAPIProtocolTransport::DellocateATACommandObjects entering\n" ) ); 1616 1617 IOATACommand * cmd = NULL; 1618 ATAPIClientData * clientData = NULL; 1619 ATAPIConfigData * configData = NULL; 1620 1621 cmd = ( IOATACommand * ) fCommandPool->getCommand ( false ); 1622 assert ( cmd != NULL ); 1623 1624 //XXX Walk the in-use queue and abort the commands (potential memory leak right now) 1625 1626 1627 // This handles walking the free command queue 1628 while ( cmd != NULL ) 1629 { 1630 1631 clientData = ( ATAPIClientData * ) cmd->refCon; 1632 assert ( clientData != NULL ); 1633 1634 IOFree ( clientData, sizeof ( ATAPIClientData ) ); 1635 clientData = NULL; 1636 1637 fATADevice->freeCommand ( cmd ); 1638 cmd = NULL; 1639 1640 cmd = ( IOATACommand * ) fCommandPool->getCommand ( false ); 1641 1642 } 1643 1644 configData = ( ATAPIConfigData * ) fConfigCommand->refCon; 1645 assert ( configData != NULL ); 1646 IOFree ( configData, sizeof ( ATAPIConfigData ) ); 1647 configData = NULL; 1648 1649 clientData = ( ATAPIClientData * ) fIdentifyCommand->refCon; 1650 assert ( clientData != NULL ); 1651 IOFree ( clientData, sizeof ( ATAPIClientData ) ); 1652 clientData = NULL; 1653 1654 // release "special" comands 1655 fATADevice->freeCommand ( fConfigCommand ); 1656 fATADevice->freeCommand ( fResetCommand ); 1657 fATADevice->freeCommand ( fIdentifyCommand ); 1658 1659 fConfigCommand = NULL; 1660 fResetCommand = NULL; 1661 fIdentifyCommand = NULL; 1662 1663 STATUS_LOG ( ( "IOATAPIProtocolTransport::DellocateATACommandObjects exiting\n" ) ); 1664 1665} 1666 1667 1668//-------------------------------------------------------------------------------------- 1669// GetATACommandObject - Gets an ata command object from the pool. 1670//-------------------------------------------------------------------------------------- 1671 1672IOATACommand * 1673IOATAPIProtocolTransport::GetATACommandObject ( bool blockForCommand ) 1674{ 1675 1676 IOATACommand * cmd = NULL; 1677 1678 STATUS_LOG ( ( "IOATAPIProtocolTransport::GetATACommandObject entering.\n" ) ); 1679 1680 cmd = ( IOATACommand * ) fCommandPool->getCommand ( blockForCommand ); 1681 1682 return cmd; 1683 1684} 1685 1686 1687//-------------------------------------------------------------------------------------- 1688// ReturnATACommandObject - Returns the command to the command pool 1689//-------------------------------------------------------------------------------------- 1690 1691void 1692IOATAPIProtocolTransport::ReturnATACommandObject ( IOATACommand * cmd ) 1693{ 1694 1695 STATUS_LOG ( ( "IOATAPIProtocolTransport::ReturnATACommandObject entering.\n" ) ); 1696 1697 assert ( cmd != NULL ); 1698 fCommandPool->returnCommand ( cmd ); 1699 1700} 1701 1702 1703//-------------------------------------------------------------------------------------- 1704// IdentifyAndConfigureATAPIDevice - Sends a device identify request to the device 1705// and uses it to configure the drive speeds 1706//-------------------------------------------------------------------------------------- 1707 1708IOReturn 1709IOATAPIProtocolTransport::IdentifyAndConfigureATAPIDevice ( void ) 1710{ 1711 1712 IOReturn theErr = kIOReturnSuccess; 1713 IOATABusInfo * busInfoPtr = NULL; 1714 IOATADevConfig * deviceConfigPtr = NULL; 1715 OSDictionary * dict = NULL; 1716 1717 // Get some info about the ATA bus 1718 busInfoPtr = IOATABusInfo::atabusinfo ( ); 1719 assert ( busInfoPtr != NULL ); 1720 1721 busInfoPtr->zeroData ( ); 1722 theErr = fATADevice->provideBusInfo ( busInfoPtr ); 1723 if ( theErr != kIOReturnSuccess ) 1724 { 1725 1726 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyAndConfigureATAPIDevice provide bus info failed thErr = %ld.\n", theErr ) ); 1727 goto ReleaseBusInfoAndBail; 1728 1729 } 1730 1731 fATASocketType = busInfoPtr->getSocketType ( ); 1732 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyAndConfigureATAPIDevice socket type = %d.\n", ( UInt8 ) fATASocketType ) ); 1733 1734 theErr = IdentifyATAPIDevice ( ); 1735 if ( theErr != kIOReturnSuccess ) 1736 { 1737 1738 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyAndConfigureATAPIDevice IdentifyATAPIDevice error = %ld, resetting device.\n", theErr ) ); 1739 1740 theErr = ResetATAPIDevice ( ); 1741 if ( theErr != kIOReturnSuccess ) 1742 { 1743 1744 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyAndConfigureATAPIDevice ResetATAPIDevice error = %ld.\n", theErr ) ); 1745 1746 // Not even a reset worked, bail 1747 goto ReleaseBusInfoAndBail; 1748 1749 } 1750 1751 theErr = IdentifyATAPIDevice ( ); 1752 if ( theErr != kIOReturnSuccess ) 1753 { 1754 1755 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyAndConfigureATAPIDevice 2nd IdentifyATAPIDevice error = %ld.\n", theErr ) ); 1756 1757 // Not even a reset worked, bail 1758 goto ReleaseBusInfoAndBail; 1759 1760 } 1761 1762 } 1763 1764 deviceConfigPtr = IOATADevConfig::atadevconfig ( ); 1765 assert ( deviceConfigPtr != NULL ); 1766 1767 theErr = fATADevice->provideConfig ( deviceConfigPtr ); 1768 if ( theErr != kIOReturnSuccess ) 1769 { 1770 1771 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyAndConfigureATAPIDevice provideConfig returned an error = %ld.\n", theErr ) ); 1772 goto ReleaseBusInfoAndBail; 1773 1774 } 1775 1776 theErr = deviceConfigPtr->initWithBestSelection ( ( UInt16 * ) fDeviceIdentifyData, busInfoPtr ); 1777 if ( theErr != kIOReturnSuccess ) 1778 { 1779 1780 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyAndConfigureATAPIDevice Autoconfigure didn't work error = %ld.\n", theErr ) ); 1781 PANIC_NOW ( ( "Autoconfigure didn't work. Initialize drive speed manually.\n" ) ); 1782 return theErr; 1783 1784 } 1785 1786 theErr = fATADevice->selectConfig ( deviceConfigPtr ); 1787 if ( theErr != kIOReturnSuccess ) 1788 { 1789 1790 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyAndConfigureATAPIDevice selectConfig returned error = %ld.\n", theErr ) ); 1791 return theErr; 1792 1793 } 1794 1795 fPIOMode = deviceConfigPtr->getPIOMode ( ); 1796 fDMAMode = deviceConfigPtr->getDMAMode ( ); 1797 fUltraDMAMode = deviceConfigPtr->getUltraMode ( ); 1798 fATAPIPacketConfig = deviceConfigPtr->getPacketConfig ( ); 1799 1800 // Adjust any of the Multiword DMA or Ultra DMA values if there is a subclass with an 1801 // ATAPI Mass Storage Characteristics dictionary. 1802 dict = OSDynamicCast ( OSDictionary, getProperty ( kIOPropertyATAPIMassStorageCharacteristics ) ); 1803 if ( dict != NULL ) 1804 { 1805 1806 OSNumber * modeNumber; 1807 1808 STATUS_LOG ( ( "ATAPI Mass Storage dictionary exists.\n" ) ); 1809 1810 modeNumber = OSDynamicCast ( OSNumber, dict->getObject ( "DMA Mode" ) ); 1811 if ( modeNumber != NULL ) 1812 { 1813 1814 STATUS_LOG ( ( "Changing default Multiword DMA Mode value from %d to %d\n", 1815 fDMAMode, modeNumber->unsigned8BitValue ( ) ) ); 1816 fDMAMode = modeNumber->unsigned8BitValue ( ); 1817 1818 } 1819 1820 modeNumber = OSDynamicCast ( OSNumber, dict->getObject ( "UDMA Mode" ) ); 1821 if ( modeNumber != NULL ) 1822 { 1823 1824 STATUS_LOG ( ( "Changing default Ultra DMA Mode value from %d to %d\n", 1825 fUltraDMAMode, modeNumber->unsigned8BitValue ( ) ) ); 1826 fUltraDMAMode = modeNumber->unsigned8BitValue ( ); 1827 1828 } 1829 1830 } 1831 1832 else 1833 { 1834 STATUS_LOG ( ( "ATAPI Mass Storage dictionary does not exist.\n" ) ); 1835 } 1836 1837 STATUS_LOG ( ( "atapiConfig = %d.\n", (int) fATAPIPacketConfig ) ); 1838 1839 theErr = ConfigureATAPIDevice ( ); 1840 1841ReleaseBusInfoAndBail: 1842 1843 1844 if ( busInfoPtr != NULL ) 1845 { 1846 1847 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyAndConfigureATAPIDevice releasing bus info.\n" ) ); 1848 busInfoPtr->release ( ); 1849 busInfoPtr = NULL; 1850 1851 } 1852 1853 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyAndConfigureATAPIDevice returning theErr = %ld.\n", theErr ) ); 1854 1855 return theErr; 1856 1857} 1858 1859 1860//-------------------------------------------------------------------------------------- 1861// IdentifyATAPIDevice - Sends a device identify request to the device 1862// and uses it to configure the drive speeds 1863//-------------------------------------------------------------------------------------- 1864 1865IOReturn 1866IOATAPIProtocolTransport::IdentifyATAPIDevice ( void ) 1867{ 1868 1869 IOReturn theErr = kIOReturnSuccess; 1870 1871 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyATAPIDevice entering.\n" ) ); 1872 1873 // Zero the command object 1874 fIdentifyCommand->zeroCommand ( ); 1875 1876 // Start filling in the command 1877 fIdentifyCommand->setUnit ( fATAUnitID ); 1878 fIdentifyCommand->setBuffer ( fDeviceIdentifyBuffer ); 1879 fIdentifyCommand->setPosition ( 0 ); 1880 fIdentifyCommand->setByteCount ( kATAPIIdentifyPacketDeviceDataSize ); 1881 fIdentifyCommand->setTransferChunkSize ( kATADefaultSectorSize ); 1882 1883 fIdentifyCommand->setCommand ( kID_DRIVE ); 1884 fIdentifyCommand->setTimeoutMS ( k10SecondTimeout ); 1885 fIdentifyCommand->setFlags ( mATAFlagIORead ); 1886 fIdentifyCommand->setOpcode ( kATAFnExecIO ); 1887 // set the device head to the correct unit 1888 fIdentifyCommand->setDevice_Head ( fATAUnitID << 4 ); 1889 fIdentifyCommand->setRegMask ( ( ataRegMask ) ( mATAErrFeaturesValid | mATAStatusCmdValid ) ); 1890 fIdentifyCommand->setCallbackPtr ( &sATACallbackSync ); 1891 1892 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyATAPIDevice executing identify command.\n" ) ); 1893 1894 theErr = SendCommand ( fIdentifyCommand ); 1895 1896 #if defined(__BIG_ENDIAN__) 1897 // The identify device info needs to be byte-swapped on big-endian (ppc) 1898 // systems because it is data that is produced by the drive, read across a 1899 // 16-bit little-endian PCI interface, directly into a big-endian system. 1900 // Regular data doesn't need to be byte-swapped because it is written and 1901 // read from the host and is intrinsically byte-order correct. 1902 sSwapBytes16 ( ( UInt8 * ) fDeviceIdentifyData, kATAPIIdentifyPacketDeviceDataSize ); 1903 #endif 1904 1905 STATUS_LOG ( ( "IOATAPIProtocolTransport::IdentifyATAPIDevice exiting with theErr = %ld.\n", theErr ) ); 1906 1907 return theErr; 1908 1909} 1910 1911 1912//-------------------------------------------------------------------------------------- 1913// ConfigureATAPIDevice - Configures the ATAPI Device 1914//-------------------------------------------------------------------------------------- 1915 1916IOReturn 1917IOATAPIProtocolTransport::ConfigureATAPIDevice ( void ) 1918{ 1919 1920 IOReturn status = kIOReturnSuccess; 1921 ATAPIConfigData * configData; 1922 1923 STATUS_LOG ( ( "IOATAPIProtocolTransport::ConfigureATAPIDevice entering.\n" ) ); 1924 1925 configData = ( ATAPIConfigData * ) fConfigCommand->refCon; 1926 1927 configData->self = this; 1928 configData->state = kPIOTransferModeSetup; 1929 configData->done = false; 1930 1931 sATAPIConfigStateMachine ( fConfigCommand ); 1932 1933 status = fCommandGate->runAction ( 1934 OSMemberFunctionCast ( 1935 IOCommandGate::Action, 1936 this, 1937 &IOATAPIProtocolTransport::GatedWaitForRequest ), 1938 configData ); 1939 1940 if ( status == kIOReturnSuccess ) 1941 { 1942 status = fConfigCommand->getResult ( ); 1943 } 1944 1945 return kIOReturnSuccess; 1946 1947} 1948 1949 1950//-------------------------------------------------------------------------------------- 1951// ReconfigureATAPIDevice - Reconfigures the ATAPI Device 1952//-------------------------------------------------------------------------------------- 1953 1954IOReturn 1955IOATAPIProtocolTransport::ReconfigureATAPIDevice ( void ) 1956{ 1957 1958 if ( fConfigCommand != NULL ) 1959 { 1960 1961 SetPIOTransferMode ( fConfigCommand, true ); 1962 1963 if ( ( fUltraDMAMode != 0 ) || ( fDMAMode != 0 ) ) 1964 { 1965 SetDMATransferMode ( fConfigCommand, true ); 1966 } 1967 1968 } 1969 1970 return kIOReturnSuccess; 1971 1972} 1973 1974 1975//-------------------------------------------------------------------------------------- 1976// SetPIOTransferMode - Configures the ATAPI Device's PIO Transfer mode 1977//-------------------------------------------------------------------------------------- 1978 1979IOReturn 1980IOATAPIProtocolTransport::SetPIOTransferMode ( IOATACommand * cmd, bool forceSync ) 1981{ 1982 1983 IOReturn theErr = kIOReturnSuccess; 1984 UInt8 mode = 0; 1985 1986 STATUS_LOG ( ( "IOATAPIProtocolTransport::SetPIOTransferMode entering.\n" ) ); 1987 1988 // Zero the command object 1989 cmd->zeroCommand ( ); 1990 1991 // Start filling in the command 1992 cmd->setUnit ( fATAUnitID ); 1993 cmd->setCommand ( kATAcmdSetFeatures ); 1994 cmd->setTimeoutMS ( k10SecondTimeout ); 1995 cmd->setFeatures ( kATASetTransferMode ); 1996 1997 // Always set to highest transfer mode 1998 mode = sConvertHighestBitToNumber ( fPIOMode ); 1999 2000 // PIO transfer mode is capped at 4 for now in the ATA-5 spec. If a device supports 2001 // more than mode 4 it has to at least support mode 4. We might not get the best 2002 // performance out of the drive, but it will work until we update to latest spec. 2003 if ( mode > 4 ) 2004 { 2005 2006 STATUS_LOG ( ( "IOATAPIProtocolTransport::SetPIOTransferMode mode > 4 = %ld.\n", ( UInt32 ) mode ) ); 2007 mode = 4; 2008 2009 } 2010 2011 cmd->setSectorCount ( kATAEnablePIOModeMask | mode ); 2012 cmd->setOpcode ( kATAFnExecIO ); 2013 2014 // set the device head to the correct unit 2015 cmd->setDevice_Head ( fATAUnitID << 4 ); 2016 cmd->setFlags ( mATAFlagImmediate ); 2017 2018 if ( forceSync ) 2019 { 2020 cmd->setCallbackPtr ( &sATAPIVoidCallback ); 2021 } 2022 2023 else 2024 { 2025 cmd->setCallbackPtr ( &sATAPIConfigStateMachine ); 2026 } 2027 2028 theErr = fATADevice->executeCommand ( cmd ); 2029 2030 STATUS_LOG ( ( "IOATAPIProtocolTransport::SetPIOTransferMode exiting with error = %ld.\n", theErr ) ); 2031 2032 return theErr; 2033 2034} 2035 2036 2037//-------------------------------------------------------------------------------------- 2038// SetDMATransferMode - Configures the ATAPI Device's DMA Transfer mode 2039//-------------------------------------------------------------------------------------- 2040 2041IOReturn 2042IOATAPIProtocolTransport::SetDMATransferMode ( IOATACommand * cmd, bool forceSync ) 2043{ 2044 2045 IOReturn theErr = kIOReturnSuccess; 2046 UInt8 mode = 0; 2047 2048 STATUS_LOG ( ( "IOATAPIProtocolTransport::SetDMATransferMode entering.\n" ) ); 2049 2050 // Zero the command object 2051 cmd->zeroCommand ( ); 2052 2053 // Start filling in the command 2054 cmd->setUnit ( fATAUnitID ); 2055 cmd->setCommand ( kATAcmdSetFeatures ); 2056 cmd->setTimeoutMS ( k10SecondTimeout ); 2057 cmd->setFeatures ( kATASetTransferMode ); 2058 cmd->setOpcode ( kATAFnExecIO ); 2059 cmd->setDevice_Head ( fATAUnitID << 4 ); 2060 cmd->setFlags ( mATAFlagImmediate ); 2061 2062 // Always set to highest transfer mode 2063 if ( fUltraDMAMode ) 2064 { 2065 2066 STATUS_LOG ( ( "IOATAPIProtocolTransport::SetDMATransferMode choosing UltraDMA.\n" ) ); 2067 mode = sConvertHighestBitToNumber ( fUltraDMAMode ); 2068 // Ultra DMA is capped at 4 for now in the ATA-5 spec. If a device supports 2069 // more than mode 4 it MUST at least support mode 4. We might not get the best 2070 // performance out of the drive, but it will work until we update to latest spec. 2071 if ( mode > 4 ) 2072 mode = 4; 2073 2074 cmd->setSectorCount ( kATAEnableUltraDMAModeMask | mode ); 2075 2076 } 2077 2078 else 2079 { 2080 2081 STATUS_LOG ( ( "IOATAPIProtocolTransport::SetDMATransferMode choosing DMA.\n" ) ); 2082 mode = sConvertHighestBitToNumber ( fDMAMode ); 2083 // MultiWord DMA is capped at 2 for now in the ATA-5 spec. If a device supports 2084 // more than mode 2 it MUST at least support mode 2. We might not get the best 2085 // performance out of the drive, but it will work until we update to latest spec. 2086 if ( mode > 2 ) 2087 mode = 2; 2088 2089 cmd->setSectorCount ( kATAEnableMultiWordDMAModeMask | mode ); 2090 2091 } 2092 2093 if ( forceSync ) 2094 { 2095 cmd->setCallbackPtr ( &sATAPIVoidCallback ); 2096 } 2097 2098 else 2099 { 2100 cmd->setCallbackPtr ( &sATAPIConfigStateMachine ); 2101 } 2102 2103 STATUS_LOG ( ( "IOATAPIProtocolTransport::SetDMATransferMode executing DMA setup command.\n" ) ); 2104 2105 theErr = fATADevice->executeCommand ( cmd ); 2106 2107 STATUS_LOG ( ( "IOATAPIProtocolTransport::SetDMATransferMode exiting with error = %ld.\n", theErr ) ); 2108 2109 return theErr; 2110 2111} 2112 2113 2114//-------------------------------------------------------------------------------------- 2115// ResetATAPIDevice - Sends a device reset command to the device 2116//-------------------------------------------------------------------------------------- 2117 2118IOReturn 2119IOATAPIProtocolTransport::ResetATAPIDevice ( void ) 2120{ 2121 2122 IOReturn theErr = kIOReturnSuccess; 2123 2124 STATUS_LOG ( ( "IOATAPIProtocolTransport::ResetATAPIDevice entering.\n" ) ); 2125 2126 if ( fResetInProgress ) 2127 return kIOReturnNotPermitted; 2128 2129 fResetInProgress = true; 2130 2131 // Zero the command object 2132 fResetCommand->zeroCommand ( ); 2133 2134 // Start filling in the command 2135 fResetCommand->setUnit ( fATAUnitID ); 2136 fResetCommand->setCommand ( kSOFTRESET ); 2137 fResetCommand->setTimeoutMS ( k45SecondTimeout ); 2138 fResetCommand->setFlags ( mATAFlagImmediate ); 2139 fResetCommand->setOpcode ( kATAFnBusReset ); 2140 fResetCommand->setCallbackPtr ( &sATAPIResetCallback ); 2141 fResetCommand->refCon = ( void * ) this; 2142 2143 RecordATAPITimeStamp ( 2144 ATAPI_TRACE ( kATAReset ), 2145 ( unsigned int ) ( uintptr_t ) this, 2146 ( unsigned int ) fATAUnitID ); 2147 2148 theErr = fATADevice->executeCommand ( fResetCommand ); 2149 2150 return theErr; 2151 2152} 2153 2154 2155//-------------------------------------------------------------------------------------- 2156// EnablePollingOfStatusRegister - Called to schedule a poll of the status register. 2157//-------------------------------------------------------------------------------------- 2158 2159void 2160IOATAPIProtocolTransport::EnablePollingOfStatusRegister ( void ) 2161{ 2162 2163 AbsoluteTime time; 2164 2165 STATUS_LOG ( ( "EnablePollingOfStatusRegister called\n" ) ); 2166 2167 RecordATAPITimeStamp ( ATAPI_TRACE ( kATAStartStatusPolling ), 2168 ( unsigned int ) ( uintptr_t ) this, 2169 ( unsigned int ) fATAUnitID, 2170 ( unsigned int ) fATADeviceType ); 2171 2172 // No reason to start a thread if we've been termintated 2173 if ( ( isInactive ( ) == false ) && 2174 ( fPollingThread != NULL ) && 2175 ( fWakeUpResetOccurred == false ) ) 2176 { 2177 2178 // Retain ourselves so that this object doesn't go away 2179 // while we are polling 2180 2181 retain ( ); 2182 2183 clock_interval_to_deadline ( 1000, kMillisecondScale, &time ); 2184 thread_call_enter_delayed ( fPollingThread, time ); 2185 2186 } 2187 2188} 2189 2190 2191//-------------------------------------------------------------------------------------- 2192// DisablePollingOfStatusRegister - Called to cancel a poll of the status register. 2193//-------------------------------------------------------------------------------------- 2194 2195void 2196IOATAPIProtocolTransport::DisablePollingOfStatusRegister ( void ) 2197{ 2198 2199 fWakeUpResetOccurred = true; 2200 2201 RecordATAPITimeStamp ( ATAPI_TRACE ( kATAStopStatusPolling ), 2202 ( unsigned int ) ( uintptr_t ) this, 2203 ( unsigned int ) fATAUnitID, 2204 ( unsigned int ) fATADeviceType ); 2205 2206 // Cancel the thread if it is scheduled. 2207 if ( thread_call_cancel ( fPollingThread ) ) 2208 { 2209 2210 // It was scheduled, so we balance out the retain ( ) 2211 // with a release ( ) 2212 release ( ); 2213 2214 } 2215 2216} 2217 2218 2219//-------------------------------------------------------------------------------------- 2220// PollStatusRegister - Called to poll the status register to see if the drive 2221// bay door has been opened. 2222//-------------------------------------------------------------------------------------- 2223 2224void 2225IOATAPIProtocolTransport::PollStatusRegister ( void * refCon ) 2226{ 2227 2228 IOATACommand * cmd; 2229 ATAPIClientData * clientData; 2230 2231 STATUS_LOG ( ( "PollStatusRegister called\n" ) ); 2232 2233 RecordATAPITimeStamp ( ATAPI_TRACE ( kATAStatusPoll ), 2234 ( unsigned int ) ( uintptr_t ) this, 2235 ( unsigned int ) fATAUnitID, 2236 ( unsigned int ) fATADeviceType ); 2237 2238 if ( fWakeUpResetOccurred == true ) 2239 return; 2240 2241 // Get a command 2242 cmd = fIdentifyCommand; 2243 2244 clientData = ( ATAPIClientData * ) cmd->refCon; 2245 2246 clientData->self = this; 2247 2248 // Zero the command 2249 cmd->zeroCommand ( ); 2250 2251 // Set the command up for reading the register 2252 cmd->setFlags ( mATAFlagIORead ); 2253 cmd->setOpcode ( kATAFnRegAccess ); 2254 cmd->setUnit ( fATAUnitID ); 2255 cmd->setRegMask ( mATAStatusCmdValid ); 2256 cmd->setTimeoutMS ( k10SecondTimeout ); 2257 cmd->setCallbackPtr ( &sPollStatusRegisterCallback ); 2258 2259 fATADevice->executeCommand ( cmd ); 2260 2261} 2262 2263 2264//-------------------------------------------------------------------------------------- 2265// PollStatusRegisterCallback - Callback handler for status register polling 2266//-------------------------------------------------------------------------------------- 2267 2268void 2269IOATAPIProtocolTransport::PollStatusRegisterCallback ( IOATACommand * cmd ) 2270{ 2271 2272 IOReturn theErr = kIOReturnSuccess; 2273 UInt8 statusRegValue = 0; 2274 2275 STATUS_LOG ( ( "IOATAPIProtocolTransport::PollStatusRegisterCallback called\n" ) ); 2276 2277 theErr = cmd->getResult ( ); 2278 if ( theErr == kIOReturnSuccess ) 2279 { 2280 2281 // Read the status register value 2282 statusRegValue = cmd->getStatus ( ); 2283 2284 // If the value is 0x50, then the drive door has been opened since we last 2285 // checked. Let the SCSI Application Layer know so it can try to poll for 2286 // media. 2287 if ( statusRegValue == 0x50 ) 2288 { 2289 2290 STATUS_LOG ( ( "Sending message to application layer.\n" ) ); 2291 2292 // Reset the device to bring it out of sleep mode, since media 2293 // might have been inserted. 2294 ResetATAPIDevice ( ); 2295 2296 } 2297 2298 else 2299 { 2300 2301 // Do another poll 2302 EnablePollingOfStatusRegister ( ); 2303 2304 } 2305 2306 } 2307 2308 else 2309 { 2310 2311 ERROR_LOG ( ( "Error = %d occurred while polling status register", theErr ) ); 2312 // Some error occurred. For now, just issue another poll 2313 EnablePollingOfStatusRegister ( ); 2314 2315 } 2316 2317 // Drop the retain for this poll 2318 release ( ); 2319 2320} 2321 2322 2323//-------------------------------------------------------------------------------------- 2324// SendATASleepCommand - Sends an ATA SLEEP command to the drive 2325//-------------------------------------------------------------------------------------- 2326 2327IOReturn 2328IOATAPIProtocolTransport::SendATASleepCommand ( void ) 2329{ 2330 2331 IOReturn status; 2332 IOATACommand * cmd; 2333 2334 STATUS_LOG ( ( "%s%s::%s called%s\n", "\033[36m", getName ( ), __FUNCTION__, "\033[0m" ) ); 2335 2336 RecordATAPITimeStamp ( ATAPI_TRACE ( kATASendATASleepCmd ), 2337 ( unsigned int ) ( uintptr_t ) this, 2338 ( unsigned int ) fATAUnitID, 2339 ( unsigned int ) fATADeviceType ); 2340 2341 cmd = GetATACommandObject ( ); 2342 2343 // Zero the command 2344 cmd->zeroCommand ( ); 2345 cmd->setUnit ( fATAUnitID ); 2346 cmd->setTimeoutMS ( kATATimeout10Seconds ); 2347 cmd->setCallbackPtr ( &IOATAPIProtocolTransport::sATACallbackSync ); 2348 cmd->setDevice_Head ( fATAUnitID << 4 ); 2349 cmd->setOpcode ( kATAFnExecIO ); 2350 cmd->setCommand ( kATAcmdSleep ); 2351 2352 status = SendCommand ( cmd ); 2353 2354 ReturnATACommandObject ( cmd ); 2355 2356 return status; 2357 2358} 2359 2360 2361//-------------------------------------------------------------------------------------- 2362// TurnDrivePowerOff - Called to turn power to the drive OFF. 2363//-------------------------------------------------------------------------------------- 2364 2365IOReturn 2366IOATAPIProtocolTransport::TurnDrivePowerOff ( void ) 2367{ 2368 2369 IOReturn status; 2370 IOATACommand * cmd; 2371 2372 STATUS_LOG ( ( "IOATAPIProtocolTransport::TurnDrivePowerOff called\n" ) ); 2373 2374 RecordATAPITimeStamp ( ATAPI_TRACE ( kATADriverPowerOff ), 2375 ( unsigned int ) ( uintptr_t ) this, 2376 ( unsigned int ) fATAUnitID ); 2377 2378 cmd = GetATACommandObject ( ); 2379 2380 // Zero the command 2381 cmd->zeroCommand ( ); 2382 2383 // Set the command up for shutting the drive power off 2384 cmd->setUnit ( fATAUnitID ); 2385 cmd->setOpcode ( kATAFnRegAccess ); 2386 cmd->setRegMask ( mATAStatusCmdValid ); 2387 cmd->setFlags ( mATAFlagIORead | mATAFlagQuiesce ); 2388 cmd->setTimeoutMS ( kATATimeout10Seconds ); 2389 cmd->setCallbackPtr ( &IOATAPIProtocolTransport::sATACallbackSync ); 2390 2391 status = SendCommand ( cmd ); 2392 2393 ReturnATACommandObject ( cmd ); 2394 2395 return status; 2396 2397} 2398 2399 2400//-------------------------------------------------------------------------------------- 2401// SetWakeupResetOccurred - Called on safe side of command gate to set state 2402//-------------------------------------------------------------------------------------- 2403 2404void 2405IOATAPIProtocolTransport::SetWakeupResetOccurred ( bool resetOccurred ) 2406{ 2407 2408 fWakeUpResetOccurred = resetOccurred; 2409 2410} 2411 2412 2413//-------------------------------------------------------------------------------------- 2414// sSetWakeupResetOccurred - Called on safe side of command gate 2415//-------------------------------------------------------------------------------------- 2416 2417void 2418IOATAPIProtocolTransport::sSetWakeupResetOccurred ( IOATAPIProtocolTransport * driver, 2419 bool resetOccurred ) 2420{ 2421 2422 driver->SetWakeupResetOccurred ( resetOccurred ); 2423 2424} 2425 2426 2427//-------------------------------------------------------------------------------------- 2428// CheckWakeupResetOccurred - Called on safe side of command gate to find out if 2429// the driver has already received a reset message 2430//-------------------------------------------------------------------------------------- 2431 2432bool 2433IOATAPIProtocolTransport::CheckWakeupResetOccurred ( void ) 2434{ 2435 2436 return fWakeUpResetOccurred; 2437 2438} 2439 2440 2441//-------------------------------------------------------------------------------------- 2442// sCheckWakeupResetOccurred - Called on safe side of command gate 2443//-------------------------------------------------------------------------------------- 2444 2445void 2446IOATAPIProtocolTransport::sCheckWakeupResetOccurred ( IOATAPIProtocolTransport * driver, 2447 bool * resetOccurred ) 2448{ 2449 2450 *resetOccurred = driver->CheckWakeupResetOccurred ( ); 2451 return; 2452 2453} 2454 2455 2456//-------------------------------------------------------------------------------------- 2457// sSwapBytes16 - Swaps the buffer for device identify data 2458//-------------------------------------------------------------------------------------- 2459 2460void 2461IOATAPIProtocolTransport::sSwapBytes16 ( UInt8 * buffer, IOByteCount numBytesToSwap ) 2462{ 2463 2464 IOByteCount index; 2465 UInt8 temp; 2466 UInt8 * firstBytePtr; 2467 2468 for ( index = 0; index < numBytesToSwap; index += 2 ) 2469 { 2470 2471 firstBytePtr = buffer; // save pointer 2472 temp = *buffer++; // Save Byte0, point to Byte1 2473 *firstBytePtr = *buffer; // Byte0 = Byte1 2474 *buffer++ = temp; // Byte1 = Byte0 2475 2476 } 2477 2478} 2479 2480 2481//-------------------------------------------------------------------------------------- 2482// sConvertHighestBitToNumber - Finds the higest bit in a number and returns 2483//-------------------------------------------------------------------------------------- 2484 2485UInt8 2486IOATAPIProtocolTransport::sConvertHighestBitToNumber ( UInt16 bitField ) 2487{ 2488 2489 UInt16 index, integer; 2490 2491 // Test all bits from left to right, terminating at the first non-zero bit 2492 for ( index = 0x0080, integer = 7; ( ( index & bitField ) == 0 && index != 0 ) ; index >>= 1, integer-- ) 2493 { ; } 2494 2495 return ( integer ); 2496 2497} 2498 2499 2500//--------------------------------------------------------------------------- 2501// Handles messages from our provider. 2502//--------------------------------------------------------------------------- 2503 2504IOReturn 2505IOATAPIProtocolTransport::message ( UInt32 type, IOService * provider, void * argument ) 2506{ 2507 2508 IOReturn status = kIOReturnSuccess; 2509 2510 STATUS_LOG ( ( "IOATABlockStorageDevice::message %p %lx\n", this, type ) ); 2511 2512 2513 switch ( type ) 2514 { 2515 2516 case kATAResetEvent: // Someone gave a reset to the bus 2517 // reconfig device here 2518 fWakeUpResetOccurred = true; 2519 status = ReconfigureATAPIDevice ( ); 2520 // Tell the layer above us that a reset occurred so it can lock media 2521 // and verify that the device is in a good state. 2522 SendNotification_VerifyDeviceState ( ); 2523 break; 2524 2525 case kATANewMediaEvent: 2526 // Tell the layer above us that new media has been added so it can lock media 2527 // and verify that the device is in a good state. 2528 SendNotification_VerifyDeviceState ( ); 2529 break; 2530 2531 case kATANullEvent: // Just kidding -- nothing happened 2532 break; 2533 2534 // atapi resets are not relevent to ATA devices, but soft-resets ARE relevant to ATAPI devices. 2535 case kATAPIResetEvent: // Someone gave a ATAPI reset to the drive 2536 // reconfig device here 2537 fWakeUpResetOccurred = true; 2538 status = ReconfigureATAPIDevice ( ); 2539 // Tell the layer above us that a reset occurred so it can lock media 2540 // and verify that the device is in a good state. 2541 SendNotification_VerifyDeviceState ( ); 2542 break; 2543 2544 case kIOMessageServiceIsRequestingClose: 2545 fPhysicallyConnected = false; 2546 SendNotification_DeviceRemoved ( ); 2547 DeallocateATACommandObjects ( ); 2548 if ( fATADevice != NULL ) 2549 { 2550 // Make sure we close provider, else the terminate won't propagate up the 2551 // stack. 2552 fATADevice->close ( this ); 2553 fATADevice = NULL; 2554 2555 } 2556 break; 2557 2558 default: 2559 status = super::message ( type, provider, argument ); 2560 break; 2561 2562 } 2563 2564 return status; 2565 2566} 2567 2568 2569//------------------------------------------------------------------------------ 2570// RecordATAPITimeStamp [STATIC] 2571//------------------------------------------------------------------------------ 2572 2573static inline void 2574RecordATAPITimeStamp ( 2575 unsigned int code, 2576 unsigned int a, unsigned int b, 2577 unsigned int c, unsigned int d ) 2578{ 2579 2580 if ( gATAPIDebugFlags != 0 ) 2581 { 2582 IOTimeStampConstant ( code, a, b, c, d ); 2583 } 2584 2585} 2586 2587 2588//--------------------------------------------------------------------------- 2589// SendCommand - Executes comand and waits for its completion. 2590//--------------------------------------------------------------------------- 2591 2592IOReturn 2593IOATAPIProtocolTransport::SendCommand ( IOATACommand * cmd ) 2594{ 2595 2596 IOReturn status; 2597 void * previousRefCon; 2598 ATAPIConfigData configData; 2599 2600 STATUS_LOG ( ( "IOATAPIProtocolTransport::SendCommand\n" ) ); 2601 2602 previousRefCon = cmd->refCon; 2603 2604 cmd->refCon = ( void * ) &configData; 2605 configData.self = this; 2606 configData.done = false; 2607 2608 status = fATADevice->executeCommand ( cmd ); 2609 2610 STATUS_LOG ( ( "executeCommand returned 0x%0lX\n", status ) ); 2611 2612 if ( status == kIOReturnSuccess ) 2613 { 2614 2615 status = fCommandGate->runAction ( 2616 OSMemberFunctionCast ( 2617 IOCommandGate::Action, 2618 this, 2619 &IOATAPIProtocolTransport::GatedWaitForRequest ), 2620 &configData ); 2621 2622 STATUS_LOG ( ( "runAction returned 0x%0lX\n", status ) ); 2623 2624 if ( status == kIOReturnSuccess ) 2625 { 2626 2627 status = cmd->getResult ( ); 2628 2629 STATUS_LOG ( ( "getResult returned 0x%0lX\n", status ) ); 2630 2631 } 2632 2633 } 2634 2635 cmd->refCon = previousRefCon; 2636 2637 return status; 2638 2639} 2640 2641 2642//--------------------------------------------------------------------------- 2643// GatedWaitForRequest - Wait for command completion. 2644//--------------------------------------------------------------------------- 2645 2646IOReturn 2647IOATAPIProtocolTransport::GatedWaitForRequest ( void * data ) 2648{ 2649 2650 IOReturn status = kIOReturnSuccess; 2651 ATAPIConfigData * configData = NULL; 2652 2653 STATUS_LOG ( ( "IOATAPIProtocolTransport::GatedWaitForRequest\n" ) ); 2654 2655 configData = ( ATAPIConfigData * ) data; 2656 2657 // Check if the request has completed already 2658 while ( configData->done == false ) 2659 { 2660 2661 STATUS_LOG ( ( "will wait for command completion\n" ) ); 2662 2663 // Wait for the completion... 2664 status = fCommandGate->commandSleep ( configData, THREAD_UNINT ); 2665 2666 if ( status != THREAD_AWAKENED ) 2667 { 2668 panic ( "IOATAPIProtocolTransport: detected spurious wakeup - status = 0x%08x\n", status ); 2669 } 2670 2671 } 2672 2673 STATUS_LOG ( ( "command completed\n" ) ); 2674 2675 return status; 2676 2677} 2678 2679 2680// Binary compatibility reserved method space 2681OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 1 ); 2682OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 2 ); 2683OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 3 ); 2684OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 4 ); 2685OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 5 ); 2686OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 6 ); 2687OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 7 ); 2688OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 8 ); 2689OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 9 ); 2690OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 10 ); 2691OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 11 ); 2692OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 12 ); 2693OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 13 ); 2694OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 14 ); 2695OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 15 ); 2696OSMetaClassDefineReservedUnused ( IOATAPIProtocolTransport, 16 ); 2697 2698 2699//-------------------------------------------------------------------------------------- 2700// End Of File 2701//-------------------------------------------------------------------------------------- 2702