ide-cd: move lba_to_msf() and msf_to_lba() to <linux/cdrom.h>
[linux-2.6.git] / drivers / ide / ide-cd.c
1 /*
2  * linux/drivers/ide/ide-cd.c
3  *
4  * Copyright (C) 1994, 1995, 1996  scott snyder  <snyder@fnald0.fnal.gov>
5  * Copyright (C) 1996-1998  Erik Andersen <andersee@debian.org>
6  * Copyright (C) 1998-2000  Jens Axboe <axboe@suse.de>
7  *
8  * May be copied or modified under the terms of the GNU General Public
9  * License.  See linux/COPYING for more information.
10  *
11  * ATAPI CD-ROM driver.  To be used with ide.c.
12  * See Documentation/cdrom/ide-cd for usage information.
13  *
14  * Suggestions are welcome. Patches that work are more welcome though. ;-)
15  * For those wishing to work on this driver, please be sure you download
16  * and comply with the latest Mt. Fuji (SFF8090 version 4) and ATAPI 
17  * (SFF-8020i rev 2.6) standards. These documents can be obtained by 
18  * anonymous ftp from:
19  * ftp://fission.dt.wdc.com/pub/standards/SFF_atapi/spec/SFF8020-r2.6/PS/8020r26.ps
20  * ftp://ftp.avc-pioneer.com/Mtfuji4/Spec/Fuji4r10.pdf
21  *
22  * Drives that deviate from these standards will be accommodated as much
23  * as possible via compile time or command-line options.  Since I only have
24  * a few drives, you generally need to send me patches...
25  *
26  * ----------------------------------
27  * TO DO LIST:
28  * -Make it so that Pioneer CD DR-A24X and friends don't get screwed up on
29  *   boot
30  *
31  * For historical changelog please see:
32  *      Documentation/ide/ChangeLog.ide-cd.1994-2004
33  */
34
35 #define IDECD_VERSION "4.61"
36
37 #include <linux/module.h>
38 #include <linux/types.h>
39 #include <linux/kernel.h>
40 #include <linux/delay.h>
41 #include <linux/timer.h>
42 #include <linux/slab.h>
43 #include <linux/interrupt.h>
44 #include <linux/errno.h>
45 #include <linux/cdrom.h>
46 #include <linux/ide.h>
47 #include <linux/completion.h>
48 #include <linux/mutex.h>
49 #include <linux/bcd.h>
50
51 #include <scsi/scsi.h>  /* For SCSI -> ATAPI command conversion */
52
53 #include <asm/irq.h>
54 #include <asm/io.h>
55 #include <asm/byteorder.h>
56 #include <asm/uaccess.h>
57 #include <asm/unaligned.h>
58
59 #include "ide-cd.h"
60
61 static DEFINE_MUTEX(idecd_ref_mutex);
62
63 #define to_ide_cd(obj) container_of(obj, struct cdrom_info, kref) 
64
65 #define ide_cd_g(disk) \
66         container_of((disk)->private_data, struct cdrom_info, driver)
67
68 static struct cdrom_info *ide_cd_get(struct gendisk *disk)
69 {
70         struct cdrom_info *cd = NULL;
71
72         mutex_lock(&idecd_ref_mutex);
73         cd = ide_cd_g(disk);
74         if (cd)
75                 kref_get(&cd->kref);
76         mutex_unlock(&idecd_ref_mutex);
77         return cd;
78 }
79
80 static void ide_cd_release(struct kref *);
81
82 static void ide_cd_put(struct cdrom_info *cd)
83 {
84         mutex_lock(&idecd_ref_mutex);
85         kref_put(&cd->kref, ide_cd_release);
86         mutex_unlock(&idecd_ref_mutex);
87 }
88
89 /****************************************************************************
90  * Generic packet command support and error handling routines.
91  */
92
93 /* Mark that we've seen a media change, and invalidate our internal
94    buffers. */
95 static void cdrom_saw_media_change (ide_drive_t *drive)
96 {
97         struct cdrom_info *cd = drive->driver_data;
98
99         cd->cd_flags |= IDE_CD_FLAG_MEDIA_CHANGED;
100         cd->cd_flags &= ~IDE_CD_FLAG_TOC_VALID;
101         cd->nsectors_buffered = 0;
102 }
103
104 static int cdrom_log_sense(ide_drive_t *drive, struct request *rq,
105                            struct request_sense *sense)
106 {
107         int log = 0;
108
109         if (!sense || !rq || (rq->cmd_flags & REQ_QUIET))
110                 return 0;
111
112         switch (sense->sense_key) {
113                 case NO_SENSE: case RECOVERED_ERROR:
114                         break;
115                 case NOT_READY:
116                         /*
117                          * don't care about tray state messages for
118                          * e.g. capacity commands or in-progress or
119                          * becoming ready
120                          */
121                         if (sense->asc == 0x3a || sense->asc == 0x04)
122                                 break;
123                         log = 1;
124                         break;
125                 case ILLEGAL_REQUEST:
126                         /*
127                          * don't log START_STOP unit with LoEj set, since
128                          * we cannot reliably check if drive can auto-close
129                          */
130                         if (rq->cmd[0] == GPCMD_START_STOP_UNIT && sense->asc == 0x24)
131                                 break;
132                         log = 1;
133                         break;
134                 case UNIT_ATTENTION:
135                         /*
136                          * Make good and sure we've seen this potential media
137                          * change. Some drives (i.e. Creative) fail to present
138                          * the correct sense key in the error register.
139                          */
140                         cdrom_saw_media_change(drive);
141                         break;
142                 default:
143                         log = 1;
144                         break;
145         }
146         return log;
147 }
148
149 static
150 void cdrom_analyze_sense_data(ide_drive_t *drive,
151                               struct request *failed_command,
152                               struct request_sense *sense)
153 {
154         unsigned long sector;
155         unsigned long bio_sectors;
156         unsigned long valid;
157         struct cdrom_info *info = drive->driver_data;
158
159         if (!cdrom_log_sense(drive, failed_command, sense))
160                 return;
161
162         /*
163          * If a read toc is executed for a CD-R or CD-RW medium where
164          * the first toc has not been recorded yet, it will fail with
165          * 05/24/00 (which is a confusing error)
166          */
167         if (failed_command && failed_command->cmd[0] == GPCMD_READ_TOC_PMA_ATIP)
168                 if (sense->sense_key == 0x05 && sense->asc == 0x24)
169                         return;
170
171         if (sense->error_code == 0x70) {        /* Current Error */
172                 switch(sense->sense_key) {
173                 case MEDIUM_ERROR:
174                 case VOLUME_OVERFLOW:
175                 case ILLEGAL_REQUEST:
176                         if (!sense->valid)
177                                 break;
178                         if (failed_command == NULL ||
179                                         !blk_fs_request(failed_command))
180                                 break;
181                         sector = (sense->information[0] << 24) |
182                                  (sense->information[1] << 16) |
183                                  (sense->information[2] <<  8) |
184                                  (sense->information[3]);
185
186                         bio_sectors = bio_sectors(failed_command->bio);
187                         if (bio_sectors < 4)
188                                 bio_sectors = 4;
189                         if (drive->queue->hardsect_size == 2048)
190                                 sector <<= 2;   /* Device sector size is 2K */
191                         sector &= ~(bio_sectors -1);
192                         valid = (sector - failed_command->sector) << 9;
193
194                         if (valid < 0)
195                                 valid = 0;
196                         if (sector < get_capacity(info->disk) &&
197                                 drive->probed_capacity - sector < 4 * 75) {
198                                 set_capacity(info->disk, sector);
199                         }
200                 }
201         }
202
203         ide_cd_log_error(drive->name, failed_command, sense);
204 }
205
206 /*
207  * Initialize a ide-cd packet command request
208  */
209 static void cdrom_prepare_request(ide_drive_t *drive, struct request *rq)
210 {
211         struct cdrom_info *cd = drive->driver_data;
212
213         ide_init_drive_cmd(rq);
214         rq->cmd_type = REQ_TYPE_ATA_PC;
215         rq->rq_disk = cd->disk;
216 }
217
218 static void cdrom_queue_request_sense(ide_drive_t *drive, void *sense,
219                                       struct request *failed_command)
220 {
221         struct cdrom_info *info         = drive->driver_data;
222         struct request *rq              = &info->request_sense_request;
223
224         if (sense == NULL)
225                 sense = &info->sense_data;
226
227         /* stuff the sense request in front of our current request */
228         cdrom_prepare_request(drive, rq);
229
230         rq->data = sense;
231         rq->cmd[0] = GPCMD_REQUEST_SENSE;
232         rq->cmd[4] = rq->data_len = 18;
233
234         rq->cmd_type = REQ_TYPE_SENSE;
235
236         /* NOTE! Save the failed command in "rq->buffer" */
237         rq->buffer = (void *) failed_command;
238
239         (void) ide_do_drive_cmd(drive, rq, ide_preempt);
240 }
241
242 static void cdrom_end_request (ide_drive_t *drive, int uptodate)
243 {
244         struct request *rq = HWGROUP(drive)->rq;
245         int nsectors = rq->hard_cur_sectors;
246
247         if (blk_sense_request(rq) && uptodate) {
248                 /*
249                  * For REQ_TYPE_SENSE, "rq->buffer" points to the original
250                  * failed request
251                  */
252                 struct request *failed = (struct request *) rq->buffer;
253                 struct cdrom_info *info = drive->driver_data;
254                 void *sense = &info->sense_data;
255                 unsigned long flags;
256
257                 if (failed) {
258                         if (failed->sense) {
259                                 sense = failed->sense;
260                                 failed->sense_len = rq->sense_len;
261                         }
262                         cdrom_analyze_sense_data(drive, failed, sense);
263                         /*
264                          * now end failed request
265                          */
266                         if (blk_fs_request(failed)) {
267                                 if (ide_end_dequeued_request(drive, failed, 0,
268                                                 failed->hard_nr_sectors))
269                                         BUG();
270                         } else {
271                                 spin_lock_irqsave(&ide_lock, flags);
272                                 if (__blk_end_request(failed, -EIO,
273                                                       failed->data_len))
274                                         BUG();
275                                 spin_unlock_irqrestore(&ide_lock, flags);
276                         }
277                 } else
278                         cdrom_analyze_sense_data(drive, NULL, sense);
279         }
280
281         if (!rq->current_nr_sectors && blk_fs_request(rq))
282                 uptodate = 1;
283         /* make sure it's fully ended */
284         if (blk_pc_request(rq))
285                 nsectors = (rq->data_len + 511) >> 9;
286         if (!nsectors)
287                 nsectors = 1;
288
289         ide_end_request(drive, uptodate, nsectors);
290 }
291
292 static void ide_dump_status_no_sense(ide_drive_t *drive, const char *msg, u8 stat)
293 {
294         if (stat & 0x80)
295                 return;
296         ide_dump_status(drive, msg, stat);
297 }
298
299 /* Returns 0 if the request should be continued.
300    Returns 1 if the request was ended. */
301 static int cdrom_decode_status(ide_drive_t *drive, int good_stat, int *stat_ret)
302 {
303         struct request *rq = HWGROUP(drive)->rq;
304         int stat, err, sense_key;
305         
306         /* Check for errors. */
307         stat = HWIF(drive)->INB(IDE_STATUS_REG);
308         if (stat_ret)
309                 *stat_ret = stat;
310
311         if (OK_STAT(stat, good_stat, BAD_R_STAT))
312                 return 0;
313
314         /* Get the IDE error register. */
315         err = HWIF(drive)->INB(IDE_ERROR_REG);
316         sense_key = err >> 4;
317
318         if (rq == NULL) {
319                 printk("%s: missing rq in cdrom_decode_status\n", drive->name);
320                 return 1;
321         }
322
323         if (blk_sense_request(rq)) {
324                 /* We got an error trying to get sense info
325                    from the drive (probably while trying
326                    to recover from a former error).  Just give up. */
327
328                 rq->cmd_flags |= REQ_FAILED;
329                 cdrom_end_request(drive, 0);
330                 ide_error(drive, "request sense failure", stat);
331                 return 1;
332
333         } else if (blk_pc_request(rq) || rq->cmd_type == REQ_TYPE_ATA_PC) {
334                 /* All other functions, except for READ. */
335                 unsigned long flags;
336
337                 /*
338                  * if we have an error, pass back CHECK_CONDITION as the
339                  * scsi status byte
340                  */
341                 if (blk_pc_request(rq) && !rq->errors)
342                         rq->errors = SAM_STAT_CHECK_CONDITION;
343
344                 /* Check for tray open. */
345                 if (sense_key == NOT_READY) {
346                         cdrom_saw_media_change (drive);
347                 } else if (sense_key == UNIT_ATTENTION) {
348                         /* Check for media change. */
349                         cdrom_saw_media_change (drive);
350                         /*printk("%s: media changed\n",drive->name);*/
351                         return 0;
352                 } else if ((sense_key == ILLEGAL_REQUEST) &&
353                            (rq->cmd[0] == GPCMD_START_STOP_UNIT)) {
354                         /*
355                          * Don't print error message for this condition--
356                          * SFF8090i indicates that 5/24/00 is the correct
357                          * response to a request to close the tray if the
358                          * drive doesn't have that capability.
359                          * cdrom_log_sense() knows this!
360                          */
361                 } else if (!(rq->cmd_flags & REQ_QUIET)) {
362                         /* Otherwise, print an error. */
363                         ide_dump_status(drive, "packet command error", stat);
364                 }
365                 
366                 rq->cmd_flags |= REQ_FAILED;
367
368                 /*
369                  * instead of playing games with moving completions around,
370                  * remove failed request completely and end it when the
371                  * request sense has completed
372                  */
373                 if (stat & ERR_STAT) {
374                         spin_lock_irqsave(&ide_lock, flags);
375                         blkdev_dequeue_request(rq);
376                         HWGROUP(drive)->rq = NULL;
377                         spin_unlock_irqrestore(&ide_lock, flags);
378
379                         cdrom_queue_request_sense(drive, rq->sense, rq);
380                 } else
381                         cdrom_end_request(drive, 0);
382
383         } else if (blk_fs_request(rq)) {
384                 int do_end_request = 0;
385
386                 /* Handle errors from READ and WRITE requests. */
387
388                 if (blk_noretry_request(rq))
389                         do_end_request = 1;
390
391                 if (sense_key == NOT_READY) {
392                         /* Tray open. */
393                         if (rq_data_dir(rq) == READ) {
394                                 cdrom_saw_media_change (drive);
395
396                                 /* Fail the request. */
397                                 printk ("%s: tray open\n", drive->name);
398                                 do_end_request = 1;
399                         } else {
400                                 struct cdrom_info *info = drive->driver_data;
401
402                                 /* allow the drive 5 seconds to recover, some
403                                  * devices will return this error while flushing
404                                  * data from cache */
405                                 if (!rq->errors)
406                                         info->write_timeout = jiffies + ATAPI_WAIT_WRITE_BUSY;
407                                 rq->errors = 1;
408                                 if (time_after(jiffies, info->write_timeout))
409                                         do_end_request = 1;
410                                 else {
411                                         unsigned long flags;
412
413                                         /*
414                                          * take a breather relying on the
415                                          * unplug timer to kick us again
416                                          */
417                                         spin_lock_irqsave(&ide_lock, flags);
418                                         blk_plug_device(drive->queue);
419                                         spin_unlock_irqrestore(&ide_lock,flags);
420                                         return 1;
421                                 }
422                         }
423                 } else if (sense_key == UNIT_ATTENTION) {
424                         /* Media change. */
425                         cdrom_saw_media_change (drive);
426
427                         /* Arrange to retry the request.
428                            But be sure to give up if we've retried
429                            too many times. */
430                         if (++rq->errors > ERROR_MAX)
431                                 do_end_request = 1;
432                 } else if (sense_key == ILLEGAL_REQUEST ||
433                            sense_key == DATA_PROTECT) {
434                         /* No point in retrying after an illegal
435                            request or data protect error.*/
436                         ide_dump_status_no_sense (drive, "command error", stat);
437                         do_end_request = 1;
438                 } else if (sense_key == MEDIUM_ERROR) {
439                         /* No point in re-trying a zillion times on a bad 
440                          * sector...  If we got here the error is not correctable */
441                         ide_dump_status_no_sense (drive, "media error (bad sector)", stat);
442                         do_end_request = 1;
443                 } else if (sense_key == BLANK_CHECK) {
444                         /* Disk appears blank ?? */
445                         ide_dump_status_no_sense (drive, "media error (blank)", stat);
446                         do_end_request = 1;
447                 } else if ((err & ~ABRT_ERR) != 0) {
448                         /* Go to the default handler
449                            for other errors. */
450                         ide_error(drive, "cdrom_decode_status", stat);
451                         return 1;
452                 } else if ((++rq->errors > ERROR_MAX)) {
453                         /* We've racked up too many retries.  Abort. */
454                         do_end_request = 1;
455                 }
456
457                 /* End a request through request sense analysis when we have
458                    sense data. We need this in order to perform end of media
459                    processing */
460
461                 if (do_end_request) {
462                         if (stat & ERR_STAT) {
463                                 unsigned long flags;
464                                 spin_lock_irqsave(&ide_lock, flags);
465                                 blkdev_dequeue_request(rq);
466                                 HWGROUP(drive)->rq = NULL;
467                                 spin_unlock_irqrestore(&ide_lock, flags);
468
469                                 cdrom_queue_request_sense(drive, rq->sense, rq);
470                         } else
471                                 cdrom_end_request(drive, 0);
472                 } else {
473                         /* If we got a CHECK_CONDITION status,
474                            queue a request sense command. */
475                         if (stat & ERR_STAT)
476                                 cdrom_queue_request_sense(drive, NULL, NULL);
477                 }
478         } else {
479                 blk_dump_rq_flags(rq, "ide-cd: bad rq");
480                 cdrom_end_request(drive, 0);
481         }
482
483         /* Retry, or handle the next request. */
484         return 1;
485 }
486
487 static int cdrom_timer_expiry(ide_drive_t *drive)
488 {
489         struct request *rq = HWGROUP(drive)->rq;
490         unsigned long wait = 0;
491
492         /*
493          * Some commands are *slow* and normally take a long time to
494          * complete. Usually we can use the ATAPI "disconnect" to bypass
495          * this, but not all commands/drives support that. Let
496          * ide_timer_expiry keep polling us for these.
497          */
498         switch (rq->cmd[0]) {
499                 case GPCMD_BLANK:
500                 case GPCMD_FORMAT_UNIT:
501                 case GPCMD_RESERVE_RZONE_TRACK:
502                 case GPCMD_CLOSE_TRACK:
503                 case GPCMD_FLUSH_CACHE:
504                         wait = ATAPI_WAIT_PC;
505                         break;
506                 default:
507                         if (!(rq->cmd_flags & REQ_QUIET))
508                                 printk(KERN_INFO "ide-cd: cmd 0x%x timed out\n", rq->cmd[0]);
509                         wait = 0;
510                         break;
511         }
512         return wait;
513 }
514
515 /* Set up the device registers for transferring a packet command on DEV,
516    expecting to later transfer XFERLEN bytes.  HANDLER is the routine
517    which actually transfers the command to the drive.  If this is a
518    drq_interrupt device, this routine will arrange for HANDLER to be
519    called when the interrupt from the drive arrives.  Otherwise, HANDLER
520    will be called immediately after the drive is prepared for the transfer. */
521
522 static ide_startstop_t cdrom_start_packet_command(ide_drive_t *drive,
523                                                   int xferlen,
524                                                   ide_handler_t *handler)
525 {
526         ide_startstop_t startstop;
527         struct cdrom_info *info = drive->driver_data;
528         ide_hwif_t *hwif = drive->hwif;
529
530         /* Wait for the controller to be idle. */
531         if (ide_wait_stat(&startstop, drive, 0, BUSY_STAT, WAIT_READY))
532                 return startstop;
533
534         /* FIXME: for Virtual DMA we must check harder */
535         if (info->dma)
536                 info->dma = !hwif->dma_setup(drive);
537
538         /* Set up the controller registers. */
539         ide_pktcmd_tf_load(drive, IDE_TFLAG_OUT_NSECT | IDE_TFLAG_OUT_LBAL |
540                            IDE_TFLAG_NO_SELECT_MASK, xferlen, info->dma);
541
542         if (info->cd_flags & IDE_CD_FLAG_DRQ_INTERRUPT) {
543                 /* waiting for CDB interrupt, not DMA yet. */
544                 if (info->dma)
545                         drive->waiting_for_dma = 0;
546
547                 /* packet command */
548                 ide_execute_command(drive, WIN_PACKETCMD, handler, ATAPI_WAIT_PC, cdrom_timer_expiry);
549                 return ide_started;
550         } else {
551                 unsigned long flags;
552
553                 /* packet command */
554                 spin_lock_irqsave(&ide_lock, flags);
555                 hwif->OUTBSYNC(drive, WIN_PACKETCMD, IDE_COMMAND_REG);
556                 ndelay(400);
557                 spin_unlock_irqrestore(&ide_lock, flags);
558
559                 return (*handler) (drive);
560         }
561 }
562
563 /* Send a packet command to DRIVE described by CMD_BUF and CMD_LEN.
564    The device registers must have already been prepared
565    by cdrom_start_packet_command.
566    HANDLER is the interrupt handler to call when the command completes
567    or there's data ready. */
568 #define ATAPI_MIN_CDB_BYTES 12
569 static ide_startstop_t cdrom_transfer_packet_command (ide_drive_t *drive,
570                                           struct request *rq,
571                                           ide_handler_t *handler)
572 {
573         ide_hwif_t *hwif = drive->hwif;
574         int cmd_len;
575         struct cdrom_info *info = drive->driver_data;
576         ide_startstop_t startstop;
577
578         if (info->cd_flags & IDE_CD_FLAG_DRQ_INTERRUPT) {
579                 /* Here we should have been called after receiving an interrupt
580                    from the device.  DRQ should how be set. */
581
582                 /* Check for errors. */
583                 if (cdrom_decode_status(drive, DRQ_STAT, NULL))
584                         return ide_stopped;
585
586                 /* Ok, next interrupt will be DMA interrupt. */
587                 if (info->dma)
588                         drive->waiting_for_dma = 1;
589         } else {
590                 /* Otherwise, we must wait for DRQ to get set. */
591                 if (ide_wait_stat(&startstop, drive, DRQ_STAT,
592                                 BUSY_STAT, WAIT_READY))
593                         return startstop;
594         }
595
596         /* Arm the interrupt handler. */
597         ide_set_handler(drive, handler, rq->timeout, cdrom_timer_expiry);
598
599         /* ATAPI commands get padded out to 12 bytes minimum */
600         cmd_len = COMMAND_SIZE(rq->cmd[0]);
601         if (cmd_len < ATAPI_MIN_CDB_BYTES)
602                 cmd_len = ATAPI_MIN_CDB_BYTES;
603
604         /* Send the command to the device. */
605         HWIF(drive)->atapi_output_bytes(drive, rq->cmd, cmd_len);
606
607         /* Start the DMA if need be */
608         if (info->dma)
609                 hwif->dma_start(drive);
610
611         return ide_started;
612 }
613
614 /****************************************************************************
615  * Block read functions.
616  */
617
618 typedef void (xfer_func_t)(ide_drive_t *, void *, u32);
619
620 static void ide_cd_pad_transfer(ide_drive_t *drive, xfer_func_t *xf, int len)
621 {
622         while (len > 0) {
623                 int dum = 0;
624                 xf(drive, &dum, sizeof(dum));
625                 len -= sizeof(dum);
626         }
627 }
628
629 /*
630  * Buffer up to SECTORS_TO_TRANSFER sectors from the drive in our sector
631  * buffer.  Once the first sector is added, any subsequent sectors are
632  * assumed to be continuous (until the buffer is cleared).  For the first
633  * sector added, SECTOR is its sector number.  (SECTOR is then ignored until
634  * the buffer is cleared.)
635  */
636 static void cdrom_buffer_sectors (ide_drive_t *drive, unsigned long sector,
637                                   int sectors_to_transfer)
638 {
639         struct cdrom_info *info = drive->driver_data;
640
641         /* Number of sectors to read into the buffer. */
642         int sectors_to_buffer = min_t(int, sectors_to_transfer,
643                                      (SECTOR_BUFFER_SIZE >> SECTOR_BITS) -
644                                        info->nsectors_buffered);
645
646         char *dest;
647
648         /* If we couldn't get a buffer, don't try to buffer anything... */
649         if (info->buffer == NULL)
650                 sectors_to_buffer = 0;
651
652         /* If this is the first sector in the buffer, remember its number. */
653         if (info->nsectors_buffered == 0)
654                 info->sector_buffered = sector;
655
656         /* Read the data into the buffer. */
657         dest = info->buffer + info->nsectors_buffered * SECTOR_SIZE;
658         while (sectors_to_buffer > 0) {
659                 HWIF(drive)->atapi_input_bytes(drive, dest, SECTOR_SIZE);
660                 --sectors_to_buffer;
661                 --sectors_to_transfer;
662                 ++info->nsectors_buffered;
663                 dest += SECTOR_SIZE;
664         }
665
666         /* Throw away any remaining data. */
667         while (sectors_to_transfer > 0) {
668                 static char dum[SECTOR_SIZE];
669                 HWIF(drive)->atapi_input_bytes(drive, dum, sizeof (dum));
670                 --sectors_to_transfer;
671         }
672 }
673
674 /*
675  * Check the contents of the interrupt reason register from the cdrom
676  * and attempt to recover if there are problems.  Returns  0 if everything's
677  * ok; nonzero if the request has been terminated.
678  */
679 static
680 int cdrom_read_check_ireason (ide_drive_t *drive, int len, int ireason)
681 {
682         if (ireason == 2)
683                 return 0;
684         else if (ireason == 0) {
685                 ide_hwif_t *hwif = drive->hwif;
686
687                 /* Whoops... The drive is expecting to receive data from us! */
688                 printk(KERN_ERR "%s: %s: wrong transfer direction!\n",
689                                 drive->name, __FUNCTION__);
690
691                 /* Throw some data at the drive so it doesn't hang
692                    and quit this request. */
693                 ide_cd_pad_transfer(drive, hwif->atapi_output_bytes, len);
694         } else  if (ireason == 1) {
695                 /* Some drives (ASUS) seem to tell us that status
696                  * info is available. just get it and ignore.
697                  */
698                 (void) HWIF(drive)->INB(IDE_STATUS_REG);
699                 return 0;
700         } else {
701                 /* Drive wants a command packet, or invalid ireason... */
702                 printk(KERN_ERR "%s: %s: bad interrupt reason 0x%02x\n",
703                                 drive->name, __FUNCTION__, ireason);
704         }
705
706         cdrom_end_request(drive, 0);
707         return -1;
708 }
709
710 /*
711  * Interrupt routine.  Called when a read request has completed.
712  */
713 static ide_startstop_t cdrom_read_intr (ide_drive_t *drive)
714 {
715         int stat;
716         int ireason, len, sectors_to_transfer, nskip;
717         struct cdrom_info *info = drive->driver_data;
718         u8 lowcyl = 0, highcyl = 0;
719         int dma = info->dma, dma_error = 0;
720
721         struct request *rq = HWGROUP(drive)->rq;
722
723         /*
724          * handle dma case
725          */
726         if (dma) {
727                 info->dma = 0;
728                 dma_error = HWIF(drive)->ide_dma_end(drive);
729                 if (dma_error) {
730                         printk(KERN_ERR "%s: DMA read error\n", drive->name);
731                         ide_dma_off(drive);
732                 }
733         }
734
735         if (cdrom_decode_status(drive, 0, &stat))
736                 return ide_stopped;
737
738         if (dma) {
739                 if (!dma_error) {
740                         ide_end_request(drive, 1, rq->nr_sectors);
741                         return ide_stopped;
742                 } else
743                         return ide_error(drive, "dma error", stat);
744         }
745
746         /* Read the interrupt reason and the transfer length. */
747         ireason = HWIF(drive)->INB(IDE_IREASON_REG) & 0x3;
748         lowcyl  = HWIF(drive)->INB(IDE_BCOUNTL_REG);
749         highcyl = HWIF(drive)->INB(IDE_BCOUNTH_REG);
750
751         len = lowcyl + (256 * highcyl);
752
753         /* If DRQ is clear, the command has completed. */
754         if ((stat & DRQ_STAT) == 0) {
755                 /* If we're not done filling the current buffer, complain.
756                    Otherwise, complete the command normally. */
757                 if (rq->current_nr_sectors > 0) {
758                         printk (KERN_ERR "%s: cdrom_read_intr: data underrun (%d blocks)\n",
759                                 drive->name, rq->current_nr_sectors);
760                         rq->cmd_flags |= REQ_FAILED;
761                         cdrom_end_request(drive, 0);
762                 } else
763                         cdrom_end_request(drive, 1);
764                 return ide_stopped;
765         }
766
767         /* Check that the drive is expecting to do the same thing we are. */
768         if (cdrom_read_check_ireason (drive, len, ireason))
769                 return ide_stopped;
770
771         /* Assume that the drive will always provide data in multiples
772            of at least SECTOR_SIZE, as it gets hairy to keep track
773            of the transfers otherwise. */
774         if ((len % SECTOR_SIZE) != 0) {
775                 printk (KERN_ERR "%s: cdrom_read_intr: Bad transfer size %d\n",
776                         drive->name, len);
777                 if (info->cd_flags & IDE_CD_FLAG_LIMIT_NFRAMES)
778                         printk (KERN_ERR "  This drive is not supported by this version of the driver\n");
779                 else {
780                         printk (KERN_ERR "  Trying to limit transfer sizes\n");
781                         info->cd_flags |= IDE_CD_FLAG_LIMIT_NFRAMES;
782                 }
783                 cdrom_end_request(drive, 0);
784                 return ide_stopped;
785         }
786
787         /* The number of sectors we need to read from the drive. */
788         sectors_to_transfer = len / SECTOR_SIZE;
789
790         /* First, figure out if we need to bit-bucket
791            any of the leading sectors. */
792         nskip = min_t(int, rq->current_nr_sectors - bio_cur_sectors(rq->bio), sectors_to_transfer);
793
794         while (nskip > 0) {
795                 /* We need to throw away a sector. */
796                 static char dum[SECTOR_SIZE];
797                 HWIF(drive)->atapi_input_bytes(drive, dum, sizeof (dum));
798
799                 --rq->current_nr_sectors;
800                 --nskip;
801                 --sectors_to_transfer;
802         }
803
804         /* Now loop while we still have data to read from the drive. */
805         while (sectors_to_transfer > 0) {
806                 int this_transfer;
807
808                 /* If we've filled the present buffer but there's another
809                    chained buffer after it, move on. */
810                 if (rq->current_nr_sectors == 0 && rq->nr_sectors)
811                         cdrom_end_request(drive, 1);
812
813                 /* If the buffers are full, cache the rest of the data in our
814                    internal buffer. */
815                 if (rq->current_nr_sectors == 0) {
816                         cdrom_buffer_sectors(drive, rq->sector, sectors_to_transfer);
817                         sectors_to_transfer = 0;
818                 } else {
819                         /* Transfer data to the buffers.
820                            Figure out how many sectors we can transfer
821                            to the current buffer. */
822                         this_transfer = min_t(int, sectors_to_transfer,
823                                              rq->current_nr_sectors);
824
825                         /* Read this_transfer sectors
826                            into the current buffer. */
827                         while (this_transfer > 0) {
828                                 HWIF(drive)->atapi_input_bytes(drive, rq->buffer, SECTOR_SIZE);
829                                 rq->buffer += SECTOR_SIZE;
830                                 --rq->nr_sectors;
831                                 --rq->current_nr_sectors;
832                                 ++rq->sector;
833                                 --this_transfer;
834                                 --sectors_to_transfer;
835                         }
836                 }
837         }
838
839         /* Done moving data!  Wait for another interrupt. */
840         ide_set_handler(drive, &cdrom_read_intr, ATAPI_WAIT_PC, NULL);
841         return ide_started;
842 }
843
844 /*
845  * Try to satisfy some of the current read request from our cached data.
846  * Returns nonzero if the request has been completed, zero otherwise.
847  */
848 static int cdrom_read_from_buffer (ide_drive_t *drive)
849 {
850         struct cdrom_info *info = drive->driver_data;
851         struct request *rq = HWGROUP(drive)->rq;
852         unsigned short sectors_per_frame;
853
854         sectors_per_frame = queue_hardsect_size(drive->queue) >> SECTOR_BITS;
855
856         /* Can't do anything if there's no buffer. */
857         if (info->buffer == NULL) return 0;
858
859         /* Loop while this request needs data and the next block is present
860            in our cache. */
861         while (rq->nr_sectors > 0 &&
862                rq->sector >= info->sector_buffered &&
863                rq->sector < info->sector_buffered + info->nsectors_buffered) {
864                 if (rq->current_nr_sectors == 0)
865                         cdrom_end_request(drive, 1);
866
867                 memcpy (rq->buffer,
868                         info->buffer +
869                         (rq->sector - info->sector_buffered) * SECTOR_SIZE,
870                         SECTOR_SIZE);
871                 rq->buffer += SECTOR_SIZE;
872                 --rq->current_nr_sectors;
873                 --rq->nr_sectors;
874                 ++rq->sector;
875         }
876
877         /* If we've satisfied the current request,
878            terminate it successfully. */
879         if (rq->nr_sectors == 0) {
880                 cdrom_end_request(drive, 1);
881                 return -1;
882         }
883
884         /* Move on to the next buffer if needed. */
885         if (rq->current_nr_sectors == 0)
886                 cdrom_end_request(drive, 1);
887
888         /* If this condition does not hold, then the kluge i use to
889            represent the number of sectors to skip at the start of a transfer
890            will fail.  I think that this will never happen, but let's be
891            paranoid and check. */
892         if (rq->current_nr_sectors < bio_cur_sectors(rq->bio) &&
893             (rq->sector & (sectors_per_frame - 1))) {
894                 printk(KERN_ERR "%s: cdrom_read_from_buffer: buffer botch (%ld)\n",
895                         drive->name, (long)rq->sector);
896                 cdrom_end_request(drive, 0);
897                 return -1;
898         }
899
900         return 0;
901 }
902
903 /*
904  * Routine to send a read packet command to the drive.
905  * This is usually called directly from cdrom_start_read.
906  * However, for drq_interrupt devices, it is called from an interrupt
907  * when the drive is ready to accept the command.
908  */
909 static ide_startstop_t cdrom_start_read_continuation (ide_drive_t *drive)
910 {
911         struct request *rq = HWGROUP(drive)->rq;
912         unsigned short sectors_per_frame;
913         int nskip;
914
915         sectors_per_frame = queue_hardsect_size(drive->queue) >> SECTOR_BITS;
916
917         /* If the requested sector doesn't start on a cdrom block boundary,
918            we must adjust the start of the transfer so that it does,
919            and remember to skip the first few sectors.
920            If the CURRENT_NR_SECTORS field is larger than the size
921            of the buffer, it will mean that we're to skip a number
922            of sectors equal to the amount by which CURRENT_NR_SECTORS
923            is larger than the buffer size. */
924         nskip = rq->sector & (sectors_per_frame - 1);
925         if (nskip > 0) {
926                 /* Sanity check... */
927                 if (rq->current_nr_sectors != bio_cur_sectors(rq->bio) &&
928                         (rq->sector & (sectors_per_frame - 1))) {
929                         printk(KERN_ERR "%s: cdrom_start_read_continuation: buffer botch (%u)\n",
930                                 drive->name, rq->current_nr_sectors);
931                         cdrom_end_request(drive, 0);
932                         return ide_stopped;
933                 }
934                 rq->current_nr_sectors += nskip;
935         }
936
937         /* Set up the command */
938         rq->timeout = ATAPI_WAIT_PC;
939
940         /* Send the command to the drive and return. */
941         return cdrom_transfer_packet_command(drive, rq, &cdrom_read_intr);
942 }
943
944
945 #define IDECD_SEEK_THRESHOLD    (1000)                  /* 1000 blocks */
946 #define IDECD_SEEK_TIMER        (5 * WAIT_MIN_SLEEP)    /* 100 ms */
947 #define IDECD_SEEK_TIMEOUT      (2 * WAIT_CMD)          /* 20 sec */
948
949 static ide_startstop_t cdrom_seek_intr (ide_drive_t *drive)
950 {
951         struct cdrom_info *info = drive->driver_data;
952         int stat;
953         static int retry = 10;
954
955         if (cdrom_decode_status(drive, 0, &stat))
956                 return ide_stopped;
957
958         info->cd_flags |= IDE_CD_FLAG_SEEKING;
959
960         if (retry && time_after(jiffies, info->start_seek + IDECD_SEEK_TIMER)) {
961                 if (--retry == 0) {
962                         /*
963                          * this condition is far too common, to bother
964                          * users about it
965                          */
966                         /* printk("%s: disabled DSC seek overlap\n", drive->name);*/ 
967                         drive->dsc_overlap = 0;
968                 }
969         }
970         return ide_stopped;
971 }
972
973 static ide_startstop_t cdrom_start_seek_continuation (ide_drive_t *drive)
974 {
975         struct request *rq = HWGROUP(drive)->rq;
976         sector_t frame = rq->sector;
977
978         sector_div(frame, queue_hardsect_size(drive->queue) >> SECTOR_BITS);
979
980         memset(rq->cmd, 0, sizeof(rq->cmd));
981         rq->cmd[0] = GPCMD_SEEK;
982         put_unaligned(cpu_to_be32(frame), (unsigned int *) &rq->cmd[2]);
983
984         rq->timeout = ATAPI_WAIT_PC;
985         return cdrom_transfer_packet_command(drive, rq, &cdrom_seek_intr);
986 }
987
988 static ide_startstop_t cdrom_start_seek (ide_drive_t *drive, unsigned int block)
989 {
990         struct cdrom_info *info = drive->driver_data;
991
992         info->dma = 0;
993         info->start_seek = jiffies;
994         return cdrom_start_packet_command(drive, 0, cdrom_start_seek_continuation);
995 }
996
997 /* Fix up a possibly partially-processed request so that we can
998    start it over entirely, or even put it back on the request queue. */
999 static void restore_request (struct request *rq)
1000 {
1001         if (rq->buffer != bio_data(rq->bio)) {
1002                 sector_t n = (rq->buffer - (char *) bio_data(rq->bio)) / SECTOR_SIZE;
1003
1004                 rq->buffer = bio_data(rq->bio);
1005                 rq->nr_sectors += n;
1006                 rq->sector -= n;
1007         }
1008         rq->hard_cur_sectors = rq->current_nr_sectors = bio_cur_sectors(rq->bio);
1009         rq->hard_nr_sectors = rq->nr_sectors;
1010         rq->hard_sector = rq->sector;
1011         rq->q->prep_rq_fn(rq->q, rq);
1012 }
1013
1014 /*
1015  * Start a read request from the CD-ROM.
1016  */
1017 static ide_startstop_t cdrom_start_read (ide_drive_t *drive, unsigned int block)
1018 {
1019         struct cdrom_info *info = drive->driver_data;
1020         struct request *rq = HWGROUP(drive)->rq;
1021         unsigned short sectors_per_frame;
1022
1023         sectors_per_frame = queue_hardsect_size(drive->queue) >> SECTOR_BITS;
1024
1025         /* We may be retrying this request after an error.  Fix up
1026            any weirdness which might be present in the request packet. */
1027         restore_request(rq);
1028
1029         /* Satisfy whatever we can of this request from our cached sector. */
1030         if (cdrom_read_from_buffer(drive))
1031                 return ide_stopped;
1032
1033         /* Clear the local sector buffer. */
1034         info->nsectors_buffered = 0;
1035
1036         /* use dma, if possible. */
1037         info->dma = drive->using_dma;
1038         if ((rq->sector & (sectors_per_frame - 1)) ||
1039             (rq->nr_sectors & (sectors_per_frame - 1)))
1040                 info->dma = 0;
1041
1042         /* Start sending the read request to the drive. */
1043         return cdrom_start_packet_command(drive, 32768, cdrom_start_read_continuation);
1044 }
1045
1046 /****************************************************************************
1047  * Execute all other packet commands.
1048  */
1049
1050 /* Interrupt routine for packet command completion. */
1051 static ide_startstop_t cdrom_pc_intr (ide_drive_t *drive)
1052 {
1053         struct request *rq = HWGROUP(drive)->rq;
1054         xfer_func_t *xferfunc = NULL;
1055         int stat, ireason, len, thislen, write;
1056         u8 lowcyl = 0, highcyl = 0;
1057
1058         /* Check for errors. */
1059         if (cdrom_decode_status(drive, 0, &stat))
1060                 return ide_stopped;
1061
1062         /* Read the interrupt reason and the transfer length. */
1063         ireason = HWIF(drive)->INB(IDE_IREASON_REG) & 0x3;
1064         lowcyl  = HWIF(drive)->INB(IDE_BCOUNTL_REG);
1065         highcyl = HWIF(drive)->INB(IDE_BCOUNTH_REG);
1066
1067         len = lowcyl + (256 * highcyl);
1068
1069         /* If DRQ is clear, the command has completed.
1070            Complain if we still have data left to transfer. */
1071         if ((stat & DRQ_STAT) == 0) {
1072                 /* Some of the trailing request sense fields are optional, and
1073                    some drives don't send them.  Sigh. */
1074                 if (rq->cmd[0] == GPCMD_REQUEST_SENSE &&
1075                     rq->data_len > 0 &&
1076                     rq->data_len <= 5) {
1077                         while (rq->data_len > 0) {
1078                                 *(unsigned char *)rq->data++ = 0;
1079                                 --rq->data_len;
1080                         }
1081                 }
1082
1083                 if (rq->data_len == 0)
1084                         cdrom_end_request(drive, 1);
1085                 else {
1086                         rq->cmd_flags |= REQ_FAILED;
1087                         cdrom_end_request(drive, 0);
1088                 }
1089                 return ide_stopped;
1090         }
1091
1092         /* Figure out how much data to transfer. */
1093         thislen = rq->data_len;
1094         if (thislen > len)
1095                 thislen = len;
1096
1097         if (ireason == 0) {
1098                 write = 1;
1099                 xferfunc = HWIF(drive)->atapi_output_bytes;
1100         } else if (ireason == 2) {
1101                 write = 0;
1102                 xferfunc = HWIF(drive)->atapi_input_bytes;
1103         }
1104
1105         if (xferfunc) {
1106                 if (!rq->data) {
1107                         printk(KERN_ERR "%s: confused, missing data\n",
1108                                         drive->name);
1109                         blk_dump_rq_flags(rq, write ? "cdrom_pc_intr, write"
1110                                                     : "cdrom_pc_intr, read");
1111                         goto pad;
1112                 }
1113                 /* Transfer the data. */
1114                 xferfunc(drive, rq->data, thislen);
1115
1116                 /* Keep count of how much data we've moved. */
1117                 len -= thislen;
1118                 rq->data += thislen;
1119                 rq->data_len -= thislen;
1120
1121                 if (write && blk_sense_request(rq))
1122                         rq->sense_len += thislen;
1123         } else {
1124                 printk (KERN_ERR "%s: cdrom_pc_intr: The drive "
1125                         "appears confused (ireason = 0x%02x). "
1126                         "Trying to recover by ending request.\n",
1127                         drive->name, ireason);
1128                 rq->cmd_flags |= REQ_FAILED;
1129                 cdrom_end_request(drive, 0);
1130                 return ide_stopped;
1131         }
1132 pad:
1133         /*
1134          * If we haven't moved enough data to satisfy the drive,
1135          * add some padding.
1136          */
1137         if (len > 0)
1138                 ide_cd_pad_transfer(drive, xferfunc, len);
1139
1140         /* Now we wait for another interrupt. */
1141         ide_set_handler(drive, &cdrom_pc_intr, ATAPI_WAIT_PC, cdrom_timer_expiry);
1142         return ide_started;
1143 }
1144
1145 static ide_startstop_t cdrom_do_pc_continuation (ide_drive_t *drive)
1146 {
1147         struct request *rq = HWGROUP(drive)->rq;
1148
1149         if (!rq->timeout)
1150                 rq->timeout = ATAPI_WAIT_PC;
1151
1152         /* Send the command to the drive and return. */
1153         return cdrom_transfer_packet_command(drive, rq, &cdrom_pc_intr);
1154 }
1155
1156
1157 static ide_startstop_t cdrom_do_packet_command (ide_drive_t *drive)
1158 {
1159         int len;
1160         struct request *rq = HWGROUP(drive)->rq;
1161         struct cdrom_info *info = drive->driver_data;
1162
1163         info->dma = 0;
1164         rq->cmd_flags &= ~REQ_FAILED;
1165         len = rq->data_len;
1166
1167         /* Start sending the command to the drive. */
1168         return cdrom_start_packet_command(drive, len, cdrom_do_pc_continuation);
1169 }
1170
1171
1172 static int cdrom_queue_packet_command(ide_drive_t *drive, struct request *rq)
1173 {
1174         struct request_sense sense;
1175         int retries = 10;
1176         unsigned int flags = rq->cmd_flags;
1177
1178         if (rq->sense == NULL)
1179                 rq->sense = &sense;
1180
1181         /* Start of retry loop. */
1182         do {
1183                 int error;
1184                 unsigned long time = jiffies;
1185                 rq->cmd_flags = flags;
1186
1187                 error = ide_do_drive_cmd(drive, rq, ide_wait);
1188                 time = jiffies - time;
1189
1190                 /* FIXME: we should probably abort/retry or something 
1191                  * in case of failure */
1192                 if (rq->cmd_flags & REQ_FAILED) {
1193                         /* The request failed.  Retry if it was due to a unit
1194                            attention status
1195                            (usually means media was changed). */
1196                         struct request_sense *reqbuf = rq->sense;
1197
1198                         if (reqbuf->sense_key == UNIT_ATTENTION)
1199                                 cdrom_saw_media_change(drive);
1200                         else if (reqbuf->sense_key == NOT_READY &&
1201                                  reqbuf->asc == 4 && reqbuf->ascq != 4) {
1202                                 /* The drive is in the process of loading
1203                                    a disk.  Retry, but wait a little to give
1204                                    the drive time to complete the load. */
1205                                 ssleep(2);
1206                         } else {
1207                                 /* Otherwise, don't retry. */
1208                                 retries = 0;
1209                         }
1210                         --retries;
1211                 }
1212
1213                 /* End of retry loop. */
1214         } while ((rq->cmd_flags & REQ_FAILED) && retries >= 0);
1215
1216         /* Return an error if the command failed. */
1217         return (rq->cmd_flags & REQ_FAILED) ? -EIO : 0;
1218 }
1219
1220 /*
1221  * Write handling
1222  */
1223 static int cdrom_write_check_ireason(ide_drive_t *drive, int len, int ireason)
1224 {
1225         /* Two notes about IDE interrupt reason here - 0 means that
1226          * the drive wants to receive data from us, 2 means that
1227          * the drive is expecting to transfer data to us.
1228          */
1229         if (ireason == 0)
1230                 return 0;
1231         else if (ireason == 2) {
1232                 ide_hwif_t *hwif = drive->hwif;
1233
1234                 /* Whoops... The drive wants to send data. */
1235                 printk(KERN_ERR "%s: %s: wrong transfer direction!\n",
1236                                 drive->name, __FUNCTION__);
1237
1238                 ide_cd_pad_transfer(drive, hwif->atapi_input_bytes, len);
1239         } else {
1240                 /* Drive wants a command packet, or invalid ireason... */
1241                 printk(KERN_ERR "%s: %s: bad interrupt reason 0x%02x\n",
1242                                 drive->name, __FUNCTION__, ireason);
1243         }
1244
1245         cdrom_end_request(drive, 0);
1246         return 1;
1247 }
1248
1249 /*
1250  * Called from blk_end_request_callback() after the data of the request
1251  * is completed and before the request is completed.
1252  * By returning value '1', blk_end_request_callback() returns immediately
1253  * without completing the request.
1254  */
1255 static int cdrom_newpc_intr_dummy_cb(struct request *rq)
1256 {
1257         return 1;
1258 }
1259
1260 /*
1261  * best way to deal with dma that is not sector aligned right now... note
1262  * that in this path we are not using ->data or ->buffer at all. this irs
1263  * can replace cdrom_pc_intr, cdrom_read_intr, and cdrom_write_intr in the
1264  * future.
1265  */
1266 static ide_startstop_t cdrom_newpc_intr(ide_drive_t *drive)
1267 {
1268         struct cdrom_info *info = drive->driver_data;
1269         struct request *rq = HWGROUP(drive)->rq;
1270         int dma_error, dma, stat, ireason, len, thislen;
1271         u8 lowcyl, highcyl;
1272         xfer_func_t *xferfunc;
1273         unsigned long flags;
1274
1275         /* Check for errors. */
1276         dma_error = 0;
1277         dma = info->dma;
1278         if (dma) {
1279                 info->dma = 0;
1280                 dma_error = HWIF(drive)->ide_dma_end(drive);
1281                 if (dma_error) {
1282                         printk(KERN_ERR "%s: DMA %s error\n", drive->name,
1283                                         rq_data_dir(rq) ? "write" : "read");
1284                         ide_dma_off(drive);
1285                 }
1286         }
1287
1288         if (cdrom_decode_status(drive, 0, &stat))
1289                 return ide_stopped;
1290
1291         /*
1292          * using dma, transfer is complete now
1293          */
1294         if (dma) {
1295                 if (dma_error)
1296                         return ide_error(drive, "dma error", stat);
1297
1298                 spin_lock_irqsave(&ide_lock, flags);
1299                 if (__blk_end_request(rq, 0, rq->data_len))
1300                         BUG();
1301                 HWGROUP(drive)->rq = NULL;
1302                 spin_unlock_irqrestore(&ide_lock, flags);
1303
1304                 return ide_stopped;
1305         }
1306
1307         /*
1308          * ok we fall to pio :/
1309          */
1310         ireason = HWIF(drive)->INB(IDE_IREASON_REG) & 0x3;
1311         lowcyl  = HWIF(drive)->INB(IDE_BCOUNTL_REG);
1312         highcyl = HWIF(drive)->INB(IDE_BCOUNTH_REG);
1313
1314         len = lowcyl + (256 * highcyl);
1315         thislen = rq->data_len;
1316         if (thislen > len)
1317                 thislen = len;
1318
1319         /*
1320          * If DRQ is clear, the command has completed.
1321          */
1322         if ((stat & DRQ_STAT) == 0) {
1323                 spin_lock_irqsave(&ide_lock, flags);
1324                 if (__blk_end_request(rq, 0, rq->data_len))
1325                         BUG();
1326                 HWGROUP(drive)->rq = NULL;
1327                 spin_unlock_irqrestore(&ide_lock, flags);
1328
1329                 return ide_stopped;
1330         }
1331
1332         /*
1333          * check which way to transfer data
1334          */
1335         if (rq_data_dir(rq) == WRITE) {
1336                 /*
1337                  * write to drive
1338                  */
1339                 if (cdrom_write_check_ireason(drive, len, ireason))
1340                         return ide_stopped;
1341
1342                 xferfunc = HWIF(drive)->atapi_output_bytes;
1343         } else  {
1344                 /*
1345                  * read from drive
1346                  */
1347                 if (cdrom_read_check_ireason(drive, len, ireason))
1348                         return ide_stopped;
1349
1350                 xferfunc = HWIF(drive)->atapi_input_bytes;
1351         }
1352
1353         /*
1354          * transfer data
1355          */
1356         while (thislen > 0) {
1357                 int blen = blen = rq->data_len;
1358                 char *ptr = rq->data;
1359
1360                 /*
1361                  * bio backed?
1362                  */
1363                 if (rq->bio) {
1364                         ptr = bio_data(rq->bio);
1365                         blen = bio_iovec(rq->bio)->bv_len;
1366                 }
1367
1368                 if (!ptr) {
1369                         printk(KERN_ERR "%s: confused, missing data\n", drive->name);
1370                         break;
1371                 }
1372
1373                 if (blen > thislen)
1374                         blen = thislen;
1375
1376                 xferfunc(drive, ptr, blen);
1377
1378                 thislen -= blen;
1379                 len -= blen;
1380                 rq->data_len -= blen;
1381
1382                 if (rq->bio)
1383                         /*
1384                          * The request can't be completed until DRQ is cleared.
1385                          * So complete the data, but don't complete the request
1386                          * using the dummy function for the callback feature
1387                          * of blk_end_request_callback().
1388                          */
1389                         blk_end_request_callback(rq, 0, blen,
1390                                                  cdrom_newpc_intr_dummy_cb);
1391                 else
1392                         rq->data += blen;
1393         }
1394
1395         /*
1396          * pad, if necessary
1397          */
1398         if (len > 0)
1399                 ide_cd_pad_transfer(drive, xferfunc, len);
1400
1401         BUG_ON(HWGROUP(drive)->handler != NULL);
1402
1403         ide_set_handler(drive, cdrom_newpc_intr, rq->timeout, NULL);
1404         return ide_started;
1405 }
1406
1407 static ide_startstop_t cdrom_write_intr(ide_drive_t *drive)
1408 {
1409         int stat, ireason, len, sectors_to_transfer, uptodate;
1410         struct cdrom_info *info = drive->driver_data;
1411         int dma_error = 0, dma = info->dma;
1412         u8 lowcyl = 0, highcyl = 0;
1413
1414         struct request *rq = HWGROUP(drive)->rq;
1415
1416         /* Check for errors. */
1417         if (dma) {
1418                 info->dma = 0;
1419                 dma_error = HWIF(drive)->ide_dma_end(drive);
1420                 if (dma_error) {
1421                         printk(KERN_ERR "%s: DMA write error\n", drive->name);
1422                         ide_dma_off(drive);
1423                 }
1424         }
1425
1426         if (cdrom_decode_status(drive, 0, &stat))
1427                 return ide_stopped;
1428
1429         /*
1430          * using dma, transfer is complete now
1431          */
1432         if (dma) {
1433                 if (dma_error)
1434                         return ide_error(drive, "dma error", stat);
1435
1436                 ide_end_request(drive, 1, rq->nr_sectors);
1437                 return ide_stopped;
1438         }
1439
1440         /* Read the interrupt reason and the transfer length. */
1441         ireason = HWIF(drive)->INB(IDE_IREASON_REG) & 0x3;
1442         lowcyl  = HWIF(drive)->INB(IDE_BCOUNTL_REG);
1443         highcyl = HWIF(drive)->INB(IDE_BCOUNTH_REG);
1444
1445         len = lowcyl + (256 * highcyl);
1446
1447         /* If DRQ is clear, the command has completed. */
1448         if ((stat & DRQ_STAT) == 0) {
1449                 /* If we're not done writing, complain.
1450                  * Otherwise, complete the command normally.
1451                  */
1452                 uptodate = 1;
1453                 if (rq->current_nr_sectors > 0) {
1454                         printk(KERN_ERR "%s: %s: data underrun (%d blocks)\n",
1455                                         drive->name, __FUNCTION__,
1456                                         rq->current_nr_sectors);
1457                         uptodate = 0;
1458                 }
1459                 cdrom_end_request(drive, uptodate);
1460                 return ide_stopped;
1461         }
1462
1463         /* Check that the drive is expecting to do the same thing we are. */
1464         if (cdrom_write_check_ireason(drive, len, ireason))
1465                 return ide_stopped;
1466
1467         sectors_to_transfer = len / SECTOR_SIZE;
1468
1469         /*
1470          * now loop and write out the data
1471          */
1472         while (sectors_to_transfer > 0) {
1473                 int this_transfer;
1474
1475                 if (!rq->current_nr_sectors) {
1476                         printk(KERN_ERR "%s: %s: confused, missing data\n",
1477                                         drive->name, __FUNCTION__);
1478                         break;
1479                 }
1480
1481                 /*
1482                  * Figure out how many sectors we can transfer
1483                  */
1484                 this_transfer = min_t(int, sectors_to_transfer, rq->current_nr_sectors);
1485
1486                 while (this_transfer > 0) {
1487                         HWIF(drive)->atapi_output_bytes(drive, rq->buffer, SECTOR_SIZE);
1488                         rq->buffer += SECTOR_SIZE;
1489                         --rq->nr_sectors;
1490                         --rq->current_nr_sectors;
1491                         ++rq->sector;
1492                         --this_transfer;
1493                         --sectors_to_transfer;
1494                 }
1495
1496                 /*
1497                  * current buffer complete, move on
1498                  */
1499                 if (rq->current_nr_sectors == 0 && rq->nr_sectors)
1500                         cdrom_end_request(drive, 1);
1501         }
1502
1503         /* re-arm handler */
1504         ide_set_handler(drive, &cdrom_write_intr, ATAPI_WAIT_PC, NULL);
1505         return ide_started;
1506 }
1507
1508 static ide_startstop_t cdrom_start_write_cont(ide_drive_t *drive)
1509 {
1510         struct request *rq = HWGROUP(drive)->rq;
1511
1512 #if 0   /* the immediate bit */
1513         rq->cmd[1] = 1 << 3;
1514 #endif
1515         rq->timeout = ATAPI_WAIT_PC;
1516
1517         return cdrom_transfer_packet_command(drive, rq, cdrom_write_intr);
1518 }
1519
1520 static ide_startstop_t cdrom_start_write(ide_drive_t *drive, struct request *rq)
1521 {
1522         struct cdrom_info *info = drive->driver_data;
1523         struct gendisk *g = info->disk;
1524         unsigned short sectors_per_frame = queue_hardsect_size(drive->queue) >> SECTOR_BITS;
1525
1526         /*
1527          * writes *must* be hardware frame aligned
1528          */
1529         if ((rq->nr_sectors & (sectors_per_frame - 1)) ||
1530             (rq->sector & (sectors_per_frame - 1))) {
1531                 cdrom_end_request(drive, 0);
1532                 return ide_stopped;
1533         }
1534
1535         /*
1536          * disk has become write protected
1537          */
1538         if (g->policy) {
1539                 cdrom_end_request(drive, 0);
1540                 return ide_stopped;
1541         }
1542
1543         info->nsectors_buffered = 0;
1544
1545         /* use dma, if possible. we don't need to check more, since we
1546          * know that the transfer is always (at least!) frame aligned */
1547         info->dma = drive->using_dma ? 1 : 0;
1548
1549         info->devinfo.media_written = 1;
1550
1551         /* Start sending the write request to the drive. */
1552         return cdrom_start_packet_command(drive, 32768, cdrom_start_write_cont);
1553 }
1554
1555 static ide_startstop_t cdrom_do_newpc_cont(ide_drive_t *drive)
1556 {
1557         struct request *rq = HWGROUP(drive)->rq;
1558
1559         if (!rq->timeout)
1560                 rq->timeout = ATAPI_WAIT_PC;
1561
1562         return cdrom_transfer_packet_command(drive, rq, cdrom_newpc_intr);
1563 }
1564
1565 static ide_startstop_t cdrom_do_block_pc(ide_drive_t *drive, struct request *rq)
1566 {
1567         struct cdrom_info *info = drive->driver_data;
1568
1569         rq->cmd_flags |= REQ_QUIET;
1570
1571         info->dma = 0;
1572
1573         /*
1574          * sg request
1575          */
1576         if (rq->bio) {
1577                 int mask = drive->queue->dma_alignment;
1578                 unsigned long addr = (unsigned long) page_address(bio_page(rq->bio));
1579
1580                 info->dma = drive->using_dma;
1581
1582                 /*
1583                  * check if dma is safe
1584                  *
1585                  * NOTE! The "len" and "addr" checks should possibly have
1586                  * separate masks.
1587                  */
1588                 if ((rq->data_len & 15) || (addr & mask))
1589                         info->dma = 0;
1590         }
1591
1592         /* Start sending the command to the drive. */
1593         return cdrom_start_packet_command(drive, rq->data_len, cdrom_do_newpc_cont);
1594 }
1595
1596 /****************************************************************************
1597  * cdrom driver request routine.
1598  */
1599 static ide_startstop_t
1600 ide_do_rw_cdrom (ide_drive_t *drive, struct request *rq, sector_t block)
1601 {
1602         ide_startstop_t action;
1603         struct cdrom_info *info = drive->driver_data;
1604
1605         if (blk_fs_request(rq)) {
1606                 if (info->cd_flags & IDE_CD_FLAG_SEEKING) {
1607                         unsigned long elapsed = jiffies - info->start_seek;
1608                         int stat = HWIF(drive)->INB(IDE_STATUS_REG);
1609
1610                         if ((stat & SEEK_STAT) != SEEK_STAT) {
1611                                 if (elapsed < IDECD_SEEK_TIMEOUT) {
1612                                         ide_stall_queue(drive, IDECD_SEEK_TIMER);
1613                                         return ide_stopped;
1614                                 }
1615                                 printk (KERN_ERR "%s: DSC timeout\n", drive->name);
1616                         }
1617                         info->cd_flags &= ~IDE_CD_FLAG_SEEKING;
1618                 }
1619                 if ((rq_data_dir(rq) == READ) && IDE_LARGE_SEEK(info->last_block, block, IDECD_SEEK_THRESHOLD) && drive->dsc_overlap) {
1620                         action = cdrom_start_seek(drive, block);
1621                 } else {
1622                         if (rq_data_dir(rq) == READ)
1623                                 action = cdrom_start_read(drive, block);
1624                         else
1625                                 action = cdrom_start_write(drive, rq);
1626                 }
1627                 info->last_block = block;
1628                 return action;
1629         } else if (rq->cmd_type == REQ_TYPE_SENSE ||
1630                    rq->cmd_type == REQ_TYPE_ATA_PC) {
1631                 return cdrom_do_packet_command(drive);
1632         } else if (blk_pc_request(rq)) {
1633                 return cdrom_do_block_pc(drive, rq);
1634         } else if (blk_special_request(rq)) {
1635                 /*
1636                  * right now this can only be a reset...
1637                  */
1638                 cdrom_end_request(drive, 1);
1639                 return ide_stopped;
1640         }
1641
1642         blk_dump_rq_flags(rq, "ide-cd bad flags");
1643         cdrom_end_request(drive, 0);
1644         return ide_stopped;
1645 }
1646
1647
1648
1649 /****************************************************************************
1650  * Ioctl handling.
1651  *
1652  * Routines which queue packet commands take as a final argument a pointer
1653  * to a request_sense struct.  If execution of the command results
1654  * in an error with a CHECK CONDITION status, this structure will be filled
1655  * with the results of the subsequent request sense command.  The pointer
1656  * can also be NULL, in which case no sense information is returned.
1657  */
1658
1659 static
1660 void msf_from_bcd (struct atapi_msf *msf)
1661 {
1662         msf->minute = BCD2BIN(msf->minute);
1663         msf->second = BCD2BIN(msf->second);
1664         msf->frame  = BCD2BIN(msf->frame);
1665 }
1666
1667 static int cdrom_check_status(ide_drive_t *drive, struct request_sense *sense)
1668 {
1669         struct request req;
1670         struct cdrom_info *info = drive->driver_data;
1671         struct cdrom_device_info *cdi = &info->devinfo;
1672
1673         cdrom_prepare_request(drive, &req);
1674
1675         req.sense = sense;
1676         req.cmd[0] = GPCMD_TEST_UNIT_READY;
1677         req.cmd_flags |= REQ_QUIET;
1678
1679         /*
1680          * Sanyo 3 CD changer uses byte 7 of TEST_UNIT_READY to
1681          * switch CDs instead of supporting the LOAD_UNLOAD opcode.
1682          */
1683         req.cmd[7] = cdi->sanyo_slot % 3;
1684
1685         return cdrom_queue_packet_command(drive, &req);
1686 }
1687
1688
1689 /* Lock the door if LOCKFLAG is nonzero; unlock it otherwise. */
1690 static int
1691 cdrom_lockdoor(ide_drive_t *drive, int lockflag, struct request_sense *sense)
1692 {
1693         struct cdrom_info *cd = drive->driver_data;
1694         struct request_sense my_sense;
1695         struct request req;
1696         int stat;
1697
1698         if (sense == NULL)
1699                 sense = &my_sense;
1700
1701         /* If the drive cannot lock the door, just pretend. */
1702         if (cd->cd_flags & IDE_CD_FLAG_NO_DOORLOCK) {
1703                 stat = 0;
1704         } else {
1705                 cdrom_prepare_request(drive, &req);
1706                 req.sense = sense;
1707                 req.cmd[0] = GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL;
1708                 req.cmd[4] = lockflag ? 1 : 0;
1709                 stat = cdrom_queue_packet_command(drive, &req);
1710         }
1711
1712         /* If we got an illegal field error, the drive
1713            probably cannot lock the door. */
1714         if (stat != 0 &&
1715             sense->sense_key == ILLEGAL_REQUEST &&
1716             (sense->asc == 0x24 || sense->asc == 0x20)) {
1717                 printk (KERN_ERR "%s: door locking not supported\n",
1718                         drive->name);
1719                 cd->cd_flags |= IDE_CD_FLAG_NO_DOORLOCK;
1720                 stat = 0;
1721         }
1722         
1723         /* no medium, that's alright. */
1724         if (stat != 0 && sense->sense_key == NOT_READY && sense->asc == 0x3a)
1725                 stat = 0;
1726
1727         if (stat == 0) {
1728                 if (lockflag)
1729                         cd->cd_flags |= IDE_CD_FLAG_DOOR_LOCKED;
1730                 else
1731                         cd->cd_flags &= ~IDE_CD_FLAG_DOOR_LOCKED;
1732         }
1733
1734         return stat;
1735 }
1736
1737
1738 /* Eject the disk if EJECTFLAG is 0.
1739    If EJECTFLAG is 1, try to reload the disk. */
1740 static int cdrom_eject(ide_drive_t *drive, int ejectflag,
1741                        struct request_sense *sense)
1742 {
1743         struct cdrom_info *cd = drive->driver_data;
1744         struct cdrom_device_info *cdi = &cd->devinfo;
1745         struct request req;
1746         char loej = 0x02;
1747
1748         if ((cd->cd_flags & IDE_CD_FLAG_NO_EJECT) && !ejectflag)
1749                 return -EDRIVE_CANT_DO_THIS;
1750
1751         /* reload fails on some drives, if the tray is locked */
1752         if ((cd->cd_flags & IDE_CD_FLAG_DOOR_LOCKED) && ejectflag)
1753                 return 0;
1754
1755         cdrom_prepare_request(drive, &req);
1756
1757         /* only tell drive to close tray if open, if it can do that */
1758         if (ejectflag && (cdi->mask & CDC_CLOSE_TRAY))
1759                 loej = 0;
1760
1761         req.sense = sense;
1762         req.cmd[0] = GPCMD_START_STOP_UNIT;
1763         req.cmd[4] = loej | (ejectflag != 0);
1764         return cdrom_queue_packet_command(drive, &req);
1765 }
1766
1767 static int cdrom_read_capacity(ide_drive_t *drive, unsigned long *capacity,
1768                                unsigned long *sectors_per_frame,
1769                                struct request_sense *sense)
1770 {
1771         struct {
1772                 __u32 lba;
1773                 __u32 blocklen;
1774         } capbuf;
1775
1776         int stat;
1777         struct request req;
1778
1779         cdrom_prepare_request(drive, &req);
1780
1781         req.sense = sense;
1782         req.cmd[0] = GPCMD_READ_CDVD_CAPACITY;
1783         req.data = (char *)&capbuf;
1784         req.data_len = sizeof(capbuf);
1785         req.cmd_flags |= REQ_QUIET;
1786
1787         stat = cdrom_queue_packet_command(drive, &req);
1788         if (stat == 0) {
1789                 *capacity = 1 + be32_to_cpu(capbuf.lba);
1790                 *sectors_per_frame =
1791                         be32_to_cpu(capbuf.blocklen) >> SECTOR_BITS;
1792         }
1793
1794         return stat;
1795 }
1796
1797 static int cdrom_read_tocentry(ide_drive_t *drive, int trackno, int msf_flag,
1798                                 int format, char *buf, int buflen,
1799                                 struct request_sense *sense)
1800 {
1801         struct request req;
1802
1803         cdrom_prepare_request(drive, &req);
1804
1805         req.sense = sense;
1806         req.data =  buf;
1807         req.data_len = buflen;
1808         req.cmd_flags |= REQ_QUIET;
1809         req.cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
1810         req.cmd[6] = trackno;
1811         req.cmd[7] = (buflen >> 8);
1812         req.cmd[8] = (buflen & 0xff);
1813         req.cmd[9] = (format << 6);
1814
1815         if (msf_flag)
1816                 req.cmd[1] = 2;
1817
1818         return cdrom_queue_packet_command(drive, &req);
1819 }
1820
1821
1822 /* Try to read the entire TOC for the disk into our internal buffer. */
1823 static int cdrom_read_toc(ide_drive_t *drive, struct request_sense *sense)
1824 {
1825         int stat, ntracks, i;
1826         struct cdrom_info *info = drive->driver_data;
1827         struct cdrom_device_info *cdi = &info->devinfo;
1828         struct atapi_toc *toc = info->toc;
1829         struct {
1830                 struct atapi_toc_header hdr;
1831                 struct atapi_toc_entry  ent;
1832         } ms_tmp;
1833         long last_written;
1834         unsigned long sectors_per_frame = SECTORS_PER_FRAME;
1835
1836         if (toc == NULL) {
1837                 /* Try to allocate space. */
1838                 toc = kmalloc(sizeof(struct atapi_toc), GFP_KERNEL);
1839                 if (toc == NULL) {
1840                         printk (KERN_ERR "%s: No cdrom TOC buffer!\n", drive->name);
1841                         return -ENOMEM;
1842                 }
1843                 info->toc = toc;
1844         }
1845
1846         /* Check to see if the existing data is still valid.
1847            If it is, just return. */
1848         (void) cdrom_check_status(drive, sense);
1849
1850         if (info->cd_flags & IDE_CD_FLAG_TOC_VALID)
1851                 return 0;
1852
1853         /* Try to get the total cdrom capacity and sector size. */
1854         stat = cdrom_read_capacity(drive, &toc->capacity, &sectors_per_frame,
1855                                    sense);
1856         if (stat)
1857                 toc->capacity = 0x1fffff;
1858
1859         set_capacity(info->disk, toc->capacity * sectors_per_frame);
1860         /* Save a private copy of te TOC capacity for error handling */
1861         drive->probed_capacity = toc->capacity * sectors_per_frame;
1862
1863         blk_queue_hardsect_size(drive->queue,
1864                                 sectors_per_frame << SECTOR_BITS);
1865
1866         /* First read just the header, so we know how long the TOC is. */
1867         stat = cdrom_read_tocentry(drive, 0, 1, 0, (char *) &toc->hdr,
1868                                     sizeof(struct atapi_toc_header), sense);
1869         if (stat)
1870                 return stat;
1871
1872         if (info->cd_flags & IDE_CD_FLAG_TOCTRACKS_AS_BCD) {
1873                 toc->hdr.first_track = BCD2BIN(toc->hdr.first_track);
1874                 toc->hdr.last_track  = BCD2BIN(toc->hdr.last_track);
1875         }
1876
1877         ntracks = toc->hdr.last_track - toc->hdr.first_track + 1;
1878         if (ntracks <= 0)
1879                 return -EIO;
1880         if (ntracks > MAX_TRACKS)
1881                 ntracks = MAX_TRACKS;
1882
1883         /* Now read the whole schmeer. */
1884         stat = cdrom_read_tocentry(drive, toc->hdr.first_track, 1, 0,
1885                                   (char *)&toc->hdr,
1886                                    sizeof(struct atapi_toc_header) +
1887                                    (ntracks + 1) *
1888                                    sizeof(struct atapi_toc_entry), sense);
1889
1890         if (stat && toc->hdr.first_track > 1) {
1891                 /* Cds with CDI tracks only don't have any TOC entries,
1892                    despite of this the returned values are
1893                    first_track == last_track = number of CDI tracks + 1,
1894                    so that this case is indistinguishable from the same
1895                    layout plus an additional audio track.
1896                    If we get an error for the regular case, we assume
1897                    a CDI without additional audio tracks. In this case
1898                    the readable TOC is empty (CDI tracks are not included)
1899                    and only holds the Leadout entry. Heiko EiƟfeldt */
1900                 ntracks = 0;
1901                 stat = cdrom_read_tocentry(drive, CDROM_LEADOUT, 1, 0,
1902                                            (char *)&toc->hdr,
1903                                            sizeof(struct atapi_toc_header) +
1904                                            (ntracks + 1) *
1905                                            sizeof(struct atapi_toc_entry),
1906                                            sense);
1907                 if (stat)
1908                         return stat;
1909
1910                 if (info->cd_flags & IDE_CD_FLAG_TOCTRACKS_AS_BCD) {
1911                         toc->hdr.first_track = (u8)BIN2BCD(CDROM_LEADOUT);
1912                         toc->hdr.last_track = (u8)BIN2BCD(CDROM_LEADOUT);
1913                 } else {
1914                         toc->hdr.first_track = CDROM_LEADOUT;
1915                         toc->hdr.last_track = CDROM_LEADOUT;
1916                 }
1917         }
1918
1919         if (stat)
1920                 return stat;
1921
1922         toc->hdr.toc_length = ntohs (toc->hdr.toc_length);
1923
1924         if (info->cd_flags & IDE_CD_FLAG_TOCTRACKS_AS_BCD) {
1925                 toc->hdr.first_track = BCD2BIN(toc->hdr.first_track);
1926                 toc->hdr.last_track  = BCD2BIN(toc->hdr.last_track);
1927         }
1928
1929         for (i = 0; i <= ntracks; i++) {
1930                 if (info->cd_flags & IDE_CD_FLAG_TOCADDR_AS_BCD) {
1931                         if (info->cd_flags & IDE_CD_FLAG_TOCTRACKS_AS_BCD)
1932                                 toc->ent[i].track = BCD2BIN(toc->ent[i].track);
1933                         msf_from_bcd(&toc->ent[i].addr.msf);
1934                 }
1935                 toc->ent[i].addr.lba = msf_to_lba (toc->ent[i].addr.msf.minute,
1936                                                    toc->ent[i].addr.msf.second,
1937                                                    toc->ent[i].addr.msf.frame);
1938         }
1939
1940         /* Read the multisession information. */
1941         if (toc->hdr.first_track != CDROM_LEADOUT) {
1942                 /* Read the multisession information. */
1943                 stat = cdrom_read_tocentry(drive, 0, 0, 1, (char *)&ms_tmp,
1944                                            sizeof(ms_tmp), sense);
1945                 if (stat)
1946                         return stat;
1947
1948                 toc->last_session_lba = be32_to_cpu(ms_tmp.ent.addr.lba);
1949         } else {
1950                 ms_tmp.hdr.first_track = ms_tmp.hdr.last_track = CDROM_LEADOUT;
1951                 toc->last_session_lba = msf_to_lba(0, 2, 0); /* 0m 2s 0f */
1952         }
1953
1954         if (info->cd_flags & IDE_CD_FLAG_TOCADDR_AS_BCD) {
1955                 /* Re-read multisession information using MSF format */
1956                 stat = cdrom_read_tocentry(drive, 0, 1, 1, (char *)&ms_tmp,
1957                                            sizeof(ms_tmp), sense);
1958                 if (stat)
1959                         return stat;
1960
1961                 msf_from_bcd (&ms_tmp.ent.addr.msf);
1962                 toc->last_session_lba = msf_to_lba(ms_tmp.ent.addr.msf.minute,
1963                                                    ms_tmp.ent.addr.msf.second,
1964                                                    ms_tmp.ent.addr.msf.frame);
1965         }
1966
1967         toc->xa_flag = (ms_tmp.hdr.first_track != ms_tmp.hdr.last_track);
1968
1969         /* Now try to get the total cdrom capacity. */
1970         stat = cdrom_get_last_written(cdi, &last_written);
1971         if (!stat && (last_written > toc->capacity)) {
1972                 toc->capacity = last_written;
1973                 set_capacity(info->disk, toc->capacity * sectors_per_frame);
1974                 drive->probed_capacity = toc->capacity * sectors_per_frame;
1975         }
1976
1977         /* Remember that we've read this stuff. */
1978         info->cd_flags |= IDE_CD_FLAG_TOC_VALID;
1979
1980         return 0;
1981 }
1982
1983 static int ide_cd_read_tochdr(ide_drive_t *drive, void *arg)
1984 {
1985         struct cdrom_info *cd = drive->driver_data;
1986         struct cdrom_tochdr *tochdr = arg;
1987         struct atapi_toc *toc;
1988         int stat;
1989
1990         /* Make sure our saved TOC is valid. */
1991         stat = cdrom_read_toc(drive, NULL);
1992         if (stat)
1993                 return stat;
1994
1995         toc = cd->toc;
1996         tochdr->cdth_trk0 = toc->hdr.first_track;
1997         tochdr->cdth_trk1 = toc->hdr.last_track;
1998
1999         return 0;
2000 }
2001
2002 static int cdrom_get_toc_entry(ide_drive_t *drive, int track,
2003                                 struct atapi_toc_entry **ent)
2004 {
2005         struct cdrom_info *info = drive->driver_data;
2006         struct atapi_toc *toc = info->toc;
2007         int ntracks;
2008
2009         /*
2010          * don't serve cached data, if the toc isn't valid
2011          */
2012         if ((info->cd_flags & IDE_CD_FLAG_TOC_VALID) == 0)
2013                 return -EINVAL;
2014
2015         /* Check validity of requested track number. */
2016         ntracks = toc->hdr.last_track - toc->hdr.first_track + 1;
2017         if (toc->hdr.first_track == CDROM_LEADOUT) ntracks = 0;
2018         if (track == CDROM_LEADOUT)
2019                 *ent = &toc->ent[ntracks];
2020         else if (track < toc->hdr.first_track ||
2021                  track > toc->hdr.last_track)
2022                 return -EINVAL;
2023         else
2024                 *ent = &toc->ent[track - toc->hdr.first_track];
2025
2026         return 0;
2027 }
2028
2029 static int ide_cd_read_tocentry(ide_drive_t *drive, void *arg)
2030 {
2031         struct cdrom_tocentry *tocentry = arg;
2032         struct atapi_toc_entry *toce;
2033         int stat;
2034
2035         stat = cdrom_get_toc_entry(drive, tocentry->cdte_track, &toce);
2036         if (stat)
2037                 return stat;
2038
2039         tocentry->cdte_ctrl = toce->control;
2040         tocentry->cdte_adr  = toce->adr;
2041         if (tocentry->cdte_format == CDROM_MSF) {
2042                 lba_to_msf(toce->addr.lba,
2043                            &tocentry->cdte_addr.msf.minute,
2044                            &tocentry->cdte_addr.msf.second,
2045                            &tocentry->cdte_addr.msf.frame);
2046         } else
2047                 tocentry->cdte_addr.lba = toce->addr.lba;
2048
2049         return 0;
2050 }
2051
2052 static int ide_cd_fake_play_trkind(ide_drive_t *drive, void *arg)
2053 {
2054         struct cdrom_ti *ti = arg;
2055         struct atapi_toc_entry *first_toc, *last_toc;
2056         unsigned long lba_start, lba_end;
2057         int stat;
2058         struct request rq;
2059         struct request_sense sense;
2060
2061         stat = cdrom_get_toc_entry(drive, ti->cdti_trk0, &first_toc);
2062         if (stat)
2063                 return stat;
2064
2065         stat = cdrom_get_toc_entry(drive, ti->cdti_trk1, &last_toc);
2066         if (stat)
2067                 return stat;
2068
2069         if (ti->cdti_trk1 != CDROM_LEADOUT)
2070                 ++last_toc;
2071         lba_start = first_toc->addr.lba;
2072         lba_end   = last_toc->addr.lba;
2073
2074         if (lba_end <= lba_start)
2075                 return -EINVAL;
2076
2077         cdrom_prepare_request(drive, &rq);
2078
2079         rq.sense = &sense;
2080         rq.cmd[0] = GPCMD_PLAY_AUDIO_MSF;
2081         lba_to_msf(lba_start,   &rq.cmd[3], &rq.cmd[4], &rq.cmd[5]);
2082         lba_to_msf(lba_end - 1, &rq.cmd[6], &rq.cmd[7], &rq.cmd[8]);
2083
2084         return cdrom_queue_packet_command(drive, &rq);
2085 }
2086
2087 /* the generic packet interface to cdrom.c */
2088 static int ide_cdrom_packet(struct cdrom_device_info *cdi,
2089                             struct packet_command *cgc)
2090 {
2091         struct request req;
2092         ide_drive_t *drive = cdi->handle;
2093
2094         if (cgc->timeout <= 0)
2095                 cgc->timeout = ATAPI_WAIT_PC;
2096
2097         /* here we queue the commands from the uniform CD-ROM
2098            layer. the packet must be complete, as we do not
2099            touch it at all. */
2100         cdrom_prepare_request(drive, &req);
2101         memcpy(req.cmd, cgc->cmd, CDROM_PACKET_SIZE);
2102         if (cgc->sense)
2103                 memset(cgc->sense, 0, sizeof(struct request_sense));
2104         req.data = cgc->buffer;
2105         req.data_len = cgc->buflen;
2106         req.timeout = cgc->timeout;
2107
2108         if (cgc->quiet)
2109                 req.cmd_flags |= REQ_QUIET;
2110
2111         req.sense = cgc->sense;
2112         cgc->stat = cdrom_queue_packet_command(drive, &req);
2113         if (!cgc->stat)
2114                 cgc->buflen -= req.data_len;
2115         return cgc->stat;
2116 }
2117
2118 static int ide_cdrom_audio_ioctl(struct cdrom_device_info *cdi,
2119                                  unsigned int cmd, void *arg)
2120 {
2121         ide_drive_t *drive = cdi->handle;
2122
2123         switch (cmd) {
2124         /*
2125          * emulate PLAY_AUDIO_TI command with PLAY_AUDIO_10, since
2126          * atapi doesn't support it
2127          */
2128         case CDROMPLAYTRKIND:
2129                 return ide_cd_fake_play_trkind(drive, arg);
2130         case CDROMREADTOCHDR:
2131                 return ide_cd_read_tochdr(drive, arg);
2132         case CDROMREADTOCENTRY:
2133                 return ide_cd_read_tocentry(drive, arg);
2134         default:
2135                 return -EINVAL;
2136         }
2137 }
2138
2139 static
2140 int ide_cdrom_reset (struct cdrom_device_info *cdi)
2141 {
2142         ide_drive_t *drive = cdi->handle;
2143         struct cdrom_info *cd = drive->driver_data;
2144         struct request_sense sense;
2145         struct request req;
2146         int ret;
2147
2148         cdrom_prepare_request(drive, &req);
2149         req.cmd_type = REQ_TYPE_SPECIAL;
2150         req.cmd_flags = REQ_QUIET;
2151         ret = ide_do_drive_cmd(drive, &req, ide_wait);
2152
2153         /*
2154          * A reset will unlock the door. If it was previously locked,
2155          * lock it again.
2156          */
2157         if (cd->cd_flags & IDE_CD_FLAG_DOOR_LOCKED)
2158                 (void) cdrom_lockdoor(drive, 1, &sense);
2159
2160         return ret;
2161 }
2162
2163
2164 static
2165 int ide_cdrom_tray_move (struct cdrom_device_info *cdi, int position)
2166 {
2167         ide_drive_t *drive = cdi->handle;
2168         struct request_sense sense;
2169
2170         if (position) {
2171                 int stat = cdrom_lockdoor(drive, 0, &sense);
2172                 if (stat)
2173                         return stat;
2174         }
2175
2176         return cdrom_eject(drive, !position, &sense);
2177 }
2178
2179 static
2180 int ide_cdrom_lock_door (struct cdrom_device_info *cdi, int lock)
2181 {
2182         ide_drive_t *drive = cdi->handle;
2183         return cdrom_lockdoor(drive, lock, NULL);
2184 }
2185
2186 static int ide_cdrom_get_capabilities(ide_drive_t *drive, u8 *buf)
2187 {
2188         struct cdrom_info *info = drive->driver_data;
2189         struct cdrom_device_info *cdi = &info->devinfo;
2190         struct packet_command cgc;
2191         int stat, attempts = 3, size = ATAPI_CAPABILITIES_PAGE_SIZE;
2192
2193         if ((info->cd_flags & IDE_CD_FLAG_FULL_CAPS_PAGE) == 0)
2194                 size -= ATAPI_CAPABILITIES_PAGE_PAD_SIZE;
2195
2196         init_cdrom_command(&cgc, buf, size, CGC_DATA_UNKNOWN);
2197         do { /* we seem to get stat=0x01,err=0x00 the first time (??) */
2198                 stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
2199                 if (!stat)
2200                         break;
2201         } while (--attempts);
2202         return stat;
2203 }
2204
2205 static void ide_cdrom_update_speed(ide_drive_t *drive, u8 *buf)
2206 {
2207         struct cdrom_info *cd = drive->driver_data;
2208         u16 curspeed, maxspeed;
2209
2210         curspeed = *(u16 *)&buf[8 + 14];
2211         maxspeed = *(u16 *)&buf[8 +  8];
2212
2213         if (cd->cd_flags & IDE_CD_FLAG_LE_SPEED_FIELDS) {
2214                 curspeed = le16_to_cpu(curspeed);
2215                 maxspeed = le16_to_cpu(maxspeed);
2216         } else {
2217                 curspeed = be16_to_cpu(curspeed);
2218                 maxspeed = be16_to_cpu(maxspeed);
2219         }
2220
2221         cd->current_speed = (curspeed + (176/2)) / 176;
2222         cd->max_speed = (maxspeed + (176/2)) / 176;
2223 }
2224
2225 /*
2226  * ATAPI devices are free to select the speed you request or any slower
2227  * rate. :-(  Requesting too fast a speed will _not_ produce an error.
2228  */
2229 static int ide_cdrom_select_speed(struct cdrom_device_info *cdi, int speed)
2230 {
2231         ide_drive_t *drive = cdi->handle;
2232         struct cdrom_info *cd = drive->driver_data;
2233         struct request rq;
2234         struct request_sense sense;
2235         u8 buf[ATAPI_CAPABILITIES_PAGE_SIZE];
2236         int stat;
2237
2238         cdrom_prepare_request(drive, &rq);
2239
2240         rq.sense = &sense;
2241
2242         if (speed == 0)
2243                 speed = 0xffff; /* set to max */
2244         else
2245                 speed *= 177;   /* Nx to kbytes/s */
2246
2247         rq.cmd[0] = GPCMD_SET_SPEED;
2248         /* Read Drive speed in kbytes/second MSB/LSB */
2249         rq.cmd[2] = (speed >> 8) & 0xff;
2250         rq.cmd[3] = speed & 0xff;
2251         if ((cdi->mask & (CDC_CD_R | CDC_CD_RW | CDC_DVD_R)) !=
2252             (CDC_CD_R | CDC_CD_RW | CDC_DVD_R)) {
2253                 /* Write Drive speed in kbytes/second MSB/LSB */
2254                 rq.cmd[4] = (speed >> 8) & 0xff;
2255                 rq.cmd[5] = speed & 0xff;
2256         }
2257
2258         stat = cdrom_queue_packet_command(drive, &rq);
2259
2260         if (!ide_cdrom_get_capabilities(drive, buf)) {
2261                 ide_cdrom_update_speed(drive, buf);
2262                 cdi->speed = cd->current_speed;
2263         }
2264
2265         return 0;
2266 }
2267
2268 /*
2269  * add logic to try GET_EVENT command first to check for media and tray
2270  * status. this should be supported by newer cd-r/w and all DVD etc
2271  * drives
2272  */
2273 static
2274 int ide_cdrom_drive_status (struct cdrom_device_info *cdi, int slot_nr)
2275 {
2276         ide_drive_t *drive = cdi->handle;
2277         struct media_event_desc med;
2278         struct request_sense sense;
2279         int stat;
2280
2281         if (slot_nr != CDSL_CURRENT)
2282                 return -EINVAL;
2283
2284         stat = cdrom_check_status(drive, &sense);
2285         if (!stat || sense.sense_key == UNIT_ATTENTION)
2286                 return CDS_DISC_OK;
2287
2288         if (!cdrom_get_media_event(cdi, &med)) {
2289                 if (med.media_present)
2290                         return CDS_DISC_OK;
2291                 else if (med.door_open)
2292                         return CDS_TRAY_OPEN;
2293                 else
2294                         return CDS_NO_DISC;
2295         }
2296
2297         if (sense.sense_key == NOT_READY && sense.asc == 0x04 && sense.ascq == 0x04)
2298                 return CDS_DISC_OK;
2299
2300         /*
2301          * If not using Mt Fuji extended media tray reports,
2302          * just return TRAY_OPEN since ATAPI doesn't provide
2303          * any other way to detect this...
2304          */
2305         if (sense.sense_key == NOT_READY) {
2306                 if (sense.asc == 0x3a && sense.ascq == 1)
2307                         return CDS_NO_DISC;
2308                 else
2309                         return CDS_TRAY_OPEN;
2310         }
2311         return CDS_DRIVE_NOT_READY;
2312 }
2313
2314 static
2315 int ide_cdrom_get_last_session (struct cdrom_device_info *cdi,
2316                                 struct cdrom_multisession *ms_info)
2317 {
2318         struct atapi_toc *toc;
2319         ide_drive_t *drive = cdi->handle;
2320         struct cdrom_info *info = drive->driver_data;
2321         struct request_sense sense;
2322         int ret;
2323
2324         if ((info->cd_flags & IDE_CD_FLAG_TOC_VALID) == 0 || info->toc == NULL)
2325                 if ((ret = cdrom_read_toc(drive, &sense)))
2326                         return ret;
2327
2328         toc = info->toc;
2329         ms_info->addr.lba = toc->last_session_lba;
2330         ms_info->xa_flag = toc->xa_flag;
2331
2332         return 0;
2333 }
2334
2335 static int ide_cdrom_get_mcn(struct cdrom_device_info *cdi,
2336                              struct cdrom_mcn *mcn_info)
2337 {
2338         ide_drive_t *drive = cdi->handle;
2339         int stat, mcnlen;
2340         struct request rq;
2341         char buf[24];
2342
2343         cdrom_prepare_request(drive, &rq);
2344
2345         rq.data = buf;
2346         rq.data_len = sizeof(buf);
2347
2348         rq.cmd[0] = GPCMD_READ_SUBCHANNEL;
2349         rq.cmd[1] = 2;          /* MSF addressing */
2350         rq.cmd[2] = 0x40;       /* request subQ data */
2351         rq.cmd[3] = 2;          /* format */
2352         rq.cmd[8] = sizeof(buf);
2353
2354         stat = cdrom_queue_packet_command(drive, &rq);
2355         if (stat)
2356                 return stat;
2357
2358         mcnlen = sizeof(mcn_info->medium_catalog_number) - 1;
2359         memcpy(mcn_info->medium_catalog_number, buf + 9, mcnlen);
2360         mcn_info->medium_catalog_number[mcnlen] = '\0';
2361
2362         return 0;
2363 }
2364
2365 /****************************************************************************
2366  * Other driver requests (open, close, check media change).
2367  */
2368
2369 static
2370 int ide_cdrom_check_media_change_real (struct cdrom_device_info *cdi,
2371                                        int slot_nr)
2372 {
2373         ide_drive_t *drive = cdi->handle;
2374         struct cdrom_info *cd = drive->driver_data;
2375         int retval;
2376
2377         if (slot_nr == CDSL_CURRENT) {
2378                 (void) cdrom_check_status(drive, NULL);
2379                 retval = (cd->cd_flags & IDE_CD_FLAG_MEDIA_CHANGED) ? 1 : 0;
2380                 cd->cd_flags &= ~IDE_CD_FLAG_MEDIA_CHANGED;
2381                 return retval;
2382         } else {
2383                 return -EINVAL;
2384         }
2385 }
2386
2387
2388 static
2389 int ide_cdrom_open_real (struct cdrom_device_info *cdi, int purpose)
2390 {
2391         return 0;
2392 }
2393
2394 /*
2395  * Close down the device.  Invalidate all cached blocks.
2396  */
2397
2398 static
2399 void ide_cdrom_release_real (struct cdrom_device_info *cdi)
2400 {
2401         ide_drive_t *drive = cdi->handle;
2402         struct cdrom_info *cd = drive->driver_data;
2403
2404         if (!cdi->use_count)
2405                 cd->cd_flags &= ~IDE_CD_FLAG_TOC_VALID;
2406 }
2407
2408 #define IDE_CD_CAPABILITIES \
2409         (CDC_CLOSE_TRAY | CDC_OPEN_TRAY | CDC_LOCK | CDC_SELECT_SPEED | \
2410          CDC_SELECT_DISC | CDC_MULTI_SESSION | CDC_MCN | CDC_MEDIA_CHANGED | \
2411          CDC_PLAY_AUDIO | CDC_RESET | CDC_DRIVE_STATUS | CDC_CD_R | \
2412          CDC_CD_RW | CDC_DVD | CDC_DVD_R | CDC_DVD_RAM | CDC_GENERIC_PACKET | \
2413          CDC_MO_DRIVE | CDC_MRW | CDC_MRW_W | CDC_RAM)
2414
2415 static struct cdrom_device_ops ide_cdrom_dops = {
2416         .open                   = ide_cdrom_open_real,
2417         .release                = ide_cdrom_release_real,
2418         .drive_status           = ide_cdrom_drive_status,
2419         .media_changed          = ide_cdrom_check_media_change_real,
2420         .tray_move              = ide_cdrom_tray_move,
2421         .lock_door              = ide_cdrom_lock_door,
2422         .select_speed           = ide_cdrom_select_speed,
2423         .get_last_session       = ide_cdrom_get_last_session,
2424         .get_mcn                = ide_cdrom_get_mcn,
2425         .reset                  = ide_cdrom_reset,
2426         .audio_ioctl            = ide_cdrom_audio_ioctl,
2427         .capability             = IDE_CD_CAPABILITIES,
2428         .generic_packet         = ide_cdrom_packet,
2429 };
2430
2431 static int ide_cdrom_register (ide_drive_t *drive, int nslots)
2432 {
2433         struct cdrom_info *info = drive->driver_data;
2434         struct cdrom_device_info *devinfo = &info->devinfo;
2435
2436         devinfo->ops = &ide_cdrom_dops;
2437         devinfo->speed = info->current_speed;
2438         devinfo->capacity = nslots;
2439         devinfo->handle = drive;
2440         strcpy(devinfo->name, drive->name);
2441
2442         if (info->cd_flags & IDE_CD_FLAG_NO_SPEED_SELECT)
2443                 devinfo->mask |= CDC_SELECT_SPEED;
2444
2445         devinfo->disk = info->disk;
2446         return register_cdrom(devinfo);
2447 }
2448
2449 static
2450 int ide_cdrom_probe_capabilities (ide_drive_t *drive)
2451 {
2452         struct cdrom_info *cd = drive->driver_data;
2453         struct cdrom_device_info *cdi = &cd->devinfo;
2454         u8 buf[ATAPI_CAPABILITIES_PAGE_SIZE];
2455         mechtype_t mechtype;
2456         int nslots = 1;
2457
2458         cdi->mask = (CDC_CD_R | CDC_CD_RW | CDC_DVD | CDC_DVD_R |
2459                      CDC_DVD_RAM | CDC_SELECT_DISC | CDC_PLAY_AUDIO |
2460                      CDC_MO_DRIVE | CDC_RAM);
2461
2462         if (drive->media == ide_optical) {
2463                 cdi->mask &= ~(CDC_MO_DRIVE | CDC_RAM);
2464                 printk(KERN_ERR "%s: ATAPI magneto-optical drive\n", drive->name);
2465                 return nslots;
2466         }
2467
2468         if (cd->cd_flags & IDE_CD_FLAG_PRE_ATAPI12) {
2469                 cd->cd_flags &= ~IDE_CD_FLAG_NO_EJECT;
2470                 cdi->mask &= ~CDC_PLAY_AUDIO;
2471                 return nslots;
2472         }
2473
2474         /*
2475          * we have to cheat a little here. the packet will eventually
2476          * be queued with ide_cdrom_packet(), which extracts the
2477          * drive from cdi->handle. Since this device hasn't been
2478          * registered with the Uniform layer yet, it can't do this.
2479          * Same goes for cdi->ops.
2480          */
2481         cdi->handle = drive;
2482         cdi->ops = &ide_cdrom_dops;
2483
2484         if (ide_cdrom_get_capabilities(drive, buf))
2485                 return 0;
2486
2487         if ((buf[8 + 6] & 0x01) == 0)
2488                 cd->cd_flags |= IDE_CD_FLAG_NO_DOORLOCK;
2489         if (buf[8 + 6] & 0x08)
2490                 cd->cd_flags &= ~IDE_CD_FLAG_NO_EJECT;
2491         if (buf[8 + 3] & 0x01)
2492                 cdi->mask &= ~CDC_CD_R;
2493         if (buf[8 + 3] & 0x02)
2494                 cdi->mask &= ~(CDC_CD_RW | CDC_RAM);
2495         if (buf[8 + 2] & 0x38)
2496                 cdi->mask &= ~CDC_DVD;
2497         if (buf[8 + 3] & 0x20)
2498                 cdi->mask &= ~(CDC_DVD_RAM | CDC_RAM);
2499         if (buf[8 + 3] & 0x10)
2500                 cdi->mask &= ~CDC_DVD_R;
2501         if ((buf[8 + 4] & 0x01) || (cd->cd_flags & IDE_CD_FLAG_PLAY_AUDIO_OK))
2502                 cdi->mask &= ~CDC_PLAY_AUDIO;
2503
2504         mechtype = buf[8 + 6] >> 5;
2505         if (mechtype == mechtype_caddy || mechtype == mechtype_popup)
2506                 cdi->mask |= CDC_CLOSE_TRAY;
2507
2508         if (cdi->sanyo_slot > 0) {
2509                 cdi->mask &= ~CDC_SELECT_DISC;
2510                 nslots = 3;
2511         } else if (mechtype == mechtype_individual_changer ||
2512                    mechtype == mechtype_cartridge_changer) {
2513                 nslots = cdrom_number_of_slots(cdi);
2514                 if (nslots > 1)
2515                         cdi->mask &= ~CDC_SELECT_DISC;
2516         }
2517
2518         ide_cdrom_update_speed(drive, buf);
2519
2520         printk(KERN_INFO "%s: ATAPI", drive->name);
2521
2522         /* don't print speed if the drive reported 0 */
2523         if (cd->max_speed)
2524                 printk(KERN_CONT " %dX", cd->max_speed);
2525
2526         printk(KERN_CONT " %s", (cdi->mask & CDC_DVD) ? "CD-ROM" : "DVD-ROM");
2527
2528         if ((cdi->mask & CDC_DVD_R) == 0 || (cdi->mask & CDC_DVD_RAM) == 0)
2529                 printk(KERN_CONT " DVD%s%s",
2530                                  (cdi->mask & CDC_DVD_R) ? "" : "-R",
2531                                  (cdi->mask & CDC_DVD_RAM) ? "" : "-RAM");
2532
2533         if ((cdi->mask & CDC_CD_R) == 0 || (cdi->mask & CDC_CD_RW) == 0)
2534                 printk(KERN_CONT " CD%s%s",
2535                                  (cdi->mask & CDC_CD_R) ? "" : "-R",
2536                                  (cdi->mask & CDC_CD_RW) ? "" : "/RW");
2537
2538         if ((cdi->mask & CDC_SELECT_DISC) == 0)
2539                 printk(KERN_CONT " changer w/%d slots", nslots);
2540         else
2541                 printk(KERN_CONT " drive");
2542
2543         printk(KERN_CONT ", %dkB Cache\n", be16_to_cpu(*(u16 *)&buf[8 + 12]));
2544
2545         return nslots;
2546 }
2547
2548 #ifdef CONFIG_IDE_PROC_FS
2549 static void ide_cdrom_add_settings(ide_drive_t *drive)
2550 {
2551         ide_add_setting(drive, "dsc_overlap", SETTING_RW, TYPE_BYTE, 0, 1, 1, 1, &drive->dsc_overlap, NULL);
2552 }
2553 #else
2554 static inline void ide_cdrom_add_settings(ide_drive_t *drive) { ; }
2555 #endif
2556
2557 /*
2558  * standard prep_rq_fn that builds 10 byte cmds
2559  */
2560 static int ide_cdrom_prep_fs(struct request_queue *q, struct request *rq)
2561 {
2562         int hard_sect = queue_hardsect_size(q);
2563         long block = (long)rq->hard_sector / (hard_sect >> 9);
2564         unsigned long blocks = rq->hard_nr_sectors / (hard_sect >> 9);
2565
2566         memset(rq->cmd, 0, sizeof(rq->cmd));
2567
2568         if (rq_data_dir(rq) == READ)
2569                 rq->cmd[0] = GPCMD_READ_10;
2570         else
2571                 rq->cmd[0] = GPCMD_WRITE_10;
2572
2573         /*
2574          * fill in lba
2575          */
2576         rq->cmd[2] = (block >> 24) & 0xff;
2577         rq->cmd[3] = (block >> 16) & 0xff;
2578         rq->cmd[4] = (block >>  8) & 0xff;
2579         rq->cmd[5] = block & 0xff;
2580
2581         /*
2582          * and transfer length
2583          */
2584         rq->cmd[7] = (blocks >> 8) & 0xff;
2585         rq->cmd[8] = blocks & 0xff;
2586         rq->cmd_len = 10;
2587         return BLKPREP_OK;
2588 }
2589
2590 /*
2591  * Most of the SCSI commands are supported directly by ATAPI devices.
2592  * This transform handles the few exceptions.
2593  */
2594 static int ide_cdrom_prep_pc(struct request *rq)
2595 {
2596         u8 *c = rq->cmd;
2597
2598         /*
2599          * Transform 6-byte read/write commands to the 10-byte version
2600          */
2601         if (c[0] == READ_6 || c[0] == WRITE_6) {
2602                 c[8] = c[4];
2603                 c[5] = c[3];
2604                 c[4] = c[2];
2605                 c[3] = c[1] & 0x1f;
2606                 c[2] = 0;
2607                 c[1] &= 0xe0;
2608                 c[0] += (READ_10 - READ_6);
2609                 rq->cmd_len = 10;
2610                 return BLKPREP_OK;
2611         }
2612
2613         /*
2614          * it's silly to pretend we understand 6-byte sense commands, just
2615          * reject with ILLEGAL_REQUEST and the caller should take the
2616          * appropriate action
2617          */
2618         if (c[0] == MODE_SENSE || c[0] == MODE_SELECT) {
2619                 rq->errors = ILLEGAL_REQUEST;
2620                 return BLKPREP_KILL;
2621         }
2622         
2623         return BLKPREP_OK;
2624 }
2625
2626 static int ide_cdrom_prep_fn(struct request_queue *q, struct request *rq)
2627 {
2628         if (blk_fs_request(rq))
2629                 return ide_cdrom_prep_fs(q, rq);
2630         else if (blk_pc_request(rq))
2631                 return ide_cdrom_prep_pc(rq);
2632
2633         return 0;
2634 }
2635
2636 struct cd_list_entry {
2637         const char      *id_model;
2638         const char      *id_firmware;
2639         unsigned int    cd_flags;
2640 };
2641
2642 static const struct cd_list_entry ide_cd_quirks_list[] = {
2643         /* Limit transfer size per interrupt. */
2644         { "SAMSUNG CD-ROM SCR-2430", NULL,   IDE_CD_FLAG_LIMIT_NFRAMES      },
2645         { "SAMSUNG CD-ROM SCR-2432", NULL,   IDE_CD_FLAG_LIMIT_NFRAMES      },
2646         /* SCR-3231 doesn't support the SET_CD_SPEED command. */
2647         { "SAMSUNG CD-ROM SCR-3231", NULL,   IDE_CD_FLAG_NO_SPEED_SELECT    },
2648         /* Old NEC260 (not R) was released before ATAPI 1.2 spec. */
2649         { "NEC CD-ROM DRIVE:260",    "1.01", IDE_CD_FLAG_TOCADDR_AS_BCD |
2650                                              IDE_CD_FLAG_PRE_ATAPI12,       },
2651         /* Vertos 300, some versions of this drive like to talk BCD. */
2652         { "V003S0DS",                NULL,   IDE_CD_FLAG_VERTOS_300_SSD,    },
2653         /* Vertos 600 ESD. */
2654         { "V006E0DS",                NULL,   IDE_CD_FLAG_VERTOS_600_ESD,    },
2655         /*
2656          * Sanyo 3 CD changer uses a non-standard command for CD changing
2657          * (by default standard ATAPI support for CD changers is used).
2658          */
2659         { "CD-ROM CDR-C3 G",         NULL,   IDE_CD_FLAG_SANYO_3CD          },
2660         { "CD-ROM CDR-C3G",          NULL,   IDE_CD_FLAG_SANYO_3CD          },
2661         { "CD-ROM CDR_C36",          NULL,   IDE_CD_FLAG_SANYO_3CD          },
2662         /* Stingray 8X CD-ROM. */
2663         { "STINGRAY 8422 IDE 8X CD-ROM 7-27-95", NULL, IDE_CD_FLAG_PRE_ATAPI12},
2664         /*
2665          * ACER 50X CD-ROM and WPI 32X CD-ROM require the full spec length
2666          * mode sense page capabilities size, but older drives break.
2667          */
2668         { "ATAPI CD ROM DRIVE 50X MAX", NULL,   IDE_CD_FLAG_FULL_CAPS_PAGE  },
2669         { "WPI CDS-32X",                NULL,   IDE_CD_FLAG_FULL_CAPS_PAGE  },
2670         /* ACER/AOpen 24X CD-ROM has the speed fields byte-swapped. */
2671         { "",                        "241N", IDE_CD_FLAG_LE_SPEED_FIELDS    },
2672         /*
2673          * Some drives used by Apple don't advertise audio play
2674          * but they do support reading TOC & audio datas.
2675          */
2676         { "MATSHITADVD-ROM SR-8187", NULL,   IDE_CD_FLAG_PLAY_AUDIO_OK      },
2677         { "MATSHITADVD-ROM SR-8186", NULL,   IDE_CD_FLAG_PLAY_AUDIO_OK      },
2678         { "MATSHITADVD-ROM SR-8176", NULL,   IDE_CD_FLAG_PLAY_AUDIO_OK      },
2679         { "MATSHITADVD-ROM SR-8174", NULL,   IDE_CD_FLAG_PLAY_AUDIO_OK      },
2680         { NULL, NULL, 0 }
2681 };
2682
2683 static unsigned int ide_cd_flags(struct hd_driveid *id)
2684 {
2685         const struct cd_list_entry *cle = ide_cd_quirks_list;
2686
2687         while (cle->id_model) {
2688                 if (strcmp(cle->id_model, id->model) == 0 &&
2689                     (cle->id_firmware == NULL ||
2690                      strstr(id->fw_rev, cle->id_firmware)))
2691                         return cle->cd_flags;
2692                 cle++;
2693         }
2694
2695         return 0;
2696 }
2697
2698 static
2699 int ide_cdrom_setup (ide_drive_t *drive)
2700 {
2701         struct cdrom_info *cd = drive->driver_data;
2702         struct cdrom_device_info *cdi = &cd->devinfo;
2703         struct hd_driveid *id = drive->id;
2704         int nslots;
2705
2706         blk_queue_prep_rq(drive->queue, ide_cdrom_prep_fn);
2707         blk_queue_dma_alignment(drive->queue, 31);
2708         drive->queue->unplug_delay = (1 * HZ) / 1000;
2709         if (!drive->queue->unplug_delay)
2710                 drive->queue->unplug_delay = 1;
2711
2712         drive->special.all      = 0;
2713
2714         cd->cd_flags = IDE_CD_FLAG_MEDIA_CHANGED | IDE_CD_FLAG_NO_EJECT |
2715                        ide_cd_flags(id);
2716
2717         if ((id->config & 0x0060) == 0x20)
2718                 cd->cd_flags |= IDE_CD_FLAG_DRQ_INTERRUPT;
2719
2720         if ((cd->cd_flags & IDE_CD_FLAG_VERTOS_300_SSD) &&
2721             id->fw_rev[4] == '1' && id->fw_rev[6] <= '2')
2722                 cd->cd_flags |= (IDE_CD_FLAG_TOCTRACKS_AS_BCD |
2723                                  IDE_CD_FLAG_TOCADDR_AS_BCD);
2724         else if ((cd->cd_flags & IDE_CD_FLAG_VERTOS_600_ESD) &&
2725                  id->fw_rev[4] == '1' && id->fw_rev[6] <= '2')
2726                 cd->cd_flags |= IDE_CD_FLAG_TOCTRACKS_AS_BCD;
2727         else if (cd->cd_flags & IDE_CD_FLAG_SANYO_3CD)
2728                 cdi->sanyo_slot = 3;    /* 3 => use CD in slot 0 */
2729
2730         nslots = ide_cdrom_probe_capabilities (drive);
2731
2732         /*
2733          * set correct block size
2734          */
2735         blk_queue_hardsect_size(drive->queue, CD_FRAMESIZE);
2736
2737         if (drive->autotune == IDE_TUNE_DEFAULT ||
2738             drive->autotune == IDE_TUNE_AUTO)
2739                 drive->dsc_overlap = (drive->next != drive);
2740
2741         if (ide_cdrom_register(drive, nslots)) {
2742                 printk (KERN_ERR "%s: ide_cdrom_setup failed to register device with the cdrom driver.\n", drive->name);
2743                 cd->devinfo.handle = NULL;
2744                 return 1;
2745         }
2746         ide_cdrom_add_settings(drive);
2747         return 0;
2748 }
2749
2750 #ifdef CONFIG_IDE_PROC_FS
2751 static
2752 sector_t ide_cdrom_capacity (ide_drive_t *drive)
2753 {
2754         unsigned long capacity, sectors_per_frame;
2755
2756         if (cdrom_read_capacity(drive, &capacity, &sectors_per_frame, NULL))
2757                 return 0;
2758
2759         return capacity * sectors_per_frame;
2760 }
2761 #endif
2762
2763 static void ide_cd_remove(ide_drive_t *drive)
2764 {
2765         struct cdrom_info *info = drive->driver_data;
2766
2767         ide_proc_unregister_driver(drive, info->driver);
2768
2769         del_gendisk(info->disk);
2770
2771         ide_cd_put(info);
2772 }
2773
2774 static void ide_cd_release(struct kref *kref)
2775 {
2776         struct cdrom_info *info = to_ide_cd(kref);
2777         struct cdrom_device_info *devinfo = &info->devinfo;
2778         ide_drive_t *drive = info->drive;
2779         struct gendisk *g = info->disk;
2780
2781         kfree(info->buffer);
2782         kfree(info->toc);
2783         if (devinfo->handle == drive && unregister_cdrom(devinfo))
2784                 printk(KERN_ERR "%s: %s failed to unregister device from the cdrom "
2785                                 "driver.\n", __FUNCTION__, drive->name);
2786         drive->dsc_overlap = 0;
2787         drive->driver_data = NULL;
2788         blk_queue_prep_rq(drive->queue, NULL);
2789         g->private_data = NULL;
2790         put_disk(g);
2791         kfree(info);
2792 }
2793
2794 static int ide_cd_probe(ide_drive_t *);
2795
2796 #ifdef CONFIG_IDE_PROC_FS
2797 static int proc_idecd_read_capacity
2798         (char *page, char **start, off_t off, int count, int *eof, void *data)
2799 {
2800         ide_drive_t *drive = data;
2801         int len;
2802
2803         len = sprintf(page,"%llu\n", (long long)ide_cdrom_capacity(drive));
2804         PROC_IDE_READ_RETURN(page,start,off,count,eof,len);
2805 }
2806
2807 static ide_proc_entry_t idecd_proc[] = {
2808         { "capacity", S_IFREG|S_IRUGO, proc_idecd_read_capacity, NULL },
2809         { NULL, 0, NULL, NULL }
2810 };
2811 #endif
2812
2813 static ide_driver_t ide_cdrom_driver = {
2814         .gen_driver = {
2815                 .owner          = THIS_MODULE,
2816                 .name           = "ide-cdrom",
2817                 .bus            = &ide_bus_type,
2818         },
2819         .probe                  = ide_cd_probe,
2820         .remove                 = ide_cd_remove,
2821         .version                = IDECD_VERSION,
2822         .media                  = ide_cdrom,
2823         .supports_dsc_overlap   = 1,
2824         .do_request             = ide_do_rw_cdrom,
2825         .end_request            = ide_end_request,
2826         .error                  = __ide_error,
2827         .abort                  = __ide_abort,
2828 #ifdef CONFIG_IDE_PROC_FS
2829         .proc                   = idecd_proc,
2830 #endif
2831 };
2832
2833 static int idecd_open(struct inode * inode, struct file * file)
2834 {
2835         struct gendisk *disk = inode->i_bdev->bd_disk;
2836         struct cdrom_info *info;
2837         int rc = -ENOMEM;
2838
2839         if (!(info = ide_cd_get(disk)))
2840                 return -ENXIO;
2841
2842         if (!info->buffer)
2843                 info->buffer = kmalloc(SECTOR_BUFFER_SIZE, GFP_KERNEL|__GFP_REPEAT);
2844
2845         if (info->buffer)
2846                 rc = cdrom_open(&info->devinfo, inode, file);
2847
2848         if (rc < 0)
2849                 ide_cd_put(info);
2850
2851         return rc;
2852 }
2853
2854 static int idecd_release(struct inode * inode, struct file * file)
2855 {
2856         struct gendisk *disk = inode->i_bdev->bd_disk;
2857         struct cdrom_info *info = ide_cd_g(disk);
2858
2859         cdrom_release (&info->devinfo, file);
2860
2861         ide_cd_put(info);
2862
2863         return 0;
2864 }
2865
2866 static int idecd_set_spindown(struct cdrom_device_info *cdi, unsigned long arg)
2867 {
2868         struct packet_command cgc;
2869         char buffer[16];
2870         int stat;
2871         char spindown;
2872
2873         if (copy_from_user(&spindown, (void __user *)arg, sizeof(char)))
2874                 return -EFAULT;
2875
2876         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
2877
2878         stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0);
2879         if (stat)
2880                 return stat;
2881
2882         buffer[11] = (buffer[11] & 0xf0) | (spindown & 0x0f);
2883         return cdrom_mode_select(cdi, &cgc);
2884 }
2885
2886 static int idecd_get_spindown(struct cdrom_device_info *cdi, unsigned long arg)
2887 {
2888         struct packet_command cgc;
2889         char buffer[16];
2890         int stat;
2891         char spindown;
2892
2893         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
2894
2895         stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0);
2896         if (stat)
2897                 return stat;
2898
2899         spindown = buffer[11] & 0x0f;
2900         if (copy_to_user((void __user *)arg, &spindown, sizeof (char)))
2901                 return -EFAULT;
2902         return 0;
2903 }
2904
2905 static int idecd_ioctl (struct inode *inode, struct file *file,
2906                         unsigned int cmd, unsigned long arg)
2907 {
2908         struct block_device *bdev = inode->i_bdev;
2909         struct cdrom_info *info = ide_cd_g(bdev->bd_disk);
2910         int err;
2911
2912         switch (cmd) {
2913         case CDROMSETSPINDOWN:
2914                 return idecd_set_spindown(&info->devinfo, arg);
2915         case CDROMGETSPINDOWN:
2916                 return idecd_get_spindown(&info->devinfo, arg);
2917         default:
2918                 break;
2919         }
2920
2921         err = generic_ide_ioctl(info->drive, file, bdev, cmd, arg);
2922         if (err == -EINVAL)
2923                 err = cdrom_ioctl(file, &info->devinfo, inode, cmd, arg);
2924
2925         return err;
2926 }
2927
2928 static int idecd_media_changed(struct gendisk *disk)
2929 {
2930         struct cdrom_info *info = ide_cd_g(disk);
2931         return cdrom_media_changed(&info->devinfo);
2932 }
2933
2934 static int idecd_revalidate_disk(struct gendisk *disk)
2935 {
2936         struct cdrom_info *info = ide_cd_g(disk);
2937         struct request_sense sense;
2938         cdrom_read_toc(info->drive, &sense);
2939         return  0;
2940 }
2941
2942 static struct block_device_operations idecd_ops = {
2943         .owner          = THIS_MODULE,
2944         .open           = idecd_open,
2945         .release        = idecd_release,
2946         .ioctl          = idecd_ioctl,
2947         .media_changed  = idecd_media_changed,
2948         .revalidate_disk= idecd_revalidate_disk
2949 };
2950
2951 /* options */
2952 static char *ignore = NULL;
2953
2954 module_param(ignore, charp, 0400);
2955 MODULE_DESCRIPTION("ATAPI CD-ROM Driver");
2956
2957 static int ide_cd_probe(ide_drive_t *drive)
2958 {
2959         struct cdrom_info *info;
2960         struct gendisk *g;
2961         struct request_sense sense;
2962
2963         if (!strstr("ide-cdrom", drive->driver_req))
2964                 goto failed;
2965         if (!drive->present)
2966                 goto failed;
2967         if (drive->media != ide_cdrom && drive->media != ide_optical)
2968                 goto failed;
2969         /* skip drives that we were told to ignore */
2970         if (ignore != NULL) {
2971                 if (strstr(ignore, drive->name)) {
2972                         printk(KERN_INFO "ide-cd: ignoring drive %s\n", drive->name);
2973                         goto failed;
2974                 }
2975         }
2976         if (drive->scsi) {
2977                 printk(KERN_INFO "ide-cd: passing drive %s to ide-scsi emulation.\n", drive->name);
2978                 goto failed;
2979         }
2980         info = kzalloc(sizeof(struct cdrom_info), GFP_KERNEL);
2981         if (info == NULL) {
2982                 printk(KERN_ERR "%s: Can't allocate a cdrom structure\n", drive->name);
2983                 goto failed;
2984         }
2985
2986         g = alloc_disk(1 << PARTN_BITS);
2987         if (!g)
2988                 goto out_free_cd;
2989
2990         ide_init_disk(g, drive);
2991
2992         ide_proc_register_driver(drive, &ide_cdrom_driver);
2993
2994         kref_init(&info->kref);
2995
2996         info->drive = drive;
2997         info->driver = &ide_cdrom_driver;
2998         info->disk = g;
2999
3000         g->private_data = &info->driver;
3001
3002         drive->driver_data = info;
3003
3004         g->minors = 1;
3005         g->driverfs_dev = &drive->gendev;
3006         g->flags = GENHD_FL_CD | GENHD_FL_REMOVABLE;
3007         if (ide_cdrom_setup(drive)) {
3008                 ide_proc_unregister_driver(drive, &ide_cdrom_driver);
3009                 ide_cd_release(&info->kref);
3010                 goto failed;
3011         }
3012
3013         cdrom_read_toc(drive, &sense);
3014         g->fops = &idecd_ops;
3015         g->flags |= GENHD_FL_REMOVABLE;
3016         add_disk(g);
3017         return 0;
3018
3019 out_free_cd:
3020         kfree(info);
3021 failed:
3022         return -ENODEV;
3023 }
3024
3025 static void __exit ide_cdrom_exit(void)
3026 {
3027         driver_unregister(&ide_cdrom_driver.gen_driver);
3028 }
3029
3030 static int __init ide_cdrom_init(void)
3031 {
3032         return driver_register(&ide_cdrom_driver.gen_driver);
3033 }
3034
3035 MODULE_ALIAS("ide:*m-cdrom*");
3036 MODULE_ALIAS("ide-cd");
3037 module_init(ide_cdrom_init);
3038 module_exit(ide_cdrom_exit);
3039 MODULE_LICENSE("GPL");