ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[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  * ----------------------------------
32  * 1.00  Oct 31, 1994 -- Initial version.
33  * 1.01  Nov  2, 1994 -- Fixed problem with starting request in
34  *                       cdrom_check_status.
35  * 1.03  Nov 25, 1994 -- leaving unmask_intr[] as a user-setting (as for disks)
36  * (from mlord)       -- minor changes to cdrom_setup()
37  *                    -- renamed ide_dev_s to ide_drive_t, enable irq on command
38  * 2.00  Nov 27, 1994 -- Generalize packet command interface;
39  *                       add audio ioctls.
40  * 2.01  Dec  3, 1994 -- Rework packet command interface to handle devices
41  *                       which send an interrupt when ready for a command.
42  * 2.02  Dec 11, 1994 -- Cache the TOC in the driver.
43  *                       Don't use SCMD_PLAYAUDIO_TI; it's not included
44  *                       in the current version of ATAPI.
45  *                       Try to use LBA instead of track or MSF addressing
46  *                       when possible.
47  *                       Don't wait for READY_STAT.
48  * 2.03  Jan 10, 1995 -- Rewrite block read routines to handle block sizes
49  *                       other than 2k and to move multiple sectors in a
50  *                       single transaction.
51  * 2.04  Apr 21, 1995 -- Add work-around for Creative Labs CD220E drives.
52  *                       Thanks to Nick Saw <cwsaw@pts7.pts.mot.com> for
53  *                       help in figuring this out.  Ditto for Acer and
54  *                       Aztech drives, which seem to have the same problem.
55  * 2.04b May 30, 1995 -- Fix to match changes in ide.c version 3.16 -ml
56  * 2.05  Jun  8, 1995 -- Don't attempt to retry after an illegal request
57  *                        or data protect error.
58  *                       Use HWIF and DEV_HWIF macros as in ide.c.
59  *                       Always try to do a request_sense after
60  *                        a failed command.
61  *                       Include an option to give textual descriptions
62  *                        of ATAPI errors.
63  *                       Fix a bug in handling the sector cache which
64  *                        showed up if the drive returned data in 512 byte
65  *                        blocks (like Pioneer drives).  Thanks to
66  *                        Richard Hirst <srh@gpt.co.uk> for diagnosing this.
67  *                       Properly supply the page number field in the
68  *                        MODE_SELECT command.
69  *                       PLAYAUDIO12 is broken on the Aztech; work around it.
70  * 2.05x Aug 11, 1995 -- lots of data structure renaming/restructuring in ide.c
71  *                       (my apologies to Scott, but now ide-cd.c is independent)
72  * 3.00  Aug 22, 1995 -- Implement CDROMMULTISESSION ioctl.
73  *                       Implement CDROMREADAUDIO ioctl (UNTESTED).
74  *                       Use input_ide_data() and output_ide_data().
75  *                       Add door locking.
76  *                       Fix usage count leak in cdrom_open, which happened
77  *                        when a read-write mount was attempted.
78  *                       Try to load the disk on open.
79  *                       Implement CDROMEJECT_SW ioctl (off by default).
80  *                       Read total cdrom capacity during open.
81  *                       Rearrange logic in cdrom_decode_status.  Issue
82  *                        request sense commands for failed packet commands
83  *                        from here instead of from cdrom_queue_packet_command.
84  *                        Fix a race condition in retrieving error information.
85  *                       Suppress printing normal unit attention errors and
86  *                        some drive not ready errors.
87  *                       Implement CDROMVOLREAD ioctl.
88  *                       Implement CDROMREADMODE1/2 ioctls.
89  *                       Fix race condition in setting up interrupt handlers
90  *                        when the `serialize' option is used.
91  * 3.01  Sep  2, 1995 -- Fix ordering of reenabling interrupts in
92  *                        cdrom_queue_request.
93  *                       Another try at using ide_[input,output]_data.
94  * 3.02  Sep 16, 1995 -- Stick total disk capacity in partition table as well.
95  *                       Make VERBOSE_IDE_CD_ERRORS dump failed command again.
96  *                       Dump out more information for ILLEGAL REQUEST errs.
97  *                       Fix handling of errors occurring before the
98  *                        packet command is transferred.
99  *                       Fix transfers with odd bytelengths.
100  * 3.03  Oct 27, 1995 -- Some Creative drives have an id of just `CD'.
101  *                       `DCI-2S10' drives are broken too.
102  * 3.04  Nov 20, 1995 -- So are Vertos drives.
103  * 3.05  Dec  1, 1995 -- Changes to go with overhaul of ide.c and ide-tape.c
104  * 3.06  Dec 16, 1995 -- Add support needed for partitions.
105  *                       More workarounds for Vertos bugs (based on patches
106  *                        from Holger Dietze <dietze@aix520.informatik.uni-leipzig.de>).
107  *                       Try to eliminate byteorder assumptions.
108  *                       Use atapi_cdrom_subchnl struct definition.
109  *                       Add STANDARD_ATAPI compilation option.
110  * 3.07  Jan 29, 1996 -- More twiddling for broken drives: Sony 55D,
111  *                        Vertos 300.
112  *                       Add NO_DOOR_LOCKING configuration option.
113  *                       Handle drive_cmd requests w/NULL args (for hdparm -t).
114  *                       Work around sporadic Sony55e audio play problem.
115  * 3.07a Feb 11, 1996 -- check drive->id for NULL before dereferencing, to fix
116  *                        problem with "hde=cdrom" with no drive present.  -ml
117  * 3.08  Mar  6, 1996 -- More Vertos workarounds.
118  * 3.09  Apr  5, 1996 -- Add CDROMCLOSETRAY ioctl.
119  *                       Switch to using MSF addressing for audio commands.
120  *                       Reformat to match kernel tabbing style.
121  *                       Add CDROM_GET_UPC ioctl.
122  * 3.10  Apr 10, 1996 -- Fix compilation error with STANDARD_ATAPI.
123  * 3.11  Apr 29, 1996 -- Patch from Heiko Eissfeldt <heiko@colossus.escape.de>
124  *                       to remove redundant verify_area calls.
125  * 3.12  May  7, 1996 -- Rudimentary changer support.  Based on patches
126  *                        from Gerhard Zuber <zuber@berlin.snafu.de>.
127  *                       Let open succeed even if there's no loaded disc.
128  * 3.13  May 19, 1996 -- Fixes for changer code.
129  * 3.14  May 29, 1996 -- Add work-around for Vertos 600.
130  *                        (From Hennus Bergman <hennus@sky.ow.nl>.)
131  * 3.15  July 2, 1996 -- Added support for Sanyo 3 CD changers
132  *                        from Ben Galliart <bgallia@luc.edu> with 
133  *                        special help from Jeff Lightfoot 
134  *                        <jeffml@pobox.com>
135  * 3.15a July 9, 1996 -- Improved Sanyo 3 CD changer identification
136  * 3.16  Jul 28, 1996 -- Fix from Gadi to reduce kernel stack usage for ioctl.
137  * 3.17  Sep 17, 1996 -- Tweak audio reads for some drives.
138  *                       Start changing CDROMLOADFROMSLOT to CDROM_SELECT_DISC.
139  * 3.18  Oct 31, 1996 -- Added module and DMA support.
140  *                       
141  *                       
142  * 4.00  Nov 5, 1996   -- New ide-cd maintainer,
143  *                                 Erik B. Andersen <andersee@debian.org>
144  *                     -- Newer Creative drives don't always set the error
145  *                          register correctly.  Make sure we see media changes
146  *                          regardless.
147  *                     -- Integrate with generic cdrom driver.
148  *                     -- CDROMGETSPINDOWN and CDROMSETSPINDOWN ioctls, based on
149  *                          a patch from Ciro Cattuto <>.
150  *                     -- Call set_device_ro.
151  *                     -- Implement CDROMMECHANISMSTATUS and CDROMSLOTTABLE
152  *                          ioctls, based on patch by Erik Andersen
153  *                     -- Add some probes of drive capability during setup.
154  *
155  * 4.01  Nov 11, 1996  -- Split into ide-cd.c and ide-cd.h
156  *                     -- Removed CDROMMECHANISMSTATUS and CDROMSLOTTABLE 
157  *                          ioctls in favor of a generalized approach 
158  *                          using the generic cdrom driver.
159  *                     -- Fully integrated with the 2.1.X kernel.
160  *                     -- Other stuff that I forgot (lots of changes)
161  *
162  * 4.02  Dec 01, 1996  -- Applied patch from Gadi Oxman <gadio@netvision.net.il>
163  *                          to fix the drive door locking problems.
164  *
165  * 4.03  Dec 04, 1996  -- Added DSC overlap support.
166  * 4.04  Dec 29, 1996  -- Added CDROMREADRAW ioclt based on patch 
167  *                          by Ales Makarov (xmakarov@sun.felk.cvut.cz)
168  *
169  * 4.05  Nov 20, 1997  -- Modified to print more drive info on init
170  *                        Minor other changes
171  *                        Fix errors on CDROMSTOP (If you have a "Dolphin",
172  *                          you must define IHAVEADOLPHIN)
173  *                        Added identifier so new Sanyo CD-changer works
174  *                        Better detection if door locking isn't supported
175  *
176  * 4.06  Dec 17, 1997  -- fixed endless "tray open" messages  -ml
177  * 4.07  Dec 17, 1997  -- fallback to set pc->stat on "tray open"
178  * 4.08  Dec 18, 1997  -- spew less noise when tray is empty
179  *                     -- fix speed display for ACER 24X, 18X
180  * 4.09  Jan 04, 1998  -- fix handling of the last block so we return
181  *                         an end of file instead of an I/O error (Gadi)
182  * 4.10  Jan 24, 1998  -- fixed a bug so now changers can change to a new
183  *                         slot when there is no disc in the current slot.
184  *                     -- Fixed a memory leak where info->changer_info was
185  *                         malloc'ed but never free'd when closing the device.
186  *                     -- Cleaned up the global namespace a bit by making more
187  *                         functions static that should already have been.
188  * 4.11  Mar 12, 1998  -- Added support for the CDROM_SELECT_SPEED ioctl
189  *                         based on a patch for 2.0.33 by Jelle Foks 
190  *                         <jelle@scintilla.utwente.nl>, a patch for 2.0.33
191  *                         by Toni Giorgino <toni@pcape2.pi.infn.it>, the SCSI
192  *                         version, and my own efforts.  -erik
193  *                     -- Fixed a stupid bug which egcs was kind enough to
194  *                         inform me of where "Illegal mode for this track"
195  *                         was never returned due to a comparison on data
196  *                         types of limited range.
197  * 4.12  Mar 29, 1998  -- Fixed bug in CDROM_SELECT_SPEED so write speed is 
198  *                         now set ionly for CD-R and CD-RW drives.  I had 
199  *                         removed this support because it produced errors.
200  *                         It produced errors _only_ for non-writers. duh.
201  * 4.13  May 05, 1998  -- Suppress useless "in progress of becoming ready"
202  *                         messages, since this is not an error.
203  *                     -- Change error messages to be const
204  *                     -- Remove a "\t" which looks ugly in the syslogs
205  * 4.14  July 17, 1998 -- Change to pointing to .ps version of ATAPI spec
206  *                         since the .pdf version doesn't seem to work...
207  *                     -- Updated the TODO list to something more current.
208  *
209  * 4.15  Aug 25, 1998  -- Updated ide-cd.h to respect mechine endianess, 
210  *                         patch thanks to "Eddie C. Dost" <ecd@skynet.be>
211  *
212  * 4.50  Oct 19, 1998  -- New maintainers!
213  *                         Jens Axboe <axboe@image.dk>
214  *                         Chris Zwilling <chris@cloudnet.com>
215  *
216  * 4.51  Dec 23, 1998  -- Jens Axboe <axboe@image.dk>
217  *                      - ide_cdrom_reset enabled since the ide subsystem
218  *                         handles resets fine now. <axboe@image.dk>
219  *                      - Transfer size fix for Samsung CD-ROMs, thanks to
220  *                        "Ville Hallik" <ville.hallik@mail.ee>.
221  *                      - other minor stuff.
222  *
223  * 4.52  Jan 19, 1999  -- Jens Axboe <axboe@image.dk>
224  *                      - Detect DVD-ROM/RAM drives
225  *
226  * 4.53  Feb 22, 1999   - Include other model Samsung and one Goldstar
227  *                         drive in transfer size limit.
228  *                      - Fix the I/O error when doing eject without a medium
229  *                         loaded on some drives.
230  *                      - CDROMREADMODE2 is now implemented through
231  *                         CDROMREADRAW, since many drives don't support
232  *                         MODE2 (even though ATAPI 2.6 says they must).
233  *                      - Added ignore parameter to ide-cd (as a module), eg
234  *                              insmod ide-cd ignore='hda hdb'
235  *                         Useful when using ide-cd in conjunction with
236  *                         ide-scsi. TODO: non-modular way of doing the
237  *                         same.
238  *
239  * 4.54  Aug 5, 1999    - Support for MMC2 class commands through the generic
240  *                        packet interface to cdrom.c.
241  *                      - Unified audio ioctl support, most of it.
242  *                      - cleaned up various deprecated verify_area().
243  *                      - Added ide_cdrom_packet() as the interface for
244  *                        the Uniform generic_packet().
245  *                      - bunch of other stuff, will fill in logs later.
246  *                      - report 1 slot for non-changers, like the other
247  *                        cd-rom drivers. don't report select disc for
248  *                        non-changers as well.
249  *                      - mask out audio playing, if the device can't do it.
250  *
251  * 4.55  Sep 1, 1999    - Eliminated the rest of the audio ioctls, except
252  *                        for CDROMREADTOC[ENTRY|HEADER]. Some of the drivers
253  *                        use this independently of the actual audio handling.
254  *                        They will disappear later when I get the time to
255  *                        do it cleanly.
256  *                      - Minimize the TOC reading - only do it when we
257  *                        know a media change has occurred.
258  *                      - Moved all the CDROMREADx ioctls to the Uniform layer.
259  *                      - Heiko Eissfeldt <heiko@colossus.escape.de> supplied
260  *                        some fixes for CDI.
261  *                      - CD-ROM leaving door locked fix from Andries
262  *                        Brouwer <Andries.Brouwer@cwi.nl>
263  *                      - Erik Andersen <andersen@xmission.com> unified
264  *                        commands across the various drivers and how
265  *                        sense errors are handled.
266  *
267  * 4.56  Sep 12, 1999   - Removed changer support - it is now in the
268  *                        Uniform layer.
269  *                      - Added partition based multisession handling.
270  *                      - Mode sense and mode select moved to the
271  *                        Uniform layer.
272  *                      - Fixed a problem with WPI CDS-32X drive - it
273  *                        failed the capabilities 
274  *
275  * 4.57  Apr 7, 2000    - Fixed sense reporting.
276  *                      - Fixed possible oops in ide_cdrom_get_last_session()
277  *                      - Fix locking mania and make ide_cdrom_reset relock
278  *                      - Stop spewing errors to log when magicdev polls with
279  *                        TEST_UNIT_READY on some drives.
280  *                      - Various fixes from Tobias Ringstrom:
281  *                        tray if it was locked prior to the reset.
282  *                        - cdrom_read_capacity returns one frame too little.
283  *                        - Fix real capacity reporting.
284  *
285  * 4.58  May 1, 2000    - Clean up ACER50 stuff.
286  *                      - Fix small problem with ide_cdrom_capacity
287  *
288  * 4.59  Aug 11, 2000   - Fix changer problem in cdrom_read_toc, we weren't
289  *                        correctly sensing a disc change.
290  *                      - Rearranged some code
291  *                      - Use extended sense on drives that support it for
292  *                        correctly reporting tray status -- from
293  *                        Michael D Johnson <johnsom@orst.edu>
294  * 4.60  Dec 17, 2003   - Add mt rainier support
295  *                      - Bump timeout for packet commands, matches sr
296  *                      - Odd stuff
297  * 4.61  Jan 22, 2004   - support hardware sector sizes other than 2kB,
298  *                        Pascal Schmidt <der.eremit@email.de>
299  *
300  *************************************************************************/
301  
302 #define IDECD_VERSION "4.61"
303
304 #include <linux/config.h>
305 #include <linux/module.h>
306 #include <linux/types.h>
307 #include <linux/kernel.h>
308 #include <linux/delay.h>
309 #include <linux/timer.h>
310 #include <linux/slab.h>
311 #include <linux/interrupt.h>
312 #include <linux/errno.h>
313 #include <linux/cdrom.h>
314 #include <linux/ide.h>
315 #include <linux/completion.h>
316
317 #include <scsi/scsi.h>  /* For SCSI -> ATAPI command conversion */
318
319 #include <asm/irq.h>
320 #include <asm/io.h>
321 #include <asm/byteorder.h>
322 #include <asm/uaccess.h>
323 #include <asm/unaligned.h>
324
325 #include "ide-cd.h"
326
327 /****************************************************************************
328  * Generic packet command support and error handling routines.
329  */
330
331 /* Mark that we've seen a media change, and invalidate our internal
332    buffers. */
333 static void cdrom_saw_media_change (ide_drive_t *drive)
334 {
335         struct cdrom_info *info = drive->driver_data;
336         
337         CDROM_STATE_FLAGS (drive)->media_changed = 1;
338         CDROM_STATE_FLAGS (drive)->toc_valid = 0;
339         info->nsectors_buffered = 0;
340 }
341
342 static int cdrom_log_sense(ide_drive_t *drive, struct request *rq,
343                            struct request_sense *sense)
344 {
345         int log = 0;
346
347         if (!sense || !rq || (rq->flags & REQ_QUIET))
348                 return 0;
349
350         switch (sense->sense_key) {
351                 case NO_SENSE: case RECOVERED_ERROR:
352                         break;
353                 case NOT_READY:
354                         /*
355                          * don't care about tray state messages for
356                          * e.g. capacity commands or in-progress or
357                          * becoming ready
358                          */
359                         if (sense->asc == 0x3a || sense->asc == 0x04)
360                                 break;
361                         log = 1;
362                         break;
363                 case ILLEGAL_REQUEST:
364                         /*
365                          * don't log START_STOP unit with LoEj set, since
366                          * we cannot reliably check if drive can auto-close
367                          */
368                         if (rq->cmd[0] == GPCMD_START_STOP_UNIT && sense->asc == 0x24)
369                                 log = 0;
370                         break;
371                 case UNIT_ATTENTION:
372                         /*
373                          * Make good and sure we've seen this potential media
374                          * change. Some drives (i.e. Creative) fail to present
375                          * the correct sense key in the error register.
376                          */
377                         cdrom_saw_media_change(drive);
378                         break;
379                 default:
380                         log = 1;
381                         break;
382         }
383         return log;
384 }
385
386 static
387 void cdrom_analyze_sense_data(ide_drive_t *drive,
388                               struct request *failed_command,
389                               struct request_sense *sense)
390 {
391         if (!cdrom_log_sense(drive, failed_command, sense))
392                 return;
393
394         /*
395          * If a read toc is executed for a CD-R or CD-RW medium where
396          * the first toc has not been recorded yet, it will fail with
397          * 05/24/00 (which is a confusing error)
398          */
399         if (failed_command && failed_command->cmd[0] == GPCMD_READ_TOC_PMA_ATIP)
400                 if (sense->sense_key == 0x05 && sense->asc == 0x24)
401                         return;
402
403 #if VERBOSE_IDE_CD_ERRORS
404         {
405                 int i;
406                 const char *s;
407                 char buf[80];
408
409                 printk ("ATAPI device %s:\n", drive->name);
410                 if (sense->error_code==0x70)
411                         printk("  Error: ");
412                 else if (sense->error_code==0x71)
413                         printk("  Deferred Error: ");
414                 else if (sense->error_code == 0x7f)
415                         printk("  Vendor-specific Error: ");
416                 else
417                         printk("  Unknown Error Type: ");
418
419                 if (sense->sense_key < ARY_LEN(sense_key_texts))
420                         s = sense_key_texts[sense->sense_key];
421                 else
422                         s = "bad sense key!";
423
424                 printk("%s -- (Sense key=0x%02x)\n", s, sense->sense_key);
425
426                 if (sense->asc == 0x40) {
427                         sprintf(buf, "Diagnostic failure on component 0x%02x",
428                                  sense->ascq);
429                         s = buf;
430                 } else {
431                         int lo = 0, mid, hi = ARY_LEN(sense_data_texts);
432                         unsigned long key = (sense->sense_key << 16);
433                         key |= (sense->asc << 8);
434                         if (!(sense->ascq >= 0x80 && sense->ascq <= 0xdd))
435                                 key |= sense->ascq;
436                         s = NULL;
437
438                         while (hi > lo) {
439                                 mid = (lo + hi) / 2;
440                                 if (sense_data_texts[mid].asc_ascq == key ||
441                                     sense_data_texts[mid].asc_ascq == (0xff0000|key)) {
442                                         s = sense_data_texts[mid].text;
443                                         break;
444                                 }
445                                 else if (sense_data_texts[mid].asc_ascq > key)
446                                         hi = mid;
447                                 else
448                                         lo = mid+1;
449                         }
450                 }
451
452                 if (s == NULL) {
453                         if (sense->asc > 0x80)
454                                 s = "(vendor-specific error)";
455                         else
456                                 s = "(reserved error code)";
457                 }
458
459                 printk("  %s -- (asc=0x%02x, ascq=0x%02x)\n",
460                         s, sense->asc, sense->ascq);
461
462                 if (failed_command != NULL) {
463
464                         int lo=0, mid, hi= ARY_LEN (packet_command_texts);
465                         s = NULL;
466
467                         while (hi > lo) {
468                                 mid = (lo + hi) / 2;
469                                 if (packet_command_texts[mid].packet_command ==
470                                     failed_command->cmd[0]) {
471                                         s = packet_command_texts[mid].text;
472                                         break;
473                                 }
474                                 if (packet_command_texts[mid].packet_command >
475                                     failed_command->cmd[0])
476                                         hi = mid;
477                                 else
478                                         lo = mid+1;
479                         }
480
481                         printk ("  The failed \"%s\" packet command was: \n  \"", s);
482                         for (i=0; i<sizeof (failed_command->cmd); i++)
483                                 printk ("%02x ", failed_command->cmd[i]);
484                         printk ("\"\n");
485                 }
486
487                 /* The SKSV bit specifies validity of the sense_key_specific
488                  * in the next two commands. It is bit 7 of the first byte.
489                  * In the case of NOT_READY, if SKSV is set the drive can
490                  * give us nice ETA readings.
491                  */
492                 if (sense->sense_key == NOT_READY && (sense->sks[0] & 0x80)) {
493                         int progress = (sense->sks[1] << 8 | sense->sks[2]) * 100;
494                         printk("  Command is %02d%% complete\n", progress / 0xffff);
495
496                 }
497
498                 if (sense->sense_key == ILLEGAL_REQUEST &&
499                     (sense->sks[0] & 0x80) != 0) {
500                         printk("  Error in %s byte %d",
501                                 (sense->sks[0] & 0x40) != 0 ?
502                                 "command packet" : "command data",
503                                 (sense->sks[1] << 8) + sense->sks[2]);
504
505                         if ((sense->sks[0] & 0x40) != 0)
506                                 printk (" bit %d", sense->sks[0] & 0x07);
507
508                         printk ("\n");
509                 }
510         }
511
512 #else /* not VERBOSE_IDE_CD_ERRORS */
513
514         /* Suppress printing unit attention and `in progress of becoming ready'
515            errors when we're not being verbose. */
516
517         if (sense->sense_key == UNIT_ATTENTION ||
518             (sense->sense_key == NOT_READY && (sense->asc == 4 ||
519                                                 sense->asc == 0x3a)))
520                 return;
521
522         printk("%s: error code: 0x%02x  sense_key: 0x%02x  asc: 0x%02x  ascq: 0x%02x\n",
523                 drive->name,
524                 sense->error_code, sense->sense_key,
525                 sense->asc, sense->ascq);
526 #endif /* not VERBOSE_IDE_CD_ERRORS */
527 }
528
529 /*
530  * Initialize a ide-cd packet command request
531  */
532 static void cdrom_prepare_request(struct request *rq)
533 {
534         ide_init_drive_cmd(rq);
535         rq->flags = REQ_PC;
536 }
537
538 static void cdrom_queue_request_sense(ide_drive_t *drive, 
539                                       struct completion *wait,
540                                       void *sense,
541                                       struct request *failed_command)
542 {
543         struct cdrom_info *info         = drive->driver_data;
544         struct request *rq              = &info->request_sense_request;
545
546         if (sense == NULL)
547                 sense = &info->sense_data;
548
549         /* stuff the sense request in front of our current request */
550         cdrom_prepare_request(rq);
551
552         rq->data = sense;
553         rq->cmd[0] = GPCMD_REQUEST_SENSE;
554         rq->cmd[4] = rq->data_len = 18;
555
556         rq->flags = REQ_SENSE;
557         rq->waiting = wait;
558
559         /* NOTE! Save the failed command in "rq->buffer" */
560         rq->buffer = (void *) failed_command;
561
562         (void) ide_do_drive_cmd(drive, rq, ide_preempt);
563 }
564
565 /*
566  * ide_error() takes action based on the error returned by the drive.
567  */
568 ide_startstop_t ide_cdrom_error (ide_drive_t *drive, const char *msg, byte stat)
569 {
570         struct request *rq;
571         byte err;
572
573         err = ide_dump_atapi_status(drive, msg, stat);
574         if (drive == NULL || (rq = HWGROUP(drive)->rq) == NULL)
575                 return ide_stopped;
576         /* retry only "normal" I/O: */
577         if (rq->flags & (REQ_DRIVE_CMD | REQ_DRIVE_TASK)) {
578                 rq->errors = 1;
579                 ide_end_drive_cmd(drive, stat, err);
580                 return ide_stopped;
581         }
582
583         if (stat & BUSY_STAT || ((stat & WRERR_STAT) && !drive->nowerr)) {
584                 /* other bits are useless when BUSY */
585                 rq->errors |= ERROR_RESET;
586         } else {
587                 /* add decoding error stuff */
588         }
589         if (HWIF(drive)->INB(IDE_STATUS_REG) & (BUSY_STAT|DRQ_STAT))
590                 /* force an abort */
591                 HWIF(drive)->OUTB(WIN_IDLEIMMEDIATE,IDE_COMMAND_REG);
592         if (rq->errors >= ERROR_MAX) {
593                 DRIVER(drive)->end_request(drive, 0, 0);
594         } else {
595                 if ((rq->errors & ERROR_RESET) == ERROR_RESET) {
596                         ++rq->errors;
597                         return ide_do_reset(drive);
598                 }
599                 ++rq->errors;
600         }
601         return ide_stopped;
602 }
603
604 ide_startstop_t ide_cdrom_abort (ide_drive_t *drive, const char *msg)
605 {
606         struct request *rq;
607
608         if (drive == NULL || (rq = HWGROUP(drive)->rq) == NULL)
609                 return ide_stopped;
610         /* retry only "normal" I/O: */
611         if (rq->flags & (REQ_DRIVE_CMD | REQ_DRIVE_TASK)) {
612                 rq->errors = 1;
613                 ide_end_drive_cmd(drive, BUSY_STAT, 0);
614                 return ide_stopped;
615         }
616         rq->errors |= ERROR_RESET;
617         DRIVER(drive)->end_request(drive, 0, 0);
618         return ide_stopped;
619 }
620
621 static void cdrom_end_request (ide_drive_t *drive, int uptodate)
622 {
623         struct request *rq = HWGROUP(drive)->rq;
624         int nsectors = rq->hard_cur_sectors;
625
626         if ((rq->flags & REQ_SENSE) && uptodate) {
627                 /*
628                  * For REQ_SENSE, "rq->buffer" points to the original failed
629                  * request
630                  */
631                 struct request *failed = (struct request *) rq->buffer;
632                 struct cdrom_info *info = drive->driver_data;
633                 void *sense = &info->sense_data;
634                 
635                 if (failed && failed->sense) {
636                         sense = failed->sense;
637                         failed->sense_len = rq->sense_len;
638                 }
639
640                 cdrom_analyze_sense_data(drive, failed, sense);
641         }
642
643         if (!rq->current_nr_sectors && blk_fs_request(rq))
644                 uptodate = 1;
645         if (!nsectors)
646                 nsectors = 1;
647
648         ide_end_request(drive, uptodate, nsectors);
649 }
650
651 /* Returns 0 if the request should be continued.
652    Returns 1 if the request was ended. */
653 static int cdrom_decode_status(ide_drive_t *drive, int good_stat, int *stat_ret)
654 {
655         struct request *rq = HWGROUP(drive)->rq;
656         int stat, err, sense_key;
657         
658         /* Check for errors. */
659         stat = HWIF(drive)->INB(IDE_STATUS_REG);
660         if (stat_ret)
661                 *stat_ret = stat;
662
663         if (OK_STAT(stat, good_stat, BAD_R_STAT))
664                 return 0;
665
666         /* Get the IDE error register. */
667         err = HWIF(drive)->INB(IDE_ERROR_REG);
668         sense_key = err >> 4;
669
670         if (rq == NULL) {
671                 printk("%s: missing rq in cdrom_decode_status\n", drive->name);
672                 return 1;
673         }
674
675         if (rq->flags & REQ_SENSE) {
676                 /* We got an error trying to get sense info
677                    from the drive (probably while trying
678                    to recover from a former error).  Just give up. */
679
680                 rq->flags |= REQ_FAILED;
681                 cdrom_end_request(drive, 0);
682                 DRIVER(drive)->error(drive, "request sense failure", stat);
683                 return 1;
684
685         } else if (rq->flags & (REQ_PC | REQ_BLOCK_PC)) {
686                 /* All other functions, except for READ. */
687                 struct completion *wait = NULL;
688
689                 /*
690                  * if we have an error, pass back CHECK_CONDITION as the
691                  * scsi status byte
692                  */
693                 if ((rq->flags & REQ_BLOCK_PC) && !rq->errors)
694                         rq->errors = SAM_STAT_CHECK_CONDITION;
695
696                 /* Check for tray open. */
697                 if (sense_key == NOT_READY) {
698                         cdrom_saw_media_change (drive);
699                 } else if (sense_key == UNIT_ATTENTION) {
700                         /* Check for media change. */
701                         cdrom_saw_media_change (drive);
702                         /*printk("%s: media changed\n",drive->name);*/
703                         return 0;
704                 } else if (!(rq->flags & REQ_QUIET)) {
705                         /* Otherwise, print an error. */
706                         ide_dump_status(drive, "packet command error", stat);
707                 }
708                 
709                 /* Set the error flag and complete the request.
710                    Then, if we have a CHECK CONDITION status,
711                    queue a request sense command.  We must be careful,
712                    though: we don't want the thread in
713                    cdrom_queue_packet_command to wake up until
714                    the request sense has completed.  We do this
715                    by transferring the semaphore from the packet
716                    command request to the request sense request. */
717
718                 rq->flags |= REQ_FAILED;
719                 if ((stat & ERR_STAT) != 0) {
720                         wait = rq->waiting;
721                         rq->waiting = NULL;
722                         if ((rq->flags & REQ_BLOCK_PC) != 0) {
723                                 cdrom_queue_request_sense(drive, wait,
724                                                           rq->sense, rq);
725                                 return 1; /* REQ_BLOCK_PC self-cares */
726                         }
727                 }
728
729                 cdrom_end_request(drive, 0);
730
731                 if ((stat & ERR_STAT) != 0)
732                         cdrom_queue_request_sense(drive, wait, rq->sense, rq);
733         } else if (blk_fs_request(rq)) {
734                 int do_end_request = 0;
735
736                 /* Handle errors from READ and WRITE requests. */
737
738                 if (blk_noretry_request(rq))
739                         do_end_request = 1;
740
741                 if (sense_key == NOT_READY) {
742                         /* Tray open. */
743                         if (rq_data_dir(rq) == READ) {
744                                 cdrom_saw_media_change (drive);
745
746                                 /* Fail the request. */
747                                 printk ("%s: tray open\n", drive->name);
748                                 do_end_request = 1;
749                         } else {
750                                 struct cdrom_info *info = drive->driver_data;
751
752                                 /* allow the drive 5 seconds to recover, some
753                                  * devices will return this error while flushing
754                                  * data from cache */
755                                 if (!rq->errors)
756                                         info->write_timeout = jiffies + ATAPI_WAIT_WRITE_BUSY;
757                                 rq->errors = 1;
758                                 if (time_after(jiffies, info->write_timeout))
759                                         do_end_request = 1;
760                                 else {
761                                         unsigned long flags;
762
763                                         /*
764                                          * take a breather relying on the
765                                          * unplug timer to kick us again
766                                          */
767                                         spin_lock_irqsave(&ide_lock, flags);
768                                         blk_plug_device(drive->queue);
769                                         spin_unlock_irqrestore(&ide_lock,flags);
770                                         return 1;
771                                 }
772                         }
773                 } else if (sense_key == UNIT_ATTENTION) {
774                         /* Media change. */
775                         cdrom_saw_media_change (drive);
776
777                         /* Arrange to retry the request.
778                            But be sure to give up if we've retried
779                            too many times. */
780                         if (++rq->errors > ERROR_MAX)
781                                 do_end_request = 1;
782                 } else if (sense_key == ILLEGAL_REQUEST ||
783                            sense_key == DATA_PROTECT) {
784                         /*
785                          * check if this was a write protected media
786                          */
787                         if (rq_data_dir(rq) == WRITE) {
788                                 printk("ide-cd: media marked write protected\n");
789                                 set_disk_ro(drive->disk, 1);
790                         }
791
792                         /* No point in retrying after an illegal
793                            request or data protect error.*/
794                         ide_dump_status (drive, "command error", stat);
795                         do_end_request = 1;
796                 } else if (sense_key == MEDIUM_ERROR) {
797                         /* No point in re-trying a zillion times on a bad 
798                          * sector...  If we got here the error is not correctable */
799                         ide_dump_status (drive, "media error (bad sector)", stat);
800                         do_end_request = 1;
801                 } else if (sense_key == BLANK_CHECK) {
802                         /* Disk appears blank ?? */
803                         ide_dump_status (drive, "media error (blank)", stat);
804                         do_end_request = 1;
805                 } else if ((err & ~ABRT_ERR) != 0) {
806                         /* Go to the default handler
807                            for other errors. */
808                         DRIVER(drive)->error(drive, "cdrom_decode_status",stat);
809                         return 1;
810                 } else if ((++rq->errors > ERROR_MAX)) {
811                         /* We've racked up too many retries.  Abort. */
812                         do_end_request = 1;
813                 }
814
815                 if (do_end_request)
816                         cdrom_end_request(drive, 0);
817
818                 /* If we got a CHECK_CONDITION status,
819                    queue a request sense command. */
820                 if ((stat & ERR_STAT) != 0)
821                         cdrom_queue_request_sense(drive, NULL, NULL, NULL);
822         } else {
823                 blk_dump_rq_flags(rq, "ide-cd: bad rq");
824                 cdrom_end_request(drive, 0);
825         }
826
827         /* Retry, or handle the next request. */
828         return 1;
829 }
830
831 static int cdrom_timer_expiry(ide_drive_t *drive)
832 {
833         struct request *rq = HWGROUP(drive)->rq;
834         unsigned long wait = 0;
835
836         /*
837          * Some commands are *slow* and normally take a long time to
838          * complete. Usually we can use the ATAPI "disconnect" to bypass
839          * this, but not all commands/drives support that. Let
840          * ide_timer_expiry keep polling us for these.
841          */
842         switch (rq->cmd[0]) {
843                 case GPCMD_BLANK:
844                 case GPCMD_FORMAT_UNIT:
845                 case GPCMD_RESERVE_RZONE_TRACK:
846                 case GPCMD_CLOSE_TRACK:
847                 case GPCMD_FLUSH_CACHE:
848                         wait = ATAPI_WAIT_PC;
849                         break;
850                 default:
851                         if (!(rq->flags & REQ_QUIET))
852                                 printk(KERN_INFO "ide-cd: cmd 0x%x timed out\n", rq->cmd[0]);
853                         wait = 0;
854                         break;
855         }
856         return wait;
857 }
858
859 /* Set up the device registers for transferring a packet command on DEV,
860    expecting to later transfer XFERLEN bytes.  HANDLER is the routine
861    which actually transfers the command to the drive.  If this is a
862    drq_interrupt device, this routine will arrange for HANDLER to be
863    called when the interrupt from the drive arrives.  Otherwise, HANDLER
864    will be called immediately after the drive is prepared for the transfer. */
865
866 static ide_startstop_t cdrom_start_packet_command(ide_drive_t *drive,
867                                                   int xferlen,
868                                                   ide_handler_t *handler)
869 {
870         ide_startstop_t startstop;
871         struct cdrom_info *info = drive->driver_data;
872
873         /* Wait for the controller to be idle. */
874         if (ide_wait_stat(&startstop, drive, 0, BUSY_STAT, WAIT_READY))
875                 return startstop;
876
877         if (info->dma) {
878                 if (info->cmd == READ) {
879                         info->dma = !HWIF(drive)->ide_dma_read(drive);
880                 } else if (info->cmd == WRITE) {
881                         info->dma = !HWIF(drive)->ide_dma_write(drive);
882                 } else {
883                         printk("ide-cd: DMA set, but not allowed\n");
884                 }
885         }
886
887         /* Set up the controller registers. */
888         /* FIXME: for Virtual DMA we must check harder */
889         HWIF(drive)->OUTB(info->dma, IDE_FEATURE_REG);
890         HWIF(drive)->OUTB(0, IDE_IREASON_REG);
891         HWIF(drive)->OUTB(0, IDE_SECTOR_REG);
892
893         HWIF(drive)->OUTB(xferlen & 0xff, IDE_BCOUNTL_REG);
894         HWIF(drive)->OUTB(xferlen >> 8  , IDE_BCOUNTH_REG);
895         if (IDE_CONTROL_REG)
896                 HWIF(drive)->OUTB(drive->ctl, IDE_CONTROL_REG);
897  
898         if (CDROM_CONFIG_FLAGS (drive)->drq_interrupt) {
899                 /* packet command */
900                 ide_execute_command(drive, WIN_PACKETCMD, handler, ATAPI_WAIT_PC, cdrom_timer_expiry);
901                 return ide_started;
902         } else {
903                 /* packet command */
904                 HWIF(drive)->OUTB(WIN_PACKETCMD, IDE_COMMAND_REG);
905                 return (*handler) (drive);
906         }
907 }
908
909 /* Send a packet command to DRIVE described by CMD_BUF and CMD_LEN.
910    The device registers must have already been prepared
911    by cdrom_start_packet_command.
912    HANDLER is the interrupt handler to call when the command completes
913    or there's data ready. */
914 /*
915  * changed 5 parameters to 3 for dvd-ram
916  * struct packet_command *pc; now packet_command_t *pc;
917  */
918 #define ATAPI_MIN_CDB_BYTES 12
919 static ide_startstop_t cdrom_transfer_packet_command (ide_drive_t *drive,
920                                           struct request *rq,
921                                           ide_handler_t *handler)
922 {
923         int cmd_len;
924         struct cdrom_info *info = drive->driver_data;
925         ide_startstop_t startstop;
926
927         if (CDROM_CONFIG_FLAGS(drive)->drq_interrupt) {
928                 /* Here we should have been called after receiving an interrupt
929                    from the device.  DRQ should how be set. */
930
931                 /* Check for errors. */
932                 if (cdrom_decode_status(drive, DRQ_STAT, NULL))
933                         return ide_stopped;
934         } else {
935                 /* Otherwise, we must wait for DRQ to get set. */
936                 if (ide_wait_stat(&startstop, drive, DRQ_STAT,
937                                 BUSY_STAT, WAIT_READY))
938                         return startstop;
939         }
940
941         /* Arm the interrupt handler. */
942         ide_set_handler(drive, handler, rq->timeout, cdrom_timer_expiry);
943
944         /* ATAPI commands get padded out to 12 bytes minimum */
945         cmd_len = COMMAND_SIZE(rq->cmd[0]);
946         if (cmd_len < ATAPI_MIN_CDB_BYTES)
947                 cmd_len = ATAPI_MIN_CDB_BYTES;
948
949         /* Send the command to the device. */
950         HWIF(drive)->atapi_output_bytes(drive, rq->cmd, cmd_len);
951
952         /* Start the DMA if need be */
953         if (info->dma)
954                 (void) HWIF(drive)->ide_dma_begin(drive);
955
956         return ide_started;
957 }
958
959 /****************************************************************************
960  * Block read functions.
961  */
962
963 /*
964  * Buffer up to SECTORS_TO_TRANSFER sectors from the drive in our sector
965  * buffer.  Once the first sector is added, any subsequent sectors are
966  * assumed to be continuous (until the buffer is cleared).  For the first
967  * sector added, SECTOR is its sector number.  (SECTOR is then ignored until
968  * the buffer is cleared.)
969  */
970 static void cdrom_buffer_sectors (ide_drive_t *drive, unsigned long sector,
971                                   int sectors_to_transfer)
972 {
973         struct cdrom_info *info = drive->driver_data;
974
975         /* Number of sectors to read into the buffer. */
976         int sectors_to_buffer = min_t(int, sectors_to_transfer,
977                                      (SECTOR_BUFFER_SIZE >> SECTOR_BITS) -
978                                        info->nsectors_buffered);
979
980         char *dest;
981
982         /* If we couldn't get a buffer, don't try to buffer anything... */
983         if (info->buffer == NULL)
984                 sectors_to_buffer = 0;
985
986         /* If this is the first sector in the buffer, remember its number. */
987         if (info->nsectors_buffered == 0)
988                 info->sector_buffered = sector;
989
990         /* Read the data into the buffer. */
991         dest = info->buffer + info->nsectors_buffered * SECTOR_SIZE;
992         while (sectors_to_buffer > 0) {
993                 HWIF(drive)->atapi_input_bytes(drive, dest, SECTOR_SIZE);
994                 --sectors_to_buffer;
995                 --sectors_to_transfer;
996                 ++info->nsectors_buffered;
997                 dest += SECTOR_SIZE;
998         }
999
1000         /* Throw away any remaining data. */
1001         while (sectors_to_transfer > 0) {
1002                 static char dum[SECTOR_SIZE];
1003                 HWIF(drive)->atapi_input_bytes(drive, dum, sizeof (dum));
1004                 --sectors_to_transfer;
1005         }
1006 }
1007
1008 /*
1009  * Check the contents of the interrupt reason register from the cdrom
1010  * and attempt to recover if there are problems.  Returns  0 if everything's
1011  * ok; nonzero if the request has been terminated.
1012  */
1013 static inline
1014 int cdrom_read_check_ireason (ide_drive_t *drive, int len, int ireason)
1015 {
1016         if (ireason == 2)
1017                 return 0;
1018         else if (ireason == 0) {
1019                 /* Whoops... The drive is expecting to receive data from us! */
1020                 printk("%s: read_intr: Drive wants to transfer data the "
1021                                                 "wrong way!\n", drive->name);
1022
1023                 /* Throw some data at the drive so it doesn't hang
1024                    and quit this request. */
1025                 while (len > 0) {
1026                         int dum = 0;
1027                         HWIF(drive)->atapi_output_bytes(drive, &dum, sizeof (dum));
1028                         len -= sizeof (dum);
1029                 }
1030         } else  if (ireason == 1) {
1031                 /* Some drives (ASUS) seem to tell us that status
1032                  * info is available. just get it and ignore.
1033                  */
1034                 (void) HWIF(drive)->INB(IDE_STATUS_REG);
1035                 return 0;
1036         } else {
1037                 /* Drive wants a command packet, or invalid ireason... */
1038                 printk("%s: read_intr: bad interrupt reason %x\n", drive->name,
1039                                                                 ireason);
1040         }
1041
1042         cdrom_end_request(drive, 0);
1043         return -1;
1044 }
1045
1046 /*
1047  * Interrupt routine.  Called when a read request has completed.
1048  */
1049 static ide_startstop_t cdrom_read_intr (ide_drive_t *drive)
1050 {
1051         int stat;
1052         int ireason, len, sectors_to_transfer, nskip;
1053         struct cdrom_info *info = drive->driver_data;
1054         u8 lowcyl = 0, highcyl = 0;
1055         int dma = info->dma, dma_error = 0;
1056
1057         struct request *rq = HWGROUP(drive)->rq;
1058
1059         /*
1060          * handle dma case
1061          */
1062         if (dma) {
1063                 info->dma = 0;
1064                 if ((dma_error = HWIF(drive)->ide_dma_end(drive)))
1065                         __ide_dma_off(drive);
1066         }
1067
1068         if (cdrom_decode_status(drive, 0, &stat))
1069                 return ide_stopped;
1070
1071         if (dma) {
1072                 if (!dma_error) {
1073                         ide_end_request(drive, 1, rq->nr_sectors);
1074                         return ide_stopped;
1075                 } else
1076                         return DRIVER(drive)->error(drive, "dma error", stat);
1077         }
1078
1079         /* Read the interrupt reason and the transfer length. */
1080         ireason = HWIF(drive)->INB(IDE_IREASON_REG) & 0x3;
1081         lowcyl  = HWIF(drive)->INB(IDE_BCOUNTL_REG);
1082         highcyl = HWIF(drive)->INB(IDE_BCOUNTH_REG);
1083
1084         len = lowcyl + (256 * highcyl);
1085
1086         /* If DRQ is clear, the command has completed. */
1087         if ((stat & DRQ_STAT) == 0) {
1088                 /* If we're not done filling the current buffer, complain.
1089                    Otherwise, complete the command normally. */
1090                 if (rq->current_nr_sectors > 0) {
1091                         printk ("%s: cdrom_read_intr: data underrun (%d blocks)\n",
1092                                 drive->name, rq->current_nr_sectors);
1093                         rq->flags |= REQ_FAILED;
1094                         cdrom_end_request(drive, 0);
1095                 } else
1096                         cdrom_end_request(drive, 1);
1097                 return ide_stopped;
1098         }
1099
1100         /* Check that the drive is expecting to do the same thing we are. */
1101         if (cdrom_read_check_ireason (drive, len, ireason))
1102                 return ide_stopped;
1103
1104         /* Assume that the drive will always provide data in multiples
1105            of at least SECTOR_SIZE, as it gets hairy to keep track
1106            of the transfers otherwise. */
1107         if ((len % SECTOR_SIZE) != 0) {
1108                 printk ("%s: cdrom_read_intr: Bad transfer size %d\n",
1109                         drive->name, len);
1110                 if (CDROM_CONFIG_FLAGS(drive)->limit_nframes)
1111                         printk ("  This drive is not supported by this version of the driver\n");
1112                 else {
1113                         printk ("  Trying to limit transfer sizes\n");
1114                         CDROM_CONFIG_FLAGS(drive)->limit_nframes = 1;
1115                 }
1116                 cdrom_end_request(drive, 0);
1117                 return ide_stopped;
1118         }
1119
1120         /* The number of sectors we need to read from the drive. */
1121         sectors_to_transfer = len / SECTOR_SIZE;
1122
1123         /* First, figure out if we need to bit-bucket
1124            any of the leading sectors. */
1125         nskip = min_t(int, rq->current_nr_sectors - bio_cur_sectors(rq->bio), sectors_to_transfer);
1126
1127         while (nskip > 0) {
1128                 /* We need to throw away a sector. */
1129                 static char dum[SECTOR_SIZE];
1130                 HWIF(drive)->atapi_input_bytes(drive, dum, sizeof (dum));
1131
1132                 --rq->current_nr_sectors;
1133                 --nskip;
1134                 --sectors_to_transfer;
1135         }
1136
1137         /* Now loop while we still have data to read from the drive. */
1138         while (sectors_to_transfer > 0) {
1139                 int this_transfer;
1140
1141                 /* If we've filled the present buffer but there's another
1142                    chained buffer after it, move on. */
1143                 if (rq->current_nr_sectors == 0 && rq->nr_sectors)
1144                         cdrom_end_request(drive, 1);
1145
1146                 /* If the buffers are full, cache the rest of the data in our
1147                    internal buffer. */
1148                 if (rq->current_nr_sectors == 0) {
1149                         cdrom_buffer_sectors(drive, rq->sector, sectors_to_transfer);
1150                         sectors_to_transfer = 0;
1151                 } else {
1152                         /* Transfer data to the buffers.
1153                            Figure out how many sectors we can transfer
1154                            to the current buffer. */
1155                         this_transfer = min_t(int, sectors_to_transfer,
1156                                              rq->current_nr_sectors);
1157
1158                         /* Read this_transfer sectors
1159                            into the current buffer. */
1160                         while (this_transfer > 0) {
1161                                 HWIF(drive)->atapi_input_bytes(drive, rq->buffer, SECTOR_SIZE);
1162                                 rq->buffer += SECTOR_SIZE;
1163                                 --rq->nr_sectors;
1164                                 --rq->current_nr_sectors;
1165                                 ++rq->sector;
1166                                 --this_transfer;
1167                                 --sectors_to_transfer;
1168                         }
1169                 }
1170         }
1171
1172         /* Done moving data!  Wait for another interrupt. */
1173         ide_set_handler(drive, &cdrom_read_intr, ATAPI_WAIT_PC, NULL);
1174         return ide_started;
1175 }
1176
1177 /*
1178  * Try to satisfy some of the current read request from our cached data.
1179  * Returns nonzero if the request has been completed, zero otherwise.
1180  */
1181 static int cdrom_read_from_buffer (ide_drive_t *drive)
1182 {
1183         struct cdrom_info *info = drive->driver_data;
1184         struct request *rq = HWGROUP(drive)->rq;
1185         unsigned short sectors_per_frame;
1186
1187         sectors_per_frame = queue_hardsect_size(drive->queue) >> SECTOR_BITS;
1188
1189         /* Can't do anything if there's no buffer. */
1190         if (info->buffer == NULL) return 0;
1191
1192         /* Loop while this request needs data and the next block is present
1193            in our cache. */
1194         while (rq->nr_sectors > 0 &&
1195                rq->sector >= info->sector_buffered &&
1196                rq->sector < info->sector_buffered + info->nsectors_buffered) {
1197                 if (rq->current_nr_sectors == 0)
1198                         cdrom_end_request(drive, 1);
1199
1200                 memcpy (rq->buffer,
1201                         info->buffer +
1202                         (rq->sector - info->sector_buffered) * SECTOR_SIZE,
1203                         SECTOR_SIZE);
1204                 rq->buffer += SECTOR_SIZE;
1205                 --rq->current_nr_sectors;
1206                 --rq->nr_sectors;
1207                 ++rq->sector;
1208         }
1209
1210         /* If we've satisfied the current request,
1211            terminate it successfully. */
1212         if (rq->nr_sectors == 0) {
1213                 cdrom_end_request(drive, 1);
1214                 return -1;
1215         }
1216
1217         /* Move on to the next buffer if needed. */
1218         if (rq->current_nr_sectors == 0)
1219                 cdrom_end_request(drive, 1);
1220
1221         /* If this condition does not hold, then the kluge i use to
1222            represent the number of sectors to skip at the start of a transfer
1223            will fail.  I think that this will never happen, but let's be
1224            paranoid and check. */
1225         if (rq->current_nr_sectors < bio_cur_sectors(rq->bio) &&
1226             (rq->sector & (sectors_per_frame - 1))) {
1227                 printk("%s: cdrom_read_from_buffer: buffer botch (%ld)\n",
1228                         drive->name, (long)rq->sector);
1229                 cdrom_end_request(drive, 0);
1230                 return -1;
1231         }
1232
1233         return 0;
1234 }
1235
1236 /*
1237  * Routine to send a read packet command to the drive.
1238  * This is usually called directly from cdrom_start_read.
1239  * However, for drq_interrupt devices, it is called from an interrupt
1240  * when the drive is ready to accept the command.
1241  */
1242 static ide_startstop_t cdrom_start_read_continuation (ide_drive_t *drive)
1243 {
1244         struct request *rq = HWGROUP(drive)->rq;
1245         unsigned short sectors_per_frame;
1246         int nskip;
1247
1248         sectors_per_frame = queue_hardsect_size(drive->queue) >> SECTOR_BITS;
1249
1250         /* If the requested sector doesn't start on a cdrom block boundary,
1251            we must adjust the start of the transfer so that it does,
1252            and remember to skip the first few sectors.
1253            If the CURRENT_NR_SECTORS field is larger than the size
1254            of the buffer, it will mean that we're to skip a number
1255            of sectors equal to the amount by which CURRENT_NR_SECTORS
1256            is larger than the buffer size. */
1257         nskip = rq->sector & (sectors_per_frame - 1);
1258         if (nskip > 0) {
1259                 /* Sanity check... */
1260                 if (rq->current_nr_sectors != bio_cur_sectors(rq->bio) &&
1261                         (rq->sector & (sectors_per_frame - 1))) {
1262                         printk ("%s: cdrom_start_read_continuation: buffer botch (%u)\n",
1263                                 drive->name, rq->current_nr_sectors);
1264                         cdrom_end_request(drive, 0);
1265                         return ide_stopped;
1266                 }
1267                 rq->current_nr_sectors += nskip;
1268         }
1269
1270         /* Set up the command */
1271         rq->timeout = ATAPI_WAIT_PC;
1272
1273         /* Send the command to the drive and return. */
1274         return cdrom_transfer_packet_command(drive, rq, &cdrom_read_intr);
1275 }
1276
1277
1278 #define IDECD_SEEK_THRESHOLD    (1000)                  /* 1000 blocks */
1279 #define IDECD_SEEK_TIMER        (5 * WAIT_MIN_SLEEP)    /* 100 ms */
1280 #define IDECD_SEEK_TIMEOUT      (2 * WAIT_CMD)          /* 20 sec */
1281
1282 static ide_startstop_t cdrom_seek_intr (ide_drive_t *drive)
1283 {
1284         struct cdrom_info *info = drive->driver_data;
1285         int stat;
1286         static int retry = 10;
1287
1288         if (cdrom_decode_status(drive, 0, &stat))
1289                 return ide_stopped;
1290         CDROM_CONFIG_FLAGS(drive)->seeking = 1;
1291
1292         if (retry && time_after(jiffies, info->start_seek + IDECD_SEEK_TIMER)) {
1293                 if (--retry == 0) {
1294                         /*
1295                          * this condition is far too common, to bother
1296                          * users about it
1297                          */
1298                         /* printk("%s: disabled DSC seek overlap\n", drive->name);*/ 
1299                         drive->dsc_overlap = 0;
1300                 }
1301         }
1302         return ide_stopped;
1303 }
1304
1305 static ide_startstop_t cdrom_start_seek_continuation (ide_drive_t *drive)
1306 {
1307         struct request *rq = HWGROUP(drive)->rq;
1308         sector_t frame = rq->sector;
1309
1310         sector_div(frame, queue_hardsect_size(drive->queue) >> SECTOR_BITS);
1311
1312         memset(rq->cmd, 0, sizeof(rq->cmd));
1313         rq->cmd[0] = GPCMD_SEEK;
1314         put_unaligned(cpu_to_be32(frame), (unsigned int *) &rq->cmd[2]);
1315
1316         rq->timeout = ATAPI_WAIT_PC;
1317         return cdrom_transfer_packet_command(drive, rq, &cdrom_seek_intr);
1318 }
1319
1320 static ide_startstop_t cdrom_start_seek (ide_drive_t *drive, unsigned int block)
1321 {
1322         struct cdrom_info *info = drive->driver_data;
1323
1324         info->dma = 0;
1325         info->cmd = 0;
1326         info->start_seek = jiffies;
1327         return cdrom_start_packet_command(drive, 0, cdrom_start_seek_continuation);
1328 }
1329
1330 /* Fix up a possibly partially-processed request so that we can
1331    start it over entirely, or even put it back on the request queue. */
1332 static void restore_request (struct request *rq)
1333 {
1334         if (rq->buffer != bio_data(rq->bio)) {
1335                 sector_t n = (rq->buffer - (char *) bio_data(rq->bio)) / SECTOR_SIZE;
1336
1337                 rq->buffer = bio_data(rq->bio);
1338                 rq->nr_sectors += n;
1339                 rq->sector -= n;
1340         }
1341         rq->hard_cur_sectors = rq->current_nr_sectors = bio_cur_sectors(rq->bio);
1342         rq->hard_nr_sectors = rq->nr_sectors;
1343         rq->hard_sector = rq->sector;
1344         rq->q->prep_rq_fn(rq->q, rq);
1345 }
1346
1347 /*
1348  * Start a read request from the CD-ROM.
1349  */
1350 static ide_startstop_t cdrom_start_read (ide_drive_t *drive, unsigned int block)
1351 {
1352         struct cdrom_info *info = drive->driver_data;
1353         struct request *rq = HWGROUP(drive)->rq;
1354         unsigned short sectors_per_frame;
1355
1356         sectors_per_frame = queue_hardsect_size(drive->queue) >> SECTOR_BITS;
1357
1358         /* We may be retrying this request after an error.  Fix up
1359            any weirdness which might be present in the request packet. */
1360         restore_request(rq);
1361
1362         /* Satisfy whatever we can of this request from our cached sector. */
1363         if (cdrom_read_from_buffer(drive))
1364                 return ide_stopped;
1365
1366         blk_attempt_remerge(drive->queue, rq);
1367
1368         /* Clear the local sector buffer. */
1369         info->nsectors_buffered = 0;
1370
1371         /* use dma, if possible. */
1372         info->dma = drive->using_dma;
1373         if ((rq->sector & (sectors_per_frame - 1)) ||
1374             (rq->nr_sectors & (sectors_per_frame - 1)))
1375                 info->dma = 0;
1376
1377         info->cmd = READ;
1378
1379         /* Start sending the read request to the drive. */
1380         return cdrom_start_packet_command(drive, 32768, cdrom_start_read_continuation);
1381 }
1382
1383 /****************************************************************************
1384  * Execute all other packet commands.
1385  */
1386
1387 /* Interrupt routine for packet command completion. */
1388 static ide_startstop_t cdrom_pc_intr (ide_drive_t *drive)
1389 {
1390         int ireason, len, thislen;
1391         struct request *rq = HWGROUP(drive)->rq;
1392         u8 lowcyl = 0, highcyl = 0;
1393         int stat;
1394
1395         /* Check for errors. */
1396         if (cdrom_decode_status(drive, 0, &stat))
1397                 return ide_stopped;
1398
1399         /* Read the interrupt reason and the transfer length. */
1400         ireason = HWIF(drive)->INB(IDE_IREASON_REG);
1401         lowcyl  = HWIF(drive)->INB(IDE_BCOUNTL_REG);
1402         highcyl = HWIF(drive)->INB(IDE_BCOUNTH_REG);
1403
1404         len = lowcyl + (256 * highcyl);
1405
1406         /* If DRQ is clear, the command has completed.
1407            Complain if we still have data left to transfer. */
1408         if ((stat & DRQ_STAT) == 0) {
1409                 /* Some of the trailing request sense fields are optional, and
1410                    some drives don't send them.  Sigh. */
1411                 if (rq->cmd[0] == GPCMD_REQUEST_SENSE &&
1412                     rq->data_len > 0 &&
1413                     rq->data_len <= 5) {
1414                         while (rq->data_len > 0) {
1415                                 *(unsigned char *)rq->data++ = 0;
1416                                 --rq->data_len;
1417                         }
1418                 }
1419
1420                 if (rq->data_len == 0)
1421                         cdrom_end_request(drive, 1);
1422                 else {
1423                         /* Comment this out, because this always happens 
1424                            right after a reset occurs, and it is annoying to 
1425                            always print expected stuff.  */
1426                         /*
1427                         printk ("%s: cdrom_pc_intr: data underrun %d\n",
1428                                 drive->name, pc->buflen);
1429                         */
1430                         rq->flags |= REQ_FAILED;
1431                         cdrom_end_request(drive, 0);
1432                 }
1433                 return ide_stopped;
1434         }
1435
1436         /* Figure out how much data to transfer. */
1437         thislen = rq->data_len;
1438         if (thislen > len) thislen = len;
1439
1440         /* The drive wants to be written to. */
1441         if ((ireason & 3) == 0) {
1442                 if (!rq->data) {
1443                         blk_dump_rq_flags(rq, "cdrom_pc_intr, write");
1444                         goto confused;
1445                 }
1446                 /* Transfer the data. */
1447                 HWIF(drive)->atapi_output_bytes(drive, rq->data, thislen);
1448
1449                 /* If we haven't moved enough data to satisfy the drive,
1450                    add some padding. */
1451                 while (len > thislen) {
1452                         int dum = 0;
1453                         HWIF(drive)->atapi_output_bytes(drive, &dum, sizeof(dum));
1454                         len -= sizeof(dum);
1455                 }
1456
1457                 /* Keep count of how much data we've moved. */
1458                 rq->data += thislen;
1459                 rq->data_len -= thislen;
1460         }
1461
1462         /* Same drill for reading. */
1463         else if ((ireason & 3) == 2) {
1464                 if (!rq->data) {
1465                         blk_dump_rq_flags(rq, "cdrom_pc_intr, write");
1466                         goto confused;
1467                 }
1468                 /* Transfer the data. */
1469                 HWIF(drive)->atapi_input_bytes(drive, rq->data, thislen);
1470
1471                 /* If we haven't moved enough data to satisfy the drive,
1472                    add some padding. */
1473                 while (len > thislen) {
1474                         int dum = 0;
1475                         HWIF(drive)->atapi_input_bytes(drive, &dum, sizeof(dum));
1476                         len -= sizeof(dum);
1477                 }
1478
1479                 /* Keep count of how much data we've moved. */
1480                 rq->data += thislen;
1481                 rq->data_len -= thislen;
1482
1483                 if (rq->flags & REQ_SENSE)
1484                         rq->sense_len += thislen;
1485         } else {
1486 confused:
1487                 printk ("%s: cdrom_pc_intr: The drive "
1488                         "appears confused (ireason = 0x%02x)\n",
1489                         drive->name, ireason);
1490                 rq->flags |= REQ_FAILED;
1491         }
1492
1493         /* Now we wait for another interrupt. */
1494         ide_set_handler(drive, &cdrom_pc_intr, ATAPI_WAIT_PC, cdrom_timer_expiry);
1495         return ide_started;
1496 }
1497
1498 static ide_startstop_t cdrom_do_pc_continuation (ide_drive_t *drive)
1499 {
1500         struct request *rq = HWGROUP(drive)->rq;
1501
1502         if (!rq->timeout)
1503                 rq->timeout = ATAPI_WAIT_PC;
1504
1505         /* Send the command to the drive and return. */
1506         return cdrom_transfer_packet_command(drive, rq, &cdrom_pc_intr);
1507 }
1508
1509
1510 static ide_startstop_t cdrom_do_packet_command (ide_drive_t *drive)
1511 {
1512         int len;
1513         struct request *rq = HWGROUP(drive)->rq;
1514         struct cdrom_info *info = drive->driver_data;
1515
1516         info->dma = 0;
1517         info->cmd = 0;
1518         rq->flags &= ~REQ_FAILED;
1519         len = rq->data_len;
1520
1521         /* Start sending the command to the drive. */
1522         return cdrom_start_packet_command(drive, len, cdrom_do_pc_continuation);
1523 }
1524
1525
1526 /* Sleep for TIME jiffies.
1527    Not to be called from an interrupt handler. */
1528 static
1529 void cdrom_sleep (int time)
1530 {
1531         int sleep = time;
1532
1533         do {
1534                 set_current_state(TASK_INTERRUPTIBLE);
1535                 sleep = schedule_timeout(sleep);
1536         } while (sleep);
1537 }
1538
1539 static
1540 int cdrom_queue_packet_command(ide_drive_t *drive, struct request *rq)
1541 {
1542         struct request_sense sense;
1543         int retries = 10;
1544         unsigned int flags = rq->flags;
1545
1546         if (rq->sense == NULL)
1547                 rq->sense = &sense;
1548
1549         /* Start of retry loop. */
1550         do {
1551                 int error;
1552                 unsigned long time = jiffies;
1553                 rq->flags = flags;
1554
1555                 error = ide_do_drive_cmd(drive, rq, ide_wait);
1556                 time = jiffies - time;
1557
1558                 /* FIXME: we should probably abort/retry or something 
1559                  * in case of failure */
1560                 if (rq->flags & REQ_FAILED) {
1561                         /* The request failed.  Retry if it was due to a unit
1562                            attention status
1563                            (usually means media was changed). */
1564                         struct request_sense *reqbuf = rq->sense;
1565
1566                         if (reqbuf->sense_key == UNIT_ATTENTION)
1567                                 cdrom_saw_media_change(drive);
1568                         else if (reqbuf->sense_key == NOT_READY &&
1569                                  reqbuf->asc == 4 && reqbuf->ascq != 4) {
1570                                 /* The drive is in the process of loading
1571                                    a disk.  Retry, but wait a little to give
1572                                    the drive time to complete the load. */
1573                                 cdrom_sleep(2 * HZ);
1574                         } else {
1575                                 /* Otherwise, don't retry. */
1576                                 retries = 0;
1577                         }
1578                         --retries;
1579                 }
1580
1581                 /* End of retry loop. */
1582         } while ((rq->flags & REQ_FAILED) && retries >= 0);
1583
1584         /* Return an error if the command failed. */
1585         return (rq->flags & REQ_FAILED) ? -EIO : 0;
1586 }
1587
1588 /*
1589  * Write handling
1590  */
1591 static inline int cdrom_write_check_ireason(ide_drive_t *drive, int len, int ireason)
1592 {
1593         /* Two notes about IDE interrupt reason here - 0 means that
1594          * the drive wants to receive data from us, 2 means that
1595          * the drive is expecting to transfer data to us.
1596          */
1597         if (ireason == 0)
1598                 return 0;
1599         else if (ireason == 2) {
1600                 /* Whoops... The drive wants to send data. */
1601                 printk("%s: write_intr: wrong transfer direction!\n",
1602                                                         drive->name);
1603
1604                 while (len > 0) {
1605                         int dum = 0;
1606                         HWIF(drive)->atapi_input_bytes(drive, &dum, sizeof(dum));
1607                         len -= sizeof(dum);
1608                 }
1609         } else {
1610                 /* Drive wants a command packet, or invalid ireason... */
1611                 printk("%s: write_intr: bad interrupt reason %x\n",
1612                                                         drive->name, ireason);
1613         }
1614
1615         cdrom_end_request(drive, 0);
1616         return 1;
1617 }
1618
1619 static void post_transform_command(struct request *req)
1620 {
1621         u8 *c = req->cmd;
1622         char *ibuf;
1623
1624         if (!blk_pc_request(req))
1625                 return;
1626
1627         if (req->bio)
1628                 ibuf = bio_data(req->bio);
1629         else
1630                 ibuf = req->data;
1631
1632         if (!ibuf)
1633                 return;
1634
1635         /*
1636          * set ansi-revision and response data as atapi
1637          */
1638         if (c[0] == GPCMD_INQUIRY) {
1639                 ibuf[2] |= 2;
1640                 ibuf[3] = (ibuf[3] & 0xf0) | 2;
1641         }
1642 }
1643
1644 typedef void (xfer_func_t)(ide_drive_t *, void *, u32);
1645
1646 /*
1647  * best way to deal with dma that is not sector aligned right now... note
1648  * that in this path we are not using ->data or ->buffer at all. this irs
1649  * can replace cdrom_pc_intr, cdrom_read_intr, and cdrom_write_intr in the
1650  * future.
1651  */
1652 static ide_startstop_t cdrom_newpc_intr(ide_drive_t *drive)
1653 {
1654         struct cdrom_info *info = drive->driver_data;
1655         struct request *rq = HWGROUP(drive)->rq;
1656         int dma_error, dma, stat, ireason, len, thislen;
1657         u8 lowcyl, highcyl;
1658         xfer_func_t *xferfunc;
1659         unsigned long flags;
1660
1661         /* Check for errors. */
1662         dma_error = 0;
1663         dma = info->dma;
1664         if (dma) {
1665                 info->dma = 0;
1666                 dma_error = HWIF(drive)->ide_dma_end(drive);
1667         }
1668
1669         if (cdrom_decode_status(drive, 0, &stat)) {
1670                 if ((stat & ERR_STAT) != 0) {
1671                         end_that_request_chunk(rq, 0, rq->data_len);
1672                         goto end_request; /* purge the whole thing... */
1673                 }
1674                 end_that_request_chunk(rq, 1, rq->data_len);
1675                 return ide_stopped;
1676         }
1677
1678         /*
1679          * using dma, transfer is complete now
1680          */
1681         if (dma) {
1682                 if (dma_error) {
1683                         printk("ide-cd: dma error\n");
1684                         __ide_dma_off(drive);
1685                         return DRIVER(drive)->error(drive, "dma error", stat);
1686                 }
1687
1688                 end_that_request_chunk(rq, 1, rq->data_len);
1689                 rq->data_len = 0;
1690                 goto end_request;
1691         }
1692
1693         /*
1694          * ok we fall to pio :/
1695          */
1696         ireason = HWIF(drive)->INB(IDE_IREASON_REG) & 0x3;
1697         lowcyl  = HWIF(drive)->INB(IDE_BCOUNTL_REG);
1698         highcyl = HWIF(drive)->INB(IDE_BCOUNTH_REG);
1699
1700         len = lowcyl + (256 * highcyl);
1701         thislen = rq->data_len;
1702         if (thislen > len)
1703                 thislen = len;
1704
1705         /*
1706          * If DRQ is clear, the command has completed.
1707          */
1708         if ((stat & DRQ_STAT) == 0)
1709                 goto end_request;
1710
1711         /*
1712          * check which way to transfer data
1713          */
1714         if (rq_data_dir(rq) == WRITE) {
1715                 /*
1716                  * write to drive
1717                  */
1718                 if (cdrom_write_check_ireason(drive, len, ireason))
1719                         return ide_stopped;
1720
1721                 xferfunc = HWIF(drive)->atapi_output_bytes;
1722         } else  {
1723                 /*
1724                  * read from drive
1725                  */
1726                 if (cdrom_read_check_ireason(drive, len, ireason))
1727                         return ide_stopped;
1728
1729                 xferfunc = HWIF(drive)->atapi_input_bytes;
1730         }
1731
1732         /*
1733          * transfer data
1734          */
1735         while (thislen > 0) {
1736                 int blen = blen = rq->data_len;
1737                 char *ptr = rq->data;
1738
1739                 /*
1740                  * bio backed?
1741                  */
1742                 if (rq->bio) {
1743                         ptr = bio_data(rq->bio);
1744                         blen = bio_iovec(rq->bio)->bv_len;
1745                 }
1746
1747                 if (!ptr) {
1748                         printk("%s: confused, missing data\n", drive->name);
1749                         break;
1750                 }
1751
1752                 if (blen > thislen)
1753                         blen = thislen;
1754
1755                 xferfunc(drive, ptr, blen);
1756
1757                 thislen -= blen;
1758                 len -= blen;
1759                 rq->data_len -= blen;
1760
1761                 if (rq->bio)
1762                         end_that_request_chunk(rq, 1, blen);
1763                 else
1764                         rq->data += blen;
1765         }
1766
1767         /*
1768          * pad, if necessary
1769          */
1770         if (len > 0) {
1771                 while (len > 0) {
1772                         int pad = 0;
1773
1774                         xferfunc(drive, &pad, sizeof(pad));
1775                         len -= sizeof(pad);
1776                 }
1777         }
1778
1779         if (HWGROUP(drive)->handler != NULL)
1780                 BUG();
1781
1782         ide_set_handler(drive, cdrom_newpc_intr, rq->timeout, NULL);
1783         return ide_started;
1784
1785 end_request:
1786         if (!rq->data_len)
1787                 post_transform_command(rq);
1788
1789         spin_lock_irqsave(&ide_lock, flags);
1790         blkdev_dequeue_request(rq);
1791         end_that_request_last(rq);
1792         HWGROUP(drive)->rq = NULL;
1793         spin_unlock_irqrestore(&ide_lock, flags);
1794         return ide_stopped;
1795 }
1796
1797 static ide_startstop_t cdrom_write_intr(ide_drive_t *drive)
1798 {
1799         int stat, ireason, len, sectors_to_transfer, uptodate;
1800         struct cdrom_info *info = drive->driver_data;
1801         int dma_error = 0, dma = info->dma;
1802         u8 lowcyl = 0, highcyl = 0;
1803
1804         struct request *rq = HWGROUP(drive)->rq;
1805
1806         /* Check for errors. */
1807         if (dma) {
1808                 info->dma = 0;
1809                 if ((dma_error = HWIF(drive)->ide_dma_end(drive))) {
1810                         printk("ide-cd: write dma error\n");
1811                         __ide_dma_off(drive);
1812                 }
1813         }
1814
1815         if (cdrom_decode_status(drive, 0, &stat))
1816                 return ide_stopped;
1817
1818         /*
1819          * using dma, transfer is complete now
1820          */
1821         if (dma) {
1822                 if (dma_error)
1823                         return DRIVER(drive)->error(drive, "dma error", stat);
1824
1825                 ide_end_request(drive, 1, rq->nr_sectors);
1826                 return ide_stopped;
1827         }
1828
1829         /* Read the interrupt reason and the transfer length. */
1830         ireason = HWIF(drive)->INB(IDE_IREASON_REG);
1831         lowcyl  = HWIF(drive)->INB(IDE_BCOUNTL_REG);
1832         highcyl = HWIF(drive)->INB(IDE_BCOUNTH_REG);
1833
1834         len = lowcyl + (256 * highcyl);
1835
1836         /* If DRQ is clear, the command has completed. */
1837         if ((stat & DRQ_STAT) == 0) {
1838                 /* If we're not done writing, complain.
1839                  * Otherwise, complete the command normally.
1840                  */
1841                 uptodate = 1;
1842                 if (rq->current_nr_sectors > 0) {
1843                         printk("%s: write_intr: data underrun (%d blocks)\n",
1844                         drive->name, rq->current_nr_sectors);
1845                         uptodate = 0;
1846                 }
1847                 cdrom_end_request(drive, uptodate);
1848                 return ide_stopped;
1849         }
1850
1851         /* Check that the drive is expecting to do the same thing we are. */
1852         if (cdrom_write_check_ireason(drive, len, ireason))
1853                 return ide_stopped;
1854
1855         sectors_to_transfer = len / SECTOR_SIZE;
1856
1857         /*
1858          * now loop and write out the data
1859          */
1860         while (sectors_to_transfer > 0) {
1861                 int this_transfer;
1862
1863                 if (!rq->current_nr_sectors) {
1864                         printk("ide-cd: write_intr: oops\n");
1865                         break;
1866                 }
1867
1868                 /*
1869                  * Figure out how many sectors we can transfer
1870                  */
1871                 this_transfer = min_t(int, sectors_to_transfer, rq->current_nr_sectors);
1872
1873                 while (this_transfer > 0) {
1874                         HWIF(drive)->atapi_output_bytes(drive, rq->buffer, SECTOR_SIZE);
1875                         rq->buffer += SECTOR_SIZE;
1876                         --rq->nr_sectors;
1877                         --rq->current_nr_sectors;
1878                         ++rq->sector;
1879                         --this_transfer;
1880                         --sectors_to_transfer;
1881                 }
1882
1883                 /*
1884                  * current buffer complete, move on
1885                  */
1886                 if (rq->current_nr_sectors == 0 && rq->nr_sectors)
1887                         cdrom_end_request(drive, 1);
1888         }
1889
1890         /* re-arm handler */
1891         ide_set_handler(drive, &cdrom_write_intr, ATAPI_WAIT_PC, NULL);
1892         return ide_started;
1893 }
1894
1895 static ide_startstop_t cdrom_start_write_cont(ide_drive_t *drive)
1896 {
1897         struct request *rq = HWGROUP(drive)->rq;
1898
1899 #if 0   /* the immediate bit */
1900         rq->cmd[1] = 1 << 3;
1901 #endif
1902         rq->timeout = ATAPI_WAIT_PC;
1903
1904         return cdrom_transfer_packet_command(drive, rq, cdrom_write_intr);
1905 }
1906
1907 static ide_startstop_t cdrom_start_write(ide_drive_t *drive, struct request *rq)
1908 {
1909         struct cdrom_info *info = drive->driver_data;
1910         struct gendisk *g = drive->disk;
1911         unsigned short sectors_per_frame = queue_hardsect_size(drive->queue) >> SECTOR_BITS;
1912
1913         /*
1914          * writes *must* be hardware frame aligned
1915          */
1916         if ((rq->nr_sectors & (sectors_per_frame - 1)) ||
1917             (rq->sector & (sectors_per_frame - 1))) {
1918                 cdrom_end_request(drive, 0);
1919                 return ide_stopped;
1920         }
1921
1922         /*
1923          * disk has become write protected
1924          */
1925         if (g->policy) {
1926                 cdrom_end_request(drive, 0);
1927                 return ide_stopped;
1928         }
1929
1930         /*
1931          * for dvd-ram and such media, it's a really big deal to get
1932          * big writes all the time. so scour the queue and attempt to
1933          * remerge requests, often the plugging will not have had time
1934          * to do this properly
1935          */
1936         blk_attempt_remerge(drive->queue, rq);
1937
1938         info->nsectors_buffered = 0;
1939
1940         /* use dma, if possible. we don't need to check more, since we
1941          * know that the transfer is always (at least!) frame aligned */
1942         info->dma = drive->using_dma ? 1 : 0;
1943         info->cmd = WRITE;
1944
1945         /* Start sending the write request to the drive. */
1946         return cdrom_start_packet_command(drive, 32768, cdrom_start_write_cont);
1947 }
1948
1949 static ide_startstop_t cdrom_do_newpc_cont(ide_drive_t *drive)
1950 {
1951         struct request *rq = HWGROUP(drive)->rq;
1952
1953         if (!rq->timeout)
1954                 rq->timeout = ATAPI_WAIT_PC;
1955
1956         return cdrom_transfer_packet_command(drive, rq, cdrom_newpc_intr);
1957 }
1958
1959 static ide_startstop_t cdrom_do_block_pc(ide_drive_t *drive, struct request *rq)
1960 {
1961         struct cdrom_info *info = drive->driver_data;
1962
1963         rq->flags |= REQ_QUIET;
1964
1965         info->dma = 0;
1966         info->cmd = 0;
1967
1968         /*
1969          * sg request
1970          */
1971         if (rq->bio) {
1972                 if (rq->data_len & 3) {
1973                         printk("%s: block pc not aligned, len=%d\n", drive->name, rq->data_len);
1974                         cdrom_end_request(drive, 0);
1975                         return ide_stopped;
1976                 }
1977                 info->dma = drive->using_dma;
1978                 info->cmd = rq_data_dir(rq);
1979         }
1980
1981         /* Start sending the command to the drive. */
1982         return cdrom_start_packet_command(drive, rq->data_len, cdrom_do_newpc_cont);
1983 }
1984
1985 /****************************************************************************
1986  * cdrom driver request routine.
1987  */
1988 static ide_startstop_t
1989 ide_do_rw_cdrom (ide_drive_t *drive, struct request *rq, sector_t block)
1990 {
1991         ide_startstop_t action;
1992         struct cdrom_info *info = drive->driver_data;
1993
1994         if (blk_fs_request(rq)) {
1995                 if (CDROM_CONFIG_FLAGS(drive)->seeking) {
1996                         unsigned long elapsed = jiffies - info->start_seek;
1997                         int stat = HWIF(drive)->INB(IDE_STATUS_REG);
1998
1999                         if ((stat & SEEK_STAT) != SEEK_STAT) {
2000                                 if (elapsed < IDECD_SEEK_TIMEOUT) {
2001                                         ide_stall_queue(drive, IDECD_SEEK_TIMER);
2002                                         return ide_stopped;
2003                                 }
2004                                 printk ("%s: DSC timeout\n", drive->name);
2005                         }
2006                         CDROM_CONFIG_FLAGS(drive)->seeking = 0;
2007                 }
2008                 if (IDE_LARGE_SEEK(info->last_block, block, IDECD_SEEK_THRESHOLD) && drive->dsc_overlap) {
2009                         action = cdrom_start_seek(drive, block);
2010                 } else {
2011                         if (rq_data_dir(rq) == READ)
2012                                 action = cdrom_start_read(drive, block);
2013                         else
2014                                 action = cdrom_start_write(drive, rq);
2015                 }
2016                 info->last_block = block;
2017                 return action;
2018         } else if (rq->flags & (REQ_PC | REQ_SENSE)) {
2019                 return cdrom_do_packet_command(drive);
2020         } else if (rq->flags & REQ_BLOCK_PC) {
2021                 return cdrom_do_block_pc(drive, rq);
2022         } else if (rq->flags & REQ_SPECIAL) {
2023                 /*
2024                  * right now this can only be a reset...
2025                  */
2026                 cdrom_end_request(drive, 1);
2027                 return ide_stopped;
2028         }
2029
2030         blk_dump_rq_flags(rq, "ide-cd bad flags");
2031         cdrom_end_request(drive, 0);
2032         return ide_stopped;
2033 }
2034
2035
2036
2037 /****************************************************************************
2038  * Ioctl handling.
2039  *
2040  * Routines which queue packet commands take as a final argument a pointer
2041  * to a request_sense struct.  If execution of the command results
2042  * in an error with a CHECK CONDITION status, this structure will be filled
2043  * with the results of the subsequent request sense command.  The pointer
2044  * can also be NULL, in which case no sense information is returned.
2045  */
2046
2047 #if ! STANDARD_ATAPI
2048 static inline
2049 int bin2bcd (int x)
2050 {
2051         return (x%10) | ((x/10) << 4);
2052 }
2053
2054
2055 static inline
2056 int bcd2bin (int x)
2057 {
2058         return (x >> 4) * 10 + (x & 0x0f);
2059 }
2060
2061 static
2062 void msf_from_bcd (struct atapi_msf *msf)
2063 {
2064         msf->minute = bcd2bin (msf->minute);
2065         msf->second = bcd2bin (msf->second);
2066         msf->frame  = bcd2bin (msf->frame);
2067 }
2068
2069 #endif /* not STANDARD_ATAPI */
2070
2071
2072 static inline
2073 void lba_to_msf (int lba, byte *m, byte *s, byte *f)
2074 {
2075         lba += CD_MSF_OFFSET;
2076         lba &= 0xffffff;  /* negative lbas use only 24 bits */
2077         *m = lba / (CD_SECS * CD_FRAMES);
2078         lba %= (CD_SECS * CD_FRAMES);
2079         *s = lba / CD_FRAMES;
2080         *f = lba % CD_FRAMES;
2081 }
2082
2083
2084 static inline
2085 int msf_to_lba (byte m, byte s, byte f)
2086 {
2087         return (((m * CD_SECS) + s) * CD_FRAMES + f) - CD_MSF_OFFSET;
2088 }
2089
2090 static int cdrom_check_status(ide_drive_t *drive, struct request_sense *sense)
2091 {
2092         struct request req;
2093         struct cdrom_info *info = drive->driver_data;
2094         struct cdrom_device_info *cdi = &info->devinfo;
2095
2096         cdrom_prepare_request(&req);
2097
2098         req.sense = sense;
2099         req.cmd[0] = GPCMD_TEST_UNIT_READY;
2100         req.flags |= REQ_QUIET;
2101
2102 #if ! STANDARD_ATAPI
2103         /* the Sanyo 3 CD changer uses byte 7 of TEST_UNIT_READY to 
2104            switch CDs instead of supporting the LOAD_UNLOAD opcode   */
2105
2106         req.cmd[7] = cdi->sanyo_slot % 3;
2107 #endif /* not STANDARD_ATAPI */
2108
2109         return cdrom_queue_packet_command(drive, &req);
2110 }
2111
2112
2113 /* Lock the door if LOCKFLAG is nonzero; unlock it otherwise. */
2114 static int
2115 cdrom_lockdoor(ide_drive_t *drive, int lockflag, struct request_sense *sense)
2116 {
2117         struct request_sense my_sense;
2118         struct request req;
2119         int stat;
2120
2121         if (sense == NULL)
2122                 sense = &my_sense;
2123
2124         /* If the drive cannot lock the door, just pretend. */
2125         if (CDROM_CONFIG_FLAGS(drive)->no_doorlock) {
2126                 stat = 0;
2127         } else {
2128                 cdrom_prepare_request(&req);
2129                 req.sense = sense;
2130                 req.cmd[0] = GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL;
2131                 req.cmd[4] = lockflag ? 1 : 0;
2132                 stat = cdrom_queue_packet_command(drive, &req);
2133         }
2134
2135         /* If we got an illegal field error, the drive
2136            probably cannot lock the door. */
2137         if (stat != 0 &&
2138             sense->sense_key == ILLEGAL_REQUEST &&
2139             (sense->asc == 0x24 || sense->asc == 0x20)) {
2140                 printk ("%s: door locking not supported\n",
2141                         drive->name);
2142                 CDROM_CONFIG_FLAGS(drive)->no_doorlock = 1;
2143                 stat = 0;
2144         }
2145         
2146         /* no medium, that's alright. */
2147         if (stat != 0 && sense->sense_key == NOT_READY && sense->asc == 0x3a)
2148                 stat = 0;
2149
2150         if (stat == 0)
2151                 CDROM_STATE_FLAGS(drive)->door_locked = lockflag;
2152
2153         return stat;
2154 }
2155
2156
2157 /* Eject the disk if EJECTFLAG is 0.
2158    If EJECTFLAG is 1, try to reload the disk. */
2159 static int cdrom_eject(ide_drive_t *drive, int ejectflag,
2160                        struct request_sense *sense)
2161 {
2162         struct request req;
2163         char loej = 0x02;
2164
2165         if (CDROM_CONFIG_FLAGS(drive)->no_eject && !ejectflag)
2166                 return -EDRIVE_CANT_DO_THIS;
2167         
2168         /* reload fails on some drives, if the tray is locked */
2169         if (CDROM_STATE_FLAGS(drive)->door_locked && ejectflag)
2170                 return 0;
2171
2172         cdrom_prepare_request(&req);
2173
2174         /* only tell drive to close tray if open, if it can do that */
2175         if (ejectflag && !CDROM_CONFIG_FLAGS(drive)->close_tray)
2176                 loej = 0;
2177
2178         req.sense = sense;
2179         req.cmd[0] = GPCMD_START_STOP_UNIT;
2180         req.cmd[4] = loej | (ejectflag != 0);
2181         return cdrom_queue_packet_command(drive, &req);
2182 }
2183
2184 static int cdrom_read_capacity(ide_drive_t *drive, unsigned long *capacity,
2185                                unsigned long *sectors_per_frame,
2186                                struct request_sense *sense)
2187 {
2188         struct {
2189                 __u32 lba;
2190                 __u32 blocklen;
2191         } capbuf;
2192
2193         int stat;
2194         struct request req;
2195
2196         cdrom_prepare_request(&req);
2197
2198         req.sense = sense;
2199         req.cmd[0] = GPCMD_READ_CDVD_CAPACITY;
2200         req.data = (char *)&capbuf;
2201         req.data_len = sizeof(capbuf);
2202
2203         stat = cdrom_queue_packet_command(drive, &req);
2204         if (stat == 0) {
2205                 *capacity = 1 + be32_to_cpu(capbuf.lba);
2206                 *sectors_per_frame =
2207                         be32_to_cpu(capbuf.blocklen) >> SECTOR_BITS;
2208         }
2209
2210         return stat;
2211 }
2212
2213 static int cdrom_read_tocentry(ide_drive_t *drive, int trackno, int msf_flag,
2214                                 int format, char *buf, int buflen,
2215                                 struct request_sense *sense)
2216 {
2217         struct request req;
2218
2219         cdrom_prepare_request(&req);
2220
2221         req.sense = sense;
2222         req.data =  buf;
2223         req.data_len = buflen;
2224         req.flags |= REQ_QUIET;
2225         req.cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
2226         req.cmd[6] = trackno;
2227         req.cmd[7] = (buflen >> 8);
2228         req.cmd[8] = (buflen & 0xff);
2229         req.cmd[9] = (format << 6);
2230
2231         if (msf_flag)
2232                 req.cmd[1] = 2;
2233
2234         return cdrom_queue_packet_command(drive, &req);
2235 }
2236
2237
2238 /* Try to read the entire TOC for the disk into our internal buffer. */
2239 static int cdrom_read_toc(ide_drive_t *drive, struct request_sense *sense)
2240 {
2241         int stat, ntracks, i;
2242         struct cdrom_info *info = drive->driver_data;
2243         struct cdrom_device_info *cdi = &info->devinfo;
2244         struct atapi_toc *toc = info->toc;
2245         struct {
2246                 struct atapi_toc_header hdr;
2247                 struct atapi_toc_entry  ent;
2248         } ms_tmp;
2249         long last_written;
2250         unsigned long sectors_per_frame = SECTORS_PER_FRAME;
2251
2252         if (toc == NULL) {
2253                 /* Try to allocate space. */
2254                 toc = (struct atapi_toc *) kmalloc (sizeof (struct atapi_toc),
2255                                                     GFP_KERNEL);
2256                 info->toc = toc;
2257                 if (toc == NULL) {
2258                         printk ("%s: No cdrom TOC buffer!\n", drive->name);
2259                         return -ENOMEM;
2260                 }
2261         }
2262
2263         /* Check to see if the existing data is still valid.
2264            If it is, just return. */
2265         (void) cdrom_check_status(drive, sense);
2266
2267         if (CDROM_STATE_FLAGS(drive)->toc_valid)
2268                 return 0;
2269
2270         /* Try to get the total cdrom capacity and sector size. */
2271         stat = cdrom_read_capacity(drive, &toc->capacity, &sectors_per_frame,
2272                                    sense);
2273         if (stat)
2274                 toc->capacity = 0x1fffff;
2275
2276         set_capacity(drive->disk, toc->capacity * sectors_per_frame);
2277         blk_queue_hardsect_size(drive->queue,
2278                                 sectors_per_frame << SECTOR_BITS);
2279
2280         /* First read just the header, so we know how long the TOC is. */
2281         stat = cdrom_read_tocentry(drive, 0, 1, 0, (char *) &toc->hdr,
2282                                     sizeof(struct atapi_toc_header), sense);
2283         if (stat) return stat;
2284
2285 #if ! STANDARD_ATAPI
2286         if (CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd) {
2287                 toc->hdr.first_track = bcd2bin(toc->hdr.first_track);
2288                 toc->hdr.last_track  = bcd2bin(toc->hdr.last_track);
2289         }
2290 #endif  /* not STANDARD_ATAPI */
2291
2292         ntracks = toc->hdr.last_track - toc->hdr.first_track + 1;
2293         if (ntracks <= 0)
2294                 return -EIO;
2295         if (ntracks > MAX_TRACKS)
2296                 ntracks = MAX_TRACKS;
2297
2298         /* Now read the whole schmeer. */
2299         stat = cdrom_read_tocentry(drive, toc->hdr.first_track, 1, 0,
2300                                   (char *)&toc->hdr,
2301                                    sizeof(struct atapi_toc_header) +
2302                                    (ntracks + 1) *
2303                                    sizeof(struct atapi_toc_entry), sense);
2304
2305         if (stat && toc->hdr.first_track > 1) {
2306                 /* Cds with CDI tracks only don't have any TOC entries,
2307                    despite of this the returned values are
2308                    first_track == last_track = number of CDI tracks + 1,
2309                    so that this case is indistinguishable from the same
2310                    layout plus an additional audio track.
2311                    If we get an error for the regular case, we assume
2312                    a CDI without additional audio tracks. In this case
2313                    the readable TOC is empty (CDI tracks are not included)
2314                    and only holds the Leadout entry. Heiko Eißfeldt */
2315                 ntracks = 0;
2316                 stat = cdrom_read_tocentry(drive, CDROM_LEADOUT, 1, 0,
2317                                            (char *)&toc->hdr,
2318                                            sizeof(struct atapi_toc_header) +
2319                                            (ntracks + 1) *
2320                                            sizeof(struct atapi_toc_entry),
2321                                            sense);
2322                 if (stat) {
2323                         return stat;
2324                 }
2325 #if ! STANDARD_ATAPI
2326                 if (CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd) {
2327                         toc->hdr.first_track = bin2bcd(CDROM_LEADOUT);
2328                         toc->hdr.last_track = bin2bcd(CDROM_LEADOUT);
2329                 } else
2330 #endif  /* not STANDARD_ATAPI */
2331                 {
2332                         toc->hdr.first_track = CDROM_LEADOUT;
2333                         toc->hdr.last_track = CDROM_LEADOUT;
2334                 }
2335         }
2336
2337         if (stat)
2338                 return stat;
2339
2340         toc->hdr.toc_length = ntohs (toc->hdr.toc_length);
2341
2342 #if ! STANDARD_ATAPI
2343         if (CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd) {
2344                 toc->hdr.first_track = bcd2bin(toc->hdr.first_track);
2345                 toc->hdr.last_track  = bcd2bin(toc->hdr.last_track);
2346         }
2347 #endif  /* not STANDARD_ATAPI */
2348
2349         for (i=0; i<=ntracks; i++) {
2350 #if ! STANDARD_ATAPI
2351                 if (CDROM_CONFIG_FLAGS(drive)->tocaddr_as_bcd) {
2352                         if (CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd)
2353                                 toc->ent[i].track = bcd2bin(toc->ent[i].track);
2354                         msf_from_bcd(&toc->ent[i].addr.msf);
2355                 }
2356 #endif  /* not STANDARD_ATAPI */
2357                 toc->ent[i].addr.lba = msf_to_lba (toc->ent[i].addr.msf.minute,
2358                                                    toc->ent[i].addr.msf.second,
2359                                                    toc->ent[i].addr.msf.frame);
2360         }
2361
2362         /* Read the multisession information. */
2363         if (toc->hdr.first_track != CDROM_LEADOUT) {
2364                 /* Read the multisession information. */
2365                 stat = cdrom_read_tocentry(drive, 0, 1, 1, (char *)&ms_tmp,
2366                                            sizeof(ms_tmp), sense);
2367                 if (stat) return stat;
2368         } else {
2369                 ms_tmp.ent.addr.msf.minute = 0;
2370                 ms_tmp.ent.addr.msf.second = 2;
2371                 ms_tmp.ent.addr.msf.frame  = 0;
2372                 ms_tmp.hdr.first_track = ms_tmp.hdr.last_track = CDROM_LEADOUT;
2373         }
2374
2375 #if ! STANDARD_ATAPI
2376         if (CDROM_CONFIG_FLAGS(drive)->tocaddr_as_bcd)
2377                 msf_from_bcd (&ms_tmp.ent.addr.msf);
2378 #endif  /* not STANDARD_ATAPI */
2379
2380         toc->last_session_lba = msf_to_lba (ms_tmp.ent.addr.msf.minute,
2381                                             ms_tmp.ent.addr.msf.second,
2382                                             ms_tmp.ent.addr.msf.frame);
2383
2384         toc->xa_flag = (ms_tmp.hdr.first_track != ms_tmp.hdr.last_track);
2385
2386         /* Now try to get the total cdrom capacity. */
2387         stat = cdrom_get_last_written(cdi, &last_written);
2388         if (!stat && (last_written > toc->capacity)) {
2389                 toc->capacity = last_written;
2390                 set_capacity(drive->disk, toc->capacity * sectors_per_frame);
2391         }
2392
2393         /* Remember that we've read this stuff. */
2394         CDROM_STATE_FLAGS(drive)->toc_valid = 1;
2395
2396         return 0;
2397 }
2398
2399
2400 static int cdrom_read_subchannel(ide_drive_t *drive, int format, char *buf,
2401                                  int buflen, struct request_sense *sense)
2402 {
2403         struct request req;
2404
2405         cdrom_prepare_request(&req);
2406
2407         req.sense = sense;
2408         req.data = buf;
2409         req.data_len = buflen;
2410         req.cmd[0] = GPCMD_READ_SUBCHANNEL;
2411         req.cmd[1] = 2;     /* MSF addressing */
2412         req.cmd[2] = 0x40;  /* request subQ data */
2413         req.cmd[3] = format;
2414         req.cmd[7] = (buflen >> 8);
2415         req.cmd[8] = (buflen & 0xff);
2416         return cdrom_queue_packet_command(drive, &req);
2417 }
2418
2419 /* ATAPI cdrom drives are free to select the speed you request or any slower
2420    rate :-( Requesting too fast a speed will _not_ produce an error. */
2421 static int cdrom_select_speed(ide_drive_t *drive, int speed,
2422                               struct request_sense *sense)
2423 {
2424         struct request req;
2425         cdrom_prepare_request(&req);
2426
2427         req.sense = sense;
2428         if (speed == 0)
2429                 speed = 0xffff; /* set to max */
2430         else
2431                 speed *= 177;   /* Nx to kbytes/s */
2432
2433         req.cmd[0] = GPCMD_SET_SPEED;
2434         /* Read Drive speed in kbytes/second MSB */
2435         req.cmd[2] = (speed >> 8) & 0xff;       
2436         /* Read Drive speed in kbytes/second LSB */
2437         req.cmd[3] = speed & 0xff;
2438         if (CDROM_CONFIG_FLAGS(drive)->cd_r ||
2439             CDROM_CONFIG_FLAGS(drive)->cd_rw ||
2440             CDROM_CONFIG_FLAGS(drive)->dvd_r) {
2441                 /* Write Drive speed in kbytes/second MSB */
2442                 req.cmd[4] = (speed >> 8) & 0xff;
2443                 /* Write Drive speed in kbytes/second LSB */
2444                 req.cmd[5] = speed & 0xff;
2445        }
2446
2447         return cdrom_queue_packet_command(drive, &req);
2448 }
2449
2450 static int cdrom_play_audio(ide_drive_t *drive, int lba_start, int lba_end)
2451 {
2452         struct request_sense sense;
2453         struct request req;
2454
2455         cdrom_prepare_request(&req);
2456
2457         req.sense = &sense;
2458         req.cmd[0] = GPCMD_PLAY_AUDIO_MSF;
2459         lba_to_msf(lba_start, &req.cmd[3], &req.cmd[4], &req.cmd[5]);
2460         lba_to_msf(lba_end-1, &req.cmd[6], &req.cmd[7], &req.cmd[8]);
2461
2462         return cdrom_queue_packet_command(drive, &req);
2463 }
2464
2465 static int cdrom_get_toc_entry(ide_drive_t *drive, int track,
2466                                 struct atapi_toc_entry **ent)
2467 {
2468         struct cdrom_info *info = drive->driver_data;
2469         struct atapi_toc *toc = info->toc;
2470         int ntracks;
2471
2472         /*
2473          * don't serve cached data, if the toc isn't valid
2474          */
2475         if (!CDROM_STATE_FLAGS(drive)->toc_valid)
2476                 return -EINVAL;
2477
2478         /* Check validity of requested track number. */
2479         ntracks = toc->hdr.last_track - toc->hdr.first_track + 1;
2480         if (toc->hdr.first_track == CDROM_LEADOUT) ntracks = 0;
2481         if (track == CDROM_LEADOUT)
2482                 *ent = &toc->ent[ntracks];
2483         else if (track < toc->hdr.first_track ||
2484                  track > toc->hdr.last_track)
2485                 return -EINVAL;
2486         else
2487                 *ent = &toc->ent[track - toc->hdr.first_track];
2488
2489         return 0;
2490 }
2491
2492 /* the generic packet interface to cdrom.c */
2493 static int ide_cdrom_packet(struct cdrom_device_info *cdi,
2494                             struct cdrom_generic_command *cgc)
2495 {
2496         struct request req;
2497         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2498
2499         if (cgc->timeout <= 0)
2500                 cgc->timeout = ATAPI_WAIT_PC;
2501
2502         /* here we queue the commands from the uniform CD-ROM
2503            layer. the packet must be complete, as we do not
2504            touch it at all. */
2505         cdrom_prepare_request(&req);
2506         memcpy(req.cmd, cgc->cmd, CDROM_PACKET_SIZE);
2507         if (cgc->sense)
2508                 memset(cgc->sense, 0, sizeof(struct request_sense));
2509         req.data = cgc->buffer;
2510         req.data_len = cgc->buflen;
2511         req.timeout = cgc->timeout;
2512
2513         if (cgc->quiet)
2514                 req.flags |= REQ_QUIET;
2515
2516         req.sense = cgc->sense;
2517         cgc->stat = cdrom_queue_packet_command(drive, &req);
2518         if (!cgc->stat)
2519                 cgc->buflen -= req.data_len;
2520         return cgc->stat;
2521 }
2522
2523 static
2524 int ide_cdrom_dev_ioctl (struct cdrom_device_info *cdi,
2525                          unsigned int cmd, unsigned long arg)
2526 {
2527         struct cdrom_generic_command cgc;
2528         char buffer[16];
2529         int stat;
2530
2531         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
2532
2533         /* These will be moved into the Uniform layer shortly... */
2534         switch (cmd) {
2535         case CDROMSETSPINDOWN: {
2536                 char spindown;
2537  
2538                 if (copy_from_user(&spindown, (void *) arg, sizeof(char)))
2539                         return -EFAULT;
2540  
2541                 if ((stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0)))
2542                         return stat;
2543
2544                 buffer[11] = (buffer[11] & 0xf0) | (spindown & 0x0f);
2545
2546                 return cdrom_mode_select(cdi, &cgc);
2547         } 
2548  
2549         case CDROMGETSPINDOWN: {
2550                 char spindown;
2551  
2552                 if ((stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0)))
2553                         return stat;
2554  
2555                 spindown = buffer[11] & 0x0f;
2556  
2557                 if (copy_to_user((void *) arg, &spindown, sizeof (char)))
2558                         return -EFAULT;
2559  
2560                 return 0;
2561         }
2562   
2563         default:
2564                 return -EINVAL;
2565         }
2566
2567 }
2568
2569 static
2570 int ide_cdrom_audio_ioctl (struct cdrom_device_info *cdi,
2571                            unsigned int cmd, void *arg)
2572                            
2573 {
2574         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2575         struct cdrom_info *info = drive->driver_data;
2576         int stat;
2577
2578         switch (cmd) {
2579         /*
2580          * emulate PLAY_AUDIO_TI command with PLAY_AUDIO_10, since
2581          * atapi doesn't support it
2582          */
2583         case CDROMPLAYTRKIND: {
2584                 unsigned long lba_start, lba_end;
2585                 struct cdrom_ti *ti = (struct cdrom_ti *)arg;
2586                 struct atapi_toc_entry *first_toc, *last_toc;
2587
2588                 stat = cdrom_get_toc_entry(drive, ti->cdti_trk0, &first_toc);
2589                 if (stat)
2590                         return stat;
2591
2592                 stat = cdrom_get_toc_entry(drive, ti->cdti_trk1, &last_toc);
2593                 if (stat)
2594                         return stat;
2595
2596                 if (ti->cdti_trk1 != CDROM_LEADOUT)
2597                         ++last_toc;
2598                 lba_start = first_toc->addr.lba;
2599                 lba_end   = last_toc->addr.lba;
2600
2601                 if (lba_end <= lba_start)
2602                         return -EINVAL;
2603
2604                 return cdrom_play_audio(drive, lba_start, lba_end);
2605         }
2606
2607         case CDROMREADTOCHDR: {
2608                 struct cdrom_tochdr *tochdr = (struct cdrom_tochdr *) arg;
2609                 struct atapi_toc *toc;
2610
2611                 /* Make sure our saved TOC is valid. */
2612                 stat = cdrom_read_toc(drive, NULL);
2613                 if (stat) return stat;
2614
2615                 toc = info->toc;
2616                 tochdr->cdth_trk0 = toc->hdr.first_track;
2617                 tochdr->cdth_trk1 = toc->hdr.last_track;
2618
2619                 return 0;
2620         }
2621
2622         case CDROMREADTOCENTRY: {
2623                 struct cdrom_tocentry *tocentry = (struct cdrom_tocentry*) arg;
2624                 struct atapi_toc_entry *toce;
2625
2626                 stat = cdrom_get_toc_entry(drive, tocentry->cdte_track, &toce);
2627                 if (stat) return stat;
2628
2629                 tocentry->cdte_ctrl = toce->control;
2630                 tocentry->cdte_adr  = toce->adr;
2631                 if (tocentry->cdte_format == CDROM_MSF) {
2632                         lba_to_msf (toce->addr.lba,
2633                                    &tocentry->cdte_addr.msf.minute,
2634                                    &tocentry->cdte_addr.msf.second,
2635                                    &tocentry->cdte_addr.msf.frame);
2636                 } else
2637                         tocentry->cdte_addr.lba = toce->addr.lba;
2638
2639                 return 0;
2640         }
2641
2642         default:
2643                 return -EINVAL;
2644         }
2645 }
2646
2647 static
2648 int ide_cdrom_reset (struct cdrom_device_info *cdi)
2649 {
2650         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2651         struct request_sense sense;
2652         struct request req;
2653         int ret;
2654
2655         cdrom_prepare_request(&req);
2656         req.flags = REQ_SPECIAL | REQ_QUIET;
2657         ret = ide_do_drive_cmd(drive, &req, ide_wait);
2658
2659         /*
2660          * A reset will unlock the door. If it was previously locked,
2661          * lock it again.
2662          */
2663         if (CDROM_STATE_FLAGS(drive)->door_locked)
2664                 (void) cdrom_lockdoor(drive, 1, &sense);
2665
2666         return ret;
2667 }
2668
2669
2670 static
2671 int ide_cdrom_tray_move (struct cdrom_device_info *cdi, int position)
2672 {
2673         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2674         struct request_sense sense;
2675
2676         if (position) {
2677                 int stat = cdrom_lockdoor(drive, 0, &sense);
2678                 if (stat) return stat;
2679         }
2680
2681         return cdrom_eject(drive, !position, &sense);
2682 }
2683
2684 static
2685 int ide_cdrom_lock_door (struct cdrom_device_info *cdi, int lock)
2686 {
2687         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2688         return cdrom_lockdoor(drive, lock, NULL);
2689 }
2690
2691 static
2692 int ide_cdrom_select_speed (struct cdrom_device_info *cdi, int speed)
2693 {
2694         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2695         struct request_sense sense;
2696         int stat;
2697
2698         if ((stat = cdrom_select_speed(drive, speed, &sense)) < 0)
2699                 return stat;
2700
2701         cdi->speed = CDROM_STATE_FLAGS(drive)->current_speed;
2702         return 0;
2703 }
2704
2705 /*
2706  * add logic to try GET_EVENT command first to check for media and tray
2707  * status. this should be supported by newer cd-r/w and all DVD etc
2708  * drives
2709  */
2710 static
2711 int ide_cdrom_drive_status (struct cdrom_device_info *cdi, int slot_nr)
2712 {
2713         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2714         struct media_event_desc med;
2715         struct request_sense sense;
2716         int stat;
2717
2718         if (slot_nr != CDSL_CURRENT)
2719                 return -EINVAL;
2720
2721         stat = cdrom_check_status(drive, &sense);
2722         if (!stat || sense.sense_key == UNIT_ATTENTION)
2723                 return CDS_DISC_OK;
2724
2725         if (!cdrom_get_media_event(cdi, &med)) {
2726                 if (med.media_present)
2727                         return CDS_DISC_OK;
2728                 if (med.door_open)
2729                         return CDS_TRAY_OPEN;
2730         }
2731
2732         if (sense.sense_key == NOT_READY && sense.asc == 0x04 && sense.ascq == 0x04)
2733                 return CDS_DISC_OK;
2734
2735         /*
2736          * If not using Mt Fuji extended media tray reports,
2737          * just return TRAY_OPEN since ATAPI doesn't provide
2738          * any other way to detect this...
2739          */
2740         if (sense.sense_key == NOT_READY) {
2741                 if (sense.asc == 0x3a && sense.ascq == 1)
2742                         return CDS_NO_DISC;
2743                 else
2744                         return CDS_TRAY_OPEN;
2745         }
2746
2747         return CDS_DRIVE_NOT_READY;
2748 }
2749
2750 static
2751 int ide_cdrom_get_last_session (struct cdrom_device_info *cdi,
2752                                 struct cdrom_multisession *ms_info)
2753 {
2754         struct atapi_toc *toc;
2755         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2756         struct cdrom_info *info = drive->driver_data;
2757         struct request_sense sense;
2758         int ret;
2759
2760         if (!CDROM_STATE_FLAGS(drive)->toc_valid || info->toc == NULL)
2761                 if ((ret = cdrom_read_toc(drive, &sense)))
2762                         return ret;
2763
2764         toc = info->toc;
2765         ms_info->addr.lba = toc->last_session_lba;
2766         ms_info->xa_flag = toc->xa_flag;
2767
2768         return 0;
2769 }
2770
2771 static
2772 int ide_cdrom_get_mcn (struct cdrom_device_info *cdi,
2773                        struct cdrom_mcn *mcn_info)
2774 {
2775         int stat;
2776         char mcnbuf[24];
2777         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2778
2779 /* get MCN */
2780         if ((stat = cdrom_read_subchannel(drive, 2, mcnbuf, sizeof (mcnbuf), NULL)))
2781                 return stat;
2782
2783         memcpy (mcn_info->medium_catalog_number, mcnbuf+9,
2784                 sizeof (mcn_info->medium_catalog_number)-1);
2785         mcn_info->medium_catalog_number[sizeof (mcn_info->medium_catalog_number)-1]
2786                 = '\0';
2787
2788         return 0;
2789 }
2790
2791
2792
2793 /****************************************************************************
2794  * Other driver requests (open, close, check media change).
2795  */
2796
2797 static
2798 int ide_cdrom_check_media_change_real (struct cdrom_device_info *cdi,
2799                                        int slot_nr)
2800 {
2801         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2802         int retval;
2803         
2804         if (slot_nr == CDSL_CURRENT) {
2805                 (void) cdrom_check_status(drive, NULL);
2806                 retval = CDROM_STATE_FLAGS(drive)->media_changed;
2807                 CDROM_STATE_FLAGS(drive)->media_changed = 0;
2808                 return retval;
2809         } else {
2810                 return -EINVAL;
2811         }
2812 }
2813
2814
2815 static
2816 int ide_cdrom_open_real (struct cdrom_device_info *cdi, int purpose)
2817 {
2818         return 0;
2819 }
2820
2821
2822 /*
2823  * Close down the device.  Invalidate all cached blocks.
2824  */
2825
2826 static
2827 void ide_cdrom_release_real (struct cdrom_device_info *cdi)
2828 {
2829         ide_drive_t *drive = cdi->handle;
2830
2831         if (!cdi->use_count)
2832                 CDROM_STATE_FLAGS(drive)->toc_valid = 0;
2833 }
2834
2835
2836
2837 /****************************************************************************
2838  * Device initialization.
2839  */
2840 static struct cdrom_device_ops ide_cdrom_dops = {
2841         .open                   = ide_cdrom_open_real,
2842         .release                = ide_cdrom_release_real,
2843         .drive_status           = ide_cdrom_drive_status,
2844         .media_changed          = ide_cdrom_check_media_change_real,
2845         .tray_move              = ide_cdrom_tray_move,
2846         .lock_door              = ide_cdrom_lock_door,
2847         .select_speed           = ide_cdrom_select_speed,
2848         .get_last_session       = ide_cdrom_get_last_session,
2849         .get_mcn                = ide_cdrom_get_mcn,
2850         .reset                  = ide_cdrom_reset,
2851         .audio_ioctl            = ide_cdrom_audio_ioctl,
2852         .dev_ioctl              = ide_cdrom_dev_ioctl,
2853         .capability             = CDC_CLOSE_TRAY | CDC_OPEN_TRAY | CDC_LOCK |
2854                                 CDC_SELECT_SPEED | CDC_SELECT_DISC |
2855                                 CDC_MULTI_SESSION | CDC_MCN |
2856                                 CDC_MEDIA_CHANGED | CDC_PLAY_AUDIO | CDC_RESET |
2857                                 CDC_IOCTLS | CDC_DRIVE_STATUS | CDC_CD_R |
2858                                 CDC_CD_RW | CDC_DVD | CDC_DVD_R| CDC_DVD_RAM |
2859                                 CDC_GENERIC_PACKET | CDC_MO_DRIVE | CDC_MRW |
2860                                 CDC_MRW_W | CDC_RAM,
2861         .generic_packet         = ide_cdrom_packet,
2862 };
2863
2864 static int ide_cdrom_register (ide_drive_t *drive, int nslots)
2865 {
2866         struct cdrom_info *info = drive->driver_data;
2867         struct cdrom_device_info *devinfo = &info->devinfo;
2868
2869         devinfo->ops = &ide_cdrom_dops;
2870         devinfo->mask = 0;
2871         devinfo->speed = CDROM_STATE_FLAGS(drive)->current_speed;
2872         devinfo->capacity = nslots;
2873         devinfo->handle = (void *) drive;
2874         strcpy(devinfo->name, drive->name);
2875         
2876         /* set capability mask to match the probe. */
2877         if (!CDROM_CONFIG_FLAGS(drive)->cd_r)
2878                 devinfo->mask |= CDC_CD_R;
2879         if (!CDROM_CONFIG_FLAGS(drive)->cd_rw)
2880                 devinfo->mask |= CDC_CD_RW;
2881         if (!CDROM_CONFIG_FLAGS(drive)->dvd)
2882                 devinfo->mask |= CDC_DVD;
2883         if (!CDROM_CONFIG_FLAGS(drive)->dvd_r)
2884                 devinfo->mask |= CDC_DVD_R;
2885         if (!CDROM_CONFIG_FLAGS(drive)->dvd_ram)
2886                 devinfo->mask |= CDC_DVD_RAM;
2887         if (!CDROM_CONFIG_FLAGS(drive)->is_changer)
2888                 devinfo->mask |= CDC_SELECT_DISC;
2889         if (!CDROM_CONFIG_FLAGS(drive)->audio_play)
2890                 devinfo->mask |= CDC_PLAY_AUDIO;
2891         if (!CDROM_CONFIG_FLAGS(drive)->close_tray)
2892                 devinfo->mask |= CDC_CLOSE_TRAY;
2893         if (!CDROM_CONFIG_FLAGS(drive)->mo_drive)
2894                 devinfo->mask |= CDC_MO_DRIVE;
2895         if (!CDROM_CONFIG_FLAGS(drive)->mrw)
2896                 devinfo->mask |= CDC_MRW;
2897         if (!CDROM_CONFIG_FLAGS(drive)->mrw_w)
2898                 devinfo->mask |= CDC_MRW_W;
2899         if (!CDROM_CONFIG_FLAGS(drive)->ram)
2900                 devinfo->mask |= CDC_RAM;
2901
2902         devinfo->disk = drive->disk;
2903         return register_cdrom(devinfo);
2904 }
2905
2906 static
2907 int ide_cdrom_get_capabilities(ide_drive_t *drive, struct atapi_capabilities_page *cap)
2908 {
2909         struct cdrom_info *info = drive->driver_data;
2910         struct cdrom_device_info *cdi = &info->devinfo;
2911         struct cdrom_generic_command cgc;
2912         int stat, attempts = 3, size = sizeof(*cap);
2913
2914         /*
2915          * ACER50 (and others?) require the full spec length mode sense
2916          * page capabilities size, but older drives break.
2917          */
2918         if (!(!strcmp(drive->id->model, "ATAPI CD ROM DRIVE 50X MAX") ||
2919             !strcmp(drive->id->model, "WPI CDS-32X")))
2920                 size -= sizeof(cap->pad);
2921
2922         init_cdrom_command(&cgc, cap, size, CGC_DATA_UNKNOWN);
2923         do { /* we seem to get stat=0x01,err=0x00 the first time (??) */
2924                 stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
2925                 if (!stat)
2926                         break;
2927         } while (--attempts);
2928         return stat;
2929 }
2930
2931 static
2932 int ide_cdrom_probe_capabilities (ide_drive_t *drive)
2933 {
2934         struct cdrom_info *info = drive->driver_data;
2935         struct cdrom_device_info *cdi = &info->devinfo;
2936         struct atapi_capabilities_page cap;
2937         int nslots = 1, mrw_write = 0, ram_write = 0;
2938
2939         if (drive->media == ide_optical) {
2940                 CDROM_CONFIG_FLAGS(drive)->mo_drive = 1;
2941                 CDROM_CONFIG_FLAGS(drive)->ram = 1;
2942                 printk("%s: ATAPI magneto-optical drive\n", drive->name);
2943                 return nslots;
2944         }
2945
2946         if (CDROM_CONFIG_FLAGS(drive)->nec260 ||
2947             !strcmp(drive->id->model,"STINGRAY 8422 IDE 8X CD-ROM 7-27-95")) {
2948                 CDROM_CONFIG_FLAGS(drive)->no_eject = 0;
2949                 CDROM_CONFIG_FLAGS(drive)->audio_play = 1;
2950                 return nslots;
2951         }
2952
2953         /*
2954          * we have to cheat a little here. the packet will eventually
2955          * be queued with ide_cdrom_packet(), which extracts the
2956          * drive from cdi->handle. Since this device hasn't been
2957          * registered with the Uniform layer yet, it can't do this.
2958          * Same goes for cdi->ops.
2959          */
2960         cdi->handle = (ide_drive_t *) drive;
2961         cdi->ops = &ide_cdrom_dops;
2962
2963         if (ide_cdrom_get_capabilities(drive, &cap))
2964                 return 0;
2965
2966         if (!cdrom_is_mrw(cdi, &mrw_write)) {
2967                 CDROM_CONFIG_FLAGS(drive)->mrw = 1;
2968                 if (mrw_write) {
2969                         CDROM_CONFIG_FLAGS(drive)->mrw_w = 1;
2970                         CDROM_CONFIG_FLAGS(drive)->ram = 1;
2971                 }
2972         }
2973         if (!cdrom_is_random_writable(cdi, &ram_write))
2974                 if (ram_write)
2975                         CDROM_CONFIG_FLAGS(drive)->ram = 1;
2976
2977         if (cap.lock == 0)
2978                 CDROM_CONFIG_FLAGS(drive)->no_doorlock = 1;
2979         if (cap.eject)
2980                 CDROM_CONFIG_FLAGS(drive)->no_eject = 0;
2981         if (cap.cd_r_write)
2982                 CDROM_CONFIG_FLAGS(drive)->cd_r = 1;
2983         if (cap.cd_rw_write)
2984                 CDROM_CONFIG_FLAGS(drive)->cd_rw = 1;
2985         if (cap.test_write)
2986                 CDROM_CONFIG_FLAGS(drive)->test_write = 1;
2987         if (cap.dvd_ram_read || cap.dvd_r_read || cap.dvd_rom)
2988                 CDROM_CONFIG_FLAGS(drive)->dvd = 1;
2989         if (cap.dvd_ram_write) {
2990                 CDROM_CONFIG_FLAGS(drive)->dvd_ram = 1;
2991                 CDROM_CONFIG_FLAGS(drive)->ram = 1;
2992         }
2993         if (cap.dvd_r_write)
2994                 CDROM_CONFIG_FLAGS(drive)->dvd_r = 1;
2995         if (cap.audio_play)
2996                 CDROM_CONFIG_FLAGS(drive)->audio_play = 1;
2997         if (cap.mechtype == mechtype_caddy || cap.mechtype == mechtype_popup)
2998                 CDROM_CONFIG_FLAGS(drive)->close_tray = 0;
2999
3000         /* Some drives used by Apple don't advertise audio play
3001          * but they do support reading TOC & audio datas
3002          */
3003         if (strcmp(drive->id->model, "MATSHITADVD-ROM SR-8187") == 0 ||
3004             strcmp(drive->id->model, "MATSHITADVD-ROM SR-8186") == 0 ||
3005             strcmp(drive->id->model, "MATSHITADVD-ROM SR-8176") == 0 ||
3006             strcmp(drive->id->model, "MATSHITADVD-ROM SR-8174") == 0)
3007                 CDROM_CONFIG_FLAGS(drive)->audio_play = 1;
3008
3009 #if ! STANDARD_ATAPI
3010         if (cdi->sanyo_slot > 0) {
3011                 CDROM_CONFIG_FLAGS(drive)->is_changer = 1;
3012                 nslots = 3;
3013         }
3014
3015         else
3016 #endif /* not STANDARD_ATAPI */
3017         if (cap.mechtype == mechtype_individual_changer ||
3018             cap.mechtype == mechtype_cartridge_changer) {
3019                 if ((nslots = cdrom_number_of_slots(cdi)) > 1) {
3020                         CDROM_CONFIG_FLAGS(drive)->is_changer = 1;
3021                         CDROM_CONFIG_FLAGS(drive)->supp_disc_present = 1;
3022                 }
3023         }
3024
3025         /* The ACER/AOpen 24X cdrom has the speed fields byte-swapped */
3026         if (!drive->id->model[0] &&
3027             !strncmp(drive->id->fw_rev, "241N", 4)) {
3028                 CDROM_STATE_FLAGS(drive)->current_speed  = 
3029                         (((unsigned int)cap.curspeed) + (176/2)) / 176;
3030                 CDROM_CONFIG_FLAGS(drive)->max_speed = 
3031                         (((unsigned int)cap.maxspeed) + (176/2)) / 176;
3032         } else {
3033                 CDROM_STATE_FLAGS(drive)->current_speed  = 
3034                         (ntohs(cap.curspeed) + (176/2)) / 176;
3035                 CDROM_CONFIG_FLAGS(drive)->max_speed = 
3036                         (ntohs(cap.maxspeed) + (176/2)) / 176;
3037         }
3038
3039         /* don't print speed if the drive reported 0.
3040          */
3041         printk("%s: ATAPI", drive->name);
3042         if (CDROM_CONFIG_FLAGS(drive)->max_speed)
3043                 printk(" %dX", CDROM_CONFIG_FLAGS(drive)->max_speed);
3044         printk(" %s", CDROM_CONFIG_FLAGS(drive)->dvd ? "DVD-ROM" : "CD-ROM");
3045
3046         if (CDROM_CONFIG_FLAGS(drive)->dvd_r|CDROM_CONFIG_FLAGS(drive)->dvd_ram)
3047                 printk(" DVD%s%s", 
3048                 (CDROM_CONFIG_FLAGS(drive)->dvd_r)? "-R" : "", 
3049                 (CDROM_CONFIG_FLAGS(drive)->dvd_ram)? "-RAM" : "");
3050
3051         if (CDROM_CONFIG_FLAGS(drive)->cd_r|CDROM_CONFIG_FLAGS(drive)->cd_rw) 
3052                 printk(" CD%s%s", 
3053                 (CDROM_CONFIG_FLAGS(drive)->cd_r)? "-R" : "", 
3054                 (CDROM_CONFIG_FLAGS(drive)->cd_rw)? "/RW" : "");
3055
3056         if (CDROM_CONFIG_FLAGS(drive)->mrw || CDROM_CONFIG_FLAGS(drive)->mrw_w)
3057                 printk(" CD-MR%s", CDROM_CONFIG_FLAGS(drive)->mrw_w ? "W" : "");
3058
3059         if (CDROM_CONFIG_FLAGS(drive)->is_changer) 
3060                 printk(" changer w/%d slots", nslots);
3061         else    
3062                 printk(" drive");
3063
3064         printk(", %dkB Cache", be16_to_cpu(cap.buffer_size));
3065
3066 #ifdef CONFIG_BLK_DEV_IDEDMA
3067         if (drive->using_dma)
3068                 (void) HWIF(drive)->ide_dma_verbose(drive);
3069 #endif /* CONFIG_BLK_DEV_IDEDMA */
3070         printk("\n");
3071
3072         return nslots;
3073 }
3074
3075 static void ide_cdrom_add_settings(ide_drive_t *drive)
3076 {
3077         ide_add_setting(drive,  "dsc_overlap",          SETTING_RW, -1, -1, TYPE_BYTE, 0, 1, 1, 1, &drive->dsc_overlap, NULL);
3078 }
3079
3080 /*
3081  * standard prep_rq_fn that builds 10 byte cmds
3082  */
3083 static int ide_cdrom_prep_fs(request_queue_t *q, struct request *rq)
3084 {
3085         int hard_sect = queue_hardsect_size(q);
3086         long block = (long)rq->hard_sector / (hard_sect >> 9);
3087         unsigned long blocks = rq->hard_nr_sectors / (hard_sect >> 9);
3088
3089         memset(rq->cmd, 0, sizeof(rq->cmd));
3090
3091         if (rq_data_dir(rq) == READ)
3092                 rq->cmd[0] = GPCMD_READ_10;
3093         else
3094                 rq->cmd[0] = GPCMD_WRITE_10;
3095
3096         /*
3097          * fill in lba
3098          */
3099         rq->cmd[2] = (block >> 24) & 0xff;
3100         rq->cmd[3] = (block >> 16) & 0xff;
3101         rq->cmd[4] = (block >>  8) & 0xff;
3102         rq->cmd[5] = block & 0xff;
3103
3104         /*
3105          * and transfer length
3106          */
3107         rq->cmd[7] = (blocks >> 8) & 0xff;
3108         rq->cmd[8] = blocks & 0xff;
3109         rq->cmd_len = 10;
3110         return BLKPREP_OK;
3111 }
3112
3113 /*
3114  * Most of the SCSI commands are supported directly by ATAPI devices.
3115  * This transform handles the few exceptions.
3116  */
3117 static int ide_cdrom_prep_pc(struct request *rq)
3118 {
3119         u8 *c = rq->cmd;
3120
3121         /*
3122          * Transform 6-byte read/write commands to the 10-byte version
3123          */
3124         if (c[0] == READ_6 || c[0] == WRITE_6) {
3125                 c[8] = c[4];
3126                 c[5] = c[3];
3127                 c[4] = c[2];
3128                 c[3] = c[1] & 0x1f;
3129                 c[2] = 0;
3130                 c[1] &= 0xe0;
3131                 c[0] += (READ_10 - READ_6);
3132                 rq->cmd_len = 10;
3133                 return BLKPREP_OK;
3134         }
3135
3136         /*
3137          * it's silly to pretend we understand 6-byte sense commands, just
3138          * reject with ILLEGAL_REQUEST and the caller should take the
3139          * appropriate action
3140          */
3141         if (c[0] == MODE_SENSE || c[0] == MODE_SELECT) {
3142                 rq->errors = ILLEGAL_REQUEST;
3143                 return BLKPREP_KILL;
3144         }
3145         
3146         return BLKPREP_OK;
3147 }
3148
3149 static int ide_cdrom_prep_fn(request_queue_t *q, struct request *rq)
3150 {
3151         if (rq->flags & REQ_CMD)
3152                 return ide_cdrom_prep_fs(q, rq);
3153         else if (rq->flags & REQ_BLOCK_PC)
3154                 return ide_cdrom_prep_pc(rq);
3155
3156         return 0;
3157 }
3158
3159 static
3160 int ide_cdrom_setup (ide_drive_t *drive)
3161 {
3162         struct cdrom_info *info = drive->driver_data;
3163         struct cdrom_device_info *cdi = &info->devinfo;
3164         int nslots;
3165
3166         blk_queue_prep_rq(drive->queue, ide_cdrom_prep_fn);
3167         blk_queue_dma_alignment(drive->queue, 3);
3168         drive->queue->unplug_delay = (1 * HZ) / 1000;
3169         if (!drive->queue->unplug_delay)
3170                 drive->queue->unplug_delay = 1;
3171
3172         drive->special.all      = 0;
3173         drive->ready_stat       = 0;
3174
3175         CDROM_STATE_FLAGS(drive)->media_changed = 1;
3176         CDROM_STATE_FLAGS(drive)->toc_valid     = 0;
3177         CDROM_STATE_FLAGS(drive)->door_locked   = 0;
3178
3179 #if NO_DOOR_LOCKING
3180         CDROM_CONFIG_FLAGS(drive)->no_doorlock = 1;
3181 #else
3182         CDROM_CONFIG_FLAGS(drive)->no_doorlock = 0;
3183 #endif
3184
3185         CDROM_CONFIG_FLAGS(drive)->drq_interrupt = ((drive->id->config & 0x0060) == 0x20);
3186         CDROM_CONFIG_FLAGS(drive)->is_changer = 0;
3187         CDROM_CONFIG_FLAGS(drive)->cd_r = 0;
3188         CDROM_CONFIG_FLAGS(drive)->cd_rw = 0;
3189         CDROM_CONFIG_FLAGS(drive)->test_write = 0;
3190         CDROM_CONFIG_FLAGS(drive)->dvd = 0;
3191         CDROM_CONFIG_FLAGS(drive)->dvd_r = 0;
3192         CDROM_CONFIG_FLAGS(drive)->dvd_ram = 0;
3193         CDROM_CONFIG_FLAGS(drive)->no_eject = 1;
3194         CDROM_CONFIG_FLAGS(drive)->supp_disc_present = 0;
3195         CDROM_CONFIG_FLAGS(drive)->audio_play = 0;
3196         CDROM_CONFIG_FLAGS(drive)->close_tray = 1;
3197         
3198         /* limit transfer size per interrupt. */
3199         CDROM_CONFIG_FLAGS(drive)->limit_nframes = 0;
3200         /* a testament to the nice quality of Samsung drives... */
3201         if (!strcmp(drive->id->model, "SAMSUNG CD-ROM SCR-2430"))
3202                 CDROM_CONFIG_FLAGS(drive)->limit_nframes = 1;
3203         else if (!strcmp(drive->id->model, "SAMSUNG CD-ROM SCR-2432"))
3204                 CDROM_CONFIG_FLAGS(drive)->limit_nframes = 1;
3205         /* the 3231 model does not support the SET_CD_SPEED command */
3206         else if (!strcmp(drive->id->model, "SAMSUNG CD-ROM SCR-3231"))
3207                 cdi->mask |= CDC_SELECT_SPEED;
3208
3209 #if ! STANDARD_ATAPI
3210         /* by default Sanyo 3 CD changer support is turned off and
3211            ATAPI Rev 2.2+ standard support for CD changers is used */
3212         cdi->sanyo_slot = 0;
3213
3214         CDROM_CONFIG_FLAGS(drive)->nec260 = 0;
3215         CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd = 0;
3216         CDROM_CONFIG_FLAGS(drive)->tocaddr_as_bcd = 0;
3217         CDROM_CONFIG_FLAGS(drive)->playmsf_as_bcd = 0;
3218         CDROM_CONFIG_FLAGS(drive)->subchan_as_bcd = 0;
3219
3220         if (strcmp (drive->id->model, "V003S0DS") == 0 &&
3221             drive->id->fw_rev[4] == '1' &&
3222             drive->id->fw_rev[6] <= '2') {
3223                 /* Vertos 300.
3224                    Some versions of this drive like to talk BCD. */
3225                 CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd = 1;
3226                 CDROM_CONFIG_FLAGS(drive)->tocaddr_as_bcd = 1;
3227                 CDROM_CONFIG_FLAGS(drive)->playmsf_as_bcd = 1;
3228                 CDROM_CONFIG_FLAGS(drive)->subchan_as_bcd = 1;
3229         }
3230
3231         else if (strcmp (drive->id->model, "V006E0DS") == 0 &&
3232             drive->id->fw_rev[4] == '1' &&
3233             drive->id->fw_rev[6] <= '2') {
3234                 /* Vertos 600 ESD. */
3235                 CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd = 1;
3236         }
3237         else if (strcmp(drive->id->model, "NEC CD-ROM DRIVE:260") == 0 &&
3238                  strncmp(drive->id->fw_rev, "1.01", 4) == 0) { /* FIXME */
3239                 /* Old NEC260 (not R).
3240                    This drive was released before the 1.2 version
3241                    of the spec. */
3242                 CDROM_CONFIG_FLAGS(drive)->tocaddr_as_bcd = 1;
3243                 CDROM_CONFIG_FLAGS(drive)->playmsf_as_bcd = 1;
3244                 CDROM_CONFIG_FLAGS(drive)->subchan_as_bcd = 1;
3245                 CDROM_CONFIG_FLAGS(drive)->nec260         = 1;
3246         }
3247         else if (strcmp(drive->id->model, "WEARNES CDD-120") == 0 &&
3248                  strncmp(drive->id->fw_rev, "A1.1", 4) == 0) { /* FIXME */
3249                 /* Wearnes */
3250                 CDROM_CONFIG_FLAGS(drive)->playmsf_as_bcd = 1;
3251                 CDROM_CONFIG_FLAGS(drive)->subchan_as_bcd = 1;
3252         }
3253         /* Sanyo 3 CD changer uses a non-standard command
3254            for CD changing */
3255         else if ((strcmp(drive->id->model, "CD-ROM CDR-C3 G") == 0) ||
3256                  (strcmp(drive->id->model, "CD-ROM CDR-C3G") == 0) ||
3257                  (strcmp(drive->id->model, "CD-ROM CDR_C36") == 0)) {
3258                  /* uses CD in slot 0 when value is set to 3 */
3259                  cdi->sanyo_slot = 3;
3260         }
3261 #endif /* not STANDARD_ATAPI */
3262
3263         info->toc               = NULL;
3264         info->buffer            = NULL;
3265         info->sector_buffered   = 0;
3266         info->nsectors_buffered = 0;
3267         info->changer_info      = NULL;
3268         info->last_block        = 0;
3269         info->start_seek        = 0;
3270
3271         nslots = ide_cdrom_probe_capabilities (drive);
3272
3273         /*
3274          * set correct block size and read-only for non-ram media
3275          */
3276         set_disk_ro(drive->disk, !CDROM_CONFIG_FLAGS(drive)->ram);
3277         blk_queue_hardsect_size(drive->queue, CD_FRAMESIZE);
3278
3279 #if 0
3280         drive->dsc_overlap = (HWIF(drive)->no_dsc) ? 0 : 1;
3281         if (HWIF(drive)->no_dsc) {
3282                 printk(KERN_INFO "ide-cd: %s: disabling DSC overlap\n",
3283                         drive->name);
3284                 drive->dsc_overlap = 0;
3285         }
3286 #endif
3287
3288         if (ide_cdrom_register(drive, nslots)) {
3289                 printk ("%s: ide_cdrom_setup failed to register device with the cdrom driver.\n", drive->name);
3290                 info->devinfo.handle = NULL;
3291                 return 1;
3292         }
3293         ide_cdrom_add_settings(drive);
3294         return 0;
3295 }
3296
3297 static
3298 sector_t ide_cdrom_capacity (ide_drive_t *drive)
3299 {
3300         unsigned long capacity, sectors_per_frame;
3301
3302         if (cdrom_read_capacity(drive, &capacity, &sectors_per_frame, NULL))
3303                 return 0;
3304
3305         return capacity * sectors_per_frame;
3306 }
3307
3308 static
3309 int ide_cdrom_cleanup(ide_drive_t *drive)
3310 {
3311         struct cdrom_info *info = drive->driver_data;
3312         struct cdrom_device_info *devinfo = &info->devinfo;
3313         struct gendisk *g = drive->disk;
3314
3315         if (ide_unregister_subdriver(drive)) {
3316                 printk("%s: %s: failed to ide_unregister_subdriver\n",
3317                         __FUNCTION__, drive->name);
3318                 return 1;
3319         }
3320         if (info->buffer != NULL)
3321                 kfree(info->buffer);
3322         if (info->toc != NULL)
3323                 kfree(info->toc);
3324         if (info->changer_info != NULL)
3325                 kfree(info->changer_info);
3326         if (devinfo->handle == drive && unregister_cdrom(devinfo))
3327                 printk("%s: ide_cdrom_cleanup failed to unregister device from the cdrom driver.\n", drive->name);
3328         kfree(info);
3329         drive->driver_data = NULL;
3330         blk_queue_prep_rq(drive->queue, NULL);
3331         del_gendisk(g);
3332         g->fops = ide_fops;
3333         return 0;
3334 }
3335
3336 static int ide_cdrom_attach (ide_drive_t *drive);
3337
3338 /*
3339  * Power Management state machine.
3340  *
3341  * We don't do much for CDs right now.
3342  */
3343
3344 static void ide_cdrom_complete_power_step (ide_drive_t *drive, struct request *rq, u8 stat, u8 error)
3345 {
3346 }
3347
3348 static ide_startstop_t ide_cdrom_start_power_step (ide_drive_t *drive, struct request *rq)
3349 {
3350         ide_task_t *args = rq->special;
3351
3352         memset(args, 0, sizeof(*args));
3353
3354         switch (rq->pm->pm_step) {
3355         case ide_pm_state_start_suspend:
3356                 break;
3357
3358         case ide_pm_state_start_resume: /* Resume step 1 (restore DMA) */
3359                 /*
3360                  * Right now, all we do is call hwif->ide_dma_check(drive),
3361                  * we could be smarter and check for current xfer_speed
3362                  * in struct drive etc...
3363                  * Also, this step could be implemented as a generic helper
3364                  * as most subdrivers will use it.
3365                  */
3366                 if ((drive->id->capability & 1) == 0)
3367                         break;
3368                 if (HWIF(drive)->ide_dma_check == NULL)
3369                         break;
3370                 HWIF(drive)->ide_dma_check(drive);
3371                 break;
3372         }
3373         rq->pm->pm_step = ide_pm_state_completed;
3374         return ide_stopped;
3375 }
3376
3377 static ide_driver_t ide_cdrom_driver = {
3378         .owner                  = THIS_MODULE,
3379         .name                   = "ide-cdrom",
3380         .version                = IDECD_VERSION,
3381         .media                  = ide_cdrom,
3382         .busy                   = 0,
3383         .supports_dsc_overlap   = 1,
3384         .cleanup                = ide_cdrom_cleanup,
3385         .do_request             = ide_do_rw_cdrom,
3386         .sense                  = ide_dump_atapi_status,
3387         .error                  = ide_cdrom_error,
3388         .abort                  = ide_cdrom_abort,
3389         .capacity               = ide_cdrom_capacity,
3390         .attach                 = ide_cdrom_attach,
3391         .drives                 = LIST_HEAD_INIT(ide_cdrom_driver.drives),
3392         .start_power_step       = ide_cdrom_start_power_step,
3393         .complete_power_step    = ide_cdrom_complete_power_step,
3394 };
3395
3396 static int idecd_open(struct inode * inode, struct file * file)
3397 {
3398         ide_drive_t *drive = inode->i_bdev->bd_disk->private_data;
3399         struct cdrom_info *info = drive->driver_data;
3400         int rc = -ENOMEM;
3401         drive->usage++;
3402
3403         if (!info->buffer)
3404                 info->buffer = kmalloc(SECTOR_BUFFER_SIZE,
3405                                         GFP_KERNEL|__GFP_REPEAT);
3406         if (!info->buffer || (rc = cdrom_open(&info->devinfo, inode, file)))
3407                 drive->usage--;
3408         return rc;
3409 }
3410
3411 static int idecd_release(struct inode * inode, struct file * file)
3412 {
3413         ide_drive_t *drive = inode->i_bdev->bd_disk->private_data;
3414         struct cdrom_info *info = drive->driver_data;
3415
3416         cdrom_release (&info->devinfo, file);
3417         drive->usage--;
3418         return 0;
3419 }
3420
3421 static int idecd_ioctl (struct inode *inode, struct file *file,
3422                         unsigned int cmd, unsigned long arg)
3423 {
3424         struct block_device *bdev = inode->i_bdev;
3425         ide_drive_t *drive = bdev->bd_disk->private_data;
3426         int err = generic_ide_ioctl(bdev, cmd, arg);
3427         if (err == -EINVAL) {
3428                 struct cdrom_info *info = drive->driver_data;
3429                 err = cdrom_ioctl(&info->devinfo, inode, cmd, arg);
3430         }
3431         return err;
3432 }
3433
3434 static int idecd_media_changed(struct gendisk *disk)
3435 {
3436         ide_drive_t *drive = disk->private_data;
3437         struct cdrom_info *info = drive->driver_data;
3438         return cdrom_media_changed(&info->devinfo);
3439 }
3440
3441 static int idecd_revalidate_disk(struct gendisk *disk)
3442 {
3443         ide_drive_t *drive = disk->private_data;
3444         struct request_sense sense;
3445         cdrom_read_toc(drive, &sense);
3446         return  0;
3447 }
3448
3449 static struct block_device_operations idecd_ops = {
3450         .owner          = THIS_MODULE,
3451         .open           = idecd_open,
3452         .release        = idecd_release,
3453         .ioctl          = idecd_ioctl,
3454         .media_changed  = idecd_media_changed,
3455         .revalidate_disk= idecd_revalidate_disk
3456 };
3457
3458 /* options */
3459 char *ignore = NULL;
3460
3461 MODULE_PARM(ignore, "s");
3462 MODULE_DESCRIPTION("ATAPI CD-ROM Driver");
3463
3464 static int ide_cdrom_attach (ide_drive_t *drive)
3465 {
3466         struct cdrom_info *info;
3467         struct gendisk *g = drive->disk;
3468         struct request_sense sense;
3469
3470         if (!strstr("ide-cdrom", drive->driver_req))
3471                 goto failed;
3472         if (!drive->present)
3473                 goto failed;
3474         if (drive->media != ide_cdrom && drive->media != ide_optical)
3475                 goto failed;
3476         /* skip drives that we were told to ignore */
3477         if (ignore != NULL) {
3478                 if (strstr(ignore, drive->name)) {
3479                         printk("ide-cd: ignoring drive %s\n", drive->name);
3480                         goto failed;
3481                 }
3482         }
3483         if (drive->scsi) {
3484                 printk("ide-cd: passing drive %s to ide-scsi emulation.\n", drive->name);
3485                 goto failed;
3486         }
3487         info = (struct cdrom_info *) kmalloc (sizeof (struct cdrom_info), GFP_KERNEL);
3488         if (info == NULL) {
3489                 printk("%s: Can't allocate a cdrom structure\n", drive->name);
3490                 goto failed;
3491         }
3492         if (ide_register_subdriver(drive, &ide_cdrom_driver)) {
3493                 printk("%s: Failed to register the driver with ide.c\n",
3494                         drive->name);
3495                 kfree(info);
3496                 goto failed;
3497         }
3498         memset(info, 0, sizeof (struct cdrom_info));
3499         drive->driver_data = info;
3500         DRIVER(drive)->busy++;
3501         g->minors = 1;
3502         snprintf(g->devfs_name, sizeof(g->devfs_name),
3503                         "%s/cd", drive->devfs_name);
3504         g->driverfs_dev = &drive->gendev;
3505         g->flags = GENHD_FL_CD | GENHD_FL_REMOVABLE;
3506         if (ide_cdrom_setup(drive)) {
3507                 struct cdrom_device_info *devinfo = &info->devinfo;
3508                 DRIVER(drive)->busy--;
3509                 ide_unregister_subdriver(drive);
3510                 if (info->buffer != NULL)
3511                         kfree(info->buffer);
3512                 if (info->toc != NULL)
3513                         kfree(info->toc);
3514                 if (info->changer_info != NULL)
3515                         kfree(info->changer_info);
3516                 if (devinfo->handle == drive && unregister_cdrom(devinfo))
3517                         printk ("%s: ide_cdrom_cleanup failed to unregister device from the cdrom driver.\n", drive->name);
3518                 kfree(info);
3519                 drive->driver_data = NULL;
3520                 goto failed;
3521         }
3522         DRIVER(drive)->busy--;
3523
3524         cdrom_read_toc(drive, &sense);
3525         g->fops = &idecd_ops;
3526         g->flags |= GENHD_FL_REMOVABLE;
3527         add_disk(g);
3528         return 0;
3529 failed:
3530         return 1;
3531 }
3532
3533 static void __exit ide_cdrom_exit(void)
3534 {
3535         ide_unregister_driver(&ide_cdrom_driver);
3536 }
3537  
3538 static int ide_cdrom_init(void)
3539 {
3540         ide_register_driver(&ide_cdrom_driver);
3541         return 0;
3542 }
3543
3544 module_init(ide_cdrom_init);
3545 module_exit(ide_cdrom_exit);
3546 MODULE_LICENSE("GPL");