home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1999 August: Tool Chest / Dev.CD Aug 99 TC.toast / What's New? / Development Kits / Hardware / Mac OS USB DDK v1.3a1 / Examples / PrinterClassDriver / PrinterClassDriver.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-06-16  |  120.6 KB  |  3,682 lines  |  [TEXT/MPS ]

  1. /*
  2.     File:        PrinterClassDriver.c
  3.  
  4.     Contains:    MacOS USB printer class driver
  5.                 [ref. IEEE Std 1284-1994]
  6.  
  7.     Version:    xxx put version here xxx
  8.  
  9.  
  10.  
  11.     Copyright:    1998 by Apple Computer, Inc., all rights reserved.
  12.  
  13. */
  14.  
  15.  
  16. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  17.     includes
  18.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  19. #include <Gestalt.h>
  20. #include <Devices.h>
  21. #include <DriverServices.h>
  22. #include <Interrupts.h>
  23. #include <LowMem.h>
  24. #include <Folders.h>
  25. #include <String.h>
  26. #include <stdio.h>
  27. #include <ctype.h>
  28. #include <USB.h>
  29.  
  30. #ifndef __CODEFRAGMENTS__
  31. #include <codefragments.h>
  32. #endif
  33.  
  34. #include "PrinterClassDriver.h"
  35. #include "TradDriverLoaderLib.h"
  36.  
  37. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  38.     constants
  39.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  40. #define MAX_SUFFIX                    127                    // maximum copies we'll enter in unit table
  41. #define kUSBParallelDrvrRsrcID        12
  42. #define kMinDrvrUnitNumber            48                    // minimum unit table entry which we'll install
  43. #define kUSS720MillisecondDelay        3*1000                // poll every three seconds
  44. #define kUSS720StatusMSDelay        100                    // poll ten times per second
  45. #define MAX_USB_TRANSFER_SIZE        TRANSFER_SIZE        // zero acts as manifest for conditional compilation
  46.  
  47. #define kUSBAttributeBulk            0x02
  48. #define kUSBInputEndpointMask        0x80
  49.  
  50. #define kDebugStatusLevel            5
  51. #define kNormalStatusLevel            4
  52.  
  53.  
  54. enum
  55. {
  56.     kUSBv12    =    0x01200000
  57. };
  58.  
  59. enum
  60. {
  61.     kCString = 0,                // StateStr, USBStatusStr selector
  62.     kPString,                    // StateStr, USBStatusStr selector
  63.     kDrvrFirstDigit = 5            // length_byte + ".USB" = 5
  64. };
  65. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  66.     manifest constants
  67. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  68. //
  69. //    DEBUGGING                        extra debugging information to USB Expert Log
  70. //    DOUBLE_BUFFER                    use a page aligned buffer in system heap to double buffer app i/o
  71. //    LOG                                echo all the write data to a log file in the system folder
  72. // LOCK_MEMORY                        LockMemory on the i/o buffer before write and unlock on write completion
  73. // VIRTUAL_MEMORY_CHECK                check the physical addresses of the buffer we pass for write requests
  74. // MACSBUG_ON_READ                    break into MacsBug before each read request
  75. //    MACSBUG_ON_READ_COMPLETE        break into MacsBug at each read completion routine
  76. //    MACSBUG_ON_WRITE                break into MacsBug on each write request
  77. // MACSBUG_ON_WRITE_COMPLETE        break into MacsBug at each write completion routine
  78. //
  79. #define DEBUGGING                        0    /* DEBUGGING */
  80. #define DOUBLE_BUFFER                    1    /* DOUBLE_BUFFER */
  81. #define LOG                                0    /* LOG */
  82. #define LOCK_MEMORY                        1    /* LOCK_MEMORY */
  83. #define MACSBUG_ON_READ                    0    /* MACSBUG_ON_READ */
  84. #define MACSBUG_ON_READ_COMPLETE        0    /* MACSBUG_ON_READ_COMPLETE */ 
  85. #define MACSBUG_ON_WRITE                0    /* MACSBUG_ON_WRITE */
  86. #define MACSBUG_ON_WRITE_COMPLETE        0    /* MACSBUG_ON_WRITE_COMPLETE */ 
  87. #define VIRTUAL_MEMORY_CHECK            0    /* VIRTUAL_MEMORY_CHECK requires LOCK_MEMORY */
  88.  
  89. #if LOG
  90. #define LOGGING(x)    x
  91. #include <stdio.h>
  92. #else
  93. #define LOGGING(x)
  94. #endif
  95.  
  96. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  97.     globals
  98.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  99. static struct usbPrinterPBStruct    printerClassRecord;
  100. static FSSpec                            printerClassDriverFileSpec;
  101. LOGGING( static FILE                    *logfile );
  102.  
  103. volatile enum{
  104.     kUSBPrintSuspended,
  105.     kUSBPrintResumed
  106.     }wantToBe = kUSBPrintResumed, currentlyAre = kUSBPrintResumed;
  107.  
  108. // These for resuming reads and writes which were delayed due to resume
  109.  
  110. IOParamPtr Wpb; DCtlPtr Wctl; struct usbPrinterPBStruct *WpPrinterPB;
  111. IOParamPtr Rpb; DCtlPtr Rctl; struct usbPrinterPBStruct *RpPrinterPB;
  112.  
  113. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  114.     prototypes
  115.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  116.  
  117. static void    PrinterDeviceCompletionProc(USBPB *pb);
  118. static void SetNullUSBParamBlock( USBDeviceRef dev, USBPB *pb );
  119. static void    SoftReset( USBPB *usbprint, short interfaceNum );
  120. static void    ClearEndpointHalt( USBPB *usbprint);
  121. static void    CapabilityRequest( USBPB *pb, Ptr p, long length, short config, short interfaceNum, short alternateSetting );
  122. static void    CentronicsStatus( USBPB *usbprint, Ptr p, short interfaceNum );
  123. static void CompletionProc(USBPB *pb);
  124.  
  125. void            PrinterDeviceInitiateTransaction(USBPB *pb);
  126.  
  127. OSErr            CFMInitialization( CFragInitBlock *initBlock );
  128.  
  129. Boolean    gUSBVersionNeedsBulkFixPresent;
  130.  
  131. void        CheckUSBVersion(void);
  132. OSStatus     SecondaryUSBBulkRead(void *pb, void *result);
  133. OSStatus     SecondaryUSBBulkWrite(void *pb, void *result);
  134. OSStatus     SafeUSBBulkRead(USBPB *pb);
  135. OSStatus     SafeUSBBulkWrite(USBPB *pb);
  136.  
  137. void    CheckUSBVersion(void)
  138. {
  139. OSStatus    err;
  140. UInt32        usbVersion;
  141.  
  142.     err = Gestalt('usbv', (long*)&usbVersion);
  143.     if (err == noErr)
  144.         gUSBVersionNeedsBulkFixPresent = (usbVersion < kUSBv12);
  145. }
  146.  
  147. OSStatus SecondaryUSBBulkRead(void *pb, void *result)
  148. {
  149.     *(OSStatus*)result = USBBulkRead((USBPB*)pb);
  150.     return noErr;
  151. }
  152.  
  153. OSStatus SecondaryUSBBulkWrite(void *pb, void *result)
  154. {
  155.     *(OSStatus*)result = USBBulkWrite((USBPB*)pb);
  156.     return noErr;
  157. }
  158.  
  159. OSStatus SafeUSBBulkRead(USBPB *pb)
  160. {
  161.     OSStatus    result;
  162.  
  163.     if (gUSBVersionNeedsBulkFixPresent)
  164.     {
  165.         // Use CallSecondaryInterruptHandler2 to call USBBulkRead if
  166.         // less than USB v1.2 present
  167.         CallSecondaryInterruptHandler2(SecondaryUSBBulkRead, nil, pb, &result);
  168.     }
  169.     else
  170.         result = USBBulkRead(pb);
  171.         
  172.     return result;
  173. }
  174.  
  175. OSStatus SafeUSBBulkWrite(USBPB *pb)
  176. {
  177.     OSStatus    result;
  178.  
  179.     if (gUSBVersionNeedsBulkFixPresent)
  180.     {
  181.         // Use CallSecondaryInterruptHandler2 to call USBBulkWrite if
  182.         // less than USB v1.2 present
  183.         CallSecondaryInterruptHandler2(SecondaryUSBBulkWrite, nil, pb, &result);
  184.     }
  185.     else
  186.         result = USBBulkWrite(pb);
  187.         
  188.     return result;
  189. }
  190.  
  191.  
  192.  
  193.  
  194. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  195.     Name:        HexString8
  196.  
  197.     Input Parameters:    
  198.         v                unsigned long value
  199.         
  200.     Output Parameters:
  201.         p                8 bytes: hex string representing value
  202.         
  203.     Description:
  204.  
  205.  
  206.  
  207. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  208. static void
  209. HexString8( unsigned long v, unsigned char *p )
  210. {
  211.     short    shift;
  212.     
  213.     for ( shift = 32-4; shift >= 0; shift -= 4 )
  214.     {
  215.         char c = (v >> shift) & 0x0F;
  216.         *p++ = c + (c > 9? ('A'-10): '0');
  217.     }
  218. }
  219.  
  220. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  221.     Name:        hexstr
  222.  
  223.     Input Parameters:    
  224.         count                number of bytes
  225.         p                    pointer to bytes
  226.         
  227.     Output Parameters:
  228.         q                    hex dump of data
  229.         
  230.     Description:
  231.  
  232.  
  233.  
  234. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  235. void hexstr( long count, char *p, char *q )
  236. {
  237.     char *s = p;
  238.     long i = count;
  239.     for ( ; count > 0; --count, ++p )
  240.     {
  241.         UInt8 hi, lo;
  242.         hi = (*p >> 4)& 0x0F;
  243.         lo = *p & 0x0F;
  244.         *q++ = '0';
  245.         *q++ = 'x';
  246.         *q++ = hi + (hi > 9? 'A' - 10: '0');
  247.         *q++ = lo + (lo > 9? 'A' - 10: '0');
  248.         *q++ = ' ';
  249.     }
  250.     for ( ; i > 0; --i, ++s )
  251.         *q++ = *s < ' ' || *s > 0x7E? '.': *s;
  252. }
  253.  
  254. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  255.     Name:        ForceUpperStr
  256.  
  257.     Input Parameters:    
  258.         s                    pointer to a null terminated string
  259.         
  260.     Output Parameters:
  261.         s                    string modified by using toupper() on each character.
  262.         
  263.     Description:
  264.  
  265.  
  266.  
  267. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  268. void 
  269. ForceUpperStr(char *s)
  270. {
  271.     while(*s){
  272.         toupper(*s);
  273.         s++;
  274.     }
  275. }
  276.     
  277. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  278.     Name:        MakeNameRegistrySafeStr
  279.  
  280.     Input Parameters:    
  281.         s                    pointer to a null terminated string
  282.         
  283.     Output Parameters:
  284.         s                    string modified by replacing / with - on each character.
  285.         
  286.     Description:
  287.  
  288.  
  289.  
  290. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  291. void 
  292. MakeNameRegistrySafeStr(char *s)
  293. {
  294.     while (*s)
  295.     {
  296.         if (*s == '/') 
  297.             *s = '-';
  298.         s++;
  299.     }
  300. }
  301.  
  302.  
  303.  
  304. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  305.     Name:        USBStatusStr
  306.  
  307.     Input Parameters:    
  308.         usbStatus            usb error code
  309.         kind                    kPString or kCString
  310.         
  311.     Output Parameters:
  312.         unsigned char *    description of error (c-string or p-string)
  313.  
  314.     Description:
  315.         a simple mapping of errors to human-readable form
  316.  
  317.  
  318.  
  319.  
  320.  
  321. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  322. static unsigned char *
  323. USBStatusStr( OSStatus usbStatus, short kind )
  324. {
  325.     unsigned char *p;
  326.  
  327.     switch ( usbStatus )
  328.     {
  329.         case    kUSBInternalErr:                    p = kPStrPrinterDriverName"Internal error"; break;
  330.         case    kUSBUnknownDeviceErr:                p = kPStrPrinterDriverName"Unknown device"; break;
  331.         case    kUSBUnknownPipeErr:                 p = kPStrPrinterDriverName"Unknown pipe"; break;
  332.         case    kUSBTooManyPipesErr:                p = kPStrPrinterDriverName"Too many pipes"; break;
  333.         case    kUSBIncorrectTypeErr:                p = kPStrPrinterDriverName"Incorrect type"; break;
  334.         case    kUSBRqErr:                            p = kPStrPrinterDriverName"Request error"; break;
  335.         case    kUSBUnknownRequestErr:                p = kPStrPrinterDriverName"Unknown request"; break;
  336.         case    kUSBTooManyTransactionsErr:            p = kPStrPrinterDriverName"Too many transactions"; break;
  337.         case    kUSBAlreadyOpenErr:                    p = kPStrPrinterDriverName"Already open"; break;
  338.         case    kUSBNoDeviceErr:                    p = kPStrPrinterDriverName"No device"; break;
  339.         case    kUSBDeviceErr:                        p = kPStrPrinterDriverName"Device error"; break;
  340.         case    kUSBOutOfMemoryErr:                    p = kPStrPrinterDriverName"Out of memory"; break;
  341.         case    kUSBNotFound:                        p = kPStrPrinterDriverName"Not found"; break;
  342.         case    kUSBLinkErr:                        p = kPStrPrinterDriverName"Link Err"; break;
  343.         case    kUSBCRCErr:                            p = kPStrPrinterDriverName"Comms/Device err, bad CRC";  break;        
  344.         case    kUSBBitstufErr:                        p = kPStrPrinterDriverName"Comms/Device err, bitstuffing"; break;        
  345.         case    kUSBDataToggleErr:                    p = kPStrPrinterDriverName"Comms/Device err, Bad data toggle"; break;        
  346.         case    kUSBEndpointStallErr:                p = kPStrPrinterDriverName"Device didn't understand"; break;        
  347.         case    kUSBNotRespondingErr:                p = kPStrPrinterDriverName"No device, device hung"; break;        
  348.         case    kUSBPIDCheckErr:                    p = kPStrPrinterDriverName"Comms/Device err, PID CRC error"; break;        
  349.         case    kUSBWrongPIDErr:                    p = kPStrPrinterDriverName"Comms/Device err, Bad or wrong PID"; break;        
  350.         case    kUSBOverRunErr:                        p = kPStrPrinterDriverName"Packet too large or more data than buffer"; break;        
  351.         case    kUSBUnderRunErr:                    p = kPStrPrinterDriverName"Less data than buffer"; break;        
  352.         case    kUSBRes1Err:                        p = kPStrPrinterDriverName"kUSBRes1Err"; break;        
  353.         case    kUSBRes2Err:                        p = kPStrPrinterDriverName"kUSBRes1Err"; break;        
  354.         case    kUSBBufOvrRunErr:                    p = kPStrPrinterDriverName"Buffer over run error"; break;        
  355.         case    kUSBBufUnderRunErr:                    p = kPStrPrinterDriverName"Buffer under run error"; break;        
  356.         case    kUSBNotSent1Err:                    p = kPStrPrinterDriverName"Transaction not sent1"; break;        
  357.         case    kUSBNotSent2Err:                    p = kPStrPrinterDriverName"Transaction not sent2"; break;    
  358.         default:
  359.             p = kPStrPrinterDriverName"Unknown error nnnnnnnn";
  360.             HexString8( usbStatus, p + *p - 8 + 1 );
  361.             break;
  362.     }
  363.     
  364.     return kind == kPString? p: p + 1;
  365. }
  366.  
  367. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  368.     Name:        StateStr
  369.  
  370.     Input Parameters:    
  371.         usbRefCon            usb error code
  372.         kind                    kPString or kCString
  373.         
  374.     Output Parameters:
  375.         unsigned char *    description of state (c-string or p-string)
  376.  
  377.     Description:
  378.         a simple mapping of states to human-readable form
  379.  
  380.  
  381.  
  382.  
  383.  
  384. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  385. static unsigned char *
  386. StateStr( OSStatus refCon, short kind )
  387. {
  388.     unsigned char *p;
  389.  
  390.     refCon &= ~(kTransactionPending | kRetryTransaction | kReturnFromDriver);
  391.     switch ( refCon )
  392.     {
  393.         case kUndefined:                            p = kPStrPrinterDriverName"kUndefined"; break;
  394.         case kNilCompletion:                        p = kPStrPrinterDriverName"kNilCompletion"; break;
  395.  
  396.         case kFindInterface_bidirectional:            p = kPStrPrinterDriverName"kFindInterface_bidirectional"; break;
  397.         case kFindInterface_unidirectional:            p = kPStrPrinterDriverName"kFindInterface_unidirectional"; break;
  398.         case kOpenDevice:                            p = kPStrPrinterDriverName"kOpenDevice"; break;
  399.         case kNewInterfaceRef:                        p = kPStrPrinterDriverName"kNewInterfaceRef"; break;
  400.  
  401.         case kSetInterface:                            p = kPStrPrinterDriverName"kSetInterface"; break;
  402.         case kConfigureInterface:                    p = kPStrPrinterDriverName"kConfigureInterface"; break;
  403.         case kGetCapabilityString:                    p = kPStrPrinterDriverName"kGetCapabilityString"; break;
  404.         case kDelayGetCapability:                    p = kPStrPrinterDriverName"kDelayGetCapability"; break;
  405.  
  406.         case kAllocateCapabilityMem:                p = kPStrPrinterDriverName"kAllocateCapabilityMem"; break;
  407.         case kGetFullCapabilityString:                p = kPStrPrinterDriverName"kGetFullCapabilityString"; break;
  408.         case kGetInterface:                            p = kPStrPrinterDriverName"kGetInterface"; break;
  409.         case kFindBulkOutPipe:                        p = kPStrPrinterDriverName"kFindBulkOutPipe"; break;
  410.  
  411.         case kFindBulkInPipe:                        p = kPStrPrinterDriverName"kFindBulkInPipe"; break;
  412.         case kTaskTimeRequired:                        p = kPStrPrinterDriverName"kTaskTimeRequired"; break;
  413.  
  414.         case kGetCentronicsStatus:                    p = kPStrPrinterDriverName"kGetCentronicsStatus"; break;
  415.         case kDelayGetCentronicsStatus:                p = kPStrPrinterDriverName"kDelayGetCentronicsStatus"; break;
  416.  
  417.         case kDeallocateCapbilityString:            p = kPStrPrinterDriverName"kDeallocateCapbilityString"; break;
  418.         default:
  419.             p = kPStrPrinterDriverName"Unknown state nnnnnnnn";
  420.             HexString8( refCon, p + *p - 8 + 1 );
  421.             break;
  422.     }
  423.     return kind == kPString? p: p + 1;    
  424. }
  425.  
  426. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  427.     Name:        HiHex
  428.  
  429.     Input Parameters:    
  430.         v                        only low byte used
  431.         
  432.     Output Parameters:
  433.         <function result>    high nibble represented as ASCII char
  434.         
  435.     Description:
  436.  
  437.  
  438.  
  439. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  440. static unsigned char
  441. HiHex( unsigned char v )
  442. {
  443.     unsigned char    hinibble = (v >> 4) & 0x0f;
  444.     return hinibble + ((hinibble > 9)? ('A'-10): '0');
  445. }
  446.  
  447. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  448.     Name:        LoHex
  449.  
  450.     Input Parameters:    
  451.         v                        only low byte used
  452.         
  453.     Output Parameters:
  454.         <function result>    low nibble represented as ASCII char
  455.         
  456.     Description:
  457.  
  458.  
  459.  
  460. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  461. static unsigned char
  462. LoHex( unsigned char v )
  463. {
  464.     unsigned char    lonibble = v & 0x0f;
  465.     return lonibble + ((lonibble > 9)? ('A'-10): '0');
  466. }
  467.  
  468. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  469.     Name:        immediateError
  470.  
  471.     Input Parameters:    
  472.         
  473.     Output Parameters:
  474.         
  475.     Description:
  476.  
  477.  
  478.  
  479. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  480. static Boolean
  481. immediateError(OSStatus err)
  482. {
  483.     return((err != kUSBPending) && (err != noErr) );
  484. }
  485.  
  486. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  487.     Name:        SetNullUSBParamBlock
  488.  
  489.     Input Parameters:    
  490.         pb                    pointer to USB parameter block
  491.         dev                USB device reference
  492.     Output Parameters:
  493.         pb                    all fields set to default values
  494.  
  495.     Description:
  496.         setup a USB parameter block for use by the current device
  497.  
  498.  
  499.  
  500.  
  501. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  502. static void
  503. SetNullUSBParamBlock( USBDeviceRef dev, USBPB *pb )
  504. {
  505.     pb->qlink = NULL;
  506.     pb->qType = 0;
  507.     pb->pbLength = sizeof(USBPB);
  508.     pb->pbVersion = kUSBCurrentPBVersion;
  509.     pb->usbFlags = 0;
  510.     pb->usbStatus = noErr;
  511.     pb->usbCompletion = (USBCompletion) NULL;
  512.  
  513.     pb->usbReference = dev;
  514. }
  515.  
  516. // BT - 15Jun99, Callback for the suspend call.
  517. static void usbPrintResume(USBPB *pb)
  518. {
  519. IOParamPtr resumePB;
  520. DCtlPtr resumeCtl;
  521. struct usbPrinterPBStruct *resumePrinterPB;
  522.  
  523.     if(pb->usbStatus != noErr)
  524.     {
  525.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver USBPrintDoSuspendResume error", pb->usbStatus);
  526.     }
  527.     else
  528.     {
  529.         currentlyAre = kUSBPrintResumed;
  530.         if(Wpb != nil)
  531.         {
  532.             // We have to restart a waiting write
  533.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver resumeing write", 0);
  534.             resumeCtl = Wctl;
  535.             resumePrinterPB = WpPrinterPB;
  536.             resumePB = Wpb;
  537.             Wpb = nil;
  538.             QueueWrite(resumePB, resumeCtl, resumePrinterPB);
  539.         }
  540.     
  541.         if(Rpb != nil)
  542.         {
  543.             // We have to restart a waiting write
  544.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver resumeing read", 0);
  545.             resumeCtl = Rctl;
  546.             resumePrinterPB = RpPrinterPB;
  547.             resumePB = Rpb;
  548.             Rpb = nil;
  549.             QueueRead(resumePB, resumeCtl, resumePrinterPB);
  550.         }
  551.     }
  552.     pb->usbRefcon = 0;
  553. }
  554.  
  555. // BT - 15Jun99, work out if we need to and can suspend or resume and do it.
  556. static USBPrintDoSuspendResume(USBDeviceRef ref)
  557. {
  558. static USBPB pb;
  559. OSStatus err;
  560.     if(wantToBe != currentlyAre)
  561.     {
  562.         if(currentlyAre == kUSBPrintSuspended)
  563.         {
  564.             USBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver resuming device", ref);
  565.             err = USBResumeDeviceByReference(ref);
  566.         }
  567.         else if(wantToBe == kUSBPrintSuspended)
  568.         {
  569.             if( (printerClassRecord.pb.usbCompletion != nil) || 
  570.                 (printerClassRecord.in.usbCompletion != nil) || 
  571.                 (printerClassRecord.out.usbCompletion != nil) )
  572.             {
  573.                 USBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver can't suspend, busy", (UInt32) printerClassRecord.pb.usbCompletion);
  574.                 return(noErr);
  575.             }
  576.         
  577.             if(pb.usbRefcon != 0)
  578.             {
  579.                 USBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver suspend already in process", err);
  580.                 return(noErr);
  581.             }
  582.             USBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver suspending device", ref);
  583.             SetNullUSBParamBlock(ref, &pb);
  584.             pb.usbCompletion = usbPrintResume;
  585.             pb.usbRefcon = 1;
  586.             currentlyAre = kUSBPrintSuspended;
  587.             err = USBSuspendDevice(&pb);
  588.         }
  589.         if( (err != kUSBPending) && (err != noErr) )
  590.         {
  591.             USBExpertStatusLevel(2, ref, "\pUSB print driver USBPrintDoSuspendResume error", err);
  592.         }
  593.     }
  594.     return(noErr);
  595. }
  596.  
  597.  
  598.  
  599.  
  600.  
  601. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  602.     Name:        ParseCapability
  603.  
  604.     Input Parameters:    
  605.         capability            pointer to 1284-1994 capability string
  606.         attribute            pointer to c-string key we're retrieving (terminate with colon)
  607.         *result_length        maximum length of the result 
  608.         
  609.     Output Parameters:
  610.         result                c-string which followed the key and was terminated by semi-colon
  611.                                 (semi-colon has been stripped)
  612.         *result_length        actual length of the result (may be zero)
  613.     
  614.     Description:
  615.         Search for "attribute" in the 1284 "capability" string
  616.         The identifier is terminated with a semi-colon
  617.  
  618.         Return the attribute in result
  619.             null-string if attribute not found.
  620.  
  621.  
  622.  
  623.  
  624. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  625. static void
  626. ParseCapability(
  627.     unsigned char    *capability,
  628.     unsigned char    *attribute,
  629.     unsigned char    *result,
  630.     short            *result_length 
  631. )
  632. {
  633.     //
  634.     //    search for "attribute" in the 1284 "capability" string
  635.     //
  636.     //    the identifier is terminated with a semi-colon
  637.     //
  638.     //    return the attribute in result
  639.     //            null-string if attribute not found
  640.     //
  641.     //    <to do> skip blanks, isolate colon, skip blanks
  642.     //
  643.     UInt32                source_length;
  644.     UInt16                target_length;
  645.     unsigned char        *source,
  646.                         *target,
  647.                         *destination;
  648.     //
  649.     //    begin a brute force search
  650.     //
  651.     source = attribute;
  652.     source_length = CStrLen((char *)attribute );
  653.  
  654.     target = capability + 2;    // skip the length
  655.     target_length =  *(UInt16*)capability;
  656.     if (target_length >= 2)
  657.         target_length -= 2;            // don't count the length
  658.     else
  659.         target_length = 0;
  660.         
  661.     while ( target_length >= source_length )
  662.     {
  663.         if ( memcmp( source, target, source_length ) == 0 )
  664.             break;
  665.         --target_length;
  666.         ++target;
  667.     }
  668.  
  669.     *result = '\0';    // empty result
  670.     destination = result;
  671.  
  672.     target += source_length;
  673.     target_length -= source_length;    // skip the attribute string
  674.  
  675.     if ( target_length > 0 )
  676.     {
  677.         //
  678.         //    we found the attribute in the capability string
  679.         //
  680.         while ( destination - result < *result_length )    // arbitrarily limit reply
  681.         {
  682.             if ( *target == ';' )
  683.                 break;
  684.             *destination++ = *target++;        // copy a byte of attribute over
  685.         }
  686.         *destination++ = '\0';                        // trailing NUL
  687.         *result_length = destination - result;    // report the length of the data (with trailing NUL)
  688.     }
  689. }
  690.  
  691.  
  692. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  693.     Name:        GetClass
  694.  
  695.     Input Parameters:    
  696.         capability            pointer to 1284-1994 capability string
  697.         *result_length        maximum length of the result 
  698.         
  699.     Output Parameters:
  700.         result                c-string extracted from the MODEL key
  701.         *result_length        actual length of the result  (may be zero)
  702.         
  703.     Description:
  704.         CLASS is a Microsoft extension to the 1284-capability string
  705.         if we don't find it
  706.             we assume that the device is a printer
  707.         Since the USB hardware has already indicated this, we're really allowing
  708.         devices which aren't printers to be reached via the DRVRs we've installed.
  709.  
  710.  
  711.  
  712.  
  713. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  714. static void
  715. GetClass(
  716.     unsigned char    *capability,
  717.     unsigned char    *result,
  718.     short            *result_length
  719. )
  720. {
  721.     //
  722.     //    We supply the upper-case PRINTER to be consistent with 1284-1994
  723.     //        if we don't find a class.
  724.     //
  725.     ParseCapability( capability, (unsigned char *) "CLASS:", result, result_length);
  726.     if ( *result == '\0' )
  727.         ParseCapability( capability, (unsigned char *) "CLS:", result, result_length);
  728.     if ( *result == '\0' )
  729.         CStrCopy( (char *)result, "PRINTER" );
  730. }
  731.  
  732.  
  733. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  734.     Name:        GetModel
  735.  
  736.     Input Parameters:    
  737.         capability            pointer to 1284-1994 capability string
  738.         *result_length        maximum length of the result 
  739.         
  740.     Output Parameters:
  741.         result                c-string extracted from the MODEL key
  742.         *result_length        actual length of the result  (may be zero)
  743.             
  744.     Description:
  745.         MODEL is a required field of the 1284-capability string
  746.         MODEL may be abbreviated MDL
  747.  
  748.  
  749.  
  750.  
  751. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  752. static void
  753. GetModel(
  754.     unsigned char    *capability, 
  755.     unsigned char    *result,
  756.     short            *result_length
  757. )
  758. {
  759.     //
  760.     //    Most manufacturers abbreviate, so we search for MDL first
  761.     //
  762.     ParseCapability( capability, (unsigned char *) "MDL:", result, result_length );
  763.     if ( *result == '\0' )
  764.         ParseCapability( capability, (unsigned char *) "MODEL:", result, result_length );
  765. }
  766.  
  767.  
  768. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  769.     Name:        GetCommandSet
  770.  
  771.     Input Parameters:    
  772.         
  773.     Output Parameters:
  774.         
  775.     Description:
  776.  
  777.  
  778.  
  779.  
  780. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  781. static void
  782. GetCommandSet(
  783.     unsigned char    *capability, 
  784.     unsigned char    *result,
  785.     short              *result_length
  786. )
  787. {
  788.     //
  789.     //    COMMAND-SET is a required field of the 1284-capability string
  790.     //    COMMAND-SET may be abbreviated CMD
  791.     //
  792.     ParseCapability( capability, (unsigned char *) "CMD:", result, result_length );
  793.     if ( *result == '\0' )
  794.         ParseCapability( capability, (unsigned char *) "COMMAND SET:", result, result_length );
  795. }
  796.  
  797. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  798.     Name:        GetManufacturer
  799.  
  800.     Input Parameters:    
  801.         
  802.     Output Parameters:
  803.         
  804.     Description:
  805.  
  806.  
  807.  
  808. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  809. static void
  810. GetManufacturer(
  811.     unsigned char *capability, 
  812.     unsigned char *result,
  813.     short *result_length
  814. )
  815. {
  816.     //
  817.     //    MANUFACTURER is a required field of the 1284-capability string
  818.     //    MANUFACTURER may be abbreviated MFG
  819.     //
  820.     ParseCapability( capability, (unsigned char *) "MFG:", result, result_length );
  821.     if ( *result == '\0' )
  822.         ParseCapability( capability, (unsigned char *) "MANUFACTURER:", result, result_length );
  823.     if ( *result == '\0' )
  824.         ParseCapability( capability, (unsigned char *) "HMFG:", result, result_length );
  825. }
  826.  
  827.  
  828. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  829.     Name:        DeregisterDevice
  830.  
  831.     Input Parameters:    
  832.         pPrinterPB
  833.  
  834.     Output Parameters:
  835.         <none>
  836.         
  837.     Description:
  838.         remove the device from the name registry
  839.  
  840.  
  841.  
  842.  
  843. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  844. #define kMinNameLength    27
  845. #define kMinModelLength    25
  846. #define kMinClassLength    23
  847.  
  848. static OSStatus
  849. DeregisterDevice( struct usbPrinterPBStruct *pPrinterPB )
  850. {
  851. RegEntryID            self, child, parent;
  852. RegEntryIter         cookie;
  853.  
  854. OSStatus    err = noErr;
  855. Str255        tempStr1,tempStr2;
  856. UInt32        nameLength, modelLength,devclassLength;
  857. Boolean     done = false;
  858.  
  859.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Removing the printer from the name registry", 0 );
  860.     // delete the printer node
  861.     // print out the printer's name (which is the same as the node name)
  862.     nameLength = CStrLen((char *)pPrinterPB->name);
  863.     CStrCopy((char *)tempStr1, (char *)(kCStrPrinterDriverName"Printer name:  "));
  864.     CStrCat((char *)tempStr1, (char *)pPrinterPB->name);
  865.     CStrToPStr((unsigned char *)tempStr2, (char *)tempStr1 );
  866.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempStr2, nameLength );
  867.     
  868.     // locate the model node (parent of printer), and delete it if the printer has no siblings
  869.     if (nameLength<kMinNameLength)
  870.     {
  871.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Warning!! Printer name string is not long enough!", nameLength);
  872.     }
  873.     else
  874.     {
  875.         RegistryEntryIDInit( &self );
  876.         err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->name , &self );
  877.         if ( err == noErr )
  878.         {    
  879.             err = RegistryEntryDelete( &self);
  880.         }
  881.         else
  882.         {
  883.             USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Printer node not found!", err );
  884.         }
  885.         RegistryEntryIDDispose(&self);
  886.         
  887.         if (err == noErr &&  pPrinterPB->outRefNum != -1 )
  888.             err = TradRemoveDriver( pPrinterPB->outRefNum, false );
  889.         if (err == noErr &&  pPrinterPB->inRefNum != -1 )
  890.             err = TradRemoveDriver( pPrinterPB->inRefNum, false );
  891.     }
  892.  
  893.  
  894.     // print out the printer's model (which is the same as the node's parent)
  895.     modelLength = CStrLen((char *)pPrinterPB->model);
  896.     CStrCopy((char *)tempStr1, (char *)(kCStrPrinterDriverName"Printer model: "));
  897.     CStrCat((char *)tempStr1, (char *)pPrinterPB->model);
  898.     CStrToPStr((unsigned char *)tempStr2, (char *)tempStr1 );
  899.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempStr2, modelLength );
  900.     
  901.  
  902.     // locate the model node (parent of printer), and delete it if the printer has no siblings
  903.     if (modelLength<kMinModelLength)
  904.     {
  905.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Warning!! Printer model string is not long enough!", modelLength);
  906.     }
  907.     else
  908.     {
  909.         RegistryEntryIDInit( &parent );
  910.         err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->model , &parent );
  911.         if ( err == noErr )
  912.         {    
  913.             RegistryEntryIDInit(&child);
  914.             
  915.             err = RegistryEntryIterateCreate(&cookie);
  916.             if (err == noErr)
  917.                 err = RegistryEntryIterateSet(&cookie, &parent);
  918.             if (err == noErr)
  919.                 err = RegistryEntryIterate(&cookie, kRegIterChildren, &child, &done);
  920.             if ((err == noErr) && done)
  921.             {
  922.                 USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"No siblings detected, so delete the parent of printer", 0 );
  923.                 err = RegistryEntryDelete(&parent);
  924.             }
  925.             else
  926.             {
  927.                 USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Siblings (or error) detected.  Leaving parent in place", err );
  928.             }
  929.             RegistryEntryIterateDispose(&cookie);
  930.         }
  931.         else
  932.         {
  933.             USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Parent node not found!", err );
  934.         }
  935.         RegistryEntryIDDispose(&parent);
  936.     }
  937.     
  938.     // print out the printer's model (which is the same as the node's parent)
  939.     devclassLength = CStrLen((char *)pPrinterPB->devclass);
  940.     CStrCopy((char *)tempStr1, (char *)(kCStrPrinterDriverName"Printer class: "));
  941.     CStrCat((char *)tempStr1, (char *)pPrinterPB->devclass);
  942.     CStrToPStr((unsigned char *)tempStr2, (char *)tempStr1 );
  943.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempStr2, devclassLength );
  944.     
  945.  
  946.     // locate the class node (parent of model), and delete it if the class has no siblings
  947.     if (devclassLength<kMinClassLength)
  948.     {
  949.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Warning!! Printer class string not long enough!", devclassLength);
  950.     }
  951.     else
  952.     {
  953.         RegistryEntryIDInit( &parent );
  954.         err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->devclass , &parent );
  955.         if ( err == noErr )
  956.         {    
  957.             RegistryEntryIDInit(&child);
  958.             
  959.             err = RegistryEntryIterateCreate(&cookie);
  960.             if (err == noErr)
  961.                 err = RegistryEntryIterateSet(&cookie, &parent);
  962.             if (err == noErr)
  963.                 err = RegistryEntryIterate(&cookie, kRegIterChildren, &child, &done);
  964.             if ((err == noErr) && done)
  965.             {
  966.                 USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"No models found, so delete the class node", 0 );
  967.                 err = RegistryEntryDelete(&parent);
  968.             }
  969.             else
  970.             {
  971.                 USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Models detected.  Leaving class nodes in place", err );
  972.             }
  973.             RegistryEntryIterateDispose(&cookie);
  974.         }
  975.         else
  976.         {
  977.             USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Parent node not found!", err );
  978.         }
  979.         RegistryEntryIDDispose(&parent);
  980.     }
  981.     
  982.     return err;
  983. }
  984.  
  985. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  986.     Name:        RegisterDevice
  987.  
  988.     Input Parameters:    
  989.         pPrinterPB
  990.  
  991.     Output Parameters:
  992.         <none>
  993.         
  994.     Description:
  995.         add the device into the name registry; we can't insert just the node
  996.         if the parent nodes aren't present.
  997.  
  998.         if it isn't present
  999.             insert the device CLASS into the registry
  1000.         if it isn't present
  1001.             insert the device MODEL into the registry
  1002.         finally insert the device itself into the registry
  1003.             we're careful to rename multiple devices
  1004.  
  1005.  
  1006.  
  1007.  
  1008.  
  1009.  
  1010.  
  1011.  
  1012.  
  1013. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1014. static OSStatus
  1015. RegisterDevice( struct usbPrinterPBStruct *pPrinterPB )
  1016. {
  1017.     //
  1018.     //    add the device into the name registry
  1019.     //    if it isn't present
  1020.     //        insert the device CLASS into the registry
  1021.     //    if it isn't present
  1022.     //        insert the device MODEL into the registry
  1023.     //    finally insert the device itself into the registry
  1024.     //        we're careful to rename multiple devices
  1025.     //
  1026. Str255        identification,
  1027.                 devclass,
  1028.                 model,
  1029.                 nameregmodel,
  1030.                 commands,
  1031.                 tempstr;
  1032.                 
  1033. RegEntryID    parent, where, self;
  1034.  
  1035. OSStatus        err;
  1036.  
  1037. short            model_length,
  1038.                 command_length,
  1039.                 class_length;
  1040.  
  1041.  
  1042.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Adding the printer to the name registry", 0 );
  1043.     CStrCopy((char *)pPrinterPB->devclass, "");
  1044.     CStrCopy((char *)pPrinterPB->model, "");
  1045.     CStrCopy((char *)pPrinterPB->name, "");
  1046.  
  1047.     command_length = sizeof(commands);
  1048.     GetCommandSet(pPrinterPB->pCapabilityString, commands, &command_length );
  1049.  
  1050.  
  1051.     // get device class and add it to the name registry.  Typically PRINTER or Printer
  1052.     class_length = sizeof(devclass);
  1053.     GetClass( pPrinterPB->pCapabilityString, devclass, &class_length );
  1054.     // force the device class to all uppercase.
  1055.     ForceUpperStr((char *)devclass);
  1056.     
  1057.     CStrCopy( (char *)pPrinterPB->devclass, (char *)"Devices:device-tree:" );
  1058.     CStrCat( (char *)pPrinterPB->devclass, (char *)devclass );
  1059.     
  1060.     RegistryEntryIDInit( &where );
  1061.     err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->devclass, &where );
  1062.     if ( err == nrPathNotFound ) 
  1063.     {
  1064.         //    class not in registry
  1065.         //        create a node for all devices of this CLASS
  1066.         //
  1067.         RegistryEntryIDInit( &parent );
  1068.         err = RegistryCStrEntryLookup( nil, "Devices:device-tree:" , &parent );
  1069.         if ( err == noErr )
  1070.             err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->devclass, &where );
  1071.         RegistryEntryIDDispose(&parent);
  1072.  
  1073.     }
  1074.     
  1075.     CStrToPStr(tempstr, (char *)pPrinterPB->devclass);
  1076.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempstr, 0 );
  1077.     
  1078.     //
  1079.     //    add this model into the name registry of this class
  1080.     //
  1081.     if ( err == noErr )
  1082.     {
  1083.         model_length = sizeof(model);
  1084.         GetModel( pPrinterPB->pCapabilityString, model, &model_length );
  1085.         CStrCopy( (char *)nameregmodel, (char *)model);
  1086.         MakeNameRegistrySafeStr((char *)nameregmodel);
  1087.         if ( *model != '\0' )
  1088.         {
  1089.             CStrCopy( (char *)pPrinterPB->model, "Devices:device-tree:" );
  1090.             CStrCat( (char *)pPrinterPB->model, (char *)devclass );
  1091.             CStrCat( (char *)pPrinterPB->model, ":" );
  1092.             if ( *model == '\0'  )
  1093.             {
  1094.                 CStrCat( (char *)pPrinterPB->model, (char *)"USB_PRINTERCLASS" );
  1095.             }
  1096.             else
  1097.             {
  1098.                 CStrCat( (char *)pPrinterPB->model, (char *)nameregmodel );
  1099.             }
  1100.             RegistryEntryIDInit( &self );
  1101.             err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->model , &self );
  1102.             if ( err != noErr )
  1103.             {
  1104.                 // model not in registry
  1105.                 err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->model, &self );
  1106.             }
  1107.             
  1108.             RegistryEntryIDDispose(&self);
  1109.         }
  1110.         CStrToPStr(tempstr, (char *)pPrinterPB->model);
  1111.         USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempstr, 0 );
  1112.     }
  1113.     
  1114.     //
  1115.     //    add this instance of this model of this class
  1116.     //        into the name registry
  1117.     //
  1118.     if ( *model == '\0'  )
  1119.     {
  1120.         //
  1121.         //    possibly the cable isn't firmly connected or the printer isn't switched on
  1122.         //
  1123.         err = kUSBInternalErr;
  1124.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Model undefined", 0);
  1125.     }
  1126.     if ( err == noErr )
  1127.     {
  1128.         //
  1129.         //    start off by identifying the device simply by the model name
  1130.         //        increment the numeric suffix until we successfully registry the device
  1131.         //
  1132.         Str32    suffix;
  1133.         short    numeric_suffix;
  1134.  
  1135.         CStrCopy( (char *)identification, (char *)nameregmodel );
  1136.         RegistryEntryIDInit( &self );
  1137.         for ( numeric_suffix = 1; numeric_suffix < MAX_SUFFIX; ++numeric_suffix )
  1138.         {
  1139.             CStrCopy( (char *)pPrinterPB->name, "Devices:device-tree:" );
  1140.             CStrCat( (char *)pPrinterPB->name, (char *)devclass );
  1141.             CStrCat( (char *)pPrinterPB->name, ":" );
  1142.             CStrCat( (char *)pPrinterPB->name, (char *)nameregmodel );
  1143.             CStrCat( (char *)pPrinterPB->name, ":" );
  1144.             CStrCat( (char *)pPrinterPB->name, (char *)identification );
  1145.             err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->name , &self );
  1146.             if ( err != noErr )
  1147.             {
  1148.                 // enter device in registry
  1149.                 err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->name, &self );
  1150.                 if ( err == noErr )
  1151.                 {
  1152.                     CStrCopy( (char *)identification, (char *)model );
  1153.                     if (numeric_suffix > 1)
  1154.                     {
  1155.                         sprintf( (char *)suffix, " %d", numeric_suffix-1 );
  1156.                         CStrCat( (char *)identification, (char *)suffix );
  1157.                     }
  1158.                     err = RegistryPropertyCreate( &self, "modelName", identification, strlen((char *)identification) );
  1159.                 }
  1160.                 if ( err == noErr )
  1161.                     err = RegistryPropertyCreate( &self, "drvrOut", &pPrinterPB->driverOutName, 1 + pPrinterPB->driverOutName[0] );
  1162.                 if ( err == noErr )
  1163.                     err = RegistryPropertyCreate( &self, "outRef", &pPrinterPB->outRefNum, sizeof(pPrinterPB->outRefNum) );
  1164.                 
  1165.                 if (pPrinterPB->printerProtocol != kUSBPrinterUnidirectionalProtocol)
  1166.                 {
  1167.                     if ( err == noErr )
  1168.                         err = RegistryPropertyCreate( &self, "drvrIn", &pPrinterPB->driverInName, 1 + pPrinterPB->driverInName[0] );
  1169.                     if ( err == noErr )
  1170.                         err = RegistryPropertyCreate( &self, "inRef", &pPrinterPB->inRefNum, sizeof(pPrinterPB->inRefNum) );
  1171.                 }
  1172.                 if ( err == noErr )
  1173.                     err = RegistryPropertyCreate( &self, "privateData", &pPrinterPB, sizeof(pPrinterPB) );
  1174.                 if ( err == noErr )
  1175.                     err = RegistryPropertyCreate( &self, "read", &pPrinterPB->r, sizeof(QueueUSBReadUPP) );
  1176.                 if ( err == noErr )
  1177.                     err = RegistryPropertyCreate( &self, "write", &pPrinterPB->w, sizeof(QueueUSBWriteUPP) );
  1178.                 if ( err == noErr && *commands != '\0' )
  1179.                     err = RegistryPropertyCreate( &self, "command-set", &commands, command_length );
  1180.                 break;
  1181.             }
  1182.             //
  1183.             //    if this name didn't succeed
  1184.             //        try the next numeric suffix
  1185.             //
  1186.             sprintf( (char *)suffix, " %d", numeric_suffix );
  1187.             CStrCopy( (char *)identification, (char *)nameregmodel );
  1188.             CStrCat( (char *)identification, (char *)suffix );
  1189.         }
  1190.         RegistryEntryIDDispose(&self);
  1191.     }
  1192.     pPrinterPB->printerRegistered = true;
  1193.     
  1194.     CStrToPStr((unsigned char *)tempstr, (char const *)pPrinterPB->name );
  1195.     
  1196.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Added printer to name registry", 0 );
  1197.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempstr, err );
  1198.     RegistryEntryIDDispose(&where);
  1199.  
  1200.     LOGGING( logfile = fopen( "USBPrinter.log", "wb+" ) );
  1201.     return err;
  1202. }
  1203.  
  1204. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1205.     Name:        LoadResources
  1206.  
  1207.     Input Parameters:
  1208.         pPrinterPB            pointer to class driver's private storage
  1209.         
  1210.     Output Parameters:
  1211.         OSStatus                resource load error
  1212.         
  1213.     Description:
  1214.         Initialize time is the only safe time to to load resources from our file.
  1215.         Here's where we load resources and detach them from the resource manager.
  1216.         Later we'll use these private copies instead of GetResource calls.
  1217.         
  1218.         Using the file spec that we got from the CFMInitialization routine, open
  1219.         our resource fork.
  1220.  
  1221.  
  1222.  
  1223.  
  1224. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1225. static OSStatus
  1226. LoadResources( struct usbPrinterPBStruct *pPrinterPB )
  1227. {
  1228.     short            rf = -1;                // class driver resource fork
  1229.     OSStatus        err;
  1230.  
  1231.     //
  1232.     //    open the resource fork of this class driver
  1233.     //
  1234.     rf = FSpOpenResFile( &printerClassDriverFileSpec,fsRdPerm );
  1235.     err = ResError();
  1236.     
  1237.     //
  1238.     //    load the DRVR that we'll stick in the unit table
  1239.     //
  1240.     pPrinterPB->hDrvr = NULL;
  1241.     if ( err == noErr )
  1242.     {
  1243.         pPrinterPB->hDrvr = (DRVRHeaderHandle) Get1Resource( 'DRVR',  kUSBParallelDrvrRsrcID );
  1244.         if ( pPrinterPB->hDrvr != NULL )
  1245.             DetachResource( (Handle) pPrinterPB->hDrvr );
  1246.         err = ResError();
  1247.     }
  1248.     
  1249.     if ( rf != -1 )
  1250.         CloseResFile( rf );
  1251.     
  1252.     return err;
  1253. }
  1254.  
  1255. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1256.     Name:        InstallDrivers
  1257.  
  1258.     Input Parameters:
  1259.         pPrinterPB
  1260.         
  1261.     Output Parameters:
  1262.         OSStatus            error code
  1263.         
  1264.     Description:
  1265.         install read and write drivers in the unit table
  1266.             we have separate drivers so that we can support a full-duplex protocol
  1267.         rename the driver we just installed (so multiple copies don't conflict)
  1268.         We use the DRVR -refnum-1 so that the driver name has the same hex chars
  1269.             as the driver number (for manual verification in MacsBug)
  1270.  
  1271.  
  1272.  
  1273.  
  1274.  
  1275.  
  1276. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1277. static OSStatus
  1278. InstallDrivers( struct usbPrinterPBStruct *pPrinterPB )
  1279. {
  1280.     //
  1281.     //    install the driver in the unit table
  1282.     //    rename the driver we just installed (so multiple copies don't conflict)
  1283.     //    
  1284.     short            refNum;                // DRVR refNum
  1285.     OSStatus        err =  paramErr;    // couldn't find driver
  1286.  
  1287.     if ( pPrinterPB->hDrvr != NULL )
  1288.         err = TradInstallDriverFromHandle( pPrinterPB->hDrvr, kMinDrvrUnitNumber, TradHighestUnitNumber() + 1, &pPrinterPB->outRefNum );
  1289.  
  1290.     if ( err == noErr )
  1291.     {
  1292.         UnitNumber        unit;
  1293.         DriverFlags        flags;
  1294.         DRVRHeaderPtr    hdr;
  1295.         unsigned char    *suffix,        // append "In" and "Out"
  1296.                             *infix;        // driver reference number follows the ".USB"
  1297.  
  1298.         TradGetDriverInformation( pPrinterPB->outRefNum, &unit, &flags, pPrinterPB->driverOutName, &hdr );
  1299.         BlockMove( pPrinterPB->driverOutName, pPrinterPB->driverInName, 1 + pPrinterPB->driverOutName[0] );
  1300.         
  1301.         suffix = pPrinterPB->driverOutName + pPrinterPB->driverOutName[0] - 2;
  1302.         infix = pPrinterPB->driverOutName + kDrvrFirstDigit;
  1303.         infix[0] = HiHex( -pPrinterPB->outRefNum -1 );
  1304.         infix[1] = LoHex( -pPrinterPB->outRefNum -1 );
  1305.         suffix[0] = 'O';
  1306.         suffix[1] = 'u';
  1307.         suffix[2] = 't';
  1308.         TradRenameDriver( pPrinterPB->outRefNum, pPrinterPB->driverOutName );
  1309.         //
  1310.         //    set the driver data to point to our parameter block
  1311.         //
  1312.         err = OpenDriver( pPrinterPB->driverOutName, &refNum );
  1313.         if ( err == noErr )
  1314.         {
  1315.             struct usbPrinterPBStruct *param = pPrinterPB;
  1316.             err = Control( refNum, kDrvrPrivateSetStorage, ¶m );
  1317.             CloseDriver( refNum );
  1318.         }
  1319.         err = TradInstallDriverFromHandle( pPrinterPB->hDrvr, kMinDrvrUnitNumber, TradHighestUnitNumber() + 1, &pPrinterPB->inRefNum );
  1320.         if ( err == noErr )
  1321.         {
  1322.             
  1323.             suffix = pPrinterPB->driverInName + pPrinterPB->driverInName[0] - 1;
  1324.             infix = pPrinterPB->driverInName + kDrvrFirstDigit;
  1325.             infix[0] = HiHex( -pPrinterPB->inRefNum -1 );
  1326.             infix[1] = LoHex( -pPrinterPB->inRefNum -1 );
  1327.             suffix[0] = 'I';
  1328.             suffix[1] = 'n';
  1329.             TradRenameDriver( pPrinterPB->inRefNum, pPrinterPB->driverInName );
  1330.             //
  1331.             //    set the driver data to point to our parameter block
  1332.             //
  1333.             err = OpenDriver( pPrinterPB->driverInName, &refNum );
  1334.             if ( err == noErr )
  1335.             {
  1336.                 struct usbPrinterPBStruct *param = pPrinterPB;
  1337.                 err = Control( refNum, kDrvrPrivateSetStorage, ¶m );
  1338.                 CloseDriver( refNum );
  1339.             }
  1340.         }
  1341.     }
  1342.     
  1343.     return err;
  1344. }
  1345.  
  1346. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1347.     Name:        GetCapability
  1348.  
  1349.     Input Parameters:    
  1350.         
  1351.     Output Parameters:
  1352.         
  1353.     Description:
  1354.         Asynchronous completion.
  1355.  
  1356.  
  1357.  
  1358. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1359. static void
  1360. GetCapability( struct usbPrinterPBStruct *pPrinterPB, unsigned char *p, short length )
  1361. {
  1362.     //
  1363.     //    queue a transaction to retrieve the 1284 capability string
  1364.     //        we must have assigned the interface by this point since the capability string
  1365.     //        may vary with the interface
  1366.     //
  1367.     OSStatus        err;
  1368.     USBPB            *pb = &pPrinterPB->pb;
  1369.  
  1370.     SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  1371.     
  1372.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  1373.     pb->usbBuffer = 0;
  1374.     pb->usbActCount = 0;
  1375.     pb->usbReqCount = 0;
  1376.  
  1377.     pb->usb.cntl.BRequest = kUSBPrintClassGetDeviceID;
  1378.     pb->usb.cntl.WValue = 0;            // configuration
  1379.     pb->usb.cntl.WIndex = (pPrinterPB->interfaceNumber<<8) | pPrinterPB->alternateSetting;
  1380.  
  1381.     pb->usbReqCount = length;
  1382.     pb->usbBuffer = p;
  1383.  
  1384.     pb->usbRefcon |= kTransactionPending;
  1385.     pb->usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  1386.     err = USBDeviceRequest(pb);
  1387.     if(immediateError(err))
  1388.     {
  1389.         USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"GetCapability", 0);
  1390.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1391.         pb->usbRefcon |= kReturnFromDriver;
  1392.     }
  1393. }
  1394.  
  1395. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1396.     Name:        IsLucentCable
  1397.  
  1398.     Input Parameters:    
  1399.         dev            USB device descriptor
  1400.         
  1401.     Output Parameters:
  1402.         Return 1 if the USB device is a USB-parallel cable
  1403.         
  1404.     Description:
  1405.         
  1406.  
  1407.  
  1408.  
  1409. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1410. static short
  1411. IsLucentCable( USBDeviceDescriptor    *dev )
  1412. {
  1413.     return ( USBToHostWord(dev->vendor) == 0x47E && USBToHostWord(dev->product) == 0x1001 )? 1: 0;
  1414. }
  1415.  
  1416.  
  1417. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1418.     Name:        GetInterface
  1419.  
  1420.     Input Parameters:    
  1421.         
  1422.     Output Parameters:
  1423.         
  1424.     Description:
  1425.         Asynchronous completion.
  1426.  
  1427.  
  1428.  
  1429. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1430. static void
  1431. GetInterface( USBPB *pb, UInt8 *alt )
  1432. {
  1433.     //
  1434.     //    make sure we account for any alternate interface currently in use by the device
  1435.     //
  1436.     OSStatus    err;
  1437.  
  1438.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBStandard, kUSBInterface);
  1439.  
  1440.     pb->usb.cntl.BRequest = kUSBRqGetInterface;
  1441.     pb->usb.cntl.WValue = 0; 
  1442.     pb->usb.cntl.WIndex = 0;
  1443.  
  1444.     pb->usbReqCount = sizeof(UInt8);        // single byte is requested
  1445.     pb->usbBuffer = alt;
  1446.  
  1447.     pb->usbStatus = 0;
  1448.     pb->usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  1449.     pb->usbRefcon |= kTransactionPending;
  1450.  
  1451.     err = USBDeviceRequest(pb);
  1452.     if(immediateError(err))
  1453.     {
  1454.         USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"GetInterface", 0);
  1455.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1456.         pb->usbRefcon |= kReturnFromDriver;
  1457.     }
  1458. }
  1459.  
  1460.  
  1461. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1462.     Name:        ReadCompletion
  1463.  
  1464.     Input Parameters:    
  1465.         pb                        USB parameter block
  1466.         
  1467.     Output Parameters:
  1468.         <none>
  1469.  
  1470.     Description:
  1471.         USB read requests complete here.
  1472.         We dequeue the MacOS DRVR read requests
  1473.  
  1474.  
  1475.  
  1476.  
  1477.  
  1478.  
  1479.  
  1480.  
  1481. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1482. static void
  1483. ReadCompletion(USBPB *pb)
  1484. {
  1485.     //    call the user completion routine
  1486.     struct usbPrinterPBStruct
  1487.             *pPrinterPB =  (struct usbPrinterPBStruct    *) pb->usbRefcon;
  1488.     IOParamPtr     clientParam = pPrinterPB->readDrvr.pb;
  1489.     OSStatus        err = pb->usbStatus;
  1490.     DCtlPtr            ctlLocal;
  1491.  
  1492. #if MACSBUG_ON_READ_COMPLETE
  1493.     Str255    text;
  1494.     sprintf( (char *)text, " PrinterClass Read Complete(%d): %d", pb->usbStatus, pb->usbActCount );
  1495.     text[0] = CStrLen((char *)text); // c2pstr
  1496.     DebugStr( text );
  1497. #endif
  1498.  
  1499. #if DOUBLE_BUFFER
  1500.     //
  1501.     //    copy the user data from our page aligned buffer
  1502.     //
  1503.     USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion - bytes read  " , (UInt32)pb->usbActCount );
  1504.  
  1505.     if ( pb->usbActCount > 0 )
  1506.         BlockCopy( pPrinterPB->pageReadAlignedBuffer, clientParam->ioBuffer + clientParam->ioActCount, pb->usbActCount );
  1507. #endif
  1508.     //    update the amount of data actually transferred
  1509.     clientParam->ioActCount += pb->usbActCount;
  1510.  
  1511.     switch( pb->usbStatus )
  1512.     {
  1513.         //
  1514.         //    only retry low level hardware problems
  1515.         //        note: abort transactions will end up here as well
  1516.         //
  1517.     case kUSBLinkErr:
  1518.     case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  1519.     case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  1520.     case kUSBDataToggleErr:                        /*  Pipe stall, Bad data toggle */
  1521.     case kUSBNotRespondingErr:                    /*  Pipe stall, No device, device hung */
  1522.     case kUSBPIDCheckErr:                        /*  Pipe stall, PID CRC error */
  1523.     case kUSBWrongPIDErr:                        /*  Pipe stall, Bad or wrong PID */
  1524.         if (  --(pPrinterPB->readRetryCount) > 0 ) 
  1525.         {
  1526.             // we got an error, and we still want to retry, clear any stalls
  1527.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion retry" , pb->usbStatus );
  1528.             USBClearPipeStallByReference(pPrinterPB->readPipeRef);
  1529.             pb->usbStatus = noErr;
  1530.         }
  1531.         break;
  1532.     case kUSBAbortedError:                        /* user cancel, or hot unplug */
  1533.         USBClearPipeStallByReference(pPrinterPB->readPipeRef);
  1534.         USBClearPipeStallByReference(pPrinterPB->deviceRef);
  1535.         break;
  1536.         //
  1537.         //    any other error will be reported to the client
  1538.         //
  1539.     default:
  1540.     case noErr:
  1541.         break;
  1542.     }
  1543.     if ( pb->usbStatus == noErr &&                                     // there were no problems
  1544.         pb->usbActCount >= pb->usbReqCount &&                        // we got all the data we requested
  1545.         clientParam->ioActCount < clientParam->ioReqCount )    // we still want more data
  1546.     {
  1547.         //
  1548.         //    haven't finish the client's request
  1549.         //        update the pointers and start another bulk read transaction
  1550.         //
  1551. #if LOCK_MEMORY
  1552.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1553.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"ReadCompletion UnlockMem failed" ) );
  1554. #endif
  1555.         pb->usbBuffer = clientParam->ioBuffer + clientParam->ioActCount;
  1556.         pb->usbReqCount = clientParam->ioReqCount - clientParam->ioActCount;
  1557. #if MAX_USB_TRANSFER_SIZE
  1558.         if ( pb->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1559.             pb->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1560. #endif
  1561. #if DOUBLE_BUFFER
  1562.         //
  1563.         //    make sure we have enough room in our buffer
  1564.         //
  1565.         if ( pb->usbReqCount > pPrinterPB->pageReadAlignedBufferSize )
  1566.             pb->usbReqCount = pPrinterPB->pageReadAlignedBufferSize;
  1567.         pb->usbBuffer = pPrinterPB->pageReadAlignedBuffer;
  1568. #endif
  1569. #if LOCK_MEMORY
  1570.         err = LockMemory( pb->usbBuffer, pb->usbReqCount );
  1571.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"ReadCompletion LockMem failed" ) );
  1572.         if ( err == noErr )
  1573. #endif
  1574.         err = SafeUSBBulkRead( pb );
  1575.         if ( immediateError(err) )
  1576.         {
  1577.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion finish immed err" , err );
  1578.  
  1579.             pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1580.             if ( pPrinterPB->readDrvr.ctl != NULL )
  1581.             {
  1582.                 ctlLocal = pPrinterPB->readDrvr.ctl;
  1583.                 pPrinterPB->readDrvr.ctl = NULL;
  1584.                 CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, err, clientParam, ctlLocal ); 
  1585.             }
  1586.         }
  1587.     }
  1588.     else
  1589.     {
  1590.         //
  1591.         //        either we have an error which we're not retrying
  1592.         //            or we successfully completed
  1593.         //
  1594. #if LOCK_MEMORY
  1595.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1596.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"ReadCompletion concluded UnlockMem failed" ) );
  1597. #endif
  1598.         IF_DEBUG( if (pb->usbStatus != noErr) USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion Error" , pb->usbStatus ) );
  1599.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1600.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"readDrvr.ctl = " , (UInt32)pPrinterPB->readDrvr.ctl );
  1601.         if ( pPrinterPB->readDrvr.ctl != NULL )
  1602.         {
  1603.             ctlLocal = pPrinterPB->readDrvr.ctl;
  1604.             pPrinterPB->readDrvr.ctl = NULL;
  1605.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, ctlLocal); 
  1606.         }
  1607.         else
  1608.         {
  1609.             IF_DEBUG( DebugStr( kPStrPrinterDriverName"ReadCompletion() pPrinterPB->readDrvr.ctl == NULL" ) );
  1610.         }
  1611.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB PRint, read completion do suspend resume" , pb->usbReference);
  1612.         USBPrintDoSuspendResume(pb->usbReference);
  1613.     }
  1614. }
  1615.  
  1616.  
  1617. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1618.     Name:        WriteCompletion
  1619.  
  1620.     Input Parameters:    
  1621.         pb                        USB parameter block
  1622.         
  1623.     Output Parameters:
  1624.         <none>
  1625.  
  1626.     Description:
  1627.         USB write requests complete here.
  1628.         We dequeue the MacOS DRVR write requests
  1629.  
  1630.         when breaking up transactions we use ioActCount to determine how much remains 
  1631.                 of the original request and where the next request begins
  1632.         if we've failed with a USB error
  1633.             usbActCount indicates how much data has been transferred with the current request
  1634.             and if the retry count hasn't been exceeded
  1635.                 we proceed as if we'd just requested that much in this transactions
  1636.         note the retry count is cumulative for the original client request
  1637.             not for each usb transaction
  1638.  
  1639.  
  1640.  
  1641.  
  1642.  
  1643.  
  1644.  
  1645.  
  1646.  
  1647.  
  1648. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1649. static void
  1650. WriteCompletion(USBPB *pb)
  1651. {
  1652.     //    call the user completion routine
  1653.     struct usbPrinterPBStruct
  1654.                     *pPrinterPB =  (struct usbPrinterPBStruct    *) pb->usbRefcon;
  1655.     IOParamPtr     clientParam = pPrinterPB->writeDrvr.pb;
  1656.     DCtlPtr            ctlLocal;
  1657.     OSStatus        err = pb->usbStatus;
  1658.  
  1659. #if MACSBUG_ON_WRITE_COMPLETE
  1660.     Str255    text;
  1661.     sprintf( (char *)text, " PrinterClass Write Complete(%d): %d", pb->usbStatus, pb->usbActCount );
  1662.     text[0] = CStrLen((char *)text); // c2pstr
  1663.     DebugStr( text );
  1664. #endif
  1665.  
  1666.     //    update the amount of data actually transferred
  1667.     clientParam->ioActCount += pb->usbActCount;
  1668.     USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion - bytes written  " , (UInt32)pb->usbActCount);
  1669.  
  1670.     switch( pb->usbStatus )
  1671.     {
  1672.         //
  1673.         //    only retry low level hardware problems
  1674.         //        note: abort transactions will end up here as well
  1675.         //
  1676.     case kUSBLinkErr:
  1677.     case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  1678.     case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  1679.     case kUSBDataToggleErr:                        /*  Pipe stall, Bad data toggle */
  1680.     case kUSBNotRespondingErr:                    /*  Pipe stall, No device, device hung */
  1681.     case kUSBPIDCheckErr:                        /*  Pipe stall, PID CRC error */
  1682.     case kUSBWrongPIDErr:                        /*  Pipe stall, Bad or wrong PID */
  1683.         if (  --(pPrinterPB->writeRetryCount) > 0 ) 
  1684.         {
  1685.             // we got an error, and we still want to retry, clear any stalls
  1686.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion retry" , pb->usbStatus );
  1687.             USBClearPipeStallByReference(pPrinterPB->writePipeRef);
  1688.             pb->usbStatus = noErr;
  1689.         }
  1690.         break;
  1691.     case kUSBAbortedError:                        /* user cancel, or hot unplug */
  1692.         USBClearPipeStallByReference(pPrinterPB->writePipeRef);
  1693.         USBClearPipeStallByReference(pPrinterPB->deviceRef);
  1694.         break;
  1695.         //
  1696.         //    any other error will be reported to the client
  1697.         //
  1698.     default:
  1699.     case noErr:
  1700.         break;
  1701.     }
  1702.  
  1703.     if ( pb->usbStatus == noErr && clientParam->ioActCount < clientParam->ioReqCount )
  1704.     {
  1705.         //
  1706.         //    haven't finish the client's request
  1707.         //        update the pointers and start another bulkOut transaction
  1708.         //
  1709. #if LOCK_MEMORY
  1710.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1711.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"WriteCompletion UnlockMem failed" ) );
  1712. #endif
  1713.         pb->usbBuffer = clientParam->ioBuffer + clientParam->ioActCount;
  1714.         pb->usbReqCount = clientParam->ioReqCount - clientParam->ioActCount;
  1715. #if MAX_USB_TRANSFER_SIZE
  1716.         if ( pb->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1717.             pb->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1718. #endif
  1719. #if DOUBLE_BUFFER
  1720.         //
  1721.         //    make sure we have enough room in our buffer
  1722.         //    then copy the user data into our page aligned buffer
  1723.         //
  1724.         if ( pb->usbReqCount > pPrinterPB->pageWriteAlignedBufferSize )
  1725.             pb->usbReqCount = pPrinterPB->pageWriteAlignedBufferSize;
  1726.             
  1727.         BlockCopy( pb->usbBuffer, pPrinterPB->pageWriteAlignedBuffer, pb->usbReqCount );
  1728.         pb->usbBuffer = pPrinterPB->pageWriteAlignedBuffer;
  1729.         
  1730. #endif
  1731. #if LOCK_MEMORY
  1732.         err = LockMemory( pb->usbBuffer, pb->usbReqCount );
  1733.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"WriteCompletion LockMem failed" ) );
  1734.         if ( err == noErr )
  1735. #endif
  1736.             err = SafeUSBBulkWrite( pb );
  1737.         if ( immediateError(err) )
  1738.         {
  1739.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion finish immed err" , err );
  1740.  
  1741.             pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1742.             if ( pPrinterPB->writeDrvr.ctl != NULL )
  1743.             {
  1744.                 ctlLocal = pPrinterPB->writeDrvr.ctl;
  1745.                 pPrinterPB->writeDrvr.ctl = NULL;
  1746.                 CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, err, clientParam, ctlLocal ); 
  1747.             }
  1748.         }
  1749.     }
  1750.     else
  1751.     {
  1752.         //
  1753.         //        either we have an error which we're not retrying
  1754.         //            or we successfully completed
  1755.         //
  1756. #if LOCK_MEMORY
  1757.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1758.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"WriteCompletion concluded UnlockMem failed" ) );
  1759. #endif
  1760.  
  1761.         IF_DEBUG( if (pb->usbStatus != noErr) USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion Error" , pb->usbStatus ) );
  1762.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1763.  
  1764.  
  1765.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"writeDrvr.ctl = " , (UInt32)pPrinterPB->writeDrvr.ctl );
  1766.         if ( pPrinterPB->writeDrvr.ctl != NULL )
  1767.         {
  1768.             ctlLocal = pPrinterPB->writeDrvr.ctl;
  1769.             pPrinterPB->writeDrvr.ctl = NULL;
  1770.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, ctlLocal ); 
  1771.         }
  1772.         else
  1773.         {
  1774.             IF_DEBUG( DebugStr( kPStrPrinterDriverName"WriteCompletion() pPrinterPB->writeDrvr.ctl == NULL" ) );
  1775.         }
  1776.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB PRint, write completion do suspend resume" , pb->usbReference );
  1777.         USBPrintDoSuspendResume(pb->usbReference);
  1778.     }
  1779. }
  1780.  
  1781. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1782.     Name:        QueueRead
  1783.  
  1784.     Input Parameters:    
  1785.         pb                        MacOS device manager parameter block
  1786.         ctl                    device manager dCtl block
  1787.         pPrinterPB            current printing device class's storage
  1788.         
  1789.     Output Parameters:
  1790.         <none>
  1791.  
  1792.     Description:
  1793.         MacOS DRVR read requests are re-queued here to the USB
  1794.         Since we only allow one read request pending at a time, we're able
  1795.         to use the USB refCon to point to our class driver's storage.
  1796.  
  1797.  
  1798.  
  1799.  
  1800. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1801. void
  1802. QueueRead( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  1803. {    
  1804.     OSStatus    err;
  1805.     USBPB        *usbprint = &pPrinterPB->in;
  1806.     
  1807. #if MACSBUG_ON_READ
  1808.     Str255    text;
  1809.  
  1810.     sprintf( (char *)text, " PrinterClass Read: %d @ %08x", pb->ioReqCount, pb->ioBuffer );
  1811.     text[0] = CStrLen((char *)text); // c2pstr
  1812.     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  1813.     DebugStr( text );
  1814. #endif
  1815.  
  1816.     // BT - 15Jun99, if we're not currently awake, delay this until we are.
  1817.     if(currentlyAre == kUSBPrintSuspended)
  1818.     {
  1819.         pb->ioResult = ioInProgress;
  1820.         USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, delaying read for resume", 0 );
  1821.         RpPrinterPB = pPrinterPB;
  1822.         Rctl = ctl;
  1823.         Rpb = pb;
  1824.         if( (currentlyAre != kUSBPrintSuspended) && (Rpb != nil) )
  1825.         {
  1826.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, resumed while we wern't looking", 0 );
  1827.             // resumed and executed this while we were doing this.
  1828.             return;
  1829.         }
  1830.         else
  1831.         {
  1832.             // now wait for resume to happen
  1833.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, let resume take over", 0 );
  1834.             return;
  1835.         }        
  1836.     }
  1837.  
  1838.  
  1839.     pb->ioActCount = 0;        // nothing transfered yet
  1840.     if ( pPrinterPB->terminating )
  1841.         pb->ioResult = abortErr;
  1842.     else
  1843.     {
  1844.  
  1845.         pPrinterPB->readRetryCount = 5;
  1846.         pPrinterPB->readDrvr.pb= pb;
  1847.         pPrinterPB->readDrvr.ctl = ctl;
  1848.         if (( pPrinterPB->readPipeRef != NULL ) && (pPrinterPB->printerConfigured))
  1849.         {
  1850.             SetNullUSBParamBlock( pPrinterPB->readPipeRef,  usbprint );
  1851.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Set up to do bulk read", pb->ioReqCount );
  1852.             usbprint->usbActCount = 0;
  1853.             usbprint->usbBuffer = pb->ioBuffer;
  1854.             usbprint->usbReqCount = pb->ioReqCount;
  1855.  
  1856. #if MAX_USB_TRANSFER_SIZE
  1857.             //
  1858.             //    the completion routine will queue another BulkWrite until we exhaust the data
  1859.             //        or there is an error which can't be retried
  1860.             //
  1861.             if ( usbprint->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1862.                 usbprint->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1863. #endif
  1864. #if DOUBLE_BUFFER
  1865.             //
  1866.             //    make sure we have enough room in our buffer
  1867.             //    then copy the user data into our page aligned buffer
  1868.             //
  1869.             if ( usbprint->usbReqCount > pPrinterPB->pageReadAlignedBufferSize )
  1870.                 usbprint->usbReqCount = pPrinterPB->pageReadAlignedBufferSize;
  1871.             usbprint->usbBuffer = pPrinterPB->pageReadAlignedBuffer;
  1872. #endif
  1873.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  1874.             usbprint->usbCompletion = (USBCompletion) ReadCompletion;
  1875.             
  1876.             pb->ioResult = ioInProgress;
  1877. #if LOCK_MEMORY
  1878.             err = LockMemory( usbprint->usbBuffer, usbprint->usbReqCount );
  1879.             IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"QueueRead LockMem failed" ) );
  1880.             if ( err == noErr )
  1881. #endif
  1882.             err = SafeUSBBulkRead( usbprint );
  1883.             if ( immediateError(err) )
  1884.             {
  1885.                 USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Error doing bulk read",err );
  1886.                 IF_DEBUG( DebugStr( USBStatusStr(err, kPString) ) );
  1887.                 usbprint->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1888.                 pb->ioResult = err;
  1889.             }
  1890.         }
  1891.         else
  1892.         {
  1893.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Read to unopened pipe" , usbprint->usbStatus ) ;
  1894.             pb->ioResult = abortErr;
  1895.         }
  1896.     }
  1897. }
  1898.  
  1899. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1900.     Name:        QueueWrite
  1901.  
  1902.     Input Parameters:    
  1903.         pb                        MacOS device manager parameter block
  1904.         ctl                    device manager dCtl block
  1905.         pPrinterPB            current printing device class's storage
  1906.         
  1907.     Output Parameters:
  1908.         <none>
  1909.  
  1910.     Description:
  1911.         MacOS DRVR write requests are re-queued here to the USB
  1912.         Since we only allow one read request pending at a time, we're able
  1913.         to use the USB refCon to point to our class driver's storage.
  1914.  
  1915.  
  1916.  
  1917. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1918. void
  1919. QueueWrite( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  1920. {
  1921.     OSStatus    err;
  1922.     USBPB        *usbprint = &pPrinterPB->out;
  1923. #if VIRTUAL_MEMORY_CHECK
  1924.     //
  1925.     //    dump the VM table
  1926.     //
  1927.     Str255                        text;
  1928.     LogicalToPhysicalTable        *vmTable;
  1929.     MemoryBlock                    *physical;
  1930.     unsigned long                vmCount,
  1931.                                 vmEntry,
  1932.                                 vmTblLength;
  1933. #endif
  1934.  
  1935. #if MACSBUG_ON_WRITE
  1936.     Str255    text;
  1937.     sprintf( (char *)text, " "kCStrPrinterDriverName"%d @ %08x", pb->ioReqCount, pb->ioBuffer );
  1938.     text[0] = CStrLen((char *)text); // c2pstr
  1939.     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  1940.     DebugStr( text );
  1941. #endif
  1942.  
  1943.     // BT - 15Jun99, if we're not currently awake, delay this until we are.
  1944.     if(currentlyAre == kUSBPrintSuspended)
  1945.     {
  1946.         pb->ioResult = ioInProgress;
  1947.         USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, delaying write for resume", 0 );
  1948.  
  1949.         WpPrinterPB = pPrinterPB;
  1950.         Wctl = ctl;
  1951.         Wpb = pb;
  1952.         if( (currentlyAre != kUSBPrintSuspended) && (Wpb != nil) )
  1953.         {
  1954.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, resumed while we wern't looking", 0 );
  1955.             // resumed and executed this while we were doing this.
  1956.         }
  1957.         else
  1958.         {
  1959.             // now wait for resume to happen
  1960.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, let resume take over", 0 );
  1961.             return;
  1962.         }        
  1963.     }
  1964.  
  1965.  
  1966.  
  1967. #if VIRTUAL_MEMORY_CHECK
  1968.     //
  1969.     //    this check current won't compile without runtime error: need to lock memory, but lock has moved
  1970.     //
  1971.     sprintf( (char *)text, " "kCStrPrinterDriverName"Write: %d @ %08x", pb->ioReqCount, pb->ioBuffer );
  1972.     text[0] = CStrLen((char *)text); // c2pstr
  1973.     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  1974.     
  1975.     vmCount = 127;
  1976.     vmTblLength = (vmCount+1)*sizeof(MemoryBlock);
  1977.     vmTable = (LogicalToPhysicalTable *) NewPtrSys( vmTblLength );
  1978.     LockMemory( vmTable, vmTblLength );
  1979.     LockMemory( &vmCount, sizeof(unsigned long) );
  1980.     vmTable->logical.address = pb->ioBuffer;
  1981.     vmTable->logical.count = pb->ioReqCount;
  1982.     err = GetPhysical( vmTable, &vmCount );
  1983.     
  1984.     if ( err == noErr )
  1985.     {
  1986.         for ( vmEntry = 0, physical = &vmTable->physical[0]; vmEntry < vmCount; ++vmEntry , ++physical)
  1987.         {
  1988.             sprintf( (char *)text, " "kCStrPrinterDriverName"Write: VM @%08x (%d)", physical->address, physical->count );
  1989.             text[0] = CStrLen((char *)text); // c2pstr
  1990.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  1991.         }
  1992.     }
  1993.     UnlockMemory( vmTable, vmTblLength );
  1994.     UnlockMemory( &vmCount, sizeof(unsigned long) );
  1995. #endif
  1996.     pb->ioActCount = 0;        // nothing transfered yet
  1997.  
  1998.  
  1999.     usbprint->usbStatus = noErr;    // forget about abort and things from previous writes
  2000.     if ( pPrinterPB->terminating )
  2001.         pb->ioResult = abortErr;
  2002.     else
  2003.     {
  2004.         pPrinterPB->writeRetryCount = 5;
  2005.         pPrinterPB->writeDrvr.pb = pb;
  2006.         pPrinterPB->writeDrvr.ctl = ctl;
  2007.         if (( pPrinterPB->writePipeRef != NULL ) && (pPrinterPB->printerConfigured))
  2008.         {
  2009.             SetNullUSBParamBlock( pPrinterPB->writePipeRef,  usbprint );
  2010.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Set up to do bulk write", pb->ioReqCount );
  2011.             usbprint->usbActCount = 0;
  2012.             usbprint->usbBuffer = pb->ioBuffer;
  2013.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  2014.             usbprint->usbCompletion = (USBCompletion) WriteCompletion;
  2015.             
  2016. #if MAX_USB_TRANSFER_SIZE
  2017.             //
  2018.             //    the completion routine will queue another BulkWrite until we exhaust the data
  2019.             //        or there is an error which can't be retried
  2020.             //
  2021.             if ( pb->ioReqCount > MAX_USB_TRANSFER_SIZE )
  2022.                 usbprint->usbReqCount = MAX_USB_TRANSFER_SIZE;
  2023.             else
  2024. #endif
  2025.                 usbprint->usbReqCount = pb->ioReqCount;
  2026.     
  2027.  
  2028. #if DOUBLE_BUFFER
  2029.             //
  2030.             //    make sure we have enough room in our buffer
  2031.             //    then copy the user data into our page aligned buffer
  2032.             //
  2033.             if ( usbprint->usbReqCount > pPrinterPB->pageWriteAlignedBufferSize )
  2034.                 usbprint->usbReqCount = pPrinterPB->pageWriteAlignedBufferSize;
  2035.             BlockCopy( usbprint->usbBuffer, pPrinterPB->pageWriteAlignedBuffer, usbprint->usbReqCount );
  2036.             usbprint->usbBuffer = pPrinterPB->pageWriteAlignedBuffer;
  2037. #endif
  2038.             pb->ioResult = ioInProgress;
  2039.     
  2040. #if LOCK_MEMORY
  2041.             err = LockMemory( usbprint->usbBuffer, usbprint->usbReqCount );
  2042.             IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"QueueWrite LockMem failed" ) );
  2043.             if ( err == noErr )
  2044. #endif
  2045.                 err = SafeUSBBulkWrite( usbprint );
  2046.             if ( immediateError(err) )
  2047.             {
  2048.                 USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Immediate error doing bulk write",0 );
  2049.                 IF_DEBUG( DebugStr( USBStatusStr(err, kPString) ) );
  2050.                 usbprint->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  2051.                 pb->ioResult = err;
  2052.             }
  2053.             //
  2054.             //    note our logging is one write for each the client request
  2055.             //        not one write for each usb transaction
  2056.             //
  2057.             LOGGING( fwrite( pb->ioBuffer, sizeof(char), pb->ioReqCount, logfile ) );
  2058.         }
  2059.         else
  2060.         {
  2061.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Write to unopened pipe" , usbprint->usbStatus );
  2062.             pb->ioResult = abortErr;
  2063.         }
  2064.     }
  2065. }
  2066.  
  2067.  
  2068. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2069.     Name:        Abort
  2070.  
  2071.     Input Parameters:    
  2072.         refNum            DRVR refnum
  2073.         pPrinterPB        current printing device class's storage
  2074.  
  2075.     Output Parameters:
  2076.         
  2077.     Description:
  2078.         Asynchronous completion.
  2079.         Note: USBAbortPipeByReference can leave the data toggle in the wrong state.
  2080.                 We need to abort both pipes, and then the client must soft reset the printer
  2081.                 to get the printer's data toggles correct.
  2082.         We prematurely call completion routines for active i/o so that CloseDriverSync
  2083.             will not hang the system after an abort, including hot unplug. This works out okay,
  2084.             since the request will be dequeued now, and when the i/o actually terminates
  2085.             the system will be called with an invalid queue element and then reject this second
  2086.             attempt to dequeue the i/o.
  2087.  
  2088.  
  2089.  
  2090.  
  2091. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2092. OSStatus
  2093. Abort( DriverRefNum refNum, struct usbPrinterPBStruct *pPrinterPB )
  2094. {
  2095.     OSStatus        err = noErr;
  2096.  
  2097.     //
  2098.     //    if there's any pending io this will call the completion routine
  2099.     //
  2100.     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB Print - Abort called" , 0);
  2101.     if (refNum == pPrinterPB->outRefNum)
  2102.     {
  2103.         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB Print - Abort called on out pipe" , 0);
  2104.         if ( pPrinterPB->in.usbCompletion != (USBCompletion) NULL )
  2105.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "***** Abort with write in progress" , 0);
  2106.         
  2107.         err = USBAbortPipeByReference( pPrinterPB->writePipeRef );
  2108.         err = USBClearPipeStallByReference( pPrinterPB->writePipeRef );
  2109.         
  2110.         if ( pPrinterPB->out.usbCompletion != (USBCompletion) NULL )
  2111.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, abortErr, pPrinterPB->writeDrvr.pb, pPrinterPB->writeDrvr.ctl ); 
  2112.     }
  2113.     
  2114.     if (refNum == pPrinterPB->inRefNum)
  2115.     {
  2116.         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB Print - Abort called on in pipe" , 0);
  2117.         if ( pPrinterPB->out.usbCompletion != (USBCompletion) NULL )
  2118.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "***** Abort with read in progress" , 0);
  2119.  
  2120.         err = USBAbortPipeByReference( pPrinterPB->readPipeRef );
  2121.         err = USBClearPipeStallByReference( pPrinterPB->readPipeRef );
  2122.  
  2123.         if ( pPrinterPB->in.usbCompletion != (USBCompletion) NULL )
  2124.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, abortErr, pPrinterPB->readDrvr.pb, pPrinterPB->readDrvr.ctl ); 
  2125.     }
  2126.     return err;
  2127. }
  2128.  
  2129.  
  2130. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2131.     Name:        CompletionProc
  2132.  
  2133.     Input Parameters:    
  2134.         pb                    USB param block ptr
  2135.     
  2136.     Output Parameters:
  2137.         
  2138.     Description:
  2139.         Asynchronous completion routine for DRVR requests.
  2140.  
  2141.  
  2142.  
  2143.  
  2144.  
  2145. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2146. static void 
  2147. CompletionProc(USBPB *pb)
  2148. {
  2149.     //    call the user completion routine
  2150.     struct usbPrinterPBStruct
  2151.                     *pPrinterPB = (struct usbPrinterPBStruct    *) pb->usbRefcon;
  2152.     IOParamPtr     clientParam = pPrinterPB->statusDrvr.pb;
  2153.  
  2154.     clientParam->ioActCount = pb->usbActCount;
  2155.  
  2156.     if ( pb->usbStatus != noErr ) 
  2157.     {
  2158.         USBClearPipeStallByReference(pb->usbReference);  // we got an error, try to clear any stalls
  2159.  
  2160.         IF_DEBUG( USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "CompletionProc Error" , pb->usbStatus ) );
  2161.         IF_DEBUG( USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, USBStatusStr(pb->usbStatus, kPString) , pb->usbStatus ) );
  2162.     }
  2163.  
  2164.     pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  2165.     if ( pPrinterPB->statusDrvr.ctl != NULL )
  2166.         CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, pPrinterPB->statusDrvr.ctl ); 
  2167. }
  2168.  
  2169. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2170.     Name:        CentronicsStatus
  2171.  
  2172.     Input Parameters:    
  2173.         pb                        MacOS device manager parameter block
  2174.         ctl                    device manager dCtl block
  2175.         pPrinterPB            current printing device class's storage
  2176.  
  2177.     Output Parameters:
  2178.         pStatusByte        
  2179.         
  2180.     Description:
  2181.         setup the device request for a USB printer class request one byte status.
  2182.  
  2183.  
  2184.  
  2185.  
  2186.  
  2187. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2188. static void
  2189. CentronicsStatus( USBPB *usbprint, Ptr buffer, short interfaceNumber )
  2190. {
  2191.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  2192.  
  2193.     usbprint->usb.cntl.BRequest = kUSBPrintClassGetCentronicsStatus;
  2194.     usbprint->usb.cntl.WValue = 0;
  2195.     usbprint->usb.cntl.WIndex = interfaceNumber;
  2196.  
  2197.     usbprint->usbReqCount = 1;
  2198.     usbprint->usbBuffer = buffer;
  2199. }
  2200.  
  2201. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2202.     Name:        ClearEndpointHalt
  2203.  
  2204.     Input Parameters:    
  2205.         usbprint                USB param block
  2206.  
  2207.     Output Parameters:
  2208.         
  2209.     Description:
  2210.         Setup the device request for a USB clear endpoint halt.
  2211.  
  2212. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2213. void
  2214. ClearEndpointHalt( USBPB *usbprint)
  2215. {
  2216.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBStandard, kUSBEndpoint);
  2217.  
  2218.     usbprint->usb.cntl.BRequest = kUSBRqClearFeature;
  2219.     usbprint->usb.cntl.WValue = kUSBFeatureEndpointStall;
  2220.     usbprint->usbFlags = kUSBAddressRequest;
  2221.  
  2222.     usbprint->usbReqCount = 0;
  2223.     usbprint->usbBuffer = NULL;
  2224.     
  2225.  
  2226. }
  2227.  
  2228. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2229.     Name:        SoftReset
  2230.  
  2231.     Input Parameters:    
  2232.         usbprint                USB param block
  2233.         interfaceNumber
  2234.  
  2235.     Output Parameters:
  2236.         
  2237.     Description:
  2238.         Setup the device request for a USB printer class request soft reset.
  2239.  
  2240.  
  2241.  
  2242.  
  2243.  
  2244. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2245. void
  2246. SoftReset( USBPB *usbprint, short interfaceNumber )
  2247. {
  2248.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBClass, kUSBOther);
  2249.  
  2250.     usbprint->usb.cntl.BRequest = kUSBPrintClassSoftReset;
  2251.     usbprint->usb.cntl.WValue = 0;
  2252.     usbprint->usb.cntl.WIndex = interfaceNumber;
  2253.  
  2254.     usbprint->usbReqCount = 0;
  2255.     usbprint->usbBuffer = NULL;
  2256.     
  2257.  
  2258. }
  2259.  
  2260. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2261.     Name:        CapabilityRequest
  2262.  
  2263.     Input Parameters:    
  2264.         usbprint            USB parameter block
  2265.         p                    result pointer
  2266.         length            amount of data allocated
  2267.         config
  2268.         interfaceNum
  2269.         alternateSetting
  2270.         
  2271.  
  2272.     Output Parameters:
  2273.         p                    result pointer
  2274.         length            amount of data allocated
  2275.         
  2276.     Description:
  2277.         setup the device request for a USB printer class request 1284 id string.
  2278.  
  2279.  
  2280.  
  2281.  
  2282.  
  2283. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2284. void
  2285. CapabilityRequest( USBPB *pb, Ptr p, long length, short configValue, short interfaceNumber, short alternateSetting  )
  2286. {
  2287.  
  2288.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  2289.  
  2290.     pb->usb.cntl.BRequest = kUSBPrintClassGetDeviceID;
  2291.     pb->usb.cntl.WValue = configValue;        // configuration
  2292.     pb->usb.cntl.WIndex = (interfaceNumber<<8) | alternateSetting;
  2293.  
  2294.     pb->usbReqCount = length;
  2295.     pb->usbBuffer = p;
  2296.  
  2297. }
  2298.  
  2299. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2300.     Name:        StatusControlRequests
  2301.  
  2302.     Input Parameters:    
  2303.         pb                        MacOS device manager parameter block
  2304.         ctl                    device manager dCtl block
  2305.         pPrinterPB            current printing device class's storage
  2306.  
  2307.     Output Parameters:
  2308.         
  2309.     Description:
  2310.         Asynchronous completion.
  2311.  
  2312.  
  2313.  
  2314.  
  2315. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2316.  
  2317. void
  2318. ControlStatusRequests( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  2319. {
  2320.  
  2321.     //
  2322.     //    queue a transaction to retrieve the centronics status
  2323.     //
  2324.     OSStatus    err;
  2325.     USBPB        *usbprint = &pPrinterPB->pb;
  2326.     Boolean        dosomething = false;
  2327.     
  2328. #if DEBUG
  2329.     Str255        text;
  2330.  
  2331.     sprintf( (char *)text, " PrinterClass ControlStatus: %d", ((CntrlParam *) pb)->csCode );
  2332.     text[0] = CStrLen((char *)text); // c2pstr
  2333.     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  2334. #endif
  2335.  
  2336.     if (pPrinterPB->terminating)
  2337.     {
  2338.         pb->ioResult = abortErr;
  2339.     }
  2340.     else
  2341.     {
  2342.         switch( ((CntrlParam *) pb)->csCode )
  2343.         {
  2344.         case kDrvrCentronicsStatus:
  2345.             dosomething = true;
  2346.             CentronicsStatus( usbprint,  *((Ptr *)((CntrlParam *) pb)->csParam), pPrinterPB->interfaceNumber );
  2347.             SetNullUSBParamBlock(pPrinterPB->deviceRef,  usbprint );
  2348.             break;
  2349.             
  2350.             
  2351.         case kDrvr1284IdString:
  2352.             dosomething = true;
  2353.             CapabilityRequest( usbprint,
  2354.                                     *((Ptr *)((CntrlParam *) pb)->csParam),
  2355.                                     *((long *) &((CntrlParam *) pb)->csParam[4]),
  2356.                                     0,        // configuration
  2357.                                     pPrinterPB->interfaceNumber,
  2358.                                     pPrinterPB->alternateSetting);
  2359.             SetNullUSBParamBlock(pPrinterPB->deviceRef,  usbprint );
  2360.             break;
  2361.             
  2362.         case kDrvrSoftReset:
  2363.             dosomething = true;
  2364.             if ( ((CntrlParam *) pb)->ioCRefNum == pPrinterPB->outRefNum )
  2365.             {
  2366.                 SetNullUSBParamBlock(pPrinterPB->writePipeRef,  usbprint );
  2367.             }
  2368.             else 
  2369.             {
  2370.                 SetNullUSBParamBlock(pPrinterPB->readPipeRef,  usbprint );
  2371.             }
  2372.             ClearEndpointHalt( usbprint );
  2373.             break;
  2374.         
  2375.         case kDrvrPrivateLog:
  2376.             // BT - 15Jun99, print a message in the log for the 68k code.
  2377.             USBExpertStatusLevel(((CntrlParam *) pb)->csParam[2], pPrinterPB->deviceRef, *(unsigned char **)(((CntrlParam *) pb)->csParam), *((long *)&((CntrlParam *) pb)->csParam[4]) );
  2378.             return;
  2379.             break;
  2380.         
  2381.         case kDrvrPrivateOpnClose:
  2382.             // BT - 15Jun99, Open or close has been called, arrange for suspend or resume.
  2383.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB print driver kDrvrPrivateOpnClose", ((CntrlParam *) pb)->csParam[0] == 0);
  2384.             // If csParam[0] is 1 we're being opened, if 0 we're being closed
  2385.             if(((CntrlParam *) pb)->csParam[0] == 1)
  2386.             {
  2387.                 wantToBe = kUSBPrintResumed;
  2388.                 // We're being opened
  2389.             }
  2390.             else if(((CntrlParam *) pb)->csParam[0] == 0)
  2391.             {
  2392.                 wantToBe = kUSBPrintSuspended;
  2393.                 // we're being closed
  2394.             }
  2395.             else
  2396.             {
  2397.                 USBExpertStatusLevel(2, pPrinterPB->deviceRef, "\pUSB print driver kDrvrPrivateOpnClose unknown message", ((CntrlParam *) pb)->csParam[0] == 0);
  2398.             }
  2399.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB PRint, control status do suspend resume" , pPrinterPB->deviceRef );
  2400.             USBPrintDoSuspendResume(pPrinterPB->interfaceRef);
  2401.             return;
  2402.             break;
  2403.         default:
  2404.             break;
  2405.         }
  2406.     
  2407.         if ( !dosomething )
  2408.             pb->ioResult = paramErr;
  2409.         else
  2410.         {
  2411.             usbprint->usbActCount = 0;
  2412.             usbprint->usbCompletion = (USBCompletion)CompletionProc;
  2413.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  2414.         
  2415.             pb->ioResult = ioInProgress;
  2416.             pPrinterPB->statusDrvr.pb = pb;
  2417.             pPrinterPB->statusDrvr.ctl = ctl;
  2418.         
  2419.             err = USBDeviceRequest(usbprint);
  2420.             if(immediateError(err))
  2421.             {
  2422.                 USBExpertFatalError(usbprint->usbReference, err, kPStrPrinterDriverName"StatusControlRequests", 0);
  2423.                 usbprint->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  2424.                 pb->ioResult = err;
  2425.             }
  2426.         }
  2427.     }
  2428. }
  2429.  
  2430.  
  2431. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2432.     Name:        PrinterDeviceCompletionProc
  2433.  
  2434.     Input Parameters:    
  2435.         pb                refCon tells which state we're completing
  2436.  
  2437.     Output Parameters:
  2438.         <none>
  2439.         
  2440.     Description:
  2441.         Complete asynch transactions initiated by PrinterDeviceInitiateTransaction.
  2442.  
  2443.  
  2444.  
  2445.  
  2446.  
  2447.  
  2448.  
  2449.  
  2450.  
  2451.  
  2452. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2453.  
  2454. static void 
  2455. PrinterDeviceCompletionProc(USBPB *pb)
  2456. {
  2457. Str255        tempstr1,tempstr2;
  2458. register     struct usbPrinterPBStruct *pPrinterPB;
  2459. OSStatus    err;
  2460. UInt32        i = 0;
  2461.     
  2462.     
  2463.     pPrinterPB = (struct usbPrinterPBStruct *)(pb);
  2464.  
  2465.     pPrinterPB->transDepth--; 
  2466.     if ((pPrinterPB->transDepth < 0) || (pPrinterPB->transDepth > 1))
  2467.     {
  2468.         USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName "CompletionProc Illegal Transaction Depth", pPrinterPB->transDepth );
  2469.     }
  2470.  
  2471.     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, StateStr(pPrinterPB->pb.usbRefcon, kPString) , pPrinterPB->pb.usbStatus );
  2472.  
  2473.     pPrinterPB->delayInProgress = false;
  2474.     
  2475.     if ( pPrinterPB->terminating )
  2476.     {
  2477.         //    if we've been hot unplugged
  2478.         //        don't startup any new transactions
  2479.         //     allow PrintDriverFinalize to continue
  2480.         pPrinterPB->pb.usbStatus = kUSBAbortedError;
  2481.         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2482.     }
  2483.     
  2484.  
  2485.     switch( pPrinterPB->pb.usbStatus )
  2486.     {
  2487.         case kUSBPending:
  2488.         case noErr:
  2489.             pPrinterPB->pb.usbRefcon &= ~kRetryTransaction;
  2490.             pPrinterPB->retryCount = kPrinterRetryCount;
  2491.             break;
  2492.             
  2493.         case kUSBLinkErr:
  2494.         case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  2495.         case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  2496.         case kUSBDataToggleErr:                            /*  Pipe stall, Bad data toggle */
  2497.         case kUSBNotRespondingErr:                        /*  Pipe stall, No device, device hung */
  2498.         case kUSBPIDCheckErr:                            /*  Pipe stall, PID CRC error */
  2499.         case kUSBWrongPIDErr:                            /*  Pipe stall, Bad or wrong PID */
  2500.         
  2501.             USBClearPipeStallByReference(pPrinterPB->deviceRef);  // we got an error, try to clear any stalls
  2502.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "    retry", pPrinterPB->pb.usbStatus);
  2503.             
  2504.             // clear out the transaction pending flag
  2505.             pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2506.             pPrinterPB->pb.usbRefcon |= kRetryTransaction;
  2507.             pPrinterPB->retryCount--;
  2508.             if (!pPrinterPB->retryCount)
  2509.             {
  2510.                 USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName "Retry failed", pPrinterPB->pb.usbRefcon & ~kRetryTransaction);
  2511.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2512.             } 
  2513.             else 
  2514.             {
  2515.                 pPrinterPB->pb.usbStatus = noErr;             // let's retry one more time
  2516.             }
  2517.             break;
  2518.             
  2519.         case kUSBNotFound:
  2520.             break;
  2521.             
  2522.         case kUSBAbortedError:                        /* user cancel, or hot unplug */
  2523.         default:
  2524.             // clear out the transaction pending flag
  2525.             pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;
  2526.             pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2527.             pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2528.             break;
  2529.     }
  2530.  
  2531.     if (pPrinterPB->pb.usbRefcon & kTransactionPending)             
  2532.     {            
  2533.         short    length;
  2534.     
  2535.         //
  2536.         //    advance to the next state
  2537.         //
  2538.         pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2539.         switch(pPrinterPB->pb.usbRefcon)
  2540.         {
  2541.             case kFindInterface_bidirectional:
  2542.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_bidirectional completed", pPrinterPB->pb.usb.cntl.WIndex);
  2543.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2544.                 {
  2545.                     if ((pPrinterPB->pb.usbClassType == kUSBPrintingClass) && 
  2546.                         (pPrinterPB->pb.usbSubclass == kUSBPrinterSubclass) &&
  2547.                         (pPrinterPB->pb.usbProtocol == kUSBPrinterBidirectionalProtocol))
  2548.                     {
  2549.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Found bidirectional interface at alt setting ", pPrinterPB->pb.usbOther);
  2550.                         pPrinterPB->configurationNumber = pPrinterPB->pb.usb.cntl.WValue;
  2551.                         pPrinterPB->alternateSetting = pPrinterPB->pb.usbOther;
  2552.                         pPrinterPB->printerProtocol = kUSBPrinterBidirectionalProtocol;
  2553.                         
  2554.                         // if we started out as a device class driver, then the interface descriptor will be NULL
  2555.                         // this would mean that the device will need to be opened before anything can be done with it
  2556.                         // if the interface descriptor point isn't null, then we started as an interface driver,
  2557.                         // so just skip by the opendevice call
  2558.                         if (pPrinterPB->pInterfaceDescriptor != NULL)
  2559.                         {
  2560.                         // did we find the interface we were looking for?
  2561.                             if (pPrinterPB->interfaceNumber == pPrinterPB->pb.usb.cntl.WIndex)
  2562.                             {
  2563.                                 pPrinterPB->pb.usbRefcon = kSetInterface;
  2564.                             }
  2565.                             else
  2566.                             {
  2567.                                 USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_Bidirectional didn't find the right interface", 0);
  2568.                             }
  2569.                         }
  2570.                         else
  2571.                         {
  2572.                             pPrinterPB->pb.usbRefcon = kOpenDevice;
  2573.                             pPrinterPB->interfaceNumber = pPrinterPB->pb.usb.cntl.WIndex;
  2574.                         }
  2575.                     }
  2576.                 }
  2577.                 else
  2578.                 {
  2579.                     if ( pPrinterPB->pb.usbStatus == kUSBNotFound )
  2580.                     {
  2581.                         USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Bidirectional interface was not found", pPrinterPB->pb.usb.cntl.WIndex);
  2582.                         pPrinterPB->pb.usbRefcon = kFindInterface_unidirectional;
  2583.                         pPrinterPB->pb.usbStatus = noErr;  // must clear error for state machine to continue <USB46>
  2584.                     }
  2585.                     else
  2586.                     {
  2587.                         USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_bidirectional failed", 0);
  2588.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2589.                     }
  2590.                 }
  2591.                 break;
  2592.                 
  2593.             case kFindInterface_unidirectional:
  2594.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_unidirectional completed", pPrinterPB->pb.usb.cntl.WIndex);
  2595.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2596.                 {
  2597.                     if ((pPrinterPB->pb.usbClassType == kUSBPrintingClass) && 
  2598.                         (pPrinterPB->pb.usbSubclass == kUSBPrinterSubclass) &&
  2599.                         (pPrinterPB->pb.usbProtocol == kUSBPrinterUnidirectionalProtocol))
  2600.                     {
  2601.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Found unidirection interface at alt setting ", pPrinterPB->pb.usbOther);
  2602.                         pPrinterPB->pb.usbRefcon = kOpenDevice;
  2603.                         pPrinterPB->configurationNumber = pPrinterPB->pb.usb.cntl.WValue;
  2604.                         pPrinterPB->alternateSetting = pPrinterPB->pb.usbOther;
  2605.                         pPrinterPB->printerProtocol = kUSBPrinterUnidirectionalProtocol;
  2606.                         // if we started out as a device class driver, then the interface descriptor will be NULL
  2607.                         // this would mean that the device will need to be opened before anything can be done with it
  2608.                         // if the interface descriptor point isn't null, then we started as an interface driver,
  2609.                         // so just skip by the opendevice call
  2610.                         if (pPrinterPB->pInterfaceDescriptor)
  2611.                         {
  2612.                             if (pPrinterPB->interfaceNumber == pPrinterPB->pb.usb.cntl.WIndex)
  2613.                             {
  2614.                                 pPrinterPB->pb.usbRefcon = kSetInterface;
  2615.                             }
  2616.                             else
  2617.                             {
  2618.                                 USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_Unidirectional didn't find the right interface", 0);
  2619.                             }
  2620.                         }
  2621.                         else
  2622.                         {
  2623.                             pPrinterPB->pb.usbRefcon = kOpenDevice;
  2624.                             pPrinterPB->interfaceNumber = pPrinterPB->pb.usb.cntl.WIndex;
  2625.                         }
  2626.                     }
  2627.                 }
  2628.                 else
  2629.                 {
  2630.                     if ( pPrinterPB->pb.usbStatus == kUSBNotFound )
  2631.                     {
  2632.                         USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Unidirectional interface was not found", pPrinterPB->pb.usb.cntl.WIndex);
  2633.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2634.                     }
  2635.                     else
  2636.                     {
  2637.                         USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_unidirectional failed", 0);
  2638.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2639.                     }
  2640.                 }
  2641.                 break;
  2642.                 
  2643.             case kOpenDevice:
  2644.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2645.                 {
  2646.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kOpenDevice completed", pPrinterPB->pb.usbStatus);
  2647.                     pPrinterPB->pb.usbRefcon = kNewInterfaceRef;
  2648.                 }
  2649.                 else
  2650.                 {
  2651.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kOpenDevice failed", 0);
  2652.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2653.                 }
  2654.                 break;
  2655.                 
  2656.             case kNewInterfaceRef:
  2657.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kNewInterfaceRef completed", pPrinterPB->pb.usbReference);
  2658.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2659.                 {
  2660.                     pPrinterPB->interfaceRef = pPrinterPB->pb.usbReference;
  2661.                     pPrinterPB->pb.usbRefcon = kSetInterface;
  2662.                 }
  2663.                 else
  2664.                 {
  2665.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kNewInterfaceRef failed", 0);
  2666.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2667.                 }
  2668.                 break;
  2669.             
  2670.             case kSetInterface:
  2671.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kSetInterface completed", 0);
  2672.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2673.                 {
  2674.                     pPrinterPB->pb.usbRefcon = kConfigureInterface;
  2675.                 }
  2676.                 else
  2677.                 {
  2678.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kSetInterface failed", 0);
  2679.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2680.                 }
  2681.                 break;
  2682.             
  2683.             case kConfigureInterface:
  2684.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kConfigureInterface completed, pipes = ", pPrinterPB->pb.usbOther);
  2685.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2686.                 {
  2687.                     pPrinterPB->pipeCount = pPrinterPB->pb.usbOther;
  2688.                     pPrinterPB->pb.usbRefcon = kGetCapabilityString;
  2689.                 }
  2690.                 else
  2691.                 {
  2692.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kConfigureInterface failed", 0);
  2693.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2694.                 }
  2695.                 break;
  2696.             
  2697.             case kGetCapabilityString:
  2698.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetCapabilityString completed", pPrinterPB->pb.usbStatus);
  2699.                 
  2700.                 if ( pPrinterPB->pb.usbActCount >= 2 )
  2701.                 {
  2702.                     length = pPrinterPB->pCapabilityString[1] | (pPrinterPB->pCapabilityString[0] << 8);
  2703.                 }
  2704.                 else
  2705.                 {
  2706.                     length = 0;
  2707.                 }
  2708.     
  2709.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2710.                 {
  2711.                     //
  2712.                     //    In the short term (fall '98) several vendors are planning on shipping 
  2713.                     //        devices with a parallel port and using the Lucent USS-720 USB-to-parallel hardware.
  2714.                     //    Unfortunately this isn't an ideal solution from the USB perspective:
  2715.                     //        users can leave the printer off while the cable responds that there's
  2716.                     //        a printer connected. Then we have no way of using the DEVICE_ID
  2717.                     //        string to tag the printer and register it.
  2718.                     //    To alleviate this situation, we repeatedly poll the USS-720 if the DEVICE_ID
  2719.                     //        string is null. Every few seconds we'll retry this state.
  2720.                     //    At some point the user wants to print and switches on the printer. The class
  2721.                     //    driver then picks up from here and registers the device properly.
  2722.                     //
  2723.                     
  2724.                     if ( pPrinterPB->pb.usbActCount == 0 )
  2725.                         pPrinterPB->pb.usbRefcon = kDelayGetCapability;
  2726.                     else
  2727.                         pPrinterPB->pb.usbRefcon = kFindBulkOutPipe;
  2728.                 }
  2729.                 else
  2730.                 {
  2731.                     if ( pPrinterPB->pb.usbStatus == kUSBOverRunErr )
  2732.                     {
  2733.                         //
  2734.                         //    if we've haven't managed to read the whole capability string
  2735.                         //        we need to allocate memory and read it in by initiating kGetFullCapabilityString
  2736.                         //
  2737.     
  2738.                         if ( length > sizeof(pPrinterPB->capability) && pPrinterPB->pb.usbRefcon == kGetCapabilityString )
  2739.                         {
  2740.                             pPrinterPB->pb.usbRefcon = kAllocateCapabilityMem;
  2741.                             pPrinterPB->pb.usbStatus = noErr;  // must clear error for state machine to continue <USB46>
  2742.                             break;                               // advance to that state <USB46>
  2743.                         }    
  2744.                         
  2745.                 
  2746.                     }
  2747.                     else
  2748.                     {
  2749.                         USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kGetCapabilityString failed", 0);
  2750.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2751.                     }
  2752.                 }
  2753.                 
  2754.                 // write the capability string to the log
  2755.                 if ((pPrinterPB->pb.usbStatus == kUSBOverRunErr)  || (pPrinterPB->pb.usbStatus == noErr))
  2756.                 {
  2757.                     if (length > 2)                     // is there a valid string? (length more than 2 bytes)
  2758.                     {
  2759.                         length -= 2;
  2760.                         if (length > 200)                // cut the string off at 200 characters
  2761.                             length = 200;
  2762.                             
  2763.                         BlockMove( (Ptr)&(pPrinterPB->pCapabilityString[2]), (Ptr)tempstr2, length);
  2764.                         tempstr2[length] = '\0';        // mark the end of the cstring
  2765.                         
  2766.                         sprintf( (char *)tempstr1, (char const *) kCStrPrinterDriverName"1284 Capability String: %s", tempstr2 );
  2767.                         CStrToPStr( (unsigned char *)tempstr2, (char *)tempstr1);    // convert it to a pstring
  2768.                     }
  2769.                     else
  2770.                     {
  2771.                         CStrCopy( (char *)tempstr2, (char const *) kCStrPrinterDriverName"Capability string is empty!!" );
  2772.                     }
  2773.                     USBExpertStatusLevel(kNormalStatusLevel,  pPrinterPB->deviceRef, tempstr2, length);
  2774.                 }
  2775.                 break;
  2776.                 
  2777.             case kDelayGetCapability:
  2778.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kDelayGetCapability completed", pPrinterPB->pb.usbStatus);
  2779.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2780.                 {
  2781.                     pPrinterPB->pb.usbRefcon = kGetCapabilityString;
  2782.                 }
  2783.                 else
  2784.                 {
  2785.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kDelayGetCapability failed", 0);
  2786.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2787.                 }
  2788.                 break;
  2789.                 
  2790.             case kAllocateCapabilityMem:
  2791.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kAllocateCapabilityMem completed", pPrinterPB->pb.usbStatus);
  2792.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2793.                 {
  2794.                     pPrinterPB->pCapabilityString = pPrinterPB->pb.usbBuffer;
  2795.                     pPrinterPB->pb.usbRefcon = kGetFullCapabilityString;    
  2796.                 }
  2797.                 else
  2798.                 {
  2799.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kAllocateCapabilityMem failed", 0);
  2800.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2801.                 }
  2802.                 break;
  2803.             
  2804.             case kGetFullCapabilityString:
  2805.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetFullCapabilityString completed", pPrinterPB->pb.usbStatus);
  2806.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2807.                 {
  2808.                     pPrinterPB->pb.usbRefcon = kGetInterface;
  2809.                 }
  2810.                 else
  2811.                 {
  2812.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kGetFullCapabilityString failed", 0);
  2813.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2814.                 }
  2815.                 break;
  2816.                 
  2817.             case kGetInterface:
  2818.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetInterface completed", pPrinterPB->pb.usbStatus);
  2819.                 if (( pPrinterPB->pb.usbStatus == noErr ) && (pPrinterPB->whichAltInterface == pPrinterPB->alternateSetting))
  2820.                 {
  2821.                     pPrinterPB->pb.usbRefcon = kFindBulkOutPipe;
  2822.                 }
  2823.                 else
  2824.                 {
  2825.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kGetInterface - wrong interface selected", pPrinterPB->whichAltInterface);
  2826.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2827.                 }
  2828.                 break;
  2829.  
  2830.             case kFindBulkOutPipe:
  2831.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkOutPipe completed", pPrinterPB->pb.usbReference);
  2832.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2833.                 {
  2834.                     pPrinterPB->writePipeRef = pPrinterPB->pb.usbReference;             // remember the ref
  2835.                     pPrinterPB->out = pPrinterPB->pb;                                    // copy the paramblock
  2836.                     pPrinterPB->out.usbCompletion =  (USBCompletion) NULL;                // for finalize
  2837.  
  2838.                     if ( pPrinterPB->printerProtocol == kUSBPrinterBidirectionalProtocol )
  2839.                         pPrinterPB->pb.usbRefcon = kFindBulkInPipe;
  2840.                     else
  2841.                         pPrinterPB->pb.usbRefcon = kTaskTimeRequired;
  2842.                 }
  2843.                 else
  2844.                 {
  2845.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindBulkOutPipe failed", 0);
  2846.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2847.                 }
  2848.                 break;
  2849.                 
  2850.             case kFindBulkInPipe:
  2851.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkInPipe completed", pPrinterPB->pb.usbReference);
  2852.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2853.                 {
  2854.                     pPrinterPB->readPipeRef = pPrinterPB->pb.usbReference;
  2855.                     pPrinterPB->in = pPrinterPB->pb;                                    // copy the paramblock
  2856.                     pPrinterPB->in.usbCompletion =  (USBCompletion) NULL;                // for finalize
  2857.  
  2858.                     pPrinterPB->pb.usbRefcon = kTaskTimeRequired;
  2859.                 }
  2860.                 else
  2861.                 {
  2862.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindBulkInPipe failed", 0);
  2863.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2864.                 }
  2865.                 break;
  2866.                 
  2867.             case kTaskTimeRequired:
  2868.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired completed (now at task time)", pPrinterPB->pb.usbReference);
  2869.             //
  2870.             //    once we know what device we're dealing with
  2871.             //        open the i/o channel(s) to the device
  2872.             //        and enter it in the name registry
  2873.             //
  2874.                 
  2875.                 err = InstallDrivers( pPrinterPB );
  2876.                 if ( err == noErr )
  2877.                 {
  2878.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired - drivers installed", pPrinterPB->pb.usbReference);
  2879.                     err = RegisterDevice( pPrinterPB );
  2880.                     if ( err == noErr )
  2881.                     {
  2882.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired - RegisterDevice successful", pPrinterPB->pb.usbReference);
  2883.                     }
  2884.                     else
  2885.                     {
  2886.                         USBExpertFatalError(pPrinterPB->interfaceRef, err, kPStrPrinterDriverName"kTaskTimeRequired - RegisterDevice failed", 0);
  2887.                     }
  2888.                 }
  2889.                 else
  2890.                 {
  2891.                     USBExpertFatalError(pPrinterPB->interfaceRef, err, kPStrPrinterDriverName"kTaskTimeRequired - InstallDrivers failed", 0);
  2892.                 }
  2893.     
  2894.                 pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;                    // Finalize
  2895.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2896.                 {
  2897.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, "\pPrinter driver now exiting setup, calling suspend", pPrinterPB->interfaceRef );
  2898.                     USBPrintDoSuspendResume(pPrinterPB->interfaceRef); 
  2899.                     pPrinterPB->pb.usbRefcon = kReturnFromDriver;
  2900.                     pPrinterPB->printerConfigured = true;
  2901.                 }
  2902.                 else
  2903.                 {
  2904.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"RegisterDevice failed", 0);
  2905.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2906.                 }
  2907.                 break;
  2908.                 
  2909.             case kGetCentronicsStatus:
  2910.                 //
  2911.                 //    if InitiateTransaction fell through on it's kTaskTimeRequired case we'll end up here
  2912.                 //
  2913.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2914.                 {
  2915.                     unsigned char text[255];
  2916.                     sprintf( (char *)text, " Centronics Status: 0x%02x", pPrinterPB->centronics.b );
  2917.                     text[0] = CStrLen((char *)text); // c2pstr
  2918.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, text, pb->usbStatus );
  2919.                     
  2920. #if DEBUG
  2921.                     if ( !pPrinterPB->centronics.status.notError )
  2922.                     {
  2923.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"Error at printer", pPrinterPB->pb.usbStatus);
  2924.                     }
  2925.                     if ( pPrinterPB->centronics.status.paperError )
  2926.                     {
  2927.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"Check paper", pPrinterPB->pb.usbStatus);
  2928.                     }
  2929.                     if ( !pPrinterPB->centronics.status.select )
  2930.                     {
  2931.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"printer offline", pPrinterPB->pb.usbStatus);
  2932.                     }
  2933. #endif
  2934.                     pPrinterPB->pb.usbRefcon = kDelayGetCentronicsStatus;
  2935.                 }
  2936.                 else
  2937.                 {
  2938.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetCentronicsStatus - error getting centronics status", pPrinterPB->pb.usbStatus);
  2939.                 }
  2940.                 break;
  2941.                 
  2942.             case kDelayGetCentronicsStatus:
  2943.                 //
  2944.                 //    loop around continually getting status
  2945.                 //
  2946.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2947.                 {
  2948.                     pPrinterPB->pb.usbRefcon = kGetCentronicsStatus;
  2949.                 }
  2950.                 break;
  2951.             case kNilCompletion:
  2952.             default:
  2953.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2954.                     pPrinterPB->pb.usbRefcon = kUndefined | kReturnFromDriver;
  2955.                 break;
  2956.         }
  2957.     }
  2958.     
  2959.     // did the removal notification get called?  If so, don't start another transaction.  Just exit
  2960.    if (!pPrinterPB->terminating)
  2961.     {
  2962.         if (pPrinterPB->pb.usbStatus == noErr )
  2963.         {
  2964.             if (!(pPrinterPB->pb.usbRefcon & kReturnFromDriver))
  2965.                 PrinterDeviceInitiateTransaction(pb);
  2966.         }
  2967.         else if ( pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  2968.         {
  2969.             USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, StateStr(pPrinterPB->pb.usbRefcon, kPString), pPrinterPB->pb.usbRefcon);
  2970.             USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, USBStatusStr(pPrinterPB->pb.usbStatus, kPString), 0);
  2971.         }
  2972.     }
  2973.     else
  2974.     {
  2975.         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2976.     }
  2977.     
  2978.     // If we're exiting the driver, then make certain the completion routine is set to NULL
  2979.     // this lets the driver removal task know that there's nothing pending.
  2980.     if ( pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  2981.     {
  2982.         pPrinterPB->pb.usbCompletion    = (USBCompletion) NULL;
  2983.     }
  2984. }
  2985.  
  2986. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2987.     Name:        PrinterDeviceInitiateTransaction
  2988.  
  2989.     Input Parameters:    
  2990.         pb            USB parameter block
  2991.         
  2992.     Output Parameters:
  2993.         
  2994.     Description:
  2995.         Since USB transactions are asynchronous we use the refCon field
  2996.         in the parameter block to implement the following logic via a state machine.
  2997.  
  2998.         Start out by getting the device configuration descriptor
  2999.         If the device has more than one printing interface
  3000.             If a bidirectional interface exists
  3001.                 select it
  3002.             Else
  3003.                 select the (mandatory) unidirectional interface
  3004.         Get the (mandatory) 1284 capability string
  3005.         Open pipes to the BulkOut (and optional BulkIn) endpoints
  3006.         Install read and write drivers in the unit table
  3007.         Using information from the capability string
  3008.             enter the printer in the MacOS name registry.
  3009.         
  3010.  
  3011.  
  3012.  
  3013.  
  3014.  
  3015.  
  3016. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3017. void
  3018. PrinterDeviceInitiateTransaction(USBPB *pb)
  3019. {
  3020. register struct usbPrinterPBStruct    *pPrinterPB;
  3021. UInt16        length;
  3022. OSStatus    err;
  3023.  
  3024.     pPrinterPB = (struct usbPrinterPBStruct *)(pb);
  3025.     
  3026.     pPrinterPB->transDepth++;
  3027.     if ((pPrinterPB->transDepth < 0) || (pPrinterPB->transDepth > 1))
  3028.     {
  3029.         USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName"InitiateTransaction illegal transaction depth", 0);
  3030.     }
  3031.     IF_DEBUG( USBExpertStatusLevel(5 pPrinterPB->deviceRef, StateStr(pPrinterPB->pb.usbRefcon, kPString), 0) );     
  3032.     
  3033.     pPrinterPB->delayInProgress = false;
  3034.     switch(pPrinterPB->pb.usbRefcon & ~kRetryTransaction)
  3035.     {
  3036.         case kFindInterface_bidirectional:
  3037.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_bidirectional", 0);
  3038.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3039.             
  3040.             pPrinterPB->pb.usbBuffer = 0;
  3041.             pPrinterPB->pb.usbActCount = 0;
  3042.             pPrinterPB->pb.usbReqCount = 0;
  3043.             pPrinterPB->pb.usb.cntl.WIndex = 0;
  3044.             pPrinterPB->pb.usb.cntl.WValue = 0;
  3045.             pPrinterPB->pb.usbClassType = kUSBPrintingClass;
  3046.             pPrinterPB->pb.usbSubclass = kUSBPrinterSubclass;
  3047.             pPrinterPB->pb.usbProtocol = kUSBPrinterBidirectionalProtocol;
  3048.             
  3049.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3050.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3051.             err = USBFindNextInterface(pb);
  3052.             if(immediateError(err))
  3053.             {
  3054.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"kFindInterface_bidirectional - immediate error", err);
  3055.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3056.             }
  3057.             break;
  3058.     
  3059.         case kFindInterface_unidirectional:
  3060.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_unidirectional", 0);
  3061.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3062.             
  3063.             pPrinterPB->pb.usbBuffer = 0;
  3064.             pPrinterPB->pb.usbActCount = 0;
  3065.             pPrinterPB->pb.usbReqCount = 0;
  3066.             pPrinterPB->pb.usb.cntl.WIndex = 0;
  3067.             pPrinterPB->pb.usb.cntl.WValue = 0;
  3068.             pPrinterPB->pb.usbClassType = kUSBPrintingClass;
  3069.             pPrinterPB->pb.usbSubclass = kUSBPrinterSubclass;
  3070.             pPrinterPB->pb.usbProtocol = kUSBPrinterUnidirectionalProtocol;
  3071.             
  3072.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3073.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3074.             err = USBFindNextInterface(pb);
  3075.             if(immediateError(err))
  3076.             {
  3077.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"kFindInterface_unidirectional - immediate error", err);
  3078.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3079.             }
  3080.             break;
  3081.     
  3082.         case kOpenDevice:
  3083.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kOpenDevice", 0);
  3084.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3085.             
  3086.             pPrinterPB->pb.usbBuffer = 0;
  3087.             pPrinterPB->pb.usbActCount = 0;
  3088.             pPrinterPB->pb.usbReqCount = 0;
  3089.             pPrinterPB->pb.usb.cntl.WValue = pPrinterPB->configurationNumber;
  3090.             
  3091.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3092.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3093.             err = USBOpenDevice(pb);
  3094.             if(immediateError(err))
  3095.             {
  3096.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"USBOpenDevice - immediate error", err);
  3097.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3098.             }
  3099.             break;
  3100.             
  3101.         case kNewInterfaceRef:
  3102.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kNewInterfaceRef for interface number", pPrinterPB->interfaceNumber);
  3103.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3104.             
  3105.             pPrinterPB->pb.usbBuffer = 0;
  3106.             pPrinterPB->pb.usbActCount = 0;
  3107.             pPrinterPB->pb.usbReqCount = 0;
  3108.             pPrinterPB->pb.usb.cntl.WIndex = pPrinterPB->interfaceNumber;
  3109.             
  3110.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3111.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3112.             err = USBNewInterfaceRef(pb);
  3113.             if(immediateError(err))
  3114.             {
  3115.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"USBNewInterfaceRef - immediate error", err);
  3116.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3117.             }
  3118.             break;
  3119.             
  3120.  
  3121.         case kSetInterface:
  3122.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kSetInterface to alternate setting", pPrinterPB->alternateSetting);
  3123.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3124.             
  3125.             pPrinterPB->pb.usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBStandard, kUSBInterface);
  3126.         
  3127.             pPrinterPB->pb.usb.cntl.BRequest = kUSBRqSetInterface;
  3128.             pPrinterPB->pb.usb.cntl.WValue = pPrinterPB->alternateSetting;        // alternate setting
  3129.             pPrinterPB->pb.usb.cntl.WIndex = pPrinterPB->interfaceNumber;        // interface
  3130.         
  3131.             pPrinterPB->pb.usbReqCount = 0;
  3132.             pPrinterPB->pb.usbBuffer = NULL;
  3133.         
  3134.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3135.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3136.             err = USBDeviceRequest(pb);
  3137.             if(immediateError(err))
  3138.             {
  3139.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"kSetInterface - immediate error", err);
  3140.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3141.             }
  3142.             break;
  3143.  
  3144.  
  3145.         case kConfigureInterface:
  3146.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kConfigureInterface for alternate setting", pPrinterPB->alternateSetting);
  3147.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3148.             
  3149.             pPrinterPB->pb.usbBuffer = 0;
  3150.             pPrinterPB->pb.usbActCount = 0;
  3151.             pPrinterPB->pb.usbReqCount = 0;
  3152.             pPrinterPB->pb.usbOther = pPrinterPB->alternateSetting;
  3153.             
  3154.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3155.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3156.             err = USBConfigureInterface(pb);
  3157.             if(immediateError(err))
  3158.             {
  3159.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"USBConfigureInterface - immediate error)", err);
  3160.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3161.             }
  3162.             break;
  3163.             
  3164.         case kGetCapabilityString:
  3165.             //
  3166.             //    once the interface (and alternate) is assinged
  3167.             //        we can retreive the 1284 capability string to see what kind of printer
  3168.             //        is attached
  3169.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetCapabilityString", 0);
  3170.             pPrinterPB->pCapabilityString = pPrinterPB->capability;
  3171.             
  3172.             GetCapability( pPrinterPB, pPrinterPB->pCapabilityString, sizeof(pPrinterPB->capability) );
  3173.             break;
  3174.             
  3175.         case kDelayGetCapability:
  3176.             //
  3177.             //    USS-720 USB-parallel cable: couldn't get the capability string because the printer is off
  3178.             //        Delay a few seconds and try again.
  3179.             //        Will succeed when the user turns the printer on.
  3180.             //
  3181.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kDelayGetCapability", 0);
  3182.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3183.             
  3184.             pPrinterPB->pb.usbBuffer = 0;
  3185.             pPrinterPB->pb.usbActCount = 0;
  3186.             pPrinterPB->pb.usbReqCount = kUSS720MillisecondDelay;
  3187.             pPrinterPB->pb.usbFlags = kUSBTaskTimeFlag;
  3188.             
  3189.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3190.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3191.             pPrinterPB->delayInProgress = true;
  3192.             err = USBDelay(&pPrinterPB->pb);
  3193.             if(immediateError(err))
  3194.             {
  3195.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kDelayGetCapability - immediate error", 0);
  3196.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3197.             }
  3198.             break;
  3199.             
  3200.         case kAllocateCapabilityMem:
  3201.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kAllocateCapabilityMem", 0);
  3202.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3203.             length = *(UInt16*)(pPrinterPB->capability);
  3204.             pPrinterPB->pb.usbBuffer = 0;
  3205.             pPrinterPB->pb.usbActCount = 0;
  3206.             pPrinterPB->pb.usbReqCount = length;
  3207.             pPrinterPB->pb.usbFlags = 0;
  3208.             
  3209.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3210.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3211.             err = USBAllocMem(&pPrinterPB->pb);
  3212.             if(immediateError(err))
  3213.             {
  3214.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kAllocateCapabilityMem - immediate error", 0);
  3215.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3216.             }
  3217.             break;
  3218.         
  3219.         case kGetFullCapabilityString:
  3220.             //
  3221.             // the capability string was too long to fit in the statically allocated space
  3222.             // need to release this memory when we finalize our driver
  3223.             //
  3224.  
  3225.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetFullCapabilityString", 0);
  3226.             length = *(UInt16*)(pPrinterPB->capability);
  3227.             if ( pPrinterPB->pCapabilityString )
  3228.                 GetCapability( pPrinterPB, pPrinterPB->pCapabilityString, length );
  3229.             else
  3230.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kPStrPrinterDriverName"Can't allocate capability memory", 0);
  3231.             break;
  3232.             
  3233.         case kGetInterface:
  3234.             // failsafe check that we've got the right setup
  3235.             //    it's possible the device didn't respond to our SetInterface
  3236.             GetInterface( &pPrinterPB->pb, &pPrinterPB->whichAltInterface );
  3237.             break;
  3238.  
  3239.         case kFindBulkOutPipe:
  3240.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkOutPipe", 0);
  3241.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3242.             
  3243.             pPrinterPB->pb.usbBuffer = 0;
  3244.             pPrinterPB->pb.usbActCount = 0;
  3245.             pPrinterPB->pb.usbReqCount = 0;
  3246.             pPrinterPB->pb.usbFlags = kUSBOut;
  3247.             pPrinterPB->pb.usbClassType = kUSBBulk;
  3248.             
  3249.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3250.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3251.             err = USBFindNextPipe( &pPrinterPB->pb );
  3252.             if (immediateError(err))
  3253.             {
  3254.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kPStrPrinterDriverName"kFindBulkOutPipe - immediate error", err);
  3255.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3256.             }
  3257.             break;
  3258.             
  3259.         case kFindBulkInPipe:    
  3260.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkInPipe", 0);
  3261.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3262.             
  3263.             pPrinterPB->pb.usbBuffer = 0;
  3264.             pPrinterPB->pb.usbActCount = 0;
  3265.             pPrinterPB->pb.usbReqCount = 0;
  3266.             pPrinterPB->pb.usbFlags = kUSBIn;
  3267.             pPrinterPB->pb.usbClassType = kUSBBulk;
  3268.             
  3269.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3270.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3271.             err = USBFindNextPipe( &pPrinterPB->pb );
  3272.             if (immediateError(err))
  3273.             {
  3274.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kPStrPrinterDriverName"kFindBulkInPipe - immediate error", err);
  3275.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3276.             }
  3277.             break;
  3278.             
  3279.         case kTaskTimeRequired:
  3280.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired", 0);
  3281.              // to stress test usb bus, fallthrough to kGetCentronicsStatus 
  3282.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3283.             
  3284.             pPrinterPB->pb.usbBuffer = 0;
  3285.             pPrinterPB->pb.usbActCount = 0;
  3286.             pPrinterPB->pb.usbReqCount = kUSBNoDelay;
  3287.             pPrinterPB->pb.usbFlags = kUSBTaskTimeFlag;
  3288.             
  3289.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3290.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3291.             pPrinterPB->delayInProgress = true;
  3292.             err = USBDelay(&pPrinterPB->pb);
  3293.             if(immediateError(err))
  3294.             {
  3295.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kTaskTimeRequired - immediate error", 0);
  3296.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3297.             }
  3298.             break;
  3299.  
  3300.         case kGetCentronicsStatus:
  3301.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3302.  
  3303.             CentronicsStatus( &pPrinterPB->pb,  &pPrinterPB->centronics.b, pPrinterPB->interfaceNumber );
  3304.             
  3305.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3306.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3307.             err = USBDeviceRequest(&pPrinterPB->pb);
  3308.             if(immediateError(err))
  3309.             {
  3310.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kGetCentronicsStatus Immediate error", 0);
  3311.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3312.             }
  3313.             break;
  3314.             
  3315.         case kDelayGetCentronicsStatus:
  3316.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3317.  
  3318.             pPrinterPB->pb.usbBuffer = 0;
  3319.             pPrinterPB->pb.usbActCount = 0;
  3320.             pPrinterPB->pb.usbReqCount = kUSS720StatusMSDelay;
  3321.             
  3322.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3323.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3324.             pPrinterPB->delayInProgress = true;
  3325.             err = USBDelay(&pPrinterPB->pb);
  3326.             if(immediateError(err))
  3327.             {
  3328.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kDelayGetCentronicsStatus - immediate error", 0);
  3329.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3330.             }
  3331.             break;
  3332.             
  3333.         default:
  3334.             USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName"InitiateTransaction - unknown state", pPrinterPB->pb.usbRefcon);
  3335.             pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3336.             break;
  3337.     }
  3338.     
  3339.     if (pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  3340.     {
  3341.         pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;
  3342.         pPrinterPB->pb.usbRefcon &= ~kTransactionPending;
  3343.     }
  3344. }
  3345.  
  3346.  
  3347. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3348.     Name:        PrintDriverEntry
  3349.  
  3350.     Input Parameters:    
  3351.         
  3352.     Output Parameters:
  3353.         
  3354.     Description:
  3355.         This is where the system instantiates a USB printing device.
  3356.  
  3357.         We need to install drivers in the MacOS unitTable, and a reference
  3358.         in the name registry.
  3359.         
  3360.         But the information we need to do this is only available after some 
  3361.         USB transactions have completed. So we initiate here a series of asynchronous
  3362.         USB operations to get that information (by calling the first 
  3363.  
  3364.  
  3365.  
  3366.  
  3367.  
  3368. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3369. void 
  3370. PrintDriverEntry(
  3371.     USBDeviceRef                    deviceRef,
  3372.     USBDeviceDescriptorPtr            pDeviceDesc,
  3373.     USBInterfaceDescriptorPtr        pInterfaceDesc,
  3374.     UInt32                            interfaceNumber
  3375.     )
  3376. {
  3377.     static Boolean        beenThereDoneThat = false;
  3378.     OSStatus                err;
  3379.     
  3380.     
  3381.     RoutineDescriptor qw = BUILD_ROUTINE_DESCRIPTOR( uppQueueUSBWriteProcInfo, QueueWrite);
  3382.     RoutineDescriptor qr = BUILD_ROUTINE_DESCRIPTOR( uppQueueUSBReadProcInfo, QueueRead);
  3383.     RoutineDescriptor qa = BUILD_ROUTINE_DESCRIPTOR( uppAbortProcInfo, Abort);
  3384.     RoutineDescriptor qs = BUILD_ROUTINE_DESCRIPTOR( uppControlStatusProcInfo, ControlStatusRequests );
  3385.     
  3386.     if( !beenThereDoneThat)
  3387.     {
  3388.         printerClassRecord.terminating = false;
  3389.         printerClassRecord.printerRegistered = false;
  3390.         beenThereDoneThat = true;
  3391.         
  3392.         //DebugStr("\pIn Printer Driver Entry");
  3393.         USBExpertStatusLevel(kNormalStatusLevel, deviceRef, kPStrPrinterDriverName"Starting USB Printer Driver", 0);
  3394.         
  3395.         printerClassRecord.deviceDescriptor = *pDeviceDesc;    /* keep a copy of the device descriptor */
  3396.         printerClassRecord.pInterfaceDescriptor = pInterfaceDesc;
  3397.         printerClassRecord.interfaceNumber = interfaceNumber;
  3398.         
  3399.         printerClassRecord.deviceRef = deviceRef;
  3400.         printerClassRecord.interfaceRef = deviceRef;
  3401.         
  3402.         printerClassRecord.transDepth = 0;            /* init Delay Callback Depth */
  3403.     
  3404.         printerClassRecord.inRefNum =  -1;            /* initially no DRVRs added to UnitTable */
  3405.         printerClassRecord.outRefNum =  -1;    
  3406.         err = LoadResources( &printerClassRecord );
  3407.         if ( err != noErr )  
  3408.             USBExpertFatalError( deviceRef, err, kPStrPrinterDriverName"LoadResources failed", 0);
  3409.         //
  3410.         //    routines to write and read to the device must be called by 68K DRVR
  3411.         //        so we use mixed-mode manager to dispatch between PPC and 68K
  3412.         //
  3413.         printerClassRecord.qwrite = (QueueUSBWriteUPP) &printerClassRecord.qwriteRD;
  3414.         printerClassRecord.qwriteRD = qw;
  3415.     
  3416.         printerClassRecord.qread = (QueueUSBReadUPP) &printerClassRecord.qreadRD;
  3417.         printerClassRecord.qreadRD = qr;    
  3418.         
  3419.         printerClassRecord.qstatus = (ControlStatusUPP) &printerClassRecord.qstatusRD;
  3420.         printerClassRecord.qstatusRD = qs;
  3421.  
  3422.         printerClassRecord.qabort = (AbortUPP) &printerClassRecord.qabortRD;
  3423.         printerClassRecord.qabortRD = qa;
  3424.  
  3425.         printerClassRecord.r = (QueueUSBReadUPP) QueueRead;
  3426.         printerClassRecord.w = (QueueUSBWriteUPP) QueueWrite;
  3427.         printerClassRecord.s = (ControlStatusUPP) ControlStatusRequests;
  3428.         printerClassRecord.a = (AbortUPP) Abort;
  3429.    
  3430.         SetNullUSBParamBlock( deviceRef, &printerClassRecord.pb );
  3431.         SetNullUSBParamBlock( 0, &printerClassRecord.in );        // fill in pipe ref later
  3432.         SetNullUSBParamBlock( 0, &printerClassRecord.out );    // fill in pipe ref later
  3433.         
  3434.         CStrCopy((char *)printerClassRecord.name, "");
  3435.         CStrCopy((char *)printerClassRecord.model, "");
  3436.  
  3437. #if DOUBLE_BUFFER
  3438.         //
  3439.         // Assume 1. TRANSFER_SIZE is a power of 2
  3440.         //    Assume 2. malignedBuffer is allocated to be 3*TRANSFER_SIZE
  3441.         //
  3442.         printerClassRecord.pageWriteAlignedBufferSize = TRANSFER_SIZE;                            // should get this from VM
  3443.         printerClassRecord.pageWriteAlignedBuffer = printerClassRecord.malignedBuffer;
  3444.  
  3445.         // align it below the buffer, then bring it into the range of the buffer
  3446.         *((UInt32 *) &printerClassRecord.pageWriteAlignedBuffer) &= ~(printerClassRecord.pageWriteAlignedBufferSize - 1);    //assumption1
  3447.         *((UInt32 *) &printerClassRecord.pageWriteAlignedBuffer) += printerClassRecord.pageWriteAlignedBufferSize;            //assumption2
  3448.  
  3449.         printerClassRecord.pageReadAlignedBufferSize = TRANSFER_SIZE;
  3450.         printerClassRecord.pageReadAlignedBuffer = printerClassRecord.pageWriteAlignedBuffer + TRANSFER_SIZE;
  3451.         
  3452. #endif
  3453.         printerClassRecord.printerConfigured = false;
  3454.     
  3455.         //
  3456.         //    Just to be thorough, lets hold our paramter blocks so that we won't page them at
  3457.         //        interrupt time. (We should be in the System heap and automatically held.)
  3458.         //
  3459.         HoldMemory( &printerClassRecord, sizeof(struct usbPrinterPBStruct) );
  3460.  
  3461.         CheckUSBVersion();
  3462.         
  3463.         //
  3464.         // Start out at first state
  3465.         //
  3466.         printerClassRecord.pCapabilityString = printerClassRecord.capability;
  3467.         printerClassRecord.pb.usbRefcon = kFindInterface_bidirectional;
  3468.         
  3469.         // don't start if we received a removal notification just as we're starting up
  3470.         if (printerClassRecord.terminating)
  3471.         {
  3472.             printerClassRecord.pb.usbCompletion    = (USBCompletion) NULL;
  3473.         }
  3474.         else
  3475.         {
  3476.             PrinterDeviceInitiateTransaction(&printerClassRecord.pb);
  3477.         }
  3478.     }
  3479. }
  3480.  
  3481. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3482.     Name:        PrinterRemovalNotification
  3483.  
  3484.     Input Parameters:    
  3485.         
  3486.     Output Parameters:
  3487.         
  3488.     Description:
  3489.         release any allocated storage
  3490.         remove DRVRs from the UnitTable
  3491.  
  3492.         One small complication happens when the USS-720 cable is used. It's possible
  3493.         that the user has the device plugged in, but the printer wasn't powered on.
  3494.         In this case, our state machine is still cycling between the states 
  3495.         kDelayGetCapability and kGetCapabilityString. If we terminate before the delay
  3496.         returns we'll crash the system. We monitor terminating to handle this
  3497.         
  3498.  
  3499.  
  3500.  
  3501.  
  3502.  
  3503.  
  3504.  
  3505.  
  3506.  
  3507. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3508. OSStatus
  3509. PrinterRemovalNotification( void )
  3510. {
  3511. static    Boolean    logfileclosed = false;
  3512. static    Boolean    aborted = false;
  3513. static    Boolean    deregistered = false;
  3514. static    Boolean    readpipeaborted = false;
  3515. static    Boolean    writepipeaborted = false;
  3516. static    Boolean    timedout = false;
  3517. OSStatus            result = noErr;
  3518. static unsigned long    tc = 0;
  3519.     //
  3520.     //    notify state machine not to continue
  3521.     //
  3522.     printerClassRecord.terminating = true;
  3523.     
  3524.     USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Driver removal notification received", 0);
  3525.     if (!logfileclosed)
  3526.     {
  3527.         USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Closing printer log file", 0);
  3528.         LOGGING( fclose( logfile ) );
  3529.         logfileclosed = true;
  3530.         return (OSStatus) kUSBDeviceBusy;
  3531.     }
  3532.     
  3533.     // per the Mac OS USB DDK API Ref 
  3534.     // "If the device associated with this call [USBDelay] is unplugged and its driver removed while
  3535.     //  this function call is pending, the function will not complete."
  3536.     // therefore don't hang around if a delay is in progress
  3537.     if (( printerClassRecord.pb.usbCompletion != (USBCompletion) NULL ) && (!printerClassRecord.delayInProgress))
  3538.     {
  3539.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Waiting for configuration to complete", printerClassRecord.pb.usbRefcon);
  3540.         return (OSStatus) kUSBDeviceBusy;
  3541.     }
  3542.     
  3543.     // Abort any outstanding write requests
  3544.     if (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL ) && (!writepipeaborted))
  3545.     {
  3546.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Abort write pipe", printerClassRecord.writePipeRef);
  3547.         USBAbortPipeByReference( printerClassRecord.writePipeRef );
  3548.         writepipeaborted = true;
  3549.         return (OSStatus) kUSBDeviceBusy;
  3550.     }
  3551.     
  3552.     // Abort any outstanding read requests
  3553.     if (( printerClassRecord.in.usbCompletion != (USBCompletion) NULL ) && (!readpipeaborted))
  3554.     {
  3555.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Abort read pipe", printerClassRecord.readPipeRef );
  3556.         USBAbortPipeByReference( printerClassRecord.readPipeRef );
  3557.         readpipeaborted = true;
  3558.         return (OSStatus) kUSBDeviceBusy;
  3559.     }
  3560.     
  3561.     // Abort any outstanding transactions
  3562.     if (!aborted)
  3563.     {
  3564.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Call Abort()", 0);
  3565.         Abort( 0, &printerClassRecord );
  3566.         aborted = true;
  3567.         return (OSStatus) kUSBDeviceBusy;
  3568.     }
  3569.  
  3570.     // wait up to ten seconds for the read & write routines to complete.  When they do, the completion procptrs will be NULL'd
  3571.     if (tc == 0)
  3572.         tc = TickCount() + 10*60;
  3573.         
  3574.     if ( TickCount() >= tc )
  3575.         timedout = true;
  3576.         
  3577.     if (( TickCount() < tc ) &&
  3578.          (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL) ||
  3579.           ( printerClassRecord.in.usbCompletion != (USBCompletion) NULL )))
  3580.     {
  3581.         return (OSStatus) kUSBDeviceBusy;
  3582.     }
  3583.     
  3584.     // Put the appropriate timeout message in the log
  3585.     if ( timedout )
  3586.     {
  3587.         USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"took longer than 10 seconds for read/write pipes to complete", 0);
  3588.     }
  3589.     else
  3590.     {
  3591.         USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Pipes closed normally", 0);
  3592.     }
  3593.     
  3594.     if (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL) ||
  3595.           ( printerClassRecord.in.usbCompletion != (USBCompletion) NULL ))
  3596.     {
  3597.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Completion procs are not nil!!", 0);
  3598.     }
  3599.     
  3600.     // if the printer was never registered, then don't try to deregister it
  3601.     if (!(printerClassRecord.printerRegistered))
  3602.         deregistered = true;
  3603.         
  3604.     if (!deregistered)    
  3605.     {
  3606.         //
  3607.         //    remove printer from the name registry
  3608.         //
  3609.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Removed printer entry from nameregistry", 0);
  3610.         DeregisterDevice( &printerClassRecord );
  3611.         deregistered = true;
  3612.         return (OSStatus) kUSBDeviceBusy;
  3613.     }
  3614.  
  3615.     //
  3616.     //    release any allocated storage
  3617.     //
  3618.     if ( printerClassRecord.pCapabilityString != printerClassRecord.capability )
  3619.     {
  3620.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Deallocated capability string memory", 0);
  3621.         printerClassRecord.pb.usbReference = printerClassRecord.deviceRef;             
  3622.         printerClassRecord.pb.usbFlags = 0;             
  3623.         printerClassRecord.pb.usbRefcon = kDeallocateCapbilityString;             
  3624.         printerClassRecord.pb.usbBuffer = printerClassRecord.pCapabilityString;        
  3625.         printerClassRecord.pb.usbCompletion = (USBCompletion)kUSBNoCallBack;
  3626.         printerClassRecord.delayInProgress = true;        // this prevents the control pipe completion procptr from being checked
  3627.         USBDeallocMem(&printerClassRecord.pb);
  3628.         
  3629.         printerClassRecord.pCapabilityString = printerClassRecord.capability;
  3630.         return (OSStatus) kUSBDeviceBusy;
  3631.     }
  3632.  
  3633.     //
  3634.     //    don't need to hang on to param blocks after we've gone away
  3635.     //
  3636.     UnholdMemory( &printerClassRecord, sizeof(struct usbPrinterPBStruct) );
  3637.  
  3638.     USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Ready for removal", 0);
  3639.     return kUSBNoErr;
  3640. }
  3641.  
  3642. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3643.     Name:        CFMInitialization
  3644.  
  3645.     Input Parameters:    
  3646.         initBlock
  3647.         
  3648.     Output Parameters:
  3649.         printerClassDriverFileSpec        set global
  3650.         
  3651.     Description:
  3652.         We use the code fragment initialization to get our filespec which 
  3653.         LoadResources will use to open our resource fork.
  3654.         
  3655.         A peculiarity of the USB 1.0 implementation is that does not lock the
  3656.         driver into physical memory. As a result a driver which does not call
  3657.         SetDriverClosureMemory on it's fragment will likely be paged in during
  3658.         interrupt time and a double bus-fault will occur. The solution for this
  3659.         is to have the USB Expert call SetDriverClosureMemory in a future release
  3660.         of the USB stack. In the meantime, we call it on ourselves to lock us into
  3661.         physical memory. When the USB stack is revved, one call to SetDriverClosureMemory
  3662.         (either this one or the Expert's) will be treated as a NOP.
  3663.  
  3664.  
  3665.  
  3666.  
  3667. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3668. OSErr
  3669. CFMInitialization( CFragInitBlock *initBlock )
  3670. {
  3671.     //
  3672.     //    get a reference to our file so that we can open up the resource fork later on
  3673.     //
  3674.     if ( CFragHasFileLocation( initBlock->fragLocator.where ) )
  3675.         printerClassDriverFileSpec = *(initBlock->fragLocator.u.onDisk.fileSpec);
  3676.  
  3677.     return noErr;
  3678.  
  3679. }
  3680.  
  3681. // eof
  3682.