[libata scsi] add CHS support to ata_scsi_start_stop_xlat()
[linux-block.git] / drivers / scsi / libata-scsi.c
1 /*
2  *  libata-scsi.c - helper library for ATA
3  *
4  *  Maintained by:  Jeff Garzik <jgarzik@pobox.com>
5  *                  Please ALWAYS copy linux-ide@vger.kernel.org
6  *                  on emails.
7  *
8  *  Copyright 2003-2004 Red Hat, Inc.  All rights reserved.
9  *  Copyright 2003-2004 Jeff Garzik
10  *
11  *
12  *  This program is free software; you can redistribute it and/or modify
13  *  it under the terms of the GNU General Public License as published by
14  *  the Free Software Foundation; either version 2, or (at your option)
15  *  any later version.
16  *
17  *  This program is distributed in the hope that it will be useful,
18  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
19  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *  GNU General Public License for more details.
21  *
22  *  You should have received a copy of the GNU General Public License
23  *  along with this program; see the file COPYING.  If not, write to
24  *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
25  *
26  *
27  *  libata documentation is available via 'make {ps|pdf}docs',
28  *  as Documentation/DocBook/libata.*
29  *
30  *  Hardware documentation available from
31  *  - http://www.t10.org/
32  *  - http://www.t13.org/
33  *
34  */
35
36 #include <linux/kernel.h>
37 #include <linux/blkdev.h>
38 #include <linux/spinlock.h>
39 #include <scsi/scsi.h>
40 #include "scsi.h"
41 #include <scsi/scsi_host.h>
42 #include <linux/libata.h>
43 #include <asm/uaccess.h>
44
45 #include "libata.h"
46
47 typedef unsigned int (*ata_xlat_func_t)(struct ata_queued_cmd *qc, u8 *scsicmd);
48 static struct ata_device *
49 ata_scsi_find_dev(struct ata_port *ap, struct scsi_device *scsidev);
50
51
52 /**
53  *      ata_std_bios_param - generic bios head/sector/cylinder calculator used by sd.
54  *      @sdev: SCSI device for which BIOS geometry is to be determined
55  *      @bdev: block device associated with @sdev
56  *      @capacity: capacity of SCSI device
57  *      @geom: location to which geometry will be output
58  *
59  *      Generic bios head/sector/cylinder calculator
60  *      used by sd. Most BIOSes nowadays expect a XXX/255/16  (CHS)
61  *      mapping. Some situations may arise where the disk is not
62  *      bootable if this is not used.
63  *
64  *      LOCKING:
65  *      Defined by the SCSI layer.  We don't really care.
66  *
67  *      RETURNS:
68  *      Zero.
69  */
70 int ata_std_bios_param(struct scsi_device *sdev, struct block_device *bdev,
71                        sector_t capacity, int geom[])
72 {
73         geom[0] = 255;
74         geom[1] = 63;
75         sector_div(capacity, 255*63);
76         geom[2] = capacity;
77
78         return 0;
79 }
80
81 int ata_scsi_ioctl(struct scsi_device *scsidev, int cmd, void __user *arg)
82 {
83         struct ata_port *ap;
84         struct ata_device *dev;
85         int val = -EINVAL, rc = -EINVAL;
86
87         ap = (struct ata_port *) &scsidev->host->hostdata[0];
88         if (!ap)
89                 goto out;
90
91         dev = ata_scsi_find_dev(ap, scsidev);
92         if (!dev) {
93                 rc = -ENODEV;
94                 goto out;
95         }
96
97         switch (cmd) {
98         case ATA_IOC_GET_IO32:
99                 val = 0;
100                 if (copy_to_user(arg, &val, 1))
101                         return -EFAULT;
102                 return 0;
103
104         case ATA_IOC_SET_IO32:
105                 val = (unsigned long) arg;
106                 if (val != 0)
107                         return -EINVAL;
108                 return 0;
109
110         default:
111                 rc = -ENOTTY;
112                 break;
113         }
114
115 out:
116         return rc;
117 }
118
119 /**
120  *      ata_scsi_qc_new - acquire new ata_queued_cmd reference
121  *      @ap: ATA port to which the new command is attached
122  *      @dev: ATA device to which the new command is attached
123  *      @cmd: SCSI command that originated this ATA command
124  *      @done: SCSI command completion function
125  *
126  *      Obtain a reference to an unused ata_queued_cmd structure,
127  *      which is the basic libata structure representing a single
128  *      ATA command sent to the hardware.
129  *
130  *      If a command was available, fill in the SCSI-specific
131  *      portions of the structure with information on the
132  *      current command.
133  *
134  *      LOCKING:
135  *      spin_lock_irqsave(host_set lock)
136  *
137  *      RETURNS:
138  *      Command allocated, or %NULL if none available.
139  */
140 struct ata_queued_cmd *ata_scsi_qc_new(struct ata_port *ap,
141                                        struct ata_device *dev,
142                                        struct scsi_cmnd *cmd,
143                                        void (*done)(struct scsi_cmnd *))
144 {
145         struct ata_queued_cmd *qc;
146
147         qc = ata_qc_new_init(ap, dev);
148         if (qc) {
149                 qc->scsicmd = cmd;
150                 qc->scsidone = done;
151
152                 if (cmd->use_sg) {
153                         qc->sg = (struct scatterlist *) cmd->request_buffer;
154                         qc->n_elem = cmd->use_sg;
155                 } else {
156                         qc->sg = &qc->sgent;
157                         qc->n_elem = 1;
158                 }
159         } else {
160                 cmd->result = (DID_OK << 16) | (QUEUE_FULL << 1);
161                 done(cmd);
162         }
163
164         return qc;
165 }
166
167 /**
168  *      ata_to_sense_error - convert ATA error to SCSI error
169  *      @qc: Command that we are erroring out
170  *      @drv_stat: value contained in ATA status register
171  *
172  *      Converts an ATA error into a SCSI error. While we are at it
173  *      we decode and dump the ATA error for the user so that they
174  *      have some idea what really happened at the non make-believe
175  *      layer.
176  *
177  *      LOCKING:
178  *      spin_lock_irqsave(host_set lock)
179  */
180
181 void ata_to_sense_error(struct ata_queued_cmd *qc, u8 drv_stat)
182 {
183         struct scsi_cmnd *cmd = qc->scsicmd;
184         u8 err = 0;
185         unsigned char *sb = cmd->sense_buffer;
186         /* Based on the 3ware driver translation table */
187         static unsigned char sense_table[][4] = {
188                 /* BBD|ECC|ID|MAR */
189                 {0xd1,          ABORTED_COMMAND, 0x00, 0x00},   // Device busy                  Aborted command
190                 /* BBD|ECC|ID */
191                 {0xd0,          ABORTED_COMMAND, 0x00, 0x00},   // Device busy                  Aborted command
192                 /* ECC|MC|MARK */
193                 {0x61,          HARDWARE_ERROR, 0x00, 0x00},    // Device fault                 Hardware error
194                 /* ICRC|ABRT */         /* NB: ICRC & !ABRT is BBD */
195                 {0x84,          ABORTED_COMMAND, 0x47, 0x00},   // Data CRC error               SCSI parity error
196                 /* MC|ID|ABRT|TRK0|MARK */
197                 {0x37,          NOT_READY, 0x04, 0x00},         // Unit offline                 Not ready
198                 /* MCR|MARK */
199                 {0x09,          NOT_READY, 0x04, 0x00},         // Unrecovered disk error       Not ready
200                 /*  Bad address mark */
201                 {0x01,          MEDIUM_ERROR, 0x13, 0x00},      // Address mark not found       Address mark not found for data field
202                 /* TRK0 */
203                 {0x02,          HARDWARE_ERROR, 0x00, 0x00},    // Track 0 not found              Hardware error
204                 /* Abort & !ICRC */
205                 {0x04,          ABORTED_COMMAND, 0x00, 0x00},   // Aborted command              Aborted command
206                 /* Media change request */
207                 {0x08,          NOT_READY, 0x04, 0x00},         // Media change request   FIXME: faking offline
208                 /* SRV */
209                 {0x10,          ABORTED_COMMAND, 0x14, 0x00},   // ID not found                 Recorded entity not found
210                 /* Media change */
211                 {0x08,          NOT_READY, 0x04, 0x00},         // Media change           FIXME: faking offline
212                 /* ECC */
213                 {0x40,          MEDIUM_ERROR, 0x11, 0x04},      // Uncorrectable ECC error      Unrecovered read error
214                 /* BBD - block marked bad */
215                 {0x80,          MEDIUM_ERROR, 0x11, 0x04},      // Block marked bad               Medium error, unrecovered read error
216                 {0xFF, 0xFF, 0xFF, 0xFF}, // END mark
217         };
218         static unsigned char stat_table[][4] = {
219                 /* Must be first because BUSY means no other bits valid */
220                 {0x80,          ABORTED_COMMAND, 0x47, 0x00},   // Busy, fake parity for now
221                 {0x20,          HARDWARE_ERROR,  0x00, 0x00},   // Device fault
222                 {0x08,          ABORTED_COMMAND, 0x47, 0x00},   // Timed out in xfer, fake parity for now
223                 {0x04,          RECOVERED_ERROR, 0x11, 0x00},   // Recovered ECC error    Medium error, recovered
224                 {0xFF, 0xFF, 0xFF, 0xFF}, // END mark
225         };
226         int i = 0;
227
228         cmd->result = SAM_STAT_CHECK_CONDITION;
229
230         /*
231          *      Is this an error we can process/parse
232          */
233
234         if(drv_stat & ATA_ERR)
235                 /* Read the err bits */
236                 err = ata_chk_err(qc->ap);
237
238         /* Display the ATA level error info */
239
240         printk(KERN_WARNING "ata%u: status=0x%02x { ", qc->ap->id, drv_stat);
241         if(drv_stat & 0x80)
242         {
243                 printk("Busy ");
244                 err = 0;        /* Data is not valid in this case */
245         }
246         else {
247                 if(drv_stat & 0x40)     printk("DriveReady ");
248                 if(drv_stat & 0x20)     printk("DeviceFault ");
249                 if(drv_stat & 0x10)     printk("SeekComplete ");
250                 if(drv_stat & 0x08)     printk("DataRequest ");
251                 if(drv_stat & 0x04)     printk("CorrectedError ");
252                 if(drv_stat & 0x02)     printk("Index ");
253                 if(drv_stat & 0x01)     printk("Error ");
254         }
255         printk("}\n");
256
257         if(err)
258         {
259                 printk(KERN_WARNING "ata%u: error=0x%02x { ", qc->ap->id, err);
260                 if(err & 0x04)          printk("DriveStatusError ");
261                 if(err & 0x80)
262                 {
263                         if(err & 0x04)
264                                 printk("BadCRC ");
265                         else
266                                 printk("Sector ");
267                 }
268                 if(err & 0x40)          printk("UncorrectableError ");
269                 if(err & 0x10)          printk("SectorIdNotFound ");
270                 if(err & 0x02)          printk("TrackZeroNotFound ");
271                 if(err & 0x01)          printk("AddrMarkNotFound ");
272                 printk("}\n");
273
274                 /* Should we dump sector info here too ?? */
275         }
276
277
278         /* Look for err */
279         while(sense_table[i][0] != 0xFF)
280         {
281                 /* Look for best matches first */
282                 if((sense_table[i][0] & err) == sense_table[i][0])
283                 {
284                         sb[0] = 0x70;
285                         sb[2] = sense_table[i][1];
286                         sb[7] = 0x0a;
287                         sb[12] = sense_table[i][2];
288                         sb[13] = sense_table[i][3];
289                         return;
290                 }
291                 i++;
292         }
293         /* No immediate match */
294         if(err)
295                 printk(KERN_DEBUG "ata%u: no sense translation for 0x%02x\n", qc->ap->id, err);
296
297         i = 0;
298         /* Fall back to interpreting status bits */
299         while(stat_table[i][0] != 0xFF)
300         {
301                 if(stat_table[i][0] & drv_stat)
302                 {
303                         sb[0] = 0x70;
304                         sb[2] = stat_table[i][1];
305                         sb[7] = 0x0a;
306                         sb[12] = stat_table[i][2];
307                         sb[13] = stat_table[i][3];
308                         return;
309                 }
310                 i++;
311         }
312         /* No error ?? */
313         printk(KERN_ERR "ata%u: called with no error (%02X)!\n", qc->ap->id, drv_stat);
314         /* additional-sense-code[-qualifier] */
315
316         sb[0] = 0x70;
317         sb[2] = MEDIUM_ERROR;
318         sb[7] = 0x0A;
319         if (cmd->sc_data_direction == DMA_FROM_DEVICE) {
320                 sb[12] = 0x11; /* "unrecovered read error" */
321                 sb[13] = 0x04;
322         } else {
323                 sb[12] = 0x0C; /* "write error -             */
324                 sb[13] = 0x02; /*  auto-reallocation failed" */
325         }
326 }
327
328 /**
329  *      ata_scsi_slave_config - Set SCSI device attributes
330  *      @sdev: SCSI device to examine
331  *
332  *      This is called before we actually start reading
333  *      and writing to the device, to configure certain
334  *      SCSI mid-layer behaviors.
335  *
336  *      LOCKING:
337  *      Defined by SCSI layer.  We don't really care.
338  */
339
340 int ata_scsi_slave_config(struct scsi_device *sdev)
341 {
342         sdev->use_10_for_rw = 1;
343         sdev->use_10_for_ms = 1;
344
345         blk_queue_max_phys_segments(sdev->request_queue, LIBATA_MAX_PRD);
346
347         if (sdev->id < ATA_MAX_DEVICES) {
348                 struct ata_port *ap;
349                 struct ata_device *dev;
350
351                 ap = (struct ata_port *) &sdev->host->hostdata[0];
352                 dev = &ap->device[sdev->id];
353
354                 /* TODO: 1024 is an arbitrary number, not the
355                  * hardware maximum.  This should be increased to
356                  * 65534 when Jens Axboe's patch for dynamically
357                  * determining max_sectors is merged.
358                  */
359                 if ((dev->flags & ATA_DFLAG_LBA48) &&
360                     ((dev->flags & ATA_DFLAG_LOCK_SECTORS) == 0)) {
361                         /*
362                          * do not overwrite sdev->host->max_sectors, since
363                          * other drives on this host may not support LBA48
364                          */
365                         blk_queue_max_sectors(sdev->request_queue, 2048);
366                 }
367         }
368
369         return 0;       /* scsi layer doesn't check return value, sigh */
370 }
371
372 /**
373  *      ata_scsi_error - SCSI layer error handler callback
374  *      @host: SCSI host on which error occurred
375  *
376  *      Handles SCSI-layer-thrown error events.
377  *
378  *      LOCKING:
379  *      Inherited from SCSI layer (none, can sleep)
380  *
381  *      RETURNS:
382  *      Zero.
383  */
384
385 int ata_scsi_error(struct Scsi_Host *host)
386 {
387         struct ata_port *ap;
388
389         DPRINTK("ENTER\n");
390
391         ap = (struct ata_port *) &host->hostdata[0];
392         ap->ops->eng_timeout(ap);
393
394         /* TODO: this is per-command; when queueing is supported
395          * this code will either change or move to a more
396          * appropriate place
397          */
398         host->host_failed--;
399         INIT_LIST_HEAD(&host->eh_cmd_q);
400
401         DPRINTK("EXIT\n");
402         return 0;
403 }
404
405 /**
406  *      ata_scsi_start_stop_xlat - Translate SCSI START STOP UNIT command
407  *      @qc: Storage for translated ATA taskfile
408  *      @scsicmd: SCSI command to translate
409  *
410  *      Sets up an ATA taskfile to issue STANDBY (to stop) or READ VERIFY
411  *      (to start). Perhaps these commands should be preceded by
412  *      CHECK POWER MODE to see what power mode the device is already in.
413  *      [See SAT revision 5 at www.t10.org]
414  *
415  *      LOCKING:
416  *      spin_lock_irqsave(host_set lock)
417  *
418  *      RETURNS:
419  *      Zero on success, non-zero on error.
420  */
421
422 static unsigned int ata_scsi_start_stop_xlat(struct ata_queued_cmd *qc,
423                                              u8 *scsicmd)
424 {
425         struct ata_taskfile *tf = &qc->tf;
426
427         tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
428         tf->protocol = ATA_PROT_NODATA;
429         if (scsicmd[1] & 0x1) {
430                 ;       /* ignore IMMED bit, violates sat-r05 */
431         }
432         if (scsicmd[4] & 0x2)
433                 return 1;       /* LOEJ bit set not supported */
434         if (((scsicmd[4] >> 4) & 0xf) != 0)
435                 return 1;       /* power conditions not supported */
436         if (scsicmd[4] & 0x1) {
437                 tf->nsect = 1;  /* 1 sector, lba=0 */
438
439                 if (qc->dev->flags & ATA_DFLAG_LBA) {
440                         qc->tf.flags |= ATA_TFLAG_LBA;
441
442                         tf->lbah = 0x0;
443                         tf->lbam = 0x0;
444                         tf->lbal = 0x0;
445                         tf->device |= ATA_LBA;
446                 } else {
447                         /* CHS */
448                         tf->lbal = 0x1; /* sect */
449                         tf->lbam = 0x0; /* cyl low */
450                         tf->lbah = 0x0; /* cyl high */
451                 }
452
453                 tf->command = ATA_CMD_VERIFY;   /* READ VERIFY */
454         } else {
455                 tf->nsect = 0;  /* time period value (0 implies now) */
456                 tf->command = ATA_CMD_STANDBY;
457                 /* Consider: ATA STANDBY IMMEDIATE command */
458         }
459         /*
460          * Standby and Idle condition timers could be implemented but that
461          * would require libata to implement the Power condition mode page
462          * and allow the user to change it. Changing mode pages requires
463          * MODE SELECT to be implemented.
464          */
465
466         return 0;
467 }
468
469
470 /**
471  *      ata_scsi_flush_xlat - Translate SCSI SYNCHRONIZE CACHE command
472  *      @qc: Storage for translated ATA taskfile
473  *      @scsicmd: SCSI command to translate (ignored)
474  *
475  *      Sets up an ATA taskfile to issue FLUSH CACHE or
476  *      FLUSH CACHE EXT.
477  *
478  *      LOCKING:
479  *      spin_lock_irqsave(host_set lock)
480  *
481  *      RETURNS:
482  *      Zero on success, non-zero on error.
483  */
484
485 static unsigned int ata_scsi_flush_xlat(struct ata_queued_cmd *qc, u8 *scsicmd)
486 {
487         struct ata_taskfile *tf = &qc->tf;
488
489         tf->flags |= ATA_TFLAG_DEVICE;
490         tf->protocol = ATA_PROT_NODATA;
491
492         if ((tf->flags & ATA_TFLAG_LBA48) &&
493             (ata_id_has_flush_ext(qc->dev->id)))
494                 tf->command = ATA_CMD_FLUSH_EXT;
495         else
496                 tf->command = ATA_CMD_FLUSH;
497
498         return 0;
499 }
500
501 /**
502  *      scsi_6_lba_len - Get LBA and transfer length
503  *      @scsicmd: SCSI command to translate
504  *
505  *      Calculate LBA and transfer length for 6-byte commands.
506  *
507  *      RETURNS:
508  *      @plba: the LBA
509  *      @plen: the transfer length
510  */
511
512 static void scsi_6_lba_len(u8 *scsicmd, u64 *plba, u32 *plen)
513 {
514         u64 lba = 0;
515         u32 len = 0;
516
517         VPRINTK("six-byte command\n");
518
519         lba |= ((u64)scsicmd[2]) << 8;
520         lba |= ((u64)scsicmd[3]);
521
522         len |= ((u32)scsicmd[4]);
523
524         *plba = lba;
525         *plen = len;
526 }
527
528 /**
529  *      scsi_10_lba_len - Get LBA and transfer length
530  *      @scsicmd: SCSI command to translate
531  *
532  *      Calculate LBA and transfer length for 10-byte commands.
533  *
534  *      RETURNS:
535  *      @plba: the LBA
536  *      @plen: the transfer length
537  */
538
539 static void scsi_10_lba_len(u8 *scsicmd, u64 *plba, u32 *plen)
540 {
541         u64 lba = 0;
542         u32 len = 0;
543
544         VPRINTK("ten-byte command\n");
545
546         lba |= ((u64)scsicmd[2]) << 24;
547         lba |= ((u64)scsicmd[3]) << 16;
548         lba |= ((u64)scsicmd[4]) << 8;
549         lba |= ((u64)scsicmd[5]);
550
551         len |= ((u32)scsicmd[7]) << 8;
552         len |= ((u32)scsicmd[8]);
553
554         *plba = lba;
555         *plen = len;
556 }
557
558 /**
559  *      scsi_16_lba_len - Get LBA and transfer length
560  *      @scsicmd: SCSI command to translate
561  *
562  *      Calculate LBA and transfer length for 16-byte commands.
563  *
564  *      RETURNS:
565  *      @plba: the LBA
566  *      @plen: the transfer length
567  */
568
569 static void scsi_16_lba_len(u8 *scsicmd, u64 *plba, u32 *plen)
570 {
571         u64 lba = 0;
572         u32 len = 0;
573
574         VPRINTK("sixteen-byte command\n");
575
576         lba |= ((u64)scsicmd[2]) << 56;
577         lba |= ((u64)scsicmd[3]) << 48;
578         lba |= ((u64)scsicmd[4]) << 40;
579         lba |= ((u64)scsicmd[5]) << 32;
580         lba |= ((u64)scsicmd[6]) << 24;
581         lba |= ((u64)scsicmd[7]) << 16;
582         lba |= ((u64)scsicmd[8]) << 8;
583         lba |= ((u64)scsicmd[9]);
584
585         len |= ((u32)scsicmd[10]) << 24;
586         len |= ((u32)scsicmd[11]) << 16;
587         len |= ((u32)scsicmd[12]) << 8;
588         len |= ((u32)scsicmd[13]);
589
590         *plba = lba;
591         *plen = len;
592 }
593
594 /**
595  *      ata_scsi_verify_xlat - Translate SCSI VERIFY command into an ATA one
596  *      @qc: Storage for translated ATA taskfile
597  *      @scsicmd: SCSI command to translate
598  *
599  *      Converts SCSI VERIFY command to an ATA READ VERIFY command.
600  *
601  *      LOCKING:
602  *      spin_lock_irqsave(host_set lock)
603  *
604  *      RETURNS:
605  *      Zero on success, non-zero on error.
606  */
607
608 static unsigned int ata_scsi_verify_xlat(struct ata_queued_cmd *qc, u8 *scsicmd)
609 {
610         struct ata_taskfile *tf = &qc->tf;
611         struct ata_device *dev = qc->dev;
612         unsigned int lba   = tf->flags & ATA_TFLAG_LBA;
613         unsigned int lba48 = tf->flags & ATA_TFLAG_LBA48;
614         u64 dev_sectors = qc->dev->n_sectors;
615         u64 block;
616         u32 n_block;
617
618         tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
619         tf->protocol = ATA_PROT_NODATA;
620
621         if (scsicmd[0] == VERIFY)
622                 scsi_10_lba_len(scsicmd, &block, &n_block);
623         else if (scsicmd[0] == VERIFY_16)
624                 scsi_16_lba_len(scsicmd, &block, &n_block);
625         else
626                 return 1;
627
628         if (!n_block)
629                 return 1;
630         if (block >= dev_sectors)
631                 return 1;
632         if ((block + n_block) > dev_sectors)
633                 return 1;
634         if (lba48) {
635                 if (n_block > (64 * 1024))
636                         return 1;
637         } else {
638                 if (n_block > 256)
639                         return 1;
640         }
641
642         if (lba) {
643                 if (lba48) {
644                         tf->command = ATA_CMD_VERIFY_EXT;
645
646                         tf->hob_nsect = (n_block >> 8) & 0xff;
647
648                         tf->hob_lbah = (block >> 40) & 0xff;
649                         tf->hob_lbam = (block >> 32) & 0xff;
650                         tf->hob_lbal = (block >> 24) & 0xff;
651                 } else {
652                         tf->command = ATA_CMD_VERIFY;
653
654                         tf->device |= (block >> 24) & 0xf;
655                 }
656
657                 tf->nsect = n_block & 0xff;
658
659                 tf->lbah = (block >> 16) & 0xff;
660                 tf->lbam = (block >> 8) & 0xff;
661                 tf->lbal = block & 0xff;
662
663                 tf->device |= ATA_LBA;
664         } else {
665                 /* CHS */
666                 u32 sect, head, cyl, track;
667
668                 /* Convert LBA to CHS */
669                 track = (u32)block / dev->sectors;
670                 cyl   = track / dev->heads;
671                 head  = track % dev->heads;
672                 sect  = (u32)block % dev->sectors + 1;
673
674                 DPRINTK("block %u track %u cyl %u head %u sect %u\n",
675                         (u32)block, track, cyl, head, sect);
676                 
677                 /* Check whether the converted CHS can fit. 
678                    Cylinder: 0-65535 
679                    Head: 0-15
680                    Sector: 1-255*/
681                 if ((cyl >> 16) || (head >> 4) || (sect >> 8) || (!sect)) 
682                         return 1;
683                 
684                 tf->command = ATA_CMD_VERIFY;
685                 tf->nsect = n_block & 0xff; /* Sector count 0 means 256 sectors */
686                 tf->lbal = sect;
687                 tf->lbam = cyl;
688                 tf->lbah = cyl >> 8;
689                 tf->device |= head;
690         }
691
692         return 0;
693 }
694
695 /**
696  *      ata_scsi_rw_xlat - Translate SCSI r/w command into an ATA one
697  *      @qc: Storage for translated ATA taskfile
698  *      @scsicmd: SCSI command to translate
699  *
700  *      Converts any of six SCSI read/write commands into the
701  *      ATA counterpart, including starting sector (LBA),
702  *      sector count, and taking into account the device's LBA48
703  *      support.
704  *
705  *      Commands %READ_6, %READ_10, %READ_16, %WRITE_6, %WRITE_10, and
706  *      %WRITE_16 are currently supported.
707  *
708  *      LOCKING:
709  *      spin_lock_irqsave(host_set lock)
710  *
711  *      RETURNS:
712  *      Zero on success, non-zero on error.
713  */
714
715 static unsigned int ata_scsi_rw_xlat(struct ata_queued_cmd *qc, u8 *scsicmd)
716 {
717         struct ata_taskfile *tf = &qc->tf;
718         struct ata_device *dev = qc->dev;
719         unsigned int lba   = tf->flags & ATA_TFLAG_LBA;
720         unsigned int lba48 = tf->flags & ATA_TFLAG_LBA48;
721         u64 block;
722         u32 n_block;
723
724         tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
725         tf->protocol = qc->dev->xfer_protocol;
726
727         if (scsicmd[0] == READ_10 || scsicmd[0] == READ_6 ||
728             scsicmd[0] == READ_16) {
729                 tf->command = qc->dev->read_cmd;
730         } else {
731                 tf->command = qc->dev->write_cmd;
732                 tf->flags |= ATA_TFLAG_WRITE;
733         }
734
735         /* Calculate the SCSI LBA and transfer length. */
736         switch (scsicmd[0]) {
737         case READ_10:
738         case WRITE_10:
739                 scsi_10_lba_len(scsicmd, &block, &n_block);
740                 break;
741         case READ_6:
742         case WRITE_6:
743                 scsi_6_lba_len(scsicmd, &block, &n_block);
744
745                 /* for 6-byte r/w commands, transfer length 0
746                  * means 256 blocks of data, not 0 block.
747                  */
748                 if (!n_block)
749                         n_block = 256;
750                 break;
751         case READ_16:
752         case WRITE_16:
753                 scsi_16_lba_len(scsicmd, &block, &n_block);
754                 break;
755         default:
756                 DPRINTK("no-byte command\n");
757                 return 1;
758         }
759
760         /* Check and compose ATA command */
761         if (!n_block)
762                 /* For 10-byte and 16-byte SCSI R/W commands, transfer
763                  * length 0 means transfer 0 block of data.
764                  * However, for ATA R/W commands, sector count 0 means
765                  * 256 or 65536 sectors, not 0 sectors as in SCSI.
766                  */
767                 return 1;
768
769         if (lba) {
770                 if (lba48) {
771                         /* The request -may- be too large for LBA48. */
772                         if ((block >> 48) || (n_block > 65536))
773                                 return 1;
774
775                         tf->hob_nsect = (n_block >> 8) & 0xff;
776
777                         tf->hob_lbah = (block >> 40) & 0xff;
778                         tf->hob_lbam = (block >> 32) & 0xff;
779                         tf->hob_lbal = (block >> 24) & 0xff;
780                 } else { 
781                         /* LBA28 */
782
783                         /* The request -may- be too large for LBA28. */
784                         if ((block >> 28) || (n_block > 256))
785                                 return 1;
786
787                         tf->device |= (block >> 24) & 0xf;
788                 }
789
790                 qc->nsect = n_block;
791                 tf->nsect = n_block & 0xff;
792
793                 tf->lbah = (block >> 16) & 0xff;
794                 tf->lbam = (block >> 8) & 0xff;
795                 tf->lbal = block & 0xff;
796
797                 tf->device |= ATA_LBA;
798         } else { 
799                 /* CHS */
800                 u32 sect, head, cyl, track;
801
802                 /* The request -may- be too large for CHS addressing. */
803                 if ((block >> 28) || (n_block > 256))
804                         return 1;
805
806                 /* Convert LBA to CHS */
807                 track = (u32)block / dev->sectors;
808                 cyl   = track / dev->heads;
809                 head  = track % dev->heads;
810                 sect  = (u32)block % dev->sectors + 1;
811
812                 DPRINTK("block %u track %u cyl %u head %u sect %u\n",
813                         (u32)block, track, cyl, head, sect);
814
815                 /* Check whether the converted CHS can fit. 
816                    Cylinder: 0-65535 
817                    Head: 0-15
818                    Sector: 1-255*/
819                 if ((cyl >> 16) || (head >> 4) || (sect >> 8) || (!sect))
820                         return 1;
821
822                 qc->nsect = n_block;
823                 tf->nsect = n_block & 0xff; /* Sector count 0 means 256 sectors */
824                 tf->lbal = sect;
825                 tf->lbam = cyl;
826                 tf->lbah = cyl >> 8;
827                 tf->device |= head;
828         }
829
830         return 0;
831 }
832
833 static int ata_scsi_qc_complete(struct ata_queued_cmd *qc, u8 drv_stat)
834 {
835         struct scsi_cmnd *cmd = qc->scsicmd;
836
837         if (unlikely(drv_stat & (ATA_ERR | ATA_BUSY | ATA_DRQ)))
838                 ata_to_sense_error(qc, drv_stat);
839         else
840                 cmd->result = SAM_STAT_GOOD;
841
842         qc->scsidone(cmd);
843
844         return 0;
845 }
846
847 /**
848  *      ata_scsi_translate - Translate then issue SCSI command to ATA device
849  *      @ap: ATA port to which the command is addressed
850  *      @dev: ATA device to which the command is addressed
851  *      @cmd: SCSI command to execute
852  *      @done: SCSI command completion function
853  *      @xlat_func: Actor which translates @cmd to an ATA taskfile
854  *
855  *      Our ->queuecommand() function has decided that the SCSI
856  *      command issued can be directly translated into an ATA
857  *      command, rather than handled internally.
858  *
859  *      This function sets up an ata_queued_cmd structure for the
860  *      SCSI command, and sends that ata_queued_cmd to the hardware.
861  *
862  *      LOCKING:
863  *      spin_lock_irqsave(host_set lock)
864  */
865
866 static void ata_scsi_translate(struct ata_port *ap, struct ata_device *dev,
867                               struct scsi_cmnd *cmd,
868                               void (*done)(struct scsi_cmnd *),
869                               ata_xlat_func_t xlat_func)
870 {
871         struct ata_queued_cmd *qc;
872         u8 *scsicmd = cmd->cmnd;
873
874         VPRINTK("ENTER\n");
875
876         qc = ata_scsi_qc_new(ap, dev, cmd, done);
877         if (!qc)
878                 return;
879
880         /* data is present; dma-map it */
881         if (cmd->sc_data_direction == DMA_FROM_DEVICE ||
882             cmd->sc_data_direction == DMA_TO_DEVICE) {
883                 if (unlikely(cmd->request_bufflen < 1)) {
884                         printk(KERN_WARNING "ata%u(%u): WARNING: zero len r/w req\n",
885                                ap->id, dev->devno);
886                         goto err_out;
887                 }
888
889                 if (cmd->use_sg)
890                         ata_sg_init(qc, cmd->request_buffer, cmd->use_sg);
891                 else
892                         ata_sg_init_one(qc, cmd->request_buffer,
893                                         cmd->request_bufflen);
894
895                 qc->dma_dir = cmd->sc_data_direction;
896         }
897
898         qc->complete_fn = ata_scsi_qc_complete;
899
900         if (xlat_func(qc, scsicmd))
901                 goto err_out;
902
903         /* select device, send command to hardware */
904         if (ata_qc_issue(qc))
905                 goto err_out;
906
907         VPRINTK("EXIT\n");
908         return;
909
910 err_out:
911         ata_qc_free(qc);
912         ata_bad_cdb(cmd, done);
913         DPRINTK("EXIT - badcmd\n");
914 }
915
916 /**
917  *      ata_scsi_rbuf_get - Map response buffer.
918  *      @cmd: SCSI command containing buffer to be mapped.
919  *      @buf_out: Pointer to mapped area.
920  *
921  *      Maps buffer contained within SCSI command @cmd.
922  *
923  *      LOCKING:
924  *      spin_lock_irqsave(host_set lock)
925  *
926  *      RETURNS:
927  *      Length of response buffer.
928  */
929
930 static unsigned int ata_scsi_rbuf_get(struct scsi_cmnd *cmd, u8 **buf_out)
931 {
932         u8 *buf;
933         unsigned int buflen;
934
935         if (cmd->use_sg) {
936                 struct scatterlist *sg;
937
938                 sg = (struct scatterlist *) cmd->request_buffer;
939                 buf = kmap_atomic(sg->page, KM_USER0) + sg->offset;
940                 buflen = sg->length;
941         } else {
942                 buf = cmd->request_buffer;
943                 buflen = cmd->request_bufflen;
944         }
945
946         *buf_out = buf;
947         return buflen;
948 }
949
950 /**
951  *      ata_scsi_rbuf_put - Unmap response buffer.
952  *      @cmd: SCSI command containing buffer to be unmapped.
953  *      @buf: buffer to unmap
954  *
955  *      Unmaps response buffer contained within @cmd.
956  *
957  *      LOCKING:
958  *      spin_lock_irqsave(host_set lock)
959  */
960
961 static inline void ata_scsi_rbuf_put(struct scsi_cmnd *cmd, u8 *buf)
962 {
963         if (cmd->use_sg) {
964                 struct scatterlist *sg;
965
966                 sg = (struct scatterlist *) cmd->request_buffer;
967                 kunmap_atomic(buf - sg->offset, KM_USER0);
968         }
969 }
970
971 /**
972  *      ata_scsi_rbuf_fill - wrapper for SCSI command simulators
973  *      @args: device IDENTIFY data / SCSI command of interest.
974  *      @actor: Callback hook for desired SCSI command simulator
975  *
976  *      Takes care of the hard work of simulating a SCSI command...
977  *      Mapping the response buffer, calling the command's handler,
978  *      and handling the handler's return value.  This return value
979  *      indicates whether the handler wishes the SCSI command to be
980  *      completed successfully, or not.
981  *
982  *      LOCKING:
983  *      spin_lock_irqsave(host_set lock)
984  */
985
986 void ata_scsi_rbuf_fill(struct ata_scsi_args *args,
987                         unsigned int (*actor) (struct ata_scsi_args *args,
988                                            u8 *rbuf, unsigned int buflen))
989 {
990         u8 *rbuf;
991         unsigned int buflen, rc;
992         struct scsi_cmnd *cmd = args->cmd;
993
994         buflen = ata_scsi_rbuf_get(cmd, &rbuf);
995         memset(rbuf, 0, buflen);
996         rc = actor(args, rbuf, buflen);
997         ata_scsi_rbuf_put(cmd, rbuf);
998
999         if (rc)
1000                 ata_bad_cdb(cmd, args->done);
1001         else {
1002                 cmd->result = SAM_STAT_GOOD;
1003                 args->done(cmd);
1004         }
1005 }
1006
1007 /**
1008  *      ata_scsiop_inq_std - Simulate INQUIRY command
1009  *      @args: device IDENTIFY data / SCSI command of interest.
1010  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
1011  *      @buflen: Response buffer length.
1012  *
1013  *      Returns standard device identification data associated
1014  *      with non-EVPD INQUIRY command output.
1015  *
1016  *      LOCKING:
1017  *      spin_lock_irqsave(host_set lock)
1018  */
1019
1020 unsigned int ata_scsiop_inq_std(struct ata_scsi_args *args, u8 *rbuf,
1021                                unsigned int buflen)
1022 {
1023         u8 hdr[] = {
1024                 TYPE_DISK,
1025                 0,
1026                 0x5,    /* claim SPC-3 version compatibility */
1027                 2,
1028                 95 - 4
1029         };
1030
1031         /* set scsi removeable (RMB) bit per ata bit */
1032         if (ata_id_removeable(args->id))
1033                 hdr[1] |= (1 << 7);
1034
1035         VPRINTK("ENTER\n");
1036
1037         memcpy(rbuf, hdr, sizeof(hdr));
1038
1039         if (buflen > 35) {
1040                 memcpy(&rbuf[8], "ATA     ", 8);
1041                 ata_dev_id_string(args->id, &rbuf[16], ATA_ID_PROD_OFS, 16);
1042                 ata_dev_id_string(args->id, &rbuf[32], ATA_ID_FW_REV_OFS, 4);
1043                 if (rbuf[32] == 0 || rbuf[32] == ' ')
1044                         memcpy(&rbuf[32], "n/a ", 4);
1045         }
1046
1047         if (buflen > 63) {
1048                 const u8 versions[] = {
1049                         0x60,   /* SAM-3 (no version claimed) */
1050
1051                         0x03,
1052                         0x20,   /* SBC-2 (no version claimed) */
1053
1054                         0x02,
1055                         0x60    /* SPC-3 (no version claimed) */
1056                 };
1057
1058                 memcpy(rbuf + 59, versions, sizeof(versions));
1059         }
1060
1061         return 0;
1062 }
1063
1064 /**
1065  *      ata_scsiop_inq_00 - Simulate INQUIRY EVPD page 0, list of pages
1066  *      @args: device IDENTIFY data / SCSI command of interest.
1067  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
1068  *      @buflen: Response buffer length.
1069  *
1070  *      Returns list of inquiry EVPD pages available.
1071  *
1072  *      LOCKING:
1073  *      spin_lock_irqsave(host_set lock)
1074  */
1075
1076 unsigned int ata_scsiop_inq_00(struct ata_scsi_args *args, u8 *rbuf,
1077                               unsigned int buflen)
1078 {
1079         const u8 pages[] = {
1080                 0x00,   /* page 0x00, this page */
1081                 0x80,   /* page 0x80, unit serial no page */
1082                 0x83    /* page 0x83, device ident page */
1083         };
1084         rbuf[3] = sizeof(pages);        /* number of supported EVPD pages */
1085
1086         if (buflen > 6)
1087                 memcpy(rbuf + 4, pages, sizeof(pages));
1088
1089         return 0;
1090 }
1091
1092 /**
1093  *      ata_scsiop_inq_80 - Simulate INQUIRY EVPD page 80, device serial number
1094  *      @args: device IDENTIFY data / SCSI command of interest.
1095  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
1096  *      @buflen: Response buffer length.
1097  *
1098  *      Returns ATA device serial number.
1099  *
1100  *      LOCKING:
1101  *      spin_lock_irqsave(host_set lock)
1102  */
1103
1104 unsigned int ata_scsiop_inq_80(struct ata_scsi_args *args, u8 *rbuf,
1105                               unsigned int buflen)
1106 {
1107         const u8 hdr[] = {
1108                 0,
1109                 0x80,                   /* this page code */
1110                 0,
1111                 ATA_SERNO_LEN,          /* page len */
1112         };
1113         memcpy(rbuf, hdr, sizeof(hdr));
1114
1115         if (buflen > (ATA_SERNO_LEN + 4 - 1))
1116                 ata_dev_id_string(args->id, (unsigned char *) &rbuf[4],
1117                                   ATA_ID_SERNO_OFS, ATA_SERNO_LEN);
1118
1119         return 0;
1120 }
1121
1122 static const char *inq_83_str = "Linux ATA-SCSI simulator";
1123
1124 /**
1125  *      ata_scsiop_inq_83 - Simulate INQUIRY EVPD page 83, device identity
1126  *      @args: device IDENTIFY data / SCSI command of interest.
1127  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
1128  *      @buflen: Response buffer length.
1129  *
1130  *      Returns device identification.  Currently hardcoded to
1131  *      return "Linux ATA-SCSI simulator".
1132  *
1133  *      LOCKING:
1134  *      spin_lock_irqsave(host_set lock)
1135  */
1136
1137 unsigned int ata_scsiop_inq_83(struct ata_scsi_args *args, u8 *rbuf,
1138                               unsigned int buflen)
1139 {
1140         rbuf[1] = 0x83;                 /* this page code */
1141         rbuf[3] = 4 + strlen(inq_83_str);       /* page len */
1142
1143         /* our one and only identification descriptor (vendor-specific) */
1144         if (buflen > (strlen(inq_83_str) + 4 + 4 - 1)) {
1145                 rbuf[4 + 0] = 2;        /* code set: ASCII */
1146                 rbuf[4 + 3] = strlen(inq_83_str);
1147                 memcpy(rbuf + 4 + 4, inq_83_str, strlen(inq_83_str));
1148         }
1149
1150         return 0;
1151 }
1152
1153 /**
1154  *      ata_scsiop_noop - Command handler that simply returns success.
1155  *      @args: device IDENTIFY data / SCSI command of interest.
1156  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
1157  *      @buflen: Response buffer length.
1158  *
1159  *      No operation.  Simply returns success to caller, to indicate
1160  *      that the caller should successfully complete this SCSI command.
1161  *
1162  *      LOCKING:
1163  *      spin_lock_irqsave(host_set lock)
1164  */
1165
1166 unsigned int ata_scsiop_noop(struct ata_scsi_args *args, u8 *rbuf,
1167                             unsigned int buflen)
1168 {
1169         VPRINTK("ENTER\n");
1170         return 0;
1171 }
1172
1173 /**
1174  *      ata_msense_push - Push data onto MODE SENSE data output buffer
1175  *      @ptr_io: (input/output) Location to store more output data
1176  *      @last: End of output data buffer
1177  *      @buf: Pointer to BLOB being added to output buffer
1178  *      @buflen: Length of BLOB
1179  *
1180  *      Store MODE SENSE data on an output buffer.
1181  *
1182  *      LOCKING:
1183  *      None.
1184  */
1185
1186 static void ata_msense_push(u8 **ptr_io, const u8 *last,
1187                             const u8 *buf, unsigned int buflen)
1188 {
1189         u8 *ptr = *ptr_io;
1190
1191         if ((ptr + buflen - 1) > last)
1192                 return;
1193
1194         memcpy(ptr, buf, buflen);
1195
1196         ptr += buflen;
1197
1198         *ptr_io = ptr;
1199 }
1200
1201 /**
1202  *      ata_msense_caching - Simulate MODE SENSE caching info page
1203  *      @id: device IDENTIFY data
1204  *      @ptr_io: (input/output) Location to store more output data
1205  *      @last: End of output data buffer
1206  *
1207  *      Generate a caching info page, which conditionally indicates
1208  *      write caching to the SCSI layer, depending on device
1209  *      capabilities.
1210  *
1211  *      LOCKING:
1212  *      None.
1213  */
1214
1215 static unsigned int ata_msense_caching(u16 *id, u8 **ptr_io,
1216                                        const u8 *last)
1217 {
1218         u8 page[] = {
1219                 0x8,                            /* page code */
1220                 0x12,                           /* page length */
1221                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   /* 10 zeroes */
1222                 0, 0, 0, 0, 0, 0, 0, 0          /* 8 zeroes */
1223         };
1224
1225         if (ata_id_wcache_enabled(id))
1226                 page[2] |= (1 << 2);    /* write cache enable */
1227         if (!ata_id_rahead_enabled(id))
1228                 page[12] |= (1 << 5);   /* disable read ahead */
1229
1230         ata_msense_push(ptr_io, last, page, sizeof(page));
1231         return sizeof(page);
1232 }
1233
1234 /**
1235  *      ata_msense_ctl_mode - Simulate MODE SENSE control mode page
1236  *      @dev: Device associated with this MODE SENSE command
1237  *      @ptr_io: (input/output) Location to store more output data
1238  *      @last: End of output data buffer
1239  *
1240  *      Generate a generic MODE SENSE control mode page.
1241  *
1242  *      LOCKING:
1243  *      None.
1244  */
1245
1246 static unsigned int ata_msense_ctl_mode(u8 **ptr_io, const u8 *last)
1247 {
1248         const u8 page[] = {0xa, 0xa, 6, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 30};
1249
1250         /* byte 2: set the descriptor format sense data bit (bit 2)
1251          * since we need to support returning this format for SAT
1252          * commands and any SCSI commands against a 48b LBA device.
1253          */
1254
1255         ata_msense_push(ptr_io, last, page, sizeof(page));
1256         return sizeof(page);
1257 }
1258
1259 /**
1260  *      ata_msense_rw_recovery - Simulate MODE SENSE r/w error recovery page
1261  *      @dev: Device associated with this MODE SENSE command
1262  *      @ptr_io: (input/output) Location to store more output data
1263  *      @last: End of output data buffer
1264  *
1265  *      Generate a generic MODE SENSE r/w error recovery page.
1266  *
1267  *      LOCKING:
1268  *      None.
1269  */
1270
1271 static unsigned int ata_msense_rw_recovery(u8 **ptr_io, const u8 *last)
1272 {
1273         const u8 page[] = {
1274                 0x1,                      /* page code */
1275                 0xa,                      /* page length */
1276                 (1 << 7) | (1 << 6),      /* note auto r/w reallocation */
1277                 0, 0, 0, 0, 0, 0, 0, 0, 0 /* 9 zeroes */
1278         };
1279
1280         ata_msense_push(ptr_io, last, page, sizeof(page));
1281         return sizeof(page);
1282 }
1283
1284 /**
1285  *      ata_scsiop_mode_sense - Simulate MODE SENSE 6, 10 commands
1286  *      @args: device IDENTIFY data / SCSI command of interest.
1287  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
1288  *      @buflen: Response buffer length.
1289  *
1290  *      Simulate MODE SENSE commands.
1291  *
1292  *      LOCKING:
1293  *      spin_lock_irqsave(host_set lock)
1294  */
1295
1296 unsigned int ata_scsiop_mode_sense(struct ata_scsi_args *args, u8 *rbuf,
1297                                   unsigned int buflen)
1298 {
1299         u8 *scsicmd = args->cmd->cmnd, *p, *last;
1300         unsigned int page_control, six_byte, output_len;
1301
1302         VPRINTK("ENTER\n");
1303
1304         six_byte = (scsicmd[0] == MODE_SENSE);
1305
1306         /* we only support saved and current values (which we treat
1307          * in the same manner)
1308          */
1309         page_control = scsicmd[2] >> 6;
1310         if ((page_control != 0) && (page_control != 3))
1311                 return 1;
1312
1313         if (six_byte)
1314                 output_len = 4;
1315         else
1316                 output_len = 8;
1317
1318         p = rbuf + output_len;
1319         last = rbuf + buflen - 1;
1320
1321         switch(scsicmd[2] & 0x3f) {
1322         case 0x01:              /* r/w error recovery */
1323                 output_len += ata_msense_rw_recovery(&p, last);
1324                 break;
1325
1326         case 0x08:              /* caching */
1327                 output_len += ata_msense_caching(args->id, &p, last);
1328                 break;
1329
1330         case 0x0a: {            /* control mode */
1331                 output_len += ata_msense_ctl_mode(&p, last);
1332                 break;
1333                 }
1334
1335         case 0x3f:              /* all pages */
1336                 output_len += ata_msense_rw_recovery(&p, last);
1337                 output_len += ata_msense_caching(args->id, &p, last);
1338                 output_len += ata_msense_ctl_mode(&p, last);
1339                 break;
1340
1341         default:                /* invalid page code */
1342                 return 1;
1343         }
1344
1345         if (six_byte) {
1346                 output_len--;
1347                 rbuf[0] = output_len;
1348         } else {
1349                 output_len -= 2;
1350                 rbuf[0] = output_len >> 8;
1351                 rbuf[1] = output_len;
1352         }
1353
1354         return 0;
1355 }
1356
1357 /**
1358  *      ata_scsiop_read_cap - Simulate READ CAPACITY[ 16] commands
1359  *      @args: device IDENTIFY data / SCSI command of interest.
1360  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
1361  *      @buflen: Response buffer length.
1362  *
1363  *      Simulate READ CAPACITY commands.
1364  *
1365  *      LOCKING:
1366  *      spin_lock_irqsave(host_set lock)
1367  */
1368
1369 unsigned int ata_scsiop_read_cap(struct ata_scsi_args *args, u8 *rbuf,
1370                                 unsigned int buflen)
1371 {
1372         u64 n_sectors;
1373         u32 tmp;
1374
1375         VPRINTK("ENTER\n");
1376
1377         if (ata_id_has_lba(args->id)) {
1378                 if (ata_id_has_lba48(args->id))
1379                         n_sectors = ata_id_u64(args->id, 100);
1380                 else
1381                         n_sectors = ata_id_u32(args->id, 60);
1382         } else {
1383                 /* CHS default translation */
1384                 n_sectors = args->id[1] * args->id[3] * args->id[6];
1385
1386                 if (ata_id_current_chs_valid(args->id))
1387                         /* CHS current translation */
1388                         n_sectors = ata_id_u32(args->id, 57);
1389         }
1390
1391         n_sectors--;            /* ATA TotalUserSectors - 1 */
1392
1393         if (args->cmd->cmnd[0] == READ_CAPACITY) {
1394                 if( n_sectors >= 0xffffffffULL )
1395                         tmp = 0xffffffff ;  /* Return max count on overflow */
1396                 else
1397                         tmp = n_sectors ;
1398
1399                 /* sector count, 32-bit */
1400                 rbuf[0] = tmp >> (8 * 3);
1401                 rbuf[1] = tmp >> (8 * 2);
1402                 rbuf[2] = tmp >> (8 * 1);
1403                 rbuf[3] = tmp;
1404
1405                 /* sector size */
1406                 tmp = ATA_SECT_SIZE;
1407                 rbuf[6] = tmp >> 8;
1408                 rbuf[7] = tmp;
1409
1410         } else {
1411                 /* sector count, 64-bit */
1412                 tmp = n_sectors >> (8 * 4);
1413                 rbuf[2] = tmp >> (8 * 3);
1414                 rbuf[3] = tmp >> (8 * 2);
1415                 rbuf[4] = tmp >> (8 * 1);
1416                 rbuf[5] = tmp;
1417                 tmp = n_sectors;
1418                 rbuf[6] = tmp >> (8 * 3);
1419                 rbuf[7] = tmp >> (8 * 2);
1420                 rbuf[8] = tmp >> (8 * 1);
1421                 rbuf[9] = tmp;
1422
1423                 /* sector size */
1424                 tmp = ATA_SECT_SIZE;
1425                 rbuf[12] = tmp >> 8;
1426                 rbuf[13] = tmp;
1427         }
1428
1429         return 0;
1430 }
1431
1432 /**
1433  *      ata_scsiop_report_luns - Simulate REPORT LUNS command
1434  *      @args: device IDENTIFY data / SCSI command of interest.
1435  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
1436  *      @buflen: Response buffer length.
1437  *
1438  *      Simulate REPORT LUNS command.
1439  *
1440  *      LOCKING:
1441  *      spin_lock_irqsave(host_set lock)
1442  */
1443
1444 unsigned int ata_scsiop_report_luns(struct ata_scsi_args *args, u8 *rbuf,
1445                                    unsigned int buflen)
1446 {
1447         VPRINTK("ENTER\n");
1448         rbuf[3] = 8;    /* just one lun, LUN 0, size 8 bytes */
1449
1450         return 0;
1451 }
1452
1453 /**
1454  *      ata_scsi_badcmd - End a SCSI request with an error
1455  *      @cmd: SCSI request to be handled
1456  *      @done: SCSI command completion function
1457  *      @asc: SCSI-defined additional sense code
1458  *      @ascq: SCSI-defined additional sense code qualifier
1459  *
1460  *      Helper function that completes a SCSI command with
1461  *      %SAM_STAT_CHECK_CONDITION, with a sense key %ILLEGAL_REQUEST
1462  *      and the specified additional sense codes.
1463  *
1464  *      LOCKING:
1465  *      spin_lock_irqsave(host_set lock)
1466  */
1467
1468 void ata_scsi_badcmd(struct scsi_cmnd *cmd, void (*done)(struct scsi_cmnd *), u8 asc, u8 ascq)
1469 {
1470         DPRINTK("ENTER\n");
1471         cmd->result = SAM_STAT_CHECK_CONDITION;
1472
1473         cmd->sense_buffer[0] = 0x70;
1474         cmd->sense_buffer[2] = ILLEGAL_REQUEST;
1475         cmd->sense_buffer[7] = 14 - 8;  /* addnl. sense len. FIXME: correct? */
1476         cmd->sense_buffer[12] = asc;
1477         cmd->sense_buffer[13] = ascq;
1478
1479         done(cmd);
1480 }
1481
1482 static int atapi_qc_complete(struct ata_queued_cmd *qc, u8 drv_stat)
1483 {
1484         struct scsi_cmnd *cmd = qc->scsicmd;
1485
1486         if (unlikely(drv_stat & (ATA_ERR | ATA_BUSY | ATA_DRQ))) {
1487                 DPRINTK("request check condition\n");
1488
1489                 cmd->result = SAM_STAT_CHECK_CONDITION;
1490
1491                 qc->scsidone(cmd);
1492
1493                 return 1;
1494         } else {
1495                 u8 *scsicmd = cmd->cmnd;
1496
1497                 if (scsicmd[0] == INQUIRY) {
1498                         u8 *buf = NULL;
1499                         unsigned int buflen;
1500
1501                         buflen = ata_scsi_rbuf_get(cmd, &buf);
1502                         buf[2] = 0x5;
1503                         buf[3] = (buf[3] & 0xf0) | 2;
1504                         ata_scsi_rbuf_put(cmd, buf);
1505                 }
1506                 cmd->result = SAM_STAT_GOOD;
1507         }
1508
1509         qc->scsidone(cmd);
1510
1511         return 0;
1512 }
1513 /**
1514  *      atapi_xlat - Initialize PACKET taskfile
1515  *      @qc: command structure to be initialized
1516  *      @scsicmd: SCSI CDB associated with this PACKET command
1517  *
1518  *      LOCKING:
1519  *      spin_lock_irqsave(host_set lock)
1520  *
1521  *      RETURNS:
1522  *      Zero on success, non-zero on failure.
1523  */
1524
1525 static unsigned int atapi_xlat(struct ata_queued_cmd *qc, u8 *scsicmd)
1526 {
1527         struct scsi_cmnd *cmd = qc->scsicmd;
1528         struct ata_device *dev = qc->dev;
1529         int using_pio = (dev->flags & ATA_DFLAG_PIO);
1530         int nodata = (cmd->sc_data_direction == DMA_NONE);
1531
1532         if (!using_pio)
1533                 /* Check whether ATAPI DMA is safe */
1534                 if (ata_check_atapi_dma(qc))
1535                         using_pio = 1;
1536
1537         memcpy(&qc->cdb, scsicmd, qc->ap->cdb_len);
1538
1539         qc->complete_fn = atapi_qc_complete;
1540
1541         qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1542         if (cmd->sc_data_direction == DMA_TO_DEVICE) {
1543                 qc->tf.flags |= ATA_TFLAG_WRITE;
1544                 DPRINTK("direction: write\n");
1545         }
1546
1547         qc->tf.command = ATA_CMD_PACKET;
1548
1549         /* no data, or PIO data xfer */
1550         if (using_pio || nodata) {
1551                 if (nodata)
1552                         qc->tf.protocol = ATA_PROT_ATAPI_NODATA;
1553                 else
1554                         qc->tf.protocol = ATA_PROT_ATAPI;
1555                 qc->tf.lbam = (8 * 1024) & 0xff;
1556                 qc->tf.lbah = (8 * 1024) >> 8;
1557         }
1558
1559         /* DMA data xfer */
1560         else {
1561                 qc->tf.protocol = ATA_PROT_ATAPI_DMA;
1562                 qc->tf.feature |= ATAPI_PKT_DMA;
1563
1564 #ifdef ATAPI_ENABLE_DMADIR
1565                 /* some SATA bridges need us to indicate data xfer direction */
1566                 if (cmd->sc_data_direction != DMA_TO_DEVICE)
1567                         qc->tf.feature |= ATAPI_DMADIR;
1568 #endif
1569         }
1570
1571         qc->nbytes = cmd->bufflen;
1572
1573         return 0;
1574 }
1575
1576 /**
1577  *      ata_scsi_find_dev - lookup ata_device from scsi_cmnd
1578  *      @ap: ATA port to which the device is attached
1579  *      @scsidev: SCSI device from which we derive the ATA device
1580  *
1581  *      Given various information provided in struct scsi_cmnd,
1582  *      map that onto an ATA bus, and using that mapping
1583  *      determine which ata_device is associated with the
1584  *      SCSI command to be sent.
1585  *
1586  *      LOCKING:
1587  *      spin_lock_irqsave(host_set lock)
1588  *
1589  *      RETURNS:
1590  *      Associated ATA device, or %NULL if not found.
1591  */
1592
1593 static struct ata_device *
1594 ata_scsi_find_dev(struct ata_port *ap, struct scsi_device *scsidev)
1595 {
1596         struct ata_device *dev;
1597
1598         /* skip commands not addressed to targets we simulate */
1599         if (likely(scsidev->id < ATA_MAX_DEVICES))
1600                 dev = &ap->device[scsidev->id];
1601         else
1602                 return NULL;
1603
1604         if (unlikely((scsidev->channel != 0) ||
1605                      (scsidev->lun != 0)))
1606                 return NULL;
1607
1608         if (unlikely(!ata_dev_present(dev)))
1609                 return NULL;
1610
1611         if (!atapi_enabled) {
1612                 if (unlikely(dev->class == ATA_DEV_ATAPI))
1613                         return NULL;
1614         }
1615
1616         return dev;
1617 }
1618
1619 /**
1620  *      ata_get_xlat_func - check if SCSI to ATA translation is possible
1621  *      @dev: ATA device
1622  *      @cmd: SCSI command opcode to consider
1623  *
1624  *      Look up the SCSI command given, and determine whether the
1625  *      SCSI command is to be translated or simulated.
1626  *
1627  *      RETURNS:
1628  *      Pointer to translation function if possible, %NULL if not.
1629  */
1630
1631 static inline ata_xlat_func_t ata_get_xlat_func(struct ata_device *dev, u8 cmd)
1632 {
1633         switch (cmd) {
1634         case READ_6:
1635         case READ_10:
1636         case READ_16:
1637
1638         case WRITE_6:
1639         case WRITE_10:
1640         case WRITE_16:
1641                 return ata_scsi_rw_xlat;
1642
1643         case SYNCHRONIZE_CACHE:
1644                 if (ata_try_flush_cache(dev))
1645                         return ata_scsi_flush_xlat;
1646                 break;
1647
1648         case VERIFY:
1649         case VERIFY_16:
1650                 return ata_scsi_verify_xlat;
1651         case START_STOP:
1652                 return ata_scsi_start_stop_xlat;
1653         }
1654
1655         return NULL;
1656 }
1657
1658 /**
1659  *      ata_scsi_dump_cdb - dump SCSI command contents to dmesg
1660  *      @ap: ATA port to which the command was being sent
1661  *      @cmd: SCSI command to dump
1662  *
1663  *      Prints the contents of a SCSI command via printk().
1664  */
1665
1666 static inline void ata_scsi_dump_cdb(struct ata_port *ap,
1667                                      struct scsi_cmnd *cmd)
1668 {
1669 #ifdef ATA_DEBUG
1670         struct scsi_device *scsidev = cmd->device;
1671         u8 *scsicmd = cmd->cmnd;
1672
1673         DPRINTK("CDB (%u:%d,%d,%d) %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
1674                 ap->id,
1675                 scsidev->channel, scsidev->id, scsidev->lun,
1676                 scsicmd[0], scsicmd[1], scsicmd[2], scsicmd[3],
1677                 scsicmd[4], scsicmd[5], scsicmd[6], scsicmd[7],
1678                 scsicmd[8]);
1679 #endif
1680 }
1681
1682 /**
1683  *      ata_scsi_queuecmd - Issue SCSI cdb to libata-managed device
1684  *      @cmd: SCSI command to be sent
1685  *      @done: Completion function, called when command is complete
1686  *
1687  *      In some cases, this function translates SCSI commands into
1688  *      ATA taskfiles, and queues the taskfiles to be sent to
1689  *      hardware.  In other cases, this function simulates a
1690  *      SCSI device by evaluating and responding to certain
1691  *      SCSI commands.  This creates the overall effect of
1692  *      ATA and ATAPI devices appearing as SCSI devices.
1693  *
1694  *      LOCKING:
1695  *      Releases scsi-layer-held lock, and obtains host_set lock.
1696  *
1697  *      RETURNS:
1698  *      Zero.
1699  */
1700
1701 int ata_scsi_queuecmd(struct scsi_cmnd *cmd, void (*done)(struct scsi_cmnd *))
1702 {
1703         struct ata_port *ap;
1704         struct ata_device *dev;
1705         struct scsi_device *scsidev = cmd->device;
1706
1707         ap = (struct ata_port *) &scsidev->host->hostdata[0];
1708
1709         ata_scsi_dump_cdb(ap, cmd);
1710
1711         dev = ata_scsi_find_dev(ap, scsidev);
1712         if (unlikely(!dev)) {
1713                 cmd->result = (DID_BAD_TARGET << 16);
1714                 done(cmd);
1715                 goto out_unlock;
1716         }
1717
1718         if (dev->class == ATA_DEV_ATA) {
1719                 ata_xlat_func_t xlat_func = ata_get_xlat_func(dev,
1720                                                               cmd->cmnd[0]);
1721
1722                 if (xlat_func)
1723                         ata_scsi_translate(ap, dev, cmd, done, xlat_func);
1724                 else
1725                         ata_scsi_simulate(dev->id, cmd, done);
1726         } else
1727                 ata_scsi_translate(ap, dev, cmd, done, atapi_xlat);
1728
1729 out_unlock:
1730         return 0;
1731 }
1732
1733 /**
1734  *      ata_scsi_simulate - simulate SCSI command on ATA device
1735  *      @id: current IDENTIFY data for target device.
1736  *      @cmd: SCSI command being sent to device.
1737  *      @done: SCSI command completion function.
1738  *
1739  *      Interprets and directly executes a select list of SCSI commands
1740  *      that can be handled internally.
1741  *
1742  *      LOCKING:
1743  *      spin_lock_irqsave(host_set lock)
1744  */
1745
1746 void ata_scsi_simulate(u16 *id,
1747                       struct scsi_cmnd *cmd,
1748                       void (*done)(struct scsi_cmnd *))
1749 {
1750         struct ata_scsi_args args;
1751         u8 *scsicmd = cmd->cmnd;
1752
1753         args.id = id;
1754         args.cmd = cmd;
1755         args.done = done;
1756
1757         switch(scsicmd[0]) {
1758                 /* no-op's, complete with success */
1759                 case SYNCHRONIZE_CACHE:
1760                 case REZERO_UNIT:
1761                 case SEEK_6:
1762                 case SEEK_10:
1763                 case TEST_UNIT_READY:
1764                 case FORMAT_UNIT:               /* FIXME: correct? */
1765                 case SEND_DIAGNOSTIC:           /* FIXME: correct? */
1766                         ata_scsi_rbuf_fill(&args, ata_scsiop_noop);
1767                         break;
1768
1769                 case INQUIRY:
1770                         if (scsicmd[1] & 2)                /* is CmdDt set?  */
1771                                 ata_bad_cdb(cmd, done);
1772                         else if ((scsicmd[1] & 1) == 0)    /* is EVPD clear? */
1773                                 ata_scsi_rbuf_fill(&args, ata_scsiop_inq_std);
1774                         else if (scsicmd[2] == 0x00)
1775                                 ata_scsi_rbuf_fill(&args, ata_scsiop_inq_00);
1776                         else if (scsicmd[2] == 0x80)
1777                                 ata_scsi_rbuf_fill(&args, ata_scsiop_inq_80);
1778                         else if (scsicmd[2] == 0x83)
1779                                 ata_scsi_rbuf_fill(&args, ata_scsiop_inq_83);
1780                         else
1781                                 ata_bad_cdb(cmd, done);
1782                         break;
1783
1784                 case MODE_SENSE:
1785                 case MODE_SENSE_10:
1786                         ata_scsi_rbuf_fill(&args, ata_scsiop_mode_sense);
1787                         break;
1788
1789                 case MODE_SELECT:       /* unconditionally return */
1790                 case MODE_SELECT_10:    /* bad-field-in-cdb */
1791                         ata_bad_cdb(cmd, done);
1792                         break;
1793
1794                 case READ_CAPACITY:
1795                         ata_scsi_rbuf_fill(&args, ata_scsiop_read_cap);
1796                         break;
1797
1798                 case SERVICE_ACTION_IN:
1799                         if ((scsicmd[1] & 0x1f) == SAI_READ_CAPACITY_16)
1800                                 ata_scsi_rbuf_fill(&args, ata_scsiop_read_cap);
1801                         else
1802                                 ata_bad_cdb(cmd, done);
1803                         break;
1804
1805                 case REPORT_LUNS:
1806                         ata_scsi_rbuf_fill(&args, ata_scsiop_report_luns);
1807                         break;
1808
1809                 /* mandantory commands we haven't implemented yet */
1810                 case REQUEST_SENSE:
1811
1812                 /* all other commands */
1813                 default:
1814                         ata_bad_scsiop(cmd, done);
1815                         break;
1816         }
1817 }
1818