ide: add ->read_status method
[firefly-linux-kernel-4.4.55.git] / drivers / ide / ide-cd.c
1 /*
2  * ATAPI CD-ROM driver.
3  *
4  * Copyright (C) 1994-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  * Copyright (C) 2005, 2007  Bartlomiej Zolnierkiewicz
8  *
9  * May be copied or modified under the terms of the GNU General Public
10  * License.  See linux/COPYING for more information.
11  *
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  * For historical changelog please see:
23  *      Documentation/ide/ChangeLog.ide-cd.1994-2004
24  */
25
26 #define IDECD_VERSION "5.00"
27
28 #include <linux/module.h>
29 #include <linux/types.h>
30 #include <linux/kernel.h>
31 #include <linux/delay.h>
32 #include <linux/timer.h>
33 #include <linux/slab.h>
34 #include <linux/interrupt.h>
35 #include <linux/errno.h>
36 #include <linux/cdrom.h>
37 #include <linux/ide.h>
38 #include <linux/completion.h>
39 #include <linux/mutex.h>
40 #include <linux/bcd.h>
41
42 /* For SCSI -> ATAPI command conversion */
43 #include <scsi/scsi.h>
44
45 #include <linux/irq.h>
46 #include <linux/io.h>
47 #include <asm/byteorder.h>
48 #include <linux/uaccess.h>
49 #include <asm/unaligned.h>
50
51 #include "ide-cd.h"
52
53 static DEFINE_MUTEX(idecd_ref_mutex);
54
55 #define to_ide_cd(obj) container_of(obj, struct cdrom_info, kref)
56
57 #define ide_cd_g(disk) \
58         container_of((disk)->private_data, struct cdrom_info, driver)
59
60 static struct cdrom_info *ide_cd_get(struct gendisk *disk)
61 {
62         struct cdrom_info *cd = NULL;
63
64         mutex_lock(&idecd_ref_mutex);
65         cd = ide_cd_g(disk);
66         if (cd)
67                 kref_get(&cd->kref);
68         mutex_unlock(&idecd_ref_mutex);
69         return cd;
70 }
71
72 static void ide_cd_release(struct kref *);
73
74 static void ide_cd_put(struct cdrom_info *cd)
75 {
76         mutex_lock(&idecd_ref_mutex);
77         kref_put(&cd->kref, ide_cd_release);
78         mutex_unlock(&idecd_ref_mutex);
79 }
80
81 /*
82  * Generic packet command support and error handling routines.
83  */
84
85 /* Mark that we've seen a media change and invalidate our internal buffers. */
86 static void cdrom_saw_media_change(ide_drive_t *drive)
87 {
88         struct cdrom_info *cd = drive->driver_data;
89
90         cd->cd_flags |= IDE_CD_FLAG_MEDIA_CHANGED;
91         cd->cd_flags &= ~IDE_CD_FLAG_TOC_VALID;
92 }
93
94 static int cdrom_log_sense(ide_drive_t *drive, struct request *rq,
95                            struct request_sense *sense)
96 {
97         int log = 0;
98
99         if (!sense || !rq || (rq->cmd_flags & REQ_QUIET))
100                 return 0;
101
102         switch (sense->sense_key) {
103         case NO_SENSE:
104         case RECOVERED_ERROR:
105                 break;
106         case NOT_READY:
107                 /*
108                  * don't care about tray state messages for e.g. capacity
109                  * commands or in-progress or becoming ready
110                  */
111                 if (sense->asc == 0x3a || sense->asc == 0x04)
112                         break;
113                 log = 1;
114                 break;
115         case ILLEGAL_REQUEST:
116                 /*
117                  * don't log START_STOP unit with LoEj set, since we cannot
118                  * reliably check if drive can auto-close
119                  */
120                 if (rq->cmd[0] == GPCMD_START_STOP_UNIT && sense->asc == 0x24)
121                         break;
122                 log = 1;
123                 break;
124         case UNIT_ATTENTION:
125                 /*
126                  * Make good and sure we've seen this potential media change.
127                  * Some drives (i.e. Creative) fail to present the correct sense
128                  * key in the error register.
129                  */
130                 cdrom_saw_media_change(drive);
131                 break;
132         default:
133                 log = 1;
134                 break;
135         }
136         return log;
137 }
138
139 static void cdrom_analyze_sense_data(ide_drive_t *drive,
140                               struct request *failed_command,
141                               struct request_sense *sense)
142 {
143         unsigned long sector;
144         unsigned long bio_sectors;
145         struct cdrom_info *info = drive->driver_data;
146
147         if (!cdrom_log_sense(drive, failed_command, sense))
148                 return;
149
150         /*
151          * If a read toc is executed for a CD-R or CD-RW medium where the first
152          * toc has not been recorded yet, it will fail with 05/24/00 (which is a
153          * confusing error)
154          */
155         if (failed_command && failed_command->cmd[0] == GPCMD_READ_TOC_PMA_ATIP)
156                 if (sense->sense_key == 0x05 && sense->asc == 0x24)
157                         return;
158
159         /* current error */
160         if (sense->error_code == 0x70) {
161                 switch (sense->sense_key) {
162                 case MEDIUM_ERROR:
163                 case VOLUME_OVERFLOW:
164                 case ILLEGAL_REQUEST:
165                         if (!sense->valid)
166                                 break;
167                         if (failed_command == NULL ||
168                                         !blk_fs_request(failed_command))
169                                 break;
170                         sector = (sense->information[0] << 24) |
171                                  (sense->information[1] << 16) |
172                                  (sense->information[2] <<  8) |
173                                  (sense->information[3]);
174
175                         if (drive->queue->hardsect_size == 2048)
176                                 /* device sector size is 2K */
177                                 sector <<= 2;
178
179                         bio_sectors = max(bio_sectors(failed_command->bio), 4U);
180                         sector &= ~(bio_sectors - 1);
181
182                         if (sector < get_capacity(info->disk) &&
183                             drive->probed_capacity - sector < 4 * 75)
184                                 set_capacity(info->disk, sector);
185                 }
186         }
187
188         ide_cd_log_error(drive->name, failed_command, sense);
189 }
190
191 static void cdrom_queue_request_sense(ide_drive_t *drive, void *sense,
192                                       struct request *failed_command)
193 {
194         struct cdrom_info *info         = drive->driver_data;
195         struct request *rq              = &info->request_sense_request;
196
197         if (sense == NULL)
198                 sense = &info->sense_data;
199
200         /* stuff the sense request in front of our current request */
201         blk_rq_init(NULL, rq);
202         rq->cmd_type = REQ_TYPE_ATA_PC;
203         rq->rq_disk = info->disk;
204
205         rq->data = sense;
206         rq->cmd[0] = GPCMD_REQUEST_SENSE;
207         rq->cmd[4] = 18;
208         rq->data_len = 18;
209
210         rq->cmd_type = REQ_TYPE_SENSE;
211         rq->cmd_flags |= REQ_PREEMPT;
212
213         /* NOTE! Save the failed command in "rq->buffer" */
214         rq->buffer = (void *) failed_command;
215
216         ide_do_drive_cmd(drive, rq);
217 }
218
219 static void cdrom_end_request(ide_drive_t *drive, int uptodate)
220 {
221         struct request *rq = HWGROUP(drive)->rq;
222         int nsectors = rq->hard_cur_sectors;
223
224         if (blk_sense_request(rq) && uptodate) {
225                 /*
226                  * For REQ_TYPE_SENSE, "rq->buffer" points to the original
227                  * failed request
228                  */
229                 struct request *failed = (struct request *) rq->buffer;
230                 struct cdrom_info *info = drive->driver_data;
231                 void *sense = &info->sense_data;
232                 unsigned long flags;
233
234                 if (failed) {
235                         if (failed->sense) {
236                                 sense = failed->sense;
237                                 failed->sense_len = rq->sense_len;
238                         }
239                         cdrom_analyze_sense_data(drive, failed, sense);
240                         /*
241                          * now end the failed request
242                          */
243                         if (blk_fs_request(failed)) {
244                                 if (ide_end_dequeued_request(drive, failed, 0,
245                                                 failed->hard_nr_sectors))
246                                         BUG();
247                         } else {
248                                 spin_lock_irqsave(&ide_lock, flags);
249                                 if (__blk_end_request(failed, -EIO,
250                                                       failed->data_len))
251                                         BUG();
252                                 spin_unlock_irqrestore(&ide_lock, flags);
253                         }
254                 } else
255                         cdrom_analyze_sense_data(drive, NULL, sense);
256         }
257
258         if (!rq->current_nr_sectors && blk_fs_request(rq))
259                 uptodate = 1;
260         /* make sure it's fully ended */
261         if (blk_pc_request(rq))
262                 nsectors = (rq->data_len + 511) >> 9;
263         if (!nsectors)
264                 nsectors = 1;
265
266         ide_end_request(drive, uptodate, nsectors);
267 }
268
269 static void ide_dump_status_no_sense(ide_drive_t *drive, const char *msg, u8 st)
270 {
271         if (st & 0x80)
272                 return;
273         ide_dump_status(drive, msg, st);
274 }
275
276 /*
277  * Returns:
278  * 0: if the request should be continued.
279  * 1: if the request was ended.
280  */
281 static int cdrom_decode_status(ide_drive_t *drive, int good_stat, int *stat_ret)
282 {
283         ide_hwif_t *hwif = drive->hwif;
284         struct request *rq = hwif->hwgroup->rq;
285         int stat, err, sense_key;
286
287         /* check for errors */
288         stat = hwif->read_status(hwif);
289
290         if (stat_ret)
291                 *stat_ret = stat;
292
293         if (OK_STAT(stat, good_stat, BAD_R_STAT))
294                 return 0;
295
296         /* get the IDE error register */
297         err = ide_read_error(drive);
298         sense_key = err >> 4;
299
300         if (rq == NULL) {
301                 printk(KERN_ERR "%s: missing rq in %s\n",
302                                 drive->name, __func__);
303                 return 1;
304         }
305
306         if (blk_sense_request(rq)) {
307                 /*
308                  * We got an error trying to get sense info from the drive
309                  * (probably while trying to recover from a former error).
310                  * Just give up.
311                  */
312                 rq->cmd_flags |= REQ_FAILED;
313                 cdrom_end_request(drive, 0);
314                 ide_error(drive, "request sense failure", stat);
315                 return 1;
316
317         } else if (blk_pc_request(rq) || rq->cmd_type == REQ_TYPE_ATA_PC) {
318                 /* All other functions, except for READ. */
319
320                 /*
321                  * if we have an error, pass back CHECK_CONDITION as the
322                  * scsi status byte
323                  */
324                 if (blk_pc_request(rq) && !rq->errors)
325                         rq->errors = SAM_STAT_CHECK_CONDITION;
326
327                 /* check for tray open */
328                 if (sense_key == NOT_READY) {
329                         cdrom_saw_media_change(drive);
330                 } else if (sense_key == UNIT_ATTENTION) {
331                         /* check for media change */
332                         cdrom_saw_media_change(drive);
333                         return 0;
334                 } else if (sense_key == ILLEGAL_REQUEST &&
335                            rq->cmd[0] == GPCMD_START_STOP_UNIT) {
336                         /*
337                          * Don't print error message for this condition--
338                          * SFF8090i indicates that 5/24/00 is the correct
339                          * response to a request to close the tray if the
340                          * drive doesn't have that capability.
341                          * cdrom_log_sense() knows this!
342                          */
343                 } else if (!(rq->cmd_flags & REQ_QUIET)) {
344                         /* otherwise, print an error */
345                         ide_dump_status(drive, "packet command error", stat);
346                 }
347
348                 rq->cmd_flags |= REQ_FAILED;
349
350                 /*
351                  * instead of playing games with moving completions around,
352                  * remove failed request completely and end it when the
353                  * request sense has completed
354                  */
355                 goto end_request;
356
357         } else if (blk_fs_request(rq)) {
358                 int do_end_request = 0;
359
360                 /* handle errors from READ and WRITE requests */
361
362                 if (blk_noretry_request(rq))
363                         do_end_request = 1;
364
365                 if (sense_key == NOT_READY) {
366                         /* tray open */
367                         if (rq_data_dir(rq) == READ) {
368                                 cdrom_saw_media_change(drive);
369
370                                 /* fail the request */
371                                 printk(KERN_ERR "%s: tray open\n", drive->name);
372                                 do_end_request = 1;
373                         } else {
374                                 struct cdrom_info *info = drive->driver_data;
375
376                                 /*
377                                  * Allow the drive 5 seconds to recover, some
378                                  * devices will return this error while flushing
379                                  * data from cache.
380                                  */
381                                 if (!rq->errors)
382                                         info->write_timeout = jiffies +
383                                                         ATAPI_WAIT_WRITE_BUSY;
384                                 rq->errors = 1;
385                                 if (time_after(jiffies, info->write_timeout))
386                                         do_end_request = 1;
387                                 else {
388                                         unsigned long flags;
389
390                                         /*
391                                          * take a breather relying on the unplug
392                                          * timer to kick us again
393                                          */
394                                         spin_lock_irqsave(&ide_lock, flags);
395                                         blk_plug_device(drive->queue);
396                                         spin_unlock_irqrestore(&ide_lock,
397                                                                 flags);
398                                         return 1;
399                                 }
400                         }
401                 } else if (sense_key == UNIT_ATTENTION) {
402                         /* media change */
403                         cdrom_saw_media_change(drive);
404
405                         /*
406                          * Arrange to retry the request but be sure to give up
407                          * if we've retried too many times.
408                          */
409                         if (++rq->errors > ERROR_MAX)
410                                 do_end_request = 1;
411                 } else if (sense_key == ILLEGAL_REQUEST ||
412                            sense_key == DATA_PROTECT) {
413                         /*
414                          * No point in retrying after an illegal request or data
415                          * protect error.
416                          */
417                         ide_dump_status_no_sense(drive, "command error", stat);
418                         do_end_request = 1;
419                 } else if (sense_key == MEDIUM_ERROR) {
420                         /*
421                          * No point in re-trying a zillion times on a bad
422                          * sector. If we got here the error is not correctable.
423                          */
424                         ide_dump_status_no_sense(drive,
425                                                  "media error (bad sector)",
426                                                  stat);
427                         do_end_request = 1;
428                 } else if (sense_key == BLANK_CHECK) {
429                         /* disk appears blank ?? */
430                         ide_dump_status_no_sense(drive, "media error (blank)",
431                                                  stat);
432                         do_end_request = 1;
433                 } else if ((err & ~ABRT_ERR) != 0) {
434                         /* go to the default handler for other errors */
435                         ide_error(drive, "cdrom_decode_status", stat);
436                         return 1;
437                 } else if ((++rq->errors > ERROR_MAX)) {
438                         /* we've racked up too many retries, abort */
439                         do_end_request = 1;
440                 }
441
442                 /*
443                  * End a request through request sense analysis when we have
444                  * sense data. We need this in order to perform end of media
445                  * processing.
446                  */
447                 if (do_end_request)
448                         goto end_request;
449
450                 /*
451                  * If we got a CHECK_CONDITION status, queue
452                  * a request sense command.
453                  */
454                 if (stat & ERR_STAT)
455                         cdrom_queue_request_sense(drive, NULL, NULL);
456         } else {
457                 blk_dump_rq_flags(rq, "ide-cd: bad rq");
458                 cdrom_end_request(drive, 0);
459         }
460
461         /* retry, or handle the next request */
462         return 1;
463
464 end_request:
465         if (stat & ERR_STAT) {
466                 unsigned long flags;
467
468                 spin_lock_irqsave(&ide_lock, flags);
469                 blkdev_dequeue_request(rq);
470                 HWGROUP(drive)->rq = NULL;
471                 spin_unlock_irqrestore(&ide_lock, flags);
472
473                 cdrom_queue_request_sense(drive, rq->sense, rq);
474         } else
475                 cdrom_end_request(drive, 0);
476
477         return 1;
478 }
479
480 static int cdrom_timer_expiry(ide_drive_t *drive)
481 {
482         struct request *rq = HWGROUP(drive)->rq;
483         unsigned long wait = 0;
484
485         /*
486          * Some commands are *slow* and normally take a long time to complete.
487          * Usually we can use the ATAPI "disconnect" to bypass this, but not all
488          * commands/drives support that. Let ide_timer_expiry keep polling us
489          * for these.
490          */
491         switch (rq->cmd[0]) {
492         case GPCMD_BLANK:
493         case GPCMD_FORMAT_UNIT:
494         case GPCMD_RESERVE_RZONE_TRACK:
495         case GPCMD_CLOSE_TRACK:
496         case GPCMD_FLUSH_CACHE:
497                 wait = ATAPI_WAIT_PC;
498                 break;
499         default:
500                 if (!(rq->cmd_flags & REQ_QUIET))
501                         printk(KERN_INFO "ide-cd: cmd 0x%x timed out\n",
502                                          rq->cmd[0]);
503                 wait = 0;
504                 break;
505         }
506         return wait;
507 }
508
509 /*
510  * Set up the device registers for transferring a packet command on DEV,
511  * expecting to later transfer XFERLEN bytes.  HANDLER is the routine
512  * which actually transfers the command to the drive.  If this is a
513  * drq_interrupt device, this routine will arrange for HANDLER to be
514  * called when the interrupt from the drive arrives.  Otherwise, HANDLER
515  * will be called immediately after the drive is prepared for the transfer.
516  */
517 static ide_startstop_t cdrom_start_packet_command(ide_drive_t *drive,
518                                                   int xferlen,
519                                                   ide_handler_t *handler)
520 {
521         struct cdrom_info *info = drive->driver_data;
522         ide_hwif_t *hwif = drive->hwif;
523
524         /* FIXME: for Virtual DMA we must check harder */
525         if (info->dma)
526                 info->dma = !hwif->dma_ops->dma_setup(drive);
527
528         /* set up the controller registers */
529         ide_pktcmd_tf_load(drive, IDE_TFLAG_OUT_NSECT | IDE_TFLAG_OUT_LBAL,
530                            xferlen, info->dma);
531
532         if (info->cd_flags & IDE_CD_FLAG_DRQ_INTERRUPT) {
533                 /* waiting for CDB interrupt, not DMA yet. */
534                 if (info->dma)
535                         drive->waiting_for_dma = 0;
536
537                 /* packet command */
538                 ide_execute_command(drive, WIN_PACKETCMD, handler,
539                                     ATAPI_WAIT_PC, cdrom_timer_expiry);
540                 return ide_started;
541         } else {
542                 ide_execute_pkt_cmd(drive);
543
544                 return (*handler) (drive);
545         }
546 }
547
548 /*
549  * Send a packet command to DRIVE described by CMD_BUF and CMD_LEN. The device
550  * registers must have already been prepared by cdrom_start_packet_command.
551  * HANDLER is the interrupt handler to call when the command completes or
552  * there's data ready.
553  */
554 #define ATAPI_MIN_CDB_BYTES 12
555 static ide_startstop_t cdrom_transfer_packet_command(ide_drive_t *drive,
556                                           struct request *rq,
557                                           ide_handler_t *handler)
558 {
559         ide_hwif_t *hwif = drive->hwif;
560         int cmd_len;
561         struct cdrom_info *info = drive->driver_data;
562         ide_startstop_t startstop;
563
564         if (info->cd_flags & IDE_CD_FLAG_DRQ_INTERRUPT) {
565                 /*
566                  * Here we should have been called after receiving an interrupt
567                  * from the device.  DRQ should how be set.
568                  */
569
570                 /* check for errors */
571                 if (cdrom_decode_status(drive, DRQ_STAT, NULL))
572                         return ide_stopped;
573
574                 /* ok, next interrupt will be DMA interrupt */
575                 if (info->dma)
576                         drive->waiting_for_dma = 1;
577         } else {
578                 /* otherwise, we must wait for DRQ to get set */
579                 if (ide_wait_stat(&startstop, drive, DRQ_STAT,
580                                 BUSY_STAT, WAIT_READY))
581                         return startstop;
582         }
583
584         /* arm the interrupt handler */
585         ide_set_handler(drive, handler, rq->timeout, cdrom_timer_expiry);
586
587         /* ATAPI commands get padded out to 12 bytes minimum */
588         cmd_len = COMMAND_SIZE(rq->cmd[0]);
589         if (cmd_len < ATAPI_MIN_CDB_BYTES)
590                 cmd_len = ATAPI_MIN_CDB_BYTES;
591
592         /* send the command to the device */
593         hwif->output_data(drive, NULL, rq->cmd, cmd_len);
594
595         /* start the DMA if need be */
596         if (info->dma)
597                 hwif->dma_ops->dma_start(drive);
598
599         return ide_started;
600 }
601
602 /*
603  * Check the contents of the interrupt reason register from the cdrom
604  * and attempt to recover if there are problems.  Returns  0 if everything's
605  * ok; nonzero if the request has been terminated.
606  */
607 static int ide_cd_check_ireason(ide_drive_t *drive, struct request *rq,
608                                 int len, int ireason, int rw)
609 {
610         ide_hwif_t *hwif = drive->hwif;
611
612         /*
613          * ireason == 0: the drive wants to receive data from us
614          * ireason == 2: the drive is expecting to transfer data to us
615          */
616         if (ireason == (!rw << 1))
617                 return 0;
618         else if (ireason == (rw << 1)) {
619
620                 /* whoops... */
621                 printk(KERN_ERR "%s: %s: wrong transfer direction!\n",
622                                 drive->name, __func__);
623
624                 ide_pad_transfer(drive, rw, len);
625         } else  if (rw == 0 && ireason == 1) {
626                 /*
627                  * Some drives (ASUS) seem to tell us that status info is
628                  * available.  Just get it and ignore.
629                  */
630                 (void)hwif->read_status(hwif);
631                 return 0;
632         } else {
633                 /* drive wants a command packet, or invalid ireason... */
634                 printk(KERN_ERR "%s: %s: bad interrupt reason 0x%02x\n",
635                                 drive->name, __func__, ireason);
636         }
637
638         if (rq->cmd_type == REQ_TYPE_ATA_PC)
639                 rq->cmd_flags |= REQ_FAILED;
640
641         cdrom_end_request(drive, 0);
642         return -1;
643 }
644
645 /*
646  * Assume that the drive will always provide data in multiples of at least
647  * SECTOR_SIZE, as it gets hairy to keep track of the transfers otherwise.
648  */
649 static int ide_cd_check_transfer_size(ide_drive_t *drive, int len)
650 {
651         struct cdrom_info *cd = drive->driver_data;
652
653         if ((len % SECTOR_SIZE) == 0)
654                 return 0;
655
656         printk(KERN_ERR "%s: %s: Bad transfer size %d\n",
657                         drive->name, __func__, len);
658
659         if (cd->cd_flags & IDE_CD_FLAG_LIMIT_NFRAMES)
660                 printk(KERN_ERR "  This drive is not supported by "
661                                 "this version of the driver\n");
662         else {
663                 printk(KERN_ERR "  Trying to limit transfer sizes\n");
664                 cd->cd_flags |= IDE_CD_FLAG_LIMIT_NFRAMES;
665         }
666
667         return 1;
668 }
669
670 static ide_startstop_t cdrom_newpc_intr(ide_drive_t *);
671
672 static ide_startstop_t ide_cd_prepare_rw_request(ide_drive_t *drive,
673                                                  struct request *rq)
674 {
675         if (rq_data_dir(rq) == READ) {
676                 unsigned short sectors_per_frame =
677                         queue_hardsect_size(drive->queue) >> SECTOR_BITS;
678                 int nskip = rq->sector & (sectors_per_frame - 1);
679
680                 /*
681                  * If the requested sector doesn't start on a frame boundary,
682                  * we must adjust the start of the transfer so that it does,
683                  * and remember to skip the first few sectors.
684                  *
685                  * If the rq->current_nr_sectors field is larger than the size
686                  * of the buffer, it will mean that we're to skip a number of
687                  * sectors equal to the amount by which rq->current_nr_sectors
688                  * is larger than the buffer size.
689                  */
690                 if (nskip > 0) {
691                         /* sanity check... */
692                         if (rq->current_nr_sectors !=
693                             bio_cur_sectors(rq->bio)) {
694                                 printk(KERN_ERR "%s: %s: buffer botch (%u)\n",
695                                                 drive->name, __func__,
696                                                 rq->current_nr_sectors);
697                                 cdrom_end_request(drive, 0);
698                                 return ide_stopped;
699                         }
700                         rq->current_nr_sectors += nskip;
701                 }
702         }
703 #if 0
704         else
705                 /* the immediate bit */
706                 rq->cmd[1] = 1 << 3;
707 #endif
708         /* set up the command */
709         rq->timeout = ATAPI_WAIT_PC;
710
711         return ide_started;
712 }
713
714 /*
715  * Routine to send a read/write packet command to the drive. This is usually
716  * called directly from cdrom_start_{read,write}(). However, for drq_interrupt
717  * devices, it is called from an interrupt when the drive is ready to accept
718  * the command.
719  */
720 static ide_startstop_t cdrom_start_rw_cont(ide_drive_t *drive)
721 {
722         struct request *rq = drive->hwif->hwgroup->rq;
723
724         /* send the command to the drive and return */
725         return cdrom_transfer_packet_command(drive, rq, cdrom_newpc_intr);
726 }
727
728 #define IDECD_SEEK_THRESHOLD    (1000)                  /* 1000 blocks */
729 #define IDECD_SEEK_TIMER        (5 * WAIT_MIN_SLEEP)    /* 100 ms */
730 #define IDECD_SEEK_TIMEOUT      (2 * WAIT_CMD)          /* 20 sec */
731
732 static ide_startstop_t cdrom_seek_intr(ide_drive_t *drive)
733 {
734         struct cdrom_info *info = drive->driver_data;
735         int stat;
736         static int retry = 10;
737
738         if (cdrom_decode_status(drive, 0, &stat))
739                 return ide_stopped;
740
741         info->cd_flags |= IDE_CD_FLAG_SEEKING;
742
743         if (retry && time_after(jiffies, info->start_seek + IDECD_SEEK_TIMER)) {
744                 if (--retry == 0)
745                         drive->dsc_overlap = 0;
746         }
747         return ide_stopped;
748 }
749
750 static void ide_cd_prepare_seek_request(ide_drive_t *drive, struct request *rq)
751 {
752         sector_t frame = rq->sector;
753
754         sector_div(frame, queue_hardsect_size(drive->queue) >> SECTOR_BITS);
755
756         memset(rq->cmd, 0, BLK_MAX_CDB);
757         rq->cmd[0] = GPCMD_SEEK;
758         put_unaligned(cpu_to_be32(frame), (unsigned int *) &rq->cmd[2]);
759
760         rq->timeout = ATAPI_WAIT_PC;
761 }
762
763 static ide_startstop_t cdrom_start_seek_continuation(ide_drive_t *drive)
764 {
765         struct request *rq = drive->hwif->hwgroup->rq;
766
767         return cdrom_transfer_packet_command(drive, rq, &cdrom_seek_intr);
768 }
769
770 /*
771  * Fix up a possibly partially-processed request so that we can start it over
772  * entirely, or even put it back on the request queue.
773  */
774 static void restore_request(struct request *rq)
775 {
776         if (rq->buffer != bio_data(rq->bio)) {
777                 sector_t n =
778                         (rq->buffer - (char *)bio_data(rq->bio)) / SECTOR_SIZE;
779
780                 rq->buffer = bio_data(rq->bio);
781                 rq->nr_sectors += n;
782                 rq->sector -= n;
783         }
784         rq->current_nr_sectors = bio_cur_sectors(rq->bio);
785         rq->hard_cur_sectors = rq->current_nr_sectors;
786         rq->hard_nr_sectors = rq->nr_sectors;
787         rq->hard_sector = rq->sector;
788         rq->q->prep_rq_fn(rq->q, rq);
789 }
790
791 /*
792  * All other packet commands.
793  */
794 static void ide_cd_request_sense_fixup(struct request *rq)
795 {
796         /*
797          * Some of the trailing request sense fields are optional,
798          * and some drives don't send them.  Sigh.
799          */
800         if (rq->cmd[0] == GPCMD_REQUEST_SENSE &&
801             rq->data_len > 0 && rq->data_len <= 5)
802                 while (rq->data_len > 0) {
803                         *(u8 *)rq->data++ = 0;
804                         --rq->data_len;
805                 }
806 }
807
808 int ide_cd_queue_pc(ide_drive_t *drive, const unsigned char *cmd,
809                     int write, void *buffer, unsigned *bufflen,
810                     struct request_sense *sense, int timeout,
811                     unsigned int cmd_flags)
812 {
813         struct cdrom_info *info = drive->driver_data;
814         struct request_sense local_sense;
815         int retries = 10;
816         unsigned int flags = 0;
817
818         if (!sense)
819                 sense = &local_sense;
820
821         /* start of retry loop */
822         do {
823                 struct request *rq;
824                 int error;
825
826                 rq = blk_get_request(drive->queue, write, __GFP_WAIT);
827
828                 memcpy(rq->cmd, cmd, BLK_MAX_CDB);
829                 rq->cmd_type = REQ_TYPE_ATA_PC;
830                 rq->sense = sense;
831                 rq->cmd_flags |= cmd_flags;
832                 rq->timeout = timeout;
833                 if (buffer) {
834                         rq->data = buffer;
835                         rq->data_len = *bufflen;
836                 }
837
838                 error = blk_execute_rq(drive->queue, info->disk, rq, 0);
839
840                 if (buffer)
841                         *bufflen = rq->data_len;
842
843                 flags = rq->cmd_flags;
844                 blk_put_request(rq);
845
846                 /*
847                  * FIXME: we should probably abort/retry or something in case of
848                  * failure.
849                  */
850                 if (flags & REQ_FAILED) {
851                         /*
852                          * The request failed.  Retry if it was due to a unit
853                          * attention status (usually means media was changed).
854                          */
855                         struct request_sense *reqbuf = sense;
856
857                         if (reqbuf->sense_key == UNIT_ATTENTION)
858                                 cdrom_saw_media_change(drive);
859                         else if (reqbuf->sense_key == NOT_READY &&
860                                  reqbuf->asc == 4 && reqbuf->ascq != 4) {
861                                 /*
862                                  * The drive is in the process of loading
863                                  * a disk.  Retry, but wait a little to give
864                                  * the drive time to complete the load.
865                                  */
866                                 ssleep(2);
867                         } else {
868                                 /* otherwise, don't retry */
869                                 retries = 0;
870                         }
871                         --retries;
872                 }
873
874                 /* end of retry loop */
875         } while ((flags & REQ_FAILED) && retries >= 0);
876
877         /* return an error if the command failed */
878         return (flags & REQ_FAILED) ? -EIO : 0;
879 }
880
881 /*
882  * Called from blk_end_request_callback() after the data of the request is
883  * completed and before the request itself is completed. By returning value '1',
884  * blk_end_request_callback() returns immediately without completing it.
885  */
886 static int cdrom_newpc_intr_dummy_cb(struct request *rq)
887 {
888         return 1;
889 }
890
891 static ide_startstop_t cdrom_newpc_intr(ide_drive_t *drive)
892 {
893         ide_hwif_t *hwif = drive->hwif;
894         struct cdrom_info *info = drive->driver_data;
895         struct request *rq = HWGROUP(drive)->rq;
896         xfer_func_t *xferfunc;
897         ide_expiry_t *expiry = NULL;
898         int dma_error = 0, dma, stat, ireason, len, thislen, uptodate = 0;
899         int write = (rq_data_dir(rq) == WRITE) ? 1 : 0;
900         unsigned int timeout;
901         u8 lowcyl, highcyl;
902
903         /* check for errors */
904         dma = info->dma;
905         if (dma) {
906                 info->dma = 0;
907                 dma_error = hwif->dma_ops->dma_end(drive);
908                 if (dma_error) {
909                         printk(KERN_ERR "%s: DMA %s error\n", drive->name,
910                                         write ? "write" : "read");
911                         ide_dma_off(drive);
912                 }
913         }
914
915         if (cdrom_decode_status(drive, 0, &stat))
916                 return ide_stopped;
917
918         /* using dma, transfer is complete now */
919         if (dma) {
920                 if (dma_error)
921                         return ide_error(drive, "dma error", stat);
922                 if (blk_fs_request(rq)) {
923                         ide_end_request(drive, 1, rq->nr_sectors);
924                         return ide_stopped;
925                 }
926                 goto end_request;
927         }
928
929         /* ok we fall to pio :/ */
930         ireason = hwif->INB(hwif->io_ports.nsect_addr) & 0x3;
931         lowcyl  = hwif->INB(hwif->io_ports.lbam_addr);
932         highcyl = hwif->INB(hwif->io_ports.lbah_addr);
933
934         len = lowcyl + (256 * highcyl);
935
936         thislen = blk_fs_request(rq) ? len : rq->data_len;
937         if (thislen > len)
938                 thislen = len;
939
940         /* If DRQ is clear, the command has completed. */
941         if ((stat & DRQ_STAT) == 0) {
942                 if (blk_fs_request(rq)) {
943                         /*
944                          * If we're not done reading/writing, complain.
945                          * Otherwise, complete the command normally.
946                          */
947                         uptodate = 1;
948                         if (rq->current_nr_sectors > 0) {
949                                 printk(KERN_ERR "%s: %s: data underrun "
950                                                 "(%d blocks)\n",
951                                                 drive->name, __func__,
952                                                 rq->current_nr_sectors);
953                                 if (!write)
954                                         rq->cmd_flags |= REQ_FAILED;
955                                 uptodate = 0;
956                         }
957                         cdrom_end_request(drive, uptodate);
958                         return ide_stopped;
959                 } else if (!blk_pc_request(rq)) {
960                         ide_cd_request_sense_fixup(rq);
961                         /* complain if we still have data left to transfer */
962                         uptodate = rq->data_len ? 0 : 1;
963                 }
964                 goto end_request;
965         }
966
967         /* check which way to transfer data */
968         if (ide_cd_check_ireason(drive, rq, len, ireason, write))
969                 return ide_stopped;
970
971         if (blk_fs_request(rq)) {
972                 if (write == 0) {
973                         int nskip;
974
975                         if (ide_cd_check_transfer_size(drive, len)) {
976                                 cdrom_end_request(drive, 0);
977                                 return ide_stopped;
978                         }
979
980                         /*
981                          * First, figure out if we need to bit-bucket
982                          * any of the leading sectors.
983                          */
984                         nskip = min_t(int, rq->current_nr_sectors
985                                            - bio_cur_sectors(rq->bio),
986                                            thislen >> 9);
987                         if (nskip > 0) {
988                                 ide_pad_transfer(drive, write, nskip << 9);
989                                 rq->current_nr_sectors -= nskip;
990                                 thislen -= (nskip << 9);
991                         }
992                 }
993         }
994
995         if (ireason == 0) {
996                 write = 1;
997                 xferfunc = hwif->output_data;
998         } else {
999                 write = 0;
1000                 xferfunc = hwif->input_data;
1001         }
1002
1003         /* transfer data */
1004         while (thislen > 0) {
1005                 u8 *ptr = blk_fs_request(rq) ? NULL : rq->data;
1006                 int blen = rq->data_len;
1007
1008                 /* bio backed? */
1009                 if (rq->bio) {
1010                         if (blk_fs_request(rq)) {
1011                                 ptr = rq->buffer;
1012                                 blen = rq->current_nr_sectors << 9;
1013                         } else {
1014                                 ptr = bio_data(rq->bio);
1015                                 blen = bio_iovec(rq->bio)->bv_len;
1016                         }
1017                 }
1018
1019                 if (!ptr) {
1020                         if (blk_fs_request(rq) && !write)
1021                                 /*
1022                                  * If the buffers are full, pipe the rest into
1023                                  * oblivion.
1024                                  */
1025                                 ide_pad_transfer(drive, 0, thislen);
1026                         else {
1027                                 printk(KERN_ERR "%s: confused, missing data\n",
1028                                                 drive->name);
1029                                 blk_dump_rq_flags(rq, rq_data_dir(rq)
1030                                                   ? "cdrom_newpc_intr, write"
1031                                                   : "cdrom_newpc_intr, read");
1032                         }
1033                         break;
1034                 }
1035
1036                 if (blen > thislen)
1037                         blen = thislen;
1038
1039                 xferfunc(drive, NULL, ptr, blen);
1040
1041                 thislen -= blen;
1042                 len -= blen;
1043
1044                 if (blk_fs_request(rq)) {
1045                         rq->buffer += blen;
1046                         rq->nr_sectors -= (blen >> 9);
1047                         rq->current_nr_sectors -= (blen >> 9);
1048                         rq->sector += (blen >> 9);
1049
1050                         if (rq->current_nr_sectors == 0 && rq->nr_sectors)
1051                                 cdrom_end_request(drive, 1);
1052                 } else {
1053                         rq->data_len -= blen;
1054
1055                         /*
1056                          * The request can't be completed until DRQ is cleared.
1057                          * So complete the data, but don't complete the request
1058                          * using the dummy function for the callback feature
1059                          * of blk_end_request_callback().
1060                          */
1061                         if (rq->bio)
1062                                 blk_end_request_callback(rq, 0, blen,
1063                                                  cdrom_newpc_intr_dummy_cb);
1064                         else
1065                                 rq->data += blen;
1066                 }
1067                 if (!write && blk_sense_request(rq))
1068                         rq->sense_len += blen;
1069         }
1070
1071         /* pad, if necessary */
1072         if (!blk_fs_request(rq) && len > 0)
1073                 ide_pad_transfer(drive, write, len);
1074
1075         if (blk_pc_request(rq)) {
1076                 timeout = rq->timeout;
1077         } else {
1078                 timeout = ATAPI_WAIT_PC;
1079                 if (!blk_fs_request(rq))
1080                         expiry = cdrom_timer_expiry;
1081         }
1082
1083         ide_set_handler(drive, cdrom_newpc_intr, timeout, expiry);
1084         return ide_started;
1085
1086 end_request:
1087         if (blk_pc_request(rq)) {
1088                 unsigned long flags;
1089                 unsigned int dlen = rq->data_len;
1090
1091                 if (dma)
1092                         rq->data_len = 0;
1093
1094                 spin_lock_irqsave(&ide_lock, flags);
1095                 if (__blk_end_request(rq, 0, dlen))
1096                         BUG();
1097                 HWGROUP(drive)->rq = NULL;
1098                 spin_unlock_irqrestore(&ide_lock, flags);
1099         } else {
1100                 if (!uptodate)
1101                         rq->cmd_flags |= REQ_FAILED;
1102                 cdrom_end_request(drive, uptodate);
1103         }
1104         return ide_stopped;
1105 }
1106
1107 static ide_startstop_t cdrom_start_rw(ide_drive_t *drive, struct request *rq)
1108 {
1109         struct cdrom_info *cd = drive->driver_data;
1110         int write = rq_data_dir(rq) == WRITE;
1111         unsigned short sectors_per_frame =
1112                 queue_hardsect_size(drive->queue) >> SECTOR_BITS;
1113
1114         if (write) {
1115                 /* disk has become write protected */
1116                 if (cd->disk->policy) {
1117                         cdrom_end_request(drive, 0);
1118                         return ide_stopped;
1119                 }
1120         } else {
1121                 /*
1122                  * We may be retrying this request after an error.  Fix up any
1123                  * weirdness which might be present in the request packet.
1124                  */
1125                 restore_request(rq);
1126         }
1127
1128         /* use DMA, if possible / writes *must* be hardware frame aligned */
1129         if ((rq->nr_sectors & (sectors_per_frame - 1)) ||
1130             (rq->sector & (sectors_per_frame - 1))) {
1131                 if (write) {
1132                         cdrom_end_request(drive, 0);
1133                         return ide_stopped;
1134                 }
1135                 cd->dma = 0;
1136         } else
1137                 cd->dma = drive->using_dma;
1138
1139         if (write)
1140                 cd->devinfo.media_written = 1;
1141
1142         return ide_started;
1143 }
1144
1145 static ide_startstop_t cdrom_do_newpc_cont(ide_drive_t *drive)
1146 {
1147         struct request *rq = HWGROUP(drive)->rq;
1148
1149         return cdrom_transfer_packet_command(drive, rq, cdrom_newpc_intr);
1150 }
1151
1152 static void cdrom_do_block_pc(ide_drive_t *drive, struct request *rq)
1153 {
1154         struct cdrom_info *info = drive->driver_data;
1155
1156         if (blk_pc_request(rq))
1157                 rq->cmd_flags |= REQ_QUIET;
1158         else
1159                 rq->cmd_flags &= ~REQ_FAILED;
1160
1161         info->dma = 0;
1162
1163         /* sg request */
1164         if (rq->bio || ((rq->cmd_type == REQ_TYPE_ATA_PC) && rq->data_len)) {
1165                 struct request_queue *q = drive->queue;
1166                 unsigned int alignment;
1167                 unsigned long addr;
1168                 unsigned long stack_mask = ~(THREAD_SIZE - 1);
1169
1170                 if (rq->bio)
1171                         addr = (unsigned long)bio_data(rq->bio);
1172                 else
1173                         addr = (unsigned long)rq->data;
1174
1175                 info->dma = drive->using_dma;
1176
1177                 /*
1178                  * check if dma is safe
1179                  *
1180                  * NOTE! The "len" and "addr" checks should possibly have
1181                  * separate masks.
1182                  */
1183                 alignment = queue_dma_alignment(q) | q->dma_pad_mask;
1184                 if (addr & alignment || rq->data_len & alignment)
1185                         info->dma = 0;
1186
1187                 if (!((addr & stack_mask) ^
1188                       ((unsigned long)current->stack & stack_mask)))
1189                         info->dma = 0;
1190         }
1191 }
1192
1193 /*
1194  * cdrom driver request routine.
1195  */
1196 static ide_startstop_t ide_cd_do_request(ide_drive_t *drive, struct request *rq,
1197                                         sector_t block)
1198 {
1199         struct cdrom_info *info = drive->driver_data;
1200         ide_handler_t *fn;
1201         int xferlen;
1202
1203         if (blk_fs_request(rq)) {
1204                 if (info->cd_flags & IDE_CD_FLAG_SEEKING) {
1205                         ide_hwif_t *hwif = drive->hwif;
1206                         unsigned long elapsed = jiffies - info->start_seek;
1207                         int stat = hwif->read_status(hwif);
1208
1209                         if ((stat & SEEK_STAT) != SEEK_STAT) {
1210                                 if (elapsed < IDECD_SEEK_TIMEOUT) {
1211                                         ide_stall_queue(drive,
1212                                                         IDECD_SEEK_TIMER);
1213                                         return ide_stopped;
1214                                 }
1215                                 printk(KERN_ERR "%s: DSC timeout\n",
1216                                                 drive->name);
1217                         }
1218                         info->cd_flags &= ~IDE_CD_FLAG_SEEKING;
1219                 }
1220                 if (rq_data_dir(rq) == READ &&
1221                     IDE_LARGE_SEEK(info->last_block, block,
1222                             IDECD_SEEK_THRESHOLD) &&
1223                     drive->dsc_overlap) {
1224                         xferlen = 0;
1225                         fn = cdrom_start_seek_continuation;
1226
1227                         info->dma = 0;
1228                         info->start_seek = jiffies;
1229
1230                         ide_cd_prepare_seek_request(drive, rq);
1231                 } else {
1232                         xferlen = 32768;
1233                         fn = cdrom_start_rw_cont;
1234
1235                         if (cdrom_start_rw(drive, rq) == ide_stopped)
1236                                 return ide_stopped;
1237
1238                         if (ide_cd_prepare_rw_request(drive, rq) == ide_stopped)
1239                                 return ide_stopped;
1240                 }
1241                 info->last_block = block;
1242         } else if (blk_sense_request(rq) || blk_pc_request(rq) ||
1243                    rq->cmd_type == REQ_TYPE_ATA_PC) {
1244                 xferlen = rq->data_len;
1245                 fn = cdrom_do_newpc_cont;
1246
1247                 if (!rq->timeout)
1248                         rq->timeout = ATAPI_WAIT_PC;
1249
1250                 cdrom_do_block_pc(drive, rq);
1251         } else if (blk_special_request(rq)) {
1252                 /* right now this can only be a reset... */
1253                 cdrom_end_request(drive, 1);
1254                 return ide_stopped;
1255         } else {
1256                 blk_dump_rq_flags(rq, "ide-cd bad flags");
1257                 cdrom_end_request(drive, 0);
1258                 return ide_stopped;
1259         }
1260
1261         return cdrom_start_packet_command(drive, xferlen, fn);
1262 }
1263
1264 /*
1265  * Ioctl handling.
1266  *
1267  * Routines which queue packet commands take as a final argument a pointer to a
1268  * request_sense struct. If execution of the command results in an error with a
1269  * CHECK CONDITION status, this structure will be filled with the results of the
1270  * subsequent request sense command. The pointer can also be NULL, in which case
1271  * no sense information is returned.
1272  */
1273 static void msf_from_bcd(struct atapi_msf *msf)
1274 {
1275         msf->minute = BCD2BIN(msf->minute);
1276         msf->second = BCD2BIN(msf->second);
1277         msf->frame  = BCD2BIN(msf->frame);
1278 }
1279
1280 int cdrom_check_status(ide_drive_t *drive, struct request_sense *sense)
1281 {
1282         struct cdrom_info *info = drive->driver_data;
1283         struct cdrom_device_info *cdi = &info->devinfo;
1284         unsigned char cmd[BLK_MAX_CDB];
1285
1286         memset(cmd, 0, BLK_MAX_CDB);
1287         cmd[0] = GPCMD_TEST_UNIT_READY;
1288
1289         /*
1290          * Sanyo 3 CD changer uses byte 7 of TEST_UNIT_READY to switch CDs
1291          * instead of supporting the LOAD_UNLOAD opcode.
1292          */
1293         cmd[7] = cdi->sanyo_slot % 3;
1294
1295         return ide_cd_queue_pc(drive, cmd, 0, NULL, 0, sense, 0, REQ_QUIET);
1296 }
1297
1298 static int cdrom_read_capacity(ide_drive_t *drive, unsigned long *capacity,
1299                                unsigned long *sectors_per_frame,
1300                                struct request_sense *sense)
1301 {
1302         struct {
1303                 __u32 lba;
1304                 __u32 blocklen;
1305         } capbuf;
1306
1307         int stat;
1308         unsigned char cmd[BLK_MAX_CDB];
1309         unsigned len = sizeof(capbuf);
1310
1311         memset(cmd, 0, BLK_MAX_CDB);
1312         cmd[0] = GPCMD_READ_CDVD_CAPACITY;
1313
1314         stat = ide_cd_queue_pc(drive, cmd, 0, &capbuf, &len, sense, 0,
1315                                REQ_QUIET);
1316         if (stat == 0) {
1317                 *capacity = 1 + be32_to_cpu(capbuf.lba);
1318                 *sectors_per_frame =
1319                         be32_to_cpu(capbuf.blocklen) >> SECTOR_BITS;
1320         }
1321
1322         return stat;
1323 }
1324
1325 static int cdrom_read_tocentry(ide_drive_t *drive, int trackno, int msf_flag,
1326                                 int format, char *buf, int buflen,
1327                                 struct request_sense *sense)
1328 {
1329         unsigned char cmd[BLK_MAX_CDB];
1330
1331         memset(cmd, 0, BLK_MAX_CDB);
1332
1333         cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
1334         cmd[6] = trackno;
1335         cmd[7] = (buflen >> 8);
1336         cmd[8] = (buflen & 0xff);
1337         cmd[9] = (format << 6);
1338
1339         if (msf_flag)
1340                 cmd[1] = 2;
1341
1342         return ide_cd_queue_pc(drive, cmd, 0, buf, &buflen, sense, 0, REQ_QUIET);
1343 }
1344
1345 /* Try to read the entire TOC for the disk into our internal buffer. */
1346 int ide_cd_read_toc(ide_drive_t *drive, struct request_sense *sense)
1347 {
1348         int stat, ntracks, i;
1349         struct cdrom_info *info = drive->driver_data;
1350         struct cdrom_device_info *cdi = &info->devinfo;
1351         struct atapi_toc *toc = info->toc;
1352         struct {
1353                 struct atapi_toc_header hdr;
1354                 struct atapi_toc_entry  ent;
1355         } ms_tmp;
1356         long last_written;
1357         unsigned long sectors_per_frame = SECTORS_PER_FRAME;
1358
1359         if (toc == NULL) {
1360                 /* try to allocate space */
1361                 toc = kmalloc(sizeof(struct atapi_toc), GFP_KERNEL);
1362                 if (toc == NULL) {
1363                         printk(KERN_ERR "%s: No cdrom TOC buffer!\n",
1364                                         drive->name);
1365                         return -ENOMEM;
1366                 }
1367                 info->toc = toc;
1368         }
1369
1370         /*
1371          * Check to see if the existing data is still valid. If it is,
1372          * just return.
1373          */
1374         (void) cdrom_check_status(drive, sense);
1375
1376         if (info->cd_flags & IDE_CD_FLAG_TOC_VALID)
1377                 return 0;
1378
1379         /* try to get the total cdrom capacity and sector size */
1380         stat = cdrom_read_capacity(drive, &toc->capacity, &sectors_per_frame,
1381                                    sense);
1382         if (stat)
1383                 toc->capacity = 0x1fffff;
1384
1385         set_capacity(info->disk, toc->capacity * sectors_per_frame);
1386         /* save a private copy of the TOC capacity for error handling */
1387         drive->probed_capacity = toc->capacity * sectors_per_frame;
1388
1389         blk_queue_hardsect_size(drive->queue,
1390                                 sectors_per_frame << SECTOR_BITS);
1391
1392         /* first read just the header, so we know how long the TOC is */
1393         stat = cdrom_read_tocentry(drive, 0, 1, 0, (char *) &toc->hdr,
1394                                     sizeof(struct atapi_toc_header), sense);
1395         if (stat)
1396                 return stat;
1397
1398         if (info->cd_flags & IDE_CD_FLAG_TOCTRACKS_AS_BCD) {
1399                 toc->hdr.first_track = BCD2BIN(toc->hdr.first_track);
1400                 toc->hdr.last_track  = BCD2BIN(toc->hdr.last_track);
1401         }
1402
1403         ntracks = toc->hdr.last_track - toc->hdr.first_track + 1;
1404         if (ntracks <= 0)
1405                 return -EIO;
1406         if (ntracks > MAX_TRACKS)
1407                 ntracks = MAX_TRACKS;
1408
1409         /* now read the whole schmeer */
1410         stat = cdrom_read_tocentry(drive, toc->hdr.first_track, 1, 0,
1411                                   (char *)&toc->hdr,
1412                                    sizeof(struct atapi_toc_header) +
1413                                    (ntracks + 1) *
1414                                    sizeof(struct atapi_toc_entry), sense);
1415
1416         if (stat && toc->hdr.first_track > 1) {
1417                 /*
1418                  * Cds with CDI tracks only don't have any TOC entries, despite
1419                  * of this the returned values are
1420                  * first_track == last_track = number of CDI tracks + 1,
1421                  * so that this case is indistinguishable from the same layout
1422                  * plus an additional audio track. If we get an error for the
1423                  * regular case, we assume a CDI without additional audio
1424                  * tracks. In this case the readable TOC is empty (CDI tracks
1425                  * are not included) and only holds the Leadout entry.
1426                  *
1427                  * Heiko Eißfeldt.
1428                  */
1429                 ntracks = 0;
1430                 stat = cdrom_read_tocentry(drive, CDROM_LEADOUT, 1, 0,
1431                                            (char *)&toc->hdr,
1432                                            sizeof(struct atapi_toc_header) +
1433                                            (ntracks + 1) *
1434                                            sizeof(struct atapi_toc_entry),
1435                                            sense);
1436                 if (stat)
1437                         return stat;
1438
1439                 if (info->cd_flags & IDE_CD_FLAG_TOCTRACKS_AS_BCD) {
1440                         toc->hdr.first_track = (u8)BIN2BCD(CDROM_LEADOUT);
1441                         toc->hdr.last_track = (u8)BIN2BCD(CDROM_LEADOUT);
1442                 } else {
1443                         toc->hdr.first_track = CDROM_LEADOUT;
1444                         toc->hdr.last_track = CDROM_LEADOUT;
1445                 }
1446         }
1447
1448         if (stat)
1449                 return stat;
1450
1451         toc->hdr.toc_length = be16_to_cpu(toc->hdr.toc_length);
1452
1453         if (info->cd_flags & IDE_CD_FLAG_TOCTRACKS_AS_BCD) {
1454                 toc->hdr.first_track = BCD2BIN(toc->hdr.first_track);
1455                 toc->hdr.last_track  = BCD2BIN(toc->hdr.last_track);
1456         }
1457
1458         for (i = 0; i <= ntracks; i++) {
1459                 if (info->cd_flags & IDE_CD_FLAG_TOCADDR_AS_BCD) {
1460                         if (info->cd_flags & IDE_CD_FLAG_TOCTRACKS_AS_BCD)
1461                                 toc->ent[i].track = BCD2BIN(toc->ent[i].track);
1462                         msf_from_bcd(&toc->ent[i].addr.msf);
1463                 }
1464                 toc->ent[i].addr.lba = msf_to_lba(toc->ent[i].addr.msf.minute,
1465                                                   toc->ent[i].addr.msf.second,
1466                                                   toc->ent[i].addr.msf.frame);
1467         }
1468
1469         if (toc->hdr.first_track != CDROM_LEADOUT) {
1470                 /* read the multisession information */
1471                 stat = cdrom_read_tocentry(drive, 0, 0, 1, (char *)&ms_tmp,
1472                                            sizeof(ms_tmp), sense);
1473                 if (stat)
1474                         return stat;
1475
1476                 toc->last_session_lba = be32_to_cpu(ms_tmp.ent.addr.lba);
1477         } else {
1478                 ms_tmp.hdr.last_track = CDROM_LEADOUT;
1479                 ms_tmp.hdr.first_track = ms_tmp.hdr.last_track;
1480                 toc->last_session_lba = msf_to_lba(0, 2, 0); /* 0m 2s 0f */
1481         }
1482
1483         if (info->cd_flags & IDE_CD_FLAG_TOCADDR_AS_BCD) {
1484                 /* re-read multisession information using MSF format */
1485                 stat = cdrom_read_tocentry(drive, 0, 1, 1, (char *)&ms_tmp,
1486                                            sizeof(ms_tmp), sense);
1487                 if (stat)
1488                         return stat;
1489
1490                 msf_from_bcd(&ms_tmp.ent.addr.msf);
1491                 toc->last_session_lba = msf_to_lba(ms_tmp.ent.addr.msf.minute,
1492                                                    ms_tmp.ent.addr.msf.second,
1493                                                    ms_tmp.ent.addr.msf.frame);
1494         }
1495
1496         toc->xa_flag = (ms_tmp.hdr.first_track != ms_tmp.hdr.last_track);
1497
1498         /* now try to get the total cdrom capacity */
1499         stat = cdrom_get_last_written(cdi, &last_written);
1500         if (!stat && (last_written > toc->capacity)) {
1501                 toc->capacity = last_written;
1502                 set_capacity(info->disk, toc->capacity * sectors_per_frame);
1503                 drive->probed_capacity = toc->capacity * sectors_per_frame;
1504         }
1505
1506         /* Remember that we've read this stuff. */
1507         info->cd_flags |= IDE_CD_FLAG_TOC_VALID;
1508
1509         return 0;
1510 }
1511
1512 int ide_cdrom_get_capabilities(ide_drive_t *drive, u8 *buf)
1513 {
1514         struct cdrom_info *info = drive->driver_data;
1515         struct cdrom_device_info *cdi = &info->devinfo;
1516         struct packet_command cgc;
1517         int stat, attempts = 3, size = ATAPI_CAPABILITIES_PAGE_SIZE;
1518
1519         if ((info->cd_flags & IDE_CD_FLAG_FULL_CAPS_PAGE) == 0)
1520                 size -= ATAPI_CAPABILITIES_PAGE_PAD_SIZE;
1521
1522         init_cdrom_command(&cgc, buf, size, CGC_DATA_UNKNOWN);
1523         do {
1524                 /* we seem to get stat=0x01,err=0x00 the first time (??) */
1525                 stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
1526                 if (!stat)
1527                         break;
1528         } while (--attempts);
1529         return stat;
1530 }
1531
1532 void ide_cdrom_update_speed(ide_drive_t *drive, u8 *buf)
1533 {
1534         struct cdrom_info *cd = drive->driver_data;
1535         u16 curspeed, maxspeed;
1536
1537         curspeed = *(u16 *)&buf[8 + 14];
1538         maxspeed = *(u16 *)&buf[8 +  8];
1539
1540         if (cd->cd_flags & IDE_CD_FLAG_LE_SPEED_FIELDS) {
1541                 curspeed = le16_to_cpu(curspeed);
1542                 maxspeed = le16_to_cpu(maxspeed);
1543         } else {
1544                 curspeed = be16_to_cpu(curspeed);
1545                 maxspeed = be16_to_cpu(maxspeed);
1546         }
1547
1548         cd->current_speed = (curspeed + (176/2)) / 176;
1549         cd->max_speed = (maxspeed + (176/2)) / 176;
1550 }
1551
1552 #define IDE_CD_CAPABILITIES \
1553         (CDC_CLOSE_TRAY | CDC_OPEN_TRAY | CDC_LOCK | CDC_SELECT_SPEED | \
1554          CDC_SELECT_DISC | CDC_MULTI_SESSION | CDC_MCN | CDC_MEDIA_CHANGED | \
1555          CDC_PLAY_AUDIO | CDC_RESET | CDC_DRIVE_STATUS | CDC_CD_R | \
1556          CDC_CD_RW | CDC_DVD | CDC_DVD_R | CDC_DVD_RAM | CDC_GENERIC_PACKET | \
1557          CDC_MO_DRIVE | CDC_MRW | CDC_MRW_W | CDC_RAM)
1558
1559 static struct cdrom_device_ops ide_cdrom_dops = {
1560         .open                   = ide_cdrom_open_real,
1561         .release                = ide_cdrom_release_real,
1562         .drive_status           = ide_cdrom_drive_status,
1563         .media_changed          = ide_cdrom_check_media_change_real,
1564         .tray_move              = ide_cdrom_tray_move,
1565         .lock_door              = ide_cdrom_lock_door,
1566         .select_speed           = ide_cdrom_select_speed,
1567         .get_last_session       = ide_cdrom_get_last_session,
1568         .get_mcn                = ide_cdrom_get_mcn,
1569         .reset                  = ide_cdrom_reset,
1570         .audio_ioctl            = ide_cdrom_audio_ioctl,
1571         .capability             = IDE_CD_CAPABILITIES,
1572         .generic_packet         = ide_cdrom_packet,
1573 };
1574
1575 static int ide_cdrom_register(ide_drive_t *drive, int nslots)
1576 {
1577         struct cdrom_info *info = drive->driver_data;
1578         struct cdrom_device_info *devinfo = &info->devinfo;
1579
1580         devinfo->ops = &ide_cdrom_dops;
1581         devinfo->speed = info->current_speed;
1582         devinfo->capacity = nslots;
1583         devinfo->handle = drive;
1584         strcpy(devinfo->name, drive->name);
1585
1586         if (info->cd_flags & IDE_CD_FLAG_NO_SPEED_SELECT)
1587                 devinfo->mask |= CDC_SELECT_SPEED;
1588
1589         devinfo->disk = info->disk;
1590         return register_cdrom(devinfo);
1591 }
1592
1593 static int ide_cdrom_probe_capabilities(ide_drive_t *drive)
1594 {
1595         struct cdrom_info *cd = drive->driver_data;
1596         struct cdrom_device_info *cdi = &cd->devinfo;
1597         u8 buf[ATAPI_CAPABILITIES_PAGE_SIZE];
1598         mechtype_t mechtype;
1599         int nslots = 1;
1600
1601         cdi->mask = (CDC_CD_R | CDC_CD_RW | CDC_DVD | CDC_DVD_R |
1602                      CDC_DVD_RAM | CDC_SELECT_DISC | CDC_PLAY_AUDIO |
1603                      CDC_MO_DRIVE | CDC_RAM);
1604
1605         if (drive->media == ide_optical) {
1606                 cdi->mask &= ~(CDC_MO_DRIVE | CDC_RAM);
1607                 printk(KERN_ERR "%s: ATAPI magneto-optical drive\n",
1608                                 drive->name);
1609                 return nslots;
1610         }
1611
1612         if (cd->cd_flags & IDE_CD_FLAG_PRE_ATAPI12) {
1613                 cd->cd_flags &= ~IDE_CD_FLAG_NO_EJECT;
1614                 cdi->mask &= ~CDC_PLAY_AUDIO;
1615                 return nslots;
1616         }
1617
1618         /*
1619          * We have to cheat a little here. the packet will eventually be queued
1620          * with ide_cdrom_packet(), which extracts the drive from cdi->handle.
1621          * Since this device hasn't been registered with the Uniform layer yet,
1622          * it can't do this. Same goes for cdi->ops.
1623          */
1624         cdi->handle = drive;
1625         cdi->ops = &ide_cdrom_dops;
1626
1627         if (ide_cdrom_get_capabilities(drive, buf))
1628                 return 0;
1629
1630         if ((buf[8 + 6] & 0x01) == 0)
1631                 cd->cd_flags |= IDE_CD_FLAG_NO_DOORLOCK;
1632         if (buf[8 + 6] & 0x08)
1633                 cd->cd_flags &= ~IDE_CD_FLAG_NO_EJECT;
1634         if (buf[8 + 3] & 0x01)
1635                 cdi->mask &= ~CDC_CD_R;
1636         if (buf[8 + 3] & 0x02)
1637                 cdi->mask &= ~(CDC_CD_RW | CDC_RAM);
1638         if (buf[8 + 2] & 0x38)
1639                 cdi->mask &= ~CDC_DVD;
1640         if (buf[8 + 3] & 0x20)
1641                 cdi->mask &= ~(CDC_DVD_RAM | CDC_RAM);
1642         if (buf[8 + 3] & 0x10)
1643                 cdi->mask &= ~CDC_DVD_R;
1644         if ((buf[8 + 4] & 0x01) || (cd->cd_flags & IDE_CD_FLAG_PLAY_AUDIO_OK))
1645                 cdi->mask &= ~CDC_PLAY_AUDIO;
1646
1647         mechtype = buf[8 + 6] >> 5;
1648         if (mechtype == mechtype_caddy || mechtype == mechtype_popup)
1649                 cdi->mask |= CDC_CLOSE_TRAY;
1650
1651         if (cdi->sanyo_slot > 0) {
1652                 cdi->mask &= ~CDC_SELECT_DISC;
1653                 nslots = 3;
1654         } else if (mechtype == mechtype_individual_changer ||
1655                    mechtype == mechtype_cartridge_changer) {
1656                 nslots = cdrom_number_of_slots(cdi);
1657                 if (nslots > 1)
1658                         cdi->mask &= ~CDC_SELECT_DISC;
1659         }
1660
1661         ide_cdrom_update_speed(drive, buf);
1662
1663         printk(KERN_INFO "%s: ATAPI", drive->name);
1664
1665         /* don't print speed if the drive reported 0 */
1666         if (cd->max_speed)
1667                 printk(KERN_CONT " %dX", cd->max_speed);
1668
1669         printk(KERN_CONT " %s", (cdi->mask & CDC_DVD) ? "CD-ROM" : "DVD-ROM");
1670
1671         if ((cdi->mask & CDC_DVD_R) == 0 || (cdi->mask & CDC_DVD_RAM) == 0)
1672                 printk(KERN_CONT " DVD%s%s",
1673                                  (cdi->mask & CDC_DVD_R) ? "" : "-R",
1674                                  (cdi->mask & CDC_DVD_RAM) ? "" : "-RAM");
1675
1676         if ((cdi->mask & CDC_CD_R) == 0 || (cdi->mask & CDC_CD_RW) == 0)
1677                 printk(KERN_CONT " CD%s%s",
1678                                  (cdi->mask & CDC_CD_R) ? "" : "-R",
1679                                  (cdi->mask & CDC_CD_RW) ? "" : "/RW");
1680
1681         if ((cdi->mask & CDC_SELECT_DISC) == 0)
1682                 printk(KERN_CONT " changer w/%d slots", nslots);
1683         else
1684                 printk(KERN_CONT " drive");
1685
1686         printk(KERN_CONT ", %dkB Cache\n", be16_to_cpu(*(u16 *)&buf[8 + 12]));
1687
1688         return nslots;
1689 }
1690
1691 /* standard prep_rq_fn that builds 10 byte cmds */
1692 static int ide_cdrom_prep_fs(struct request_queue *q, struct request *rq)
1693 {
1694         int hard_sect = queue_hardsect_size(q);
1695         long block = (long)rq->hard_sector / (hard_sect >> 9);
1696         unsigned long blocks = rq->hard_nr_sectors / (hard_sect >> 9);
1697
1698         memset(rq->cmd, 0, BLK_MAX_CDB);
1699
1700         if (rq_data_dir(rq) == READ)
1701                 rq->cmd[0] = GPCMD_READ_10;
1702         else
1703                 rq->cmd[0] = GPCMD_WRITE_10;
1704
1705         /*
1706          * fill in lba
1707          */
1708         rq->cmd[2] = (block >> 24) & 0xff;
1709         rq->cmd[3] = (block >> 16) & 0xff;
1710         rq->cmd[4] = (block >>  8) & 0xff;
1711         rq->cmd[5] = block & 0xff;
1712
1713         /*
1714          * and transfer length
1715          */
1716         rq->cmd[7] = (blocks >> 8) & 0xff;
1717         rq->cmd[8] = blocks & 0xff;
1718         rq->cmd_len = 10;
1719         return BLKPREP_OK;
1720 }
1721
1722 /*
1723  * Most of the SCSI commands are supported directly by ATAPI devices.
1724  * This transform handles the few exceptions.
1725  */
1726 static int ide_cdrom_prep_pc(struct request *rq)
1727 {
1728         u8 *c = rq->cmd;
1729
1730         /* transform 6-byte read/write commands to the 10-byte version */
1731         if (c[0] == READ_6 || c[0] == WRITE_6) {
1732                 c[8] = c[4];
1733                 c[5] = c[3];
1734                 c[4] = c[2];
1735                 c[3] = c[1] & 0x1f;
1736                 c[2] = 0;
1737                 c[1] &= 0xe0;
1738                 c[0] += (READ_10 - READ_6);
1739                 rq->cmd_len = 10;
1740                 return BLKPREP_OK;
1741         }
1742
1743         /*
1744          * it's silly to pretend we understand 6-byte sense commands, just
1745          * reject with ILLEGAL_REQUEST and the caller should take the
1746          * appropriate action
1747          */
1748         if (c[0] == MODE_SENSE || c[0] == MODE_SELECT) {
1749                 rq->errors = ILLEGAL_REQUEST;
1750                 return BLKPREP_KILL;
1751         }
1752
1753         return BLKPREP_OK;
1754 }
1755
1756 static int ide_cdrom_prep_fn(struct request_queue *q, struct request *rq)
1757 {
1758         if (blk_fs_request(rq))
1759                 return ide_cdrom_prep_fs(q, rq);
1760         else if (blk_pc_request(rq))
1761                 return ide_cdrom_prep_pc(rq);
1762
1763         return 0;
1764 }
1765
1766 struct cd_list_entry {
1767         const char      *id_model;
1768         const char      *id_firmware;
1769         unsigned int    cd_flags;
1770 };
1771
1772 #ifdef CONFIG_IDE_PROC_FS
1773 static sector_t ide_cdrom_capacity(ide_drive_t *drive)
1774 {
1775         unsigned long capacity, sectors_per_frame;
1776
1777         if (cdrom_read_capacity(drive, &capacity, &sectors_per_frame, NULL))
1778                 return 0;
1779
1780         return capacity * sectors_per_frame;
1781 }
1782
1783 static int proc_idecd_read_capacity(char *page, char **start, off_t off,
1784                                         int count, int *eof, void *data)
1785 {
1786         ide_drive_t *drive = data;
1787         int len;
1788
1789         len = sprintf(page, "%llu\n", (long long)ide_cdrom_capacity(drive));
1790         PROC_IDE_READ_RETURN(page, start, off, count, eof, len);
1791 }
1792
1793 static ide_proc_entry_t idecd_proc[] = {
1794         { "capacity", S_IFREG|S_IRUGO, proc_idecd_read_capacity, NULL },
1795         { NULL, 0, NULL, NULL }
1796 };
1797
1798 static void ide_cdrom_add_settings(ide_drive_t *drive)
1799 {
1800         ide_add_setting(drive, "dsc_overlap", SETTING_RW, TYPE_BYTE, 0, 1, 1, 1,
1801                         &drive->dsc_overlap, NULL);
1802 }
1803 #else
1804 static inline void ide_cdrom_add_settings(ide_drive_t *drive) { ; }
1805 #endif
1806
1807 static const struct cd_list_entry ide_cd_quirks_list[] = {
1808         /* Limit transfer size per interrupt. */
1809         { "SAMSUNG CD-ROM SCR-2430", NULL,   IDE_CD_FLAG_LIMIT_NFRAMES      },
1810         { "SAMSUNG CD-ROM SCR-2432", NULL,   IDE_CD_FLAG_LIMIT_NFRAMES      },
1811         /* SCR-3231 doesn't support the SET_CD_SPEED command. */
1812         { "SAMSUNG CD-ROM SCR-3231", NULL,   IDE_CD_FLAG_NO_SPEED_SELECT    },
1813         /* Old NEC260 (not R) was released before ATAPI 1.2 spec. */
1814         { "NEC CD-ROM DRIVE:260",    "1.01", IDE_CD_FLAG_TOCADDR_AS_BCD |
1815                                              IDE_CD_FLAG_PRE_ATAPI12,       },
1816         /* Vertos 300, some versions of this drive like to talk BCD. */
1817         { "V003S0DS",                NULL,   IDE_CD_FLAG_VERTOS_300_SSD,    },
1818         /* Vertos 600 ESD. */
1819         { "V006E0DS",                NULL,   IDE_CD_FLAG_VERTOS_600_ESD,    },
1820         /*
1821          * Sanyo 3 CD changer uses a non-standard command for CD changing
1822          * (by default standard ATAPI support for CD changers is used).
1823          */
1824         { "CD-ROM CDR-C3 G",         NULL,   IDE_CD_FLAG_SANYO_3CD          },
1825         { "CD-ROM CDR-C3G",          NULL,   IDE_CD_FLAG_SANYO_3CD          },
1826         { "CD-ROM CDR_C36",          NULL,   IDE_CD_FLAG_SANYO_3CD          },
1827         /* Stingray 8X CD-ROM. */
1828         { "STINGRAY 8422 IDE 8X CD-ROM 7-27-95", NULL, IDE_CD_FLAG_PRE_ATAPI12},
1829         /*
1830          * ACER 50X CD-ROM and WPI 32X CD-ROM require the full spec length
1831          * mode sense page capabilities size, but older drives break.
1832          */
1833         { "ATAPI CD ROM DRIVE 50X MAX", NULL,   IDE_CD_FLAG_FULL_CAPS_PAGE  },
1834         { "WPI CDS-32X",                NULL,   IDE_CD_FLAG_FULL_CAPS_PAGE  },
1835         /* ACER/AOpen 24X CD-ROM has the speed fields byte-swapped. */
1836         { "",                        "241N", IDE_CD_FLAG_LE_SPEED_FIELDS    },
1837         /*
1838          * Some drives used by Apple don't advertise audio play
1839          * but they do support reading TOC & audio datas.
1840          */
1841         { "MATSHITADVD-ROM SR-8187", NULL,   IDE_CD_FLAG_PLAY_AUDIO_OK      },
1842         { "MATSHITADVD-ROM SR-8186", NULL,   IDE_CD_FLAG_PLAY_AUDIO_OK      },
1843         { "MATSHITADVD-ROM SR-8176", NULL,   IDE_CD_FLAG_PLAY_AUDIO_OK      },
1844         { "MATSHITADVD-ROM SR-8174", NULL,   IDE_CD_FLAG_PLAY_AUDIO_OK      },
1845         { "Optiarc DVD RW AD-5200A", NULL,   IDE_CD_FLAG_PLAY_AUDIO_OK      },
1846         { NULL, NULL, 0 }
1847 };
1848
1849 static unsigned int ide_cd_flags(struct hd_driveid *id)
1850 {
1851         const struct cd_list_entry *cle = ide_cd_quirks_list;
1852
1853         while (cle->id_model) {
1854                 if (strcmp(cle->id_model, id->model) == 0 &&
1855                     (cle->id_firmware == NULL ||
1856                      strstr(id->fw_rev, cle->id_firmware)))
1857                         return cle->cd_flags;
1858                 cle++;
1859         }
1860
1861         return 0;
1862 }
1863
1864 static int ide_cdrom_setup(ide_drive_t *drive)
1865 {
1866         struct cdrom_info *cd = drive->driver_data;
1867         struct cdrom_device_info *cdi = &cd->devinfo;
1868         struct hd_driveid *id = drive->id;
1869         int nslots;
1870
1871         blk_queue_prep_rq(drive->queue, ide_cdrom_prep_fn);
1872         blk_queue_dma_alignment(drive->queue, 31);
1873         blk_queue_update_dma_pad(drive->queue, 15);
1874         drive->queue->unplug_delay = (1 * HZ) / 1000;
1875         if (!drive->queue->unplug_delay)
1876                 drive->queue->unplug_delay = 1;
1877
1878         drive->special.all      = 0;
1879
1880         cd->cd_flags = IDE_CD_FLAG_MEDIA_CHANGED | IDE_CD_FLAG_NO_EJECT |
1881                        ide_cd_flags(id);
1882
1883         if ((id->config & 0x0060) == 0x20)
1884                 cd->cd_flags |= IDE_CD_FLAG_DRQ_INTERRUPT;
1885
1886         if ((cd->cd_flags & IDE_CD_FLAG_VERTOS_300_SSD) &&
1887             id->fw_rev[4] == '1' && id->fw_rev[6] <= '2')
1888                 cd->cd_flags |= (IDE_CD_FLAG_TOCTRACKS_AS_BCD |
1889                                  IDE_CD_FLAG_TOCADDR_AS_BCD);
1890         else if ((cd->cd_flags & IDE_CD_FLAG_VERTOS_600_ESD) &&
1891                  id->fw_rev[4] == '1' && id->fw_rev[6] <= '2')
1892                 cd->cd_flags |= IDE_CD_FLAG_TOCTRACKS_AS_BCD;
1893         else if (cd->cd_flags & IDE_CD_FLAG_SANYO_3CD)
1894                 /* 3 => use CD in slot 0 */
1895                 cdi->sanyo_slot = 3;
1896
1897         nslots = ide_cdrom_probe_capabilities(drive);
1898
1899         /* set correct block size */
1900         blk_queue_hardsect_size(drive->queue, CD_FRAMESIZE);
1901
1902         drive->dsc_overlap = (drive->next != drive);
1903
1904         if (ide_cdrom_register(drive, nslots)) {
1905                 printk(KERN_ERR "%s: %s failed to register device with the"
1906                                 " cdrom driver.\n", drive->name, __func__);
1907                 cd->devinfo.handle = NULL;
1908                 return 1;
1909         }
1910         ide_cdrom_add_settings(drive);
1911         return 0;
1912 }
1913
1914 static void ide_cd_remove(ide_drive_t *drive)
1915 {
1916         struct cdrom_info *info = drive->driver_data;
1917
1918         ide_proc_unregister_driver(drive, info->driver);
1919
1920         del_gendisk(info->disk);
1921
1922         ide_cd_put(info);
1923 }
1924
1925 static void ide_cd_release(struct kref *kref)
1926 {
1927         struct cdrom_info *info = to_ide_cd(kref);
1928         struct cdrom_device_info *devinfo = &info->devinfo;
1929         ide_drive_t *drive = info->drive;
1930         struct gendisk *g = info->disk;
1931
1932         kfree(info->toc);
1933         if (devinfo->handle == drive)
1934                 unregister_cdrom(devinfo);
1935         drive->dsc_overlap = 0;
1936         drive->driver_data = NULL;
1937         blk_queue_prep_rq(drive->queue, NULL);
1938         g->private_data = NULL;
1939         put_disk(g);
1940         kfree(info);
1941 }
1942
1943 static int ide_cd_probe(ide_drive_t *);
1944
1945 static ide_driver_t ide_cdrom_driver = {
1946         .gen_driver = {
1947                 .owner          = THIS_MODULE,
1948                 .name           = "ide-cdrom",
1949                 .bus            = &ide_bus_type,
1950         },
1951         .probe                  = ide_cd_probe,
1952         .remove                 = ide_cd_remove,
1953         .version                = IDECD_VERSION,
1954         .media                  = ide_cdrom,
1955         .supports_dsc_overlap   = 1,
1956         .do_request             = ide_cd_do_request,
1957         .end_request            = ide_end_request,
1958         .error                  = __ide_error,
1959 #ifdef CONFIG_IDE_PROC_FS
1960         .proc                   = idecd_proc,
1961 #endif
1962 };
1963
1964 static int idecd_open(struct inode *inode, struct file *file)
1965 {
1966         struct gendisk *disk = inode->i_bdev->bd_disk;
1967         struct cdrom_info *info;
1968         int rc = -ENOMEM;
1969
1970         info = ide_cd_get(disk);
1971         if (!info)
1972                 return -ENXIO;
1973
1974         rc = cdrom_open(&info->devinfo, inode, file);
1975
1976         if (rc < 0)
1977                 ide_cd_put(info);
1978
1979         return rc;
1980 }
1981
1982 static int idecd_release(struct inode *inode, struct file *file)
1983 {
1984         struct gendisk *disk = inode->i_bdev->bd_disk;
1985         struct cdrom_info *info = ide_cd_g(disk);
1986
1987         cdrom_release(&info->devinfo, file);
1988
1989         ide_cd_put(info);
1990
1991         return 0;
1992 }
1993
1994 static int idecd_set_spindown(struct cdrom_device_info *cdi, unsigned long arg)
1995 {
1996         struct packet_command cgc;
1997         char buffer[16];
1998         int stat;
1999         char spindown;
2000
2001         if (copy_from_user(&spindown, (void __user *)arg, sizeof(char)))
2002                 return -EFAULT;
2003
2004         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
2005
2006         stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0);
2007         if (stat)
2008                 return stat;
2009
2010         buffer[11] = (buffer[11] & 0xf0) | (spindown & 0x0f);
2011         return cdrom_mode_select(cdi, &cgc);
2012 }
2013
2014 static int idecd_get_spindown(struct cdrom_device_info *cdi, unsigned long arg)
2015 {
2016         struct packet_command cgc;
2017         char buffer[16];
2018         int stat;
2019         char spindown;
2020
2021         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
2022
2023         stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0);
2024         if (stat)
2025                 return stat;
2026
2027         spindown = buffer[11] & 0x0f;
2028         if (copy_to_user((void __user *)arg, &spindown, sizeof(char)))
2029                 return -EFAULT;
2030         return 0;
2031 }
2032
2033 static int idecd_ioctl(struct inode *inode, struct file *file,
2034                         unsigned int cmd, unsigned long arg)
2035 {
2036         struct block_device *bdev = inode->i_bdev;
2037         struct cdrom_info *info = ide_cd_g(bdev->bd_disk);
2038         int err;
2039
2040         switch (cmd) {
2041         case CDROMSETSPINDOWN:
2042                 return idecd_set_spindown(&info->devinfo, arg);
2043         case CDROMGETSPINDOWN:
2044                 return idecd_get_spindown(&info->devinfo, arg);
2045         default:
2046                 break;
2047         }
2048
2049         err = generic_ide_ioctl(info->drive, file, bdev, cmd, arg);
2050         if (err == -EINVAL)
2051                 err = cdrom_ioctl(file, &info->devinfo, inode, cmd, arg);
2052
2053         return err;
2054 }
2055
2056 static int idecd_media_changed(struct gendisk *disk)
2057 {
2058         struct cdrom_info *info = ide_cd_g(disk);
2059         return cdrom_media_changed(&info->devinfo);
2060 }
2061
2062 static int idecd_revalidate_disk(struct gendisk *disk)
2063 {
2064         struct cdrom_info *info = ide_cd_g(disk);
2065         struct request_sense sense;
2066
2067         ide_cd_read_toc(info->drive, &sense);
2068
2069         return  0;
2070 }
2071
2072 static struct block_device_operations idecd_ops = {
2073         .owner                  = THIS_MODULE,
2074         .open                   = idecd_open,
2075         .release                = idecd_release,
2076         .ioctl                  = idecd_ioctl,
2077         .media_changed          = idecd_media_changed,
2078         .revalidate_disk        = idecd_revalidate_disk
2079 };
2080
2081 /* module options */
2082 static char *ignore;
2083
2084 module_param(ignore, charp, 0400);
2085 MODULE_DESCRIPTION("ATAPI CD-ROM Driver");
2086
2087 static int ide_cd_probe(ide_drive_t *drive)
2088 {
2089         struct cdrom_info *info;
2090         struct gendisk *g;
2091         struct request_sense sense;
2092
2093         if (!strstr("ide-cdrom", drive->driver_req))
2094                 goto failed;
2095         if (!drive->present)
2096                 goto failed;
2097         if (drive->media != ide_cdrom && drive->media != ide_optical)
2098                 goto failed;
2099         /* skip drives that we were told to ignore */
2100         if (ignore != NULL) {
2101                 if (strstr(ignore, drive->name)) {
2102                         printk(KERN_INFO "ide-cd: ignoring drive %s\n",
2103                                          drive->name);
2104                         goto failed;
2105                 }
2106         }
2107         info = kzalloc(sizeof(struct cdrom_info), GFP_KERNEL);
2108         if (info == NULL) {
2109                 printk(KERN_ERR "%s: Can't allocate a cdrom structure\n",
2110                                 drive->name);
2111                 goto failed;
2112         }
2113
2114         g = alloc_disk(1 << PARTN_BITS);
2115         if (!g)
2116                 goto out_free_cd;
2117
2118         ide_init_disk(g, drive);
2119
2120         ide_proc_register_driver(drive, &ide_cdrom_driver);
2121
2122         kref_init(&info->kref);
2123
2124         info->drive = drive;
2125         info->driver = &ide_cdrom_driver;
2126         info->disk = g;
2127
2128         g->private_data = &info->driver;
2129
2130         drive->driver_data = info;
2131
2132         g->minors = 1;
2133         g->driverfs_dev = &drive->gendev;
2134         g->flags = GENHD_FL_CD | GENHD_FL_REMOVABLE;
2135         if (ide_cdrom_setup(drive)) {
2136                 ide_proc_unregister_driver(drive, &ide_cdrom_driver);
2137                 ide_cd_release(&info->kref);
2138                 goto failed;
2139         }
2140
2141         ide_cd_read_toc(drive, &sense);
2142         g->fops = &idecd_ops;
2143         g->flags |= GENHD_FL_REMOVABLE;
2144         add_disk(g);
2145         return 0;
2146
2147 out_free_cd:
2148         kfree(info);
2149 failed:
2150         return -ENODEV;
2151 }
2152
2153 static void __exit ide_cdrom_exit(void)
2154 {
2155         driver_unregister(&ide_cdrom_driver.gen_driver);
2156 }
2157
2158 static int __init ide_cdrom_init(void)
2159 {
2160         return driver_register(&ide_cdrom_driver.gen_driver);
2161 }
2162
2163 MODULE_ALIAS("ide:*m-cdrom*");
2164 MODULE_ALIAS("ide-cd");
2165 module_init(ide_cdrom_init);
2166 module_exit(ide_cdrom_exit);
2167 MODULE_LICENSE("GPL");