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