added mtd driver
[linux-2.4.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 accomodated 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  *
295  *************************************************************************/
296  
297 #define IDECD_VERSION "4.59-ac1"
298
299 #include <linux/config.h>
300 #include <linux/module.h>
301 #include <linux/types.h>
302 #include <linux/kernel.h>
303 #include <linux/delay.h>
304 #include <linux/timer.h>
305 #include <linux/slab.h>
306 #include <linux/interrupt.h>
307 #include <linux/errno.h>
308 #include <linux/cdrom.h>
309 #include <linux/ide.h>
310 #include <linux/completion.h>
311
312 #include <asm/irq.h>
313 #include <asm/io.h>
314 #include <asm/byteorder.h>
315 #include <asm/uaccess.h>
316 #include <asm/unaligned.h>
317
318 #include "ide-cd.h"
319
320 /****************************************************************************
321  * Generic packet command support and error handling routines.
322  */
323
324 /* Mark that we've seen a media change, and invalidate our internal
325    buffers. */
326 static void cdrom_saw_media_change (ide_drive_t *drive)
327 {
328         struct cdrom_info *info = drive->driver_data;
329         
330         CDROM_STATE_FLAGS (drive)->media_changed = 1;
331         CDROM_STATE_FLAGS (drive)->toc_valid = 0;
332         info->nsectors_buffered = 0;
333 }
334
335 static int cdrom_log_sense(ide_drive_t *drive, struct packet_command *pc,
336                            struct request_sense *sense)
337 {
338         int log = 0;
339
340         if (sense == NULL || pc == NULL || pc->quiet)
341                 return 0;
342
343         switch (sense->sense_key) {
344                 case NO_SENSE: case RECOVERED_ERROR:
345                         break;
346                 case NOT_READY:
347                         /*
348                          * don't care about tray state messages for
349                          * e.g. capacity commands or in-progress or
350                          * becoming ready
351                          */
352                         if (sense->asc == 0x3a || sense->asc == 0x04)
353                                 break;
354                         log = 1;
355                         break;
356                 case UNIT_ATTENTION:
357                         /*
358                          * Make good and sure we've seen this potential media
359                          * change. Some drives (i.e. Creative) fail to present
360                          * the correct sense key in the error register.
361                          */
362                         cdrom_saw_media_change(drive);
363                         break;
364                 default:
365                         log = 1;
366                         break;
367         }
368         return log;
369 }
370
371 static
372 void cdrom_analyze_sense_data(ide_drive_t *drive,
373                               struct packet_command *failed_command,
374                               struct request_sense *sense)
375 {
376
377         if (!cdrom_log_sense(drive, failed_command, sense))
378                 return;
379
380         /*
381          * If a read toc is executed for a CD-R or CD-RW medium where
382          * the first toc has not been recorded yet, it will fail with
383          * 05/24/00 (which is a confusing error)
384          */
385         if (failed_command && failed_command->c[0] == GPCMD_READ_TOC_PMA_ATIP)
386                 if (sense->sense_key == 0x05 && sense->asc == 0x24)
387                         return;
388
389 #if VERBOSE_IDE_CD_ERRORS
390         {
391                 int i;
392                 const char *s;
393                 char buf[80];
394
395                 printk ("ATAPI device %s:\n", drive->name);
396                 if (sense->error_code==0x70)
397                         printk("  Error: ");
398                 else if (sense->error_code==0x71)
399                         printk("  Deferred Error: ");
400                 else if (sense->error_code == 0x7f)
401                         printk("  Vendor-specific Error: ");
402                 else
403                         printk("  Unknown Error Type: ");
404
405                 if (sense->sense_key < ARY_LEN(sense_key_texts))
406                         s = sense_key_texts[sense->sense_key];
407                 else
408                         s = "bad sense key!";
409
410                 printk("%s -- (Sense key=0x%02x)\n", s, sense->sense_key);
411
412                 if (sense->asc == 0x40) {
413                         sprintf(buf, "Diagnostic failure on component 0x%02x",
414                                  sense->ascq);
415                         s = buf;
416                 } else {
417                         int lo = 0, mid, hi = ARY_LEN(sense_data_texts);
418                         unsigned long key = (sense->sense_key << 16);
419                         key |= (sense->asc << 8);
420                         if (!(sense->ascq >= 0x80 && sense->ascq <= 0xdd))
421                                 key |= sense->ascq;
422                         s = NULL;
423
424                         while (hi > lo) {
425                                 mid = (lo + hi) / 2;
426                                 if (sense_data_texts[mid].asc_ascq == key ||
427                                     sense_data_texts[mid].asc_ascq == (0xff0000|key)) {
428                                         s = sense_data_texts[mid].text;
429                                         break;
430                                 }
431                                 else if (sense_data_texts[mid].asc_ascq > key)
432                                         hi = mid;
433                                 else
434                                         lo = mid+1;
435                         }
436                 }
437
438                 if (s == NULL) {
439                         if (sense->asc > 0x80)
440                                 s = "(vendor-specific error)";
441                         else
442                                 s = "(reserved error code)";
443                 }
444
445                 printk("  %s -- (asc=0x%02x, ascq=0x%02x)\n",
446                         s, sense->asc, sense->ascq);
447
448                 if (failed_command != NULL) {
449
450                         int lo=0, mid, hi= ARY_LEN (packet_command_texts);
451                         s = NULL;
452
453                         while (hi > lo) {
454                                 mid = (lo + hi) / 2;
455                                 if (packet_command_texts[mid].packet_command ==
456                                     failed_command->c[0]) {
457                                         s = packet_command_texts[mid].text;
458                                         break;
459                                 }
460                                 if (packet_command_texts[mid].packet_command >
461                                     failed_command->c[0])
462                                         hi = mid;
463                                 else
464                                         lo = mid+1;
465                         }
466
467                         printk ("  The failed \"%s\" packet command was: \n  \"", s);
468                         for (i=0; i<sizeof (failed_command->c); i++)
469                                 printk ("%02x ", failed_command->c[i]);
470                         printk ("\"\n");
471                 }
472
473                 /* The SKSV bit specifies validity of the sense_key_specific
474                  * in the next two commands. It is bit 7 of the first byte.
475                  * In the case of NOT_READY, if SKSV is set the drive can
476                  * give us nice ETA readings.
477                  */
478                 if (sense->sense_key == NOT_READY && (sense->sks[0] & 0x80)) {
479                         int progress = (sense->sks[1] << 8 | sense->sks[2]) * 100;
480                         printk("  Command is %02d%% complete\n", progress / 0xffff);
481
482                 }
483
484                 if (sense->sense_key == ILLEGAL_REQUEST &&
485                     (sense->sks[0] & 0x80) != 0) {
486                         printk("  Error in %s byte %d",
487                                 (sense->sks[0] & 0x40) != 0 ?
488                                 "command packet" : "command data",
489                                 (sense->sks[1] << 8) + sense->sks[2]);
490
491                         if ((sense->sks[0] & 0x40) != 0)
492                                 printk (" bit %d", sense->sks[0] & 0x07);
493
494                         printk ("\n");
495                 }
496         }
497
498 #else /* not VERBOSE_IDE_CD_ERRORS */
499
500         /* Suppress printing unit attention and `in progress of becoming ready'
501            errors when we're not being verbose. */
502
503         if (sense->sense_key == UNIT_ATTENTION ||
504             (sense->sense_key == NOT_READY && (sense->asc == 4 ||
505                                                 sense->asc == 0x3a)))
506                 return;
507
508         printk("%s: error code: 0x%02x  sense_key: 0x%02x  asc: 0x%02x  ascq: 0x%02x\n",
509                 drive->name,
510                 sense->error_code, sense->sense_key,
511                 sense->asc, sense->ascq);
512 #endif /* not VERBOSE_IDE_CD_ERRORS */
513 }
514
515 static void cdrom_queue_request_sense(ide_drive_t *drive, 
516                                       struct completion *wait,
517                                       struct request_sense *sense,
518                                       struct packet_command *failed_command)
519 {
520         struct cdrom_info *info         = drive->driver_data;
521         struct packet_command *pc       = &info->request_sense_pc;
522         struct request *rq;
523
524         if (sense == NULL)
525                 sense = &info->sense_data;
526
527         memset(pc, 0, sizeof(struct packet_command));
528         pc->c[0] = GPCMD_REQUEST_SENSE;
529         pc->c[4] = pc->buflen = 18;
530         pc->buffer = (char *) sense;
531         pc->sense = (struct request_sense *) failed_command;
532
533         /* stuff the sense request in front of our current request */
534         rq = &info->request_sense_request;
535         ide_init_drive_cmd(rq);
536         rq->cmd = REQUEST_SENSE_COMMAND;
537         rq->buffer = (char *) pc;
538         rq->waiting = wait;
539         (void) ide_do_drive_cmd(drive, rq, ide_preempt);
540 }
541
542
543 /*
544  * This is our end_request replacement function.
545  */
546 static int ide_cdrom_end_request (ide_drive_t *drive, int uptodate)
547 {
548         struct request *rq;
549         unsigned long flags;
550         int ret = 1;
551
552         spin_lock_irqsave(&io_request_lock, flags);
553         rq = HWGROUP(drive)->rq;
554
555         /*
556          * decide whether to reenable DMA -- 3 is a random magic for now,
557          * if we DMA timeout more than 3 times, just stay in PIO
558          */
559         if (drive->state == DMA_PIO_RETRY && drive->retry_pio <= 3) {
560                 drive->state = 0;
561                 HWGROUP(drive)->hwif->ide_dma_on(drive);
562         }
563
564         if (!end_that_request_first(rq, uptodate, drive->name)) {
565                 add_blkdev_randomness(MAJOR(rq->rq_dev));
566                 blkdev_dequeue_request(rq);
567                 HWGROUP(drive)->rq = NULL;
568                 end_that_request_last(rq);
569                 ret = 0;
570         }
571         spin_unlock_irqrestore(&io_request_lock, flags);
572         return ret;
573 }
574
575 /*
576  * Error reporting, in human readable form (luxurious, but a memory hog).
577  */
578 byte ide_cdrom_dump_status (ide_drive_t *drive, const char *msg, byte stat)
579 {
580         unsigned long flags;
581
582         atapi_status_t status;
583         atapi_error_t error;
584
585         status.all = stat;
586         local_irq_set(flags);
587         printk("%s: %s: status=0x%02x", drive->name, msg, stat);
588 #if FANCY_STATUS_DUMPS
589         printk(" { ");
590         if (status.b.bsy)
591                 printk("Busy ");
592         else {
593                 if (status.b.drdy)      printk("DriveReady ");
594                 if (status.b.df)        printk("DeviceFault ");
595                 if (status.b.dsc)       printk("SeekComplete ");
596                 if (status.b.drq)       printk("DataRequest ");
597                 if (status.b.corr)      printk("CorrectedError ");
598                 if (status.b.idx)       printk("Index ");
599                 if (status.b.check)     printk("Error ");
600         }
601         printk("}");
602 #endif  /* FANCY_STATUS_DUMPS */
603         printk("\n");
604         if ((status.all & (status.b.bsy|status.b.check)) == status.b.check) {
605                 error.all = HWIF(drive)->INB(IDE_ERROR_REG);
606                 printk("%s: %s: error=0x%02x", drive->name, msg, error.all);
607 #if FANCY_STATUS_DUMPS
608                 if (error.b.ili)        printk("IllegalLengthIndication ");
609                 if (error.b.eom)        printk("EndOfMedia ");
610                 if (error.b.abrt)       printk("Aborted Command ");
611                 if (error.b.mcr)        printk("MediaChangeRequested ");
612                 if (error.b.sense_key)  printk("LastFailedSense 0x%02x ",
613                                                 error.b.sense_key);
614 #endif  /* FANCY_STATUS_DUMPS */
615                 printk("\n");
616         }
617         local_irq_restore(flags);
618         return error.all;
619 }
620
621 /*
622  * ide_error() takes action based on the error returned by the drive.
623  */
624 ide_startstop_t ide_cdrom_error (ide_drive_t *drive, const char *msg, byte stat)
625 {
626         struct request *rq;
627         byte err;
628
629         err = ide_cdrom_dump_status(drive, msg, stat);
630         if (drive == NULL || (rq = HWGROUP(drive)->rq) == NULL)
631                 return ide_stopped;
632         /* retry only "normal" I/O: */
633         if (rq->cmd == IDE_DRIVE_CMD || rq->cmd == IDE_DRIVE_TASK) {
634                 rq->errors = 1;
635                 ide_end_drive_cmd(drive, stat, err);
636                 return ide_stopped;
637         }
638
639         if (stat & BUSY_STAT || ((stat & WRERR_STAT) && !drive->nowerr)) {
640                 /* other bits are useless when BUSY */
641                 rq->errors |= ERROR_RESET;
642         } else {
643                 /* add decoding error stuff */
644         }
645         if (HWIF(drive)->INB(IDE_STATUS_REG) & (BUSY_STAT|DRQ_STAT))
646                 /* force an abort */
647                 HWIF(drive)->OUTB(WIN_IDLEIMMEDIATE,IDE_COMMAND_REG);
648         if (rq->errors >= ERROR_MAX) {
649                 DRIVER(drive)->end_request(drive, 0);
650         } else {
651                 if ((rq->errors & ERROR_RESET) == ERROR_RESET) {
652                         ++rq->errors;
653                         return ide_do_reset(drive);
654                 }
655                 ++rq->errors;
656         }
657         return ide_stopped;
658 }
659
660 ide_startstop_t ide_cdrom_abort (ide_drive_t *drive, const char *msg)
661 {
662         struct request *rq;
663
664         if (drive == NULL || (rq = HWGROUP(drive)->rq) == NULL)
665                 return ide_stopped;
666         /* retry only "normal" I/O: */
667         if (rq->cmd == IDE_DRIVE_CMD || rq->cmd == IDE_DRIVE_TASK) {
668                 rq->errors = 1;
669                 ide_end_drive_cmd(drive, BUSY_STAT, 0);
670                 return ide_stopped;
671         }
672         rq->errors |= ERROR_RESET;
673         DRIVER(drive)->end_request(drive, 0);
674         return ide_stopped;
675 }
676
677 static void cdrom_end_request (ide_drive_t *drive, int uptodate)
678 {
679         struct request *rq = HWGROUP(drive)->rq;
680
681         if (rq->cmd == REQUEST_SENSE_COMMAND && uptodate) {
682                 struct packet_command *pc = (struct packet_command *) rq->buffer;
683                 cdrom_analyze_sense_data(drive,
684                         (struct packet_command *) pc->sense,
685                         (struct request_sense *) (pc->buffer - pc->c[4]));
686         }
687         if (blk_fs_request(rq) && !rq->current_nr_sectors)
688                 uptodate = 1;
689
690         ide_cdrom_end_request(drive, uptodate);
691 }
692
693
694 /* Returns 0 if the request should be continued.
695    Returns 1 if the request was ended. */
696 static int cdrom_decode_status (ide_startstop_t *startstop, ide_drive_t *drive,
697                                 int good_stat, int *stat_ret)
698 {
699         struct request *rq = HWGROUP(drive)->rq;
700         int stat, err, sense_key;
701         struct packet_command *pc;
702         
703         /* Check for errors. */
704         *stat_ret = stat = HWIF(drive)->INB(IDE_STATUS_REG);
705
706         if (OK_STAT (stat, good_stat, BAD_R_STAT))
707                 return 0;
708
709         /* Get the IDE error register. */
710         err = HWIF(drive)->INB(IDE_ERROR_REG);
711         sense_key = err >> 4;
712
713         if (rq == NULL) {
714                 printk("%s: missing rq in cdrom_decode_status\n", drive->name);
715                 *startstop = ide_stopped;
716                 return 1;
717         }
718
719         if (rq->cmd == REQUEST_SENSE_COMMAND) {
720                 /* We got an error trying to get sense info
721                    from the drive (probably while trying
722                    to recover from a former error).  Just give up. */
723
724                 pc = (struct packet_command *) rq->buffer;
725                 pc->stat = 1;
726                 cdrom_end_request(drive, 1);
727                 *startstop = DRIVER(drive)->error(drive, "request sense failure", stat);
728                 return 1;
729
730         } else if (rq->cmd == PACKET_COMMAND) {
731                 /* All other functions, except for READ. */
732                 struct completion *wait = NULL;
733                 pc = (struct packet_command *) rq->buffer;
734
735                 /* Check for tray open. */
736                 if (sense_key == NOT_READY) {
737                         cdrom_saw_media_change (drive);
738                 } else if (sense_key == UNIT_ATTENTION) {
739                         /* Check for media change. */
740                         cdrom_saw_media_change (drive);
741                         /*printk("%s: media changed\n",drive->name);*/
742                         return 0;
743                 } else if (!pc->quiet) {
744                         /* Otherwise, print an error. */
745                         ide_dump_status(drive, "packet command error", stat);
746                 }
747                 
748                 /* Set the error flag and complete the request.
749                    Then, if we have a CHECK CONDITION status,
750                    queue a request sense command.  We must be careful,
751                    though: we don't want the thread in
752                    cdrom_queue_packet_command to wake up until
753                    the request sense has completed.  We do this
754                    by transferring the semaphore from the packet
755                    command request to the request sense request. */
756
757                 if ((stat & ERR_STAT) != 0) {
758                         wait = rq->waiting;
759                         rq->waiting = NULL;
760                 }
761
762                 pc->stat = 1;
763                 cdrom_end_request(drive, 1);
764
765                 if ((stat & ERR_STAT) != 0)
766                         cdrom_queue_request_sense(drive, wait, pc->sense, pc);
767         } else if (blk_fs_request(rq)) {
768                 int do_end_request = 0;
769
770                 /* Handle errors from READ and WRITE requests. */
771
772                 if (sense_key == NOT_READY) {
773                         /* Tray open. */
774                         cdrom_saw_media_change (drive);
775
776                         /* Fail the request. */
777                         printk ("%s: tray open\n", drive->name);
778                         do_end_request = 1;
779                 } else if (sense_key == UNIT_ATTENTION) {
780                         /* Media change. */
781                         cdrom_saw_media_change (drive);
782
783                         /* Arrange to retry the request.
784                            But be sure to give up if we've retried
785                            too many times. */
786                         if (++rq->errors > ERROR_MAX)
787                                 do_end_request = 1;
788                 } else if (sense_key == ILLEGAL_REQUEST ||
789                            sense_key == DATA_PROTECT) {
790                         /* No point in retrying after an illegal
791                            request or data protect error.*/
792                         ide_dump_status (drive, "command error", stat);
793                         do_end_request = 1;
794                 } else if (sense_key == MEDIUM_ERROR) {
795                         /* No point in re-trying a zillion times on a bad 
796                          * sector...  If we got here the error is not correctable */
797                         ide_dump_status (drive, "media error (bad sector)", stat);
798                         do_end_request = 1;
799                 } else if ((err & ~ABRT_ERR) != 0) {
800                         /* Go to the default handler
801                            for other errors. */
802                         *startstop = DRIVER(drive)->error(drive, "cdrom_decode_status", stat);
803                         return 1;
804                 } else if ((++rq->errors > ERROR_MAX)) {
805                         /* We've racked up too many retries.  Abort. */
806                         do_end_request = 1;
807                 }
808
809                 if (do_end_request)
810                         cdrom_end_request(drive, 0);
811
812                 /* If we got a CHECK_CONDITION status,
813                    queue a request sense command. */
814                 if ((stat & ERR_STAT) != 0)
815                         cdrom_queue_request_sense(drive, NULL, NULL, NULL);
816         }
817
818         /* Retry, or handle the next request. */
819         *startstop = ide_stopped;
820         return 1;
821 }
822
823 static int cdrom_timer_expiry(ide_drive_t *drive)
824 {
825         struct request *rq = HWGROUP(drive)->rq;
826         struct packet_command *pc = (struct packet_command *) rq->buffer;
827         unsigned long wait = 0;
828
829         /*
830          * Some commands are *slow* and normally take a long time to
831          * complete. Usually we can use the ATAPI "disconnect" to bypass
832          * this, but not all commands/drives support that. Let
833          * ide_timer_expiry keep polling us for these.
834          */
835         switch (pc->c[0]) {
836                 case GPCMD_BLANK:
837                 case GPCMD_FORMAT_UNIT:
838                 case GPCMD_RESERVE_RZONE_TRACK:
839                         wait = WAIT_CMD;
840                         break;
841                 default:
842                         wait = 0;
843                         break;
844         }
845         return wait;
846 }
847
848 /* Set up the device registers for transferring a packet command on DEV,
849    expecting to later transfer XFERLEN bytes.  HANDLER is the routine
850    which actually transfers the command to the drive.  If this is a
851    drq_interrupt device, this routine will arrange for HANDLER to be
852    called when the interrupt from the drive arrives.  Otherwise, HANDLER
853    will be called immediately after the drive is prepared for the transfer. */
854
855 static ide_startstop_t cdrom_start_packet_command(ide_drive_t *drive,
856                                                   int xferlen,
857                                                   ide_handler_t *handler)
858 {
859         ide_startstop_t startstop;
860         struct cdrom_info *info = drive->driver_data;
861
862         /* Wait for the controller to be idle. */
863         if (ide_wait_stat(&startstop, drive, 0, BUSY_STAT, WAIT_READY))
864                 return startstop;
865
866         if (info->dma) {
867                 if (info->cmd == READ) {
868                         info->dma = !HWIF(drive)->ide_dma_read(drive);
869                 } else if (info->cmd == WRITE) {
870                         info->dma = !HWIF(drive)->ide_dma_write(drive);
871                 } else {
872                         printk("ide-cd: DMA set, but not allowed\n");
873                 }
874         }
875
876         /* Set up the controller registers. */
877         /* FIXME: for Virtual DMA we must check harder */
878         HWIF(drive)->OUTB(info->dma, IDE_FEATURE_REG);
879         HWIF(drive)->OUTB(0, IDE_IREASON_REG);
880         HWIF(drive)->OUTB(0, IDE_SECTOR_REG);
881
882         HWIF(drive)->OUTB(xferlen & 0xff, IDE_BCOUNTL_REG);
883         HWIF(drive)->OUTB(xferlen >> 8  , IDE_BCOUNTH_REG);
884         if (IDE_CONTROL_REG)
885                 HWIF(drive)->OUTB(drive->ctl, IDE_CONTROL_REG);
886  
887         if (CDROM_CONFIG_FLAGS (drive)->drq_interrupt) {
888                 /* packet command */
889                 ide_execute_command(drive, WIN_PACKETCMD, handler, WAIT_CMD, cdrom_timer_expiry);
890                 return ide_started;
891         } else {
892                 /* packet command */
893                 HWIF(drive)->OUTB(WIN_PACKETCMD, IDE_COMMAND_REG);
894                 return (*handler) (drive);
895         }
896 }
897
898 /* Send a packet command to DRIVE described by CMD_BUF and CMD_LEN.
899    The device registers must have already been prepared
900    by cdrom_start_packet_command.
901    HANDLER is the interrupt handler to call when the command completes
902    or there's data ready. */
903 /*
904  * changed 5 parameters to 3 for dvd-ram
905  * struct packet_command *pc; now packet_command_t *pc;
906  */
907 static ide_startstop_t cdrom_transfer_packet_command (ide_drive_t *drive,
908                                           struct packet_command *pc,
909                                           ide_handler_t *handler)
910 {
911         unsigned char *cmd_buf  = pc->c;
912         int cmd_len             = sizeof(pc->c);
913         unsigned int timeout    = pc->timeout;
914         struct cdrom_info *info = drive->driver_data;
915         ide_startstop_t startstop;
916
917         if (CDROM_CONFIG_FLAGS(drive)->drq_interrupt) {
918                 /* Here we should have been called after receiving an interrupt
919                    from the device.  DRQ should how be set. */
920                 int stat_dum;
921
922                 /* Check for errors. */
923                 if (cdrom_decode_status(&startstop, drive, DRQ_STAT, &stat_dum))
924                         return startstop;
925         } else {
926                 /* Otherwise, we must wait for DRQ to get set. */
927                 if (ide_wait_stat(&startstop, drive, DRQ_STAT,
928                                 BUSY_STAT, WAIT_READY))
929                         return startstop;
930         }
931
932         /* Arm the interrupt handler. */
933         ide_set_handler(drive, handler, timeout, cdrom_timer_expiry);
934
935         /* Send the command to the device. */
936         HWIF(drive)->atapi_output_bytes(drive, cmd_buf, cmd_len);
937
938         /* Start the DMA if need be */
939         if (info->dma)
940                 (void) HWIF(drive)->ide_dma_begin(drive);
941
942         return ide_started;
943 }
944
945 /****************************************************************************
946  * Block read functions.
947  */
948
949 /*
950  * Buffer up to SECTORS_TO_TRANSFER sectors from the drive in our sector
951  * buffer.  Once the first sector is added, any subsequent sectors are
952  * assumed to be continuous (until the buffer is cleared).  For the first
953  * sector added, SECTOR is its sector number.  (SECTOR is then ignored until
954  * the buffer is cleared.)
955  */
956 static void cdrom_buffer_sectors (ide_drive_t *drive, unsigned long sector,
957                                   int sectors_to_transfer)
958 {
959         struct cdrom_info *info = drive->driver_data;
960
961         /* Number of sectors to read into the buffer. */
962         int sectors_to_buffer = MIN (sectors_to_transfer,
963                                      (SECTOR_BUFFER_SIZE >> SECTOR_BITS) -
964                                        info->nsectors_buffered);
965
966         char *dest;
967
968         /* If we couldn't get a buffer, don't try to buffer anything... */
969         if (info->buffer == NULL)
970                 sectors_to_buffer = 0;
971
972         /* If this is the first sector in the buffer, remember its number. */
973         if (info->nsectors_buffered == 0)
974                 info->sector_buffered = sector;
975
976         /* Read the data into the buffer. */
977         dest = info->buffer + info->nsectors_buffered * SECTOR_SIZE;
978         while (sectors_to_buffer > 0) {
979                 HWIF(drive)->atapi_input_bytes(drive, dest, SECTOR_SIZE);
980                 --sectors_to_buffer;
981                 --sectors_to_transfer;
982                 ++info->nsectors_buffered;
983                 dest += SECTOR_SIZE;
984         }
985
986         /* Throw away any remaining data. */
987         while (sectors_to_transfer > 0) {
988                 char dum[SECTOR_SIZE];
989                 HWIF(drive)->atapi_input_bytes(drive, dum, sizeof (dum));
990                 --sectors_to_transfer;
991         }
992 }
993
994 /*
995  * Check the contents of the interrupt reason register from the cdrom
996  * and attempt to recover if there are problems.  Returns  0 if everything's
997  * ok; nonzero if the request has been terminated.
998  */
999 static inline
1000 int cdrom_read_check_ireason (ide_drive_t *drive, int len, int ireason)
1001 {
1002         ireason &= 3;
1003         if (ireason == 2) return 0;
1004
1005         if (ireason == 0) {
1006                 /* Whoops... The drive is expecting to receive data from us! */
1007                 printk ("%s: cdrom_read_intr: "
1008                         "Drive wants to transfer data the wrong way!\n",
1009                         drive->name);
1010
1011                 /* Throw some data at the drive so it doesn't hang
1012                    and quit this request. */
1013                 while (len > 0) {
1014                         int dum = 0;
1015                         HWIF(drive)->atapi_output_bytes(drive, &dum, sizeof (dum));
1016                         len -= sizeof (dum);
1017                 }
1018         } else  if (ireason == 1) {
1019                 /* Some drives (ASUS) seem to tell us that status
1020                  * info is available. just get it and ignore.
1021                  */
1022                 (void) HWIF(drive)->INB(IDE_STATUS_REG);
1023                 return 0;
1024         } else {
1025                 /* Drive wants a command packet, or invalid ireason... */
1026                 printk ("%s: cdrom_read_intr: bad interrupt reason %d\n",
1027                         drive->name, ireason);
1028         }
1029
1030         cdrom_end_request(drive, 0);
1031         return -1;
1032 }
1033
1034 /*
1035  * Interrupt routine.  Called when a read request has completed.
1036  */
1037 static ide_startstop_t cdrom_read_intr (ide_drive_t *drive)
1038 {
1039         int stat;
1040         int ireason, len, sectors_to_transfer, nskip;
1041         struct cdrom_info *info = drive->driver_data;
1042         u8 lowcyl = 0, highcyl = 0;
1043         int i, dma = info->dma, dma_error = 0;
1044         ide_startstop_t startstop;
1045
1046         struct request *rq = HWGROUP(drive)->rq;
1047
1048         /* Check for errors. */
1049         if (dma) {
1050                 info->dma = 0;
1051                 if ((dma_error = HWIF(drive)->ide_dma_end(drive)))
1052                         HWIF(drive)->ide_dma_off(drive);
1053         }
1054
1055         if (cdrom_decode_status (&startstop, drive, 0, &stat))
1056                 return startstop;
1057  
1058         if (dma) {
1059                 if (!dma_error) {
1060                         for (i = rq->nr_sectors; i > 0;) {
1061                                 i -= rq->current_nr_sectors;
1062                                 ide_cdrom_end_request(drive, 1);
1063                         }
1064                         return ide_stopped;
1065                 } else
1066                         return DRIVER(drive)->error(drive, "dma error", stat);
1067         }
1068
1069         /* Read the interrupt reason and the transfer length. */
1070         ireason = HWIF(drive)->INB(IDE_IREASON_REG);
1071         lowcyl  = HWIF(drive)->INB(IDE_BCOUNTL_REG);
1072         highcyl = HWIF(drive)->INB(IDE_BCOUNTH_REG);
1073
1074         len = lowcyl + (256 * highcyl);
1075
1076         /* If DRQ is clear, the command has completed. */
1077         if ((stat & DRQ_STAT) == 0) {
1078                 /* If we're not done filling the current buffer, complain.
1079                    Otherwise, complete the command normally. */
1080                 if (rq->current_nr_sectors > 0) {
1081                         printk ("%s: cdrom_read_intr: data underrun (%ld blocks)\n",
1082                                 drive->name, rq->current_nr_sectors);
1083                         cdrom_end_request(drive, 0);
1084                 } else
1085                         cdrom_end_request(drive, 1);
1086                 return ide_stopped;
1087         }
1088
1089         /* Check that the drive is expecting to do the same thing we are. */
1090         if (cdrom_read_check_ireason (drive, len, ireason))
1091                 return ide_stopped;
1092
1093         /* Assume that the drive will always provide data in multiples
1094            of at least SECTOR_SIZE, as it gets hairy to keep track
1095            of the transfers otherwise. */
1096         if ((len % SECTOR_SIZE) != 0) {
1097                 printk ("%s: cdrom_read_intr: Bad transfer size %d\n",
1098                         drive->name, len);
1099                 if (CDROM_CONFIG_FLAGS(drive)->limit_nframes)
1100                         printk ("  This drive is not supported by this version of the driver\n");
1101                 else {
1102                         printk ("  Trying to limit transfer sizes\n");
1103                         CDROM_CONFIG_FLAGS(drive)->limit_nframes = 1;
1104                 }
1105                 cdrom_end_request(drive, 0);
1106                 return ide_stopped;
1107         }
1108
1109         /* The number of sectors we need to read from the drive. */
1110         sectors_to_transfer = len / SECTOR_SIZE;
1111
1112         /* First, figure out if we need to bit-bucket
1113            any of the leading sectors. */
1114         nskip = MIN ((int)(rq->current_nr_sectors - (rq->bh->b_size >> SECTOR_BITS)),
1115                      sectors_to_transfer);
1116
1117         while (nskip > 0) {
1118                 /* We need to throw away a sector. */
1119                 char dum[SECTOR_SIZE];
1120                 HWIF(drive)->atapi_input_bytes(drive, dum, sizeof (dum));
1121
1122                 --rq->current_nr_sectors;
1123                 --nskip;
1124                 --sectors_to_transfer;
1125         }
1126
1127         /* Now loop while we still have data to read from the drive. */
1128         while (sectors_to_transfer > 0) {
1129                 int this_transfer;
1130
1131                 /* If we've filled the present buffer but there's another
1132                    chained buffer after it, move on. */
1133                 if (rq->current_nr_sectors == 0 && rq->nr_sectors)
1134                         cdrom_end_request(drive, 1);
1135
1136                 /* If the buffers are full, cache the rest of the data in our
1137                    internal buffer. */
1138                 if (rq->current_nr_sectors == 0) {
1139                         cdrom_buffer_sectors(drive, rq->sector, sectors_to_transfer);
1140                         sectors_to_transfer = 0;
1141                 } else {
1142                         /* Transfer data to the buffers.
1143                            Figure out how many sectors we can transfer
1144                            to the current buffer. */
1145                         this_transfer = MIN (sectors_to_transfer,
1146                                              rq->current_nr_sectors);
1147
1148                         /* Read this_transfer sectors
1149                            into the current buffer. */
1150                         while (this_transfer > 0) {
1151                                 HWIF(drive)->atapi_input_bytes(drive, rq->buffer, SECTOR_SIZE);
1152                                 rq->buffer += SECTOR_SIZE;
1153                                 --rq->nr_sectors;
1154                                 --rq->current_nr_sectors;
1155                                 ++rq->sector;
1156                                 --this_transfer;
1157                                 --sectors_to_transfer;
1158                         }
1159                 }
1160         }
1161
1162         /* Done moving data!  Wait for another interrupt. */
1163         ide_set_handler(drive, &cdrom_read_intr, WAIT_CMD, NULL);
1164         return ide_started;
1165 }
1166
1167 /*
1168  * Try to satisfy some of the current read request from our cached data.
1169  * Returns nonzero if the request has been completed, zero otherwise.
1170  */
1171 static int cdrom_read_from_buffer (ide_drive_t *drive)
1172 {
1173         struct cdrom_info *info = drive->driver_data;
1174         struct request *rq = HWGROUP(drive)->rq;
1175
1176         /* Can't do anything if there's no buffer. */
1177         if (info->buffer == NULL) return 0;
1178
1179         /* Loop while this request needs data and the next block is present
1180            in our cache. */
1181         while (rq->nr_sectors > 0 &&
1182                rq->sector >= info->sector_buffered &&
1183                rq->sector < info->sector_buffered + info->nsectors_buffered) {
1184                 if (rq->current_nr_sectors == 0)
1185                         cdrom_end_request(drive, 1);
1186
1187                 memcpy (rq->buffer,
1188                         info->buffer +
1189                         (rq->sector - info->sector_buffered) * SECTOR_SIZE,
1190                         SECTOR_SIZE);
1191                 rq->buffer += SECTOR_SIZE;
1192                 --rq->current_nr_sectors;
1193                 --rq->nr_sectors;
1194                 ++rq->sector;
1195         }
1196
1197         /* If we've satisfied the current request,
1198            terminate it successfully. */
1199         if (rq->nr_sectors == 0) {
1200                 cdrom_end_request(drive, 1);
1201                 return -1;
1202         }
1203
1204         /* Move on to the next buffer if needed. */
1205         if (rq->current_nr_sectors == 0)
1206                 cdrom_end_request(drive, 1);
1207
1208         /* If this condition does not hold, then the kluge i use to
1209            represent the number of sectors to skip at the start of a transfer
1210            will fail.  I think that this will never happen, but let's be
1211            paranoid and check. */
1212         if (rq->current_nr_sectors < (rq->bh->b_size >> SECTOR_BITS) &&
1213             (rq->sector % SECTORS_PER_FRAME) != 0) {
1214                 printk("%s: cdrom_read_from_buffer: buffer botch (%ld)\n",
1215                         drive->name, rq->sector);
1216                 cdrom_end_request(drive, 0);
1217                 return -1;
1218         }
1219
1220         return 0;
1221 }
1222
1223 /*
1224  * Routine to send a read packet command to the drive.
1225  * This is usually called directly from cdrom_start_read.
1226  * However, for drq_interrupt devices, it is called from an interrupt
1227  * when the drive is ready to accept the command.
1228  */
1229 static ide_startstop_t cdrom_start_read_continuation (ide_drive_t *drive)
1230 {
1231         struct packet_command pc;
1232         struct request *rq = HWGROUP(drive)->rq;
1233         int nsect, sector, nframes, frame, nskip;
1234
1235         /* Number of sectors to transfer. */
1236         nsect = rq->nr_sectors;
1237
1238         /* Starting sector. */
1239         sector = rq->sector;
1240
1241         /* If the requested sector doesn't start on a cdrom block boundary,
1242            we must adjust the start of the transfer so that it does,
1243            and remember to skip the first few sectors.
1244            If the CURRENT_NR_SECTORS field is larger than the size
1245            of the buffer, it will mean that we're to skip a number
1246            of sectors equal to the amount by which CURRENT_NR_SECTORS
1247            is larger than the buffer size. */
1248         nskip = (sector % SECTORS_PER_FRAME);
1249         if (nskip > 0) {
1250                 /* Sanity check... */
1251                 if (rq->current_nr_sectors != (rq->bh->b_size >> SECTOR_BITS) &&
1252                         (rq->sector % CD_FRAMESIZE != 0)) {
1253                         printk ("%s: cdrom_start_read_continuation: buffer botch (%lu)\n",
1254                                 drive->name, rq->current_nr_sectors);
1255                         cdrom_end_request(drive, 0);
1256                         return ide_stopped;
1257                 }
1258                 sector -= nskip;
1259                 nsect += nskip;
1260                 rq->current_nr_sectors += nskip;
1261         }
1262
1263         /* Convert from sectors to cdrom blocks, rounding up the transfer
1264            length if needed. */
1265         nframes = (nsect + SECTORS_PER_FRAME-1) / SECTORS_PER_FRAME;
1266         frame = sector / SECTORS_PER_FRAME;
1267
1268         /* Largest number of frames was can transfer at once is 64k-1. For
1269            some drives we need to limit this even more. */
1270         nframes = MIN (nframes, (CDROM_CONFIG_FLAGS (drive)->limit_nframes) ?
1271                 (65534 / CD_FRAMESIZE) : 65535);
1272
1273         /* Set up the command */
1274         memset (&pc.c, 0, sizeof (pc.c));
1275         pc.c[0] = GPCMD_READ_10;
1276         pc.c[7] = (nframes >> 8);
1277         pc.c[8] = (nframes & 0xff);
1278         put_unaligned(cpu_to_be32(frame), (unsigned int *) &pc.c[2]);
1279         pc.timeout = WAIT_CMD;
1280
1281         /* Send the command to the drive and return. */
1282         return cdrom_transfer_packet_command(drive, &pc, &cdrom_read_intr);
1283 }
1284
1285
1286 #define IDECD_SEEK_THRESHOLD    (1000)                  /* 1000 blocks */
1287 #define IDECD_SEEK_TIMER        (5 * WAIT_MIN_SLEEP)    /* 100 ms */
1288 #define IDECD_SEEK_TIMEOUT     WAIT_CMD                 /* 10 sec */
1289
1290 static ide_startstop_t cdrom_seek_intr (ide_drive_t *drive)
1291 {
1292         struct cdrom_info *info = drive->driver_data;
1293         int stat;
1294         static int retry = 10;
1295         ide_startstop_t startstop;
1296
1297         if (cdrom_decode_status (&startstop, drive, 0, &stat))
1298                 return startstop;
1299         CDROM_CONFIG_FLAGS(drive)->seeking = 1;
1300
1301         if (retry && time_after(jiffies, info->start_seek + IDECD_SEEK_TIMER)) {
1302                 if (--retry == 0) {
1303                         /*
1304                          * this condition is far too common, to bother
1305                          * users about it
1306                          */
1307 #if 0
1308                         printk("%s: disabled DSC seek overlap\n", drive->name);
1309 #endif
1310                         drive->dsc_overlap = 0;
1311                 }
1312         }
1313         return ide_stopped;
1314 }
1315
1316 static ide_startstop_t cdrom_start_seek_continuation (ide_drive_t *drive)
1317 {
1318         struct packet_command pc;
1319         struct request *rq = HWGROUP(drive)->rq;
1320         int sector, frame, nskip;
1321
1322         sector = rq->sector;
1323         nskip = (sector % SECTORS_PER_FRAME);
1324         if (nskip > 0)
1325                 sector -= nskip;
1326         frame = sector / SECTORS_PER_FRAME;
1327
1328         memset (&pc.c, 0, sizeof (pc.c));
1329         pc.c[0] = GPCMD_SEEK;
1330         put_unaligned(cpu_to_be32(frame), (unsigned int *) &pc.c[2]);
1331
1332         pc.timeout = WAIT_CMD;
1333         return cdrom_transfer_packet_command(drive, &pc, &cdrom_seek_intr);
1334 }
1335
1336 static ide_startstop_t cdrom_start_seek (ide_drive_t *drive, unsigned int block)
1337 {
1338         struct cdrom_info *info = drive->driver_data;
1339
1340         info->dma = 0;
1341         info->cmd = 0;
1342         info->start_seek = jiffies;
1343         return cdrom_start_packet_command(drive, 0, cdrom_start_seek_continuation);
1344 }
1345
1346 static inline int cdrom_merge_requests(struct request *rq, struct request *nxt)
1347 {
1348         int ret = 1;
1349
1350         /*
1351          * partitions not really working, but better check anyway...
1352          */
1353         if (rq->cmd == nxt->cmd && rq->rq_dev == nxt->rq_dev) {
1354                 rq->nr_sectors += nxt->nr_sectors;
1355                 rq->hard_nr_sectors += nxt->nr_sectors;
1356                 rq->bhtail->b_reqnext = nxt->bh;
1357                 rq->bhtail = nxt->bhtail;
1358                 list_del(&nxt->queue);
1359                 blkdev_release_request(nxt);
1360                 ret = 0;
1361         }
1362
1363         return ret;
1364 }
1365
1366 /*
1367  * the current request will always be the first one on the list
1368  */
1369 static void cdrom_attempt_remerge(ide_drive_t *drive, struct request *rq)
1370 {
1371         struct list_head *entry;
1372         struct request *nxt;
1373         unsigned long flags;
1374
1375         spin_lock_irqsave(&io_request_lock, flags);
1376
1377         while (1) {
1378                 entry = rq->queue.next;
1379                 if (entry == &drive->queue.queue_head)
1380                         break;
1381
1382                 nxt = blkdev_entry_to_request(entry);
1383                 if (rq->sector + rq->nr_sectors != nxt->sector)
1384                         break;
1385                 else if (rq->nr_sectors + nxt->nr_sectors > SECTORS_MAX)
1386                         break;
1387
1388                 if (cdrom_merge_requests(rq, nxt))
1389                         break;
1390         }
1391
1392         spin_unlock_irqrestore(&io_request_lock, flags);
1393 }
1394
1395 /* Fix up a possibly partially-processed request so that we can
1396    start it over entirely, or even put it back on the request queue. */
1397 static void restore_request (struct request *rq)
1398 {
1399         if (rq->buffer != rq->bh->b_data) {
1400                 int n = (rq->buffer - rq->bh->b_data) / SECTOR_SIZE;
1401                 rq->buffer = rq->bh->b_data;
1402                 rq->nr_sectors += n;
1403                 rq->sector -= n;
1404         }
1405         rq->current_nr_sectors = rq->bh->b_size >> SECTOR_BITS;
1406         rq->hard_nr_sectors = rq->nr_sectors;
1407         rq->hard_sector = rq->sector;
1408 }
1409
1410 /*
1411  * Start a read request from the CD-ROM.
1412  */
1413 static ide_startstop_t cdrom_start_read (ide_drive_t *drive, unsigned int block)
1414 {
1415         struct cdrom_info *info = drive->driver_data;
1416         struct request *rq = HWGROUP(drive)->rq;
1417         int minor = MINOR(rq->rq_dev);
1418
1419         /* If the request is relative to a partition, fix it up to refer to the
1420            absolute address.  */
1421         if (minor & PARTN_MASK) {
1422                 rq->sector = block;
1423                 minor &= ~PARTN_MASK;
1424                 rq->rq_dev = MKDEV(MAJOR(rq->rq_dev), minor);
1425         }
1426
1427         /* We may be retrying this request after an error.  Fix up
1428            any weirdness which might be present in the request packet. */
1429         restore_request(rq);
1430
1431         /* Satisfy whatever we can of this request from our cached sector. */
1432         if (cdrom_read_from_buffer(drive))
1433                 return ide_stopped;
1434
1435         cdrom_attempt_remerge(drive, rq);
1436
1437         /* Clear the local sector buffer. */
1438         info->nsectors_buffered = 0;
1439
1440         /* use dma, if possible. */
1441         if (drive->using_dma && (rq->sector % SECTORS_PER_FRAME == 0) &&
1442                                 (rq->nr_sectors % SECTORS_PER_FRAME == 0))
1443                 info->dma = 1;
1444         else
1445                 info->dma = 0;
1446
1447         info->cmd = READ;
1448         /* Start sending the read request to the drive. */
1449         return cdrom_start_packet_command(drive, 32768, cdrom_start_read_continuation);
1450 }
1451
1452 /****************************************************************************
1453  * Execute all other packet commands.
1454  */
1455
1456 /* Forward declarations. */
1457 static int cdrom_lockdoor(ide_drive_t *drive, int lockflag,
1458                           struct request_sense *sense);
1459
1460 /* Interrupt routine for packet command completion. */
1461 static ide_startstop_t cdrom_pc_intr (ide_drive_t *drive)
1462 {
1463         int ireason, len, stat, thislen;
1464         struct request *rq = HWGROUP(drive)->rq;
1465         struct packet_command *pc = (struct packet_command *)rq->buffer;
1466         ide_startstop_t startstop;
1467         u8 lowcyl = 0, highcyl = 0;
1468
1469         /* Check for errors. */
1470         if (cdrom_decode_status(&startstop, drive, 0, &stat))
1471                 return startstop;
1472
1473         /* Read the interrupt reason and the transfer length. */
1474         ireason = HWIF(drive)->INB(IDE_IREASON_REG);
1475         lowcyl  = HWIF(drive)->INB(IDE_BCOUNTL_REG);
1476         highcyl = HWIF(drive)->INB(IDE_BCOUNTH_REG);
1477
1478         len = lowcyl + (256 * highcyl);
1479
1480         /* If DRQ is clear, the command has completed.
1481            Complain if we still have data left to transfer. */
1482         if ((stat & DRQ_STAT) == 0) {
1483                 /* Some of the trailing request sense fields are optional, and
1484                    some drives don't send them.  Sigh. */
1485                 if (pc->c[0] == GPCMD_REQUEST_SENSE &&
1486                     pc->buflen > 0 &&
1487                     pc->buflen <= 5) {
1488                         while (pc->buflen > 0) {
1489                                 *pc->buffer++ = 0;
1490                                 --pc->buflen;
1491                         }
1492                 }
1493
1494                 if (pc->buflen == 0)
1495                         cdrom_end_request(drive, 1);
1496                 else {
1497                         /* Comment this out, because this always happens 
1498                            right after a reset occurs, and it is annoying to 
1499                            always print expected stuff.  */
1500                         /*
1501                         printk ("%s: cdrom_pc_intr: data underrun %d\n",
1502                                 drive->name, pc->buflen);
1503                         */
1504                         pc->stat = 1;
1505                         cdrom_end_request(drive, 1);
1506                 }
1507                 return ide_stopped;
1508         }
1509
1510         /* Figure out how much data to transfer. */
1511         thislen = pc->buflen;
1512         if (thislen > len) thislen = len;
1513
1514         /* The drive wants to be written to. */
1515         if ((ireason & 3) == 0) {
1516                 /* Transfer the data. */
1517                 HWIF(drive)->atapi_output_bytes(drive, pc->buffer, thislen);
1518
1519                 /* If we haven't moved enough data to satisfy the drive,
1520                    add some padding. */
1521                 while (len > thislen) {
1522                         int dum = 0;
1523                         HWIF(drive)->atapi_output_bytes(drive, &dum, sizeof(dum));
1524                         len -= sizeof(dum);
1525                 }
1526
1527                 /* Keep count of how much data we've moved. */
1528                 pc->buffer += thislen;
1529                 pc->buflen -= thislen;
1530         }
1531
1532         /* Same drill for reading. */
1533         else if ((ireason & 3) == 2) {
1534
1535                 /* Transfer the data. */
1536                 HWIF(drive)->atapi_input_bytes(drive, pc->buffer, thislen);
1537
1538                 /* If we haven't moved enough data to satisfy the drive,
1539                    add some padding. */
1540                 while (len > thislen) {
1541                         int dum = 0;
1542                         HWIF(drive)->atapi_input_bytes(drive, &dum, sizeof(dum));
1543                         len -= sizeof(dum);
1544                 }
1545
1546                 /* Keep count of how much data we've moved. */
1547                 pc->buffer += thislen;
1548                 pc->buflen -= thislen;
1549         } else {
1550                 printk ("%s: cdrom_pc_intr: The drive "
1551                         "appears confused (ireason = 0x%2x)\n",
1552                         drive->name, ireason);
1553                 pc->stat = 1;
1554         }
1555
1556         /* Now we wait for another interrupt. */
1557         ide_set_handler(drive, &cdrom_pc_intr, WAIT_CMD, cdrom_timer_expiry);
1558         return ide_started;
1559 }
1560
1561
1562 static ide_startstop_t cdrom_do_pc_continuation (ide_drive_t *drive)
1563 {
1564         struct request *rq = HWGROUP(drive)->rq;
1565         struct packet_command *pc = (struct packet_command *)rq->buffer;
1566
1567         if (!pc->timeout)
1568                 pc->timeout = WAIT_CMD;
1569
1570         /* Send the command to the drive and return. */
1571         return cdrom_transfer_packet_command(drive, pc, &cdrom_pc_intr);
1572 }
1573
1574
1575 static ide_startstop_t cdrom_do_packet_command (ide_drive_t *drive)
1576 {
1577         int len;
1578         struct request *rq = HWGROUP(drive)->rq;
1579         struct packet_command *pc = (struct packet_command *)rq->buffer;
1580         struct cdrom_info *info = drive->driver_data;
1581
1582         info->dma = 0;
1583         info->cmd = 0;
1584         pc->stat = 0;
1585         len = pc->buflen;
1586
1587         /* Start sending the command to the drive. */
1588         return cdrom_start_packet_command(drive, len, cdrom_do_pc_continuation);
1589 }
1590
1591
1592 /* Sleep for TIME jiffies.
1593    Not to be called from an interrupt handler. */
1594 static
1595 void cdrom_sleep (int time)
1596 {
1597         int sleep = time;
1598
1599         do {
1600                 set_current_state(TASK_INTERRUPTIBLE);
1601                 sleep = schedule_timeout(sleep);
1602         } while (sleep);
1603 }
1604
1605 static
1606 int cdrom_queue_packet_command(ide_drive_t *drive, struct packet_command *pc)
1607 {
1608         struct request_sense sense;
1609         struct request req;
1610         int retries = 10;
1611
1612         if (pc->sense == NULL)
1613                 pc->sense = &sense;
1614
1615         /* Start of retry loop. */
1616         do {
1617                 ide_init_drive_cmd (&req);
1618                 req.cmd = PACKET_COMMAND;
1619                 req.buffer = (char *)pc;
1620                 ide_do_drive_cmd(drive, &req, ide_wait);
1621                 /* FIXME: we should probably abort/retry or something 
1622                  * in case of failure */
1623                 if (pc->stat != 0) {
1624                         /* The request failed.  Retry if it was due to a unit
1625                            attention status
1626                            (usually means media was changed). */
1627                         struct request_sense *reqbuf = pc->sense;
1628
1629                         if (reqbuf->sense_key == UNIT_ATTENTION)
1630                                 cdrom_saw_media_change(drive);
1631                         else if (reqbuf->sense_key == NOT_READY &&
1632                                  reqbuf->asc == 4 && reqbuf->ascq != 4) {
1633                                 /* The drive is in the process of loading
1634                                    a disk.  Retry, but wait a little to give
1635                                    the drive time to complete the load. */
1636                                 cdrom_sleep(2 * HZ);
1637                         } else {
1638                                 /* Otherwise, don't retry. */
1639                                 retries = 0;
1640                         }
1641                         --retries;
1642                 }
1643
1644                 /* End of retry loop. */
1645         } while (pc->stat != 0 && retries >= 0);
1646
1647         /* Return an error if the command failed. */
1648         return pc->stat ? -EIO : 0;
1649 }
1650
1651 /*
1652  * Write handling
1653  */
1654 static inline int cdrom_write_check_ireason(ide_drive_t *drive, int len, int ireason)
1655 {
1656         /* Two notes about IDE interrupt reason here - 0 means that
1657          * the drive wants to receive data from us, 2 means that
1658          * the drive is expecting data from us.
1659          */
1660         ireason &= 3;
1661
1662         if (ireason == 2) {
1663                 /* Whoops... The drive wants to send data. */
1664                 printk("%s: cdrom_write_intr: wrong transfer direction!\n",
1665                         drive->name);
1666
1667                 /* Throw some data at the drive so it doesn't hang
1668                    and quit this request. */
1669                 while (len > 0) {
1670                         int dum = 0;
1671                         HWIF(drive)->atapi_output_bytes(drive, &dum, sizeof(dum));
1672                         len -= sizeof(dum);
1673                 }
1674         } else {
1675                 /* Drive wants a command packet, or invalid ireason... */
1676                 printk("%s: cdrom_write_intr: bad interrupt reason %d\n",
1677                         drive->name, ireason);
1678         }
1679
1680         cdrom_end_request(drive, 0);
1681         return 1;
1682 }
1683
1684 static ide_startstop_t cdrom_write_intr(ide_drive_t *drive)
1685 {
1686         int stat, ireason, len, sectors_to_transfer, uptodate;
1687         struct cdrom_info *info = drive->driver_data;
1688         int i, dma_error = 0, dma = info->dma;
1689         u8 lowcyl = 0, highcyl = 0;
1690         ide_startstop_t startstop;
1691
1692         struct request *rq = HWGROUP(drive)->rq;
1693
1694         /* Check for errors. */
1695         if (dma) {
1696                 info->dma = 0;
1697                 if ((dma_error = HWIF(drive)->ide_dma_end(drive))) {
1698                         printk("ide-cd: write dma error\n");
1699                         HWIF(drive)->ide_dma_off(drive);
1700                 }
1701         }
1702
1703         if (cdrom_decode_status(&startstop, drive, 0, &stat)) {
1704                 printk("ide-cd: write_intr decode_status bad\n");
1705                 return startstop;
1706         }
1707  
1708         /*
1709          * using dma, transfer is complete now
1710          */
1711         if (dma) {
1712                 if (dma_error)
1713                         return DRIVER(drive)->error(drive, "dma error", stat);
1714
1715                 rq = HWGROUP(drive)->rq;
1716                 for (i = rq->nr_sectors; i > 0;) {
1717                         i -= rq->current_nr_sectors;
1718                         ide_cdrom_end_request(drive, 1);
1719                 }
1720                 return ide_stopped;
1721         }
1722
1723         /* Read the interrupt reason and the transfer length. */
1724         ireason = HWIF(drive)->INB(IDE_IREASON_REG);
1725         lowcyl  = HWIF(drive)->INB(IDE_BCOUNTL_REG);
1726         highcyl = HWIF(drive)->INB(IDE_BCOUNTH_REG);
1727
1728         len = lowcyl + (256 * highcyl);
1729
1730         /* If DRQ is clear, the command has completed. */
1731         if ((stat & DRQ_STAT) == 0) {
1732                 /* If we're not done writing, complain.
1733                  * Otherwise, complete the command normally.
1734                  */
1735                 uptodate = 1;
1736                 if (rq->current_nr_sectors > 0) {
1737                         printk("%s: write_intr: data underrun (%ld blocks)\n",
1738                         drive->name, rq->current_nr_sectors);
1739                         uptodate = 0;
1740                 }
1741                 cdrom_end_request(drive, uptodate);
1742                 return ide_stopped;
1743         }
1744
1745         /* Check that the drive is expecting to do the same thing we are. */
1746         if (ireason & 3)
1747                 if (cdrom_write_check_ireason(drive, len, ireason))
1748                         return ide_stopped;
1749
1750         sectors_to_transfer = len / SECTOR_SIZE;
1751
1752         /*
1753          * now loop and write out the data
1754          */
1755         while (sectors_to_transfer > 0) {
1756                 int this_transfer;
1757
1758                 if (!rq->current_nr_sectors) {
1759                         printk("ide-cd: write_intr: oops\n");
1760                         break;
1761                 }
1762
1763                 /*
1764                  * Figure out how many sectors we can transfer
1765                  */
1766                 this_transfer = MIN(sectors_to_transfer,rq->current_nr_sectors);
1767
1768                 while (this_transfer > 0) {
1769                         HWIF(drive)->atapi_output_bytes(drive, rq->buffer, SECTOR_SIZE);
1770                         rq->buffer += SECTOR_SIZE;
1771                         --rq->nr_sectors;
1772                         --rq->current_nr_sectors;
1773                         ++rq->sector;
1774                         --this_transfer;
1775                         --sectors_to_transfer;
1776                 }
1777
1778                 /*
1779                  * current buffer complete, move on
1780                  */
1781                 if (rq->current_nr_sectors == 0 && rq->nr_sectors)
1782                         cdrom_end_request(drive, 1);
1783         }
1784
1785         /* re-arm handler */
1786         ide_set_handler(drive, &cdrom_write_intr, 5 * WAIT_CMD, NULL);
1787         return ide_started;
1788 }
1789
1790 static ide_startstop_t cdrom_start_write_cont(ide_drive_t *drive)
1791 {
1792         struct packet_command pc;       /* packet_command_t pc; */
1793         struct request *rq = HWGROUP(drive)->rq;
1794         unsigned nframes, frame;
1795
1796         nframes = rq->nr_sectors >> 2;
1797         frame = rq->sector >> 2;
1798
1799         memset(&pc.c, 0, sizeof(pc.c));
1800         /*
1801          * we might as well use WRITE_12, but none of the device I have
1802          * support the streaming feature anyway, so who cares.
1803          */
1804         pc.c[0] = GPCMD_WRITE_10;
1805 #if 0   /* the immediate bit */
1806         pc.c[1] = 1 << 3;
1807 #endif
1808         pc.c[7] = (nframes >> 8) & 0xff;
1809         pc.c[8] = nframes & 0xff;
1810         put_unaligned(cpu_to_be32(frame), (unsigned int *)&pc.c[2]);
1811         pc.timeout = 2 * WAIT_CMD;
1812
1813         return cdrom_transfer_packet_command(drive, &pc, cdrom_write_intr);
1814 }
1815
1816 static ide_startstop_t cdrom_start_write(ide_drive_t *drive, struct request *rq)
1817 {
1818         struct cdrom_info *info = drive->driver_data;
1819
1820         /*
1821          * writes *must* be 2kB frame aligned
1822          */
1823         if ((rq->nr_sectors & 3) || (rq->sector & 3)) {
1824                 cdrom_end_request(drive, 0);
1825                 return ide_stopped;
1826         }
1827
1828         /*
1829          * for dvd-ram and such media, it's a really big deal to get
1830          * big writes all the time. so scour the queue and attempt to
1831          * remerge requests, often the plugging will not have had time
1832          * to do this properly
1833          */
1834         cdrom_attempt_remerge(drive, rq);
1835
1836         info->nsectors_buffered = 0;
1837
1838         /* use dma, if possible. we don't need to check more, since we
1839          * know that the transfer is always (at least!) 2KB aligned */
1840         info->dma = drive->using_dma ? 1 : 0;
1841         info->cmd = WRITE;
1842
1843         /* Start sending the read request to the drive. */
1844         return cdrom_start_packet_command(drive, 32768, cdrom_start_write_cont);
1845 }
1846
1847 /****************************************************************************
1848  * cdrom driver request routine.
1849  */
1850 static ide_startstop_t
1851 ide_do_rw_cdrom (ide_drive_t *drive, struct request *rq, unsigned long block)
1852 {
1853         ide_startstop_t action;
1854         struct cdrom_info *info = drive->driver_data;
1855
1856         switch (rq->cmd) {
1857                 case WRITE:
1858                 case READ: {
1859                         if (CDROM_CONFIG_FLAGS(drive)->seeking) {
1860                                 int stat = HWIF(drive)->INB(IDE_STATUS_REG);
1861
1862                                 if ((stat & SEEK_STAT) != SEEK_STAT) {
1863                                         if (time_before(jiffies, info->start_seek + IDECD_SEEK_TIMEOUT)) {
1864                                                 ide_stall_queue(drive, IDECD_SEEK_TIMER);
1865                                                 return ide_stopped;
1866                                         }
1867                                         printk ("%s: DSC timeout\n", drive->name);
1868                                 }
1869                                 CDROM_CONFIG_FLAGS(drive)->seeking = 0;
1870                         }
1871                         if (IDE_LARGE_SEEK(info->last_block, block, IDECD_SEEK_THRESHOLD) && drive->dsc_overlap)
1872                                 action = cdrom_start_seek(drive, block);
1873                         else {
1874                                 if (rq_data_dir(rq) == READ)
1875                                         action = cdrom_start_read(drive, block);
1876                                 else
1877                                         action = cdrom_start_write(drive, rq);
1878                         }
1879                         info->last_block = block;
1880                         return action;
1881                 }
1882
1883                 case PACKET_COMMAND:
1884                 case REQUEST_SENSE_COMMAND: {
1885                         return cdrom_do_packet_command(drive);
1886                 }
1887
1888                 case RESET_DRIVE_COMMAND: {
1889                         cdrom_end_request(drive, 1);
1890                         return ide_do_reset(drive);
1891                 }
1892
1893                 default: {
1894                         printk("ide-cd: bad cmd %d\n", rq->cmd);
1895                         cdrom_end_request(drive, 0);
1896                         return ide_stopped;
1897                 }
1898         }
1899 }
1900
1901
1902
1903 /****************************************************************************
1904  * Ioctl handling.
1905  *
1906  * Routines which queue packet commands take as a final argument a pointer
1907  * to a request_sense struct.  If execution of the command results
1908  * in an error with a CHECK CONDITION status, this structure will be filled
1909  * with the results of the subsequent request sense command.  The pointer
1910  * can also be NULL, in which case no sense information is returned.
1911  */
1912
1913 #if ! STANDARD_ATAPI
1914 static inline
1915 int bin2bcd (int x)
1916 {
1917         return (x%10) | ((x/10) << 4);
1918 }
1919
1920
1921 static inline
1922 int bcd2bin (int x)
1923 {
1924         return (x >> 4) * 10 + (x & 0x0f);
1925 }
1926
1927 static
1928 void msf_from_bcd (struct atapi_msf *msf)
1929 {
1930         msf->minute = bcd2bin (msf->minute);
1931         msf->second = bcd2bin (msf->second);
1932         msf->frame  = bcd2bin (msf->frame);
1933 }
1934
1935 #endif /* not STANDARD_ATAPI */
1936
1937
1938 static inline
1939 void lba_to_msf (int lba, byte *m, byte *s, byte *f)
1940 {
1941         lba += CD_MSF_OFFSET;
1942         lba &= 0xffffff;  /* negative lbas use only 24 bits */
1943         *m = lba / (CD_SECS * CD_FRAMES);
1944         lba %= (CD_SECS * CD_FRAMES);
1945         *s = lba / CD_FRAMES;
1946         *f = lba % CD_FRAMES;
1947 }
1948
1949
1950 static inline
1951 int msf_to_lba (byte m, byte s, byte f)
1952 {
1953         return (((m * CD_SECS) + s) * CD_FRAMES + f) - CD_MSF_OFFSET;
1954 }
1955
1956 static int cdrom_check_status(ide_drive_t *drive, struct request_sense *sense)
1957 {
1958         struct packet_command pc;
1959         struct cdrom_info *info = drive->driver_data;
1960         struct cdrom_device_info *cdi = &info->devinfo;
1961
1962         memset(&pc, 0, sizeof(pc));
1963         pc.sense = sense;
1964
1965         pc.c[0] = GPCMD_TEST_UNIT_READY;
1966
1967 #if ! STANDARD_ATAPI
1968         /* the Sanyo 3 CD changer uses byte 7 of TEST_UNIT_READY to 
1969            switch CDs instead of supporting the LOAD_UNLOAD opcode   */
1970
1971         pc.c[7] = cdi->sanyo_slot % 3;
1972 #endif /* not STANDARD_ATAPI */
1973
1974         return cdrom_queue_packet_command(drive, &pc);
1975 }
1976
1977
1978 /* Lock the door if LOCKFLAG is nonzero; unlock it otherwise. */
1979 static int
1980 cdrom_lockdoor(ide_drive_t *drive, int lockflag, struct request_sense *sense)
1981 {
1982         struct request_sense my_sense;
1983         struct packet_command pc;
1984         int stat;
1985
1986         if (sense == NULL)
1987                 sense = &my_sense;
1988
1989         /* If the drive cannot lock the door, just pretend. */
1990         if (CDROM_CONFIG_FLAGS(drive)->no_doorlock) {
1991                 stat = 0;
1992         } else {
1993                 memset(&pc, 0, sizeof(pc));
1994                 pc.sense = sense;
1995                 pc.c[0] = GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL;
1996                 pc.c[4] = lockflag ? 1 : 0;
1997                 stat = cdrom_queue_packet_command(drive, &pc);
1998         }
1999
2000         /* If we got an illegal field error, the drive
2001            probably cannot lock the door. */
2002         if (stat != 0 &&
2003             sense->sense_key == ILLEGAL_REQUEST &&
2004             (sense->asc == 0x24 || sense->asc == 0x20)) {
2005                 printk ("%s: door locking not supported\n",
2006                         drive->name);
2007                 CDROM_CONFIG_FLAGS(drive)->no_doorlock = 1;
2008                 stat = 0;
2009         }
2010         
2011         /* no medium, that's alright. */
2012         if (stat != 0 && sense->sense_key == NOT_READY && sense->asc == 0x3a)
2013                 stat = 0;
2014
2015         if (stat == 0)
2016                 CDROM_STATE_FLAGS(drive)->door_locked = lockflag;
2017
2018         return stat;
2019 }
2020
2021
2022 /* Eject the disk if EJECTFLAG is 0.
2023    If EJECTFLAG is 1, try to reload the disk. */
2024 static int cdrom_eject(ide_drive_t *drive, int ejectflag,
2025                        struct request_sense *sense)
2026 {
2027         struct packet_command pc;
2028
2029         if (CDROM_CONFIG_FLAGS(drive)->no_eject && !ejectflag)
2030                 return -EDRIVE_CANT_DO_THIS;
2031         
2032         /* reload fails on some drives, if the tray is locked */
2033         if (CDROM_STATE_FLAGS(drive)->door_locked && ejectflag)
2034                 return 0;
2035
2036         memset(&pc, 0, sizeof (pc));
2037         pc.sense = sense;
2038
2039         pc.c[0] = GPCMD_START_STOP_UNIT;
2040         pc.c[4] = 0x02 + (ejectflag != 0);
2041         return cdrom_queue_packet_command(drive, &pc);
2042 }
2043
2044 static int cdrom_read_capacity(ide_drive_t *drive, unsigned long *capacity,
2045                                struct request_sense *sense)
2046 {
2047         struct {
2048                 __u32 lba;
2049                 __u32 blocklen;
2050         } capbuf;
2051
2052         int stat;
2053         struct packet_command pc;
2054
2055         memset(&pc, 0, sizeof(pc));
2056         pc.sense = sense;
2057
2058         pc.c[0] = GPCMD_READ_CDVD_CAPACITY;
2059         pc.buffer = (char *)&capbuf;
2060         pc.buflen = sizeof(capbuf);
2061
2062         stat = cdrom_queue_packet_command(drive, &pc);
2063         if (stat == 0)
2064                 *capacity = 1 + be32_to_cpu(capbuf.lba);
2065
2066         return stat;
2067 }
2068
2069 static int cdrom_read_tocentry(ide_drive_t *drive, int trackno, int msf_flag,
2070                                 int format, char *buf, int buflen,
2071                                 struct request_sense *sense)
2072 {
2073         struct packet_command pc;
2074
2075         memset(&pc, 0, sizeof(pc));
2076         pc.sense = sense;
2077
2078         pc.buffer =  buf;
2079         pc.buflen = buflen;
2080         pc.quiet = 1;
2081         pc.c[0] = GPCMD_READ_TOC_PMA_ATIP;
2082         pc.c[6] = trackno;
2083         pc.c[7] = (buflen >> 8);
2084         pc.c[8] = (buflen & 0xff);
2085         pc.c[9] = (format << 6);
2086
2087         if (msf_flag)
2088                 pc.c[1] = 2;
2089
2090         return cdrom_queue_packet_command(drive, &pc);
2091 }
2092
2093
2094 /* Try to read the entire TOC for the disk into our internal buffer. */
2095 static int cdrom_read_toc(ide_drive_t *drive, struct request_sense *sense)
2096 {
2097         int minor, stat, ntracks, i;
2098         kdev_t dev;
2099         struct cdrom_info *info = drive->driver_data;
2100         struct atapi_toc *toc = info->toc;
2101         struct {
2102                 struct atapi_toc_header hdr;
2103                 struct atapi_toc_entry  ent;
2104         } ms_tmp;
2105
2106         if (toc == NULL) {
2107                 /* Try to allocate space. */
2108                 toc = (struct atapi_toc *) kmalloc (sizeof (struct atapi_toc),
2109                                                     GFP_KERNEL);
2110                 info->toc = toc;
2111                 if (toc == NULL) {
2112                         printk ("%s: No cdrom TOC buffer!\n", drive->name);
2113                         return -ENOMEM;
2114                 }
2115         }
2116
2117         /* Check to see if the existing data is still valid.
2118            If it is, just return. */
2119         (void) cdrom_check_status(drive, sense);
2120
2121         if (CDROM_STATE_FLAGS(drive)->toc_valid)
2122                 return 0;
2123
2124         /* First read just the header, so we know how long the TOC is. */
2125         stat = cdrom_read_tocentry(drive, 0, 1, 0, (char *) &toc->hdr,
2126                                     sizeof(struct atapi_toc_header), sense);
2127         if (stat) return stat;
2128
2129 #if ! STANDARD_ATAPI
2130         if (CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd) {
2131                 toc->hdr.first_track = bcd2bin(toc->hdr.first_track);
2132                 toc->hdr.last_track  = bcd2bin(toc->hdr.last_track);
2133         }
2134 #endif  /* not STANDARD_ATAPI */
2135
2136         ntracks = toc->hdr.last_track - toc->hdr.first_track + 1;
2137         if (ntracks <= 0)
2138                 return -EIO;
2139         if (ntracks > MAX_TRACKS)
2140                 ntracks = MAX_TRACKS;
2141
2142         /* Now read the whole schmeer. */
2143         stat = cdrom_read_tocentry(drive, toc->hdr.first_track, 1, 0,
2144                                   (char *)&toc->hdr,
2145                                    sizeof(struct atapi_toc_header) +
2146                                    (ntracks + 1) *
2147                                    sizeof(struct atapi_toc_entry), sense);
2148
2149         if (stat && toc->hdr.first_track > 1) {
2150                 /* Cds with CDI tracks only don't have any TOC entries,
2151                    despite of this the returned values are
2152                    first_track == last_track = number of CDI tracks + 1,
2153                    so that this case is indistinguishable from the same
2154                    layout plus an additional audio track.
2155                    If we get an error for the regular case, we assume
2156                    a CDI without additional audio tracks. In this case
2157                    the readable TOC is empty (CDI tracks are not included)
2158                    and only holds the Leadout entry. Heiko Eißfeldt */
2159                 ntracks = 0;
2160                 stat = cdrom_read_tocentry(drive, CDROM_LEADOUT, 1, 0,
2161                                            (char *)&toc->hdr,
2162                                            sizeof(struct atapi_toc_header) +
2163                                            (ntracks + 1) *
2164                                            sizeof(struct atapi_toc_entry),
2165                                            sense);
2166                 if (stat) {
2167                         return stat;
2168                 }
2169 #if ! STANDARD_ATAPI
2170                 if (CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd) {
2171                         toc->hdr.first_track = bin2bcd(CDROM_LEADOUT);
2172                         toc->hdr.last_track = bin2bcd(CDROM_LEADOUT);
2173                 } else
2174 #endif  /* not STANDARD_ATAPI */
2175                 {
2176                         toc->hdr.first_track = CDROM_LEADOUT;
2177                         toc->hdr.last_track = CDROM_LEADOUT;
2178                 }
2179         }
2180
2181         if (stat)
2182                 return stat;
2183
2184         toc->hdr.toc_length = ntohs (toc->hdr.toc_length);
2185
2186 #if ! STANDARD_ATAPI
2187         if (CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd) {
2188                 toc->hdr.first_track = bcd2bin(toc->hdr.first_track);
2189                 toc->hdr.last_track  = bcd2bin(toc->hdr.last_track);
2190         }
2191 #endif  /* not STANDARD_ATAPI */
2192
2193         for (i=0; i<=ntracks; i++) {
2194 #if ! STANDARD_ATAPI
2195                 if (CDROM_CONFIG_FLAGS(drive)->tocaddr_as_bcd) {
2196                         if (CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd)
2197                                 toc->ent[i].track = bcd2bin(toc->ent[i].track);
2198                         msf_from_bcd(&toc->ent[i].addr.msf);
2199                 }
2200 #endif  /* not STANDARD_ATAPI */
2201                 toc->ent[i].addr.lba = msf_to_lba (toc->ent[i].addr.msf.minute,
2202                                                    toc->ent[i].addr.msf.second,
2203                                                    toc->ent[i].addr.msf.frame);
2204         }
2205
2206         /* Read the multisession information. */
2207         if (toc->hdr.first_track != CDROM_LEADOUT) {
2208                 /* Read the multisession information. */
2209                 stat = cdrom_read_tocentry(drive, 0, 0, 1, (char *)&ms_tmp,
2210                                            sizeof(ms_tmp), sense);
2211                 if (stat) return stat;
2212         
2213                 toc->last_session_lba = be32_to_cpu(ms_tmp.ent.addr.lba);
2214         } else {
2215                 ms_tmp.hdr.first_track = ms_tmp.hdr.last_track = CDROM_LEADOUT;
2216                 toc->last_session_lba = msf_to_lba(0, 2, 0); /* 0m 2s 0f */
2217         }
2218
2219 #if ! STANDARD_ATAPI
2220         if (CDROM_CONFIG_FLAGS(drive)->tocaddr_as_bcd) {
2221                 /* Re-read multisession information using MSF format */
2222                 stat = cdrom_read_tocentry(drive, 0, 1, 1, (char *)&ms_tmp,
2223                                            sizeof(ms_tmp), sense);
2224                 if (stat)
2225                         return stat;
2226
2227                 msf_from_bcd (&ms_tmp.ent.addr.msf);
2228                 toc->last_session_lba = msf_to_lba(ms_tmp.ent.addr.msf.minute,
2229                                                    ms_tmp.ent.addr.msf.second,
2230                                                    ms_tmp.ent.addr.msf.frame);
2231         }
2232 #endif  /* not STANDARD_ATAPI */
2233
2234         toc->xa_flag = (ms_tmp.hdr.first_track != ms_tmp.hdr.last_track);
2235
2236         /* Now try to get the total cdrom capacity. */
2237         minor = (drive->select.b.unit) << PARTN_BITS;
2238         dev = MKDEV(HWIF(drive)->major, minor);
2239         stat = cdrom_get_last_written(dev, &toc->capacity);
2240         if (stat || !toc->capacity)
2241                 stat = cdrom_read_capacity(drive, &toc->capacity, sense);
2242         if (stat)
2243                 toc->capacity = 0x1fffff;
2244
2245         HWIF(drive)->gd->sizes[drive->select.b.unit << PARTN_BITS] = (toc->capacity * SECTORS_PER_FRAME) >> (BLOCK_SIZE_BITS - 9);
2246         drive->part[0].nr_sects = toc->capacity * SECTORS_PER_FRAME;
2247
2248         /* Remember that we've read this stuff. */
2249         CDROM_STATE_FLAGS(drive)->toc_valid = 1;
2250
2251         return 0;
2252 }
2253
2254
2255 static int cdrom_read_subchannel(ide_drive_t *drive, int format, char *buf,
2256                                  int buflen, struct request_sense *sense)
2257 {
2258         struct packet_command pc;
2259
2260         memset(&pc, 0, sizeof(pc));
2261         pc.sense = sense;
2262
2263         pc.buffer = buf;
2264         pc.buflen = buflen;
2265         pc.c[0] = GPCMD_READ_SUBCHANNEL;
2266         pc.c[1] = 2;     /* MSF addressing */
2267         pc.c[2] = 0x40;  /* request subQ data */
2268         pc.c[3] = format;
2269         pc.c[7] = (buflen >> 8);
2270         pc.c[8] = (buflen & 0xff);
2271         return cdrom_queue_packet_command(drive, &pc);
2272 }
2273
2274 /* ATAPI cdrom drives are free to select the speed you request or any slower
2275    rate :-( Requesting too fast a speed will _not_ produce an error. */
2276 static int cdrom_select_speed(ide_drive_t *drive, int speed,
2277                               struct request_sense *sense)
2278 {
2279         struct packet_command pc;
2280         memset(&pc, 0, sizeof(pc));
2281         pc.sense = sense;
2282
2283         if (speed == 0)
2284                 speed = 0xffff; /* set to max */
2285         else
2286                 speed *= 177;   /* Nx to kbytes/s */
2287
2288         pc.c[0] = GPCMD_SET_SPEED;
2289         /* Read Drive speed in kbytes/second MSB */
2290         pc.c[2] = (speed >> 8) & 0xff;  
2291         /* Read Drive speed in kbytes/second LSB */
2292         pc.c[3] = speed & 0xff;
2293         if (CDROM_CONFIG_FLAGS(drive)->cd_r ||
2294             CDROM_CONFIG_FLAGS(drive)->cd_rw ||
2295             CDROM_CONFIG_FLAGS(drive)->dvd_r) {
2296                 /* Write Drive speed in kbytes/second MSB */
2297                 pc.c[4] = (speed >> 8) & 0xff;
2298                 /* Write Drive speed in kbytes/second LSB */
2299                 pc.c[5] = speed & 0xff;
2300        }
2301
2302         return cdrom_queue_packet_command(drive, &pc);
2303 }
2304
2305 static int cdrom_play_audio(ide_drive_t *drive, int lba_start, int lba_end)
2306 {
2307         struct request_sense sense;
2308         struct packet_command pc;
2309
2310         memset(&pc, 0, sizeof (pc));
2311         pc.sense = &sense;
2312
2313         pc.c[0] = GPCMD_PLAY_AUDIO_MSF;
2314         lba_to_msf(lba_start, &pc.c[3], &pc.c[4], &pc.c[5]);
2315         lba_to_msf(lba_end-1, &pc.c[6], &pc.c[7], &pc.c[8]);
2316
2317         return cdrom_queue_packet_command(drive, &pc);
2318 }
2319
2320 static int cdrom_get_toc_entry(ide_drive_t *drive, int track,
2321                                 struct atapi_toc_entry **ent)
2322 {
2323         struct cdrom_info *info = drive->driver_data;
2324         struct atapi_toc *toc = info->toc;
2325         int ntracks;
2326
2327         /*
2328          * don't serve cached data, if the toc isn't valid
2329          */
2330         if (!CDROM_STATE_FLAGS(drive)->toc_valid)
2331                 return -EINVAL;
2332
2333         /* Check validity of requested track number. */
2334         ntracks = toc->hdr.last_track - toc->hdr.first_track + 1;
2335         if (toc->hdr.first_track == CDROM_LEADOUT) ntracks = 0;
2336         if (track == CDROM_LEADOUT)
2337                 *ent = &toc->ent[ntracks];
2338         else if (track < toc->hdr.first_track ||
2339                  track > toc->hdr.last_track)
2340                 return -EINVAL;
2341         else
2342                 *ent = &toc->ent[track - toc->hdr.first_track];
2343
2344         return 0;
2345 }
2346
2347 /* the generic packet interface to cdrom.c */
2348 static int ide_cdrom_packet(struct cdrom_device_info *cdi,
2349                             struct cdrom_generic_command *cgc)
2350 {
2351         struct packet_command pc;
2352         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2353
2354         if (cgc->timeout <= 0)
2355                 cgc->timeout = WAIT_CMD;
2356
2357         /* here we queue the commands from the uniform CD-ROM
2358            layer. the packet must be complete, as we do not
2359            touch it at all. */
2360         memset(&pc, 0, sizeof(pc));
2361         if (cgc->sense)
2362                 memset(cgc->sense, 0, sizeof(struct request_sense));
2363         memcpy(pc.c, cgc->cmd, CDROM_PACKET_SIZE);
2364         pc.buffer = cgc->buffer;
2365         pc.buflen = cgc->buflen;
2366         pc.quiet = cgc->quiet;
2367         pc.timeout = cgc->timeout;
2368         pc.sense = cgc->sense;
2369         return cgc->stat = cdrom_queue_packet_command(drive, &pc);
2370 }
2371
2372 static
2373 int ide_cdrom_dev_ioctl (struct cdrom_device_info *cdi,
2374                          unsigned int cmd, unsigned long arg)
2375 {
2376         struct cdrom_generic_command cgc;
2377         char buffer[16];
2378         int stat;
2379
2380         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
2381
2382         /* These will be moved into the Uniform layer shortly... */
2383         switch (cmd) {
2384         case CDROMSETSPINDOWN: {
2385                 char spindown;
2386  
2387                 if (copy_from_user(&spindown, (void *) arg, sizeof(char)))
2388                         return -EFAULT;
2389  
2390                 if ((stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0)))
2391                         return stat;
2392
2393                 buffer[11] = (buffer[11] & 0xf0) | (spindown & 0x0f);
2394
2395                 return cdrom_mode_select(cdi, &cgc);
2396         } 
2397  
2398         case CDROMGETSPINDOWN: {
2399                 char spindown;
2400  
2401                 if ((stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0)))
2402                         return stat;
2403  
2404                 spindown = buffer[11] & 0x0f;
2405  
2406                 if (copy_to_user((void *) arg, &spindown, sizeof (char)))
2407                         return -EFAULT;
2408  
2409                 return 0;
2410         }
2411   
2412         default:
2413                 return -EINVAL;
2414         }
2415
2416 }
2417
2418 static
2419 int ide_cdrom_audio_ioctl (struct cdrom_device_info *cdi,
2420                            unsigned int cmd, void *arg)
2421                            
2422 {
2423         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2424         struct cdrom_info *info = drive->driver_data;
2425         int stat;
2426
2427         switch (cmd) {
2428         /*
2429          * emulate PLAY_AUDIO_TI command with PLAY_AUDIO_10, since
2430          * atapi doesn't support it
2431          */
2432         case CDROMPLAYTRKIND: {
2433                 unsigned long lba_start, lba_end;
2434                 struct cdrom_ti *ti = (struct cdrom_ti *)arg;
2435                 struct atapi_toc_entry *first_toc, *last_toc;
2436
2437                 stat = cdrom_get_toc_entry(drive, ti->cdti_trk0, &first_toc);
2438                 if (stat)
2439                         return stat;
2440
2441                 stat = cdrom_get_toc_entry(drive, ti->cdti_trk1, &last_toc);
2442                 if (stat)
2443                         return stat;
2444
2445                 if (ti->cdti_trk1 != CDROM_LEADOUT)
2446                         ++last_toc;
2447                 lba_start = first_toc->addr.lba;
2448                 lba_end   = last_toc->addr.lba;
2449
2450                 if (lba_end <= lba_start)
2451                         return -EINVAL;
2452
2453                 return cdrom_play_audio(drive, lba_start, lba_end);
2454         }
2455
2456         case CDROMREADTOCHDR: {
2457                 struct cdrom_tochdr *tochdr = (struct cdrom_tochdr *) arg;
2458                 struct atapi_toc *toc;
2459
2460                 /* Make sure our saved TOC is valid. */
2461                 stat = cdrom_read_toc(drive, NULL);
2462                 if (stat) return stat;
2463
2464                 toc = info->toc;
2465                 tochdr->cdth_trk0 = toc->hdr.first_track;
2466                 tochdr->cdth_trk1 = toc->hdr.last_track;
2467
2468                 return 0;
2469         }
2470
2471         case CDROMREADTOCENTRY: {
2472                 struct cdrom_tocentry *tocentry = (struct cdrom_tocentry*) arg;
2473                 struct atapi_toc_entry *toce;
2474
2475                 stat = cdrom_get_toc_entry(drive, tocentry->cdte_track, &toce);
2476                 if (stat) return stat;
2477
2478                 tocentry->cdte_ctrl = toce->control;
2479                 tocentry->cdte_adr  = toce->adr;
2480                 if (tocentry->cdte_format == CDROM_MSF) {
2481                         lba_to_msf (toce->addr.lba,
2482                                    &tocentry->cdte_addr.msf.minute,
2483                                    &tocentry->cdte_addr.msf.second,
2484                                    &tocentry->cdte_addr.msf.frame);
2485                 } else
2486                         tocentry->cdte_addr.lba = toce->addr.lba;
2487
2488                 return 0;
2489         }
2490
2491         default:
2492                 return -EINVAL;
2493         }
2494 }
2495
2496 static
2497 int ide_cdrom_reset (struct cdrom_device_info *cdi)
2498 {
2499         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2500         struct request_sense sense;
2501         struct request req;
2502         int ret;
2503
2504         ide_init_drive_cmd (&req);
2505         req.cmd = RESET_DRIVE_COMMAND;
2506         ret = ide_do_drive_cmd(drive, &req, ide_wait);
2507
2508         /*
2509          * A reset will unlock the door. If it was previously locked,
2510          * lock it again.
2511          */
2512         if (CDROM_STATE_FLAGS(drive)->door_locked)
2513                 (void) cdrom_lockdoor(drive, 1, &sense);
2514
2515         return ret;
2516 }
2517
2518
2519 static
2520 int ide_cdrom_tray_move (struct cdrom_device_info *cdi, int position)
2521 {
2522         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2523         struct request_sense sense;
2524
2525         if (position) {
2526                 int stat = cdrom_lockdoor(drive, 0, &sense);
2527                 if (stat) return stat;
2528         }
2529
2530         return cdrom_eject(drive, !position, &sense);
2531 }
2532
2533 static
2534 int ide_cdrom_lock_door (struct cdrom_device_info *cdi, int lock)
2535 {
2536         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2537         return cdrom_lockdoor(drive, lock, NULL);
2538 }
2539
2540 static
2541 int ide_cdrom_select_speed (struct cdrom_device_info *cdi, int speed)
2542 {
2543         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2544         struct request_sense sense;
2545         int stat;
2546
2547         if ((stat = cdrom_select_speed(drive, speed, &sense)) < 0)
2548                 return stat;
2549
2550         cdi->speed = CDROM_STATE_FLAGS(drive)->current_speed;
2551         return 0;
2552 }
2553
2554 static
2555 int ide_cdrom_drive_status (struct cdrom_device_info *cdi, int slot_nr)
2556 {
2557         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2558
2559         if (slot_nr == CDSL_CURRENT) {
2560                 struct request_sense sense;
2561                 int stat = cdrom_check_status(drive, &sense);
2562                 if (stat == 0 || sense.sense_key == UNIT_ATTENTION)
2563                         return CDS_DISC_OK;
2564
2565                 if (sense.sense_key == NOT_READY && sense.asc == 0x04 &&
2566                     sense.ascq == 0x04)
2567                         return CDS_DISC_OK;
2568
2569
2570                 /*
2571                  * If not using Mt Fuji extended media tray reports,
2572                  * just return TRAY_OPEN since ATAPI doesn't provide
2573                  * any other way to detect this...
2574                  */
2575                 if (sense.sense_key == NOT_READY) {
2576                         if (sense.asc == 0x3a && sense.ascq == 1)
2577                                 return CDS_NO_DISC;
2578                         else
2579                                 return CDS_TRAY_OPEN;
2580                 }
2581
2582                 return CDS_DRIVE_NOT_READY;
2583         }
2584         return -EINVAL;
2585 }
2586
2587 static
2588 int ide_cdrom_get_last_session (struct cdrom_device_info *cdi,
2589                                 struct cdrom_multisession *ms_info)
2590 {
2591         struct atapi_toc *toc;
2592         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2593         struct cdrom_info *info = drive->driver_data;
2594         struct request_sense sense;
2595         int ret;
2596
2597         if (!CDROM_STATE_FLAGS(drive)->toc_valid || info->toc == NULL)
2598                 if ((ret = cdrom_read_toc(drive, &sense)))
2599                         return ret;
2600
2601         toc = info->toc;
2602         ms_info->addr.lba = toc->last_session_lba;
2603         ms_info->xa_flag = toc->xa_flag;
2604
2605         return 0;
2606 }
2607
2608 static
2609 int ide_cdrom_get_mcn (struct cdrom_device_info *cdi,
2610                        struct cdrom_mcn *mcn_info)
2611 {
2612         int stat;
2613         char mcnbuf[24];
2614         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2615
2616 /* get MCN */
2617         if ((stat = cdrom_read_subchannel(drive, 2, mcnbuf, sizeof (mcnbuf), NULL)))
2618                 return stat;
2619
2620         memcpy (mcn_info->medium_catalog_number, mcnbuf+9,
2621                 sizeof (mcn_info->medium_catalog_number)-1);
2622         mcn_info->medium_catalog_number[sizeof (mcn_info->medium_catalog_number)-1]
2623                 = '\0';
2624
2625         return 0;
2626 }
2627
2628
2629
2630 /****************************************************************************
2631  * Other driver requests (open, close, check media change).
2632  */
2633
2634 static
2635 int ide_cdrom_check_media_change_real (struct cdrom_device_info *cdi,
2636                                        int slot_nr)
2637 {
2638         ide_drive_t *drive = (ide_drive_t*) cdi->handle;
2639         int retval;
2640         
2641         if (slot_nr == CDSL_CURRENT) {
2642                 (void) cdrom_check_status(drive, NULL);
2643                 retval = CDROM_STATE_FLAGS(drive)->media_changed;
2644                 CDROM_STATE_FLAGS(drive)->media_changed = 0;
2645                 return retval;
2646         } else {
2647                 return -EINVAL;
2648         }
2649 }
2650
2651
2652 static
2653 int ide_cdrom_open_real (struct cdrom_device_info *cdi, int purpose)
2654 {
2655         return 0;
2656 }
2657
2658
2659 /*
2660  * Close down the device.  Invalidate all cached blocks.
2661  */
2662
2663 static
2664 void ide_cdrom_release_real (struct cdrom_device_info *cdi)
2665 {
2666 }
2667
2668
2669
2670 /****************************************************************************
2671  * Device initialization.
2672  */
2673 static struct cdrom_device_ops ide_cdrom_dops = {
2674         open:                   ide_cdrom_open_real,
2675         release:                ide_cdrom_release_real,
2676         drive_status:           ide_cdrom_drive_status,
2677         media_changed:          ide_cdrom_check_media_change_real,
2678         tray_move:              ide_cdrom_tray_move,
2679         lock_door:              ide_cdrom_lock_door,
2680         select_speed:           ide_cdrom_select_speed,
2681         get_last_session:       ide_cdrom_get_last_session,
2682         get_mcn:                ide_cdrom_get_mcn,
2683         reset:                  ide_cdrom_reset,
2684         audio_ioctl:            ide_cdrom_audio_ioctl,
2685         dev_ioctl:              ide_cdrom_dev_ioctl,
2686         capability:             CDC_CLOSE_TRAY | CDC_OPEN_TRAY | CDC_LOCK |
2687                                 CDC_SELECT_SPEED | CDC_SELECT_DISC |
2688                                 CDC_MULTI_SESSION | CDC_MCN |
2689                                 CDC_MEDIA_CHANGED | CDC_PLAY_AUDIO | CDC_RESET |
2690                                 CDC_IOCTLS | CDC_DRIVE_STATUS | CDC_CD_R |
2691                                 CDC_CD_RW | CDC_DVD | CDC_DVD_R| CDC_DVD_RAM |
2692                                 CDC_GENERIC_PACKET,
2693         generic_packet:         ide_cdrom_packet,
2694 };
2695
2696 static int ide_cdrom_register (ide_drive_t *drive, int nslots)
2697 {
2698         struct cdrom_info *info = drive->driver_data;
2699         struct cdrom_device_info *devinfo = &info->devinfo;
2700         int minor = (drive->select.b.unit) << PARTN_BITS;
2701
2702         devinfo->dev = MKDEV(HWIF(drive)->major, minor);
2703         devinfo->ops = &ide_cdrom_dops;
2704         devinfo->mask = 0;
2705         devinfo->speed = CDROM_STATE_FLAGS(drive)->current_speed;
2706         devinfo->capacity = nslots;
2707         devinfo->handle = (void *) drive;
2708         strcpy(devinfo->name, drive->name);
2709         
2710         /* set capability mask to match the probe. */
2711         if (!CDROM_CONFIG_FLAGS(drive)->cd_r)
2712                 devinfo->mask |= CDC_CD_R;
2713         if (!CDROM_CONFIG_FLAGS(drive)->cd_rw)
2714                 devinfo->mask |= CDC_CD_RW;
2715         if (!CDROM_CONFIG_FLAGS(drive)->dvd)
2716                 devinfo->mask |= CDC_DVD;
2717         if (!CDROM_CONFIG_FLAGS(drive)->dvd_r)
2718                 devinfo->mask |= CDC_DVD_R;
2719         if (!CDROM_CONFIG_FLAGS(drive)->dvd_ram)
2720                 devinfo->mask |= CDC_DVD_RAM;
2721         if (!CDROM_CONFIG_FLAGS(drive)->is_changer)
2722                 devinfo->mask |= CDC_SELECT_DISC;
2723         if (!CDROM_CONFIG_FLAGS(drive)->audio_play)
2724                 devinfo->mask |= CDC_PLAY_AUDIO;
2725         if (!CDROM_CONFIG_FLAGS(drive)->close_tray)
2726                 devinfo->mask |= CDC_CLOSE_TRAY;
2727
2728         devinfo->de = devfs_register(drive->de, "cd", DEVFS_FL_DEFAULT,
2729                                      HWIF(drive)->major, minor,
2730                                      S_IFBLK | S_IRUGO | S_IWUGO,
2731                                      ide_fops, NULL);
2732
2733         return register_cdrom(devinfo);
2734 }
2735
2736 static
2737 int ide_cdrom_get_capabilities(ide_drive_t *drive, struct atapi_capabilities_page *cap)
2738 {
2739         struct cdrom_info *info = drive->driver_data;
2740         struct cdrom_device_info *cdi = &info->devinfo;
2741         struct cdrom_generic_command cgc;
2742         int stat, attempts = 3, size = sizeof(*cap);
2743
2744         /*
2745          * ACER50 (and others?) require the full spec length mode sense
2746          * page capabilities size, but older drives break.
2747          */
2748         if (!(!strcmp(drive->id->model, "ATAPI CD ROM DRIVE 50X MAX") ||
2749             !strcmp(drive->id->model, "WPI CDS-32X")))
2750                 size -= sizeof(cap->pad);
2751
2752         /* we have to cheat a little here. the packet will eventually
2753          * be queued with ide_cdrom_packet(), which extracts the
2754          * drive from cdi->handle. Since this device hasn't been
2755          * registered with the Uniform layer yet, it can't do this.
2756          * Same goes for cdi->ops.
2757          */
2758         cdi->handle = (ide_drive_t *) drive;
2759         cdi->ops = &ide_cdrom_dops;
2760         init_cdrom_command(&cgc, cap, size, CGC_DATA_UNKNOWN);
2761         do { /* we seem to get stat=0x01,err=0x00 the first time (??) */
2762                 stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
2763                 if (!stat)
2764                         break;
2765         } while (--attempts);
2766         return stat;
2767 }
2768
2769 static
2770 int ide_cdrom_probe_capabilities (ide_drive_t *drive)
2771 {
2772         struct cdrom_info *info = drive->driver_data;
2773         struct cdrom_device_info *cdi = &info->devinfo;
2774         struct atapi_capabilities_page cap;
2775         int nslots = 1;
2776
2777         if (CDROM_CONFIG_FLAGS(drive)->nec260) {
2778                 CDROM_CONFIG_FLAGS(drive)->no_eject = 0;                       
2779                 CDROM_CONFIG_FLAGS(drive)->audio_play = 1;       
2780                 return nslots;
2781         }
2782
2783         if (ide_cdrom_get_capabilities(drive, &cap))
2784                 return 0;
2785
2786         if (cap.lock == 0)
2787                 CDROM_CONFIG_FLAGS(drive)->no_doorlock = 1;
2788         if (cap.eject)
2789                 CDROM_CONFIG_FLAGS(drive)->no_eject = 0;
2790         if (cap.cd_r_write)
2791                 CDROM_CONFIG_FLAGS(drive)->cd_r = 1;
2792         if (cap.cd_rw_write)
2793                 CDROM_CONFIG_FLAGS(drive)->cd_rw = 1;
2794         if (cap.test_write)
2795                 CDROM_CONFIG_FLAGS(drive)->test_write = 1;
2796         if (cap.dvd_ram_read || cap.dvd_r_read || cap.dvd_rom)
2797                 CDROM_CONFIG_FLAGS(drive)->dvd = 1;
2798         if (cap.dvd_ram_write)
2799                 CDROM_CONFIG_FLAGS(drive)->dvd_ram = 1;
2800         if (cap.dvd_r_write)
2801                 CDROM_CONFIG_FLAGS(drive)->dvd_r = 1;
2802         if (cap.audio_play)
2803                 CDROM_CONFIG_FLAGS(drive)->audio_play = 1;
2804         if (cap.mechtype == mechtype_caddy || cap.mechtype == mechtype_popup)
2805                 CDROM_CONFIG_FLAGS(drive)->close_tray = 0;
2806
2807         /* Some drives used by Apple don't advertise audio play
2808          * but they do support reading TOC & audio datas
2809          */
2810         if (strcmp(drive->id->model, "MATSHITADVD-ROM SR-8187") == 0 ||
2811             strcmp(drive->id->model, "MATSHITADVD-ROM SR-8186") == 0 ||
2812             strcmp(drive->id->model, "MATSHITADVD-ROM SR-8176") == 0 ||
2813             strcmp(drive->id->model, "MATSHITADVD-ROM SR-8174") == 0)
2814                 CDROM_CONFIG_FLAGS(drive)->audio_play = 1;
2815
2816 #if ! STANDARD_ATAPI
2817         if (cdi->sanyo_slot > 0) {
2818                 CDROM_CONFIG_FLAGS(drive)->is_changer = 1;
2819                 nslots = 3;
2820         }
2821
2822         else
2823 #endif /* not STANDARD_ATAPI */
2824         if (cap.mechtype == mechtype_individual_changer ||
2825             cap.mechtype == mechtype_cartridge_changer) {
2826                 if ((nslots = cdrom_number_of_slots(cdi)) > 1) {
2827                         CDROM_CONFIG_FLAGS(drive)->is_changer = 1;
2828                         CDROM_CONFIG_FLAGS(drive)->supp_disc_present = 1;
2829                 }
2830         }
2831
2832         /* The ACER/AOpen 24X cdrom has the speed fields byte-swapped */
2833         if (!drive->id->model[0] &&
2834             !strncmp(drive->id->fw_rev, "241N", 4)) {
2835                 CDROM_STATE_FLAGS(drive)->current_speed  = 
2836                         (((unsigned int)cap.curspeed) + (176/2)) / 176;
2837                 CDROM_CONFIG_FLAGS(drive)->max_speed = 
2838                         (((unsigned int)cap.maxspeed) + (176/2)) / 176;
2839         } else {
2840                 CDROM_STATE_FLAGS(drive)->current_speed  = 
2841                         (ntohs(cap.curspeed) + (176/2)) / 176;
2842                 CDROM_CONFIG_FLAGS(drive)->max_speed = 
2843                         (ntohs(cap.maxspeed) + (176/2)) / 176;
2844         }
2845
2846         /* don't print speed if the drive reported 0.
2847          */
2848         printk(KERN_INFO "%s: ATAPI", drive->name);
2849         if (CDROM_CONFIG_FLAGS(drive)->max_speed)
2850                 printk(" %dX", CDROM_CONFIG_FLAGS(drive)->max_speed);
2851         printk(" %s", CDROM_CONFIG_FLAGS(drive)->dvd ? "DVD-ROM" : "CD-ROM");
2852
2853         if (CDROM_CONFIG_FLAGS(drive)->dvd_r|CDROM_CONFIG_FLAGS(drive)->dvd_ram)
2854                 printk(" DVD%s%s", 
2855                 (CDROM_CONFIG_FLAGS(drive)->dvd_r)? "-R" : "", 
2856                 (CDROM_CONFIG_FLAGS(drive)->dvd_ram)? "-RAM" : "");
2857
2858         if (CDROM_CONFIG_FLAGS(drive)->cd_r|CDROM_CONFIG_FLAGS(drive)->cd_rw) 
2859                 printk(" CD%s%s", 
2860                 (CDROM_CONFIG_FLAGS(drive)->cd_r)? "-R" : "", 
2861                 (CDROM_CONFIG_FLAGS(drive)->cd_rw)? "/RW" : "");
2862
2863         if (CDROM_CONFIG_FLAGS(drive)->is_changer) 
2864                 printk(" changer w/%d slots", nslots);
2865         else    
2866                 printk(" drive");
2867
2868         printk(", %dkB Cache", be16_to_cpu(cap.buffer_size));
2869
2870 #ifdef CONFIG_BLK_DEV_IDEDMA
2871         if (drive->using_dma)
2872                 (void) HWIF(drive)->ide_dma_verbose(drive);
2873 #endif /* CONFIG_BLK_DEV_IDEDMA */
2874         printk("\n");
2875
2876         return nslots;
2877 }
2878
2879 static void ide_cdrom_add_settings(ide_drive_t *drive)
2880 {
2881         int major = HWIF(drive)->major;
2882         int minor = drive->select.b.unit << PARTN_BITS;
2883
2884         ide_add_setting(drive,  "breada_readahead",     SETTING_RW, BLKRAGET, BLKRASET, TYPE_INT, 0, 255, 1, 2, &read_ahead[major], NULL);
2885         ide_add_setting(drive,  "file_readahead",       SETTING_RW, BLKFRAGET, BLKFRASET, TYPE_INTA, 0, INT_MAX, 1, 1024, &max_readahead[major][minor], NULL);
2886         ide_add_setting(drive,  "max_kb_per_request",   SETTING_RW, BLKSECTGET, BLKSECTSET, TYPE_INTA, 1, 255, 1, 2, &max_sectors[major][minor], NULL);
2887         ide_add_setting(drive,  "dsc_overlap",          SETTING_RW, -1, -1, TYPE_BYTE, 0, 1, 1, 1, &drive->dsc_overlap, NULL);
2888 }
2889
2890 static
2891 int ide_cdrom_setup (ide_drive_t *drive)
2892 {
2893         struct cdrom_info *info = drive->driver_data;
2894         struct cdrom_device_info *cdi = &info->devinfo;
2895         int minor = drive->select.b.unit << PARTN_BITS;
2896         int nslots;
2897
2898         /*
2899          * default to read-only always and fix latter at the bottom
2900          */
2901         set_device_ro(MKDEV(HWIF(drive)->major, minor), 1);
2902         set_blocksize(MKDEV(HWIF(drive)->major, minor), CD_FRAMESIZE);
2903
2904         drive->special.all      = 0;
2905         drive->ready_stat       = 0;
2906
2907         CDROM_STATE_FLAGS(drive)->media_changed = 1;
2908         CDROM_STATE_FLAGS(drive)->toc_valid     = 0;
2909         CDROM_STATE_FLAGS(drive)->door_locked   = 0;
2910
2911 #if NO_DOOR_LOCKING
2912         CDROM_CONFIG_FLAGS(drive)->no_doorlock = 1;
2913 #else
2914         CDROM_CONFIG_FLAGS(drive)->no_doorlock = 0;
2915 #endif
2916
2917         CDROM_CONFIG_FLAGS(drive)->drq_interrupt =
2918                 ((drive->id->config & 0x0060) == 0x20);
2919
2920         CDROM_CONFIG_FLAGS(drive)->is_changer = 0;
2921         CDROM_CONFIG_FLAGS(drive)->cd_r = 0;
2922         CDROM_CONFIG_FLAGS(drive)->cd_rw = 0;
2923         CDROM_CONFIG_FLAGS(drive)->test_write = 0;
2924         CDROM_CONFIG_FLAGS(drive)->dvd = 0;
2925         CDROM_CONFIG_FLAGS(drive)->dvd_r = 0;
2926         CDROM_CONFIG_FLAGS(drive)->dvd_ram = 0;
2927         CDROM_CONFIG_FLAGS(drive)->no_eject = 1;
2928         CDROM_CONFIG_FLAGS(drive)->supp_disc_present = 0;
2929         CDROM_CONFIG_FLAGS(drive)->audio_play = 0;
2930         CDROM_CONFIG_FLAGS(drive)->close_tray = 1;
2931         
2932         /* limit transfer size per interrupt. */
2933         CDROM_CONFIG_FLAGS(drive)->limit_nframes = 0;
2934
2935         /* a testament to the nice quality of Samsung drives... */
2936         if (!strcmp(drive->id->model, "SAMSUNG CD-ROM SCR-2430"))
2937                 CDROM_CONFIG_FLAGS(drive)->limit_nframes = 1;
2938         else if (!strcmp(drive->id->model, "SAMSUNG CD-ROM SCR-2432"))
2939                 CDROM_CONFIG_FLAGS(drive)->limit_nframes = 1;
2940         /* the 3231 model does not support the SET_CD_SPEED command */
2941         else if (!strcmp(drive->id->model, "SAMSUNG CD-ROM SCR-3231"))
2942                 cdi->mask |= CDC_SELECT_SPEED;
2943
2944 #if ! STANDARD_ATAPI
2945         /* by default Sanyo 3 CD changer support is turned off and
2946            ATAPI Rev 2.2+ standard support for CD changers is used */
2947         cdi->sanyo_slot = 0;
2948
2949         CDROM_CONFIG_FLAGS(drive)->nec260 = 0;
2950         CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd = 0;
2951         CDROM_CONFIG_FLAGS(drive)->tocaddr_as_bcd = 0;
2952         CDROM_CONFIG_FLAGS(drive)->playmsf_as_bcd = 0;
2953         CDROM_CONFIG_FLAGS(drive)->subchan_as_bcd = 0;
2954
2955         if (strcmp (drive->id->model, "V003S0DS") == 0 &&
2956             drive->id->fw_rev[4] == '1' &&
2957             drive->id->fw_rev[6] <= '2') {
2958                 /* Vertos 300.
2959                    Some versions of this drive like to talk BCD. */
2960                 CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd = 1;
2961                 CDROM_CONFIG_FLAGS(drive)->tocaddr_as_bcd = 1;
2962                 CDROM_CONFIG_FLAGS(drive)->playmsf_as_bcd = 1;
2963                 CDROM_CONFIG_FLAGS(drive)->subchan_as_bcd = 1;
2964         }
2965         else if (strcmp (drive->id->model, "V006E0DS") == 0 &&
2966             drive->id->fw_rev[4] == '1' &&
2967             drive->id->fw_rev[6] <= '2') {
2968                 /* Vertos 600 ESD. */
2969                 CDROM_CONFIG_FLAGS(drive)->toctracks_as_bcd = 1;
2970         }
2971
2972         else if (strcmp(drive->id->model,
2973                          "NEC CD-ROM DRIVE:260") == 0 &&
2974                  strncmp(drive->id->fw_rev, "1.01", 4) == 0) { /* FIXME */
2975                 /* Old NEC260 (not R).
2976                    This drive was released before the 1.2 version
2977                    of the spec. */
2978                 CDROM_CONFIG_FLAGS(drive)->tocaddr_as_bcd = 1;
2979                 CDROM_CONFIG_FLAGS(drive)->playmsf_as_bcd = 1;
2980                 CDROM_CONFIG_FLAGS(drive)->subchan_as_bcd = 1;
2981                 CDROM_CONFIG_FLAGS(drive)->nec260         = 1;
2982         }
2983         else if (strcmp(drive->id->model, "WEARNES CDD-120") == 0 &&
2984                  strncmp(drive->id->fw_rev, "A1.1", 4) == 0) { /* FIXME */
2985                 /* Wearnes */
2986                 CDROM_CONFIG_FLAGS(drive)->playmsf_as_bcd = 1;
2987                 CDROM_CONFIG_FLAGS(drive)->subchan_as_bcd = 1;
2988         }
2989         /* Sanyo 3 CD changer uses a non-standard command
2990            for CD changing */
2991         else if ((strcmp(drive->id->model, "CD-ROM CDR-C3 G") == 0) ||
2992                 (strcmp(drive->id->model, "CD-ROM CDR-C3G") == 0) ||
2993                 (strcmp(drive->id->model, "CD-ROM CDR_C36") == 0)) {
2994                         /* uses CD in slot 0 when value is set to 3 */
2995                         cdi->sanyo_slot = 3;
2996         }
2997 #endif /* not STANDARD_ATAPI */
2998
2999         info->toc               = NULL;
3000         info->buffer            = NULL;
3001         info->sector_buffered   = 0;
3002         info->nsectors_buffered = 0;
3003         info->changer_info      = NULL;
3004         info->last_block        = 0;
3005         info->start_seek        = 0;
3006
3007         nslots = ide_cdrom_probe_capabilities (drive);
3008
3009         if (CDROM_CONFIG_FLAGS(drive)->dvd_ram)
3010                 set_device_ro(MKDEV(HWIF(drive)->major, minor), 0);
3011
3012 #if 0
3013         drive->dsc_overlap = (HWIF(drive)->no_dsc) ? 0 : 1;
3014         if (HWIF(drive)->no_dsc) {
3015                 printk(KERN_INFO "ide-cd: %s: disabling DSC overlap\n",
3016                         drive->name);
3017                 drive->dsc_overlap = 0;
3018         }
3019 #endif
3020
3021         if (ide_cdrom_register(drive, nslots)) {
3022                 printk ("%s: ide_cdrom_setup failed to register device with the cdrom driver.\n", drive->name);
3023                 info->devinfo.handle = NULL;
3024                 return 1;
3025         }
3026         ide_cdrom_add_settings(drive);
3027         return 0;
3028 }
3029
3030 /* Forwarding functions to generic routines. */
3031 static
3032 int ide_cdrom_ioctl (ide_drive_t *drive,
3033                      struct inode *inode, struct file *file,
3034                      unsigned int cmd, unsigned long arg)
3035 {
3036         return cdrom_ioctl(inode, file, cmd, arg);
3037 }
3038
3039 static
3040 int ide_cdrom_open (struct inode *ip, struct file *fp, ide_drive_t *drive)
3041 {
3042         struct cdrom_info *info = drive->driver_data;
3043         int rc = -ENOMEM;
3044
3045         MOD_INC_USE_COUNT;
3046         if (info->buffer == NULL)
3047                 info->buffer = (char *) kmalloc(SECTOR_BUFFER_SIZE, GFP_KERNEL);
3048         if ((info->buffer == NULL) || (rc = cdrom_open(ip, fp))) {
3049                 drive->usage--;
3050                 MOD_DEC_USE_COUNT;
3051         }
3052         return rc;
3053 }
3054
3055 static
3056 void ide_cdrom_release (struct inode *inode, struct file *file,
3057                         ide_drive_t *drive)
3058 {
3059         cdrom_release (inode, file);
3060         MOD_DEC_USE_COUNT;
3061 }
3062
3063 static
3064 int ide_cdrom_check_media_change (ide_drive_t *drive)
3065 {
3066         return cdrom_media_changed(MKDEV (HWIF(drive)->major,
3067                         (drive->select.b.unit) << PARTN_BITS));
3068 }
3069
3070 static
3071 void ide_cdrom_revalidate (ide_drive_t *drive)
3072 {
3073         struct cdrom_info *info = drive->driver_data;
3074         struct atapi_toc *toc;
3075         int minor = drive->select.b.unit << PARTN_BITS;
3076         struct request_sense sense;
3077
3078         cdrom_read_toc(drive, &sense);
3079
3080         if (!CDROM_STATE_FLAGS(drive)->toc_valid)
3081                 return;
3082
3083         toc = info->toc;
3084
3085         /* for general /dev/cdrom like mounting, one big disc */
3086         drive->part[0].nr_sects = toc->capacity * SECTORS_PER_FRAME;
3087         HWIF(drive)->gd->sizes[minor] = toc->capacity * BLOCKS_PER_FRAME;
3088
3089         /*
3090          * reset block size, ide_revalidate_disk incorrectly sets it to
3091          * 1024 even for CDROM's
3092          */
3093         blk_size[HWIF(drive)->major] = HWIF(drive)->gd->sizes;
3094         set_blocksize(MKDEV(HWIF(drive)->major, minor), CD_FRAMESIZE);
3095 }
3096
3097 static
3098 unsigned long ide_cdrom_capacity (ide_drive_t *drive)
3099 {
3100         unsigned long capacity;
3101
3102         if (cdrom_read_capacity(drive, &capacity, NULL))
3103                 return 0;
3104
3105         return capacity * SECTORS_PER_FRAME;
3106 }
3107
3108 static
3109 int ide_cdrom_cleanup(ide_drive_t *drive)
3110 {
3111         struct cdrom_info *info = drive->driver_data;
3112         struct cdrom_device_info *devinfo = &info->devinfo;
3113
3114         if (ide_unregister_subdriver(drive)) {
3115                 printk("%s: %s: failed to ide_unregister_subdriver\n",
3116                         __FUNCTION__, drive->name);
3117                 return 1;
3118         }
3119         if (info->buffer != NULL)
3120                 kfree(info->buffer);
3121         if (info->toc != NULL)
3122                 kfree(info->toc);
3123         if (info->changer_info != NULL)
3124                 kfree(info->changer_info);
3125         if (devinfo->handle == drive && unregister_cdrom(devinfo))
3126                 printk("%s: ide_cdrom_cleanup failed to unregister device from the cdrom driver.\n", drive->name);
3127         kfree(info);
3128         drive->driver_data = NULL;
3129         return 0;
3130 }
3131
3132 int ide_cdrom_init(void);
3133 int ide_cdrom_attach (ide_drive_t *drive);
3134
3135 static ide_driver_t ide_cdrom_driver = {
3136         name:                   "ide-cdrom",
3137         version:                IDECD_VERSION,
3138         media:                  ide_cdrom,
3139         busy:                   0,
3140         supports_dma:           1,
3141         supports_dsc_overlap:   1,
3142         cleanup:                ide_cdrom_cleanup,
3143         standby:                NULL,
3144         suspend:                NULL,
3145         resume:                 NULL,
3146         flushcache:             NULL,
3147         do_request:             ide_do_rw_cdrom,
3148         end_request:            ide_cdrom_end_request,
3149         sense:                  ide_cdrom_dump_status,
3150         error:                  ide_cdrom_error,
3151         abort:                  ide_cdrom_abort,
3152         ioctl:                  ide_cdrom_ioctl,
3153         open:                   ide_cdrom_open,
3154         release:                ide_cdrom_release,
3155         media_change:           ide_cdrom_check_media_change,
3156         revalidate:             ide_cdrom_revalidate,
3157         pre_reset:              NULL,
3158         capacity:               ide_cdrom_capacity,
3159         special:                NULL,
3160         proc:                   NULL,
3161         init:                   ide_cdrom_init,
3162         attach:                 ide_cdrom_attach,
3163         ata_prebuilder:         NULL,
3164         atapi_prebuilder:       NULL,
3165 };
3166
3167 static ide_module_t ide_cdrom_module = {
3168         IDE_DRIVER_MODULE,
3169         ide_cdrom_init,
3170         &ide_cdrom_driver,
3171         NULL
3172 };
3173
3174 /* options */
3175 char *ignore = NULL;
3176
3177 MODULE_PARM(ignore, "s");
3178 MODULE_DESCRIPTION("ATAPI CD-ROM Driver");
3179
3180 int ide_cdrom_attach (ide_drive_t *drive)
3181 {
3182         struct cdrom_info *info;
3183         int failed = 0;
3184
3185         if (drive->scsi) {
3186                 printk("ide-cd: passing drive %s to ide-scsi emulation.\n",
3187                         drive->name);
3188                 return 1;
3189         }
3190
3191         MOD_INC_USE_COUNT;
3192         info = (struct cdrom_info *) kmalloc (sizeof (struct cdrom_info), GFP_KERNEL);
3193         if (info == NULL) {
3194                 printk("%s: Can't allocate a cdrom structure\n", drive->name);
3195                 MOD_DEC_USE_COUNT;
3196                 return 1;
3197         }
3198         if (ide_register_subdriver(drive,
3199                         &ide_cdrom_driver, IDE_SUBDRIVER_VERSION)) {
3200                 printk(KERN_ERR "ide-cd: %s: Failed to register the driver "
3201                         "with ide.c\n", drive->name);
3202                 kfree(info);
3203                 MOD_DEC_USE_COUNT;
3204                 return 1;
3205         }
3206         memset(info, 0, sizeof(struct cdrom_info));
3207         drive->driver_data = info;
3208         DRIVER(drive)->busy++;
3209         if (ide_cdrom_setup(drive)) {
3210                 DRIVER(drive)->busy--;
3211                 if (ide_cdrom_cleanup(drive))
3212                         printk("%s: ide_cdrom_cleanup failed in "
3213                                 "ide_cdrom_init\n", drive->name);
3214                 MOD_DEC_USE_COUNT;
3215                 return 1;
3216         }
3217         DRIVER(drive)->busy--;
3218         failed--;
3219
3220         MOD_DEC_USE_COUNT;
3221         return 0;
3222 }
3223
3224 static void __exit ide_cdrom_exit(void)
3225 {
3226         ide_drive_t *drive;
3227         int failed = 0;
3228
3229         while ((drive = ide_scan_devices(ide_cdrom, ide_cdrom_driver.name,
3230                         &ide_cdrom_driver, failed)) != NULL)
3231                 if (ide_cdrom_cleanup(drive)) {
3232                         printk("%s: cleanup_module() called while still "
3233                                 "busy\n", drive->name);
3234                         failed++;
3235                 }
3236         ide_unregister_module(&ide_cdrom_module);
3237 }
3238
3239 int ide_cdrom_init(void)
3240 {
3241 #ifdef CLASSIC_BUILTINS_METHOD
3242         ide_drive_t *drive;
3243         struct cdrom_info *info;
3244         int failed = 0;
3245 #endif /* CLASSIC_BUILTINS_METHOD */
3246         MOD_INC_USE_COUNT;
3247 #ifdef CLASSIC_BUILTINS_METHOD
3248         while ((drive = ide_scan_devices(ide_cdrom,
3249                         ide_cdrom_driver.name, NULL, failed++)) != NULL) {
3250                 /* skip drives that we were told to ignore */
3251                 if (ignore != NULL) {
3252                         if (strstr(ignore, drive->name)) {
3253                                 printk("ide-cd: ignoring drive %s\n",
3254                                         drive->name);
3255                                 continue;
3256                         }
3257                 }
3258                 if (drive->scsi) {
3259                         printk("ide-cd: passing drive %s to ide-scsi "
3260                                 "emulation.\n", drive->name);
3261                         continue;
3262                 }
3263                 info = (struct cdrom_info *) kmalloc (sizeof (struct cdrom_info), GFP_KERNEL);
3264                 if (info == NULL) {
3265                         printk ("%s: Can't allocate a cdrom structure\n",
3266                                 drive->name);
3267                         continue;
3268                 }
3269                 if (ide_register_subdriver(drive, 
3270                                 &ide_cdrom_driver, IDE_SUBDRIVER_VERSION)) {
3271                         printk("ide-cd: %s: Failed to register the driver with "
3272                                 "ide.c\n", drive->name);
3273                         kfree(info);
3274                         continue;
3275                 }
3276                 memset (info, 0, sizeof (struct cdrom_info));
3277                 drive->driver_data = info;
3278                 DRIVER(drive)->busy++;
3279                 if (ide_cdrom_setup (drive)) {
3280                         DRIVER(drive)->busy--;
3281                         if (ide_cdrom_cleanup (drive))
3282                                 printk ("%s: ide_cdrom_cleanup failed in "
3283                                         "ide_cdrom_init\n", drive->name);
3284                         continue;
3285                 }
3286                 DRIVER(drive)->busy--;
3287                 failed--;
3288         }
3289 #endif /* CLASSIC_BUILTINS_METHOD */
3290         ide_register_module(&ide_cdrom_module);
3291         MOD_DEC_USE_COUNT;
3292         return 0;
3293 }
3294
3295 module_init(ide_cdrom_init);
3296 module_exit(ide_cdrom_exit);
3297 MODULE_LICENSE("GPL");