v2.4.9.9 -> v2.4.9.10
[opensuse:kernel.git] / drivers / usb / storage / isd200.c
1 /* Transport & Protocol Driver for In-System Design, Inc. ISD200 ASIC
2  *
3  * First release
4  *
5  * Current development and maintenance by:
6  *   (c) 2000 In-System Design, Inc. (support@in-system.com)
7  *
8  * The ISD200 ASIC does not natively support ATA devices.  The chip
9  * does implement an interface, the ATA Command Block (ATACB) which provides
10  * a means of passing ATA commands and ATA register accesses to a device.
11  *
12  * This program is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU General Public License as published by the
14  * Free Software Foundation; either version 2, or (at your option) any
15  * later version.
16  *
17  * This program is distributed in the hope that it will be useful, but
18  * WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along
23  * with this program; if not, write to the Free Software Foundation, Inc.,
24  * 675 Mass Ave, Cambridge, MA 02139, USA.
25  *
26  * History:
27  *
28  *  2001-02-24: Removed lots of duplicate code and simplified the structure.
29  *              (bjorn@haxx.se)
30  */
31
32
33 /* Include files */
34
35 #include "transport.h"
36 #include "protocol.h"
37 #include "usb.h"
38 #include "debug.h"
39 #include "scsiglue.h"
40 #include "isd200.h"
41
42 #include <linux/sched.h>
43 #include <linux/errno.h>
44 #include <linux/slab.h>
45 #include <linux/hdreg.h>
46 #include <linux/ide.h>
47
48 /*
49  * Inquiry defines. Used to interpret data returned from target as result
50  * of inquiry command.
51  *
52  * DeviceType field
53  */
54
55 #define DIRECT_ACCESS_DEVICE            0x00    /* disks */
56
57 /* Timeout defines (in Seconds) */
58
59 #define ISD200_ENUM_BSY_TIMEOUT         35
60 #define ISD200_ENUM_DETECT_TIMEOUT      30
61 #define ISD200_DEFAULT_TIMEOUT          30
62
63 /* device flags */
64 #define DF_ATA_DEVICE               0x0001
65 #define DF_MEDIA_STATUS_ENABLED     0x0002
66 #define DF_REMOVABLE_MEDIA          0x0004
67
68 /* capability bit definitions */
69 #define CAPABILITY_DMA          0x01
70 #define CAPABILITY_LBA          0x02
71
72 /* command_setX bit definitions */
73 #define COMMANDSET_REMOVABLE    0x02
74 #define COMMANDSET_MEDIA_STATUS 0x10
75
76 /* ATA Vendor Specific defines */
77 #define ATA_ADDRESS_DEVHEAD_STD      0xa0
78 #define ATA_ADDRESS_DEVHEAD_LBA_MODE 0x40    
79 #define ATA_ADDRESS_DEVHEAD_SLAVE    0x10
80
81 /* Action Select bits */
82 #define ACTION_SELECT_0             0x01
83 #define ACTION_SELECT_1             0x02
84 #define ACTION_SELECT_2             0x04
85 #define ACTION_SELECT_3             0x08
86 #define ACTION_SELECT_4             0x10
87 #define ACTION_SELECT_5             0x20
88 #define ACTION_SELECT_6             0x40
89 #define ACTION_SELECT_7             0x80
90
91 /* ATA error definitions not in <linux/hdreg.h> */
92 #define ATA_ERROR_MEDIA_CHANGE       0x20
93
94 /* ATA command definitions not in <linux/hdreg.h> */
95 #define ATA_COMMAND_GET_MEDIA_STATUS        0xDA
96 #define ATA_COMMAND_MEDIA_EJECT             0xED
97
98 /* ATA drive control definitions */
99 #define ATA_DC_DISABLE_INTERRUPTS    0x02
100 #define ATA_DC_RESET_CONTROLLER      0x04
101 #define ATA_DC_REENABLE_CONTROLLER   0x00
102
103 /*
104  *  General purpose return codes
105  */ 
106
107 #define ISD200_ERROR                -1
108 #define ISD200_GOOD                 0
109
110 /*
111  * Transport return codes
112  */
113
114 #define ISD200_TRANSPORT_GOOD       0   /* Transport good, command good     */
115 #define ISD200_TRANSPORT_FAILED     1   /* Transport good, command failed   */
116 #define ISD200_TRANSPORT_ERROR      2   /* Transport bad (i.e. device dead) */
117 #define ISD200_TRANSPORT_ABORTED    3   /* Transport aborted                */
118 #define ISD200_TRANSPORT_SHORT      4   /* Transport short                  */
119
120 /* driver action codes */
121 #define ACTION_READ_STATUS      0
122 #define ACTION_RESET            1
123 #define ACTION_REENABLE         2
124 #define ACTION_SOFT_RESET       3
125 #define ACTION_ENUM             4
126 #define ACTION_IDENTIFY         5
127
128
129 /*
130  * ata_cdb struct
131  */
132
133
134 union ata_cdb {
135         struct {
136                 unsigned char SignatureByte0;
137                 unsigned char SignatureByte1;
138                 unsigned char ActionSelect;
139                 unsigned char RegisterSelect;
140                 unsigned char TransferBlockSize;
141                 unsigned char WriteData3F6;
142                 unsigned char WriteData1F1;
143                 unsigned char WriteData1F2;
144                 unsigned char WriteData1F3;
145                 unsigned char WriteData1F4;
146                 unsigned char WriteData1F5;
147                 unsigned char WriteData1F6;
148                 unsigned char WriteData1F7;
149                 unsigned char Reserved[3];
150         } generic;
151         
152         struct {
153                 unsigned char SignatureByte0;
154                 unsigned char SignatureByte1;
155                 unsigned char ReadRegisterAccessBit : 1;
156                 unsigned char NoDeviceSelectionBit : 1;
157                 unsigned char NoBSYPollBit : 1;
158                 unsigned char IgnorePhaseErrorBit : 1;
159                 unsigned char IgnoreDeviceErrorBit : 1;
160                 unsigned char Reserved0Bit : 3;
161                 unsigned char SelectAlternateStatus : 1;
162                 unsigned char SelectError : 1;
163                 unsigned char SelectSectorCount : 1;
164                 unsigned char SelectSectorNumber : 1;
165                 unsigned char SelectCylinderLow : 1;
166                 unsigned char SelectCylinderHigh : 1;
167                 unsigned char SelectDeviceHead : 1;
168                 unsigned char SelectStatus : 1;
169                 unsigned char TransferBlockSize;
170                 unsigned char AlternateStatusByte;
171                 unsigned char ErrorByte;
172                 unsigned char SectorCountByte;
173                 unsigned char SectorNumberByte;
174                 unsigned char CylinderLowByte;
175                 unsigned char CylinderHighByte;
176                 unsigned char DeviceHeadByte;
177                 unsigned char StatusByte;
178                 unsigned char Reserved[3];
179         } read;
180
181         struct {
182                 unsigned char SignatureByte0;
183                 unsigned char SignatureByte1;
184                 unsigned char ReadRegisterAccessBit : 1;
185                 unsigned char NoDeviceSelectionBit : 1;
186                 unsigned char NoBSYPollBit : 1;
187                 unsigned char IgnorePhaseErrorBit : 1;
188                 unsigned char IgnoreDeviceErrorBit : 1;
189                 unsigned char Reserved0Bit : 3;
190                 unsigned char SelectDeviceControl : 1;
191                 unsigned char SelectFeatures : 1;
192                 unsigned char SelectSectorCount : 1;
193                 unsigned char SelectSectorNumber : 1;
194                 unsigned char SelectCylinderLow : 1;
195                 unsigned char SelectCylinderHigh : 1;
196                 unsigned char SelectDeviceHead : 1;
197                 unsigned char SelectCommand : 1;
198                 unsigned char TransferBlockSize;
199                 unsigned char DeviceControlByte;
200                 unsigned char FeaturesByte;
201                 unsigned char SectorCountByte;
202                 unsigned char SectorNumberByte;
203                 unsigned char CylinderLowByte;
204                 unsigned char CylinderHighByte;
205                 unsigned char DeviceHeadByte;
206                 unsigned char CommandByte;
207                 unsigned char Reserved[3];
208         } write;
209 };
210
211
212 /*
213  * Inquiry data structure. This is the data returned from the target
214  * after it receives an inquiry.
215  *
216  * This structure may be extended by the number of bytes specified
217  * in the field AdditionalLength. The defined size constant only
218  * includes fields through ProductRevisionLevel.
219  */
220
221 struct inquiry_data {
222         unsigned char DeviceType : 5;
223         unsigned char DeviceTypeQualifier : 3;
224         unsigned char DeviceTypeModifier : 7;
225         unsigned char RemovableMedia : 1;
226         unsigned char Versions;
227         unsigned char ResponseDataFormat : 4;
228         unsigned char HiSupport : 1;
229         unsigned char NormACA : 1;
230         unsigned char ReservedBit : 1;
231         unsigned char AERC : 1;
232         unsigned char AdditionalLength;
233         unsigned char Reserved[2];
234         unsigned char SoftReset : 1;
235         unsigned char CommandQueue : 1;
236         unsigned char Reserved2 : 1;
237         unsigned char LinkedCommands : 1;
238         unsigned char Synchronous : 1;
239         unsigned char Wide16Bit : 1;
240         unsigned char Wide32Bit : 1;
241         unsigned char RelativeAddressing : 1;
242         unsigned char VendorId[8];
243         unsigned char ProductId[16];
244         unsigned char ProductRevisionLevel[4];
245         unsigned char VendorSpecific[20];
246         unsigned char Reserved3[40];
247 } __attribute__ ((packed));
248
249 /*
250  * INQUIRY data buffer size
251  */
252
253 #define INQUIRYDATABUFFERSIZE 36
254
255
256 /*
257  * ISD200 CONFIG data struct
258  */
259
260 struct isd200_config {
261         unsigned char EventNotification;
262         unsigned char ExternalClock;
263         unsigned char ATAInitTimeout;
264         unsigned char ATATiming : 4;
265         unsigned char ATAPIReset : 1;
266         unsigned char MasterSlaveSelection : 1;
267         unsigned char ATAPICommandBlockSize : 2;
268         unsigned char ATAMajorCommand;
269         unsigned char ATAMinorCommand;
270         unsigned char LastLUNIdentifier : 3;
271         unsigned char DescriptOverride : 1;
272         unsigned char ATA3StateSuspend : 1;
273         unsigned char SkipDeviceBoot : 1;
274         unsigned char ConfigDescriptor2 : 1;
275         unsigned char InitStatus : 1;
276         unsigned char SRSTEnable : 1;
277         unsigned char Reserved0 : 7;
278 };
279
280
281 /*
282  * ISD200 driver information struct
283  */
284
285 struct isd200_info {
286         struct inquiry_data InquiryData;
287         struct hd_driveid drive;
288         struct isd200_config ConfigData;
289         unsigned char ATARegs[8];
290         unsigned char DeviceHead;
291         unsigned char DeviceFlags;
292
293         /* maximum number of LUNs supported */
294         unsigned char MaxLUNs;
295 };
296
297
298 /*
299  * Read Capacity Data - returned in Big Endian format
300  */
301
302 struct read_capacity_data {
303         unsigned long LogicalBlockAddress;
304         unsigned long BytesPerBlock;
305 };
306
307 /*
308  * Read Block Limits Data - returned in Big Endian format
309  * This structure returns the maximum and minimum block
310  * size for a TAPE device.
311  */
312
313 struct read_block_limits {
314         unsigned char Reserved;
315         unsigned char BlockMaximumSize[3];
316         unsigned char BlockMinimumSize[2];
317 };
318
319
320 /*
321  * Sense Data Format
322  */
323
324 struct sense_data {
325         unsigned char ErrorCode:7;
326         unsigned char Valid:1;
327         unsigned char SegmentNumber;
328         unsigned char SenseKey:4;
329         unsigned char Reserved:1;
330         unsigned char IncorrectLength:1;
331         unsigned char EndOfMedia:1;
332         unsigned char FileMark:1;
333         unsigned char Information[4];
334         unsigned char AdditionalSenseLength;
335         unsigned char CommandSpecificInformation[4];
336         unsigned char AdditionalSenseCode;
337         unsigned char AdditionalSenseCodeQualifier;
338         unsigned char FieldReplaceableUnitCode;
339         unsigned char SenseKeySpecific[3];
340 } __attribute__ ((packed));
341
342 /*
343  * Default request sense buffer size
344  */
345
346 #define SENSE_BUFFER_SIZE 18
347
348 /***********************************************************************
349  * Helper routines
350  ***********************************************************************/
351
352
353 /**************************************************************************
354  * isd200_build_sense
355  *                                                                         
356  *  Builds an artificial sense buffer to report the results of a 
357  *  failed command.
358  *                                                                       
359  * RETURNS:
360  *    void
361  */                                                                        
362 void isd200_build_sense(struct us_data *us, Scsi_Cmnd *srb)
363 {
364         struct isd200_info *info = (struct isd200_info *)us->extra;
365         struct sense_data *buf = (struct sense_data *) &srb->sense_buffer[0];
366         unsigned char error = info->ATARegs[IDE_ERROR_OFFSET];
367
368         if(error & ATA_ERROR_MEDIA_CHANGE) {
369                 buf->ErrorCode = 0x70;
370                 buf->Valid     = 1;
371                 buf->AdditionalSenseLength = 0xb;
372                 buf->SenseKey =  UNIT_ATTENTION;
373                 buf->AdditionalSenseCode = 0;
374                 buf->AdditionalSenseCodeQualifier = 0;
375         } else if(error & MCR_ERR) {
376                 buf->ErrorCode = 0x70;
377                 buf->Valid     = 1;
378                 buf->AdditionalSenseLength = 0xb;
379                 buf->SenseKey =  UNIT_ATTENTION;
380                 buf->AdditionalSenseCode = 0;
381                 buf->AdditionalSenseCodeQualifier = 0;
382         } else if(error & TRK0_ERR) {
383                 buf->ErrorCode = 0x70;
384                 buf->Valid     = 1;
385                 buf->AdditionalSenseLength = 0xb;
386                 buf->SenseKey =  NOT_READY;
387                 buf->AdditionalSenseCode = 0;
388                 buf->AdditionalSenseCodeQualifier = 0;
389         } else if(error & ECC_ERR) {
390                 buf->ErrorCode = 0x70;
391                 buf->Valid     = 1;
392                 buf->AdditionalSenseLength = 0xb;
393                 buf->SenseKey =  DATA_PROTECT;
394                 buf->AdditionalSenseCode = 0;
395                 buf->AdditionalSenseCodeQualifier = 0;
396         } else {
397                 buf->ErrorCode = 0;
398                 buf->Valid     = 0;
399                 buf->AdditionalSenseLength = 0;
400                 buf->SenseKey =  0;
401                 buf->AdditionalSenseCode = 0;
402                 buf->AdditionalSenseCodeQualifier = 0;
403         }
404 }
405
406 /***********************************************************************
407  * Data transfer routines
408  ***********************************************************************/
409
410
411 /**************************************************************************
412  * Transfer one SCSI scatter-gather buffer via bulk transfer
413  *
414  * Note that this function is necessary because we want the ability to
415  * use scatter-gather memory.  Good performance is achieved by a combination
416  * of scatter-gather and clustering (which makes each chunk bigger).
417  *
418  * Note that the lower layer will always retry when a NAK occurs, up to the
419  * timeout limit.  Thus we don't have to worry about it for individual
420  * packets.
421  */
422 static int isd200_transfer_partial( struct us_data *us, 
423                                     unsigned char dataDirection,
424                                     char *buf, int length )
425 {
426         int result;
427         int partial;
428         int pipe;
429
430         /* calculate the appropriate pipe information */
431         if (dataDirection == SCSI_DATA_READ)
432                 pipe = usb_rcvbulkpipe(us->pusb_dev, us->ep_in);
433         else
434                 pipe = usb_sndbulkpipe(us->pusb_dev, us->ep_out);
435
436         /* transfer the data */
437         US_DEBUGP("isd200_transfer_partial(): xfer %d bytes\n", length);
438         result = usb_stor_bulk_msg(us, buf, pipe, length, &partial);
439         US_DEBUGP("usb_stor_bulk_msg() returned %d xferred %d/%d\n",
440                   result, partial, length);
441
442         /* if we stall, we need to clear it before we go on */
443         if (result == -EPIPE) {
444                 US_DEBUGP("clearing endpoint halt for pipe 0x%x\n", pipe);
445                 usb_stor_clear_halt(us->pusb_dev, pipe);
446         }
447     
448         /* did we send all the data? */
449         if (partial == length) {
450                 US_DEBUGP("isd200_transfer_partial(): transfer complete\n");
451                 return ISD200_TRANSPORT_GOOD;
452         }
453
454         /* uh oh... we have an error code, so something went wrong. */
455         if (result) {
456                 /* NAK - that means we've retried a few times already */
457                 if (result == -ETIMEDOUT) {
458                         US_DEBUGP("isd200_transfer_partial(): device NAKed\n");
459                         return ISD200_TRANSPORT_FAILED;
460                 }
461
462                 /* -ENOENT -- we canceled this transfer */
463                 if (result == -ENOENT) {
464                         US_DEBUGP("isd200_transfer_partial(): transfer aborted\n");
465                         return ISD200_TRANSPORT_ABORTED;
466                 }
467
468                 /* the catch-all case */
469                 US_DEBUGP("isd200_transfer_partial(): unknown error\n");
470                 return ISD200_TRANSPORT_FAILED;
471         }
472
473         /* no error code, so we must have transferred some data, 
474          * just not all of it */
475         return ISD200_TRANSPORT_SHORT;
476 }
477
478
479 /**************************************************************************
480  * Transfer an entire SCSI command's worth of data payload over the bulk
481  * pipe.
482  *
483  * Note that this uses us_transfer_partial to achieve it's goals -- this
484  * function simply determines if we're going to use scatter-gather or not,
485  * and acts appropriately.  For now, it also re-interprets the error codes.
486  */
487 static void isd200_transfer( struct us_data *us, Scsi_Cmnd *srb )
488 {
489         int i;
490         int result = -1;
491         struct scatterlist *sg;
492         unsigned int total_transferred = 0;
493         unsigned int transfer_amount;
494
495         /* calculate how much we want to transfer */
496         int dir = srb->sc_data_direction;
497         srb->sc_data_direction = SCSI_DATA_WRITE;
498         transfer_amount = usb_stor_transfer_length(srb);
499         srb->sc_data_direction = dir;
500
501         /* was someone foolish enough to request more data than available
502          * buffer space? */
503         if (transfer_amount > srb->request_bufflen)
504                 transfer_amount = srb->request_bufflen;
505
506         /* are we scatter-gathering? */
507         if (srb->use_sg) {
508
509                 /* loop over all the scatter gather structures and 
510                  * make the appropriate requests for each, until done
511                  */
512                 sg = (struct scatterlist *) srb->request_buffer;
513                 for (i = 0; i < srb->use_sg; i++) {
514
515                         /* transfer the lesser of the next buffer or the
516                          * remaining data */
517                         if (transfer_amount - total_transferred >= 
518                             sg[i].length) {
519                                 result = isd200_transfer_partial(us, 
520                                                                  srb->sc_data_direction,
521                                                                  sg[i].address, 
522                                                                  sg[i].length);
523                                 total_transferred += sg[i].length;
524                         } else
525                                 result = isd200_transfer_partial(us, 
526                                                                  srb->sc_data_direction,                            
527                                                                  sg[i].address,
528                                                                  transfer_amount - total_transferred);
529
530                         /* if we get an error, end the loop here */
531                         if (result)
532                                 break;
533                 }
534         }
535         else
536                 /* no scatter-gather, just make the request */
537                 result = isd200_transfer_partial(us, 
538                                                  srb->sc_data_direction,
539                                                  srb->request_buffer, 
540                                                  transfer_amount);
541
542         /* return the result in the data structure itself */
543         srb->result = result;
544 }
545
546
547 /***********************************************************************
548  * Transport routines
549  ***********************************************************************/
550
551
552 /**************************************************************************
553  *  ISD200 Bulk Transport
554  *
555  * Note:  This routine was copied from the usb_stor_Bulk_transport routine
556  * located in the transport.c source file.  The scsi command is limited to
557  * only 12 bytes while the CDB for the ISD200 must be 16 bytes.
558  */
559 int isd200_Bulk_transport( struct us_data *us, Scsi_Cmnd *srb, 
560                            union ata_cdb *AtaCdb, unsigned char AtaCdbLength )
561 {
562         struct bulk_cb_wrap bcb;
563         struct bulk_cs_wrap bcs;
564         int result;
565         int pipe;
566         int partial;
567         unsigned int transfer_amount;
568
569         int dir = srb->sc_data_direction;
570         srb->sc_data_direction = SCSI_DATA_WRITE;
571         transfer_amount = usb_stor_transfer_length(srb);
572         srb->sc_data_direction = dir;
573     
574         /* set up the command wrapper */
575         bcb.Signature = cpu_to_le32(US_BULK_CB_SIGN);
576         bcb.DataTransferLength = cpu_to_le32(transfer_amount);
577         bcb.Flags = srb->sc_data_direction == SCSI_DATA_READ ? 1 << 7 : 0;
578         bcb.Tag = srb->serial_number;
579         bcb.Lun = srb->cmnd[1] >> 5;
580         if (us->flags & US_FL_SCM_MULT_TARG)
581                 bcb.Lun |= srb->target << 4;
582
583         bcb.Length = AtaCdbLength;
584     
585         /* construct the pipe handle */
586         pipe = usb_sndbulkpipe(us->pusb_dev, us->ep_out);
587     
588         /* copy the command payload */
589         memset(bcb.CDB, 0, sizeof(bcb.CDB));
590         memcpy(bcb.CDB, AtaCdb, bcb.Length);
591     
592         /* send it to out endpoint */
593         US_DEBUGP("Bulk command S 0x%x T 0x%x Trg %d LUN %d L %d F %d CL %d\n",
594                   le32_to_cpu(bcb.Signature), bcb.Tag,
595                   (bcb.Lun >> 4), (bcb.Lun & 0xFF), 
596                   bcb.DataTransferLength, bcb.Flags, bcb.Length);
597         result = usb_stor_bulk_msg(us, &bcb, pipe, US_BULK_CB_WRAP_LEN, 
598                                    &partial);
599         US_DEBUGP("Bulk command transfer result=%d\n", result);
600     
601         if (result == -ENOENT)
602                 return ISD200_TRANSPORT_ABORTED;
603         else if (result == -EPIPE) {
604                 /* if we stall, we need to clear it before we go on */
605                 US_DEBUGP("clearing endpoint halt for pipe 0x%x\n", pipe);
606                 usb_stor_clear_halt(us->pusb_dev, pipe);
607         } else if (result)  
608                 return ISD200_TRANSPORT_ERROR;
609     
610         /* if the command transfered well, then we go to the data stage */
611         if (!result && bcb.DataTransferLength) {
612                 isd200_transfer(us, srb);
613                 US_DEBUGP("Bulk data transfer result 0x%x\n", srb->result);
614                 
615                 if (srb->result == ISD200_TRANSPORT_ABORTED)
616                         return ISD200_TRANSPORT_ABORTED;
617         }
618     
619         /* See flow chart on pg 15 of the Bulk Only Transport spec for
620          * an explanation of how this code works.
621          */
622     
623         /* construct the pipe handle */
624         pipe = usb_rcvbulkpipe(us->pusb_dev, us->ep_in);
625     
626         /* get CSW for device status */
627         US_DEBUGP("Attempting to get CSW...\n");
628         result = usb_stor_bulk_msg(us, &bcs, pipe, US_BULK_CS_WRAP_LEN, 
629                                    &partial);
630         if (result == -ENOENT)
631                 return ISD200_TRANSPORT_ABORTED;
632
633         /* did the attempt to read the CSW fail? */
634         if (result == -EPIPE) {
635                 US_DEBUGP("clearing endpoint halt for pipe 0x%x\n", pipe);
636                 usb_stor_clear_halt(us->pusb_dev, pipe);
637            
638                 /* get the status again */
639                 US_DEBUGP("Attempting to get CSW (2nd try)...\n");
640                 result = usb_stor_bulk_msg(us, &bcs, pipe,
641                                            US_BULK_CS_WRAP_LEN, &partial);
642
643                 /* if the command was aborted, indicate that */
644                 if (result == -ENOENT)
645                         return ISD200_TRANSPORT_ABORTED;
646         
647                 /* if it fails again, we need a reset and return an error*/
648                 if (result == -EPIPE) {
649                         US_DEBUGP("clearing halt for pipe 0x%x\n", pipe);
650                         usb_stor_clear_halt(us->pusb_dev, pipe);
651                         return ISD200_TRANSPORT_ERROR;
652                 }
653         }
654     
655         /* if we still have a failure at this point, we're in trouble */
656         US_DEBUGP("Bulk status result = %d\n", result);
657         if (result)
658                 return ISD200_TRANSPORT_ERROR;
659     
660         /* check bulk status */
661         US_DEBUGP("Bulk status Sig 0x%x T 0x%x R %d Stat 0x%x\n",
662                   le32_to_cpu(bcs.Signature), bcs.Tag, 
663                   bcs.Residue, bcs.Status);
664         if (bcs.Signature != cpu_to_le32(US_BULK_CS_SIGN) || 
665             bcs.Tag != bcb.Tag || 
666             bcs.Status > US_BULK_STAT_PHASE || partial != 13) {
667                 US_DEBUGP("Bulk logical error\n");
668                 return ISD200_TRANSPORT_ERROR;
669         }
670     
671         /* based on the status code, we report good or bad */
672         switch (bcs.Status) {
673         case US_BULK_STAT_OK:
674                 /* command good -- note that we could be short on data */
675                 return ISD200_TRANSPORT_GOOD;
676
677         case US_BULK_STAT_FAIL:
678                 /* command failed */
679                 return ISD200_TRANSPORT_FAILED;
680         
681         case US_BULK_STAT_PHASE:
682                 /* phase error */
683                 usb_stor_Bulk_reset(us);
684                 return ISD200_TRANSPORT_ERROR;
685         }
686     
687         /* we should never get here, but if we do, we're in trouble */
688         return ISD200_TRANSPORT_ERROR;
689 }
690
691
692 /**************************************************************************
693  *  isd200_action
694  *
695  * Routine for sending commands to the isd200
696  *
697  * RETURNS:
698  *    ISD status code
699  */
700 static int isd200_action( struct us_data *us, int action, 
701                           void* pointer, int value )
702 {
703         union ata_cdb ata;
704         struct scsi_cmnd srb;
705         struct isd200_info *info = (struct isd200_info *)us->extra;
706         int status;
707
708         memset(&ata, 0, sizeof(ata));
709         memset(&srb, 0, sizeof(srb));
710
711         ata.generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
712         ata.generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
713         ata.generic.TransferBlockSize = 1;
714
715         switch ( action ) {
716         case ACTION_READ_STATUS:
717                 US_DEBUGP("   isd200_action(READ_STATUS)\n");
718                 ata.generic.ActionSelect = ACTION_SELECT_0|ACTION_SELECT_2;
719                 ata.read.SelectStatus = 1;
720                 ata.read.SelectError = 1;
721                 ata.read.SelectCylinderHigh = 1;
722                 ata.read.SelectCylinderLow = 1;
723                 srb.sc_data_direction = SCSI_DATA_READ;
724                 srb.request_buffer = pointer;
725                 srb.request_bufflen = value;
726                 break;
727
728         case ACTION_ENUM:
729                 US_DEBUGP("   isd200_action(ENUM,0x%02x)\n",value);
730                 ata.generic.ActionSelect = ACTION_SELECT_1|ACTION_SELECT_2|
731                                            ACTION_SELECT_3|ACTION_SELECT_4|
732                                            ACTION_SELECT_5;
733                 ata.write.SelectDeviceHead = 1;
734                 ata.write.DeviceHeadByte = value;
735                 srb.sc_data_direction = SCSI_DATA_NONE;
736                 break;
737
738         case ACTION_RESET:
739                 US_DEBUGP("   isd200_action(RESET)\n");
740                 ata.generic.ActionSelect = ACTION_SELECT_1|ACTION_SELECT_2|
741                                            ACTION_SELECT_3|ACTION_SELECT_4;
742                 ata.write.SelectDeviceControl = 1;
743                 ata.write.DeviceControlByte = ATA_DC_RESET_CONTROLLER;
744                 srb.sc_data_direction = SCSI_DATA_NONE;
745                 break;
746
747         case ACTION_REENABLE:
748                 US_DEBUGP("   isd200_action(REENABLE)\n");
749                 ata.generic.ActionSelect = ACTION_SELECT_1|ACTION_SELECT_2|
750                                            ACTION_SELECT_3|ACTION_SELECT_4;
751                 ata.write.SelectDeviceControl = 1;
752                 ata.write.DeviceControlByte = ATA_DC_REENABLE_CONTROLLER;
753                 srb.sc_data_direction = SCSI_DATA_NONE;
754                 break;
755
756         case ACTION_SOFT_RESET:
757                 US_DEBUGP("   isd200_action(SOFT_RESET)\n");
758                 ata.generic.ActionSelect = ACTION_SELECT_1|ACTION_SELECT_5;
759                 ata.write.SelectDeviceHead = 1;
760                 ata.write.DeviceHeadByte = info->DeviceHead;
761                 ata.write.SelectCommand = 1;
762                 ata.write.CommandByte = WIN_SRST;
763                 srb.sc_data_direction = SCSI_DATA_NONE;
764                 break;
765
766         case ACTION_IDENTIFY:
767                 US_DEBUGP("   isd200_action(IDENTIFY)\n");
768                 ata.write.SelectCommand = 1;
769                 ata.write.CommandByte = WIN_IDENTIFY;
770                 srb.sc_data_direction = SCSI_DATA_READ;
771                 srb.request_buffer = (void *)&info->drive;
772                 srb.request_bufflen = sizeof(struct hd_driveid);
773                 break;
774
775         default:
776                 US_DEBUGP("Error: Undefined action %d\n",action);
777                 break;
778         }
779
780         status = isd200_Bulk_transport(us, &srb, &ata, sizeof(ata.generic));
781         if (status != ISD200_TRANSPORT_GOOD) {
782                 US_DEBUGP("   isd200_action(0x%02x) error: %d\n",action,status);
783                 status = ISD200_ERROR;
784                 /* need to reset device here */
785         }
786
787         return status;
788 }
789
790 /**************************************************************************
791  * isd200_read_regs
792  *                                                                         
793  * Read ATA Registers
794  *
795  * RETURNS:
796  *    ISD status code
797  */                                                                        
798 int isd200_read_regs( struct us_data *us )
799 {
800         struct isd200_info *info = (struct isd200_info *)us->extra;
801         int retStatus = ISD200_GOOD;
802         int transferStatus;
803
804         US_DEBUGP("Entering isd200_IssueATAReadRegs\n");
805
806         transferStatus = isd200_action( us, ACTION_READ_STATUS,
807                                     info->ATARegs, sizeof(info->ATARegs) );
808         if (transferStatus != ISD200_TRANSPORT_GOOD) {
809                 US_DEBUGP("   Error reading ATA registers\n");
810                 retStatus = ISD200_ERROR;
811         } else {
812                 US_DEBUGP("   Got ATA Register[IDE_ERROR_OFFSET] = 0x%x\n", 
813                           info->ATARegs[IDE_ERROR_OFFSET]);
814         }
815
816         return retStatus;
817 }
818
819
820 /**************************************************************************
821  * Invoke the transport and basic error-handling/recovery methods
822  *
823  * This is used by the protocol layers to actually send the message to
824  * the device and recieve the response.
825  */
826 void isd200_invoke_transport( struct us_data *us, 
827                               Scsi_Cmnd *srb, 
828                               union ata_cdb *ataCdb )
829 {
830         int need_auto_sense = 0;
831         int transferStatus;
832
833         /* send the command to the transport layer */
834         transferStatus = isd200_Bulk_transport(us, srb, ataCdb,
835                                                sizeof(ataCdb->generic));
836         switch (transferStatus) {
837
838         case ISD200_TRANSPORT_GOOD:
839                 /* Indicate a good result */
840                 srb->result = GOOD;
841                 break;
842
843         case ISD200_TRANSPORT_ABORTED:
844                 /* if the command gets aborted by the higher layers, we need to
845                  * short-circuit all other processing
846                  */
847                 US_DEBUGP("-- transport indicates command was aborted\n");
848                 srb->result = DID_ABORT << 16;
849                 break;
850
851         case ISD200_TRANSPORT_FAILED:
852                 US_DEBUGP("-- transport indicates command failure\n");
853                 need_auto_sense = 1;
854                 break;
855
856         case ISD200_TRANSPORT_ERROR:
857                 US_DEBUGP("-- transport indicates transport failure\n");
858                 srb->result = DID_ERROR << 16;
859                 break;
860
861         case ISD200_TRANSPORT_SHORT:
862                 if (!((srb->cmnd[0] == REQUEST_SENSE) ||
863                       (srb->cmnd[0] == INQUIRY) ||
864                       (srb->cmnd[0] == MODE_SENSE) ||
865                       (srb->cmnd[0] == LOG_SENSE) ||
866                       (srb->cmnd[0] == MODE_SENSE_10))) {
867                         US_DEBUGP("-- unexpectedly short transfer\n");
868                         need_auto_sense = 1;
869                 }
870                 break;
871     
872         default:
873                 US_DEBUGP("-- transport indicates unknown failure\n");   
874                 srb->result = DID_ERROR << 16;
875        
876         }
877
878         if (need_auto_sense)
879                 if (isd200_read_regs(us) == ISD200_GOOD)
880                         isd200_build_sense(us, srb);
881
882         /* Regardless of auto-sense, if we _know_ we have an error
883          * condition, show that in the result code
884          */
885         if (transferStatus == ISD200_TRANSPORT_FAILED)
886                 srb->result = CHECK_CONDITION;
887 }
888
889
890 /**************************************************************************
891  * isd200_write_config
892  *                                                                         
893  * Write the ISD200 Configuraton data
894  *
895  * RETURNS:
896  *    ISD status code
897  */                                                                        
898 int isd200_write_config( struct us_data *us ) 
899 {
900         struct isd200_info *info = (struct isd200_info *)us->extra;
901         int retStatus = ISD200_GOOD;
902         int result;
903
904
905         US_DEBUGP("Entering isd200_write_config\n");
906
907         US_DEBUGP("   Writing the following ISD200 Config Data:\n");
908         US_DEBUGP("      Event Notification: 0x%x\n", info->ConfigData.EventNotification);
909         US_DEBUGP("      External Clock: 0x%x\n", info->ConfigData.ExternalClock);
910         US_DEBUGP("      ATA Init Timeout: 0x%x\n", info->ConfigData.ATAInitTimeout);
911         US_DEBUGP("      ATAPI Command Block Size: 0x%x\n", info->ConfigData.ATAPICommandBlockSize);
912         US_DEBUGP("      Master/Slave Selection: 0x%x\n", info->ConfigData.MasterSlaveSelection);
913         US_DEBUGP("      ATAPI Reset: 0x%x\n", info->ConfigData.ATAPIReset);
914         US_DEBUGP("      ATA Timing: 0x%x\n", info->ConfigData.ATATiming);
915         US_DEBUGP("      ATA Major Command: 0x%x\n", info->ConfigData.ATAMajorCommand);
916         US_DEBUGP("      ATA Minor Command: 0x%x\n", info->ConfigData.ATAMinorCommand);
917         US_DEBUGP("      Init Status: 0x%x\n", info->ConfigData.InitStatus);
918         US_DEBUGP("      Config Descriptor 2: 0x%x\n", info->ConfigData.ConfigDescriptor2);
919         US_DEBUGP("      Skip Device Boot: 0x%x\n", info->ConfigData.SkipDeviceBoot);
920         US_DEBUGP("      ATA 3 State Supsend: 0x%x\n", info->ConfigData.ATA3StateSuspend);
921         US_DEBUGP("      Descriptor Override: 0x%x\n", info->ConfigData.DescriptOverride);
922         US_DEBUGP("      Last LUN Identifier: 0x%x\n", info->ConfigData.LastLUNIdentifier);
923         US_DEBUGP("      SRST Enable: 0x%x\n", info->ConfigData.SRSTEnable);
924
925         /* let's send the command via the control pipe */
926         result = usb_stor_control_msg(
927                 us, 
928                 usb_sndctrlpipe(us->pusb_dev,0),
929                 0x01, 
930                 USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
931                 0x0000, 
932                 0x0002, 
933                 (void *) &info->ConfigData, 
934                 sizeof(info->ConfigData));
935
936         if (result >= 0) {
937                 US_DEBUGP("   ISD200 Config Data was written successfully\n");
938         } else {
939                 US_DEBUGP("   Request to write ISD200 Config Data failed!\n");
940
941                 /* STALL must be cleared when they are detected */
942                 if (result == -EPIPE) {
943                         US_DEBUGP("-- Stall on control pipe. Clearing\n");
944                         result = usb_stor_clear_halt(us->pusb_dev,
945                                                      usb_sndctrlpipe(us->pusb_dev, 0));
946                         US_DEBUGP("-- usb_stor_clear_halt() returns %d\n", result);
947
948                 }
949                 retStatus = ISD200_ERROR;
950         }
951
952         US_DEBUGP("Leaving isd200_write_config %08X\n", retStatus);
953         return retStatus;
954 }
955
956
957 /**************************************************************************
958  * isd200_read_config
959  *                                                                         
960  * Reads the ISD200 Configuraton data
961  *
962  * RETURNS:
963  *    ISD status code
964  */                                                                        
965 int isd200_read_config( struct us_data *us ) 
966 {
967         struct isd200_info *info = (struct isd200_info *)us->extra;
968         int retStatus = ISD200_GOOD;
969         int result;
970
971         US_DEBUGP("Entering isd200_read_config\n");
972
973         /* read the configuration information from ISD200.  Use this to */
974         /* determine what the special ATA CDB bytes are.                */
975
976         result = usb_stor_control_msg(
977                 us, 
978                 usb_rcvctrlpipe(us->pusb_dev,0),
979                 0x02, 
980                 USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
981                 0x0000, 
982                 0x0002, 
983                 (void *) &info->ConfigData, 
984                 sizeof(info->ConfigData));
985
986
987         if (result >= 0) {
988                 US_DEBUGP("   Retrieved the following ISD200 Config Data:\n");
989                 US_DEBUGP("      Event Notification: 0x%x\n", info->ConfigData.EventNotification);
990                 US_DEBUGP("      External Clock: 0x%x\n", info->ConfigData.ExternalClock);
991                 US_DEBUGP("      ATA Init Timeout: 0x%x\n", info->ConfigData.ATAInitTimeout);
992                 US_DEBUGP("      ATAPI Command Block Size: 0x%x\n", info->ConfigData.ATAPICommandBlockSize);
993                 US_DEBUGP("      Master/Slave Selection: 0x%x\n", info->ConfigData.MasterSlaveSelection);
994                 US_DEBUGP("      ATAPI Reset: 0x%x\n", info->ConfigData.ATAPIReset);
995                 US_DEBUGP("      ATA Timing: 0x%x\n", info->ConfigData.ATATiming);
996                 US_DEBUGP("      ATA Major Command: 0x%x\n", info->ConfigData.ATAMajorCommand);
997                 US_DEBUGP("      ATA Minor Command: 0x%x\n", info->ConfigData.ATAMinorCommand);
998                 US_DEBUGP("      Init Status: 0x%x\n", info->ConfigData.InitStatus);
999                 US_DEBUGP("      Config Descriptor 2: 0x%x\n", info->ConfigData.ConfigDescriptor2);
1000                 US_DEBUGP("      Skip Device Boot: 0x%x\n", info->ConfigData.SkipDeviceBoot);
1001                 US_DEBUGP("      ATA 3 State Supsend: 0x%x\n", info->ConfigData.ATA3StateSuspend);
1002                 US_DEBUGP("      Descriptor Override: 0x%x\n", info->ConfigData.DescriptOverride);
1003                 US_DEBUGP("      Last LUN Identifier: 0x%x\n", info->ConfigData.LastLUNIdentifier);
1004                 US_DEBUGP("      SRST Enable: 0x%x\n", info->ConfigData.SRSTEnable);
1005         } else {
1006                 US_DEBUGP("   Request to get ISD200 Config Data failed!\n");
1007
1008                 /* STALL must be cleared when they are detected */
1009                 if (result == -EPIPE) {
1010                         US_DEBUGP("-- Stall on control pipe. Clearing\n");
1011                         result = usb_stor_clear_halt(us->pusb_dev,   
1012                                                      usb_sndctrlpipe(us->pusb_dev, 0));
1013                         US_DEBUGP("-- usb_stor_clear_halt() returns %d\n", result);
1014
1015                 }
1016                 retStatus = ISD200_ERROR;
1017         }
1018
1019         US_DEBUGP("Leaving isd200_read_config %08X\n", retStatus);
1020         return retStatus;
1021 }
1022
1023
1024 /**************************************************************************
1025  * isd200_atapi_soft_reset
1026  *                                                                         
1027  * Perform an Atapi Soft Reset on the device
1028  *
1029  * RETURNS:
1030  *    NT status code
1031  */                                                                        
1032 int isd200_atapi_soft_reset( struct us_data *us ) 
1033 {
1034         int retStatus = ISD200_GOOD;
1035         int transferStatus;
1036
1037         US_DEBUGP("Entering isd200_atapi_soft_reset\n");
1038
1039         transferStatus = isd200_action( us, ACTION_SOFT_RESET, NULL, 0 );
1040         if (transferStatus != ISD200_TRANSPORT_GOOD) {
1041                 US_DEBUGP("   Error issuing Atapi Soft Reset\n");
1042                 retStatus = ISD200_ERROR;
1043         }
1044
1045         US_DEBUGP("Leaving isd200_atapi_soft_reset %08X\n", retStatus);
1046         return retStatus;
1047 }
1048
1049
1050 /**************************************************************************
1051  * isd200_srst
1052  *                                                                         
1053  * Perform an SRST on the device
1054  *
1055  * RETURNS:
1056  *    ISD status code
1057  */                                                                        
1058 int isd200_srst( struct us_data *us ) 
1059 {
1060         int retStatus = ISD200_GOOD;
1061         int transferStatus;
1062
1063         US_DEBUGP("Entering isd200_SRST\n");
1064
1065         transferStatus = isd200_action( us, ACTION_RESET, NULL, 0 );
1066
1067         /* check to see if this request failed */
1068         if (transferStatus != ISD200_TRANSPORT_GOOD) {
1069                 US_DEBUGP("   Error issuing SRST\n");
1070                 retStatus = ISD200_ERROR;
1071         } else {
1072                 /* delay 10ms to give the drive a chance to see it */
1073                 wait_ms(10);
1074
1075                 transferStatus = isd200_action( us, ACTION_REENABLE, NULL, 0 );
1076                 if (transferStatus != ISD200_TRANSPORT_GOOD) {
1077                         US_DEBUGP("   Error taking drive out of reset\n");
1078                         retStatus = ISD200_ERROR;
1079                 } else {
1080                         /* delay 50ms to give the drive a chance to recover after SRST */
1081                         wait_ms(50);
1082                 }
1083         }
1084
1085         US_DEBUGP("Leaving isd200_srst %08X\n", retStatus);
1086         return retStatus;
1087 }
1088
1089
1090 /**************************************************************************
1091  * isd200_try_enum
1092  *                                                                         
1093  * Helper function for isd200_manual_enum(). Does ENUM and READ_STATUS
1094  * and tries to analyze the status registers
1095  *
1096  * RETURNS:
1097  *    ISD status code
1098  */                                                                        
1099 static int isd200_try_enum(struct us_data *us, unsigned char master_slave,
1100                            int detect )
1101 {
1102         int status = ISD200_GOOD;
1103         unsigned char regs[8];
1104         unsigned long endTime;
1105         struct isd200_info *info = (struct isd200_info *)us->extra;
1106         int recheckAsMaster = FALSE;
1107
1108         if ( detect )
1109                 endTime = jiffies + ISD200_ENUM_DETECT_TIMEOUT * HZ;
1110         else
1111                 endTime = jiffies + ISD200_ENUM_BSY_TIMEOUT * HZ;
1112
1113         /* loop until we detect !BSY or timeout */
1114         while(TRUE) {
1115                 char* mstr = master_slave == ATA_ADDRESS_DEVHEAD_STD ?
1116                         "Master" : "Slave";
1117
1118                 status = isd200_action( us, ACTION_ENUM, NULL, master_slave );
1119                 if ( status != ISD200_GOOD )
1120                         break;
1121
1122                 status = isd200_action( us, ACTION_READ_STATUS, 
1123                                         regs, sizeof(regs) );
1124                 if ( status != ISD200_GOOD )
1125                         break;
1126
1127                 if (!detect) {
1128                         if (regs[IDE_STATUS_OFFSET] & BUSY_STAT ) {
1129                                 US_DEBUGP("   %s status is still BSY, try again...\n",mstr);
1130                         } else {
1131                                 US_DEBUGP("   %s status !BSY, continue with next operation\n",mstr);
1132                                 break;
1133                         }
1134                 }
1135                 /* check for BUSY_STAT and */
1136                 /* WRERR_STAT (workaround ATA Zip drive) and */ 
1137                 /* ERR_STAT (workaround for Archos CD-ROM) */
1138                 else if (regs[IDE_STATUS_OFFSET] & 
1139                          (BUSY_STAT | WRERR_STAT | ERR_STAT )) {
1140                         US_DEBUGP("   Status indicates it is not ready, try again...\n");
1141                 }
1142                 /* check for DRDY, ATA devices set DRDY after SRST */
1143                 else if (regs[IDE_STATUS_OFFSET] & READY_STAT) {
1144                         US_DEBUGP("   Identified ATA device\n");
1145                         info->DeviceFlags |= DF_ATA_DEVICE;
1146                         info->DeviceHead = master_slave;
1147                         break;
1148                 } 
1149                 /* check Cylinder High/Low to
1150                    determine if it is an ATAPI device
1151                 */
1152                 else if ((regs[IDE_HCYL_OFFSET] == 0xEB) &&
1153                          (regs[IDE_LCYL_OFFSET] == 0x14)) {
1154                         /* It seems that the RICOH 
1155                            MP6200A CD/RW drive will 
1156                            report itself okay as a
1157                            slave when it is really a
1158                            master. So this check again
1159                            as a master device just to
1160                            make sure it doesn't report
1161                            itself okay as a master also
1162                         */
1163                         if ((master_slave & ATA_ADDRESS_DEVHEAD_SLAVE) &&
1164                             (recheckAsMaster == FALSE)) {
1165                                 US_DEBUGP("   Identified ATAPI device as slave.  Rechecking again as master\n");
1166                                 recheckAsMaster = TRUE;
1167                                 master_slave = ATA_ADDRESS_DEVHEAD_STD;
1168                         } else {
1169                                 US_DEBUGP("   Identified ATAPI device\n");
1170                                 info->DeviceHead = master_slave;
1171                               
1172                                 status = isd200_atapi_soft_reset(us);
1173                                 break;
1174                         }
1175                 } else {
1176                         US_DEBUGP("   Not ATA, not ATAPI. Weird.\n");
1177                 }
1178
1179                 /* check for timeout on this request */
1180                 if (jiffies >= endTime) {
1181                         if (!detect)
1182                                 US_DEBUGP("   BSY check timeout, just continue with next operation...\n");
1183                         else
1184                                 US_DEBUGP("   Device detect timeout!\n");
1185                         break;
1186                 }
1187         }
1188
1189         return status;
1190 }
1191
1192 /**************************************************************************
1193  * isd200_manual_enum
1194  *                                                                         
1195  * Determines if the drive attached is an ATA or ATAPI and if it is a
1196  * master or slave.
1197  *
1198  * RETURNS:
1199  *    ISD status code
1200  */                                                                        
1201 int isd200_manual_enum(struct us_data *us)
1202 {
1203         struct isd200_info *info = (struct isd200_info *)us->extra;
1204         int retStatus = ISD200_GOOD;
1205
1206         US_DEBUGP("Entering isd200_manual_enum\n");
1207
1208         retStatus = isd200_read_config(us);
1209         if (retStatus == ISD200_GOOD) {
1210                 int isslave;
1211                 /* master or slave? */
1212                 retStatus = isd200_try_enum( us, ATA_ADDRESS_DEVHEAD_STD, FALSE );
1213                 if (retStatus == ISD200_GOOD)
1214                         retStatus = isd200_try_enum( us, ATA_ADDRESS_DEVHEAD_SLAVE, FALSE );
1215
1216                 if (retStatus == ISD200_GOOD) {
1217                         retStatus = isd200_srst(us);
1218                         if (retStatus == ISD200_GOOD)
1219                                 /* ata or atapi? */
1220                                 retStatus = isd200_try_enum( us, ATA_ADDRESS_DEVHEAD_STD, TRUE );
1221                 }
1222
1223                 isslave = (info->DeviceHead & ATA_ADDRESS_DEVHEAD_SLAVE) ? 1 : 0;
1224                 if (info->ConfigData.MasterSlaveSelection != isslave) {
1225                         US_DEBUGP("   Setting Master/Slave selection to %d\n", isslave);
1226                         info->ConfigData.MasterSlaveSelection = isslave;
1227                         retStatus = isd200_write_config(us);
1228                 }
1229         }
1230
1231         US_DEBUGP("Leaving isd200_manual_enum %08X\n", retStatus);
1232         return(retStatus);
1233 }
1234
1235
1236 /**************************************************************************
1237  * isd200_get_inquiry_data
1238  *
1239  * Get inquiry data
1240  *
1241  * RETURNS:
1242  *    ISD status code
1243  */
1244 int isd200_get_inquiry_data( struct us_data *us )
1245 {
1246         struct isd200_info *info = (struct isd200_info *)us->extra;
1247         int retStatus = ISD200_GOOD;
1248
1249         US_DEBUGP("Entering isd200_get_inquiry_data\n");
1250
1251         /* set default to Master */
1252         info->DeviceHead = ATA_ADDRESS_DEVHEAD_STD;
1253
1254         /* attempt to manually enumerate this device */
1255         retStatus = isd200_manual_enum(us);
1256         if (retStatus == ISD200_GOOD) {
1257                 int transferStatus;
1258
1259                 /* check for an ATA device */
1260                 if (info->DeviceFlags & DF_ATA_DEVICE) {
1261                         /* this must be an ATA device */
1262                         /* perform an ATA Commmand Identify */
1263                         transferStatus = isd200_action( us, ACTION_IDENTIFY,
1264                                                         &info->drive, 
1265                                                         sizeof(struct hd_driveid) );
1266                         if (transferStatus != ISD200_TRANSPORT_GOOD) {
1267                                 /* Error issuing ATA Command Identify */
1268                                 US_DEBUGP("   Error issuing ATA Command Identify\n");
1269                                 retStatus = ISD200_ERROR;
1270                         } else {
1271                                 /* ATA Command Identify successful */
1272                                 int i;
1273
1274                                 US_DEBUGP("   Identify Data Structure:\n");
1275                                 US_DEBUGP("      config = 0x%x\n", info->drive.config);
1276                                 US_DEBUGP("      cyls = 0x%x\n", info->drive.cyls);
1277                                 US_DEBUGP("      heads = 0x%x\n", info->drive.heads);
1278                                 US_DEBUGP("      track_bytes = 0x%x\n", info->drive.track_bytes);
1279                                 US_DEBUGP("      sector_bytes = 0x%x\n", info->drive.sector_bytes);
1280                                 US_DEBUGP("      sectors = 0x%x\n", info->drive.sectors);
1281                                 US_DEBUGP("      serial_no[0] = 0x%x\n", info->drive.serial_no[0]);
1282                                 US_DEBUGP("      buf_type = 0x%x\n", info->drive.buf_type);
1283                                 US_DEBUGP("      buf_size = 0x%x\n", info->drive.buf_size);
1284                                 US_DEBUGP("      ecc_bytes = 0x%x\n", info->drive.ecc_bytes);
1285                                 US_DEBUGP("      fw_rev[0] = 0x%x\n", info->drive.fw_rev[0]);
1286                                 US_DEBUGP("      model[0] = 0x%x\n", info->drive.model[0]);
1287                                 US_DEBUGP("      max_multsect = 0x%x\n", info->drive.max_multsect);
1288                                 US_DEBUGP("      dword_io = 0x%x\n", info->drive.dword_io);
1289                                 US_DEBUGP("      capability = 0x%x\n", info->drive.capability);
1290                                 US_DEBUGP("      tPIO = 0x%x\n", info->drive.tPIO);
1291                                 US_DEBUGP("      tDMA = 0x%x\n", info->drive.tDMA);
1292                                 US_DEBUGP("      field_valid = 0x%x\n", info->drive.field_valid);
1293                                 US_DEBUGP("      cur_cyls = 0x%x\n", info->drive.cur_cyls);
1294                                 US_DEBUGP("      cur_heads = 0x%x\n", info->drive.cur_heads);
1295                                 US_DEBUGP("      cur_sectors = 0x%x\n", info->drive.cur_sectors);
1296                                 US_DEBUGP("      cur_capacity = 0x%x\n", (info->drive.cur_capacity1 << 16) + info->drive.cur_capacity0 );
1297                                 US_DEBUGP("      multsect = 0x%x\n", info->drive.multsect);
1298                                 US_DEBUGP("      lba_capacity = 0x%x\n", info->drive.lba_capacity);
1299                                 US_DEBUGP("      command_set_1 = 0x%x\n", info->drive.command_set_1);
1300                                 US_DEBUGP("      command_set_2 = 0x%x\n", info->drive.command_set_2);
1301
1302                                 memset(&info->InquiryData, 0, sizeof(info->InquiryData));
1303
1304                                 /* Standard IDE interface only supports disks */
1305                                 info->InquiryData.DeviceType = DIRECT_ACCESS_DEVICE;
1306
1307                                 /* Fix-up the return data from an INQUIRY command to show 
1308                                  * ANSI SCSI rev 2 so we don't confuse the SCSI layers above us
1309                                  * in Linux.
1310                                  */
1311                                 info->InquiryData.Versions = 0x2;
1312
1313                                 /* The length must be at least 36 (5 + 31) */
1314                                 info->InquiryData.AdditionalLength = 0x1F;
1315
1316                                 if (info->drive.command_set_1 & COMMANDSET_MEDIA_STATUS) {
1317                                         /* set the removable bit */
1318                                         info->InquiryData.RemovableMedia = 1;
1319                                         info->DeviceFlags |= DF_REMOVABLE_MEDIA;
1320                                 }
1321
1322                                 /* Fill in vendor identification fields */
1323                                 for (i = 0; i < 20; i += 2) {
1324                                         info->InquiryData.VendorId[i] = 
1325                                                 info->drive.model[i + 1];
1326                                         info->InquiryData.VendorId[i+1] = 
1327                                                 info->drive.model[i];
1328                                 }
1329
1330                                 /* Initialize unused portion of product id */
1331                                 for (i = 0; i < 4; i++) {
1332                                         info->InquiryData.ProductId[12+i] = ' ';
1333                                 }
1334
1335                                 /* Move firmware revision from IDENTIFY data to */
1336                                 /* product revision in INQUIRY data             */
1337                                 for (i = 0; i < 4; i += 2) {
1338                                         info->InquiryData.ProductRevisionLevel[i] =
1339                                                 info->drive.fw_rev[i+1];
1340                                         info->InquiryData.ProductRevisionLevel[i+1] =
1341                                                 info->drive.fw_rev[i];
1342                                 }
1343
1344                                 /* determine if it supports Media Status Notification */
1345                                 if (info->drive.command_set_2 & COMMANDSET_MEDIA_STATUS) {
1346                                         US_DEBUGP("   Device supports Media Status Notification\n");
1347
1348                                         /* Indicate that it is enabled, even though it is not
1349                                          * This allows the lock/unlock of the media to work
1350                                          * correctly.
1351                                          */
1352                                         info->DeviceFlags |= DF_MEDIA_STATUS_ENABLED;
1353                                 }
1354                                 else
1355                                         info->DeviceFlags &= ~DF_MEDIA_STATUS_ENABLED;
1356
1357                         }
1358                 } else {
1359                         /* 
1360                          * this must be an ATAPI device 
1361                          * use an ATAPI protocol (Transparent SCSI)
1362                          */
1363                         us->protocol_name = "Transparent SCSI";
1364                         us->proto_handler = usb_stor_transparent_scsi_command;
1365
1366                         US_DEBUGP("Protocol changed to: %s\n", us->protocol_name);
1367             
1368                         /* Free driver structure */            
1369                         if (us->extra != NULL) {
1370                                 kfree(us->extra);
1371                                 us->extra = NULL;
1372                                 us->extra_destructor = NULL;
1373                         }
1374                 }
1375         }
1376
1377         US_DEBUGP("Leaving isd200_get_inquiry_data %08X\n", retStatus);
1378
1379         return(retStatus);
1380 }
1381
1382
1383 /**************************************************************************
1384  * isd200_data_copy
1385  *                                                                         
1386  * Copy data into the srb request buffer.  Use scatter gather if required.
1387  *
1388  * RETURNS:
1389  *    void
1390  */                                                                        
1391 void isd200_data_copy(Scsi_Cmnd *srb, char * src, int length)
1392 {
1393         unsigned int len = length;
1394         struct scatterlist *sg;
1395
1396         if (srb->use_sg) {
1397                 int i;
1398                 unsigned int total = 0;
1399
1400                 /* Add up the sizes of all the sg segments */
1401                 sg = (struct scatterlist *) srb->request_buffer;
1402                 for (i = 0; i < srb->use_sg; i++)
1403                         total += sg[i].length;
1404
1405                 if (length > total)
1406                         len = total;
1407
1408                 total = 0;
1409
1410                 /* Copy data into sg buffer(s) */
1411                 for (i = 0; i < srb->use_sg; i++) {
1412                         if ((len > total) && (len > 0)) {
1413                                 /* transfer the lesser of the next buffer or the
1414                                  * remaining data */
1415                                 if (len - total >= sg[i].length) {
1416                                         memcpy(sg[i].address, src + total, sg[i].length);
1417                                         total += sg[i].length;
1418                                 } else {
1419                                         memcpy(sg[i].address, src + total, len - total);
1420                                         total = len;
1421                                 }
1422                         } 
1423                         else
1424                                 break;
1425                 }
1426         } else  {
1427                 /* Make sure length does not exceed buffer length */
1428                 if (length > srb->request_bufflen)
1429                         len = srb->request_bufflen;
1430
1431                 if (len > 0)
1432                         memcpy(srb->request_buffer, src, len);
1433         }
1434 }
1435
1436
1437 /**************************************************************************
1438  * isd200_scsi_to_ata
1439  *                                                                         
1440  * Translate SCSI commands to ATA commands.
1441  *
1442  * RETURNS:
1443  *    TRUE if the command needs to be sent to the transport layer
1444  *    FALSE otherwise
1445  */                                                                        
1446 int isd200_scsi_to_ata(Scsi_Cmnd *srb, struct us_data *us, 
1447                        union ata_cdb * ataCdb)
1448 {
1449         struct isd200_info *info = (struct isd200_info *)us->extra;
1450         int sendToTransport = TRUE;
1451         unsigned char sectnum, head;
1452         unsigned short cylinder;
1453         unsigned long lba;
1454         unsigned long blockCount;
1455         unsigned char senseData[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
1456
1457         memset(ataCdb, 0, sizeof(union ata_cdb));
1458
1459         /* SCSI Command */
1460         switch (srb->cmnd[0]) {
1461         case INQUIRY:
1462                 US_DEBUGP("   ATA OUT - INQUIRY\n");
1463
1464                 if (srb->request_bufflen > sizeof(struct inquiry_data))
1465                         srb->request_bufflen = sizeof(struct inquiry_data);
1466
1467                 /* copy InquiryData */
1468                 isd200_data_copy(srb, (char *) &info->InquiryData, srb->request_bufflen);
1469                 srb->result = GOOD;
1470                 sendToTransport = FALSE;
1471                 break;
1472
1473         case MODE_SENSE:
1474                 US_DEBUGP("   ATA OUT - SCSIOP_MODE_SENSE\n");
1475
1476                 /* Initialize the return buffer */
1477                 isd200_data_copy(srb, (char *) &senseData, 8);
1478
1479                 if (info->DeviceFlags & DF_MEDIA_STATUS_ENABLED)
1480                 {
1481                         ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
1482                         ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
1483                         ataCdb->generic.TransferBlockSize = 1;
1484                         ataCdb->write.SelectCommand = 1;
1485                         ataCdb->write.CommandByte = ATA_COMMAND_GET_MEDIA_STATUS;
1486                         srb->request_bufflen = 0;
1487                 } else {
1488                         US_DEBUGP("   Media Status not supported, just report okay\n");
1489                         srb->result = GOOD;
1490                         sendToTransport = FALSE;
1491                 }
1492                 break;
1493
1494         case TEST_UNIT_READY:
1495                 US_DEBUGP("   ATA OUT - SCSIOP_TEST_UNIT_READY\n");
1496
1497                 /* Initialize the return buffer */
1498                 isd200_data_copy(srb, (char *) &senseData, 8);
1499
1500                 if (info->DeviceFlags & DF_MEDIA_STATUS_ENABLED)
1501                 {
1502                         ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
1503                         ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
1504                         ataCdb->generic.TransferBlockSize = 1;
1505                         ataCdb->write.SelectCommand = 1;
1506                         ataCdb->write.CommandByte = ATA_COMMAND_GET_MEDIA_STATUS;
1507                         srb->request_bufflen = 0;
1508                 } else {
1509                         US_DEBUGP("   Media Status not supported, just report okay\n");
1510                         srb->result = GOOD;
1511                         sendToTransport = FALSE;
1512                 }
1513                 break;
1514
1515         case READ_CAPACITY:
1516         {
1517                 unsigned long capacity;
1518                 struct read_capacity_data readCapacityData;
1519
1520                 US_DEBUGP("   ATA OUT - SCSIOP_READ_CAPACITY\n");
1521
1522                 if (info->drive.capability & CAPABILITY_LBA ) {
1523                         capacity = info->drive.lba_capacity - 1;
1524                 } else {
1525                         capacity = (info->drive.heads *
1526                                     info->drive.cyls *
1527                                     info->drive.sectors) - 1;
1528                 }
1529                 readCapacityData.LogicalBlockAddress = cpu_to_be32(capacity);
1530                 readCapacityData.BytesPerBlock = cpu_to_be32(0x200);
1531
1532                 if (srb->request_bufflen > sizeof(struct read_capacity_data))
1533                         srb->request_bufflen = sizeof(struct read_capacity_data);
1534
1535                 isd200_data_copy(srb, (char *) &readCapacityData, srb->request_bufflen);
1536                 srb->result = GOOD;
1537                 sendToTransport = FALSE;
1538         }
1539         break;
1540
1541         case READ_10:
1542                 US_DEBUGP("   ATA OUT - SCSIOP_READ\n");
1543
1544                 lba = *(unsigned long *)&srb->cmnd[2]; 
1545                 lba = cpu_to_be32(lba);
1546                 blockCount = (unsigned long)srb->cmnd[7]<<8 | (unsigned long)srb->cmnd[8];
1547
1548                 if (info->drive.capability & CAPABILITY_LBA) {
1549                         sectnum = (unsigned char)(lba);
1550                         cylinder = (unsigned short)(lba>>8);
1551                         head = ATA_ADDRESS_DEVHEAD_LBA_MODE | (unsigned char)(lba>>24 & 0x0F);
1552                 } else {
1553                         sectnum = (unsigned char)((lba % info->drive.sectors) + 1);
1554                         cylinder = (unsigned short)(lba / (info->drive.sectors *
1555                                                            info->drive.heads));
1556                         head = (unsigned char)((lba / info->drive.sectors) %
1557                                                info->drive.heads);
1558                 }
1559                 ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
1560                 ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
1561                 ataCdb->generic.TransferBlockSize = 1;
1562                 ataCdb->write.SelectSectorCount = 1;
1563                 ataCdb->write.SectorCountByte = (unsigned char)blockCount;
1564                 ataCdb->write.SelectSectorNumber = 1;
1565                 ataCdb->write.SectorNumberByte = sectnum;
1566                 ataCdb->write.SelectCylinderHigh = 1;
1567                 ataCdb->write.CylinderHighByte = (unsigned char)(cylinder>>8);
1568                 ataCdb->write.SelectCylinderLow = 1;
1569                 ataCdb->write.CylinderLowByte = (unsigned char)cylinder;
1570                 ataCdb->write.SelectDeviceHead = 1;
1571                 ataCdb->write.DeviceHeadByte = (head | ATA_ADDRESS_DEVHEAD_STD);
1572                 ataCdb->write.SelectCommand = 1;
1573                 ataCdb->write.CommandByte = WIN_READ;
1574                 break;
1575
1576         case WRITE_10:
1577                 US_DEBUGP("   ATA OUT - SCSIOP_WRITE\n");
1578
1579                 lba = *(unsigned long *)&srb->cmnd[2]; 
1580                 lba = cpu_to_be32(lba);
1581                 blockCount = (unsigned long)srb->cmnd[7]<<8 | (unsigned long)srb->cmnd[8];
1582
1583                 if (info->drive.capability & CAPABILITY_LBA) {
1584                         sectnum = (unsigned char)(lba);
1585                         cylinder = (unsigned short)(lba>>8);
1586                         head = ATA_ADDRESS_DEVHEAD_LBA_MODE | (unsigned char)(lba>>24 & 0x0F);
1587                 } else {
1588                         sectnum = (unsigned char)((lba % info->drive.sectors) + 1);
1589                         cylinder = (unsigned short)(lba / (info->drive.sectors * info->drive.heads));
1590                         head = (unsigned char)((lba / info->drive.sectors) % info->drive.heads);
1591                 }
1592                 ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
1593                 ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
1594                 ataCdb->generic.TransferBlockSize = 1;
1595                 ataCdb->write.SelectSectorCount = 1;
1596                 ataCdb->write.SectorCountByte = (unsigned char)blockCount;
1597                 ataCdb->write.SelectSectorNumber = 1;
1598                 ataCdb->write.SectorNumberByte = sectnum;
1599                 ataCdb->write.SelectCylinderHigh = 1;
1600                 ataCdb->write.CylinderHighByte = (unsigned char)(cylinder>>8);
1601                 ataCdb->write.SelectCylinderLow = 1;
1602                 ataCdb->write.CylinderLowByte = (unsigned char)cylinder;
1603                 ataCdb->write.SelectDeviceHead = 1;
1604                 ataCdb->write.DeviceHeadByte = (head | ATA_ADDRESS_DEVHEAD_STD);
1605                 ataCdb->write.SelectCommand = 1;
1606                 ataCdb->write.CommandByte = WIN_WRITE;
1607                 break;
1608
1609         case ALLOW_MEDIUM_REMOVAL:
1610                 US_DEBUGP("   ATA OUT - SCSIOP_MEDIUM_REMOVAL\n");
1611
1612                 if (info->DeviceFlags & DF_REMOVABLE_MEDIA) {
1613                         US_DEBUGP("   srb->cmnd[4] = 0x%X\n", srb->cmnd[4]);
1614             
1615                         ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
1616                         ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
1617                         ataCdb->generic.TransferBlockSize = 1;
1618                         ataCdb->write.SelectCommand = 1;
1619                         ataCdb->write.CommandByte = (srb->cmnd[4] & 0x1) ?
1620                                 WIN_DOORLOCK : WIN_DOORUNLOCK;
1621                         srb->request_bufflen = 0;
1622                 } else {
1623                         US_DEBUGP("   Not removeable media, just report okay\n");
1624                         srb->result = GOOD;
1625                         sendToTransport = FALSE;
1626                 }
1627                 break;
1628
1629         case START_STOP:    
1630                 US_DEBUGP("   ATA OUT - SCSIOP_START_STOP_UNIT\n");
1631                 US_DEBUGP("   srb->cmnd[4] = 0x%X\n", srb->cmnd[4]);
1632
1633                 /* Initialize the return buffer */
1634                 isd200_data_copy(srb, (char *) &senseData, 8);
1635
1636                 if ((srb->cmnd[4] & 0x3) == 0x2) {
1637                         US_DEBUGP("   Media Eject\n");
1638                         ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
1639                         ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
1640                         ataCdb->generic.TransferBlockSize = 0;
1641                         ataCdb->write.SelectCommand = 1;
1642                         ataCdb->write.CommandByte = ATA_COMMAND_MEDIA_EJECT;
1643                 } else if ((srb->cmnd[4] & 0x3) == 0x1) {
1644                         US_DEBUGP("   Get Media Status\n");
1645                         ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
1646                         ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
1647                         ataCdb->generic.TransferBlockSize = 1;
1648                         ataCdb->write.SelectCommand = 1;
1649                         ataCdb->write.CommandByte = ATA_COMMAND_GET_MEDIA_STATUS;
1650                         srb->request_bufflen = 0;
1651                 } else {
1652                         US_DEBUGP("   Nothing to do, just report okay\n");
1653                         srb->result = GOOD;
1654                         sendToTransport = FALSE;
1655                 }
1656                 break;
1657
1658         default:
1659                 US_DEBUGP("Unsupported SCSI command - 0x%X\n", srb->cmnd[0]);
1660                 srb->result = DID_ERROR << 16;
1661                 sendToTransport = FALSE;
1662                 break;
1663         }
1664
1665         return(sendToTransport);
1666 }
1667
1668
1669 /**************************************************************************
1670  * isd200_init_info
1671  *                                                                         
1672  * Allocates (if necessary) and initializes the driver structure.
1673  *
1674  * RETURNS:
1675  *    ISD status code
1676  */                                                                        
1677 int isd200_init_info(struct us_data *us)
1678 {
1679         int retStatus = ISD200_GOOD;
1680
1681         if (!us->extra) {
1682                 us->extra = (void *) kmalloc(sizeof(struct isd200_info), GFP_KERNEL);
1683                 if (!us->extra) {
1684                         US_DEBUGP("ERROR - kmalloc failure\n");
1685                         retStatus = ISD200_ERROR;
1686                 }
1687         }
1688
1689         if (retStatus == ISD200_GOOD) {
1690                 memset(us->extra, 0, sizeof(struct isd200_info));
1691         }
1692
1693         return(retStatus);
1694 }
1695
1696 /**************************************************************************
1697  * Initialization for the ISD200 
1698  */
1699
1700 int isd200_Initialization(struct us_data *us)
1701 {
1702         US_DEBUGP("ISD200 Initialization...\n");
1703
1704         /* Initialize ISD200 info struct */
1705
1706         if (isd200_init_info(us) == ISD200_ERROR) {
1707                 US_DEBUGP("ERROR Initializing ISD200 Info struct\n");
1708         } else {
1709                 /* Get device specific data */
1710
1711                 if (isd200_get_inquiry_data(us) != ISD200_GOOD)
1712                         US_DEBUGP("ISD200 Initialization Failure\n");
1713                 else
1714                         US_DEBUGP("ISD200 Initialization complete\n");
1715         }
1716
1717         return 0;
1718 }
1719
1720
1721 /**************************************************************************
1722  * Protocol and Transport for the ISD200 ASIC
1723  *
1724  * This protocol and transport are for ATA devices connected to an ISD200
1725  * ASIC.  An ATAPI device that is conected as a slave device will be
1726  * detected in the driver initialization function and the protocol will
1727  * be changed to an ATAPI protocol (Transparent SCSI).
1728  *
1729  */
1730
1731 void isd200_ata_command(Scsi_Cmnd *srb, struct us_data *us)
1732 {
1733         int sendToTransport = TRUE;
1734         union ata_cdb ataCdb;
1735
1736         /* Make sure driver was initialized */
1737
1738         if (us->extra == NULL)
1739                 US_DEBUGP("ERROR Driver not initialized\n");
1740
1741         /* Convert command */
1742         sendToTransport = isd200_scsi_to_ata(srb, us, &ataCdb);
1743
1744         /* send the command to the transport layer */
1745         if (sendToTransport)
1746                 isd200_invoke_transport(us, srb, &ataCdb);
1747 }